Миграция сроков разрешений переименована в 0034 (0033 заняла PEP-252). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1127 lines
50 KiB
TypeScript
1127 lines
50 KiB
TypeScript
"use server";
|
||
|
||
import {
|
||
setAutonomy,
|
||
type AutonomyLevel,
|
||
type AutonomySettings,
|
||
createEpic,
|
||
createTask,
|
||
updateEpic,
|
||
getQuestion,
|
||
getSession,
|
||
PeppaError,
|
||
unlinkGoogle,
|
||
projectForUser,
|
||
resolveTask,
|
||
revokeApp,
|
||
createPairingCode,
|
||
unpairTelegram,
|
||
getIncident,
|
||
getProject as getProjectByKey,
|
||
updateIncidentSettings,
|
||
setReviewSettings,
|
||
setIntakeSettings,
|
||
setUserBot,
|
||
clearUserBot,
|
||
type IncidentPolicy,
|
||
getUser,
|
||
isSuperadmin,
|
||
setUserDisabled,
|
||
setSuperadmin,
|
||
mergeAccounts,
|
||
NOTIFY_EVENTS,
|
||
defaultPrefs,
|
||
deletePushSubscription,
|
||
getNotifyPrefs,
|
||
isValidTimezone,
|
||
savePushSubscription,
|
||
sendWebPush,
|
||
setNotifyPrefs,
|
||
userPushSubscriptions,
|
||
addStoryComment,
|
||
updateTask,
|
||
listSessions,
|
||
setProjectRunnerSettings,
|
||
setTaskRunnerSettings,
|
||
dismissOnboarding,
|
||
AGENT_FIELDS,
|
||
setProjectAgentSettings,
|
||
setTaskAgentSettings,
|
||
cleanBudget,
|
||
logEvent,
|
||
setPublishMode,
|
||
type PublishMode,
|
||
setProjectBudget,
|
||
setTaskBudget,
|
||
type Budget,
|
||
setProjectSecret,
|
||
setSecretAudience,
|
||
secretToConnection,
|
||
setAgentSecretsEnabled,
|
||
setNeedDone,
|
||
removeNeed,
|
||
deleteProjectSecret,
|
||
reencryptAll,
|
||
markSecretRotated,
|
||
revokeClientTokens,
|
||
checkGiteaBotToken,
|
||
setUiMode,
|
||
} from "@peppa/core";
|
||
import { checkConnection, createConnection, decideIdleGrant, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGatewayProtocol, isGrantTerm, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core";
|
||
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
|
||
import { deleteProject, decideProposals, mergeProposals } from "@peppa/runner";
|
||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||
import { loadEnv } from "@peppa/shared";
|
||
import { pauseProject, resumeProject, acceptAll, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
|
||
import { revalidatePath } from "next/cache";
|
||
import { redirect } from "next/navigation";
|
||
import { asWebActor, requireUser, words } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
import { getT } from "@/lib/i18n";
|
||
import { m, PRODUCT_NAME } from "@peppa/shared/i18n";
|
||
|
||
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 t = await getT();
|
||
// PEP-98: core errors are rendered Russian text — translate them for the reader.
|
||
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { 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(m("Пустой ответ"));
|
||
if (q.answeredAt) throw new PeppaError(q.answeredVia === "system" ? m("Уже отвечено: {answer}", { answer: q.answer }) : m("Уже отвечено ({via}): {answer}", { via: q.answeredVia, answer: 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(m("Нужно название задачи"));
|
||
const epic = Number(str(f, "epicId")) || undefined;
|
||
const ids = parseAttachmentIds(f.getAll("attachment"));
|
||
const ref = await createTask(db, { projectId: p.id, title: str(f, "title"), description: str(f, "description") || undefined, goalId: epic });
|
||
await linkAttachments(db, user, p.id, ids, { taskId: ref.task.id });
|
||
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(m("Нужно название эпика"));
|
||
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(m("Нужно название эпика"));
|
||
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(m("Нужно название задачи"));
|
||
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 ids = parseAttachmentIds(f.getAll("attachment"));
|
||
const body = String(f.get("text") ?? "").trim() || (await attachmentLabel(db, ids));
|
||
const c = await addStoryComment(db, ref, user, body);
|
||
await linkAttachments(db, user, ref.project.id, ids, { taskId: ref.task.id, eventId: c.id });
|
||
if (str(f, "toAgent")) {
|
||
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
|
||
if (!live) throw new PeppaError(m("Комментарий сохранён, но агент сейчас не работает — увидит его, когда вернётся к задаче"));
|
||
// i18n-ignore — text for the agent
|
||
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}${await syncSessionAttachments(db, live.id)}`, { person: true });
|
||
}
|
||
});
|
||
}
|
||
|
||
/** «Принять и смержить» 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-209: «Принять» / «Принять всё» on the acceptance page — one by one, a failure of one doesn't
|
||
* stop the others; the page shows the result («Принято 6, на доработке 1…»).
|
||
*/
|
||
export async function acceptAllAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
const key = str(f, "project");
|
||
const base = `/p/${encodeURIComponent(key)}/accept`;
|
||
await attempt(f, async () => {
|
||
const refs = [];
|
||
for (const k of f.getAll("taskKey").map(String)) {
|
||
const ref = await resolveTask(db, k).catch(() => null);
|
||
if (!ref || ref.project.key !== key) continue;
|
||
await projectForUser(db, user.id, ref.project.id);
|
||
if (ref.task.status === "review") refs.push(ref);
|
||
}
|
||
if (!refs.length) throw new PeppaError(m("Принимать нечего: задачи уже приняты или вернулись в работу"));
|
||
const r = await acceptAll(db, refs, "web");
|
||
return `${base}?ok=${r.accepted.length}&pending=${r.pending.length}&failed=${r.failed.length}`;
|
||
});
|
||
}
|
||
|
||
/** «Поправить» on the story page in «Продакт» mode (PEP-120): the remark goes to the agent, the story — back to work. */
|
||
export async function fixStoryAction(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 fixStory(db, ref, user, String(f.get("text") ?? ""));
|
||
});
|
||
}
|
||
|
||
/** PEP-198: «Подходит» / «Нужно иначе» / «Не делить» on a decision of «Фабрика решила за вас». */
|
||
export async function decisionAction(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 id = Number(str(f, "id"));
|
||
const choice = str(f, "choice");
|
||
if (choice === "confirm") await confirmTaskDecision(db, ref, id, user);
|
||
else if (choice === "unsplit") await undoSplit(db, ref, id, user);
|
||
else if (choice === "change") await changeTaskDecision(db, ref, id, String(f.get("how") ?? ""), user);
|
||
else throw new PeppaError(m("Эта кнопка уже не работает. Обновите страницу."));
|
||
});
|
||
}
|
||
|
||
/** 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(m("Отметьте хотя бы одну подписку"));
|
||
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(m("Пустое сообщение"));
|
||
await sendToSession(db, s.id, str(f, "text"), { person: true });
|
||
});
|
||
}
|
||
|
||
export async function createProjectAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
// PEP-142: the same form sent twice (a second click, another tab) opens the one project.
|
||
const p = await provisionProjectOnce(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);
|
||
});
|
||
}
|
||
|
||
/** PEP-145: «Показывать всем: сам / по кнопке» (owner or member). */
|
||
export async function setPublishModeAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
const mode = await setPublishMode(db, p.id, str(f, "mode") as PublishMode);
|
||
await logEvent(db, { projectId: p.id, type: "publish_mode_set", payload: { mode, login: user.login } });
|
||
// «Сам» chosen with an accepted version waiting: it goes to everyone right away.
|
||
if (mode === "auto") await autoPublish(db, p).catch(() => false);
|
||
});
|
||
}
|
||
|
||
/** PEP-174: «Поставить на паузу» — owner, member or superadmin. Agents stop, nothing is sent. */
|
||
export async function pauseProjectAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
await pauseProject(db, p.id, user.id);
|
||
});
|
||
}
|
||
|
||
/** PEP-174: «Продолжить» — the agents stopped by the pause continue, the dispatcher takes stories again. */
|
||
export async function resumeProjectAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
await resumeProject(db, p.id);
|
||
});
|
||
}
|
||
|
||
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(m("Неизвестная колонка"));
|
||
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((await words()).engineer ? m("{login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную", { login: r.login }) : m("{login} добавлен, но доступ к коду проекта выдать не удалось. Напишите в поддержку FORGE.", { login: r.login }));
|
||
});
|
||
}
|
||
|
||
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(m("Не удалось выдать доступ к репозиторию: {logins} — нет прав администратора в Gitea, добавьте соавторов вручную", { logins: r.failed.join(", ") }));
|
||
});
|
||
}
|
||
|
||
/** PEP-163: the owner deletes the project; it stays with the superadmin for a week. */
|
||
export async function deleteProjectAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
if (str(f, "confirm") !== "yes") throw new PeppaError(m("Отметьте, что хотите удалить проект"));
|
||
await deleteProject(db, user.id, Number(str(f, "projectId")));
|
||
return "/projects";
|
||
});
|
||
}
|
||
|
||
export async function restoreProjectAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await restoreProject(db, Number(str(f, "projectId")), user.id);
|
||
});
|
||
}
|
||
|
||
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")),
|
||
acceptOwn: (str(f, "acceptOwn") || undefined) as AutonomySettings["acceptOwn"],
|
||
idlePush: f.get("idlePush") === "on",
|
||
idlePushHours: Number(str(f, "idlePushHours")),
|
||
quietFrom: quiet ? hour("quietFrom") : null,
|
||
quietTo: quiet ? hour("quietTo") : null,
|
||
});
|
||
});
|
||
}
|
||
|
||
/** PEP-197: «Делать» / «Не надо» on a suggested story (board, chat). */
|
||
export async function proposalAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const choice = str(f, "choice");
|
||
// PEP-209: «Объединить в одну» — the ticked proposals become one story.
|
||
if (choice === "merge") {
|
||
await mergeProposals(db, user, f.getAll("pick").map(Number).filter((n) => Number.isInteger(n) && n > 0));
|
||
return;
|
||
}
|
||
if (choice !== "do" && choice !== "no" && choice !== "important" && choice !== "none") throw new PeppaError(m("Эта кнопка уже не работает."));
|
||
const ids = str(f, "ids").split(",").map(Number).filter((n) => Number.isInteger(n) && n > 0);
|
||
await decideProposals(db, user, ids, choice);
|
||
});
|
||
}
|
||
|
||
/** PEP-197: «Принимать сами» — whose stories are accepted without the owner. */
|
||
export async function setAcceptOwnAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
await setAutonomy(db, p.id, { acceptOwn: str(f, "acceptOwn") as AutonomySettings["acceptOwn"] });
|
||
});
|
||
}
|
||
|
||
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 "/";
|
||
});
|
||
}
|
||
|
||
/** PEP-100: the pairing link for the client to open in a new tab — Peppa stays where it is. */
|
||
export async function pairingLinkAction(): Promise<{ url?: string; error?: string }> {
|
||
const user = asWebActor(await requireUser());
|
||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||
// Every user has their own bot: no pairing link through the shared one.
|
||
const username = user.telegramBotUsername;
|
||
const t = await getT();
|
||
if (!username) return { error: t("Сначала подключите своего бота (шаги 1–2)") };
|
||
if (!token) return { error: t("Telegram сейчас недоступен. Попробуйте через минуту.") };
|
||
return { url: `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}` };
|
||
}
|
||
|
||
export async function pairTelegram(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||
// Every user has their own bot (PEP-85/100): the platform's bot is never offered to users.
|
||
const username = user.telegramBotUsername;
|
||
if (!username) throw new PeppaError(m("Сначала подключите своего Telegram-бота"));
|
||
if (!token) throw new PeppaError(m("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) ──────────────────────────────────────────────
|
||
|
||
/** PEP-119: «Продакт» or «Инженер» — what this user sees. */
|
||
export async function setUiModeAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await setUiMode(db, user.id, str(f, "mode"));
|
||
return "/settings?mode=saved";
|
||
});
|
||
}
|
||
|
||
/** «Настройки → Уведомления»: 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(m("Неизвестная таймзона: {tz}", { 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);
|
||
const t = await getT();
|
||
if (!sub) return { ok: false, error: t("Этот браузер не подписан") };
|
||
const prefs = await getNotifyPrefs(db, user.id);
|
||
const r = await sendWebPush(db, sub, { title: PRODUCT_NAME, body: t("Уведомления в этом браузере работают ✅"), 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(m("Не найдено"));
|
||
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(m("Подключает владелец проекта"));
|
||
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(m("Неизвестное решение"));
|
||
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(m("Не найдено"));
|
||
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(m("Не найдено"));
|
||
if (u.id === admin.id) throw new PeppaError(m("Нельзя отключить самого себя"));
|
||
await setUserDisabled(db, u.id, str(f, "disabled") === "1");
|
||
});
|
||
}
|
||
|
||
/** PEP-226: appoint or remove a superadmin from «Пользователи». */
|
||
export async function setSuperadminAction(f: FormData) {
|
||
await attempt(f, async () => {
|
||
const admin = asWebActor(await requireSuperadmin());
|
||
await setSuperadmin(db, admin, Number(str(f, "userId")), str(f, "on") === "1");
|
||
});
|
||
}
|
||
|
||
/** PEP-204: merge an old account into the person's main one, after the confirmation screen. */
|
||
export async function mergeAccountsAction(f: FormData) {
|
||
await attempt(f, async () => {
|
||
// The actor is set in this frame: set inside requireSuperadmin it would not reach the journal entry.
|
||
const admin = asWebActor(await requireSuperadmin());
|
||
await mergeAccounts(db, admin, Number(str(f, "from")), Number(str(f, "to")), { confirm: str(f, "confirm") === "1", confirmAdmin: str(f, "confirmAdmin") === "1" });
|
||
return "/users";
|
||
});
|
||
}
|
||
|
||
|
||
// ── 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 ?? "проекта" } }); // i18n-ignore — stored value
|
||
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.
|
||
// PEP-253: «Кому» — only the product by default.
|
||
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""), { agent: str(f, "audience") === "agent" });
|
||
});
|
||
}
|
||
|
||
// PEP-253: «только продукту» ⇄ «агенту и продукту».
|
||
export async function setSecretAudienceAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await setSecretAudience(db, user.id, Number(str(f, "projectId")), str(f, "name"), str(f, "audience") === "agent");
|
||
});
|
||
}
|
||
|
||
// PEP-253: «Сделать подключением» — a catalog connection with the secret's key, granted to the project.
|
||
export async function secretToConnectionAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await secretToConnection(db, user.id, Number(str(f, "projectId")), str(f, "name"));
|
||
});
|
||
}
|
||
|
||
// PEP-253: «Агенты получают секреты в окружение».
|
||
export async function setAgentSecretsAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await setAgentSecretsEnabled(db, user.id, Number(str(f, "projectId")), str(f, "on") === "1");
|
||
});
|
||
}
|
||
|
||
// PEP-112: «чтобы заработало по-настоящему» on the «Ваш продукт» card.
|
||
export async function setNeedDoneAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const project = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
await setNeedDone(db, project.id, str(f, "id"), str(f, "done") !== "0");
|
||
});
|
||
}
|
||
|
||
export async function removeNeedAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const project = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
await removeNeed(db, project.id, str(f, "id"));
|
||
});
|
||
}
|
||
|
||
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"))));
|
||
});
|
||
}
|
||
|
||
/** PEP-186: «Попросить подписку у администратора». */
|
||
export async function requestSubscriptionAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await requestSubscription(db, user, await projectForUser(db, user.id, Number(str(f, "projectId"))), new Date(), { ahead: str(f, "ahead") === "1" });
|
||
});
|
||
}
|
||
|
||
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(m("Выберите, что подключить"));
|
||
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"), str(f, "account"));
|
||
});
|
||
}
|
||
|
||
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-107: «Убрать» one of the user's own subscriptions from the project's pool. */
|
||
export async function removeOwnSubscriptionAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||
await removeOwnSubscription(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" });
|
||
});
|
||
}
|
||
|
||
// ── 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";
|
||
});
|
||
}
|
||
|
||
|
||
// ── PEP-143: users' reports about Peppa — the superadmin decides ─────────────────────
|
||
export async function fixFeedbackAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await fixFeedback(db, user, Number(str(f, "feedbackId")), Number(str(f, "option")));
|
||
});
|
||
}
|
||
|
||
export async function linkFeedbackAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await linkFeedback(db, user, Number(str(f, "feedbackId")), str(f, "task") || null);
|
||
});
|
||
}
|
||
|
||
export async function rejectFeedbackAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await rejectFeedback(db, user, Number(str(f, "feedbackId")), str(f, "reason") || null);
|
||
});
|
||
}
|
||
|
||
// PEP-234 Access Hub: the user's own connections. Every core function checks the owner itself.
|
||
// PEP-249: catalog cards, a key check right after saving, read / write modes.
|
||
const checkWord = (r: ConnectionCheckResult | null) => (!r ? "down" : r.reachableOnly ? "reachable" : r.status);
|
||
const AUTH_KINDS: CatalogAuth[] = ["bearer", "header", "query", "basic"];
|
||
|
||
// PEP-251: the form fields of a database / server / storage / mailbox (never the secret).
|
||
const PROTOCOL_FIELDS = ["host", "port", "database", "user", "tls", "root", "hostKey", "endpoint", "region", "bucket", "prefix", "accessKeyId", "imapHost", "imapPort", "smtpHost", "smtpPort", "from"];
|
||
|
||
export async function createConnectionAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const protocol = str(f, "protocol");
|
||
if (isGatewayProtocol(protocol)) {
|
||
const config = Object.fromEntries(PROTOCOL_FIELDS.filter((k) => f.has(k)).map((k) => [k, str(f, k)]));
|
||
// An SSH key keeps its line breaks; a password is one line.
|
||
const raw = String(f.get("secret") ?? "");
|
||
const secret = protocol === "ssh" && raw.includes("-----BEGIN") ? `${raw.replace(/\r\n/g, "\n").trim()}\n` : raw.trim();
|
||
const c = await createConnection(db, user.id, { protocol, name: str(f, "name"), config, secret });
|
||
const r = await checkConnection(db, user.id, c.id).catch(() => null);
|
||
return `/connections?created=${c.id}&check=${checkWord(r)}#c${c.id}`;
|
||
}
|
||
const kind = str(f, "authKind") as CatalogAuth;
|
||
const c = await createConnection(db, user.id, {
|
||
catalogId: str(f, "catalogId") || null,
|
||
name: str(f, "name"),
|
||
baseUrl: str(f, "baseUrl"),
|
||
secret: String(f.get("secret") ?? "").trim(),
|
||
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
||
authHeader: str(f, "authHeader") || null,
|
||
});
|
||
const r = await checkConnection(db, user.id, c.id).catch(() => null);
|
||
return `/connections?created=${c.id}&check=${checkWord(r)}#c${c.id}`;
|
||
});
|
||
}
|
||
|
||
export async function checkConnectionAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const id = Number(str(f, "connectionId"));
|
||
const r = await checkConnection(db, user.id, id);
|
||
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||
});
|
||
}
|
||
|
||
export async function replaceConnectionSecretAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const id = Number(str(f, "connectionId"));
|
||
const raw = String(f.get("secret") ?? "");
|
||
await replaceConnectionSecret(db, user.id, id, raw.includes("-----BEGIN") ? `${raw.replace(/\r\n/g, "\n").trim()}\n` : raw.trim());
|
||
const r = await checkConnection(db, user.id, id).catch(() => null);
|
||
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||
});
|
||
}
|
||
|
||
export async function resetHostKeyAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const id = Number(str(f, "connectionId"));
|
||
await resetHostKey(db, user.id, id);
|
||
const r = await checkConnection(db, user.id, id).catch(() => null);
|
||
return `/connections?checked=${id}&check=${checkWord(r)}#c${id}`;
|
||
});
|
||
}
|
||
|
||
export async function revokeConnectionAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const id = Number(str(f, "connectionId"));
|
||
const r = await revokeConnection(db, user.id, id);
|
||
// PEP-252: the service didn't confirm the revoke of a sign-in — tell the owner to do it there too.
|
||
if (r.remote === "failed") return `/connections?revoked=${id}&remote=failed#c${id}`;
|
||
});
|
||
}
|
||
|
||
export async function deleteConnectionAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await deleteConnection(db, user.id, Number(str(f, "connectionId")));
|
||
return "/connections";
|
||
});
|
||
}
|
||
|
||
export async function grantConnectionAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const agent = str(f, "agentId");
|
||
const mode = (k: string): GrantMode => (["auto", "ask"].includes(str(f, k)) ? (str(f, k) as GrantMode) : "off");
|
||
await grantConnection(db, user.id, Number(str(f, "connectionId")), { projectId: Number(str(f, "projectId")), agentId: agent ? Number(agent) : null, readMode: mode("readMode"), writeMode: mode("writeMode"), operations: String(f.get("operations") ?? ""), term: isGrantTerm(str(f, "term")) ? (str(f, "term") as GrantTerm) : DEFAULT_GRANT_TERM });
|
||
});
|
||
}
|
||
|
||
/** PEP-259 «Продлить»: the same term again from now. */
|
||
export async function extendGrantAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await extendGrant(db, user.id, Number(str(f, "grantId")));
|
||
});
|
||
}
|
||
|
||
/** PEP-259: the owner's answer to «агенты давно не пользуются — снять?»: «Снять» / «Оставить». */
|
||
export async function decideIdleGrantAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await decideIdleGrant(db, user.id, Number(str(f, "grantId")), str(f, "decision") === "revoke" ? "revoke" : "keep");
|
||
});
|
||
}
|
||
|
||
/** PEP-259: «Спрашивать о разрешении без дела через …» of one connection ("" — platform default). */
|
||
export async function setConnectionIdleAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
const v = str(f, "idleHours");
|
||
await setConnectionIdleHours(db, user.id, Number(str(f, "connectionId")), v === "" ? null : Number(v));
|
||
});
|
||
}
|
||
|
||
export async function revokeGrantAction(f: FormData) {
|
||
const user = asWebActor(await requireUser());
|
||
await attempt(f, async () => {
|
||
await revokeGrant(db, user.id, Number(str(f, "grantId")));
|
||
});
|
||
}
|