import Link from "next/link"; import { ExternalLink, PlugZap, Search } from "lucide-react"; import { CATALOG_KIND_TEXT, CATALOG_KINDS, catalogService, CONNECTION_CHECK_TEXT, CONNECTION_REASON_TEXT, connectionJournal, DEFAULT_GRANT_TERM, defaultIdleRevokeHours, GRANT_TERM_TEXT, GRANT_TERMS, IDLE_HOURS_CHOICES, serverTimezone, JOURNAL_VERIFY_SCRIPT, grantableAgents, listConnections, listUserProjects, oauthOffer, scopeLabel, searchCatalog, type CatalogKind, type CatalogService, type ConnectionGrantView, type ConnectionLogView, type ConnectionReason, type ConnectionView, type GrantMode, type GatewayProtocol, GATEWAY_PROTOCOLS, } from "@peppa/core"; import { Hidden } from "@/components/cards"; import { intlLocale } from "@peppa/shared/i18n"; 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, uiMode } from "@/lib/auth"; import { db } from "@/lib/db"; import { getT } from "@/lib/i18n"; import { m, type Translator } from "@peppa/shared/i18n"; import { checkConnectionAction, createConnectionAction, decideIdleGrantAction, deleteConnectionAction, extendGrantAction, grantConnectionAction, replaceConnectionSecretAction, resetHostKeyAction, revokeConnectionAction, revokeGrantAction, setConnectionIdleAction } from "../actions"; export async function generateMetadata() { const t = await getT(); return { title: t("Подключения — FORGE") }; } type Params = { error?: string; created?: string; checked?: string; check?: string; signed?: string; revoked?: string; remote?: string; service?: string; q?: string; kind?: 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 }) { // PEP-254: the call is written before the service answers; no result after a while — a crash in the middle. if (row.state === "running") return {t("выполняется")}; if (row.state === "unfinished") return {t("начато, итога нет")}; if (row.decision === "allowed") return {t("разрешено")}; if (row.decision === "denied") return {t("запрещено")}; return {t("не выполнено")}; } const reasonText = (r: string | null, t: Translator) => (r && r in CONNECTION_REASON_TEXT ? t.text(CONNECTION_REASON_TEXT[r as ConnectionReason]) : ""); const kindText = (k: CatalogKind, t: Translator) => t.text(CATALOG_KIND_TEXT[k]); /** «ключ работает» / «ключ не подходит» / «сервис не отвечает» / «ещё не проверялся». */ function KeyState({ c, t }: { c: ConnectionView; t: Translator }) { if (c.status === "relogin") return {t("нужно войти заново")}; if (c.status !== "active") return {t("доступ отозван")}; // PEP-252: a sign-in connection has no key to speak of. if (c.authKind === "oauth") { if (!c.checkStatus) return {t("вход ещё не проверялся")}; return c.checkStatus === "ok" ? {t("вход работает")} : c.checkStatus === "bad_key" ? {t("сервис не пускает FORGE")} : {t.text(CONNECTION_CHECK_TEXT.down)}; } if (!c.checkStatus) return {t("ключ ещё не проверялся")}; const text = t.text(CONNECTION_CHECK_TEXT[c.checkStatus]); return {text}; } function modeText(m: GrantMode, t: Translator): string { return m === "auto" ? t("сразу") : m === "ask" ? t("спрашивать меня") : t("нет"); } /** «14:05 25.11» in the platform's time zone. */ function when(d: Date, t: Translator): string { const loc = intlLocale(t.locale); const tz = serverTimezone(); return `${d.toLocaleTimeString(loc, { hour: "2-digit", minute: "2-digit", timeZone: tz })} ${d.toLocaleDateString(loc, { day: "2-digit", month: "2-digit", timeZone: tz })}`; } /** «5 ч» / «2 дн» — how soon the owner is asked about a grant without calls. */ function hoursLeft(d: Date, t: Translator): string { const h = Math.max(0, Math.ceil((d.getTime() - Date.now()) / 3600_000)); return h < 48 ? t("{n} ч", { n: h }) : t("{n} дн", { n: Math.round(h / 24) }); } function GrantLine({ g, engineer, t }: { g: ConnectionGrantView; engineer: boolean; t: Translator }) { const ended = g.state !== "active"; return (
  • {g.projectKey} · {g.agentName ? t("агент {name}", { name: g.agentName }) : t("любой агент проекта")} · {t("чтение: {mode}", { mode: modeText(g.readMode, t) })} · {t("запись: {mode}", { mode: modeText(g.writeMode, t) })} {g.state === "expired" && {t("срок истёк")}} {g.state === "idle" && {t("снято: {n} ч без дела", { n: g.idleHours })}} {g.idleAskedAt && {t("не используется {n} ч — снять?", { n: g.idleHours })}} {engineer && g.operations.length > 0 && {g.operations.join(", ")}}
    {g.idleAskedAt && ( <>
    )} {(ended || g.term !== "forever") && (
    )}
    {!ended && {g.expiresAt ? t("до {when}", { when: when(g.expiresAt, t) }) : t("до отзыва")}} {g.state === "expired" && g.expiresAt && {t("действовало до {when}", { when: when(g.expiresAt, t) })}} {g.state === "idle" && g.endedAt && {t("снято {ago}", { ago: ago(g.endedAt, t) })}} {g.lastUsedAt ? t("последний вызов {ago}", { ago: ago(g.lastUsedAt, t) }) : t("вызовов ещё не было")} {g.idleAskAt && {t("спросим вас о снятии через {left} без дела", { left: hoursLeft(g.idleAskAt, t) })}}
  • ); } function TermSelect({ t }: { t: Translator }) { return ( ); } function idleText(h: number, t: Translator): string { return h === 0 ? t("не спрашивать") : h % 24 === 0 && h >= 48 ? t("{n} дн без дела", { n: h / 24 }) : t("{n} ч без дела", { n: h }); } /** PEP-259: «Спрашивать, снять ли разрешение без дела, через …» of one connection. */ function IdleForm({ c, t }: { c: ConnectionView; t: Translator }) { const def = defaultIdleRevokeHours(); return (
    {t("Спрашивать, снять ли разрешение, которым не пользуются:")} ); } function ModeSelect({ name, label, def, t }: { name: string; label: string; def: GrantMode; t: Translator }) { return ( ); } function GrantForm({ c, projects, agents, engineer, t }: { c: ConnectionView; projects: Array<{ id: number; key: string; name: string }>; agents: Array<{ id: number; name: string }>; engineer: boolean; t: Translator }) { return (
    {/* PEP-251: changing a database and sending letters ask the owner by default. */}

    {c.protocol === "http" ? t("Чтение — смотреть данные, ничего не меняя. Запись — создавать, менять, удалять и отправлять. «Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.") : t.text(PROTOCOL_TEXT[c.protocol as GatewayProtocol].modes)} {c.protocol !== "http" && <> {t("«Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.")}}

    {engineer && c.protocol === "http" && (
    {t("Тонкая настройка")}