PEP-191: archive change

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-17 12:59:53 +05:00
parent 5db4841fb8
commit 79d75e5234
18 changed files with 399 additions and 1 deletions

View File

@ -73,6 +73,7 @@
- **Свой Telegram-бот (PEP-85)**: `users.telegram_bot_token_enc` (в `encryptedColumns`) + `telegram_bot_username` (миграция 0016). core/telegram.ts: `verifyBotToken`, `setUserBot`/`clearUserBot`, `userBots`; `acceptPairing(…, { botUserId })` — свой бот привязывает только владельца, общий не привязывает того, у кого есть свой; `getOffset`/`claimUpdate` принимают `botUserId` (ключ обновления `userId·2^36 + update_id`). apps/bot: `syncOwnBots` (раз в `userBotsIntervalMs`), `ownPollLoop`, обработка внутри `via.run(bot)`, объект `api` маршрутизирует вызов: бот текущего обновления → бот владельца `chat_id` → общий. Группы и каналы — только общий бот. Веб «Настройки → Telegram»: три шага. Тест `own-bot.test.ts` — два `MockTelegram` (`userApi` в опциях бота)
- **Удаление проекта (PEP-163)**: `projects.deleted_at`/`deleted_by` (миграция 0021). Владелец — «⋯ Настройки проекта → Удалить проект» (`deleteProjectAction` → `deleteProject` в runner/project-trash.ts: `markProjectDeleted` + остановка сессий). Удалённый скрыт: `userProjectIds`, `listProjects(db)` (диспетчеры, intake) его не отдают, `projectForUser` пускает только суперадмина; он видит его в «Проектах других» («удалён, ещё N дн.») и жмёт «Вернуть проект» (`restoreProject`). `projectTrashTick` в вачдоге после `PEPPA_PROJECT_TRASH_DAYS` (7) делает `DELETE` строки (FK каскадные); репозиторий в Gitea и рабочая копия остаются. Платформенный проект не удаляется. Тест `project-trash.test.ts`
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Защита основной ветки (PEP-191)**: `runner/branch-protection.ts` — push и merge в основную ветку только `peppa-bot` (белый список Gitea, без deploy-ключей, одобрений 0; `GiteaClient.protectBranch`, идемпотентно). Ставят `provisionProject`, `transferProject`, `connectCi` (`peppa ci connect`), `branchProtectionTick` (вачдог раз в сутки, `PEPPA_BRANCH_PROTECT=off`); клиенты по очереди — владелец, потом бот (нужен admin). Сбой не ломает проект: суперадмину одно сообщение (`branch.protect.failed:<id>`). CLI `peppa project protect <KEY|--all>`. Запись в main не от бота — отказ 403 (`saveAgentsMd` откатывается на бота). Мок: `MockGitea.protections`, `protectionDown`. Тест `branch-protection.test.ts`
- **Перенос репозитория проекта (PEP-4)**: `peppa project transfer <KEY> <owner>` (админ, от имени peppa-bot; `transferProject` в runner/transfer.ts): `POST /repos/{o}/{r}/transfer` → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` (репо вне пространства бота получает свой раннер `repo-<owner>--<repo>`, секрет, вебхук) → событие `repo_transferred` (чат проекта). Повторный запуск доводит до конца (репозиторий уже на месте — чинит только сторону Пеппы); цель — организация, где бот может создавать репозитории, иначе Gitea оставляет перенос ожидающим и команда падает. Откат — та же команда обратно
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility <KEY|--all> public|private` — админ, без проверки владельца
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`

View File

@ -0,0 +1,7 @@
## Решения
- Модуль `runner/branch-protection.ts`: `ensureBranchProtection` (пробует клиентов по очереди: владелец → peppa-bot; нужен admin), `branchProtectionState`, `branchProtectionTick` (раз в сутки, `PEPPA_BRANCH_PROTECT=off` выключает).
- Сбой: `alertAdmins` один раз на «период поломки» (`settings` `branch.protect.failed:<id>`, снимается при успехе); `platformDelay` не берём — у него причины привязаны к задачам.
- Белый список — `GITEA_BOT_USER` (как в `ci.ts`), по умолчанию `peppa-bot`.
- `saveAgentsMd` уже перебирает клиентов: владелец получает 403 на защищённой main, запись идёт от peppa-bot (проверено тестом).
- Теги `deploy-*` не защищаем; `scripts/push-template.sh` и `git push` агентов идут от бота (credential helper).
- Мок не может запретить настоящий `git push` по пути; отказ моделируется на contents API и merge.

View File

@ -0,0 +1,9 @@
## Why
Код в основную ветку проекта должен попадать только через Peppa FACTORY (агенты, «Принять», автомерж) и её проверки. Защита main включена вручную в 28 существующих репозиториях; новые проекты её не получали.
## What Changes
- `GiteaClient.getBranchProtection` / `protectBranch` — правило ветки: push и merge только `peppa-bot`, без deploy-ключей, без обязательных одобрений; идемпотентно (POST или PATCH).
- Защита ставится при создании и подключении проекта (`provisionProject`), переносе (`transferProject`), `peppa ci connect`, и сверяется раз в сутки в вачдоге.
- Сбой установки не ломает проект: суперадмину одно сообщение, пока не заработает.
- CLI `peppa project protect <KEY|--all>`.
- `mock-gitea`: branch_protections, отказ push/merge вне белого списка.

View File

@ -0,0 +1,28 @@
## ADDED Requirements
### Requirement: Основная ветка проекта защищена
Основная ветка каждого проекта SHALL быть защищена в Gitea: пишет и мержит только peppa-bot.
#### Scenario: Новый проект
- **GIVEN** пользователь создаёт проект
- **WHEN** создание проекта завершено
- **THEN** у main есть правило с белым списком push и merge «peppa-bot»
#### Scenario: Подключённый репозиторий
- **GIVEN** существующий репозиторий с кодом
- **WHEN** пользователь подключает его как проект
- **THEN** main получает такое же правило
#### Scenario: Другой пользователь
- **GIVEN** main защищена
- **WHEN** владелец пытается записать файл в main или смержить PR
- **THEN** Gitea отвечает отказом, а peppa-bot мержит PR
#### Scenario: Защита не поставилась
- **GIVEN** Gitea не принимает правило
- **WHEN** создаётся проект
- **THEN** проект создан, суперадмин получает одно сообщение, повторные попытки молчат
#### Scenario: Правило изменили руками
- **GIVEN** в белый список добавлен посторонний
- **WHEN** срабатывает суточная проверка вачдога
- **THEN** правило возвращено к белому списку из peppa-bot

View File

@ -0,0 +1,5 @@
- [x] 1. GiteaClient.getBranchProtection / protectBranch
- [x] 2. runner/branch-protection.ts, provision, transfer, ci connect, вачдог
- [x] 3. CLI `peppa project protect`
- [x] 4. mock-gitea: branch_protections, отказ вне белого списка
- [x] 5. Тесты branch-protection.test.ts, словарь и переводы

View File

@ -74,7 +74,7 @@ import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runner
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
import { connectErrorTrackingFromEnv, pauseProject, resumeProject } from "@peppa/runner";
import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtection, pauseProject, resumeProject } from "@peppa/runner";
import { logoutAllUsers, showWelcomeToEveryone } from "@peppa/core";
import { installCrashReporting } from "@peppa/core";
import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
@ -93,6 +93,7 @@ const USAGE = `peppa — Peppa software factory CLI
peppa project visibility <KEY|--all> public|private (repo visibility in Gitea: owner's client, then peppa-bot)
peppa project pause|resume <KEY> (PEP-174: agents stop, nothing is sent; resume continues them)
peppa project transfer <KEY> <owner> (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook)
peppa project protect <KEY|--all> (PEP-191: default branch protected, only peppa-bot writes)
peppa project errors <KEY> (PEP-58/91: connect to Bugsink — <KEY>-web and <KEY>-api, webhook, goal «Стабильность»)
peppa project import-issues <KEY> (PEP-46: open Gitea issues of the repo → backlog stories, linked back)
peppa project list
@ -348,6 +349,24 @@ async function main(): Promise<void> {
if (failed) process.exitCode = 1;
break;
}
case "project protect": {
// PEP-191: puts the default branch under protection (only the bot writes) and shows who may.
const keys = opts.all ? (await listProjects(db)).map((p) => p.key) : args[0] ? [args[0]] : [];
if (!keys.length) throw new PeppaError("usage: peppa project protect <KEY|--all>");
let bad = 0;
for (const key of keys) {
const p = await getProject(db, key);
let st = await branchProtectionState(db, p);
if (!st?.protected) {
await ensureBranchProtection(db, p, { log: (l) => console.log(`… ${l}`) });
st = await branchProtectionState(db, p);
}
if (!st?.protected) bad++;
console.log(`${p.key.padEnd(8)} ${p.giteaOwner}/${p.giteaRepo}@${p.defaultBranch} ${st?.protected ? "защищена" : "НЕ защищена"} push: ${st?.pushUsers.join(",") || "—"} merge: ${st?.mergeUsers.join(",") || "—"}`);
}
if (bad) process.exitCode = 1;
break;
}
case "project transfer": {
const [key, owner] = args;
if (!key || !owner) throw new PeppaError("usage: peppa project transfer <KEY> <owner>");

View File

@ -70,6 +70,16 @@ export interface GiteaIssue {
user?: { login: string };
pull_request?: unknown;
}
export interface GiteaBranchProtection {
rule_name?: string;
branch_name?: string;
enable_push: boolean;
enable_push_whitelist: boolean;
push_whitelist_usernames: string[] | null;
push_whitelist_deploy_keys?: boolean;
enable_merge_whitelist: boolean;
merge_whitelist_usernames: string[] | null;
}
export interface GiteaHook {
id: number;
type: string;
@ -313,6 +323,35 @@ export class GiteaClient {
return this.request<{ commit: { sha: string; html_url: string } }>(o.sha ? "PUT" : "POST", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}`, body);
}
/** PEP-191: the protection rule of `branch`, null when there is none. */
async getBranchProtection(owner: string, repo: string, branch: string): Promise<GiteaBranchProtection | null> {
try {
return await this.request<GiteaBranchProtection>("GET", `${this.repoPath(owner, repo)}/branch_protections/${encodeURIComponent(branch)}`);
} catch (e) {
if (e instanceof GiteaError && e.status === 404) return null;
throw e;
}
}
/**
* PEP-191: only `users` push to and merge into `branch` (deploy keys do not push; no approvals
* required — Peppa merges after green checks). Creates the rule or updates the existing one.
*/
async protectBranch(owner: string, repo: string, branch: string, o: { users: string[] }): Promise<GiteaBranchProtection> {
const body = {
rule_name: branch,
enable_push: true,
enable_push_whitelist: true,
push_whitelist_usernames: o.users,
push_whitelist_deploy_keys: false,
enable_merge_whitelist: true,
merge_whitelist_usernames: o.users,
required_approvals: 0,
};
if (await this.getBranchProtection(owner, repo, branch)) return this.request<GiteaBranchProtection>("PATCH", `${this.repoPath(owner, repo)}/branch_protections/${encodeURIComponent(branch)}`, body);
return this.request<GiteaBranchProtection>("POST", `${this.repoPath(owner, repo)}/branch_protections`, body);
}
setActionsSecret(owner: string, repo: string, name: string, data: string) {
return this.request<void>("PUT", `${this.repoPath(owner, repo)}/actions/secrets/${encodeURIComponent(name)}`, { data });
}

View File

@ -0,0 +1,84 @@
// PEP-191: the default branch of every project is protected in Gitea — only peppa-bot pushes to it
// and merges into it, so code reaches `main` through Peppa (agents, «Принять», auto-merge) and
// through its checks, never around them. Tags (`deploy-*`) are not protected.
import { m } from "@peppa/shared/i18n";
import { alertAdmins, deleteSetting, getSetting, listProjects, setSetting, type GiteaClient, type Project } from "@peppa/core";
import type { Db } from "@peppa/db";
import { repoAdmins } from "./share.ts";
const botLogin = () => process.env.GITEA_BOT_USER ?? "peppa-bot";
const DAY_MS = 24 * 3600_000;
export interface BranchProtectionState {
branch: string;
/** The rule exists and only the bot is on both whitelists. */
protected: boolean;
/** Logins allowed to push (empty when push is open to everyone with write access). */
pushUsers: string[];
mergeUsers: string[];
}
const same = (a: string[], b: string[]) => a.length === b.length && a.every((x) => b.includes(x));
/** Reads the rule with the first client that can see it; null when no client could ask. */
export async function branchProtectionState(db: Db, project: Project, clients?: GiteaClient[]): Promise<BranchProtectionState | null> {
for (const c of clients ?? (await repoAdmins(db, project))) {
try {
const r = await c.getBranchProtection(project.giteaOwner, project.giteaRepo, project.defaultBranch);
const pushUsers = r?.enable_push && r.enable_push_whitelist ? (r.push_whitelist_usernames ?? []) : [];
const mergeUsers = r?.enable_merge_whitelist ? (r.merge_whitelist_usernames ?? []) : [];
const ok = !!r && r.enable_push_whitelist && r.enable_merge_whitelist && !r.push_whitelist_deploy_keys && same(pushUsers, [botLogin()]) && same(mergeUsers, [botLogin()]);
return { branch: project.defaultBranch, protected: ok, pushUsers, mergeUsers };
} catch {}
}
return null;
}
/**
* Sets (or repairs) the protection with the first client that has admin rights. Never throws:
* when no client can, the superadmin hears about it once (until it works again) and `false` is
* returned — the caller goes on (a project without protection still works).
*/
export async function ensureBranchProtection(db: Db, project: Project, o: { clients?: GiteaClient[]; log?: (line: string) => void } = {}): Promise<boolean> {
const repo = `${project.giteaOwner}/${project.giteaRepo}`;
const failKey = `branch.protect.failed:${project.id}`;
let last: unknown = null;
try {
for (const c of o.clients ?? (await repoAdmins(db, project))) {
try {
await c.protectBranch(project.giteaOwner, project.giteaRepo, project.defaultBranch, { users: [botLogin()] });
await deleteSetting(db, failKey);
return true;
} catch (e) {
last = e;
}
}
} catch (e) {
last = e;
}
const reason = (last as Error | null)?.message ?? m("нет доступа к коду проекта");
o.log?.(`branch protection ${repo}: ${reason}`);
try {
if (!(await getSetting(db, failKey))) {
const at = Date.now();
await setSetting(db, failKey, { at, reason: reason.slice(0, 300) });
// glossary-ignore: сообщение читает администратор платформы
await alertAdmins(db, `protect:${project.id}:${at}`, m("Основная ветка проекта {key} не защищена: {reason}. Peppa FACTORY повторит проверку сама; сразу — peppa project protect {key}.", { key: project.key, reason }), o.log ?? (() => {}));
}
} catch {}
return false;
}
/** Watchdog: once a day every project's rule is checked and put back if someone changed it. */
export async function branchProtectionTick(db: Db, opts: { now?: Date; log?: (line: string) => void } = {}): Promise<void> {
if (process.env.PEPPA_BRANCH_PROTECT === "off") return;
const now = (opts.now ?? new Date()).getTime();
const last = await getSetting<number>(db, "branch.protect.last");
if (last != null && now - last < DAY_MS) return;
await setSetting(db, "branch.protect.last", now);
for (const p of await listProjects(db)) {
const st = await branchProtectionState(db, p);
if (st?.protected) continue;
await ensureBranchProtection(db, p, { log: opts.log });
}
}

View File

@ -9,6 +9,7 @@ import { dirname, join } from "node:path";
import { giteaForBot, PeppaError, projectHookSecret, type GiteaClient, type Project } from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { ensureBranchProtection } from "./branch-protection.ts";
import { repoAdmins } from "./share.ts";
import { git, run, templateRepoUrl } from "./git.ts";
@ -87,6 +88,9 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str
const log = o.log ?? (() => {});
log("runner + secret");
const setup = await setupCi(db, project);
// PEP-191: the same command also puts the default branch protection back.
log("protect branch");
await ensureBranchProtection(db, project, { log });
const bot = giteaForBot();
const repo = await bot.getRepo(project.giteaOwner, project.giteaRepo);
if (!repo) throw new PeppaError(m("Код проекта {repo} не найден", { repo: `${project.giteaOwner}/${project.giteaRepo}` }));

View File

@ -29,6 +29,7 @@ export * from "./project-subscription.ts";
export * from "./subscription-request.ts";
export * from "./intake.ts";
export * from "./project-trash.ts";
export * from "./branch-protection.ts";
export * from "./story-refine.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";

View File

@ -9,6 +9,7 @@ import { createProject, NEW_PROJECT_AUTONOMY, NEW_PROJECT_PUBLISH, setPublishMod
import { projects, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { eq, or } from "drizzle-orm";
import { ensureBranchProtection } from "./branch-protection.ts";
import { setupCi } from "./ci.ts";
import { credentialHelper, git, run, templateRepoUrl } from "./git.ts";
@ -177,6 +178,17 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise<Pro
if (own) await setProjectPool(db, project.id, own.id);
// PEP-84: every new story of a new project goes through «продакт» and «аналитик» first.
await setIntakeSettings(db, project.id, { enabled: true });
// PEP-191: after the first commit only peppa-bot writes to the default branch. Best effort:
// the project works without it; the superadmin is told once and the watchdog retries daily.
log("protect branch");
const bot = (() => {
try {
return giteaForBot();
} catch {
return null; // no bot token (tests, a half-set machine): protect with the owner's client alone
}
})();
await ensureBranchProtection(db, project, { clients: bot ? [o.gitea, bot] : [o.gitea], log });
// 7. CI (PEP-57): runner, Actions secret, webhook. Best effort — `peppa ci connect` redoes it.
log("ci");
const ci = await setupCi(db, project).then(() => true, (e) => (log(`ci: ${(e as Error).message}`), false));

View File

@ -7,6 +7,7 @@ import { existsSync } from "node:fs";
import { eq } from "drizzle-orm";
import { GiteaError, giteaForBot, logEvent, PeppaError, type Project } from "@peppa/core";
import { projects, type Db } from "@peppa/db";
import { ensureBranchProtection } from "./branch-protection.ts";
import { setupCi } from "./ci.ts";
import { git } from "./git.ts";
import { forgetRepoInfo } from "./share.ts";
@ -66,6 +67,8 @@ export async function transferProject(db: Db, project: Project, newOwner: string
log("origin");
await git(project.workspacePath, "remote", "set-url", "origin", dest.clone_url);
}
log("protect branch");
await ensureBranchProtection(db, updated, { clients: [bot], log });
log("ci");
const ciError = await setupCi(db, updated).then(
() => null,

View File

@ -3,6 +3,7 @@
import { asIs, m } from "@peppa/shared/i18n";
import { runnerTick } from "./runners.ts";
import { projectTrashTick } from "./project-trash.ts";
import { branchProtectionTick } from "./branch-protection.ts";
import { createHash } from "node:crypto";
import {
backupDb,
@ -124,6 +125,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
// PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them.
// PEP-163: deleted projects leave for good after their week.
await projectTrashTick(db, { now: opts.now, log }).catch(failed(db, log, "project trash"));
// PEP-191: once a day the protection of every project's default branch is checked.
await branchProtectionTick(db, { now: opts.now, log }).catch(failed(db, log, "branch protection"));
await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake"));
// PEP-115: a comment on a backlog story — the analyst reworks the story.
await storyRefineTick(db, { now: opts.now, log }).catch(failed(db, log, "story refine"));

View File

@ -257,6 +257,8 @@ export const runner: Dict = {
'Slug "{slug}" уже занят': 'Slug "{slug}" is already taken',
'Ключ "{key}" уже занят': 'Key "{key}" is already taken',
"Рабочая копия {path} уже существует": "Working copy {path} already exists",
"Основная ветка проекта {key} не защищена: {reason}. Peppa FACTORY повторит проверку сама; сразу — peppa project protect {key}.": "The default branch of project {key} is not protected: {reason}. Peppa FACTORY will check again by itself; to do it now — peppa project protect {key}.",
"нет доступа к коду проекта": "no access to the project's code",
"Нет прав администратора на {repo}": "No admin rights on {repo}",
"Код проекта {repo} уже есть — подключите его как существующий": "The project code {repo} already exists — connect it as an existing one",
"Не удалось подготовить проект: {error}": "Could not prepare the project: {error}",

View File

@ -198,6 +198,8 @@ export const runner: Dict = {
"Slug \"{slug}\" уже занят": "Slug \"{slug}\" бос емес",
"Ключ \"{key}\" уже занят": "\"{key}\" кілті бос емес",
"Рабочая копия {path} уже существует": "{path} жұмыс көшірмесі бұрыннан бар",
"Основная ветка проекта {key} не защищена: {reason}. Peppa FACTORY повторит проверку сама; сразу — peppa project protect {key}.": "{key} жобасының негізгі тармағы қорғалмаған: {reason}. Peppa FACTORY тексеруді өзі қайталайды; дәл қазір — peppa project protect {key}.",
"нет доступа к коду проекта": "жоба кодына қол жетімділік жоқ",
"Нет прав администратора на {repo}": "{repo} үшін әкімші құқықтары жоқ",
"Код проекта {repo} уже есть — подключите его как существующий": "{repo} жоба коды бұрыннан бар — оны бар код ретінде қосыңыз",
"Не удалось подготовить проект: {error}": "Жобаны дайындау мүмкін болмады: {error}",

View File

@ -10,6 +10,18 @@ import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { join } from "node:path";
/** PEP-191: the fields of Gitea's branch protection Peppa uses. */
export interface MockProtection {
rule_name: string;
enable_push: boolean;
enable_push_whitelist: boolean;
push_whitelist_usernames: string[];
push_whitelist_deploy_keys: boolean;
enable_merge_whitelist: boolean;
merge_whitelist_usernames: string[];
required_approvals: number;
}
interface MockRepo {
id: number;
owner: string;
@ -24,6 +36,8 @@ interface MockRepo {
hooks: Array<{ id: number; url: string; secret: string; events: string[] }>;
tags: Array<{ name: string; target: string }>;
issues: MockIssue[];
/** PEP-191: branch protection rules by branch name (like Gitea's `branch_protections`). */
protections: Map<string, MockProtection>;
}
/** PEP-46: an issue with its comments (by login). */
@ -58,6 +72,8 @@ export class MockGitea {
readonly repos = new Map<string, MockRepo>();
/** Every request answers 500, like Gitea being down (PEP-127). */
down = false;
/** PEP-191: the branch_protections API answers 500 (a failed setup must not break projects). */
protectionDown = false;
readonly users = new Map<string, MockGiteaUser>();
readonly oauthCodes = new Map<string, string>(); // code → token
readonly runnerTokens: Array<{ scope: string; token: string }> = [];
@ -137,6 +153,7 @@ export class MockGitea {
hooks: [],
tags: [],
issues: [],
protections: new Map(),
private: opts.private ?? true,
};
this.repos.set(`${owner}/${name}`, repo);
@ -300,6 +317,14 @@ export class MockGitea {
p.state = "closed";
}
/** PEP-191: may `login` push to / merge into `branch`? (open when there is no rule). */
mayWrite(r: MockRepo, branch: string, login: string, what: "push" | "merge"): boolean {
const rule = r.protections.get(branch);
if (!rule) return true;
if (what === "push") return !rule.enable_push || (rule.enable_push_whitelist && rule.push_whitelist_usernames.includes(login));
return rule.enable_merge_whitelist ? rule.merge_whitelist_usernames.includes(login) : true;
}
private isEmpty(r: MockRepo) {
return execFileSync("git", ["--git-dir", r.path, "for-each-ref"], { encoding: "utf8" }).trim() === "";
}
@ -431,6 +456,32 @@ export class MockGitea {
this.runnerTokens.push({ scope: `repo:${r.owner}/${r.name}`, token });
return { status: 200, body: { token } };
}
if (this.protectionDown && /^branch_protections/.test(sub)) return { status: 500, body: { message: "mock-gitea: branch protection down" } };
if (method === "GET" && (m = sub.match(/^branch_protections\/([^/]+)$/))) {
if (!isAdmin) return { status: 403, body: { message: "forbidden" } };
const rule = r.protections.get(decodeURIComponent(m[1]!));
return rule ? { status: 200, body: rule } : { status: 404, body: { message: "branch protection does not exist" } };
}
if ((method === "POST" && sub === "branch_protections") || (method === "PATCH" && (m = sub.match(/^branch_protections\/([^/]+)$/)))) {
if (!isAdmin) return { status: 403, body: { message: "forbidden" } };
const name = method === "POST" ? String(body.rule_name ?? body.branch_name) : decodeURIComponent(m![1]!);
const cur = r.protections.get(name);
if (method === "POST" && cur) return { status: 403, body: { message: "branch protection already exists" } };
if (method === "PATCH" && !cur) return { status: 404, body: { message: "branch protection does not exist" } };
const b = body as Partial<MockProtection>;
const rule: MockProtection = {
rule_name: name,
enable_push: b.enable_push ?? cur?.enable_push ?? false,
enable_push_whitelist: b.enable_push_whitelist ?? cur?.enable_push_whitelist ?? false,
push_whitelist_usernames: b.push_whitelist_usernames ?? cur?.push_whitelist_usernames ?? [],
push_whitelist_deploy_keys: b.push_whitelist_deploy_keys ?? cur?.push_whitelist_deploy_keys ?? false,
enable_merge_whitelist: b.enable_merge_whitelist ?? cur?.enable_merge_whitelist ?? false,
merge_whitelist_usernames: b.merge_whitelist_usernames ?? cur?.merge_whitelist_usernames ?? [],
required_approvals: b.required_approvals ?? cur?.required_approvals ?? 0,
};
r.protections.set(name, rule);
return { status: method === "POST" ? 201 : 200, body: rule };
}
if (method === "PUT" && (m = sub.match(/^actions\/secrets\/([^/]+)$/))) {
if (!isAdmin && r.owner !== me.login) return { status: 403, body: { message: "forbidden" } };
r.secrets[decodeURIComponent(m[1]!)] = String(body.data);
@ -479,6 +530,7 @@ export class MockGitea {
}
if (method === "POST" && m[2] === "/merge") {
if (!canWrite) return { status: 403, body: { message: "forbidden" } };
if (!this.mayWrite(r, p.base, me.login, "merge")) return { status: 403, body: { message: "user not allowed to merge PR" } };
if (p.merged) return { status: 405, body: { message: "already merged" } };
if (!p.mergeable) return { status: 405, body: { message: "Please try again later: merge conflict" } };
if (body.head_commit_id && body.head_commit_id !== this.sha(r.owner, r.name, p.head)) return { status: 409, body: { message: "head out of date" } };
@ -541,6 +593,7 @@ export class MockGitea {
// Gitea's create (POST, file must not exist) / update (PUT, `sha` = current blob) — one commit on `branch`.
const path = decodeURIComponent(m[1]!);
const branch = String(body.branch ?? "main");
if (!this.mayWrite(r, branch, me.login, "push")) return { status: 403, body: { message: `Branch protected: ${branch}` } };
const git = (args: string[], env?: NodeJS.ProcessEnv, input?: string) =>
execFileSync("git", ["--git-dir", r.path, ...args], { encoding: "utf8", input, env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "ignore"] }).trim();
let parent: string | null = null;

View File

@ -0,0 +1,125 @@
// PEP-191: the default branch of a project is protected in Gitea — only peppa-bot pushes and merges.
// Tests are named after the scenarios of openspec/specs/branch-protection.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync } 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 { like } from "drizzle-orm";
import { telegramOutbox } from "@peppa/db";
import { core, db, runner, superadmin, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-protect-"));
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: 91, login: "mock-prot-alice", token: "mock-token-prot-alice" };
const BOT = { id: 92, login: "peppa-bot", token: "mock-token-prot-bot" };
type U = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let alice: U;
let templateUrl = "";
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
for (const u of [ALICE, BOT]) gitea.addUser(u);
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, ALICE, { access_token: ALICE.token });
});
after(async () => {
gitea.protectionDown = false;
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,
});
const rule = (slug: string) => gitea.repos.get(`${ALICE.login}/${slug}`)!.protections.get("main");
const protectAlerts = async () => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "protect:%"))).length;
describe("branch protection", () => {
test("new project gets main protected with peppa-bot", async () => {
await provision({ slug: "mock-prot-new", key: "MPNEW" });
const r = rule("mock-prot-new")!;
assert.deepEqual(r.push_whitelist_usernames, ["peppa-bot"]);
assert.deepEqual(r.merge_whitelist_usernames, ["peppa-bot"]);
assert.equal(r.enable_push_whitelist, true);
assert.equal(r.push_whitelist_deploy_keys, false);
assert.equal(r.required_approvals, 0);
});
test("a connected existing repository gets it too", async () => {
const repo = gitea.addRepo(ALICE.login, "mock-prot-existing", { files: { "README.md": "# x\n" } });
repo.collaborators["peppa-bot"] = "write";
await provision({ slug: "mock-prot-existing", key: "MPEXI", existing: true });
assert.deepEqual(rule("mock-prot-existing")!.push_whitelist_usernames, ["peppa-bot"]);
});
test("accept merges into protected main; another user is refused", async () => {
const p = await provision({ slug: "mock-prot-merge", key: "MPMRG" });
const repo = gitea.repos.get(`${ALICE.login}/mock-prot-merge`)!;
const work = join(TMP, "work-merge");
execFileSync("bash", ["-c", `git clone -q ${JSON.stringify(repo.path)} ${JSON.stringify(work)} && cd ${JSON.stringify(work)} && git checkout -q -b task/x && echo 1 > f.txt && git add -A && git -c user.name=t -c user.email=t@t commit -qm f && git push -q origin task/x`]);
gitea.openPull(ALICE.login, "mock-prot-merge", "task/x");
const aliceClient = await core.giteaForUser(db, alice);
await assert.rejects(aliceClient.mergePullRequest(ALICE.login, "mock-prot-merge", 1), /403/);
await assert.rejects(aliceClient.writeFile(ALICE.login, "mock-prot-merge", "evil.txt", { text: "x", branch: "main", message: "m" }), /403/);
await core.giteaForBot().mergePullRequest(ALICE.login, "mock-prot-merge", 1);
assert.ok(gitea.files(ALICE.login, "mock-prot-merge").includes("f.txt"));
assert.ok(p);
});
test("a failed setup does not break the project and tells the superadmin once", async () => {
await superadmin();
gitea.protectionDown = true;
const before = await protectAlerts();
const p = await provision({ slug: "mock-prot-fail", key: "MPFAL" });
assert.ok(p.id);
assert.equal(rule("mock-prot-fail"), undefined);
assert.equal(await protectAlerts(), before + 1);
assert.equal(await runner.ensureBranchProtection(db, p), false);
assert.equal(await protectAlerts(), before + 1, "no second message while it stays broken");
gitea.protectionDown = false;
assert.equal(await runner.ensureBranchProtection(db, p), true);
assert.deepEqual(rule("mock-prot-fail")!.push_whitelist_usernames, ["peppa-bot"]);
});
test("the daily check repairs a changed rule; ensure is idempotent", async () => {
const p = await provision({ slug: "mock-prot-tick", key: "MPTIK" });
rule("mock-prot-tick")!.push_whitelist_usernames.push("mock-prot-alice");
assert.equal((await runner.branchProtectionState(db, p))!.protected, false);
process.env.PEPPA_BRANCH_PROTECT = "on";
try {
await runner.branchProtectionTick(db, { now: new Date(Date.now() + 3 * 86400_000) });
} finally {
process.env.PEPPA_BRANCH_PROTECT = "off";
}
assert.equal((await runner.branchProtectionState(db, p))!.protected, true);
assert.equal(await runner.ensureBranchProtection(db, p), true);
});
test("saving AGENTS.md works while main is protected", async () => {
const p = await provision({ slug: "mock-prot-agents", key: "MPAGT" });
const cur = await runner.readAgentsMd(db, p);
assert.equal(cur.error, null);
await runner.saveAgentsMd(db, alice, p, `${cur.text}\n- PEP-191 проверка\n`, cur.sha);
assert.match(gitea.show(ALICE.login, "mock-prot-agents", "AGENTS.md"), /PEP-191 проверка/);
});
});

View File

@ -31,6 +31,7 @@ Object.assign(process.env, {
// PEP-145: the watchdog files «Продукт должен открываться по ссылке» for any project with
// accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on.
PEPPA_PRODUCT_LINK: "off",
PEPPA_BRANCH_PROTECT: "off",
// PEP-185: no «Взять в работу?» questions in other suites; pick-question.test.ts turns it on.
PEPPA_PICK_QUESTION: "off",
// PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe.