«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя». Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
85 lines
4.2 KiB
TypeScript
85 lines
4.2 KiB
TypeScript
// 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}. FORGE повторит проверку сама; сразу — 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 });
|
|
}
|
|
}
|