peppa/apps/web/app/(app)/actions.ts
Асель 3159e888d2 PEP-90: sign in and register with Google (OAuth code + PKCE), link with eGov in Settings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:40:26 +05:00

737 lines
31 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use server";
import {
setAutonomy,
type AutonomyLevel,
type AutonomySettings,
createEpic,
createTask,
updateEpic,
getQuestion,
getSession,
PeppaError,
unlinkGoogle,
projectForUser,
resolveTask,
revokeApp,
createPairingCode,
getSetting,
unpairTelegram,
getIncident,
getProject as getProjectByKey,
updateIncidentSettings,
setReviewSettings,
setIntakeSettings,
setUserBot,
clearUserBot,
type IncidentPolicy,
getUser,
isSuperadmin,
setUserDisabled,
NOTIFY_EVENTS,
defaultPrefs,
deletePushSubscription,
getNotifyPrefs,
isValidTimezone,
savePushSubscription,
sendWebPush,
setNotifyPrefs,
userPushSubscriptions,
addStoryComment,
updateTask,
listSessions,
setProjectRunnerSettings,
setTaskRunnerSettings,
dismissOnboarding,
AGENT_FIELDS,
setProjectAgentSettings,
setTaskAgentSettings,
cleanBudget,
logEvent,
setProjectBudget,
setTaskBudget,
type Budget,
setProjectSecret,
deleteProjectSecret,
reencryptAll,
markSecretRotated,
revokeClientTokens,
checkGiteaBotToken,
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, 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 [path, query] = target.split("?");
const params = new URLSearchParams(query);
params.set("error", msg.slice(0, 300));
target = `${path}?${params}`;
}
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;
}
/** PEP-31: hide the first-run checklist on the home page. */
export async function dismissOnboardingAction(f: FormData) {
const user = await requireUser();
await attempt(f, () => dismissOnboarding(db, user.id));
}
export async function answerQuestion(f: FormData) {
const user = asWebActor(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}`);
if (answer === "__accept") {
await acceptTask(db, q.id, "web");
return;
}
await answerAndDeliver(db, q.id, answer, "web");
});
}
export async function addTask(f: FormData) {
const user = asWebActor(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 epic = Number(str(f, "epicId")) || undefined;
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
return `/t/${ref.key}`;
});
}
/** Epics (PEP-66): labels that group stories; stored in the goals table. */
export async function addEpic(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
await createEpic(db, p.id, str(f, "title"), str(f, "description") || undefined);
});
}
export async function editEpic(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const id = Number(str(f, "epicId"));
if (str(f, "archive")) {
await updateEpic(db, p.id, id, { status: "archived" });
return;
}
if (str(f, "title").length < 2) throw new PeppaError("Нужно название эпика");
await updateEpic(db, p.id, id, { title: str(f, "title"), description: str(f, "description") || null });
});
}
/** Story page (PEP-32): title, description and epic from the web; no agent is started. */
export async function editStoryAction(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);
const title = str(f, "title");
if (title.length < 2) throw new PeppaError("Нужно название стори");
const epic = str(f, "epicId");
await updateTask(db, ref, { title, description: String(f.get("description") ?? "").trim(), goalId: epic ? Number(epic) : null }, undefined, user.login);
});
}
/** PM comment on a story (PEP-32): the agent sees it in get_task; optionally typed into the live runner. */
export async function commentStoryAction(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);
const c = await addStoryComment(db, ref, user, String(f.get("text") ?? ""));
if (str(f, "toAgent")) {
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
if (!live) throw new PeppaError("Комментарий сохранён, но живой сессии нет — агент увидит его в get_task");
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`);
}
});
}
/** «Принять и смержить» on the story's merge request tab (PEP-32): the same gate as «Принять». */
export async function acceptStoryAction(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 acceptStory(db, ref, "web");
});
}
/** PEP-67: a superadmin may pick a pool or tick subscriptions; otherwise the project's pool. */
async function launchChoice(f: FormData, user: Awaited<ReturnType<typeof requireUser>>) {
const choice = (await isSuperadmin(db, user)) ? str(f, "choice") : "";
const subscriptionIds = choice === "pick" ? f.getAll("subscription").map(Number).filter((n) => n > 0) : undefined;
if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError("Отметьте хотя бы одну подписку");
const poolId = choice.startsWith("pool:") ? Number(choice.slice(5)) : undefined;
const provider = str(f, "provider") as Provider | "";
return { provider: provider || undefined, subscriptionIds, poolId };
}
export async function startTaskSession(f: FormData) {
const user = asWebActor(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, { ...(await launchChoice(f, user)), prompt: str(f, "prompt") || undefined });
});
}
/** PEP-53: «Новый терминал» — a free runner in the project, opened in «Раннеры». */
export async function startFreeRunnerAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const s = await startFreeRunner(db, p.id, { ...(await launchChoice(f, user)), name: str(f, "name") || undefined, prompt: str(f, "prompt") || undefined });
return `/runners?id=${s.id}`;
});
}
export async function renameRunnerAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
await renameRunner(db, s.id, str(f, "name"));
});
}
/** PEP-53: «Оформить стори» from a free runner. */
export async function promoteRunnerAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
const ref = await promoteRunner(db, s.id, { title: str(f, "title"), description: str(f, "description") || undefined });
return `/t/${ref.key}`;
});
}
/** PEP-10: a story into the runner's queue. */
export async function queueOnRunnerAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const s = await ownedSession(user.id, Number(str(f, "sessionId")));
const ref = await resolveTask(db, str(f, "taskKey"), s.projectKey);
await queueTaskOnRunner(db, s.id, ref, str(f, "prompt") || undefined);
});
}
/** PEP-10/27: runner settings of a project, or mode/context of one story ("" = inherit). */
export async function setRunnerSettingsAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
const pick = <T extends string>(k: string) => (str(f, k) || undefined) as T | undefined;
if (str(f, "taskKey")) {
const ref = await resolveTask(db, str(f, "taskKey"));
await projectForUser(db, user.id, ref.project.id);
await setTaskRunnerSettings(db, ref.task.id, { mode: pick("mode"), context: pick("context") });
return;
}
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const max = str(f, "maxRunners");
await setProjectRunnerSettings(db, p.id, {
mode: pick("mode"),
context: pick("context"),
workspace: pick("workspace"),
isolation: pick("isolation"),
...(max === "" ? {} : { maxRunners: max === "0" ? null : Number(max) }),
// PEP-40: "" inherit, local — Peppa's machine, list — the ticked hosts.
...(str(f, "hostsMode") === "local" ? { hosts: [] } : str(f, "hostsMode") === "list" ? { hosts: f.getAll("hosts").map(Number).filter((n) => n > 0) } : {}),
});
});
}
/** PEP-41: agent provider/model/effort of a project (all fields) or a story ("" = inherit). */
export async function setAgentSettingsAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const patch: Record<string, unknown> = {};
for (const k of AGENT_FIELDS) if (f.has(k)) patch[k] = str(f, k);
if (patch.escalateAfter === "0") patch.escalateAfter = null;
if (str(f, "taskKey")) {
const ref = await resolveTask(db, str(f, "taskKey"));
await projectForUser(db, user.id, ref.project.id);
await setTaskAgentSettings(db, ref.task.id, patch);
return;
}
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await setProjectAgentSettings(db, p.id, patch);
});
}
export async function stopTaskSession(f: FormData) {
const user = asWebActor(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 = asWebActor(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 = asWebActor(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 = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await provisionProject(db, {
...(await projectNamespace(db, user, str(f, "owner"))), // PEP-68: local user → peppa-bot
slug: str(f, "slug").toLowerCase(),
key: str(f, "key"),
name: str(f, "name"),
existing: str(f, "mode") === "existing",
visibility: str(f, "visibility") === "private" ? "private" : "public",
ownerId: user.id,
});
return `/p/${p.key}?created=1`;
});
}
export async function deployProdAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, (await getProjectByKey(db, str(f, "projectKey"))).id);
await deployProd(db, p, user.login);
});
}
export async function moveTaskCard(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const ref = await resolveTask(db, str(f, "taskKey"));
await projectForUser(db, user.id, ref.project.id);
const to = str(f, "to") as BoardColumn;
if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError("Неизвестная колонка");
await moveTask(db, ref, to);
});
}
export async function revokeConnectedApp(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await revokeApp(db, user.id, str(f, "clientId"));
});
}
export async function addProjectMember(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const r = await shareProject(db, user, p, str(f, "login"));
if (!r.repoAccess) throw new PeppaError(`${r.login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную`);
});
}
export async function grantRepoAccessToMembers(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const r = await grantRepoAccess(db, user, p);
if (r.failed.length) throw new PeppaError(`Не удалось выдать доступ к репозиторию: ${r.failed.join(", ")} — нет прав администратора в Gitea, добавьте соавторов вручную`);
});
}
export async function setProjectVisibilityAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await setProjectVisibility(db, p, str(f, "visibility") === "private" ? "private" : "public", { actor: user });
});
}
/** PEP-23: project autonomy — a preset level, or the individual settings (owner or member). */
export async function setAutonomyAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const level = str(f, "level");
if (level) {
await setAutonomy(db, p.id, { level: level as AutonomyLevel });
return;
}
const hour = (k: string) => (str(f, k) === "" ? null : Number(str(f, k)));
const quiet = f.get("quiet") === "on";
await setAutonomy(db, p.id, {
pick: str(f, "pick") as AutonomySettings["pick"],
wipLimit: Number(str(f, "wipLimit")),
proposal: str(f, "proposal") as AutonomySettings["proposal"],
merge: str(f, "merge") as AutonomySettings["merge"],
close: str(f, "close") as AutonomySettings["close"],
closeAfterHours: Number(str(f, "closeAfterHours")),
idlePush: f.get("idlePush") === "on",
idlePushHours: Number(str(f, "idlePushHours")),
quietFrom: quiet ? hour("quietFrom") : null,
quietTo: quiet ? hour("quietTo") : null,
});
});
}
export async function removeProjectMember(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const login = str(f, "login");
await unshareProject(db, user, p, login);
// Left the project myself: its page is gone for me.
if (login.toLowerCase() === user.login.toLowerCase()) return "/";
});
}
export async function pairTelegram(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const token = loadEnv().TELEGRAM_BOT_TOKEN;
// PEP-85: the user's own bot if they connected one, else the platform's shared bot.
const username = user.telegramBotUsername ?? (await getSetting<{ username: string }>(db, "telegram.bot"))?.username;
if (!token || !username) throw new PeppaError("Telegram-бот Пеппы не запущен");
return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
});
}
export async function unlinkGoogleAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await unlinkGoogle(db, user.id);
});
}
export async function unpairTelegramAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await unpairTelegram(db, user.id);
});
}
// ── notifications (PEP-35, PEP-55) ──────────────────────────────────────────────
/** «Настройки → Уведомления»: events × channels, quiet hours, timezone, digest, sound, projects. */
export async function saveNotifyPrefsAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const cur = await getNotifyPrefs(db, user.id);
const d = defaultPrefs();
const events = { ...d.events };
for (const e of NOTIFY_EVENTS) events[e] = { telegram: f.get(`${e}.telegram`) === "on", push: f.get(`${e}.push`) === "on" };
const tz = str(f, "timezone") || cur.timezone;
if (!isValidTimezone(tz)) throw new PeppaError(`Неизвестная таймзона: ${tz}`);
const shown = f.getAll("projectShown").map(Number);
const enabled = new Set(f.getAll("project").map(Number));
// Projects not on the form (no access any more) keep their old state.
const muted = [...cur.mutedProjects.filter((id) => !shown.includes(id)), ...shown.filter((id) => !enabled.has(id))];
try {
await setNotifyPrefs(db, user.id, {
events,
quiet: f.get("quietOn") === "on" ? { from: str(f, "quietFrom"), to: str(f, "quietTo") } : null,
timezone: tz,
digestTime: str(f, "digestTime") || cur.digestTime,
sound: f.get("sound") === "on",
mutedProjects: muted,
});
} catch (e) {
throw new PeppaError((e as Error).message);
}
return "/settings?notify=saved#notifications";
});
}
/** The browser subscribed to Web Push (called from the client with PushSubscription.toJSON()). */
export async function savePushSubscriptionAction(sub: { endpoint: string; keys: { p256dh: string; auth: string } }, userAgent: string | null) {
const user = asWebActor(await requireUser());
await savePushSubscription(db, user.id, { ...sub, userAgent });
revalidatePath("/settings");
return { ok: true };
}
export async function deletePushSubscriptionAction(endpoint: string) {
const user = asWebActor(await requireUser());
await deletePushSubscription(db, user.id, endpoint);
revalidatePath("/settings");
return { ok: true };
}
/** Test notification to this browser, sent right away (doesn't depend on the bot). */
export async function testPushAction(endpoint: string): Promise<{ ok: boolean; error?: string }> {
const user = asWebActor(await requireUser());
const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint);
if (!sub) return { ok: false, error: "Этот браузер не подписан" };
const prefs = await getNotifyPrefs(db, user.id);
const r = await sendWebPush(db, sub, { title: "Пеппа", body: "Уведомления в этом браузере работают ✅", url: "/settings#notifications", tag: "test", sound: prefs.sound });
if (r.ok) return { ok: true };
if (r.gone) await deletePushSubscription(db, user.id, endpoint);
return { ok: false, error: r.error };
}
// ── errors from running products (PEP-58) ───────────────────────────────────────
async function incidentInProject(userId: number, f: FormData) {
const p = await projectForUser(db, userId, Number(str(f, "projectId")));
const i = await getIncident(db, Number(str(f, "incidentId")));
if (i.projectId !== p.id) throw new PeppaError("Не найдено");
return i;
}
export async function connectErrorTrackingAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
if (!(await managesProject(db, user, p))) throw new PeppaError("Подключает владелец проекта");
await connectErrorTracking(db, p, bugsinkFromEnv(), bugsinkWebhookBase());
});
}
export async function saveIncidentSettings(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await updateIncidentSettings(db, p.id, {
policy: str(f, "policy") as IncidentPolicy,
triagePrompt: str(f, "triagePrompt") || null,
environments: str(f, "environments").split(","),
dailyLimit: Number(str(f, "dailyLimit") || 5),
ignorePattern: str(f, "ignorePattern") || null,
});
});
}
// ── reviewer agent (PEP-26) ──────────────────────────────────────────────────────
export async function saveReviewSettingsAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await setReviewSettings(db, p.id, {
enabled: f.get("enabled") === "on",
maxIterations: Number(str(f, "maxIterations") || 2),
rules: str(f, "rules") || null,
});
});
}
export async function decideIncidentAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const i = await incidentInProject(user.id, f);
const action = str(f, "action");
if (action !== "backlog" && action !== "start" && action !== "ignore") throw new PeppaError("Неизвестное решение");
await decideIncident(db, i.id, action, user.login);
});
}
export async function resolveIncidentAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const i = await incidentInProject(user.id, f);
await resolveIncident(db, i.id, { who: user.login, release: str(f, "release") || null });
});
}
// ── local users (PEP-68) ────────────────────────────────────────────────────────────
/** Superadmin-only actions: everybody else gets "not found", nothing changes. */
async function requireSuperadmin() {
const user = asWebActor(await requireUser());
if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено");
return user;
}
export async function setUserDisabledAction(f: FormData) {
await attempt(f, async () => {
const admin = await requireSuperadmin();
const u = await getUser(db, Number(str(f, "userId")));
if (!u) throw new PeppaError("Не найдено");
if (u.id === admin.id) throw new PeppaError("Нельзя отключить самого себя");
await setUserDisabled(db, u.id, str(f, "disabled") === "1");
});
}
// ── PEP-43: budgets ────────────────────────────────────────────────────────────────
const budgetFrom = (f: FormData): Budget => cleanBudget(Object.fromEntries(["minutes", "tokens", "restarts", "costUsd"].map((k) => [k, Number(str(f, k)) || null])));
export async function saveTaskBudgetAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const ref = await resolveTaskById(db, Number(str(f, "taskId")));
await projectForUser(db, user.id, ref.project.id);
const mode = str(f, "mode");
const budget = mode === "inherit" ? null : mode === "unlimited" ? {} : budgetFrom(f);
await setTaskBudget(db, ref.task.id, budget);
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "budget_changed", payload: { budget: budget ?? "проекта" } });
await budgetChanged(db, ref.task.id);
});
}
export async function saveProjectBudgetAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
const budget = budgetFrom(f);
await setProjectBudget(db, p.id, budget);
await logEvent(db, { projectId: p.id, type: "project_budget_changed", payload: { budget } });
});
}
// ── project secrets (PEP-54) and platform secrets (PEP-19) ─────────────────────────
export async function saveProjectSecretAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
// The value is taken as is (no trim): keys may legitimately end with spaces/newlines.
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""));
});
}
export async function deleteProjectSecretAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await deleteProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"));
});
}
export async function reencryptSecretsAction(f: FormData) {
await attempt(f, async () => {
const admin = await requireSuperadmin();
const r = await reencryptAll(db, admin.login);
return `/secrets?reencrypted=${r.reencrypted}&unreadable=${r.unreadable.length}`;
});
}
export async function markSecretRotatedAction(f: FormData) {
await attempt(f, async () => {
const admin = await requireSuperadmin();
await markSecretRotated(db, str(f, "name"), admin.login);
return "/secrets";
});
}
export async function revokeClientTokensAction(f: FormData) {
await attempt(f, async () => {
await requireSuperadmin();
const n = await revokeClientTokens(db, str(f, "clientId"));
return `/secrets?revoked=${n}`;
});
}
export async function checkGiteaTokenAction(f: FormData) {
await attempt(f, async () => {
await requireSuperadmin();
const r = await checkGiteaBotToken();
return `/secrets?gitea=${encodeURIComponent(r.ok ? `ok:${r.login}` : r.problems.join("; "))}`;
});
}
// ── PEP-73: the project's AGENTS.md ──────────────────────────────────────────────
export async function saveAgentsMdAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await saveAgentsMd(db, user, p, String(f.get("text") ?? ""), str(f, "sha") || null);
return `/p/${p.key}?tab=agents&saved=1`;
});
}
// ── PEP-76: what the project's agents run on ───────────────────────────────────────
export async function chooseSharedSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await chooseSharedSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))));
});
}
export async function connectOwnSubscriptionAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const kind = str(f, "kind") as OwnSubscriptionKind;
if (!["claude_login", "claude", "codex_login", "codex_key", "existing"].includes(kind)) throw new PeppaError("Выберите, что подключить");
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await connectOwnSubscription(db, user, p, kind, String(f.get("secret") ?? ""));
});
}
/** PEP-82: step 3 of the Claude sign-in on the project page. */
export async function finishOwnClaudeLoginAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await finishOwnClaudeLogin(db, user, p, Number(str(f, "subscriptionId")), str(f, "code"));
});
}
export async function cancelOwnLoginAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await cancelOwnLogin(db, user, p, Number(str(f, "subscriptionId")));
});
}
// ── PEP-84: «продакт» and «аналитик» ───────────────────────────────────────────────
export async function saveIntakeSettingsAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
});
}
// ── PEP-85: the user's own Telegram bot ────────────────────────────────────────────
export async function connectOwnBotAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await setUserBot(db, user.id, String(f.get("token") ?? ""));
// On the Home page the next step (Start) shows right there.
return str(f, "back") === "/" ? "/" : "/settings?bot=connected#telegram";
});
}
export async function disconnectOwnBotAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
await clearUserBot(db, user.id);
return str(f, "back") === "/" ? "/" : "/settings#telegram";
});
}