PEP-1: web platform with Gitea login, projects, goals, tasks, sessions
- web: Gitea OAuth2 login, signed session cookie, everything behind login; inbox with answers, project board (goals → tasks), task page with OpenSpec artifacts, questions and session controls; new project form; auto-refresh, light/dark, mobile - users + projects.owner_id; tokens AES-256-GCM encrypted; owner-only access - provisionProject (runner): new or existing Gitea repo, peppa-bot collaborator, template + openspec init, push, rollback; used by web and peppa project create (replaces scripts/bootstrap-project.sh) - peppa web login-link, peppa project owner; Gitea OAuth app script - bins/template resolved via PEPPA_ROOT (works inside the Next build) - testkit: mock-gitea + 10 tests (42 e2e total, all green) - OpenSpec: pep-1-web-platform archived into specs web-auth, project-provisioning, web-workspace Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f53b3447cf
commit
2b0f2fd984
@ -4,7 +4,7 @@
|
|||||||
проекты ведутся по OpenSpec.
|
проекты ведутся по OpenSpec.
|
||||||
|
|
||||||
## Структура
|
## Структура
|
||||||
- `apps/web` — Next.js платформа (порт 3100): проекты, цели, задачи, сессии
|
- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; входящие, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web`
|
||||||
- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка только через `/start <код>` (`peppa telegram pair`), чужие чаты игнорируются. Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
|
- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка только через `/start <код>` (`peppa telegram pair`), чужие чаты игнорируются. Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
|
||||||
- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433)
|
- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433)
|
||||||
- `packages/shared` — env, ключи задач (`PEP-42`)
|
- `packages/shared` — env, ключи задач (`PEP-42`)
|
||||||
@ -21,7 +21,7 @@
|
|||||||
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
|
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
|
||||||
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
|
- `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 не трогаем
|
- 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, bootstrap-project.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate)
|
- `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate)
|
||||||
|
|
||||||
## Внешние зависимости — через моки
|
## Внешние зависимости — через моки
|
||||||
|
|
||||||
@ -39,6 +39,8 @@
|
|||||||
|
|
||||||
## Команды
|
## Команды
|
||||||
- `pnpm db:up` / `pnpm db:generate` / `pnpm db:migrate`
|
- `pnpm db:up` / `pnpm db:generate` / `pnpm db:migrate`
|
||||||
|
- `peppa project create <slug> <KEY> <name> [--existing]` — проект в Gitea (`provisionProject` в runner, тот же код, что у веба); `peppa project owner <KEY> <login>`
|
||||||
|
- `peppa web login-link <login>` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea
|
||||||
- `pnpm typecheck`
|
- `pnpm typecheck`
|
||||||
- `tsx packages/mcp/scripts/smoke.ts <project-dir> <task>` — смоук MCP-сервера
|
- `tsx packages/mcp/scripts/smoke.ts <project-dir> <task>` — смоук MCP-сервера
|
||||||
- `pnpm dev:web`
|
- `pnpm dev:web`
|
||||||
|
|||||||
@ -7,5 +7,5 @@ pnpm install
|
|||||||
cp .env.example .env # GITEA_TOKEN и т.д.
|
cp .env.example .env # GITEA_TOKEN и т.д.
|
||||||
pnpm db:up && pnpm db:migrate
|
pnpm db:up && pnpm db:migrate
|
||||||
scripts/push-template.sh # залить template/ в Gitea
|
scripts/push-template.sh # залить template/ в Gitea
|
||||||
scripts/bootstrap-project.sh demo DEMO "Demo project"
|
peppa project create demo DEMO "Demo project"
|
||||||
```
|
```
|
||||||
|
|||||||
124
apps/web/app/(app)/actions.ts
Normal file
124
apps/web/app/(app)/actions.ts
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createGoal,
|
||||||
|
createTask,
|
||||||
|
getQuestion,
|
||||||
|
getSession,
|
||||||
|
giteaForUser,
|
||||||
|
PeppaError,
|
||||||
|
projectForUser,
|
||||||
|
resolveTask,
|
||||||
|
} from "@peppa/core";
|
||||||
|
import { answerAndDeliver, provisionProject, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
|
||||||
|
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
|
||||||
|
const back = (f: FormData) => str(f, "back") || "/";
|
||||||
|
|
||||||
|
/** Runs an action; errors come back to the page as ?error=… (redirect must stay outside try). */
|
||||||
|
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
|
||||||
|
let target = back(f);
|
||||||
|
try {
|
||||||
|
target = (await fn()) || target;
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
|
||||||
|
const sep = target.includes("?") ? "&" : "?";
|
||||||
|
target = `${target.split("?")[0]}${sep}error=${encodeURIComponent(msg.slice(0, 300))}`;
|
||||||
|
}
|
||||||
|
revalidatePath("/", "layout");
|
||||||
|
redirect(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ownedSession(userId: number, sessionId: number) {
|
||||||
|
const s = await getSession(db, sessionId);
|
||||||
|
await projectForUser(db, userId, s.projectId);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function answerQuestion(f: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const q = await getQuestion(db, Number(str(f, "questionId")));
|
||||||
|
await projectForUser(db, user.id, q.projectId);
|
||||||
|
const answer = str(f, "choice") || str(f, "answer");
|
||||||
|
if (!answer) throw new PeppaError("Пустой ответ");
|
||||||
|
if (q.answeredAt) throw new PeppaError(`Уже отвечено${q.answeredVia === "system" ? "" : ` (${q.answeredVia})`}: ${q.answer}`);
|
||||||
|
await answerAndDeliver(db, q.id, answer, "web");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addGoal(f: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
|
if (!str(f, "title")) throw new PeppaError("Нужно название цели");
|
||||||
|
await createGoal(db, p.id, str(f, "title"), str(f, "description") || undefined);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addTask(f: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
|
if (!str(f, "title")) throw new PeppaError("Нужно название задачи");
|
||||||
|
const goalId = str(f, "goalId") ? Number(str(f, "goalId")) : undefined;
|
||||||
|
const ref = await createTask(db, { projectId: p.id, goalId, title: str(f, "title"), description: str(f, "description") || undefined });
|
||||||
|
return `/t/${ref.key}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function startTaskSession(f: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||||
|
await projectForUser(db, user.id, ref.project.id);
|
||||||
|
await startSession(db, ref.key, { provider: (str(f, "provider") || "claude") as Provider, prompt: str(f, "prompt") || undefined });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function stopTaskSession(f: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||||||
|
await stopSession(db, s.id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resumeTaskSession(f: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||||||
|
await resumeSession(db, s.id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function messageSession(f: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
|
||||||
|
if (!str(f, "text")) throw new PeppaError("Пустое сообщение");
|
||||||
|
await sendToSession(db, s.id, str(f, "text"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createProjectAction(f: FormData) {
|
||||||
|
const user = await requireUser();
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const owner = str(f, "owner") || user.login;
|
||||||
|
const p = await provisionProject(db, {
|
||||||
|
gitea: await giteaForUser(db, user),
|
||||||
|
owner,
|
||||||
|
ownerIsUser: owner === user.login,
|
||||||
|
slug: str(f, "slug").toLowerCase(),
|
||||||
|
key: str(f, "key"),
|
||||||
|
name: str(f, "name"),
|
||||||
|
existing: str(f, "mode") === "existing",
|
||||||
|
ownerId: user.id,
|
||||||
|
});
|
||||||
|
return `/p/${p.key}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
28
apps/web/app/(app)/layout.tsx
Normal file
28
apps/web/app/(app)/layout.tsx
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<header className="top">
|
||||||
|
<Link href="/" className="brand">🐷 Peppa</Link>
|
||||||
|
<nav>
|
||||||
|
<Link href="/">Входящие</Link>
|
||||||
|
<Link href="/projects/new">Новый проект</Link>
|
||||||
|
</nav>
|
||||||
|
<div className="me">
|
||||||
|
{user.avatarUrl && <img src={user.avatarUrl} alt="" width={24} height={24} />}
|
||||||
|
<span>{user.login}</span>
|
||||||
|
<form action="/logout" method="post">
|
||||||
|
<button className="link">Выйти</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main>{children}</main>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
79
apps/web/app/(app)/p/[key]/page.tsx
Normal file
79
apps/web/app/(app)/p/[key]/page.tsx
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||||
|
import { Badge, Flash, SessionCard } from "@/components/ui";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
|
||||||
|
import { addGoal, addTask } from "../../actions";
|
||||||
|
|
||||||
|
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
const { key } = await params;
|
||||||
|
const { error } = await searchParams;
|
||||||
|
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||||
|
if (!p) notFound();
|
||||||
|
const [{ goals, tasks }, sessions] = await Promise.all([board(p.id), projectSessions(p.id)]);
|
||||||
|
const back = `/p/${p.key}`;
|
||||||
|
const groups = [...goals.map((g) => ({ goal: g, tasks: tasks.filter((t) => t.goalId === g.id) })), { goal: null, tasks: tasks.filter((t) => !t.goalId) }];
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<AutoRefresh />
|
||||||
|
<Flash error={error} />
|
||||||
|
<h1>
|
||||||
|
<span className="mono">{p.key}</span> {p.name}
|
||||||
|
</h1>
|
||||||
|
<p className="muted">
|
||||||
|
<a href={`${loadEnv().GITEA_URL}/${p.giteaOwner}/${p.giteaRepo}`}>{p.giteaOwner}/{p.giteaRepo}</a> · <span className="mono">{p.workspacePath}</span>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{groups.map(({ goal, tasks: ts }) =>
|
||||||
|
goal || ts.length ? (
|
||||||
|
<section key={goal?.id ?? "none"} className="goal">
|
||||||
|
<h2>{goal ? `🎯 ${goal.title}` : "Без цели"}</h2>
|
||||||
|
{goal?.description && <p className="muted">{goal.description}</p>}
|
||||||
|
<ul className="tasks">
|
||||||
|
{ts.map((t) => (
|
||||||
|
<li key={t.id}>
|
||||||
|
<Link href={`/t/${p.key}-${t.number}`}>
|
||||||
|
<span className="mono">{p.key}-{t.number}</span> {t.title}
|
||||||
|
</Link>
|
||||||
|
<Badge status={t.status} />
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<details>
|
||||||
|
<summary>+ Задача{goal ? " в эту цель" : ""}</summary>
|
||||||
|
<form action={addTask} className="stack">
|
||||||
|
<input type="hidden" name="projectId" value={p.id} />
|
||||||
|
<input type="hidden" name="back" value={back} />
|
||||||
|
{goal && <input type="hidden" name="goalId" value={goal.id} />}
|
||||||
|
<input type="text" name="title" required placeholder="Что сделать" aria-label="Название задачи" />
|
||||||
|
<textarea name="description" rows={3} placeholder="Описание: контекст, критерии готовности" aria-label="Описание задачи" />
|
||||||
|
<button className="primary">Создать задачу</button>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
</section>
|
||||||
|
) : null,
|
||||||
|
)}
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<details>
|
||||||
|
<summary>+ Цель</summary>
|
||||||
|
<form action={addGoal} className="stack">
|
||||||
|
<input type="hidden" name="projectId" value={p.id} />
|
||||||
|
<input type="hidden" name="back" value={back} />
|
||||||
|
<input type="text" name="title" required placeholder="Верхнеуровневая цель" aria-label="Название цели" />
|
||||||
|
<textarea name="description" rows={3} placeholder="Зачем и какой результат" aria-label="Описание цели" />
|
||||||
|
<button className="primary">Создать цель</button>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Сессии</h2>
|
||||||
|
{sessions.length === 0 ? <p className="empty">Сессий ещё не было.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)}
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
46
apps/web/app/(app)/page.tsx
Normal file
46
apps/web/app/(app)/page.tsx
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { listUserProjects } from "@peppa/core";
|
||||||
|
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||||
|
import { Flash, QuestionCard, SessionCard } from "@/components/ui";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { activeSessions, inbox } from "@/lib/queries";
|
||||||
|
|
||||||
|
export default async function Inbox({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
const { error } = await searchParams;
|
||||||
|
const [items, sessions, projects] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id)]);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<AutoRefresh />
|
||||||
|
<Flash error={error} />
|
||||||
|
<section>
|
||||||
|
<h1>Входящие {items.length > 0 && <span className="count">{items.length}</span>}</h1>
|
||||||
|
{items.length === 0 ? <p className="empty">Агентам от тебя ничего не нужно.</p> : items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} back="/" />)}
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>Активные сессии</h2>
|
||||||
|
{sessions.length === 0 ? <p className="empty">Сейчас ничего не запущено.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back="/" />)}
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>Мои проекты</h2>
|
||||||
|
{projects.length === 0 ? (
|
||||||
|
<p className="empty">
|
||||||
|
Проектов пока нет. <Link href="/projects/new">Создать первый</Link>
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<ul className="projects">
|
||||||
|
{projects.map((p) => (
|
||||||
|
<li key={p.id}>
|
||||||
|
<Link href={`/p/${p.key}`}>
|
||||||
|
<span className="mono">{p.key}</span> {p.name}
|
||||||
|
</Link>
|
||||||
|
<span className="muted">{p.giteaOwner}/{p.giteaRepo}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
63
apps/web/app/(app)/projects/new/page.tsx
Normal file
63
apps/web/app/(app)/projects/new/page.tsx
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
import { giteaForUser, type GiteaOrg } from "@peppa/core";
|
||||||
|
import { Flash } from "@/components/ui";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { createProjectAction } from "../../actions";
|
||||||
|
|
||||||
|
export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
const { error } = await searchParams;
|
||||||
|
let orgs: GiteaOrg[] = [];
|
||||||
|
let giteaError: string | undefined;
|
||||||
|
try {
|
||||||
|
orgs = await (await giteaForUser(db, user)).orgsWithRepoCreate(user.login);
|
||||||
|
} catch (e) {
|
||||||
|
giteaError = (e as Error).message;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<section className="narrow">
|
||||||
|
<h1>Новый проект</h1>
|
||||||
|
<Flash error={error ?? giteaError} />
|
||||||
|
<form action={createProjectAction} className="stack">
|
||||||
|
<input type="hidden" name="back" value="/projects/new" />
|
||||||
|
<label>
|
||||||
|
Название
|
||||||
|
<input type="text" name="name" required placeholder="Платёжный сервис" />
|
||||||
|
</label>
|
||||||
|
<div className="row">
|
||||||
|
<label className="grow">
|
||||||
|
Репозиторий (slug)
|
||||||
|
<input type="text" name="slug" required pattern="[a-z0-9][a-z0-9-]*" placeholder="payments" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Ключ задач
|
||||||
|
<input type="text" name="key" required pattern="[A-Za-z][A-Za-z0-9]{1,9}" placeholder="PAY" className="short" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label>
|
||||||
|
Где в Gitea
|
||||||
|
<select name="owner" defaultValue={user.login}>
|
||||||
|
<option value={user.login}>{user.login} (личный)</option>
|
||||||
|
{orgs.map((o) => (
|
||||||
|
<option key={o.id} value={o.username}>{o.username}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<fieldset>
|
||||||
|
<legend>Репозиторий</legend>
|
||||||
|
<label className="inline">
|
||||||
|
<input type="radio" name="mode" value="new" defaultChecked /> Создать новый
|
||||||
|
</label>
|
||||||
|
<label className="inline">
|
||||||
|
<input type="radio" name="mode" value="existing" /> Подключить существующий (нужны права админа)
|
||||||
|
</label>
|
||||||
|
</fieldset>
|
||||||
|
<p className="muted">
|
||||||
|
Пеппа добавит <span className="mono">peppa-bot</span> соавтором, положит AGENTS.md, .mcp.json и .peppa/project.json из шаблона и запустит
|
||||||
|
openspec init. Занимает до ~15 секунд.
|
||||||
|
</p>
|
||||||
|
<button className="primary">Создать проект</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
84
apps/web/app/(app)/t/[key]/page.tsx
Normal file
84
apps/web/app/(app)/t/[key]/page.tsx
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||||
|
import { ago, Badge, Flash, QuestionCard, SessionCard } from "@/components/ui";
|
||||||
|
import { requireUser } from "@/lib/auth";
|
||||||
|
import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { goals } from "@peppa/db";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { startTaskSession } from "../../actions";
|
||||||
|
|
||||||
|
export default async function TaskPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
|
||||||
|
const user = await requireUser();
|
||||||
|
const { key } = await params;
|
||||||
|
const { error } = await searchParams;
|
||||||
|
const ref = await taskForUser(user.id, decodeURIComponent(key)).catch(() => null);
|
||||||
|
if (!ref) notFound();
|
||||||
|
const { task, project } = ref;
|
||||||
|
const [goal] = task.goalId ? await db.select().from(goals).where(eq(goals.id, task.goalId)) : [];
|
||||||
|
const { questions, sessions, events } = await taskActivity(task.id);
|
||||||
|
const artifacts = openspecArtifacts(project, task.openspecChange);
|
||||||
|
const back = `/t/${ref.key}`;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<AutoRefresh />
|
||||||
|
<Flash error={error} />
|
||||||
|
<p className="crumbs">
|
||||||
|
<Link href={`/p/${project.key}`}>{project.name}</Link>
|
||||||
|
{goal && <> · 🎯 {goal.title}</>}
|
||||||
|
</p>
|
||||||
|
<h1>
|
||||||
|
<span className="mono">{ref.key}</span> {task.title} <Badge status={task.status} />
|
||||||
|
</h1>
|
||||||
|
{task.prUrl && <p><a href={task.prUrl}>PR</a></p>}
|
||||||
|
<p className="desc">{task.description || <span className="muted">Без описания</span>}</p>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Сессии</h2>
|
||||||
|
<form action={startTaskSession} className="row wrap">
|
||||||
|
<input type="hidden" name="taskKey" value={ref.key} />
|
||||||
|
<input type="hidden" name="back" value={back} />
|
||||||
|
<select name="provider" defaultValue="claude" aria-label="Агент">
|
||||||
|
<option value="claude">Claude Code</option>
|
||||||
|
<option value="codex">Codex</option>
|
||||||
|
</select>
|
||||||
|
<input type="text" name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="grow" />
|
||||||
|
<button className="primary">Запустить агента</button>
|
||||||
|
</form>
|
||||||
|
{sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Вопросы</h2>
|
||||||
|
{questions.length === 0 ? <p className="empty">Вопросов не было.</p> : questions.map((q) => <QuestionCard key={q.id} q={q} back={back} />)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>OpenSpec {task.openspecChange && <span className="mono muted">{task.openspecChange}</span>}</h2>
|
||||||
|
{artifacts?.length ? (
|
||||||
|
artifacts.map((a) => (
|
||||||
|
<details key={a.name} open={a.name === "proposal.md"}>
|
||||||
|
<summary className="mono">{a.name}</summary>
|
||||||
|
<pre className="md">{a.text}</pre>
|
||||||
|
</details>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p className="empty">Change ещё не создан.</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>События</h2>
|
||||||
|
<ul className="events">
|
||||||
|
{events.map((e) => (
|
||||||
|
<li key={e.id}>
|
||||||
|
<span className="muted">{ago(e.createdAt)}</span> <span className="mono">{e.type}</span>{" "}
|
||||||
|
{e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
29
apps/web/app/auth/callback/route.ts
Normal file
29
apps/web/app/auth/callback/route.ts
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import { exchangeOAuthCode, GiteaClient, upsertUserFromGitea } from "@peppa/core";
|
||||||
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { publicOrigin, sessionCookie, STATE_COOKIE } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const env = loadEnv();
|
||||||
|
const origin = await publicOrigin();
|
||||||
|
const fail = (msg: string) => NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(msg)}`);
|
||||||
|
const code = req.nextUrl.searchParams.get("code");
|
||||||
|
const state = req.nextUrl.searchParams.get("state");
|
||||||
|
const expected = (await cookies()).get(STATE_COOKIE)?.value;
|
||||||
|
if (!code || !state || !expected || state !== expected) return fail("Вход не подтверждён (state не совпал) — попробуйте ещё раз");
|
||||||
|
if (!env.GITEA_OAUTH_CLIENT_ID || !env.GITEA_OAUTH_CLIENT_SECRET) return fail("OAuth не настроен");
|
||||||
|
try {
|
||||||
|
const tokens = await exchangeOAuthCode(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, env.GITEA_OAUTH_CLIENT_SECRET, code, `${origin}/auth/callback`);
|
||||||
|
const me = await new GiteaClient(env.GITEA_URL, tokens.access_token).me();
|
||||||
|
const user = await upsertUserFromGitea(db, me, tokens);
|
||||||
|
const res = NextResponse.redirect(`${origin}/`);
|
||||||
|
const c = sessionCookie(user.id);
|
||||||
|
res.cookies.set(c.name, c.value, c.options);
|
||||||
|
res.cookies.delete({ name: STATE_COOKIE, path: "/auth" });
|
||||||
|
return res;
|
||||||
|
} catch (e) {
|
||||||
|
return fail(`Не удалось войти: ${(e as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
15
apps/web/app/auth/link/route.ts
Normal file
15
apps/web/app/auth/link/route.ts
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import { consumeLoginLink } from "@peppa/core";
|
||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { publicOrigin, sessionCookie } from "@/lib/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
|
||||||
|
/** One-time admin login link from `peppa web login-link`. */
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const origin = await publicOrigin();
|
||||||
|
const uid = await consumeLoginLink(db, req.nextUrl.searchParams.get("code") ?? "");
|
||||||
|
if (!uid) return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent("Ссылка входа недействительна или уже использована")}`);
|
||||||
|
const res = NextResponse.redirect(`${origin}/`);
|
||||||
|
const c = sessionCookie(uid);
|
||||||
|
res.cookies.set(c.name, c.value, c.options);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
14
apps/web/app/auth/start/route.ts
Normal file
14
apps/web/app/auth/start/route.ts
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { randomBytes } from "node:crypto";
|
||||||
|
import { oauthAuthorizeUrl } from "@peppa/core";
|
||||||
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { publicOrigin, STATE_COOKIE } from "@/lib/auth";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const env = loadEnv();
|
||||||
|
if (!env.GITEA_OAUTH_CLIENT_ID) return new NextResponse("GITEA_OAUTH_CLIENT_ID is not configured", { status: 500 });
|
||||||
|
const state = randomBytes(18).toString("base64url");
|
||||||
|
const res = NextResponse.redirect(oauthAuthorizeUrl(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, `${await publicOrigin()}/auth/callback`, state));
|
||||||
|
res.cookies.set(STATE_COOKIE, state, { httpOnly: true, sameSite: "lax", path: "/auth", maxAge: 600, secure: env.PEPPA_WEB_URL.startsWith("https://") });
|
||||||
|
return res;
|
||||||
|
}
|
||||||
141
apps/web/app/globals.css
Normal file
141
apps/web/app/globals.css
Normal file
@ -0,0 +1,141 @@
|
|||||||
|
:root {
|
||||||
|
--bg: #f7f6f3;
|
||||||
|
--surface: #ffffff;
|
||||||
|
--text: #1f1d1a;
|
||||||
|
--muted: #6f6a62;
|
||||||
|
--border: #e4e0d8;
|
||||||
|
--accent: #d6457a;
|
||||||
|
--accent-text: #ffffff;
|
||||||
|
--danger: #b4332b;
|
||||||
|
--ok: #2f7d4f;
|
||||||
|
--warn: #a8661b;
|
||||||
|
--info: #3460a8;
|
||||||
|
--code-bg: #f0ede7;
|
||||||
|
--radius: 10px;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
--bg: #151412;
|
||||||
|
--surface: #1e1d1a;
|
||||||
|
--text: #ece8e1;
|
||||||
|
--muted: #a39d93;
|
||||||
|
--border: #34312c;
|
||||||
|
--accent: #ec6b9a;
|
||||||
|
--accent-text: #1a0d12;
|
||||||
|
--danger: #e0675e;
|
||||||
|
--ok: #6cc28f;
|
||||||
|
--warn: #e0a05a;
|
||||||
|
--info: #7fa6ea;
|
||||||
|
--code-bg: #26241f;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
html, body { margin: 0; }
|
||||||
|
body {
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||||
|
}
|
||||||
|
a { color: var(--accent); text-decoration: none; }
|
||||||
|
a:hover { text-decoration: underline; }
|
||||||
|
h1 { font-size: 1.5rem; margin: 0 0 12px; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||||
|
h2 { font-size: 1.1rem; margin: 28px 0 10px; }
|
||||||
|
.mono, code, pre { font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: 0.9em; }
|
||||||
|
.muted { color: var(--muted); }
|
||||||
|
.empty { color: var(--muted); padding: 12px 0; }
|
||||||
|
|
||||||
|
.top {
|
||||||
|
display: flex; align-items: center; gap: 20px; padding: 10px 24px;
|
||||||
|
background: var(--surface); border-bottom: 1px solid var(--border);
|
||||||
|
position: sticky; top: 0; z-index: 1;
|
||||||
|
}
|
||||||
|
.brand { font-weight: 700; color: var(--text); }
|
||||||
|
.top nav { display: flex; gap: 16px; flex: 1; }
|
||||||
|
.top nav a { color: var(--muted); }
|
||||||
|
.me { display: flex; align-items: center; gap: 8px; color: var(--muted); }
|
||||||
|
.me img { border-radius: 50%; }
|
||||||
|
main { max-width: 960px; margin: 0 auto; padding: 24px; }
|
||||||
|
.narrow { max-width: 560px; }
|
||||||
|
.crumbs { margin: 0 0 4px; color: var(--muted); }
|
||||||
|
.desc { white-space: pre-wrap; }
|
||||||
|
|
||||||
|
.card {
|
||||||
|
background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
|
||||||
|
padding: 14px 16px; margin: 10px 0;
|
||||||
|
}
|
||||||
|
.q { border-left: 4px solid var(--info); }
|
||||||
|
.q-approval { border-left-color: var(--accent); }
|
||||||
|
.q-permission { border-left-color: var(--warn); }
|
||||||
|
.q-attention { border-left-color: var(--ok); }
|
||||||
|
.q.answered { opacity: 0.7; border-left-color: var(--border); }
|
||||||
|
.kind { font-weight: 600; }
|
||||||
|
.qtext { white-space: pre-wrap; margin: 8px 0; max-height: 18em; overflow: auto; }
|
||||||
|
.attach { display: block; color: var(--muted); margin: 6px 0; overflow-x: auto; }
|
||||||
|
.count { background: var(--accent); color: var(--accent-text); border-radius: 999px; font-size: 0.8rem; padding: 1px 9px; }
|
||||||
|
|
||||||
|
.row { display: flex; gap: 8px; align-items: center; }
|
||||||
|
.row.wrap { flex-wrap: wrap; }
|
||||||
|
.grow { flex: 1; min-width: 0; }
|
||||||
|
.row > input[type=text] { flex: 1; min-width: 0; }
|
||||||
|
.stack { display: flex; flex-direction: column; gap: 12px; margin: 10px 0; }
|
||||||
|
label { display: flex; flex-direction: column; gap: 4px; font-weight: 500; }
|
||||||
|
label.inline { flex-direction: row; align-items: center; font-weight: 400; }
|
||||||
|
fieldset { border: 1px solid var(--border); border-radius: var(--radius); padding: 8px 12px; }
|
||||||
|
.answer { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }
|
||||||
|
|
||||||
|
input[type=text], textarea, select {
|
||||||
|
font: inherit; color: var(--text); background: var(--bg);
|
||||||
|
border: 1px solid var(--border); border-radius: 8px; padding: 7px 10px; width: 100%;
|
||||||
|
}
|
||||||
|
input.short { width: 8em; }
|
||||||
|
textarea { resize: vertical; }
|
||||||
|
input:focus, textarea:focus, select:focus, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||||
|
|
||||||
|
button, .button {
|
||||||
|
font: inherit; cursor: pointer; border-radius: 8px; padding: 7px 14px;
|
||||||
|
border: 1px solid var(--border); background: var(--surface); color: var(--text); white-space: nowrap;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
button:hover, .button:hover { border-color: var(--muted); text-decoration: none; }
|
||||||
|
.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
|
||||||
|
.danger { color: var(--danger); }
|
||||||
|
button.link { border: 0; background: none; padding: 0; color: var(--muted); }
|
||||||
|
|
||||||
|
.badge {
|
||||||
|
font-size: 0.75rem; font-weight: 600; border-radius: 999px; padding: 2px 9px;
|
||||||
|
background: var(--code-bg); color: var(--muted); white-space: nowrap;
|
||||||
|
}
|
||||||
|
.s-in_progress, .s-running { color: var(--info); }
|
||||||
|
.s-awaiting_approval, .s-waiting_input, .s-proposing { color: var(--accent); }
|
||||||
|
.s-review, .s-done { color: var(--ok); }
|
||||||
|
.s-blocked, .s-failed, .s-stalled, .s-rate_limited { color: var(--danger); }
|
||||||
|
|
||||||
|
.flash { background: color-mix(in srgb, var(--danger) 12%, var(--surface)); border: 1px solid var(--danger); border-radius: var(--radius); padding: 10px 14px; }
|
||||||
|
|
||||||
|
ul.tasks, ul.projects, ul.events { list-style: none; padding: 0; margin: 0; }
|
||||||
|
ul.tasks li, ul.projects li {
|
||||||
|
display: flex; gap: 10px; align-items: center; justify-content: space-between;
|
||||||
|
padding: 8px 12px; background: var(--surface); border: 1px solid var(--border); border-radius: 8px; margin: 6px 0;
|
||||||
|
}
|
||||||
|
ul.tasks li a, ul.projects li a { color: var(--text); min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
ul.events li { padding: 3px 0; border-bottom: 1px dashed var(--border); overflow-wrap: anywhere; }
|
||||||
|
details { margin: 8px 0; }
|
||||||
|
summary { cursor: pointer; color: var(--accent); }
|
||||||
|
pre.md {
|
||||||
|
white-space: pre-wrap; background: var(--code-bg); border-radius: 8px; padding: 12px;
|
||||||
|
max-height: 32em; overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login { max-width: 420px; margin: 18vh auto; text-align: center; display: flex; flex-direction: column; gap: 14px; align-items: center; }
|
||||||
|
.login h1 { font-size: 2rem; justify-content: center; }
|
||||||
|
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
main { padding: 16px; }
|
||||||
|
.top { padding: 10px 16px; gap: 12px; flex-wrap: wrap; }
|
||||||
|
.top nav { order: 3; flex-basis: 100%; }
|
||||||
|
.me span { display: none; }
|
||||||
|
ul.tasks li { flex-direction: column; align-items: flex-start; }
|
||||||
|
}
|
||||||
@ -1,11 +1,12 @@
|
|||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
|
import "./globals.css";
|
||||||
|
|
||||||
export const metadata = { title: "Peppa", description: "Software factory" };
|
export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, задачи и агенты" };
|
||||||
|
|
||||||
export default function RootLayout({ children }: { children: ReactNode }) {
|
export default function RootLayout({ children }: { children: ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<html lang="ru">
|
<html lang="ru">
|
||||||
<body style={{ fontFamily: "system-ui, sans-serif", margin: 0, padding: 24 }}>{children}</body>
|
<body>{children}</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
18
apps/web/app/login/page.tsx
Normal file
18
apps/web/app/login/page.tsx
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { currentUser } from "@/lib/auth";
|
||||||
|
import { Flash } from "@/components/ui";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||||
|
if (await currentUser()) redirect("/");
|
||||||
|
const { error } = await searchParams;
|
||||||
|
return (
|
||||||
|
<main className="login">
|
||||||
|
<h1>🐷 Peppa</h1>
|
||||||
|
<p className="muted">Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.</p>
|
||||||
|
<Flash error={error} />
|
||||||
|
<a className="button primary" href="/auth/start">Войти через Gitea</a>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
8
apps/web/app/logout/route.ts
Normal file
8
apps/web/app/logout/route.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { publicOrigin, SESSION_COOKIE } from "@/lib/auth";
|
||||||
|
|
||||||
|
export async function POST() {
|
||||||
|
const res = NextResponse.redirect(`${await publicOrigin()}/login`, { status: 303 });
|
||||||
|
res.cookies.delete(SESSION_COOKIE);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
@ -1,8 +0,0 @@
|
|||||||
export default function Home() {
|
|
||||||
return (
|
|
||||||
<main>
|
|
||||||
<h1>Peppa</h1>
|
|
||||||
<p>Проекты, цели и задачи появятся на этапе 5.</p>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
19
apps/web/components/AutoRefresh.tsx
Normal file
19
apps/web/components/AutoRefresh.tsx
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
/** Re-renders server data every few seconds, unless the user is typing. */
|
||||||
|
export function AutoRefresh({ everyMs = 5000 }: { everyMs?: number }) {
|
||||||
|
const router = useRouter();
|
||||||
|
useEffect(() => {
|
||||||
|
const id = setInterval(() => {
|
||||||
|
const el = document.activeElement;
|
||||||
|
const typing = el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && el.type === "text");
|
||||||
|
const draft = [...document.querySelectorAll<HTMLTextAreaElement | HTMLInputElement>("textarea, input[type=text]")].some((i) => i.value);
|
||||||
|
if (!typing && !draft && document.visibilityState === "visible") router.refresh();
|
||||||
|
}, everyMs);
|
||||||
|
return () => clearInterval(id);
|
||||||
|
}, [router, everyMs]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
129
apps/web/components/ui.tsx
Normal file
129
apps/web/components/ui.tsx
Normal file
@ -0,0 +1,129 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import type { Question, SessionView } from "@peppa/core";
|
||||||
|
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
|
||||||
|
|
||||||
|
const TASK_STATUS: Record<string, string> = {
|
||||||
|
backlog: "Бэклог",
|
||||||
|
proposing: "Proposal",
|
||||||
|
awaiting_approval: "Ждёт одобрения",
|
||||||
|
in_progress: "В работе",
|
||||||
|
review: "Ревью",
|
||||||
|
done: "Готово",
|
||||||
|
blocked: "Блок",
|
||||||
|
};
|
||||||
|
const SESSION_STATUS: Record<string, string> = {
|
||||||
|
starting: "запуск",
|
||||||
|
running: "работает",
|
||||||
|
waiting_input: "ждёт тебя",
|
||||||
|
idle: "простаивает",
|
||||||
|
stalled: "зависла?",
|
||||||
|
rate_limited: "лимит",
|
||||||
|
done: "завершена",
|
||||||
|
failed: "упала",
|
||||||
|
};
|
||||||
|
const KIND: Record<string, string> = { approval: "Одобрение proposal", question: "Вопрос", permission: "Разрешение", attention: "Сессия ждёт тебя" };
|
||||||
|
|
||||||
|
export function Badge({ status, kind = "task" }: { status: string; kind?: "task" | "session" }) {
|
||||||
|
const label = (kind === "task" ? TASK_STATUS : SESSION_STATUS)[status] ?? status;
|
||||||
|
return <span className={`badge s-${status}`}>{label}</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Flash({ error }: { error?: string }) {
|
||||||
|
return error ? <p className="flash" role="alert">{error}</p> : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ago(d: Date | null | undefined): string {
|
||||||
|
if (!d) return "—";
|
||||||
|
const s = Math.round((Date.now() - d.getTime()) / 1000);
|
||||||
|
if (s < 60) return `${s} с назад`;
|
||||||
|
if (s < 3600) return `${Math.round(s / 60)} мин назад`;
|
||||||
|
if (s < 86400) return `${Math.round(s / 3600)} ч назад`;
|
||||||
|
return d.toLocaleDateString("ru-RU");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function QuestionCard({ q, taskKey, back }: { q: Question; taskKey?: string | null; back: string }) {
|
||||||
|
const answered = !!q.answeredAt;
|
||||||
|
return (
|
||||||
|
<article className={`card q q-${q.kind}${answered ? " answered" : ""}`}>
|
||||||
|
<header className="row">
|
||||||
|
<span className="kind">{KIND[q.kind]}</span>
|
||||||
|
{taskKey && (
|
||||||
|
<Link href={`/t/${taskKey}`} className="mono">
|
||||||
|
{taskKey}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
<span className="muted">#{q.id} · {ago(q.createdAt)}</span>
|
||||||
|
</header>
|
||||||
|
<p className="qtext">{q.text}</p>
|
||||||
|
{answered ? (
|
||||||
|
<p className="muted">
|
||||||
|
{q.answeredVia === "system" ? "⌛ " : "✅ "}
|
||||||
|
{q.answeredVia === "system" ? q.answer : `Ответ (${q.answeredVia}): ${q.answer}`}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<form action={answerQuestion} className="answer">
|
||||||
|
<input type="hidden" name="questionId" value={q.id} />
|
||||||
|
<input type="hidden" name="back" value={back} />
|
||||||
|
<div className="row wrap">
|
||||||
|
{q.kind === "approval" && <button name="choice" value="ок" className="primary">Одобрить</button>}
|
||||||
|
{q.kind === "permission" && (
|
||||||
|
<>
|
||||||
|
<button name="choice" value="allow" className="primary">Разрешить</button>
|
||||||
|
<button name="choice" value="always">Всегда</button>
|
||||||
|
<button name="choice" value="deny" className="danger">Запретить</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{q.kind === "attention" && <button name="choice" value="Продолжай." className="primary">Продолжай</button>}
|
||||||
|
{(q.options ?? []).map((o) => (
|
||||||
|
<button key={o} name="choice" value={o}>{o}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{q.kind !== "permission" && (
|
||||||
|
<div className="row">
|
||||||
|
<input type="text" name="answer" placeholder={q.kind === "approval" ? "Комментарий — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" />
|
||||||
|
<button>Ответить</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SessionCard({ s, back }: { s: SessionView; back: string }) {
|
||||||
|
const alive = !["done", "failed"].includes(s.status);
|
||||||
|
return (
|
||||||
|
<article className="card session">
|
||||||
|
<header className="row">
|
||||||
|
<Badge status={s.status} kind="session" />
|
||||||
|
{s.taskKey && <Link href={`/t/${s.taskKey}`} className="mono">{s.taskKey}</Link>}
|
||||||
|
<span className="muted">#{s.id} · {s.provider} · поколение {s.generation} · {ago(s.lastActivityAt)}</span>
|
||||||
|
</header>
|
||||||
|
<code className="attach">tmux attach -t {s.tmuxName}</code>
|
||||||
|
<div className="row wrap">
|
||||||
|
{alive && (
|
||||||
|
<form action={messageSession} className="row grow">
|
||||||
|
<input type="hidden" name="sessionId" value={s.id} />
|
||||||
|
<input type="hidden" name="back" value={back} />
|
||||||
|
<input type="text" name="text" placeholder="Сообщение в сессию" aria-label="Сообщение в сессию" />
|
||||||
|
<button>Отправить</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
{alive ? (
|
||||||
|
<form action={stopTaskSession}>
|
||||||
|
<input type="hidden" name="sessionId" value={s.id} />
|
||||||
|
<input type="hidden" name="back" value={back} />
|
||||||
|
<button className="danger">Остановить</button>
|
||||||
|
</form>
|
||||||
|
) : null}
|
||||||
|
{(!alive || ["rate_limited", "stalled"].includes(s.status)) && (
|
||||||
|
<form action={resumeTaskSession}>
|
||||||
|
<input type="hidden" name="sessionId" value={s.id} />
|
||||||
|
<input type="hidden" name="back" value={back} />
|
||||||
|
<button>Resume</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
50
apps/web/lib/auth.ts
Normal file
50
apps/web/lib/auth.ts
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
import { getUser, sign, verify, type User } from "@peppa/core";
|
||||||
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
import { cookies, headers } from "next/headers";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { db } from "./db";
|
||||||
|
|
||||||
|
export const SESSION_COOKIE = "peppa_session";
|
||||||
|
export const STATE_COOKIE = "peppa_oauth_state";
|
||||||
|
const SESSION_DAYS = 30;
|
||||||
|
|
||||||
|
interface SessionPayload {
|
||||||
|
uid: number;
|
||||||
|
exp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function currentUser(): Promise<User | null> {
|
||||||
|
const p = verify<SessionPayload>((await cookies()).get(SESSION_COOKIE)?.value);
|
||||||
|
if (!p || p.exp < Date.now()) return null;
|
||||||
|
return getUser(db, p.uid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** For pages and server actions: the logged-in user, or a redirect to /login. */
|
||||||
|
export async function requireUser(): Promise<User> {
|
||||||
|
const u = await currentUser();
|
||||||
|
if (!u) redirect("/login");
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sessionCookie(uid: number) {
|
||||||
|
const exp = Date.now() + SESSION_DAYS * 86400_000;
|
||||||
|
return {
|
||||||
|
name: SESSION_COOKIE,
|
||||||
|
value: sign({ uid, exp } satisfies SessionPayload),
|
||||||
|
options: { httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/", maxAge: SESSION_DAYS * 86400 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const isHttps = () => loadEnv().PEPPA_WEB_URL.startsWith("https://");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public origin of this request. Behind Cloudflare → Traefik the proto header says http,
|
||||||
|
* so the configured PEPPA_WEB_URL wins when the host matches it.
|
||||||
|
*/
|
||||||
|
export async function publicOrigin(): Promise<string> {
|
||||||
|
const h = await headers();
|
||||||
|
const host = h.get("x-forwarded-host") ?? h.get("host") ?? "localhost:3100";
|
||||||
|
const configured = new URL(loadEnv().PEPPA_WEB_URL);
|
||||||
|
if (host === configured.host) return configured.origin;
|
||||||
|
return `${host.startsWith("localhost") || host.startsWith("127.") ? "http" : "https"}://${host}`;
|
||||||
|
}
|
||||||
5
apps/web/lib/db.ts
Normal file
5
apps/web/lib/db.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { createDb, type Db } from "@peppa/db";
|
||||||
|
|
||||||
|
// One pool per server process (survives dev hot reloads).
|
||||||
|
const g = globalThis as { __peppaDb?: Db };
|
||||||
|
export const db: Db = (g.__peppaDb ??= createDb());
|
||||||
77
apps/web/lib/queries.ts
Normal file
77
apps/web/lib/queries.ts
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { listSessions, PeppaError, projectForUser, resolveTask, type Project, type TaskRef } from "@peppa/core";
|
||||||
|
import { events, goals, projects, questions, sessions, tasks } from "@peppa/db";
|
||||||
|
import { formatTaskKey } from "@peppa/shared";
|
||||||
|
import { and, asc, desc, eq, isNull } from "drizzle-orm";
|
||||||
|
import { db } from "./db";
|
||||||
|
|
||||||
|
export type InboxItem = Awaited<ReturnType<typeof inbox>>[number];
|
||||||
|
|
||||||
|
/** Open PM questions across the user's projects, oldest first. */
|
||||||
|
export async function inbox(userId: number) {
|
||||||
|
const rows = await db
|
||||||
|
.select({ q: questions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, tmux: sessions.tmuxName })
|
||||||
|
.from(questions)
|
||||||
|
.innerJoin(projects, eq(questions.projectId, projects.id))
|
||||||
|
.leftJoin(tasks, eq(questions.taskId, tasks.id))
|
||||||
|
.leftJoin(sessions, eq(questions.sessionId, sessions.id))
|
||||||
|
.where(and(eq(projects.ownerId, userId), isNull(questions.answeredAt)))
|
||||||
|
.orderBy(asc(questions.id));
|
||||||
|
return rows.map((r) => ({ ...r.q, taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, taskTitle: r.taskTitle, tmux: r.tmux }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function activeSessions(userId: number) {
|
||||||
|
const mine = await db.select({ id: projects.id }).from(projects).where(eq(projects.ownerId, userId));
|
||||||
|
if (!mine.length) return [];
|
||||||
|
const ids = new Set(mine.map((p) => p.id));
|
||||||
|
return (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function projectForUserByKey(userId: number, key: string): Promise<Project> {
|
||||||
|
const [p] = await db.select().from(projects).where(eq(projects.key, key.toUpperCase()));
|
||||||
|
if (!p) throw new PeppaError("Не найдено");
|
||||||
|
return projectForUser(db, userId, p.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function board(projectId: number) {
|
||||||
|
const gs = await db.select().from(goals).where(eq(goals.projectId, projectId)).orderBy(asc(goals.id));
|
||||||
|
const ts = await db.select().from(tasks).where(eq(tasks.projectId, projectId)).orderBy(asc(tasks.number));
|
||||||
|
return { goals: gs, tasks: ts };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function projectSessions(projectId: number) {
|
||||||
|
return (await listSessions(db)).filter((s) => s.projectId === projectId).slice(0, 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function taskForUser(userId: number, key: string): Promise<TaskRef> {
|
||||||
|
const ref = await resolveTask(db, key);
|
||||||
|
await projectForUser(db, userId, ref.project.id);
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function taskActivity(taskId: number) {
|
||||||
|
const qs = await db.select().from(questions).where(eq(questions.taskId, taskId)).orderBy(desc(questions.id));
|
||||||
|
const ss = await listSessions(db, { taskId });
|
||||||
|
const evs = await db.select().from(events).where(eq(events.taskId, taskId)).orderBy(desc(events.id)).limit(40);
|
||||||
|
return { questions: qs, sessions: ss, events: evs };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isActiveSession = (status: string) => !["done", "failed"].includes(status);
|
||||||
|
|
||||||
|
/** OpenSpec artifacts of a change from the working copy (active or archived). */
|
||||||
|
export function openspecArtifacts(p: Project, change: string | null): Array<{ name: string; text: string }> | null {
|
||||||
|
if (!change) return null;
|
||||||
|
const changes = join(p.workspacePath, "openspec", "changes");
|
||||||
|
let dir = join(changes, change);
|
||||||
|
if (!existsSync(dir)) {
|
||||||
|
const archive = join(changes, "archive");
|
||||||
|
const hit = existsSync(archive) ? readdirSync(archive).find((d) => d.endsWith(`-${change}`) || d === change) : undefined;
|
||||||
|
if (!hit) return null;
|
||||||
|
dir = join(archive, hit);
|
||||||
|
}
|
||||||
|
return ["proposal.md", "design.md", "tasks.md"]
|
||||||
|
.filter((f) => existsSync(join(dir, f)))
|
||||||
|
.map((f) => ({ name: f, text: readFileSync(join(dir, f), "utf8") }));
|
||||||
|
}
|
||||||
|
|
||||||
@ -1,7 +1,8 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
const config: NextConfig = {
|
const config: NextConfig = {
|
||||||
transpilePackages: ["@peppa/db", "@peppa/shared"],
|
// Workspace packages ship TypeScript sources.
|
||||||
|
transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner"],
|
||||||
};
|
};
|
||||||
|
|
||||||
export default config;
|
export default config;
|
||||||
|
|||||||
@ -14,7 +14,10 @@
|
|||||||
"@peppa/shared": "workspace:*",
|
"@peppa/shared": "workspace:*",
|
||||||
"next": "16.4.6",
|
"next": "16.4.6",
|
||||||
"react": "19.3.1",
|
"react": "19.3.1",
|
||||||
"react-dom": "19.3.1"
|
"react-dom": "19.3.1",
|
||||||
|
"@peppa/core": "workspace:*",
|
||||||
|
"@peppa/runner": "workspace:*",
|
||||||
|
"drizzle-orm": "0.45.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/react": "19.3.0",
|
"@types/react": "19.3.0",
|
||||||
|
|||||||
@ -4,11 +4,31 @@
|
|||||||
"module": "ESNext",
|
"module": "ESNext",
|
||||||
"moduleResolution": "Bundler",
|
"moduleResolution": "Bundler",
|
||||||
"jsx": "preserve",
|
"jsx": "preserve",
|
||||||
"lib": ["dom", "dom.iterable", "ES2023"],
|
"lib": [
|
||||||
|
"dom",
|
||||||
|
"dom.iterable",
|
||||||
|
"ES2023"
|
||||||
|
],
|
||||||
"allowJs": false,
|
"allowJs": false,
|
||||||
"allowImportingTsExtensions": true,
|
"allowImportingTsExtensions": true,
|
||||||
"plugins": [{ "name": "next" }]
|
"plugins": [
|
||||||
|
{
|
||||||
|
"name": "next"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"paths": {
|
||||||
|
"@/*": [
|
||||||
|
"./*"
|
||||||
|
]
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
"include": [
|
||||||
"exclude": ["node_modules"]
|
"next-env.d.ts",
|
||||||
|
"**/*.ts",
|
||||||
|
"**/*.tsx",
|
||||||
|
".next/types/**/*.ts"
|
||||||
|
],
|
||||||
|
"exclude": [
|
||||||
|
"node_modules"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,35 +2,35 @@
|
|||||||
|
|
||||||
## 1. Данные и core
|
## 1. Данные и core
|
||||||
|
|
||||||
- [ ] 1.1 Миграция: `users` (gitea id, login, имя, аватар, зашифрованные токены, срок), `projects.owner_id`; `pnpm db:migrate` проходит на основной и тестовой БД
|
- [x] 1.1 Миграция: `users` (gitea id, login, имя, аватар, зашифрованные токены, срок), `projects.owner_id`; `pnpm db:migrate` проходит на основной и тестовой БД
|
||||||
- [ ] 1.2 core: шифрование токенов (AES-256-GCM от `PEPPA_SECRET`), upsert пользователя, `assertProjectAccess`; unit-тест шифрования и проверки доступа
|
- [x] 1.2 core: шифрование токенов (AES-256-GCM от `PEPPA_SECRET`), upsert пользователя, `assertProjectAccess`; unit-тест шифрования и проверки доступа
|
||||||
- [ ] 1.3 core: клиент Gitea API (user, orgs, repo get/create, collaborator, OAuth token/refresh); тесты против mock-gitea
|
- [x] 1.3 core: клиент Gitea API (user, orgs, repo get/create, collaborator, OAuth token/refresh); тесты против mock-gitea
|
||||||
- [ ] 1.4 `PEPPA_ROOT` для путей к bin/шаблону в runner и core; e2e-набор зелёный
|
- [x] 1.4 `PEPPA_ROOT` для путей к bin/шаблону в runner и core; e2e-набор зелёный
|
||||||
|
|
||||||
## 2. Создание проекта
|
## 2. Создание проекта
|
||||||
|
|
||||||
- [ ] 2.1 runner: `provisionProject` (новый/существующий репо, бот-соавтор, шаблон, openspec, коммит, push, запись в БД, откат при ошибке); тест на mock-gitea + локальном bare-репо
|
- [x] 2.1 runner: `provisionProject` (новый/существующий репо, бот-соавтор, шаблон, openspec, коммит, push, запись в БД, откат при ошибке); тест на mock-gitea + локальном bare-репо
|
||||||
- [ ] 2.2 CLI `peppa project create`, `peppa project owner`; удалить `scripts/bootstrap-project.sh`; проверка: создать проект из CLI в реальной Gitea
|
- [x] 2.2 CLI `peppa project create`, `peppa project owner`; удалить `scripts/bootstrap-project.sh`; проверка: создать проект из CLI в реальной Gitea
|
||||||
- [ ] 2.3 Скрипт создания OAuth-приложения Gitea, переменные в `.env`; проверка: authorize URL открывает экран согласия Gitea
|
- [x] 2.3 Скрипт создания OAuth-приложения Gitea, переменные в `.env`; проверка: authorize URL открывает экран согласия Gitea
|
||||||
|
|
||||||
## 3. Веб: вход
|
## 3. Веб: вход
|
||||||
|
|
||||||
- [ ] 3.1 Cookie-сессия, `/login`, `/auth/callback` (state, обмен кода, upsert), `/logout`, middleware закрытия страниц; проверка: без cookie любая страница → `/login`
|
- [x] 3.1 Cookie-сессия, `/login`, `/auth/callback` (state, обмен кода, upsert), `/logout`, middleware закрытия страниц; проверка: без cookie любая страница → `/login`
|
||||||
- [ ] 3.2 Админская ссылка: `peppa web login-link` + `/auth/link`; проверка: ссылка работает один раз и 10 минут
|
- [x] 3.2 Админская ссылка: `peppa web login-link` + `/auth/link`; проверка: ссылка работает один раз и 10 минут
|
||||||
|
|
||||||
## 4. Веб: работа
|
## 4. Веб: работа
|
||||||
|
|
||||||
- [ ] 4.1 Главная: входящие (вопросы с формой ответа), активные сессии, мои проекты
|
- [x] 4.1 Главная: входящие (вопросы с формой ответа), активные сессии, мои проекты
|
||||||
- [ ] 4.2 Новый проект: форма (имя, slug, ключ, пространство из Gitea, новый/существующий репо) → `provisionProject`
|
- [x] 4.2 Новый проект: форма (имя, slug, ключ, пространство из Gitea, новый/существующий репо) → `provisionProject`
|
||||||
- [ ] 4.3 Проект: цели → задачи, создание цели и задачи, сессии
|
- [x] 4.3 Проект: цели → задачи, создание цели и задачи, сессии
|
||||||
- [ ] 4.4 Задача: описание, артефакты OpenSpec из рабочей копии, вопросы и ответы, сессии (старт с провайдером, стоп, resume, сообщение), события
|
- [x] 4.4 Задача: описание, артефакты OpenSpec из рабочей копии, вопросы и ответы, сессии (старт с провайдером, стоп, resume, сообщение), события
|
||||||
- [ ] 4.5 Авто-обновление страниц (≤10 с), светлая/тёмная тема, мобильная ширина
|
- [x] 4.5 Авто-обновление страниц (≤10 с), светлая/тёмная тема, мобильная ширина
|
||||||
|
|
||||||
## 5. Проверка и выкатка
|
## 5. Проверка и выкатка
|
||||||
|
|
||||||
- [ ] 5.1 e2e-набор testkit + новые тесты зелёные; `pnpm typecheck` и `next build` проходят
|
- [x] 5.1 e2e-набор testkit + новые тесты зелёные; `pnpm typecheck` и `next build` проходят
|
||||||
- [ ] 5.2 Выкатка: миграция, сборка, перезапуск launchd web; проверка в браузере через админскую ссылку: входящие, проект PEP, задача PEP-1, ответ на вопрос, запуск сессии на моке
|
- [x] 5.2 Выкатка: миграция, сборка, перезапуск launchd web; проверка в браузере через админскую ссылку: входящие, проект PEP, задача PEP-1, ответ на вопрос, запуск сессии на моке
|
||||||
- [ ] 5.3 `openspec validate pep-1-web-platform` проходит
|
- [x] 5.3 `openspec validate pep-1-web-platform` проходит
|
||||||
|
|
||||||
## Workflow follow-up
|
## Workflow follow-up
|
||||||
|
|
||||||
47
openspec/specs/project-provisioning/spec.md
Normal file
47
openspec/specs/project-provisioning/spec.md
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
# project-provisioning Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
Описывает, как появляется проект Пеппы: репозиторий в Gitea с ботом-соавтором, общий шаблон и OpenSpec, рабочая копия для сессий агентов и запись в Пеппе.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Новый проект с новым репозиторием
|
||||||
|
Пеппа SHALL создавать проект по имени, slug и ключу задач: приватный репозиторий в
|
||||||
|
выбранном пространстве (пользователь или организация, где он может создавать
|
||||||
|
репозитории), заполненный из шаблона и инициализированный OpenSpec.
|
||||||
|
|
||||||
|
#### Scenario: Успешное создание
|
||||||
|
- **WHEN** пользователь создаёт проект «Demo», slug `demo`, ключ `DEMO` в своём пространстве
|
||||||
|
- **THEN** в Gitea появляется приватный `<login>/demo` с первым коммитом от Peppa, содержащим `AGENTS.md`, `CLAUDE.md`, `.mcp.json`, `.peppa/project.json` (slug, ключ, URL Пеппы) и `openspec/`, но не `RULES.md`; в Пеппе появляется проект DEMO с владельцем-пользователем; рабочая копия лежит в `$PEPPA_WORKSPACES/demo`
|
||||||
|
|
||||||
|
#### Scenario: Конфликты
|
||||||
|
- **WHEN** slug или ключ уже заняты в Пеппе, или репозиторий с таким именем уже есть в выбранном пространстве
|
||||||
|
- **THEN** проект не создаётся, пользователь видит причину, частично созданное не остаётся в Пеппе
|
||||||
|
|
||||||
|
### Requirement: Подключение существующего репозитория
|
||||||
|
Пеппа SHALL подключать существующий репозиторий, к которому у пользователя есть права
|
||||||
|
администратора, не теряя его содержимого.
|
||||||
|
|
||||||
|
#### Scenario: Репозиторий с кодом
|
||||||
|
- **WHEN** пользователь подключает существующий непустой репозиторий
|
||||||
|
- **THEN** в основную ветку добавляется коммит с недостающими файлами Пеппы (`.peppa/project.json`, `.mcp.json`, `AGENTS.md` — только если их нет) и `openspec/` (если нет); существующие файлы не перезаписываются
|
||||||
|
|
||||||
|
#### Scenario: Нет прав администратора
|
||||||
|
- **WHEN** у пользователя нет прав администратора на репозиторий
|
||||||
|
- **THEN** подключение отклоняется с объяснением
|
||||||
|
|
||||||
|
### Requirement: Бот-соавтор
|
||||||
|
Каждый репозиторий проекта SHALL иметь `peppa-bot` соавтором с правом записи, чтобы
|
||||||
|
сессии агентов могли пушить ветки; рабочая копия настроена пушить от имени бота.
|
||||||
|
|
||||||
|
#### Scenario: После создания или подключения
|
||||||
|
- **WHEN** проект создан или подключён
|
||||||
|
- **THEN** `peppa-bot` — соавтор репозитория с правом write, а `git push` из рабочей копии проходит без ввода учётных данных
|
||||||
|
|
||||||
|
### Requirement: Создание проекта из CLI
|
||||||
|
Тот же сценарий SHALL быть доступен из CLI на машине Пеппы от имени `peppa-bot`
|
||||||
|
(репозиторий в пространстве бота, без владельца-пользователя).
|
||||||
|
|
||||||
|
#### Scenario: CLI
|
||||||
|
- **WHEN** админ выполняет `peppa project create demo DEMO "Demo"`
|
||||||
|
- **THEN** результат совпадает с созданием из веба, кроме пространства (`peppa-bot`) и отсутствия владельца
|
||||||
54
openspec/specs/web-auth/spec.md
Normal file
54
openspec/specs/web-auth/spec.md
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
# web-auth Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
Определяет, кто и как входит в веб Пеппы и к каким данным получает доступ: вход через аккаунт Gitea, сессии веба и изоляция проектов между пользователями.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Вход через Gitea
|
||||||
|
Веб SHALL пускать пользователя только после авторизации через OAuth2 Gitea, на которой
|
||||||
|
размещены репозитории Пеппы. Пользователь Пеппы однозначно соответствует аккаунту Gitea.
|
||||||
|
|
||||||
|
#### Scenario: Первый вход
|
||||||
|
- **WHEN** неавторизованный пользователь открывает любую страницу веба
|
||||||
|
- **THEN** он попадает на страницу входа, а после подтверждения в Gitea возвращается в веб авторизованным, и для него создаётся пользователь Пеппы с логином, именем и аватаром из Gitea
|
||||||
|
|
||||||
|
#### Scenario: Подделка или повтор колбэка
|
||||||
|
- **WHEN** колбэк OAuth приходит без корректного `state` текущего браузера или с уже использованным кодом
|
||||||
|
- **THEN** вход не выполняется и показывается ошибка
|
||||||
|
|
||||||
|
### Requirement: Закрытый веб
|
||||||
|
Все страницы и действия веба, кроме страницы входа и колбэка OAuth, SHALL требовать
|
||||||
|
действующую сессию. Сессия хранится в подписанной httpOnly cookie и истекает через 30 дней.
|
||||||
|
|
||||||
|
#### Scenario: Запрос без сессии
|
||||||
|
- **WHEN** запрос к странице или действию приходит без сессии или с невалидной подписью
|
||||||
|
- **THEN** страница перенаправляет на вход, а действие отклоняется без изменений данных
|
||||||
|
|
||||||
|
#### Scenario: Выход
|
||||||
|
- **WHEN** пользователь нажимает «Выйти»
|
||||||
|
- **THEN** cookie сессии удаляется, и следующий запрос требует входа
|
||||||
|
|
||||||
|
### Requirement: Доступ только к своим проектам
|
||||||
|
Пользователь SHALL видеть и изменять только проекты, владельцем которых он является, а
|
||||||
|
также их цели, задачи, сессии и вопросы.
|
||||||
|
|
||||||
|
#### Scenario: Чужой проект
|
||||||
|
- **WHEN** пользователь открывает проект, задачу или сессию чужого проекта (в том числе по прямой ссылке) или отправляет по ним действие
|
||||||
|
- **THEN** он получает «не найдено», данные не раскрываются и не меняются
|
||||||
|
|
||||||
|
### Requirement: Токены Gitea пользователя
|
||||||
|
Токены OAuth пользователя SHALL храниться только в зашифрованном виде и обновляться
|
||||||
|
по refresh-токену, когда истекли. Токены не показываются в вебе и не пишутся в логи.
|
||||||
|
|
||||||
|
#### Scenario: Истёкший токен
|
||||||
|
- **WHEN** действие требует обращения к Gitea от имени пользователя, а access-токен истёк
|
||||||
|
- **THEN** Пеппа обновляет его по refresh-токену; если обновить нельзя — просит войти заново
|
||||||
|
|
||||||
|
### Requirement: Админская ссылка входа
|
||||||
|
Пользователь машины Пеппы SHALL иметь возможность получить одноразовую ссылку входа
|
||||||
|
за существующего пользователя через локальный CLI. Ссылка действует 10 минут и один раз.
|
||||||
|
|
||||||
|
#### Scenario: Использование ссылки
|
||||||
|
- **WHEN** админ выполняет `peppa web login-link <login>` и открывает ссылку
|
||||||
|
- **THEN** браузер получает сессию этого пользователя; повторное открытие ссылки или открытие после 10 минут — отказ
|
||||||
64
openspec/specs/web-workspace/spec.md
Normal file
64
openspec/specs/web-workspace/spec.md
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
# web-workspace Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
Определяет, что пользователь делает в вебе со своими проектами: ведёт цели и задачи, следит за сессиями агентов и управляет ими, отвечает на вопросы агентов.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Входящие
|
||||||
|
Главная страница SHALL показывать открытые вопросы PM по проектам пользователя (сначала
|
||||||
|
старые), активные сессии и список проектов.
|
||||||
|
|
||||||
|
#### Scenario: Есть вопросы
|
||||||
|
- **WHEN** у пользователя есть неотвеченные вопросы в его проектах
|
||||||
|
- **THEN** на главной каждый виден с задачей, типом (одобрение, вопрос, разрешение, «ждёт тебя»), текстом и формой ответа
|
||||||
|
|
||||||
|
### Requirement: Цели и задачи
|
||||||
|
Пользователь SHALL создавать цели и задачи в своём проекте и видеть задачи
|
||||||
|
сгруппированными по целям со статусами. Номер задачи выдаётся так же, как через MCP и CLI.
|
||||||
|
|
||||||
|
#### Scenario: Новая задача под целью
|
||||||
|
- **WHEN** пользователь создаёт задачу с названием и описанием под целью
|
||||||
|
- **THEN** задача получает следующий номер проекта (`KEY-N`), статус `backlog` и видна под этой целью
|
||||||
|
|
||||||
|
### Requirement: Страница задачи
|
||||||
|
Страница задачи SHALL показывать описание, цель, статус, PR, артефакты OpenSpec change
|
||||||
|
(proposal, design, tasks — как текст из рабочей копии), вопросы с ответами, сессии и
|
||||||
|
последние события.
|
||||||
|
|
||||||
|
#### Scenario: Change ещё не создан
|
||||||
|
- **WHEN** у задачи нет OpenSpec change или его файлов нет в рабочей копии
|
||||||
|
- **THEN** вместо артефактов показывается «change ещё не создан», страница работает
|
||||||
|
|
||||||
|
### Requirement: Ответ на вопрос из веба
|
||||||
|
Ответ на открытый вопрос из веба SHALL сохраняться с отметкой «web» и доставляться в
|
||||||
|
сессию тем же путём, что ответ из Telegram (включая одобрение proposal и ответы на
|
||||||
|
разрешения).
|
||||||
|
|
||||||
|
#### Scenario: Одобрение из веба
|
||||||
|
- **WHEN** пользователь одобряет proposal задачи в статусе `awaiting_approval`
|
||||||
|
- **THEN** задача переходит в `in_progress`, агент получает сообщение «переходи к Apply», вопрос закрыт с ответом «web»
|
||||||
|
|
||||||
|
#### Scenario: Уже отвечено
|
||||||
|
- **WHEN** пользователь отвечает на вопрос, на который уже ответили в другом месте
|
||||||
|
- **THEN** ответ не применяется, показывается, кто и что ответил
|
||||||
|
|
||||||
|
### Requirement: Управление сессиями
|
||||||
|
Пользователь SHALL запускать сессию по задаче (Claude или Codex), останавливать,
|
||||||
|
перезапускать (resume) и отправлять сообщение в работающую сессию.
|
||||||
|
|
||||||
|
#### Scenario: Запуск
|
||||||
|
- **WHEN** пользователь запускает сессию по задаче с провайдером Claude
|
||||||
|
- **THEN** сессия стартует в tmux так же, как `peppa session start`, и видна со статусом и командой `tmux attach`
|
||||||
|
|
||||||
|
#### Scenario: Resume недоступен
|
||||||
|
- **WHEN** пользователь пытается перезапустить ещё работающую сессию
|
||||||
|
- **THEN** действие отклоняется с объяснением
|
||||||
|
|
||||||
|
### Requirement: Актуальность
|
||||||
|
Страницы входящих, проекта и задачи SHALL обновлять данные без ручной перезагрузки не
|
||||||
|
реже раза в 10 секунд.
|
||||||
|
|
||||||
|
#### Scenario: Вопрос появился, пока страница открыта
|
||||||
|
- **WHEN** агент задаёт вопрос, пока у пользователя открыта главная
|
||||||
|
- **THEN** вопрос появляется на странице в течение 10 секунд
|
||||||
@ -7,10 +7,14 @@ import {
|
|||||||
createTask,
|
createTask,
|
||||||
findProjectFile,
|
findProjectFile,
|
||||||
getProject,
|
getProject,
|
||||||
|
createLoginLink,
|
||||||
createPairingCode,
|
createPairingCode,
|
||||||
getBinding,
|
getBinding,
|
||||||
getSession,
|
getSession,
|
||||||
getSetting,
|
getSetting,
|
||||||
|
getUserByLogin,
|
||||||
|
giteaForBot,
|
||||||
|
setProjectOwner,
|
||||||
getTaskDetails,
|
getTaskDetails,
|
||||||
unpair,
|
unpair,
|
||||||
listSessions,
|
listSessions,
|
||||||
@ -25,13 +29,15 @@ import {
|
|||||||
type TaskStatus,
|
type TaskStatus,
|
||||||
} from "@peppa/core";
|
} from "@peppa/core";
|
||||||
import { createDb } from "@peppa/db";
|
import { createDb } from "@peppa/db";
|
||||||
import { answerAndDeliver, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
import { answerAndDeliver, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||||
import { spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
|
||||||
const USAGE = `peppa — Peppa software factory CLI
|
const USAGE = `peppa — Peppa software factory CLI
|
||||||
|
|
||||||
peppa project add <slug> <KEY> <name> [--owner peppa] [--repo <name>] [--path <dir>]
|
peppa project create <slug> <KEY> <name> [--existing] (repo in peppa-bot's Gitea namespace)
|
||||||
|
peppa project add <slug> <KEY> <name> [--owner peppa] [--repo <name>] [--path <dir>] (register only)
|
||||||
|
peppa project owner <KEY> <gitea-login|->
|
||||||
peppa project list
|
peppa project list
|
||||||
peppa goal add [KEY] <title> [-d <description>]
|
peppa goal add [KEY] <title> [-d <description>]
|
||||||
peppa goal list [KEY]
|
peppa goal list [KEY]
|
||||||
@ -48,6 +54,7 @@ const USAGE = `peppa — Peppa software factory CLI
|
|||||||
peppa session stop <id>
|
peppa session stop <id>
|
||||||
peppa session resume <id> [-p <extra prompt>] (new generation, claude --resume)
|
peppa session resume <id> [-p <extra prompt>] (new generation, claude --resume)
|
||||||
peppa telegram pair | status | unpair
|
peppa telegram pair | status | unpair
|
||||||
|
peppa web login-link <gitea-login> (one-time admin login, 10 minutes)
|
||||||
peppa watchdog [--once] [--interval <sec>] [--stall <min>]
|
peppa watchdog [--once] [--interval <sec>] [--stall <min>]
|
||||||
|
|
||||||
KEY defaults to the project of the current directory (.peppa/project.json).
|
KEY defaults to the project of the current directory (.peppa/project.json).
|
||||||
@ -56,7 +63,8 @@ Statuses: ${TASK_STATUSES.join(", ")}`;
|
|||||||
const { values: opts, positionals } = parseArgs({
|
const { values: opts, positionals } = parseArgs({
|
||||||
allowPositionals: true,
|
allowPositionals: true,
|
||||||
options: {
|
options: {
|
||||||
owner: { type: "string", default: "peppa" },
|
owner: { type: "string", default: "peppa-bot" },
|
||||||
|
existing: { type: "boolean" },
|
||||||
repo: { type: "string" },
|
repo: { type: "string" },
|
||||||
path: { type: "string" },
|
path: { type: "string" },
|
||||||
description: { type: "string", short: "d" },
|
description: { type: "string", short: "d" },
|
||||||
@ -114,8 +122,35 @@ async function main(): Promise<void> {
|
|||||||
console.log(`Project ${p.key} (${p.slug}) → ${p.workspacePath}`);
|
console.log(`Project ${p.key} (${p.slug}) → ${p.workspacePath}`);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case "project create": {
|
||||||
|
const [slug, key, name] = args;
|
||||||
|
if (!slug || !key || !name) throw new PeppaError("usage: peppa project create <slug> <KEY> <name> [--existing]");
|
||||||
|
const bot = giteaForBot();
|
||||||
|
const p = await provisionProject(db, {
|
||||||
|
gitea: bot,
|
||||||
|
owner: process.env.GITEA_BOT_USER ?? "peppa-bot",
|
||||||
|
ownerIsUser: true,
|
||||||
|
slug,
|
||||||
|
key,
|
||||||
|
name,
|
||||||
|
existing: opts.existing,
|
||||||
|
log: (step) => console.log(`… ${step}`),
|
||||||
|
});
|
||||||
|
console.log(`Project ${p.key} → ${p.workspacePath} (${env.GITEA_URL}/${p.giteaOwner}/${p.giteaRepo})`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "project owner": {
|
||||||
|
const [key, login] = args;
|
||||||
|
if (!key || !login) throw new PeppaError("usage: peppa project owner <KEY> <gitea-login|->");
|
||||||
|
const p = await getProject(db, key);
|
||||||
|
const u = login === "-" ? null : await getUserByLogin(db, login);
|
||||||
|
if (login !== "-" && !u) throw new PeppaError(`User ${login} has never logged into the web`);
|
||||||
|
await setProjectOwner(db, p.id, u?.id ?? null);
|
||||||
|
console.log(`${p.key} owner → ${u?.login ?? "none"}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "project list":
|
case "project list":
|
||||||
for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}`);
|
for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}${p.ownerId ? ` owner #${p.ownerId}` : ""}`);
|
||||||
break;
|
break;
|
||||||
case "goal add": {
|
case "goal add": {
|
||||||
const [key, [title]] = withKey(args, 1);
|
const [key, [title]] = withKey(args, 1);
|
||||||
@ -203,6 +238,12 @@ async function main(): Promise<void> {
|
|||||||
await stopSession(db, Number(args[0]));
|
await stopSession(db, Number(args[0]));
|
||||||
console.log("stopped");
|
console.log("stopped");
|
||||||
break;
|
break;
|
||||||
|
case "web login-link": {
|
||||||
|
const u = await getUserByLogin(db, args[0] ?? "");
|
||||||
|
if (!u) throw new PeppaError(`User "${args[0]}" has never logged into the web`);
|
||||||
|
console.log(`${env.PEPPA_WEB_URL}/auth/link?code=${await createLoginLink(db, u.id)}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "telegram pair": {
|
case "telegram pair": {
|
||||||
if (!env.TELEGRAM_BOT_TOKEN) throw new PeppaError("TELEGRAM_BOT_TOKEN is not set in .env");
|
if (!env.TELEGRAM_BOT_TOKEN) throw new PeppaError("TELEGRAM_BOT_TOKEN is not set in .env");
|
||||||
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
|
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
|
||||||
|
|||||||
47
packages/core/src/crypto.ts
Normal file
47
packages/core/src/crypto.ts
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||||
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
|
||||||
|
function secret(): string {
|
||||||
|
const s = loadEnv().PEPPA_SECRET;
|
||||||
|
if (!s) throw new Error("PEPPA_SECRET is not set");
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = (purpose: string) => createHash("sha256").update(`${purpose}:${secret()}`).digest();
|
||||||
|
|
||||||
|
/** AES-256-GCM; output is base64url(iv | tag | ciphertext). */
|
||||||
|
export function encrypt(plain: string): string {
|
||||||
|
const iv = randomBytes(12);
|
||||||
|
const c = createCipheriv("aes-256-gcm", key("enc"), iv);
|
||||||
|
const data = Buffer.concat([c.update(plain, "utf8"), c.final()]);
|
||||||
|
return Buffer.concat([iv, c.getAuthTag(), data]).toString("base64url");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decrypt(enc: string): string {
|
||||||
|
const buf = Buffer.from(enc, "base64url");
|
||||||
|
const d = createDecipheriv("aes-256-gcm", key("enc"), buf.subarray(0, 12));
|
||||||
|
d.setAuthTag(buf.subarray(12, 28));
|
||||||
|
return Buffer.concat([d.update(buf.subarray(28)), d.final()]).toString("utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `payload.signature` token (HMAC-SHA256), used for web session cookies. */
|
||||||
|
export function sign(payload: object): string {
|
||||||
|
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
||||||
|
return `${body}.${createHmac("sha256", key("sign")).update(body).digest("base64url")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verify<T>(token: string | undefined): T | null {
|
||||||
|
if (!token) return null;
|
||||||
|
const [body, sig] = token.split(".");
|
||||||
|
if (!body || !sig) return null;
|
||||||
|
const expected = createHmac("sha256", key("sign")).update(body).digest();
|
||||||
|
const given = Buffer.from(sig, "base64url");
|
||||||
|
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
|
||||||
|
try {
|
||||||
|
return JSON.parse(Buffer.from(body, "base64url").toString("utf8")) as T;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const hashToken = (s: string) => createHmac("sha256", key("hash")).update(s).digest("hex");
|
||||||
130
packages/core/src/gitea.ts
Normal file
130
packages/core/src/gitea.ts
Normal file
@ -0,0 +1,130 @@
|
|||||||
|
// Gitea API client: as a user (OAuth token) or as peppa-bot (GITEA_TOKEN).
|
||||||
|
import { PeppaError } from "./errors.ts";
|
||||||
|
|
||||||
|
export interface GiteaUser {
|
||||||
|
id: number;
|
||||||
|
login: string;
|
||||||
|
full_name?: string;
|
||||||
|
email?: string;
|
||||||
|
avatar_url?: string;
|
||||||
|
}
|
||||||
|
export interface GiteaOrg {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
full_name?: string;
|
||||||
|
}
|
||||||
|
export interface GiteaRepo {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
full_name: string;
|
||||||
|
owner: { login: string };
|
||||||
|
empty: boolean;
|
||||||
|
private: boolean;
|
||||||
|
default_branch: string;
|
||||||
|
clone_url: string;
|
||||||
|
html_url: string;
|
||||||
|
permissions?: { admin: boolean; push: boolean; pull: boolean };
|
||||||
|
}
|
||||||
|
export interface OAuthTokens {
|
||||||
|
access_token: string;
|
||||||
|
refresh_token?: string;
|
||||||
|
expires_in?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GiteaError extends PeppaError {
|
||||||
|
constructor(
|
||||||
|
readonly status: number,
|
||||||
|
message: string,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GiteaClient {
|
||||||
|
constructor(
|
||||||
|
readonly baseUrl: string,
|
||||||
|
private readonly token: string,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||||
|
const res = await fetch(`${this.baseUrl}/api/v1${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Authorization: `token ${this.token}`, "Content-Type": "application/json", Accept: "application/json" },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(15_000),
|
||||||
|
});
|
||||||
|
if (res.status === 204) return undefined as T;
|
||||||
|
const text = await res.text();
|
||||||
|
if (!res.ok) {
|
||||||
|
let msg = text;
|
||||||
|
try {
|
||||||
|
msg = (JSON.parse(text) as { message?: string }).message ?? text;
|
||||||
|
} catch {}
|
||||||
|
throw new GiteaError(res.status, `Gitea ${method} ${path}: ${res.status} ${msg}`.slice(0, 400));
|
||||||
|
}
|
||||||
|
return (text ? JSON.parse(text) : undefined) as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
me() {
|
||||||
|
return this.request<GiteaUser>("GET", "/user");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Orgs where the user may create repositories. */
|
||||||
|
async orgsWithRepoCreate(login: string): Promise<GiteaOrg[]> {
|
||||||
|
const orgs = await this.request<GiteaOrg[]>("GET", "/user/orgs?limit=50");
|
||||||
|
const out: GiteaOrg[] = [];
|
||||||
|
for (const o of orgs) {
|
||||||
|
const p = await this.request<{ can_create_repository: boolean }>("GET", `/users/${encodeURIComponent(login)}/orgs/${encodeURIComponent(o.username)}/permissions`).catch(() => null);
|
||||||
|
if (p?.can_create_repository) out.push(o);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getRepo(owner: string, name: string): Promise<GiteaRepo | null> {
|
||||||
|
try {
|
||||||
|
return await this.request<GiteaRepo>("GET", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`);
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof GiteaError && e.status === 404) return null;
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Creates a private repo; `asUser` = in the token owner's own namespace. */
|
||||||
|
createRepo(owner: string, asUser: boolean, name: string, description: string) {
|
||||||
|
const body = { name, description, private: true, default_branch: "main", auto_init: false };
|
||||||
|
return this.request<GiteaRepo>("POST", asUser ? "/user/repos" : `/orgs/${encodeURIComponent(owner)}/repos`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
addCollaborator(owner: string, repo: string, login: string, permission: "read" | "write" | "admin") {
|
||||||
|
return this.request<void>("PUT", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators/${encodeURIComponent(login)}`, { permission });
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteRepo(owner: string, repo: string) {
|
||||||
|
return this.request<void>("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function oauthToken(baseUrl: string, body: Record<string, string>): Promise<OAuthTokens> {
|
||||||
|
const res = await fetch(`${baseUrl}/login/oauth/access_token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(15_000),
|
||||||
|
});
|
||||||
|
const data = (await res.json().catch(() => ({}))) as OAuthTokens & { error?: string; error_description?: string };
|
||||||
|
if (!res.ok || !data.access_token) throw new GiteaError(res.status, `OAuth: ${data.error_description ?? data.error ?? res.status}`);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function oauthAuthorizeUrl(baseUrl: string, clientId: string, redirectUri: string, state: string): string {
|
||||||
|
const q = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, response_type: "code", state });
|
||||||
|
return `${baseUrl}/login/oauth/authorize?${q}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function exchangeOAuthCode(baseUrl: string, clientId: string, clientSecret: string, code: string, redirectUri: string) {
|
||||||
|
return oauthToken(baseUrl, { client_id: clientId, client_secret: clientSecret, code, grant_type: "authorization_code", redirect_uri: redirectUri });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function refreshOAuthToken(baseUrl: string, clientId: string, clientSecret: string, refreshToken: string) {
|
||||||
|
return oauthToken(baseUrl, { client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, grant_type: "refresh_token" });
|
||||||
|
}
|
||||||
@ -7,3 +7,6 @@ export * from "./sessions.ts";
|
|||||||
export * from "./rules.ts";
|
export * from "./rules.ts";
|
||||||
export * from "./settings.ts";
|
export * from "./settings.ts";
|
||||||
export * from "./telegram.ts";
|
export * from "./telegram.ts";
|
||||||
|
export * from "./crypto.ts";
|
||||||
|
export * from "./gitea.ts";
|
||||||
|
export * from "./users.ts";
|
||||||
|
|||||||
@ -13,6 +13,7 @@ export interface NewProject {
|
|||||||
giteaOwner: string;
|
giteaOwner: string;
|
||||||
giteaRepo?: string;
|
giteaRepo?: string;
|
||||||
workspacePath: string;
|
workspacePath: string;
|
||||||
|
ownerId?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createProject(db: Db, p: NewProject): Promise<Project> {
|
export async function createProject(db: Db, p: NewProject): Promise<Project> {
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||||
import { dirname, join, resolve } from "node:path";
|
import { dirname, join, resolve } from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { loadEnv, peppaHome } from "@peppa/shared";
|
import { loadEnv, peppaHome, peppaRoot } from "@peppa/shared";
|
||||||
|
|
||||||
const CACHE = join(peppaHome(), "rules.md");
|
const CACHE = join(peppaHome(), "rules.md");
|
||||||
const LOCAL = resolve(dirname(fileURLToPath(import.meta.url)), "../../../template/RULES.md");
|
const LOCAL = () => join(peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../..")), "template/RULES.md");
|
||||||
|
|
||||||
export interface SharedRules {
|
export interface SharedRules {
|
||||||
text: string;
|
text: string;
|
||||||
@ -28,6 +28,6 @@ export async function loadSharedRules(env = loadEnv()): Promise<SharedRules> {
|
|||||||
return { text, source: "gitea" };
|
return { text, source: "gitea" };
|
||||||
} catch {
|
} catch {
|
||||||
if (existsSync(CACHE)) return { text: readFileSync(CACHE, "utf8"), source: "cache" };
|
if (existsSync(CACHE)) return { text: readFileSync(CACHE, "utf8"), source: "cache" };
|
||||||
return { text: readFileSync(LOCAL, "utf8"), source: "local" };
|
return { text: readFileSync(LOCAL(), "utf8"), source: "local" };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
109
packages/core/src/users.ts
Normal file
109
packages/core/src/users.ts
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
import { projects, users, type Db } from "@peppa/db";
|
||||||
|
import { loadEnv } from "@peppa/shared";
|
||||||
|
import { and, asc, eq } from "drizzle-orm";
|
||||||
|
import { decrypt, encrypt, hashToken } from "./crypto.ts";
|
||||||
|
import { randomBytes } from "node:crypto";
|
||||||
|
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||||
|
import { PeppaError } from "./errors.ts";
|
||||||
|
import { GiteaClient, refreshOAuthToken, type GiteaUser, type OAuthTokens } from "./gitea.ts";
|
||||||
|
import type { Project } from "./projects.ts";
|
||||||
|
|
||||||
|
export type User = typeof users.$inferSelect;
|
||||||
|
|
||||||
|
/** Creates or refreshes the Peppa user for a Gitea account after OAuth login. */
|
||||||
|
export async function upsertUserFromGitea(db: Db, g: GiteaUser, tokens: OAuthTokens): Promise<User> {
|
||||||
|
const values = {
|
||||||
|
giteaId: g.id,
|
||||||
|
login: g.login,
|
||||||
|
name: g.full_name || null,
|
||||||
|
email: g.email || null,
|
||||||
|
avatarUrl: g.avatar_url || null,
|
||||||
|
...tokenColumns(tokens),
|
||||||
|
lastLoginAt: new Date(),
|
||||||
|
};
|
||||||
|
const [row] = await db
|
||||||
|
.insert(users)
|
||||||
|
.values(values)
|
||||||
|
.onConflictDoUpdate({ target: users.giteaId, set: values })
|
||||||
|
.returning();
|
||||||
|
return row!;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenColumns(t: OAuthTokens) {
|
||||||
|
return {
|
||||||
|
accessTokenEnc: encrypt(t.access_token),
|
||||||
|
refreshTokenEnc: t.refresh_token ? encrypt(t.refresh_token) : null,
|
||||||
|
tokenExpiresAt: t.expires_in ? new Date(Date.now() + t.expires_in * 1000) : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUser(db: Db, id: number): Promise<User | null> {
|
||||||
|
const [row] = await db.select().from(users).where(eq(users.id, id));
|
||||||
|
return row ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserByLogin(db: Db, login: string): Promise<User | null> {
|
||||||
|
const [row] = await db.select().from(users).where(eq(users.login, login));
|
||||||
|
return row ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Gitea client acting as the user; refreshes the OAuth token when it has expired. */
|
||||||
|
export async function giteaForUser(db: Db, user: User): Promise<GiteaClient> {
|
||||||
|
const env = loadEnv();
|
||||||
|
if (!user.accessTokenEnc) throw new PeppaError("Нет токена Gitea — войдите заново");
|
||||||
|
let token = decrypt(user.accessTokenEnc);
|
||||||
|
if (user.tokenExpiresAt && user.tokenExpiresAt.getTime() < Date.now() + 60_000) {
|
||||||
|
if (!user.refreshTokenEnc || !env.GITEA_OAUTH_CLIENT_ID || !env.GITEA_OAUTH_CLIENT_SECRET) {
|
||||||
|
throw new PeppaError("Сессия Gitea истекла — войдите заново");
|
||||||
|
}
|
||||||
|
const t = await refreshOAuthToken(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, env.GITEA_OAUTH_CLIENT_SECRET, decrypt(user.refreshTokenEnc)).catch(() => {
|
||||||
|
throw new PeppaError("Сессия Gitea истекла — войдите заново");
|
||||||
|
});
|
||||||
|
await db.update(users).set(tokenColumns(t)).where(eq(users.id, user.id));
|
||||||
|
token = t.access_token;
|
||||||
|
}
|
||||||
|
return new GiteaClient(env.GITEA_URL, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Gitea client acting as peppa-bot. */
|
||||||
|
export function giteaForBot(): GiteaClient {
|
||||||
|
const env = loadEnv();
|
||||||
|
if (!env.GITEA_TOKEN) throw new PeppaError("GITEA_TOKEN is not set");
|
||||||
|
return new GiteaClient(env.GITEA_URL, env.GITEA_TOKEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listUserProjects(db: Db, userId: number): Promise<Project[]> {
|
||||||
|
return db.select().from(projects).where(eq(projects.ownerId, userId)).orderBy(asc(projects.key));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The project if `userId` owns it; otherwise "not found" (no existence leak). */
|
||||||
|
export async function projectForUser(db: Db, userId: number, projectId: number): Promise<Project> {
|
||||||
|
const [row] = await db
|
||||||
|
.select()
|
||||||
|
.from(projects)
|
||||||
|
.where(and(eq(projects.id, projectId), eq(projects.ownerId, userId)));
|
||||||
|
if (!row) throw new PeppaError("Не найдено");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setProjectOwner(db: Db, projectId: number, userId: number | null): Promise<void> {
|
||||||
|
await db.update(projects).set({ ownerId: userId }).where(eq(projects.id, projectId));
|
||||||
|
}
|
||||||
|
|
||||||
|
const LOGIN_LINK_TTL_MS = 10 * 60_000;
|
||||||
|
|
||||||
|
/** One-time admin login link code (local CLI only); valid 10 minutes. */
|
||||||
|
export async function createLoginLink(db: Db, userId: number): Promise<string> {
|
||||||
|
const code = randomBytes(24).toString("base64url");
|
||||||
|
await setSetting(db, `web.login:${hashToken(code)}`, { userId, expiresAt: Date.now() + LOGIN_LINK_TTL_MS });
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Consumes a login link code: returns the user id once, then the code is gone. */
|
||||||
|
export async function consumeLoginLink(db: Db, code: string): Promise<number | null> {
|
||||||
|
const key = `web.login:${hashToken(code)}`;
|
||||||
|
const saved = await getSetting<{ userId: number; expiresAt: number }>(db, key);
|
||||||
|
if (!saved) return null;
|
||||||
|
await deleteSetting(db, key);
|
||||||
|
return Date.now() < saved.expiresAt ? saved.userId : null;
|
||||||
|
}
|
||||||
18
packages/db/migrations/0004_loving_wasp.sql
Normal file
18
packages/db/migrations/0004_loving_wasp.sql
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
CREATE TABLE "users" (
|
||||||
|
"id" serial PRIMARY KEY NOT NULL,
|
||||||
|
"gitea_id" integer NOT NULL,
|
||||||
|
"login" text NOT NULL,
|
||||||
|
"name" text,
|
||||||
|
"email" text,
|
||||||
|
"avatar_url" text,
|
||||||
|
"access_token_enc" text,
|
||||||
|
"refresh_token_enc" text,
|
||||||
|
"token_expires_at" timestamp with time zone,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"last_login_at" timestamp with time zone,
|
||||||
|
CONSTRAINT "users_gitea_id_unique" UNIQUE("gitea_id"),
|
||||||
|
CONSTRAINT "users_login_unique" UNIQUE("login")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "projects" ADD COLUMN "owner_id" integer;--> statement-breakpoint
|
||||||
|
ALTER TABLE "projects" ADD CONSTRAINT "projects_owner_id_users_id_fk" FOREIGN KEY ("owner_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
|
||||||
1003
packages/db/migrations/meta/0004_snapshot.json
Normal file
1003
packages/db/migrations/meta/0004_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -29,6 +29,13 @@
|
|||||||
"when": 1794496377868,
|
"when": 1794496377868,
|
||||||
"tag": "0003_material_wild_child",
|
"tag": "0003_material_wild_child",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 4,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1794498071152,
|
||||||
|
"tag": "0004_loving_wasp",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@ -5,6 +5,22 @@ const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull(
|
|||||||
const updatedAt = () =>
|
const updatedAt = () =>
|
||||||
timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date());
|
timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date());
|
||||||
|
|
||||||
|
/** People who log into the web, one per Gitea account. */
|
||||||
|
export const users = pgTable("users", {
|
||||||
|
id: serial("id").primaryKey(),
|
||||||
|
giteaId: integer("gitea_id").notNull().unique(),
|
||||||
|
login: text("login").notNull().unique(),
|
||||||
|
name: text("name"),
|
||||||
|
email: text("email"),
|
||||||
|
avatarUrl: text("avatar_url"),
|
||||||
|
// OAuth tokens, AES-256-GCM encrypted with PEPPA_SECRET (core/crypto.ts).
|
||||||
|
accessTokenEnc: text("access_token_enc"),
|
||||||
|
refreshTokenEnc: text("refresh_token_enc"),
|
||||||
|
tokenExpiresAt: timestamp("token_expires_at", { withTimezone: true }),
|
||||||
|
createdAt: createdAt(),
|
||||||
|
lastLoginAt: timestamp("last_login_at", { withTimezone: true }),
|
||||||
|
});
|
||||||
|
|
||||||
export const projects = pgTable("projects", {
|
export const projects = pgTable("projects", {
|
||||||
id: serial("id").primaryKey(),
|
id: serial("id").primaryKey(),
|
||||||
slug: text("slug").notNull().unique(),
|
slug: text("slug").notNull().unique(),
|
||||||
@ -16,6 +32,8 @@ export const projects = pgTable("projects", {
|
|||||||
giteaRepo: text("gitea_repo").notNull(),
|
giteaRepo: text("gitea_repo").notNull(),
|
||||||
defaultBranch: text("default_branch").notNull().default("main"),
|
defaultBranch: text("default_branch").notNull().default("main"),
|
||||||
workspacePath: text("workspace_path").notNull(),
|
workspacePath: text("workspace_path").notNull(),
|
||||||
|
// Null for projects created by the bot/CLI; only the owner sees a project in the web.
|
||||||
|
ownerId: integer("owner_id").references(() => users.id, { onDelete: "set null" }),
|
||||||
// Next task number to hand out; bumped atomically on task creation.
|
// Next task number to hand out; bumped atomically on task creation.
|
||||||
nextTaskNumber: integer("next_task_number").notNull().default(1),
|
nextTaskNumber: integer("next_task_number").notNull().default(1),
|
||||||
createdAt: createdAt(),
|
createdAt: createdAt(),
|
||||||
|
|||||||
@ -4,3 +4,4 @@ export * as tmux from "./tmux.ts";
|
|||||||
export * from "./watchdog.ts";
|
export * from "./watchdog.ts";
|
||||||
export * from "./run-settings.ts";
|
export * from "./run-settings.ts";
|
||||||
export * from "./providers.ts";
|
export * from "./providers.ts";
|
||||||
|
export * from "./provision.ts";
|
||||||
|
|||||||
@ -1,14 +1,16 @@
|
|||||||
import { dirname, resolve } from "node:path";
|
import { dirname, resolve } from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import type { Session } from "@peppa/core";
|
import type { Session } from "@peppa/core";
|
||||||
|
import { peppaRoot } from "@peppa/shared";
|
||||||
import { writeRunRules, writeRunSettings } from "./run-settings.ts";
|
import { writeRunRules, writeRunSettings } from "./run-settings.ts";
|
||||||
|
|
||||||
export type Provider = Session["provider"];
|
export type Provider = Session["provider"];
|
||||||
export const PROVIDERS: Provider[] = ["claude", "codex"];
|
export const PROVIDERS: Provider[] = ["claude", "codex"];
|
||||||
|
|
||||||
const BIN = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
|
// PEPPA_ROOT first: inside a Next.js build import.meta.url points into .next/.
|
||||||
const HOOK_BIN = `${BIN}/packages/runner/bin/peppa-hook`;
|
const ROOT = () => peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../.."));
|
||||||
const MCP_BIN = `${BIN}/packages/mcp/bin/peppa-mcp`;
|
const HOOK_BIN = () => `${ROOT()}/packages/runner/bin/peppa-hook`;
|
||||||
|
const MCP_BIN = () => `${ROOT()}/packages/mcp/bin/peppa-mcp`;
|
||||||
|
|
||||||
export interface LaunchContext {
|
export interface LaunchContext {
|
||||||
sessionId: number;
|
sessionId: number;
|
||||||
@ -57,11 +59,11 @@ function codexCommand(c: LaunchContext): string[] {
|
|||||||
...(c.permissionMode ?? process.env.PEPPA_CODEX_MODE ?? "--full-auto").split(" ").filter(Boolean),
|
...(c.permissionMode ?? process.env.PEPPA_CODEX_MODE ?? "--full-auto").split(" ").filter(Boolean),
|
||||||
...(c.model ? ["--model", c.model] : []),
|
...(c.model ? ["--model", c.model] : []),
|
||||||
"-c",
|
"-c",
|
||||||
`notify=${toml([HOOK_BIN, "codex-notify"])}`,
|
`notify=${toml([HOOK_BIN(), "codex-notify"])}`,
|
||||||
"-c",
|
"-c",
|
||||||
`developer_instructions=${toml(c.rules)}`,
|
`developer_instructions=${toml(c.rules)}`,
|
||||||
"-c",
|
"-c",
|
||||||
`mcp_servers.peppa.command=${toml(MCP_BIN)}`,
|
`mcp_servers.peppa.command=${toml(MCP_BIN())}`,
|
||||||
...(c.resume ? ["resume", c.resume] : []),
|
...(c.resume ? ["resume", c.resume] : []),
|
||||||
"--",
|
"--",
|
||||||
c.prompt,
|
c.prompt,
|
||||||
|
|||||||
143
packages/runner/src/provision.ts
Normal file
143
packages/runner/src/provision.ts
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
// Creates or connects a project: Gitea repo with peppa-bot as collaborator, files from the
|
||||||
|
// shared template, OpenSpec, a working copy for agent sessions, and the Peppa record.
|
||||||
|
// Used by the web (acting as the logged-in user) and the CLI (acting as peppa-bot).
|
||||||
|
import { execFile } from "node:child_process";
|
||||||
|
import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { promisify } from "node:util";
|
||||||
|
import { createProject, PeppaError, type GiteaClient, type Project } from "@peppa/core";
|
||||||
|
import { projects, type Db } from "@peppa/db";
|
||||||
|
import { loadEnv, peppaRoot } from "@peppa/shared";
|
||||||
|
import { eq, or } from "drizzle-orm";
|
||||||
|
|
||||||
|
const run = promisify(execFile);
|
||||||
|
|
||||||
|
export interface ProvisionOptions {
|
||||||
|
/** Acts in Gitea: the user's OAuth client, or the bot's. */
|
||||||
|
gitea: GiteaClient;
|
||||||
|
/** Namespace for the repo: the actor's login or an org. */
|
||||||
|
owner: string;
|
||||||
|
ownerIsUser: boolean;
|
||||||
|
slug: string;
|
||||||
|
key: string;
|
||||||
|
name: string;
|
||||||
|
/** Connect an existing repo `owner/slug` instead of creating one. */
|
||||||
|
existing?: boolean;
|
||||||
|
/** Peppa user who owns the project (null for CLI/bot projects). */
|
||||||
|
ownerId?: number | null;
|
||||||
|
/** Override for tests; defaults to the template repo in Gitea. */
|
||||||
|
templateUrl?: string;
|
||||||
|
log?: (step: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Template files that stay in the template repo (RULES.md is loaded live by the runner).
|
||||||
|
const TEMPLATE_SKIP = new Set([".git", "RULES.md", "README.md"]);
|
||||||
|
|
||||||
|
export async function provisionProject(db: Db, o: ProvisionOptions): Promise<Project> {
|
||||||
|
const env = loadEnv();
|
||||||
|
const log = o.log ?? (() => {});
|
||||||
|
const key = o.key.toUpperCase();
|
||||||
|
const botLogin = process.env.GITEA_BOT_USER ?? "peppa-bot";
|
||||||
|
if (!/^[a-z0-9][a-z0-9-]*$/.test(o.slug)) throw new PeppaError(`Slug "${o.slug}": только a–z, 0–9 и дефис`);
|
||||||
|
if (!/^[A-Z][A-Z0-9]{1,9}$/.test(key)) throw new PeppaError(`Ключ "${o.key}": 2–10 символов A–Z/0–9, начинается с буквы`);
|
||||||
|
const [taken] = await db.select().from(projects).where(or(eq(projects.slug, o.slug), eq(projects.key, key)));
|
||||||
|
if (taken) throw new PeppaError(taken.slug === o.slug ? `Slug "${o.slug}" уже занят` : `Ключ "${key}" уже занят`);
|
||||||
|
const dest = join(env.PEPPA_WORKSPACES, o.slug);
|
||||||
|
if (existsSync(dest)) throw new PeppaError(`Рабочая копия ${dest} уже существует`);
|
||||||
|
|
||||||
|
// 1. Repository
|
||||||
|
let repo = await o.gitea.getRepo(o.owner, o.slug);
|
||||||
|
if (o.existing) {
|
||||||
|
if (!repo) throw new PeppaError(`Репозиторий ${o.owner}/${o.slug} не найден`);
|
||||||
|
if (!repo.permissions?.admin) throw new PeppaError(`Нет прав администратора на ${o.owner}/${o.slug}`);
|
||||||
|
} else {
|
||||||
|
if (repo) throw new PeppaError(`Репозиторий ${o.owner}/${o.slug} уже существует — подключите его как существующий`);
|
||||||
|
log("create repo");
|
||||||
|
repo = await o.gitea.createRepo(o.owner, o.ownerIsUser, o.slug, o.name);
|
||||||
|
}
|
||||||
|
if (repo.owner.login !== botLogin) {
|
||||||
|
log("add peppa-bot");
|
||||||
|
await o.gitea.addCollaborator(repo.owner.login, repo.name, botLogin, "write");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 2. Working copy (git as peppa-bot)
|
||||||
|
log("clone");
|
||||||
|
mkdirSync(env.PEPPA_WORKSPACES, { recursive: true });
|
||||||
|
await git(env.PEPPA_WORKSPACES, "clone", "-q", repo.clone_url, dest);
|
||||||
|
const branch = repo.empty ? "main" : repo.default_branch || "main";
|
||||||
|
if (repo.empty) await git(dest, "symbolic-ref", "HEAD", `refs/heads/${branch}`);
|
||||||
|
await git(dest, "config", "credential.helper", "");
|
||||||
|
await git(dest, "config", "--add", "credential.helper", credentialHelper());
|
||||||
|
await git(dest, "config", "user.name", "Peppa");
|
||||||
|
await git(dest, "config", "user.email", `${botLogin}@telecom.quest`);
|
||||||
|
|
||||||
|
// 3. Template files that are missing (never overwrite the project's own)
|
||||||
|
log("template");
|
||||||
|
const tpl = mkdtempSync(join(tmpdir(), "peppa-tpl-"));
|
||||||
|
try {
|
||||||
|
await git(tmpdir(), "clone", "-q", "--depth", "1", o.templateUrl ?? `${env.GITEA_URL}/${env.GITEA_TEMPLATE_REPO}.git`, tpl);
|
||||||
|
for (const entry of readdirSync(tpl)) {
|
||||||
|
if (TEMPLATE_SKIP.has(entry) || existsSync(join(dest, entry))) continue;
|
||||||
|
cpSync(join(tpl, entry), join(dest, entry), { recursive: true });
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
rmSync(tpl, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
if (!existsSync(join(dest, "README.md"))) {
|
||||||
|
writeFileSync(join(dest, "README.md"), `# ${o.name}\n\nПроект Пеппы. Ключ задач: \`${key}\`. Правила — в [AGENTS.md](AGENTS.md).\n`);
|
||||||
|
}
|
||||||
|
mkdirSync(join(dest, ".peppa"), { recursive: true });
|
||||||
|
if (!existsSync(join(dest, ".peppa/project.json"))) {
|
||||||
|
writeFileSync(join(dest, ".peppa/project.json"), `${JSON.stringify({ slug: o.slug, key, name: o.name, peppaUrl: env.PEPPA_WEB_URL })}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. OpenSpec — the template ships openspec/config.yaml, so "set up" means changes/
|
||||||
|
// exists (init also installs the agent skills); a repo's own config is kept by init.
|
||||||
|
if (!existsSync(join(dest, "openspec", "changes"))) {
|
||||||
|
log("openspec init");
|
||||||
|
await run(process.env.PEPPA_OPENSPEC_BIN ?? "openspec", ["init", "--tools", "claude,agents", "--no-animation", "."], { cwd: dest });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Commit + push
|
||||||
|
await git(dest, "add", "-A");
|
||||||
|
const { stdout: staged } = await git(dest, "diff", "--cached", "--name-only");
|
||||||
|
if (staged.trim()) {
|
||||||
|
log("push");
|
||||||
|
await git(dest, "commit", "-qm", repo.empty ? `Bootstrap ${o.name} from Peppa template` : `Connect ${o.name} to Peppa`);
|
||||||
|
await git(dest, "push", "-q", "-u", "origin", `HEAD:${branch}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Peppa record — last, so a failure above leaves nothing in Peppa
|
||||||
|
return await createProject(db, {
|
||||||
|
slug: o.slug,
|
||||||
|
key,
|
||||||
|
name: o.name,
|
||||||
|
giteaOwner: repo.owner.login,
|
||||||
|
giteaRepo: repo.name,
|
||||||
|
workspacePath: dest,
|
||||||
|
ownerId: o.ownerId ?? null,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
rmSync(dest, { recursive: true, force: true });
|
||||||
|
if (e instanceof PeppaError) throw e;
|
||||||
|
const err = e as { stderr?: string; message: string };
|
||||||
|
throw new PeppaError(
|
||||||
|
`Не удалось подготовить проект: ${(err.stderr || err.message).trim().slice(0, 300)}${o.existing ? "" : ` (репозиторий ${repo.full_name} уже создан — можно подключить его как существующий)`}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function credentialHelper(): string {
|
||||||
|
return `!${peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../.."))}/packages/cli/bin/git-credential-peppa`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function git(cwd: string, ...args: string[]) {
|
||||||
|
// The peppa helper answers for the Gitea host with the bot token; nothing else is consulted.
|
||||||
|
return run("git", ["-c", "credential.helper=", "-c", `credential.helper=${credentialHelper()}`, ...args], {
|
||||||
|
cwd,
|
||||||
|
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,9 +1,9 @@
|
|||||||
import { mkdirSync, writeFileSync } from "node:fs";
|
import { mkdirSync, writeFileSync } from "node:fs";
|
||||||
import { peppaHome } from "@peppa/shared";
|
import { peppaHome, peppaRoot } from "@peppa/shared";
|
||||||
import { dirname, join, resolve } from "node:path";
|
import { dirname, join, resolve } from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
const HOOK_BIN = resolve(dirname(fileURLToPath(import.meta.url)), "../bin/peppa-hook");
|
const hookBin = () => `${peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../.."))}/packages/runner/bin/peppa-hook`;
|
||||||
/** Blocking hooks wait for the PM this long before falling back to the terminal. */
|
/** Blocking hooks wait for the PM this long before falling back to the terminal. */
|
||||||
export const HOOK_WAIT_SEC = Number(process.env.PEPPA_HOOK_WAIT_SEC ?? 540);
|
export const HOOK_WAIT_SEC = Number(process.env.PEPPA_HOOK_WAIT_SEC ?? 540);
|
||||||
|
|
||||||
@ -28,7 +28,7 @@ export function writeRunRules(sessionId: number, generation: number, text: strin
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function writeRunSettings(sessionId: number, generation: number): string {
|
export function writeRunSettings(sessionId: number, generation: number): string {
|
||||||
const hook = (event: string, timeout = 30) => ({ type: "command", command: `${HOOK_BIN} ${event}`, timeout });
|
const hook = (event: string, timeout = 30) => ({ type: "command", command: `${hookBin()} ${event}`, timeout });
|
||||||
const settings = {
|
const settings = {
|
||||||
hooks: {
|
hooks: {
|
||||||
SessionStart: [{ hooks: [hook("session-start")] }],
|
SessionStart: [{ hooks: [hook("session-start")] }],
|
||||||
|
|||||||
@ -10,6 +10,9 @@ const schema = z.object({
|
|||||||
TELEGRAM_BOT_TOKEN: z.string().optional(),
|
TELEGRAM_BOT_TOKEN: z.string().optional(),
|
||||||
TELEGRAM_PM_CHAT_ID: z.string().optional(),
|
TELEGRAM_PM_CHAT_ID: z.string().optional(),
|
||||||
PEPPA_WEB_URL: z.string().default("http://localhost:3100"),
|
PEPPA_WEB_URL: z.string().default("http://localhost:3100"),
|
||||||
|
PEPPA_SECRET: z.string().optional(),
|
||||||
|
GITEA_OAUTH_CLIENT_ID: z.string().optional(),
|
||||||
|
GITEA_OAUTH_CLIENT_SECRET: z.string().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type Env = z.infer<typeof schema>;
|
export type Env = z.infer<typeof schema>;
|
||||||
@ -20,6 +23,13 @@ export function loadEnv(source: NodeJS.ProcessEnv = process.env): Env {
|
|||||||
return env;
|
return env;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The Peppa checkout; bins, hooks and the template are resolved from it. */
|
||||||
|
export function peppaRoot(fallback?: string): string {
|
||||||
|
if (process.env.PEPPA_ROOT) return process.env.PEPPA_ROOT;
|
||||||
|
if (fallback) return fallback;
|
||||||
|
throw new Error("PEPPA_ROOT is not set");
|
||||||
|
}
|
||||||
|
|
||||||
/** Peppa's local state dir (logs, run files, caches). Tests point it elsewhere. */
|
/** Peppa's local state dir (logs, run files, caches). Tests point it elsewhere. */
|
||||||
export function peppaHome(): string {
|
export function peppaHome(): string {
|
||||||
return process.env.PEPPA_HOME ?? `${homedir()}/.peppa`;
|
return process.env.PEPPA_HOME ?? `${homedir()}/.peppa`;
|
||||||
|
|||||||
146
packages/testkit/src/mock-gitea.ts
Normal file
146
packages/testkit/src/mock-gitea.ts
Normal file
@ -0,0 +1,146 @@
|
|||||||
|
// Mock Gitea for tests: the API endpoints Peppa uses plus OAuth token exchange. Repos are
|
||||||
|
// local bare git repositories, so clone/push against `clone_url` really works.
|
||||||
|
import { execFileSync } from "node:child_process";
|
||||||
|
import { mkdirSync } from "node:fs";
|
||||||
|
import { createServer, type Server } from "node:http";
|
||||||
|
import type { AddressInfo } from "node:net";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
interface MockRepo {
|
||||||
|
id: number;
|
||||||
|
owner: string;
|
||||||
|
name: string;
|
||||||
|
path: string;
|
||||||
|
collaborators: Record<string, string>;
|
||||||
|
admins: Set<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MockGiteaUser {
|
||||||
|
id: number;
|
||||||
|
login: string;
|
||||||
|
token: string;
|
||||||
|
orgs?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MockGitea {
|
||||||
|
readonly repos = new Map<string, MockRepo>();
|
||||||
|
readonly users = new Map<string, MockGiteaUser>();
|
||||||
|
readonly oauthCodes = new Map<string, string>(); // code → token
|
||||||
|
private seq = 1;
|
||||||
|
private server: Server | null = null;
|
||||||
|
url = "";
|
||||||
|
|
||||||
|
constructor(private readonly dir: string) {
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async start(): Promise<this> {
|
||||||
|
this.server = createServer((req, res) => {
|
||||||
|
let body = "";
|
||||||
|
req.on("data", (c) => (body += c));
|
||||||
|
req.on("end", () => {
|
||||||
|
const r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {});
|
||||||
|
res.writeHead(r.status, { "Content-Type": "application/json" });
|
||||||
|
res.end(r.body === undefined ? "" : JSON.stringify(r.body));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await new Promise<void>((r) => this.server!.listen(0, "127.0.0.1", r));
|
||||||
|
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
return new Promise<void>((r) => this.server?.close(() => r()) ?? r());
|
||||||
|
}
|
||||||
|
|
||||||
|
addUser(u: MockGiteaUser) {
|
||||||
|
this.users.set(u.token, u);
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Creates a bare repo, optionally with an initial commit of `files`. */
|
||||||
|
addRepo(owner: string, name: string, opts: { admins?: string[]; files?: Record<string, string> } = {}): MockRepo {
|
||||||
|
const path = join(this.dir, `${owner}-${name}-${this.seq}.git`);
|
||||||
|
execFileSync("git", ["init", "-q", "--bare", "-b", "main", path]);
|
||||||
|
if (opts.files) {
|
||||||
|
const work = `${path}-work`;
|
||||||
|
execFileSync("git", ["init", "-q", "-b", "main", work]);
|
||||||
|
for (const [f, text] of Object.entries(opts.files)) {
|
||||||
|
mkdirSync(join(work, f, ".."), { recursive: true });
|
||||||
|
execFileSync("bash", ["-c", `cat > ${JSON.stringify(join(work, f))}`], { input: text });
|
||||||
|
}
|
||||||
|
execFileSync("bash", ["-c", `cd ${JSON.stringify(work)} && git add -A && git -c user.name=t -c user.email=t@t commit -qm init && git push -q ${JSON.stringify(path)} main`]);
|
||||||
|
}
|
||||||
|
const repo: MockRepo = { id: this.seq++, owner, name, path, collaborators: {}, admins: new Set(opts.admins ?? [owner]) };
|
||||||
|
this.repos.set(`${owner}/${name}`, repo);
|
||||||
|
return repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Files on the default branch of a repo (empty if no commits). */
|
||||||
|
files(owner: string, name: string): string[] {
|
||||||
|
const r = this.repos.get(`${owner}/${name}`);
|
||||||
|
if (!r || this.isEmpty(r)) return [];
|
||||||
|
return execFileSync("git", ["--git-dir", r.path, "ls-tree", "-r", "--name-only", "main"], { encoding: "utf8" }).trim().split("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
show(owner: string, name: string, file: string): string {
|
||||||
|
const r = this.repos.get(`${owner}/${name}`)!;
|
||||||
|
return execFileSync("git", ["--git-dir", r.path, "show", `main:${file}`], { encoding: "utf8" });
|
||||||
|
}
|
||||||
|
|
||||||
|
private isEmpty(r: MockRepo) {
|
||||||
|
return execFileSync("git", ["--git-dir", r.path, "for-each-ref"], { encoding: "utf8" }).trim() === "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private json(r: MockRepo, as: MockGiteaUser) {
|
||||||
|
return {
|
||||||
|
id: r.id,
|
||||||
|
name: r.name,
|
||||||
|
full_name: `${r.owner}/${r.name}`,
|
||||||
|
owner: { login: r.owner },
|
||||||
|
empty: this.isEmpty(r),
|
||||||
|
private: true,
|
||||||
|
default_branch: "main",
|
||||||
|
clone_url: r.path,
|
||||||
|
html_url: `${this.url}/${r.owner}/${r.name}`,
|
||||||
|
permissions: { admin: r.admins.has(as.login), push: true, pull: true },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private handle(method: string, url: string, auth: string, body: Record<string, unknown>): { status: number; body?: unknown } {
|
||||||
|
const path = url.split("?")[0]!;
|
||||||
|
if (method === "POST" && path === "/login/oauth/access_token") {
|
||||||
|
const token = this.oauthCodes.get(String(body.code));
|
||||||
|
if (!token) return { status: 400, body: { error: "invalid_grant" } };
|
||||||
|
this.oauthCodes.delete(String(body.code));
|
||||||
|
return { status: 200, body: { access_token: token, refresh_token: `r-${token}`, expires_in: 3600 } };
|
||||||
|
}
|
||||||
|
const me = this.users.get(auth.replace(/^token /, ""));
|
||||||
|
if (!me) return { status: 401, body: { message: "unauthorized" } };
|
||||||
|
let m: RegExpMatchArray | null;
|
||||||
|
if (method === "GET" && path === "/api/v1/user") return { status: 200, body: { id: me.id, login: me.login, full_name: me.login, email: `${me.login}@x`, avatar_url: "" } };
|
||||||
|
if (method === "GET" && path === "/api/v1/user/orgs") return { status: 200, body: (me.orgs ?? []).map((o, i) => ({ id: 1000 + i, username: o })) };
|
||||||
|
if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)\/orgs\/([^/]+)\/permissions$/))) {
|
||||||
|
return { status: 200, body: { can_create_repository: (me.orgs ?? []).includes(decodeURIComponent(m[2]!)) } };
|
||||||
|
}
|
||||||
|
if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)$/))) {
|
||||||
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
||||||
|
if (!r) return { status: 404, body: { message: "not found" } };
|
||||||
|
if (method === "DELETE") return this.repos.delete(`${r.owner}/${r.name}`), { status: 204 };
|
||||||
|
return { status: 200, body: this.json(r, me) };
|
||||||
|
}
|
||||||
|
if (method === "POST" && (path === "/api/v1/user/repos" || (m = path.match(/^\/api\/v1\/orgs\/([^/]+)\/repos$/)))) {
|
||||||
|
const owner = path === "/api/v1/user/repos" ? me.login : decodeURIComponent(m![1]!);
|
||||||
|
if (this.repos.has(`${owner}/${body.name}`)) return { status: 409, body: { message: "repository already exists" } };
|
||||||
|
return { status: 201, body: this.json(this.addRepo(owner, String(body.name), { admins: [me.login] }), me) };
|
||||||
|
}
|
||||||
|
if (method === "PUT" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators\/([^/]+)$/))) {
|
||||||
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
||||||
|
if (!r) return { status: 404, body: { message: "not found" } };
|
||||||
|
if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } };
|
||||||
|
r.collaborators[decodeURIComponent(m[3]!)] = String(body.permission);
|
||||||
|
return { status: 204 };
|
||||||
|
}
|
||||||
|
return { status: 404, body: { message: `mock-gitea: ${method} ${path}` } };
|
||||||
|
}
|
||||||
|
}
|
||||||
144
packages/testkit/test/web.test.ts
Normal file
144
packages/testkit/test/web.test.ts
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
// PEP-1: auth primitives, access control and project provisioning (mock-gitea + real git).
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { execFileSync } from "node:child_process";
|
||||||
|
import { existsSync, mkdtempSync, readFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { after, before, describe, test } from "node:test";
|
||||||
|
import { core, db, runner, teardown } from "./helpers.ts";
|
||||||
|
import { MockGitea } from "../src/mock-gitea.ts";
|
||||||
|
|
||||||
|
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||||
|
const TMP = mkdtempSync(join(tmpdir(), "peppa-web-"));
|
||||||
|
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||||
|
process.env.PEPPA_WORKSPACES = join(TMP, "workspaces");
|
||||||
|
|
||||||
|
const gitea = new MockGitea(join(TMP, "gitea"));
|
||||||
|
const ALICE = { id: 11, login: "mock-alice", token: "mock-token-alice", orgs: ["mock-team"] };
|
||||||
|
const BOB = { id: 12, login: "mock-bob", token: "mock-token-bob" };
|
||||||
|
let templateUrl = "";
|
||||||
|
let alice: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||||
|
let bob: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
await gitea.start();
|
||||||
|
process.env.GITEA_URL = gitea.url;
|
||||||
|
gitea.addUser(ALICE);
|
||||||
|
gitea.addUser(BOB);
|
||||||
|
// Template repo from the real template/ dir.
|
||||||
|
const tpl = gitea.addRepo("peppa-bot", "template");
|
||||||
|
execFileSync("bash", ["-c", `cd ${JSON.stringify(join(ROOT, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]);
|
||||||
|
templateUrl = tpl.path;
|
||||||
|
alice = await core.upsertUserFromGitea(db, { id: ALICE.id, login: ALICE.login }, { access_token: ALICE.token, refresh_token: "r", expires_in: 3600 });
|
||||||
|
bob = await core.upsertUserFromGitea(db, { id: BOB.id, login: BOB.login }, { access_token: BOB.token });
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
await gitea.stop();
|
||||||
|
await teardown();
|
||||||
|
});
|
||||||
|
|
||||||
|
const provision = async (over: Partial<Parameters<typeof runner.provisionProject>[1]> & { slug: string; key: string }) =>
|
||||||
|
runner.provisionProject(db, {
|
||||||
|
gitea: await core.giteaForUser(db, alice),
|
||||||
|
owner: ALICE.login,
|
||||||
|
ownerIsUser: true,
|
||||||
|
name: `Mock ${over.key}`,
|
||||||
|
ownerId: alice.id,
|
||||||
|
templateUrl,
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("auth primitives", () => {
|
||||||
|
test("token encryption round-trips and tokens are not stored in clear", async () => {
|
||||||
|
const enc = core.encrypt("secret-token");
|
||||||
|
assert.notEqual(enc, "secret-token");
|
||||||
|
assert.equal(core.decrypt(enc), "secret-token");
|
||||||
|
assert.ok(!alice.accessTokenEnc?.includes(ALICE.token));
|
||||||
|
assert.equal(core.decrypt(alice.accessTokenEnc!), ALICE.token);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("signed session payloads reject tampering", () => {
|
||||||
|
const t = core.sign({ uid: 1, exp: 1 });
|
||||||
|
assert.deepEqual(core.verify(t), { uid: 1, exp: 1 });
|
||||||
|
const [body, sig] = t.split(".");
|
||||||
|
const forged = Buffer.from(JSON.stringify({ uid: 2, exp: 1 })).toString("base64url");
|
||||||
|
assert.equal(core.verify(`${forged}.${sig}`), null);
|
||||||
|
assert.equal(core.verify(`${body}.AAAA`), null);
|
||||||
|
assert.equal(core.verify(undefined), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("admin login link works once and expires", async () => {
|
||||||
|
const code = await core.createLoginLink(db, alice.id);
|
||||||
|
assert.equal(await core.consumeLoginLink(db, code), alice.id);
|
||||||
|
assert.equal(await core.consumeLoginLink(db, code), null, "single use");
|
||||||
|
const old = await core.createLoginLink(db, alice.id);
|
||||||
|
await core.setSetting(db, `web.login:${core.hashToken(old)}`, { userId: alice.id, expiresAt: Date.now() - 1 });
|
||||||
|
assert.equal(await core.consumeLoginLink(db, old), null, "expired");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("OAuth code exchange + Gitea user → Peppa user", async () => {
|
||||||
|
gitea.oauthCodes.set("mock-code", BOB.token);
|
||||||
|
const tokens = await core.exchangeOAuthCode(gitea.url, "id", "secret", "mock-code", "http://x/auth/callback");
|
||||||
|
const me = await new core.GiteaClient(gitea.url, tokens.access_token).me();
|
||||||
|
const u = await core.upsertUserFromGitea(db, me, tokens);
|
||||||
|
assert.equal(u.id, bob.id, "same Gitea account → same Peppa user");
|
||||||
|
await assert.rejects(core.exchangeOAuthCode(gitea.url, "id", "secret", "mock-code", "http://x/auth/callback"), "code is single use");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("project provisioning", () => {
|
||||||
|
test("new repo: template + OpenSpec pushed, peppa-bot collaborator, owned by the user", async () => {
|
||||||
|
const p = await provision({ slug: "mock-demo", key: "MDEMO" });
|
||||||
|
assert.equal(p.ownerId, alice.id);
|
||||||
|
assert.equal(p.giteaOwner, ALICE.login);
|
||||||
|
const files = gitea.files(ALICE.login, "mock-demo");
|
||||||
|
for (const f of ["AGENTS.md", "CLAUDE.md", ".mcp.json", ".peppa/project.json", "openspec/config.yaml", "README.md"]) assert.ok(files.includes(f), `${f} pushed`);
|
||||||
|
assert.ok(!files.includes("RULES.md"), "RULES.md stays in the template repo");
|
||||||
|
assert.ok(files.some((f) => f.startsWith(".agents/skills/openspec-")), "openspec init ran (agent skills)");
|
||||||
|
assert.match(gitea.show(ALICE.login, "mock-demo", "openspec/config.yaml"), /Пеппа/, "template OpenSpec config kept");
|
||||||
|
assert.equal(JSON.parse(gitea.show(ALICE.login, "mock-demo", ".peppa/project.json")).key, "MDEMO");
|
||||||
|
assert.equal(gitea.repos.get(`${ALICE.login}/mock-demo`)!.collaborators["peppa-bot"], "write");
|
||||||
|
assert.match(execFileSync("git", ["-C", p.workspacePath, "config", "--get-all", "credential.helper"], { encoding: "utf8" }), /git-credential-peppa/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("project in an org the user can create repos in", async () => {
|
||||||
|
const p = await provision({ slug: "mock-team-app", key: "MTEAM", owner: "mock-team", ownerIsUser: false });
|
||||||
|
assert.equal(p.giteaOwner, "mock-team");
|
||||||
|
assert.ok(gitea.files("mock-team", "mock-team-app").includes("AGENTS.md"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("conflicts leave nothing behind in Peppa", async () => {
|
||||||
|
await assert.rejects(provision({ slug: "mock-demo", key: "MOTHER" }), /Slug "mock-demo" уже занят/);
|
||||||
|
await assert.rejects(provision({ slug: "mock-other", key: "MDEMO" }), /Ключ "MDEMO" уже занят/);
|
||||||
|
gitea.addRepo(ALICE.login, "mock-taken");
|
||||||
|
await assert.rejects(provision({ slug: "mock-taken", key: "MTAKEN" }), /уже существует/);
|
||||||
|
assert.ok(!existsSync(join(process.env.PEPPA_WORKSPACES!, "mock-taken")));
|
||||||
|
await assert.rejects(core.getProject(db, "MTAKEN"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("existing repo with code: own files kept, Peppa files added", async () => {
|
||||||
|
gitea.addRepo(ALICE.login, "mock-legacy", { files: { "AGENTS.md": "# Свои правила\n", "src/app.ts": "export {};\n" } });
|
||||||
|
const p = await provision({ slug: "mock-legacy", key: "MLEG", existing: true });
|
||||||
|
assert.equal(gitea.show(ALICE.login, "mock-legacy", "AGENTS.md"), "# Свои правила\n", "existing AGENTS.md not overwritten");
|
||||||
|
const files = gitea.files(ALICE.login, "mock-legacy");
|
||||||
|
for (const f of ["src/app.ts", ".peppa/project.json", ".mcp.json", "openspec/config.yaml"]) assert.ok(files.includes(f), f);
|
||||||
|
assert.ok(files.some((f) => f.startsWith(".agents/skills/openspec-")), "openspec init ran");
|
||||||
|
assert.ok(readFileSync(join(p.workspacePath, "src/app.ts"), "utf8"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("existing repo without admin rights is refused", async () => {
|
||||||
|
gitea.addRepo(ALICE.login, "mock-foreign", { admins: ["someone-else"], files: { "x.txt": "x" } });
|
||||||
|
await assert.rejects(provision({ slug: "mock-foreign", key: "MFOR", existing: true }), /Нет прав администратора/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("access control", () => {
|
||||||
|
test("a user only reaches own projects", async () => {
|
||||||
|
const p = await core.getProject(db, "MDEMO");
|
||||||
|
assert.equal((await core.projectForUser(db, alice.id, p.id)).key, "MDEMO");
|
||||||
|
await assert.rejects(core.projectForUser(db, bob.id, p.id), /Не найдено/);
|
||||||
|
assert.deepEqual((await core.listUserProjects(db, bob.id)).map((x) => x.key), []);
|
||||||
|
assert.ok((await core.listUserProjects(db, alice.id)).some((x) => x.key === "MDEMO"));
|
||||||
|
});
|
||||||
|
});
|
||||||
9
pnpm-lock.yaml
generated
9
pnpm-lock.yaml
generated
@ -196,12 +196,21 @@ importers:
|
|||||||
|
|
||||||
apps/web:
|
apps/web:
|
||||||
dependencies:
|
dependencies:
|
||||||
|
'@peppa/core':
|
||||||
|
specifier: workspace:*
|
||||||
|
version: link:../../packages/core
|
||||||
'@peppa/db':
|
'@peppa/db':
|
||||||
specifier: workspace:*
|
specifier: workspace:*
|
||||||
version: link:../../packages/db
|
version: link:../../packages/db
|
||||||
|
'@peppa/runner':
|
||||||
|
specifier: workspace:*
|
||||||
|
version: link:../../packages/runner
|
||||||
'@peppa/shared':
|
'@peppa/shared':
|
||||||
specifier: workspace:*
|
specifier: workspace:*
|
||||||
version: link:../../packages/shared
|
version: link:../../packages/shared
|
||||||
|
drizzle-orm:
|
||||||
|
specifier: 0.45.4
|
||||||
|
version: 0.45.4(postgres@4.1.1)
|
||||||
next:
|
next:
|
||||||
specifier: 16.4.6
|
specifier: 16.4.6
|
||||||
version: 16.4.6(@types/node@26.6.6)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
version: 16.4.6(@types/node@26.6.6)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||||
|
|||||||
@ -1,38 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Usage: scripts/bootstrap-project.sh <slug> <KEY> "<Name>" [owner=peppa-bot]
|
|
||||||
# Creates a Gitea repo, fills it from the Gitea template repo, runs `openspec init`, pushes, and
|
|
||||||
# leaves a working clone in $PEPPA_WORKSPACES/<slug>. The web platform will call the
|
|
||||||
# same steps (stage 5); this script is the manual path until then.
|
|
||||||
set -euo pipefail
|
|
||||||
cd "$(dirname "$0")/.."
|
|
||||||
ROOT="$PWD"
|
|
||||||
[ -f .env ] && set -a && . ./.env && set +a
|
|
||||||
. scripts/gitea-lib.sh
|
|
||||||
SLUG="${1:?slug}"; KEY="$(echo "${2:?KEY}" | tr a-z A-Z)"; NAME="${3:?name}"; OWNER="${4:-$GITEA_BOT_USER}"
|
|
||||||
WS="${PEPPA_WORKSPACES:-$HOME/peppa/workspaces}"; WS="${WS/#\~/$HOME}"
|
|
||||||
DEST="$WS/$SLUG"
|
|
||||||
|
|
||||||
[ -e "$DEST" ] && { echo "already exists: $DEST" >&2; exit 1; }
|
|
||||||
gitea_create_repo "$OWNER" "$SLUG" "$NAME"
|
|
||||||
|
|
||||||
# Start from the shared template in Gitea (RULES.md stays there: sessions load it live).
|
|
||||||
TPL="$(mktemp -d)"; trap 'rm -rf "$TPL"' EXIT
|
|
||||||
git -c credential.helper=peppa clone -q --depth 1 "$GITEA_URL/${GITEA_TEMPLATE_REPO:-peppa-bot/template}.git" "$TPL"
|
|
||||||
rm -rf "$TPL/.git" "$TPL/RULES.md" "$TPL/README.md"
|
|
||||||
mkdir -p "$DEST"
|
|
||||||
cp -R "$TPL/." "$DEST/"
|
|
||||||
cd "$DEST"
|
|
||||||
printf '# %s\n\nПроект Пеппы. Ключ задач: `%s`. Правила — в [AGENTS.md](AGENTS.md).\n' "$NAME" "$KEY" > README.md
|
|
||||||
mkdir -p .peppa
|
|
||||||
cat > .peppa/project.json <<JSON
|
|
||||||
{ "slug": "$SLUG", "key": "$KEY", "name": "$NAME", "peppaUrl": "${PEPPA_WEB_URL:-http://localhost:3100}" }
|
|
||||||
JSON
|
|
||||||
openspec init --tools claude,agents --no-animation . >/dev/null
|
|
||||||
git init -q -b main
|
|
||||||
gitea_git_setup
|
|
||||||
git add -A
|
|
||||||
git commit -qm "Bootstrap $NAME from Peppa template"
|
|
||||||
git remote add origin "$GITEA_URL/$OWNER/$SLUG.git"
|
|
||||||
git push -q -u origin main
|
|
||||||
"$ROOT/packages/cli/bin/peppa" project add "$SLUG" "$KEY" "$NAME" --owner "$OWNER" --path "$DEST"
|
|
||||||
echo "ready: $DEST ($GITEA_URL/$OWNER/$SLUG)"
|
|
||||||
22
scripts/create-oauth-app.sh
Executable file
22
scripts/create-oauth-app.sh
Executable file
@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Creates the Gitea OAuth2 application for web login (owned by peppa-bot) and writes
|
||||||
|
# GITEA_OAUTH_CLIENT_ID / GITEA_OAUTH_CLIENT_SECRET into .env. Idempotent: an existing
|
||||||
|
# "Peppa" app is reused only if .env already has its secret (Gitea never shows it again).
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
PEPPA_ROOT="$PWD"; . scripts/lib/load-env.sh
|
||||||
|
. scripts/gitea-lib.sh
|
||||||
|
REDIRECTS="[\"${PEPPA_WEB_URL%/}/auth/callback\",\"http://localhost:3100/auth/callback\"]"
|
||||||
|
existing=$(gitea_api "$GITEA_URL/api/v1/user/applications/oauth2" | python3 -c 'import json,sys;print(next((str(a["id"]) for a in json.load(sys.stdin) if a["name"]=="Peppa"),""))')
|
||||||
|
if [ -n "$existing" ] && [ -n "${GITEA_OAUTH_CLIENT_SECRET:-}" ]; then echo "OAuth app exists (id $existing), .env has its secret"; exit 0; fi
|
||||||
|
[ -n "$existing" ] && gitea_api -X DELETE "$GITEA_URL/api/v1/user/applications/oauth2/$existing" >/dev/null
|
||||||
|
gitea_api -X POST "$GITEA_URL/api/v1/user/applications/oauth2" \
|
||||||
|
-d "{\"name\":\"Peppa\",\"redirect_uris\":$REDIRECTS,\"confidential_client\":true}" |
|
||||||
|
python3 -c '
|
||||||
|
import json,re,sys
|
||||||
|
d=json.load(sys.stdin); p=".env"; s=open(p).read()
|
||||||
|
for k,v in (("GITEA_OAUTH_CLIENT_ID",d["client_id"]),("GITEA_OAUTH_CLIENT_SECRET",d["client_secret"])):
|
||||||
|
s=re.sub(rf"^{k}=.*\n?","",s,flags=re.M)
|
||||||
|
s=s.rstrip("\n")+f"\n{k}={v}\n"
|
||||||
|
open(p,"w").write(s)
|
||||||
|
print("created OAuth app, client id", d["client_id"])'
|
||||||
Loading…
Reference in New Issue
Block a user