«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя». Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
194 lines
12 KiB
TypeScript
194 lines
12 KiB
TypeScript
import { PlugZap } from "lucide-react";
|
||
import { CONNECTION_REASON_TEXT, connectionJournal, grantableAgents, listConnections, listUserProjects, type ConnectionLogView, type ConnectionReason, type ConnectionView } from "@peppa/core";
|
||
import { Hidden } from "@/components/cards";
|
||
import { ago, 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 { Input, Textarea } from "@/components/ui/input";
|
||
import { Workspace } from "@/components/Workspace";
|
||
import { requireUser } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
import { getT } from "@/lib/i18n";
|
||
import type { Translator } from "@peppa/shared/i18n";
|
||
import { createConnectionAction, deleteConnectionAction, grantConnectionAction, replaceConnectionSecretAction, revokeConnectionAction, revokeGrantAction } from "../actions";
|
||
|
||
export async function generateMetadata() {
|
||
const t = await getT();
|
||
return { title: t("Подключения — FORGE") };
|
||
}
|
||
|
||
type Params = { error?: string; created?: string };
|
||
|
||
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
||
const BACK = "/connections";
|
||
|
||
function Decision({ row, t }: { row: ConnectionLogView; t: Translator }) {
|
||
if (row.decision === "allowed") return <Badge variant="ok">{t("разрешено")}</Badge>;
|
||
if (row.decision === "denied") return <Badge variant="danger">{t("запрещено")}</Badge>;
|
||
return <Badge variant="warn">{t("не выполнено")}</Badge>;
|
||
}
|
||
|
||
const reasonText = (r: string | null, t: Translator) => (r && r in CONNECTION_REASON_TEXT ? t.text(CONNECTION_REASON_TEXT[r as ConnectionReason]) : "");
|
||
|
||
function ConnectionCard({ c, projects, agents, t }: { c: ConnectionView; projects: Array<{ id: number; key: string; name: string }>; agents: Array<{ id: number; name: string }>; t: Translator }) {
|
||
const active = c.status === "active";
|
||
return (
|
||
<Card id={`c${c.id}`} className="flex flex-col gap-4 p-4">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<span className="text-base font-medium">{c.name}</span>
|
||
{active ? <Badge variant="ok">{t("работает")}</Badge> : <Badge variant="danger">{t("доступ отозван")}</Badge>}
|
||
<span className="truncate font-mono text-xs text-muted-foreground">{c.baseUrl}</span>
|
||
<span className="ml-auto text-xs text-muted-foreground">{c.lastUsedAt ? t("последний запрос {ago}", { ago: ago(c.lastUsedAt, t) }) : t("запросов ещё не было")}</span>
|
||
</div>
|
||
|
||
<div className="flex flex-col gap-2">
|
||
<span className="text-sm font-medium">{t("Кому разрешено")}</span>
|
||
{c.grants.length === 0 ? (
|
||
<p className="m-0 text-sm text-muted-foreground">{t("Пока никому: агенты не могут пользоваться этим подключением.")}</p>
|
||
) : (
|
||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||
{c.grants.map((g) => (
|
||
<li key={g.id} className="flex flex-wrap items-center gap-2 rounded-md border bg-background/40 px-2.5 py-1.5">
|
||
<span className="font-medium">{g.projectKey}</span>
|
||
<span>· {g.agentName ? t("агент {name}", { name: g.agentName }) : t("любой агент проекта")}</span>
|
||
<span className="font-mono text-xs text-muted-foreground">{g.operations.join(", ")}</span>
|
||
<form action={revokeGrantAction} className="ml-auto">
|
||
<Hidden fields={{ grantId: g.id, back: BACK }} />
|
||
<Button variant="ghost" size="sm">{t("Убрать")}</Button>
|
||
</form>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
{active && projects.length > 0 && (
|
||
<form action={grantConnectionAction} className="flex flex-col gap-2 rounded-md border border-dashed p-3">
|
||
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||
<div className="flex flex-wrap gap-2">
|
||
<select name="projectId" required aria-label={t("Проект")} className={SELECT}>
|
||
{projects.map((p) => (
|
||
<option key={p.id} value={p.id}>
|
||
{p.key} — {p.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
<select name="agentId" aria-label={t("Агент")} className={SELECT} defaultValue="">
|
||
<option value="">{t("Любой агент проекта")}</option>
|
||
{agents.map((a) => (
|
||
<option key={a.id} value={a.id}>
|
||
{a.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
<Textarea name="operations" required rows={2} placeholder={"GET /items\nPOST /orders"} aria-label={t("Разрешённые операции")} className="font-mono" spellCheck={false} />
|
||
<p className="m-0 text-xs text-muted-foreground">{t("По одной операции в строке: действие (GET — читать, POST — создавать, PUT и PATCH — менять, DELETE — удалять) и начало пути. «GET /items» разрешает читать /items и всё внутри, остальное запрещено.")}</p>
|
||
<Button size="sm" className="self-start">{t("Разрешить")}</Button>
|
||
</form>
|
||
)}
|
||
</div>
|
||
|
||
<div className="flex flex-wrap items-end gap-2 border-t pt-3">
|
||
<form action={replaceConnectionSecretAction} className="flex flex-1 flex-wrap items-center gap-2" autoComplete="off">
|
||
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||
<Input name="secret" type="password" required placeholder={active ? t("Новый ключ доступа") : t("Новый ключ доступа, чтобы включить снова")} aria-label={t("Новый ключ доступа")} className="max-w-xs" autoComplete="new-password" />
|
||
<Button size="sm" variant="secondary">{active ? t("Заменить ключ") : t("Включить снова")}</Button>
|
||
</form>
|
||
{active && (
|
||
<form action={revokeConnectionAction}>
|
||
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||
<Button size="sm" variant="destructive">{t("Отозвать доступ")}</Button>
|
||
</form>
|
||
)}
|
||
<form action={deleteConnectionAction}>
|
||
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||
<Button size="sm" variant="ghost">{t("Удалить")}</Button>
|
||
</form>
|
||
</div>
|
||
</Card>
|
||
);
|
||
}
|
||
|
||
/** PEP-234 Access Hub: «Подключения» — the user's own external services and who may use them. */
|
||
export default async function ConnectionsPage({ searchParams }: { searchParams: Promise<Params> }) {
|
||
const q = await searchParams;
|
||
const user = await requireUser();
|
||
const t = await getT();
|
||
const [list, journal, projects, agents] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db)]);
|
||
return (
|
||
<Workspace>
|
||
<Flash error={q.error} />
|
||
{q.created && <Notice>{t("Подключение сохранено. Ключ доступа больше не показывается никому. Теперь разрешите нужным агентам операции.")}</Notice>}
|
||
<PageHeader title={<><PlugZap className="mr-1 inline size-5 text-primary" />{t("Подключения")}</>}>
|
||
<p className="m-0 text-sm text-muted-foreground">
|
||
{t("Подключите свои сервисы и решите, какие агенты и что в них могут делать. Агенты не видят ключ доступа: запросы выполняет FORGE и записывает их в журнал. Без вашего разрешения агент ничего не сделает, а «Отозвать доступ» действует сразу.")}
|
||
</p>
|
||
</PageHeader>
|
||
|
||
<Section title={t("Ваши подключения")} count={list.length}>
|
||
{list.length === 0 ? <Empty>{t("Подключений пока нет.")}</Empty> : list.map((c) => <ConnectionCard key={c.id} c={c} projects={projects} agents={agents} t={t} />)}
|
||
</Section>
|
||
|
||
<Section title={t("Подключить сервис")}>
|
||
<Card className="p-4">
|
||
<form action={createConnectionAction} className="flex max-w-xl flex-col gap-2" autoComplete="off">
|
||
<Hidden fields={{ back: BACK }} />
|
||
<Input name="name" required maxLength={60} placeholder={t("Название, например «Магазин»")} aria-label={t("Название")} />
|
||
<Input name="baseUrl" required type="url" placeholder="https://api.example.com/v1" aria-label={t("Адрес сервиса")} className="font-mono" spellCheck={false} />
|
||
<Input name="secret" required type="password" placeholder={t("Ключ доступа — после сохранения его не увидит никто")} aria-label={t("Ключ доступа")} autoComplete="new-password" />
|
||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||
<select name="authKind" aria-label={t("Как передавать ключ")} className={SELECT} defaultValue="bearer">
|
||
<option value="bearer">{t("Как «Authorization: Bearer …»")}</option>
|
||
<option value="header">{t("В своём заголовке")}</option>
|
||
</select>
|
||
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка")} className="max-w-48 font-mono" spellCheck={false} />
|
||
</div>
|
||
<Button size="sm" className="self-start">{t("Подключить")}</Button>
|
||
</form>
|
||
</Card>
|
||
</Section>
|
||
|
||
<Section title={t("Журнал запросов")} count={journal.length}>
|
||
{journal.length === 0 ? (
|
||
<Empty>{t("Агенты ещё не обращались к вашим подключениям.")}</Empty>
|
||
) : (
|
||
<div className="overflow-x-auto">
|
||
<table className="w-full text-sm">
|
||
<thead className="text-left text-xs text-muted-foreground">
|
||
<tr>
|
||
<th className="py-1 pr-3 font-normal">{t("Когда")}</th>
|
||
<th className="py-1 pr-3 font-normal">{t("Подключение")}</th>
|
||
<th className="py-1 pr-3 font-normal">{t("Проект и агент")}</th>
|
||
<th className="py-1 pr-3 font-normal">{t("Операция")}</th>
|
||
<th className="py-1 font-normal">{t("Решение")}</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{journal.map((r) => (
|
||
<tr key={r.id} className="border-t align-top">
|
||
<td className="py-1.5 pr-3 whitespace-nowrap text-muted-foreground">{ago(r.createdAt, t)}</td>
|
||
<td className="py-1.5 pr-3">{r.connectionName}</td>
|
||
<td className="py-1.5 pr-3">
|
||
{r.projectKey ?? "—"}
|
||
{r.agentName ? ` · ${r.agentName}` : ""}
|
||
</td>
|
||
<td className="py-1.5 pr-3 font-mono text-xs">
|
||
{r.method} {r.path}
|
||
</td>
|
||
<td className="py-1.5">
|
||
<span className="flex flex-wrap items-center gap-1.5">
|
||
<Decision row={r} t={t} />
|
||
<span className="text-xs text-muted-foreground">{reasonText(r.reason, t)}</span>
|
||
</span>
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
)}
|
||
</Section>
|
||
</Workspace>
|
||
);
|
||
}
|