peppa/apps/web/app/(app)/settings/page.tsx
Асель 9149c75840 PEP-19/54: project secrets for agents, secrets audit and two-key PEPPA_SECRET rotation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:19:57 +05:00

279 lines
15 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.

import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, MIN_PASSWORD, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { Hidden } from "@/components/cards";
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
import { EgovSign } from "@/components/EgovSign";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { changePasswordAction, pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unlinkEgov, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
import { TimezoneField } from "@/components/TimezoneField";
const back = { back: "/settings" };
/** A connected thing: title + details on the left, actions on the right. */
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
return (
<Card className="flex-row flex-wrap items-center gap-3">
<div className="min-w-0 flex-[1_1_16rem]">
<div className="font-medium">{title}</div>
{children && <div className="text-sm text-muted-foreground">{children}</div>}
</div>
{actions && <div className="flex gap-2">{actions}</div>}
</Card>
);
}
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; password?: string; notify?: string }> }) {
const user = await requireUser();
const { error, egov, password, notify } = await searchParams;
const local = isLocalUser(user);
const superadmin = await isSuperadmin(db, user);
const apps = await connectedApps(db, user.id);
const origin = await publicOrigin();
const prefs = await getNotifyPrefs(db, user.id);
const myProjects = await listUserProjects(db, user.id);
const pushSubs = await userPushSubscriptions(db, user.id);
const vapid = await vapidPublicKey(db);
return (
<Workspace>
<div className="max-w-2xl">
<Flash error={error} />
<PageHeader title="Настройки" />
<Section title="Учётная запись">
{password === "changed" && <Notice>Пароль изменён</Notice>}
{local ? (
<Card>
<p className="m-0 text-sm">
<span className="font-mono">{user.login}</span> — локальный пользователь Пеппы, <b>нет аккаунта Gitea</b>. Доступ к коду проектов — только через Пеппу
(агенты, PR, проверки); соавтором репозитория в Gitea вас добавить нельзя, новые проекты создаются в пространстве{" "}
<span className="font-mono">peppa-bot</span>.
</p>
<form action={changePasswordAction} className="flex flex-col gap-3" aria-label="Смена пароля">
<Hidden fields={back} />
<input type="text" name="username" value={user.login} autoComplete="username" readOnly hidden />
<div className="flex flex-wrap gap-3">
<Label className="min-w-40 flex-1">
Текущий пароль
<Input name="current" type="password" required autoComplete="current-password" />
</Label>
<Label className="min-w-40 flex-1">
Новый пароль
<Input name="newPassword" type="password" required minLength={MIN_PASSWORD} autoComplete="new-password" />
</Label>
<Label className="min-w-40 flex-1">
Повтор
<Input name="confirm" type="password" required minLength={MIN_PASSWORD} autoComplete="new-password" />
</Label>
</div>
<Button variant="default" className="self-start">Сменить пароль</Button>
</form>
</Card>
) : (
<Row title={`Gitea: ${user.login}`}>Вы входите через Gitea{user.egovIin ? " или eGov" : ""}; пароль Пеппы не нужен.</Row>
)}
{superadmin && (
<Row
title="Суперадмин"
actions={
<>
<Button asChild size="sm">
<a href="/users">Пользователи</a>
</Button>
<Button asChild size="sm">
<a href="/subscriptions">Подписки</a>
</Button>
<Button asChild size="sm">
<a href="/secrets">Секреты</a>
</Button>
<Button asChild size="sm">
<a href="/journal">Журнал</a>
</Button>
</>
}
>
Локальные пользователи без Gitea: создать, сбросить пароль, отключить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.
</Row>
)}
</Section>
<Section title="Агенты">
<p className="m-0 text-sm text-muted-foreground">
Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок.
</p>
</Section>
<Section title="eGov">
{egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
{user.egovIin ? (
<Card>
<p className="m-0 text-sm">
Привязан ИИН <span className="font-mono">{maskIin(user.egovIin)}</span> — на странице входа можно войти через eGov QR.
</p>
<form action={unlinkEgov}>
<Hidden fields={back} />
<Button variant="destructive" size="sm">Отвязать</Button>
</form>
</Card>
) : (
<Card>
<p className="m-0 text-sm">Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. После этого можно входить в Пеппу через eGov.</p>
<div className="max-w-xs">
<EgovSign purpose="link" label="Привязать eGov" />
</div>
</Card>
)}
</Section>
<Section title="Telegram">
{user.telegramChatId ? (
<Row
title={`Telegram привязан${user.telegramUsername ? ` (@${user.telegramUsername})` : ""}`}
actions={
<form action={unpairTelegramAction}>
<Hidden fields={back} />
<Button size="sm" variant="destructive">Отвязать</Button>
</form>
}
>
Вопросы агентов из ваших и общих проектов приходят в этот чат.
</Row>
) : (
<Row
title="Telegram не привязан"
actions={
<form action={pairTelegram}>
<Hidden fields={back} />
<Button variant="default" size="sm">Привязать Telegram</Button>
</form>
}
>
Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
</Row>
)}
</Section>
<Section title="Уведомления" id="notifications">
{notify === "saved" && <Notice>Настройки уведомлений сохранены</Notice>}
<Card>
<div className="flex flex-col gap-1">
<div className="font-medium">Браузер</div>
<p className="m-0 text-sm text-muted-foreground">
Push приходят и при закрытой вкладке; клик открывает стори или проект. Подписано браузеров: {pushSubs.length}. Пеппу можно установить как приложение (Chrome → «Установить»).
</p>
</div>
<PushNotifications vapidKey={vapid} known={pushSubs.map((s) => s.endpoint)} />
</Card>
<form action={saveNotifyPrefsAction} className="flex flex-col gap-4" aria-label="Настройки уведомлений">
<Hidden fields={back} />
<Card className="gap-0 p-0">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="px-4 py-2 font-normal">Событие</th>
<th className="w-24 px-2 py-2 text-center font-normal">Telegram</th>
<th className="w-24 px-2 py-2 text-center font-normal">Браузер</th>
</tr>
</thead>
<tbody>
{NOTIFY_EVENTS.filter((e) => e !== "monitoring" || superadmin).map((e) => (
<tr key={e} className="border-b last:border-0">
<td className="px-4 py-2">{NOTIFY_EVENT_NAMES[e]}</td>
<td className="px-2 py-2 text-center">
<input type="checkbox" name={`${e}.telegram`} defaultChecked={prefs.events[e].telegram} aria-label={`${NOTIFY_EVENT_NAMES[e]} — Telegram`} className="size-4 accent-primary" />
</td>
<td className="px-2 py-2 text-center">
<input type="checkbox" name={`${e}.push`} defaultChecked={prefs.events[e].push} aria-label={`${NOTIFY_EVENT_NAMES[e]} — браузер`} className="size-4 accent-primary" />
</td>
</tr>
))}
</tbody>
</table>
{!superadmin && (
<>
<input type="hidden" name="monitoring.telegram" value={prefs.events.monitoring.telegram ? "on" : ""} />
<input type="hidden" name="monitoring.push" value={prefs.events.monitoring.push ? "on" : ""} />
</>
)}
</Card>
<Card>
<label className="flex items-center gap-2 text-sm font-medium">
<input type="checkbox" name="quietOn" defaultChecked={!!prefs.quiet} className="size-4 accent-primary" />
Тихие часы
</label>
<div className="flex flex-wrap items-end gap-3">
<Label className="w-32">
С
<Input type="time" name="quietFrom" defaultValue={prefs.quiet?.from ?? "23:00"} />
</Label>
<Label className="w-32">
До
<Input type="time" name="quietTo" defaultValue={prefs.quiet?.to ?? "08:00"} />
</Label>
</div>
<p className="m-0 text-sm text-muted-foreground">В тихие часы Telegram приходит без звука, push в браузер не показываются. Дайджест приходит в своё время.</p>
<div className="flex flex-wrap items-end gap-3">
<Label className="w-32">
Дайджест в
<Input type="time" name="digestTime" defaultValue={prefs.digestTime} />
</Label>
<TimezoneField value={prefs.timezone} />
</div>
<p className="m-0 text-sm text-muted-foreground">
Сводка за сутки по вашим проектам: сделано, в работе, на ревью, ждёт вас, зависло, лимиты. Пустая не приходит. В боте — команда /digest.
</p>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="sound" defaultChecked={prefs.sound} className="size-4 accent-primary" />
Звук: сигнал в открытой вкладке при новом вопросе и звук у push
</label>
</Card>
{myProjects.length > 0 && (
<Card>
<div className="text-sm font-medium">Проекты</div>
<p className="m-0 text-sm text-muted-foreground">Из снятых проектов уведомления не приходят (вопросы остаются в вебе).</p>
<div className="flex flex-wrap gap-x-5 gap-y-2">
{myProjects.map((p) => (
<label key={p.id} className="flex items-center gap-2 text-sm">
<input type="hidden" name="projectShown" value={p.id} />
<input type="checkbox" name="project" value={p.id} defaultChecked={!prefs.mutedProjects.includes(p.id)} className="size-4 accent-primary" />
{p.name} <span className="font-mono text-xs text-muted-foreground">{p.key}</span>
</label>
))}
</div>
</Card>
)}
<Button variant="default" className="self-start">Сохранить уведомления</Button>
</form>
</Section>
<Section title="MCP для ChatGPT и других клиентов">
<p className="m-0 text-sm">Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 font-mono text-sm">{origin}/mcp</code>
<p className="m-0 text-sm text-muted-foreground">
Как подключить и что спрашивать — в <a href="/help" className="text-primary">Помощи</a>.
</p>
</Section>
<Section title="Подключённые приложения">
{apps.length === 0 ? (
<Empty>Нет подключённых приложений.</Empty>
) : (
apps.map((a) => (
<Row
key={a.clientId}
title={a.name}
actions={
<form action={revokeConnectedApp}>
<Hidden fields={{ clientId: a.clientId, ...back }} />
<Button size="sm" variant="destructive">Отозвать</Button>
</form>
}
>
с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
</Row>
))
)}
</Section>
</div>
</Workspace>
);
}