209 lines
11 KiB
TypeScript
209 lines
11 KiB
TypeScript
import { notFound } from "next/navigation";
|
||
import { ShieldCheck } from "lucide-react";
|
||
import { isSuperadmin, secretsAudit, type PlatformSecretRow } from "@peppa/core";
|
||
import { Hidden } from "@/components/cards";
|
||
import { Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Card } from "@/components/ui/card";
|
||
import { Workspace } from "@/components/Workspace";
|
||
import { requireUser } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
import { getT } from "@/lib/i18n";
|
||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||
import { checkGiteaTokenAction, markSecretRotatedAction, reencryptSecretsAction, revokeClientTokensAction } from "../actions";
|
||
|
||
export async function generateMetadata() {
|
||
const t = await getT();
|
||
return { title: t("Секреты — Peppa FACTORY") };
|
||
}
|
||
|
||
type Params = { error?: string; reencrypted?: string; unreadable?: string; revoked?: string; gitea?: string };
|
||
|
||
const day = (d: Date | null, t: Translator) => (d ? d.toLocaleDateString(intlLocale(t.locale)) : "—");
|
||
|
||
function State({ r, t }: { r: PlatformSecretRow; t: Translator }) {
|
||
if (r.set === null) return <Badge variant="secondary">{t("вне .env")}</Badge>;
|
||
if (!r.set) return r.optional ? <Badge variant="secondary">{t("не задан")}</Badge> : <Badge variant="danger">{t("не задан")}</Badge>;
|
||
return <Badge variant="ok">{t("задан")}</Badge>;
|
||
}
|
||
|
||
function Age({ r, t }: { r: PlatformSecretRow; t: Translator }) {
|
||
if (r.ageDays === null) return <Badge variant="warn">{t("возраст неизвестен")}</Badge>;
|
||
return r.stale ? <Badge variant="warn">{t("{n} дн. — пора ротировать", { n: r.ageDays })}</Badge> : <Badge variant="info">{t("{n} дн.", { n: r.ageDays })}</Badge>;
|
||
}
|
||
|
||
/** Inline `code` in instruction steps. */
|
||
function Step({ text }: { text: string }) {
|
||
return (
|
||
<>
|
||
{text.split(/(`[^`]+`)/).map((part, i) =>
|
||
part.startsWith("`") ? (
|
||
<code key={i} className="rounded bg-muted px-1 font-mono text-[12px]">
|
||
{part.slice(1, -1)}
|
||
</code>
|
||
) : (
|
||
part
|
||
),
|
||
)}
|
||
</>
|
||
);
|
||
}
|
||
|
||
export default async function Secrets({ searchParams }: { searchParams: Promise<Params> }) {
|
||
const user = await requireUser();
|
||
const t = await getT();
|
||
if (!(await isSuperadmin(db, user))) notFound();
|
||
const q = await searchParams;
|
||
const a = await secretsAudit(db);
|
||
const enc = a.encryption;
|
||
// The link sits inside the sentence: split the translated text around {link}.
|
||
const reissue = t("Перевыпуск — в {link}: «Переподключить» запускает новый вход, старый токен Claude отзывается в claude.ai → Settings → Claude Code.").split("{link}");
|
||
|
||
return (
|
||
<Workspace>
|
||
<div className="max-w-3xl">
|
||
<Flash error={q.error} />
|
||
<PageHeader title={<><ShieldCheck className="mr-1 inline size-5 text-primary" />{t("Секреты")}</>}>
|
||
{t("Ревизия секретов и доступов платформы: что задано, сколько лет каждому секрету, кто им пользуется и как его сменить. Значения здесь не показываются никогда. Раздел видят только суперадмины.")}
|
||
</PageHeader>
|
||
{q.reencrypted !== undefined && (
|
||
<Notice>
|
||
{t("Перешифровано: {n}", { n: q.reencrypted })}
|
||
{Number(q.unreadable) > 0 ? " · " + t("не читается ни одним ключом: {n}", { n: q.unreadable }) : ""}
|
||
</Notice>
|
||
)}
|
||
{q.revoked !== undefined && <Notice>{t("Отозвано токенов: {n}", { n: q.revoked })}</Notice>}
|
||
{q.gitea && <Notice>{q.gitea.startsWith("ok:") ? t("GITEA_TOKEN принадлежит {login}, админских прав нет", { login: q.gitea.slice(3) }) : `GITEA_TOKEN: ${t.text(q.gitea)}`}</Notice>}
|
||
|
||
<Section title={t("Ключ шифрования")}>
|
||
<Card className="flex flex-col gap-2 p-4 text-sm">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
{!enc.configured ? <Badge variant="danger">{t("PEPPA_SECRET не задан")}</Badge> : enc.rotating ? <Badge variant="warn">{t("идёт смена ключа")}</Badge> : <Badge variant="ok">{t("один ключ")}</Badge>}
|
||
<span>{t("на старом ключе: {n}", { n: enc.previous })}</span>
|
||
<span>· {t("не читается: {n}", { n: enc.unreadable })}</span>
|
||
</div>
|
||
<ul className="m-0 flex list-none flex-col gap-0.5 p-0 text-xs text-muted-foreground">
|
||
{enc.columns.filter((c) => c.total).map((c) => (
|
||
<li key={`${c.table}.${c.column}`} className="font-mono">
|
||
{c.table}.{c.column}: {t("{total} · текущий {current} · старый {previous} · не читается {unreadable}", { total: c.total, current: c.current, previous: c.previous, unreadable: c.unreadable })}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
<form action={reencryptSecretsAction}>
|
||
<Hidden fields={{ back: "/secrets" }} />
|
||
<Button size="sm" variant={enc.previous ? "default" : "outline"} disabled={!enc.configured}>
|
||
{t("Перешифровать текущим ключом")}
|
||
</Button>
|
||
</form>
|
||
</Card>
|
||
</Section>
|
||
|
||
<Section title={t("Секреты платформы")} count={a.platform.length}>
|
||
{a.platform.map((r) => (
|
||
<Card key={r.name} className="flex flex-col gap-2 p-4">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<span className="font-mono text-sm font-medium">{r.name}</span>
|
||
<State r={r} t={t} />
|
||
<Age r={r} t={t} />
|
||
<Badge variant="secondary">{r.how === "peppa" ? t("ротирует Peppa FACTORY") : t("вручную")}</Badge>
|
||
</div>
|
||
<p className="m-0 text-sm">{t.text(r.label)}</p>
|
||
<p className="m-0 text-xs text-muted-foreground">
|
||
{t("Использует: {who}", { who: t.text(r.usedBy) })}
|
||
{r.rotatedAt ? " · " + (r.rotatedBy ? t("последняя ротация {date} ({by})", { date: day(r.rotatedAt, t), by: r.rotatedBy }) : t("последняя ротация {date}", { date: day(r.rotatedAt, t) })) : ""}
|
||
</p>
|
||
<Disclosure summary={t("Как ротировать")}>
|
||
<ol className="m-0 flex flex-col gap-1 pl-5 text-sm">
|
||
{r.steps.map((s, i) => (
|
||
<li key={i}>
|
||
<Step text={t.text(s)} />
|
||
</li>
|
||
))}
|
||
</ol>
|
||
</Disclosure>
|
||
<div className="flex flex-wrap gap-2">
|
||
{r.how === "external" && (
|
||
<form action={markSecretRotatedAction}>
|
||
<Hidden fields={{ name: r.name, back: "/secrets" }} />
|
||
<Button size="sm" variant="outline">{t("Отметить: ротирован сегодня")}</Button>
|
||
</form>
|
||
)}
|
||
{r.name === "GITEA_TOKEN" && (
|
||
<form action={checkGiteaTokenAction}>
|
||
<Hidden fields={{ back: "/secrets" }} />
|
||
<Button size="sm" variant="outline">{t("Проверить токен Gitea")}</Button>
|
||
</form>
|
||
)}
|
||
</div>
|
||
</Card>
|
||
))}
|
||
</Section>
|
||
|
||
<Section title={t("MCP-клиенты (OAuth)")} count={a.oauth.length}>
|
||
{a.oauth.length === 0 ? (
|
||
<Empty>{t("Живых MCP-токенов нет.")}</Empty>
|
||
) : (
|
||
a.oauth.map((c) => (
|
||
<Card key={c.clientId} className="flex flex-wrap items-center gap-2 p-3 text-sm">
|
||
<span className="font-medium">{c.name}</span>
|
||
<span className="text-xs text-muted-foreground">
|
||
{t("токенов {tokens} · людей {users} · старейший {oldest} · использован {used}", { tokens: c.liveTokens, users: c.users, oldest: day(c.oldestAt, t), used: day(c.lastUsedAt, t) })}
|
||
{c.beforeKeyRotation ? " · " + t("выданы до смены ключа: {n}", { n: c.beforeKeyRotation }) : ""}
|
||
</span>
|
||
<form action={revokeClientTokensAction} className="ml-auto">
|
||
<Hidden fields={{ clientId: c.clientId, back: "/secrets" }} />
|
||
<Button size="sm" variant="outline">{t("Отозвать все токены")}</Button>
|
||
</form>
|
||
</Card>
|
||
))
|
||
)}
|
||
<p className="m-0 text-xs text-muted-foreground">{t("Пользователи отзывают свои подключения сами в «Настройках»; OAuth Gitea у пользователей: {n} (истекли {expired}) — обновляются при входе.", { n: a.gitea.usersWithToken, expired: a.gitea.expired })}</p>
|
||
</Section>
|
||
|
||
<Section title={t("Подписки агентов")} count={a.subscriptions.length}>
|
||
{a.subscriptions.length === 0 ? (
|
||
<Empty>{t("Подписок нет.")}</Empty>
|
||
) : (
|
||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||
{a.subscriptions.map((s) => (
|
||
<li key={s.id} className="flex flex-wrap items-center gap-2 rounded-md border px-3 py-2">
|
||
<span className="font-medium">{s.name}</span>
|
||
<span className="text-xs text-muted-foreground">
|
||
{s.provider} · {s.status} · {t("сессий {n} · пулы: {pools}", { n: s.liveSessions, pools: s.pools.join(", ") || "—" })}
|
||
</span>
|
||
{s.stale ? <Badge variant="warn">{t("{n} дн. — перевыпустить", { n: s.ageDays })}</Badge> : <Badge variant="info">{t("{n} дн.", { n: s.ageDays })}</Badge>}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
<p className="m-0 text-xs text-muted-foreground">
|
||
{reissue[0]}
|
||
<a href="/subscriptions">{t("«Подписках»")}</a>
|
||
{reissue[1]}
|
||
</p>
|
||
</Section>
|
||
|
||
<Section title={t("Секреты проектов")} count={a.projects.length}>
|
||
{a.projects.length === 0 ? (
|
||
<Empty>{t("Ни в одном проекте секретов нет.")}</Empty>
|
||
) : (
|
||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||
{a.projects.map((p) => (
|
||
<li key={p.projectId} className="flex flex-wrap items-center gap-2 rounded-md border px-3 py-2">
|
||
<a href={`/p/${p.key}`} className="font-mono font-medium">
|
||
{p.key}
|
||
</a>
|
||
<span className="text-xs text-muted-foreground">
|
||
{t("секретов {n} · старейший {oldest} · выдан агенту {used}", { n: p.secrets, oldest: day(p.oldestAt, t), used: day(p.lastUsedAt, t) })}
|
||
</span>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
</Section>
|
||
</div>
|
||
</Workspace>
|
||
);
|
||
}
|