185 lines
11 KiB
TypeScript
185 lines
11 KiB
TypeScript
import Link from "next/link";
|
||
import { notFound } from "next/navigation";
|
||
import { ExternalLink, KeyRound } from "lucide-react";
|
||
import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core";
|
||
import type { Translator } from "@peppa/shared/i18n";
|
||
import { AccessStatus, accessModeText } from "@/components/AccessRequests";
|
||
import { Hidden } from "@/components/cards";
|
||
import { Flash, Notice, PageHeader, Section } from "@/components/common";
|
||
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 { connectAccessRequestAction, denyAccessRequestAction, grantAccessRequestAction } from "../../../actions";
|
||
|
||
export async function generateMetadata() {
|
||
const t = await getT();
|
||
return { title: t("Запрос доступа — FORGE") };
|
||
}
|
||
|
||
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
||
|
||
function Fact({ label, children }: { label: string; children: React.ReactNode }) {
|
||
return (
|
||
<div className="flex flex-col gap-0.5 sm:flex-row sm:gap-3">
|
||
<span className="w-32 shrink-0 text-muted-foreground">{label}</span>
|
||
<span className="min-w-0 break-words">{children}</span>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function DoneNotice({ done, check, t }: { done?: string; check?: string; t: Translator }) {
|
||
if (done === "denied") return <Notice>{t("Отказано. Агент получит вашу причину и продолжит без этого сервиса.")}</Notice>;
|
||
if (done !== "granted") return null;
|
||
const tail = check === "bad_key" ? t("Но сервис не принял ключ: замените его в разделе «Подключения».") : check === "down" ? t("Сервис сейчас не отвечает — ключ проверится при первом запросе агента.") : "";
|
||
return (
|
||
<Notice>
|
||
{t("Доступ выдан. Агент получил сообщение и продолжит работу; ключ доступа он не видит.")} {tail}
|
||
</Notice>
|
||
);
|
||
}
|
||
|
||
function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) {
|
||
const back = `/connections/requests/${r.id}`;
|
||
return (
|
||
<ol className="m-0 flex list-decimal flex-col gap-4 pl-5 text-sm">
|
||
<li className="flex flex-col gap-1">
|
||
<span className="font-medium">{t("Возьмите ключ доступа")}</span>
|
||
{card ? (
|
||
<>
|
||
<span className="text-muted-foreground">{t.text(card.keyHint)}</span>
|
||
<a href={card.keyUrl} target="_blank" rel="noreferrer noopener" className="inline-flex items-center gap-1 self-start text-primary underline-offset-2 hover:underline">
|
||
{t("Открыть страницу, где берут ключ")} <ExternalLink className="size-3" />
|
||
</a>
|
||
</>
|
||
) : (
|
||
<span className="text-muted-foreground">{t("Он есть в описании сервиса для разработчиков или у того, кто его сделал.")}</span>
|
||
)}
|
||
</li>
|
||
<li className="flex flex-col gap-2">
|
||
<span className="font-medium">{t("Вставьте его сюда")}</span>
|
||
<form action={connectAccessRequestAction} className="flex max-w-xl flex-col gap-2" autoComplete="off">
|
||
<Hidden fields={{ back, requestId: r.id }} />
|
||
{(!card || card.baseEditable) && <Input name="baseUrl" required type="url" defaultValue={r.host ?? ""} placeholder={card?.baseUrl ?? "https://api.example.com/v1"} aria-label={t("Адрес сервиса")} className="font-mono" spellCheck={false} />}
|
||
<Input name="secret" required type="password" placeholder={card?.auth === "basic" ? t("логин:пароль — после сохранения их не увидит никто") : t("Ключ доступа — после сохранения его не увидит никто")} aria-label={t("Ключ доступа")} autoComplete="new-password" />
|
||
{!card && (
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<select name="authKind" aria-label={t("Как передавать ключ")} className={SELECT} defaultValue="bearer">
|
||
<option value="bearer">{t("Как «Authorization: Bearer …»")}</option>
|
||
<option value="header">{t("В своём заголовке")}</option>
|
||
<option value="query">{t("В адресе запроса (параметр)")}</option>
|
||
<option value="basic">{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>
|
||
</li>
|
||
</ol>
|
||
);
|
||
}
|
||
|
||
function ExistingForm({ r, fit, other, t }: { r: AccessRequestView; fit: ConnectionView[]; other: ConnectionView[]; t: Translator }) {
|
||
const all = [...fit, ...other];
|
||
if (!all.length) return null;
|
||
return (
|
||
<form action={grantAccessRequestAction} className="flex flex-wrap items-center gap-2 text-sm">
|
||
<Hidden fields={{ back: `/connections/requests/${r.id}`, requestId: r.id }} />
|
||
<select name="connectionId" required aria-label={t("Подключение")} className={SELECT} defaultValue={fit[0]?.id ?? ""}>
|
||
{!fit.length && <option value="">{t("Выберите подключение")}</option>}
|
||
{all.map((c) => (
|
||
<option key={c.id} value={c.id}>
|
||
{c.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
<Button size="sm" variant="secondary">{t("Разрешить из уже подключённого")}</Button>
|
||
</form>
|
||
);
|
||
}
|
||
|
||
/** PEP-250: the card of an agent's access request — its project's owner only (others: 404). */
|
||
export default async function AccessRequestPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; done?: string; check?: string }> }) {
|
||
const [{ id }, q] = await Promise.all([params, searchParams]);
|
||
const user = await requireUser();
|
||
const t = await getT();
|
||
const r = /^\d+$/.test(id) ? await accessRequestForUser(db, user.id, Number(id)) : null;
|
||
if (!r) notFound();
|
||
const card = catalogService(r.catalogId);
|
||
const { fit, other } = r.status === "open" ? await connectionsForRequest(db, user.id, r) : { fit: [], other: [] };
|
||
return (
|
||
<Workspace>
|
||
<Flash error={q.error} />
|
||
<DoneNotice done={q.done} check={q.check} t={t} />
|
||
<PageHeader
|
||
title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Агент просит доступ к {service}", { service: r.service })}</>}
|
||
crumbs={<Link href="/connections" className="hover:underline">{t("Подключения")}</Link>}
|
||
>
|
||
<p className="m-0 text-sm text-muted-foreground">
|
||
{r.status === "open"
|
||
? t("Агенту нужен этот сервис для работы над задачей. Ключ доступа вы вводите один раз, агент его не увидит: запросы выполняет FORGE и записывает их в журнал. Можно и отказать — агент продолжит без сервиса.")
|
||
: t("По этому запросу уже есть решение.")}
|
||
</p>
|
||
</PageHeader>
|
||
|
||
<Card className="flex flex-col gap-2 p-4 text-sm">
|
||
<div className="mb-1 flex flex-wrap items-center gap-2">
|
||
<AccessStatus r={r} t={t} />
|
||
{r.repeats > 0 && <span className="text-xs text-muted-foreground">{t("агент просил ещё раз: {n}", { n: r.repeats })}</span>}
|
||
</div>
|
||
<Fact label={t("Агент")}>{r.agentName ?? "—"}</Fact>
|
||
<Fact label={t("Задача")}>{r.taskKey ? <Link href={`/t/${r.taskKey}`} className="text-primary hover:underline">{r.taskKey}{r.taskTitle ? ` — ${r.taskTitle}` : ""}</Link> : "—"}</Fact>
|
||
<Fact label={t("Проект")}>{r.projectName}</Fact>
|
||
<Fact label={t("Сервис")}>
|
||
{r.service}
|
||
{card && (
|
||
<a href={card.docsUrl} target="_blank" rel="noreferrer noopener" className="ml-2 inline-flex items-center gap-1 text-xs text-muted-foreground hover:underline">
|
||
{t("Документация сервиса")} <ExternalLink className="size-3" />
|
||
</a>
|
||
)}
|
||
{!card && r.host && <span className="ml-2 font-mono text-xs text-muted-foreground">{r.host}</span>}
|
||
</Fact>
|
||
<Fact label={t("Что можно")}>{accessModeText(r.mode, t)}</Fact>
|
||
{/* The agent's own words: shown as is, never as instructions. */}
|
||
<Fact label={t("Зачем")}>{r.purpose}</Fact>
|
||
{r.status === "denied" && <Fact label={t("Причина отказа")}>{r.reason ?? t("без причины")}</Fact>}
|
||
</Card>
|
||
|
||
{r.status === "open" && (
|
||
<>
|
||
<Section title={t("Подключить и разрешить")}>
|
||
<Card className="p-4">
|
||
<ConnectForm r={r} card={card} t={t} />
|
||
<p className="m-0 mt-3 text-xs text-muted-foreground">
|
||
{r.mode === "write"
|
||
? t("Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")
|
||
: t("Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")}
|
||
</p>
|
||
</Card>
|
||
</Section>
|
||
{fit.length + other.length > 0 && (
|
||
<Section title={t("Или разрешить из уже подключённого")}>
|
||
<Card className="p-4">
|
||
<ExistingForm r={r} fit={fit} other={other} t={t} />
|
||
</Card>
|
||
</Section>
|
||
)}
|
||
<Section title={t("Отказать")}>
|
||
<Card className="p-4">
|
||
<form action={denyAccessRequestAction} className="flex max-w-xl flex-col gap-2">
|
||
<Hidden fields={{ back: `/connections/requests/${r.id}`, requestId: r.id }} />
|
||
<Textarea name="reason" rows={2} maxLength={500} placeholder={t("Причина — агент её получит, например «используйте тестовые данные»")} aria-label={t("Причина отказа")} />
|
||
<Button size="sm" variant="destructive" className="self-start">{t("Отказать")}</Button>
|
||
</form>
|
||
</Card>
|
||
</Section>
|
||
</>
|
||
)}
|
||
</Workspace>
|
||
);
|
||
}
|