diff --git a/AGENTS.md b/AGENTS.md index 713777b7..afc633c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,7 @@ - SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane - StopFailure `rate_limit` → `rate_limited`; `peppa session resume ` → `claude --resume` - агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP) +- **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate) diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 1049f281..66b07186 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -10,8 +10,9 @@ import { projectForUser, resolveTask, revokeApp, + setClaudeToken, } from "@peppa/core"; -import { acceptTask, answerAndDeliver, moveTask, provisionProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; +import { acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, moveTask, provisionProject, startClaudeSetup, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { requireUser } from "@/lib/auth"; @@ -145,3 +146,32 @@ export async function revokeConnectedApp(f: FormData) { await revokeApp(db, user.id, str(f, "clientId")); }); } + +export async function connectClaude(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await startClaudeSetup(db, user.id); + }); +} + +export async function submitClaudeCode(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await finishClaudeSetup(db, user.id, str(f, "code")); + return "/settings?claude=connected"; + }); +} + +export async function cancelClaude(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await cancelClaudeSetup(db, user.id); + }); +} + +export async function disconnectClaude(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await setClaudeToken(db, user.id, null); + }); +} diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index c42c8a8e..19f75a2e 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -2,17 +2,67 @@ import { connectedApps } from "@peppa/core"; import { ago, Flash } from "@/components/ui"; import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { revokeConnectedApp } from "../actions"; +import { pendingClaudeSetup } from "@peppa/runner"; +import { cancelClaude, connectClaude, disconnectClaude, revokeConnectedApp, submitClaudeCode } from "../actions"; -export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string }> }) { +export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) { const user = await requireUser(); - const { error } = await searchParams; + const { error, claude } = await searchParams; + const setup = await pendingClaudeSetup(db, user.id); const apps = await connectedApps(db, user.id); const origin = await publicOrigin(); return (

Настройки

+

Claude

+ {claude === "connected" &&

Claude подключён ✅

} + {setup ? ( +
+

+ 1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка): +

+ Войти в Claude ↗ +

2. Claude покажет код — вставьте его сюда:

+
+ + + +
+
+ + +
+
+ ) : user.claudeTokenEnc ? ( +
+
+ Claude подключён +
+ с {user.claudeTokenSetAt?.toLocaleDateString("ru-RU")} · сессии ваших проектов работают на вашей подписке +
+
+
+ + +
+
+ + +
+
+ ) : ( +
+

+ Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой + токен через claude setup-token, вход делаете вы сами по ссылке. +

+
+ + +
+
+ )}

MCP для ChatGPT и других клиентов

Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index e7a018ae..b748e021 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -156,3 +156,5 @@ details.add { margin: 4px 0; } .consent h1 { justify-content: flex-start; } .scopes { margin: 0; padding-left: 20px; } .mcp-url { display: block; padding: 10px 12px; background: var(--code-bg); border-radius: 8px; overflow-x: auto; } + +.ok { background: color-mix(in srgb, var(--ok) 12%, var(--surface)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; } diff --git a/openspec/changes/archive/2026-11-12-pep-13-connect-claude/.openspec.yaml b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-12-pep-13-connect-claude/proposal.md b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/proposal.md new file mode 100644 index 00000000..52707cde --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/proposal.md @@ -0,0 +1,37 @@ +# Proposal: PEP-13 — подключить Claude из веба + +Задача Пеппы: **PEP-13** · Цель #3 «Надёжность фабрики на живых агентах». + +## Why + +Сессии агентов падают с `authentication_failed`: вход Claude CLI на Mac истёк, а PM +работает удалённо и не может выполнить `claude login` на машине. + +## What Changes + +- «Настройки → Claude»: кнопка «Подключить». Пеппа запускает на Mac `claude setup-token`, + показывает ссылку входа; пользователь открывает её на своём устройстве, вставляет код в + форму Пеппы; полученный годовой токен хранится зашифрованным у пользователя. +- Сессии Claude по проектам владельца запускаются с его токеном + (`CLAUDE_CODE_OAUTH_TOKEN`); без токена — как сейчас (вход машины). +- Статус подключения, дата, «Отключить». Токен нигде не показывается. + +Вне scope: Codex (позже тем же способом), токены участников при шеринге (PEP-12). + +## Capabilities + +### New Capabilities +- `agent-credentials`: подключение аккаунта агента (Claude) пользователем из веба и использование его в сессиях. + +### Modified Capabilities + +## Impact + +`packages/db` (`users.claude_token_enc`, `claude_token_set_at`), `packages/runner` +(процесс setup-token в tmux, env сессий), `apps/web` (Настройки), `packages/testkit` +(mock-claude `setup-token`). + +## Решение по секретам + +Хранение — как у токенов Gitea (AES-256-GCM от `PEPPA_SECRET`); код вводит сам +пользователь, агент Пеппы его не видит. Согласовано с PM в чате. diff --git a/openspec/changes/archive/2026-11-12-pep-13-connect-claude/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/specs/agent-credentials/spec.md new file mode 100644 index 00000000..1261aaf3 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/specs/agent-credentials/spec.md @@ -0,0 +1,35 @@ +# Spec Delta: agent-credentials + +## Purpose + +Позволяет пользователю, работающему удалённо, подключить свой аккаунт Claude к Пеппе из веба, чтобы сессии его проектов работали на его подписке. + +## ADDED Requirements + +### Requirement: Подключение Claude из веба +Пользователь SHALL мочь подключить Claude, не имея доступа к машине Пеппы: Пеппа +показывает ссылку входа Claude, пользователь вводит полученный код в веб-форму, Пеппа +сохраняет долгоживущий токен. + +#### Scenario: Успешное подключение +- **WHEN** пользователь нажимает «Подключить Claude», открывает показанную ссылку, получает код и вставляет его в форму +- **THEN** в настройках отображается «Claude подключён» с датой, токен не показывается + +#### Scenario: Неверный или просроченный код +- **WHEN** введённый код не принят Claude +- **THEN** пользователь видит ошибку и может начать заново; старый токен (если был) не меняется + +### Requirement: Хранение и отключение +Токен SHALL храниться только в зашифрованном виде и удаляться по «Отключить». + +#### Scenario: Отключение +- **WHEN** пользователь нажимает «Отключить» +- **THEN** токен удалён, новые сессии его проектов запускаются без него + +### Requirement: Токен в сессиях +Сессии Claude по проектам владельца с подключённым Claude SHALL запускаться с его +токеном; проекты без владельца или владельцы без токена используют вход машины. + +#### Scenario: Запуск сессии +- **WHEN** запускается сессия Claude по задаче проекта, владелец которого подключил Claude +- **THEN** процесс агента получает токен владельца diff --git a/openspec/changes/archive/2026-11-12-pep-13-connect-claude/tasks.md b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/tasks.md new file mode 100644 index 00000000..122a757f --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/tasks.md @@ -0,0 +1,16 @@ +# Tasks: PEP-13 + +## 1. Токен + +- [x] 1.1 Миграция `users.claude_token_enc`, `claude_token_set_at`; core: set/clear/get (шифрование) +- [x] 1.2 runner: процесс `claude setup-token` в tmux (`peppa-auth-u`): старт → ссылка; ввод кода → токен или ошибка; таймаут и уборка +- [x] 1.3 runner: сессии Claude получают `CLAUDE_CODE_OAUTH_TOKEN` владельца проекта + +## 2. Веб + +- [x] 2.1 Настройки → Claude: статус, «Подключить» (ссылка + поле кода), «Отключить» + +## 3. Проверка + +- [x] 3.1 mock-claude `setup-token`; тесты: подключение, неверный код, токен в env сессии, отключение; весь набор зелёный +- [x] 3.2 Выкатка; на проде «Подключить» показывает настоящую ссылку claude.com; `openspec validate` diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md new file mode 100644 index 00000000..29441d1a --- /dev/null +++ b/openspec/specs/agent-credentials/spec.md @@ -0,0 +1,34 @@ +# agent-credentials Specification + +## Purpose +Позволяет пользователю, работающему удалённо, подключить свой аккаунт Claude к Пеппе из веба, чтобы сессии его проектов работали на его подписке. + +## Requirements + +### Requirement: Подключение Claude из веба +Пользователь SHALL мочь подключить Claude, не имея доступа к машине Пеппы: Пеппа +показывает ссылку входа Claude, пользователь вводит полученный код в веб-форму, Пеппа +сохраняет долгоживущий токен. + +#### Scenario: Успешное подключение +- **WHEN** пользователь нажимает «Подключить Claude», открывает показанную ссылку, получает код и вставляет его в форму +- **THEN** в настройках отображается «Claude подключён» с датой, токен не показывается + +#### Scenario: Неверный или просроченный код +- **WHEN** введённый код не принят Claude +- **THEN** пользователь видит ошибку и может начать заново; старый токен (если был) не меняется + +### Requirement: Хранение и отключение +Токен SHALL храниться только в зашифрованном виде и удаляться по «Отключить». + +#### Scenario: Отключение +- **WHEN** пользователь нажимает «Отключить» +- **THEN** токен удалён, новые сессии его проектов запускаются без него + +### Requirement: Токен в сессиях +Сессии Claude по проектам владельца с подключённым Claude SHALL запускаться с его +токеном; проекты без владельца или владельцы без токена используют вход машины. + +#### Scenario: Запуск сессии +- **WHEN** запускается сессия Claude по задаче проекта, владелец которого подключил Claude +- **THEN** процесс агента получает токен владельца diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts index c5c58db2..2c46d808 100644 --- a/packages/core/src/users.ts +++ b/packages/core/src/users.ts @@ -107,3 +107,17 @@ export async function consumeLoginLink(db: Db, code: string): Promise { + await db + .update(users) + .set({ claudeTokenEnc: token ? encrypt(token) : null, claudeTokenSetAt: token ? new Date() : null }) + .where(eq(users.id, userId)); +} + +/** The decrypted Claude token of a project's owner, if they connected Claude. */ +export async function claudeTokenForProject(db: Db, project: Pick): Promise { + if (!project.ownerId) return null; + const u = await getUser(db, project.ownerId); + return u?.claudeTokenEnc ? decrypt(u.claudeTokenEnc) : null; +} diff --git a/packages/db/migrations/0007_empty_crystal.sql b/packages/db/migrations/0007_empty_crystal.sql new file mode 100644 index 00000000..ebad339b --- /dev/null +++ b/packages/db/migrations/0007_empty_crystal.sql @@ -0,0 +1,2 @@ +ALTER TABLE "users" ADD COLUMN "claude_token_enc" text;--> statement-breakpoint +ALTER TABLE "users" ADD COLUMN "claude_token_set_at" timestamp with time zone; \ No newline at end of file diff --git a/packages/db/migrations/meta/0007_snapshot.json b/packages/db/migrations/meta/0007_snapshot.json new file mode 100644 index 00000000..3d6d1c5d --- /dev/null +++ b/packages/db/migrations/meta/0007_snapshot.json @@ -0,0 +1,1243 @@ +{ + "id": "d7d79655-c98d-4cc6-b49b-b8db3ce22738", + "prevId": "141bce5b-54a3-438f-b6c9-edf22525ab7b", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_codes": { + "name": "oauth_codes", + "schema": "", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_tokens": { + "name": "oauth_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "nullsNotDistinct": false, + "columns": [ + "gitea_id" + ] + }, + "users_login_unique": { + "name": "users_login_unique", + "nullsNotDistinct": false, + "columns": [ + "login" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 2126e00e..0aa98ed7 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -50,6 +50,13 @@ "when": 1794500991061, "tag": "0006_crazy_stellaris", "breakpoints": true + }, + { + "idx": 7, + "version": "7", + "when": 1794502693680, + "tag": "0007_empty_crystal", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index f9178bac..ec8be278 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -17,6 +17,10 @@ export const users = pgTable("users", { accessTokenEnc: text("access_token_enc"), refreshTokenEnc: text("refresh_token_enc"), tokenExpiresAt: timestamp("token_expires_at", { withTimezone: true }), + // Long-lived Claude Code token from `claude setup-token` (encrypted); used for the + // Claude sessions of this user's projects. + claudeTokenEnc: text("claude_token_enc"), + claudeTokenSetAt: timestamp("claude_token_set_at", { withTimezone: true }), createdAt: createdAt(), lastLoginAt: timestamp("last_login_at", { withTimezone: true }), }); diff --git a/packages/runner/src/claude-auth.ts b/packages/runner/src/claude-auth.ts new file mode 100644 index 00000000..8221df0e --- /dev/null +++ b/packages/runner/src/claude-auth.ts @@ -0,0 +1,90 @@ +// "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 секунд. Начните заново."); +} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 6a842df0..3cc94a96 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -6,3 +6,4 @@ export * from "./run-settings.ts"; export * from "./providers.ts"; export * from "./provision.ts"; export * from "./flow.ts"; +export * from "./claude-auth.ts"; diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 3dc8ca90..8fa5bdcd 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -2,6 +2,7 @@ import { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { answerQuestion, + claudeTokenForProject, createSession, expireSessionQuestions, getSession, @@ -81,6 +82,8 @@ async function launch( ): Promise { const generation = s.generation + 1; const rules = await loadSharedRules(); + const [owner] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, s.projectId)); + const claudeToken = s.provider === "claude" && owner ? await claudeTokenForProject(db, owner) : null; const argv = buildCommand(s.provider, { sessionId: s.id, generation, @@ -109,6 +112,8 @@ async function launch( // Hooks and the MCP server must talk to the same DB / state dir as the runner. DATABASE_URL: loadEnv().DATABASE_URL, ...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}), + // The project owner's own Claude subscription, if they connected it (PEP-13). + ...(claudeToken ? { CLAUDE_CODE_OAUTH_TOKEN: claudeToken } : {}), ...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}), }, }); diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index 28ed1ef9..fedf053f 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -16,6 +16,7 @@ export interface NewTmuxSession { cwd: string; command: string; env: Record; + width?: number; } export async function newSession(s: NewTmuxSession): Promise { @@ -23,7 +24,7 @@ export async function newSession(s: NewTmuxSession): Promise { // Keep the server up when its last session ends: otherwise a session created while the // previous last one is being killed can land on a server that is shutting down. await tmux("start-server", ";", "set-option", "-s", "exit-empty", "off"); - await tmux("new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", "220", "-y", "50", ...envArgs, s.command); + await tmux("new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command); // Keep the pane after claude exits so the watchdog can read the exit status. await tmux("set-option", "-t", s.name, "remain-on-exit", "on"); await tmux("set-option", "-t", s.name, "history-limit", "20000"); diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts index fe09ba85..7e8d8274 100644 --- a/packages/testkit/src/mock-agent.ts +++ b/packages/testkit/src/mock-agent.ts @@ -329,7 +329,14 @@ async function main() { const scenario: Scenario = existsSync(SCENARIO) ? JSON.parse(readFileSync(SCENARIO, "utf8")) : { turns: [] }; const turns = (args.resume && scenario.resumeTurns) || scenario.turns; const rules = args.rulesFile ? readFileSync(args.rulesFile, "utf8") : (args.developerInstructions ?? ""); - log("start", { argv, resume: args.resume ?? null, conversationId, rulesChars: rules.length, rulesHead: rules.split("\n")[0] }); + log("start", { + argv, + resume: args.resume ?? null, + conversationId, + rulesChars: rules.length, + rulesHead: rules.split("\n")[0], + oauthToken: process.env.CLAUDE_CODE_OAUTH_TOKEN ? `…${process.env.CLAUDE_CODE_OAUTH_TOKEN.slice(-4)}` : null, + }); if (process.stdin.isTTY) process.stdin.setRawMode(true); process.stdin.setEncoding("utf8"); @@ -349,7 +356,33 @@ async function main() { for (;;) await run(await nextPrompt()); } -main().catch((e) => { +/** + * `claude setup-token`: prints a sign-in URL, waits for the code. "mock-good-…" codes + * yield a token, anything else fails like an invalid code. + */ +async function setupToken() { + out(" This will guide you through long-lived (1-year) auth token setup for your Claude account.\n"); + out(" Browser didn't open? Use the url below to sign in (c to copy)\n\n"); + out(`https://claude.com/cai/oauth/authorize?code=true&client_id=mock-client&response_type=code&state=mock-${randomUUID()}\n\n`); + out(" Paste code here if prompted > "); + process.stdin.setEncoding("utf8"); + let buf = ""; + for await (const chunk of process.stdin) { + buf += String(chunk).replace(/\x1b\[20[01]~/g, ""); + if (/[\r\n]/.test(buf)) break; + } + const code = buf.trim(); + // Runs in the home dir: log next to Peppa's state, never into a stray ~/.peppa. + if (process.env.PEPPA_HOME) appendFileSync(join(process.env.PEPPA_HOME, "mock-setup-log.jsonl"), `${JSON.stringify({ ev: "setup_token", code, t: Date.now() })}\n`); + if (code.startsWith("mock-good-")) { + out(`\n\n ✓ Long-lived authentication token created successfully!\n\n Your OAuth token (valid for 1 year):\n\n sk-ant-oat01-mock${randomUUID().replace(/-/g, "")}\n\n Store this token securely.\n`); + process.exit(0); + } + out("\n\n OAuth error: Invalid code\n"); + process.exit(1); +} + +(argv[0] === "setup-token" ? setupToken() : main()).catch((e) => { log("fatal", { error: String(e?.stack ?? e) }); process.exit(1); }); diff --git a/packages/testkit/test/claude-auth.test.ts b/packages/testkit/test/claude-auth.test.ts new file mode 100644 index 00000000..83d47458 --- /dev/null +++ b/packages/testkit/test/claude-auth.test.ts @@ -0,0 +1,54 @@ +// PEP-13: connect Claude from the web (setup-token in tmux) and use the token in sessions. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown } from "./helpers.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; + +let user: Awaited>; +before(async () => { + user = await core.upsertUserFromGitea(db, { id: 31, login: "mock-claude-user" }, { access_token: "x" }); +}); +after(teardown); + +describe("connect Claude", () => { + test("wrong code → error, nothing stored; right code → encrypted token", async () => { + const s1 = await runner.startClaudeSetup(db, user.id); + assert.match(s1.url, /^https:\/\/claude\.com\/cai\/oauth\/authorize\?/); + assert.deepEqual((await runner.pendingClaudeSetup(db, user.id))?.url, s1.url); + await assert.rejects(runner.finishClaudeSetup(db, user.id, "mock-bad-code"), /не принял код/); + assert.equal((await core.getUser(db, user.id))?.claudeTokenEnc, null); + assert.equal(await runner.pendingClaudeSetup(db, user.id), null, "failed setup is cleaned up"); + await assert.rejects(runner.finishClaudeSetup(db, user.id, "mock-good-1"), /не начато/); + + await runner.startClaudeSetup(db, user.id); + await runner.finishClaudeSetup(db, user.id, "mock-good-1"); + const u = (await core.getUser(db, user.id))!; + assert.ok(u.claudeTokenEnc && !u.claudeTokenEnc.includes("sk-ant"), "stored encrypted"); + assert.match(core.decrypt(u.claudeTokenEnc), /^sk-ant-oat01-mock/); + assert.ok(u.claudeTokenSetAt); + assert.equal(await runner.pendingClaudeSetup(db, user.id), null); + }); + + test("sessions of the owner's projects get the token; other projects and disconnect don't", async () => { + const token = core.decrypt((await core.getUser(db, user.id))!.claudeTokenEnc!); + const mine = await project({ turns: [[{ say: "ok" }]] }); + await core.setProjectOwner(db, (await core.getProject(db, mine.key)).id, user.id); + const sid = await mine.start(); + const start = await mine.waitLog("started", (e) => e.ev === "start"); + assert.equal(start.oauthToken, `…${token.slice(-4)}`); + await runner.stopSession(db, sid); + + const other = await project({ turns: [[{ say: "ok" }]] }); + const sid2 = await other.start(); + assert.equal((await other.waitLog("started", (e) => e.ev === "start")).oauthToken, null); + await runner.stopSession(db, sid2); + + await core.setClaudeToken(db, user.id, null); + const again = await project({ turns: [[{ say: "ok" }]] }); + await core.setProjectOwner(db, (await core.getProject(db, again.key)).id, user.id); + const sid3 = await again.start(); + assert.equal((await again.waitLog("started", (e) => e.ev === "start")).oauthToken, null); + await runner.stopSession(db, sid3); + }); +});