PEP-253: веб — кому идёт секрет, «Сделать подключением», настройка проекта, отчёт суперадмину; MCP, CLI
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e8a651a3b8
commit
ce706efb18
@ -55,6 +55,9 @@ import {
|
|||||||
setTaskBudget,
|
setTaskBudget,
|
||||||
type Budget,
|
type Budget,
|
||||||
setProjectSecret,
|
setProjectSecret,
|
||||||
|
setSecretAudience,
|
||||||
|
secretToConnection,
|
||||||
|
setAgentSecretsEnabled,
|
||||||
setNeedDone,
|
setNeedDone,
|
||||||
removeNeed,
|
removeNeed,
|
||||||
deleteProjectSecret,
|
deleteProjectSecret,
|
||||||
@ -801,7 +804,32 @@ export async function saveProjectSecretAction(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
// The value is taken as is (no trim): keys may legitimately end with spaces/newlines.
|
// The value is taken as is (no trim): keys may legitimately end with spaces/newlines.
|
||||||
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""));
|
// PEP-253: «Кому» — only the product by default.
|
||||||
|
await setProjectSecret(db, user.id, Number(str(f, "projectId")), str(f, "name"), String(f.get("value") ?? ""), { agent: str(f, "audience") === "agent" });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// PEP-253: «только продукту» ⇄ «агенту и продукту».
|
||||||
|
export async function setSecretAudienceAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await setSecretAudience(db, user.id, Number(str(f, "projectId")), str(f, "name"), str(f, "audience") === "agent");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// PEP-253: «Сделать подключением» — a catalog connection with the secret's key, granted to the project.
|
||||||
|
export async function secretToConnectionAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await secretToConnection(db, user.id, Number(str(f, "projectId")), str(f, "name"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// PEP-253: «Агенты получают секреты в окружение».
|
||||||
|
export async function setAgentSecretsAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await setAgentSecretsEnabled(db, user.id, Number(str(f, "projectId")), str(f, "on") === "1");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -5,7 +5,7 @@ import { PublishPanel } from "@/components/PublishPanel";
|
|||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||||
import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
|
import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
|
||||||
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, agentSecretsEnabled, secretsAgentReport, secretNameHints, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||||
import { productNeeds, lastProductReview } from "@peppa/core";
|
import { productNeeds, lastProductReview } from "@peppa/core";
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
import { PanelSection } from "@/components/ActivityAside";
|
import { PanelSection } from "@/components/ActivityAside";
|
||||||
@ -132,6 +132,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
const [pool, pools, autonomy, shared] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id), sharedPool(db)]);
|
const [pool, pools, autonomy, shared] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id), sharedPool(db)]);
|
||||||
// PEP-10/27: runner settings of the project over the system ones.
|
// PEP-10/27: runner settings of the project over the system ones.
|
||||||
const [runnerOwn, runnerSystem, secrets, runnerHosts] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id), listHosts(db, { enabled: true })]);
|
const [runnerOwn, runnerSystem, secrets, runnerHosts] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id), listHosts(db, { enabled: true })]);
|
||||||
|
// PEP-253: where secrets go and which of them are keys of catalog services.
|
||||||
|
const [agentSecrets, secretReport] = await Promise.all([agentSecretsEnabled(db, p.id), secretsAgentReport(db, { projectIds: [p.id] })]);
|
||||||
// PEP-41: agent provider/model of the project over the platform's.
|
// PEP-41: agent provider/model of the project over the platform's.
|
||||||
const [agentOwn, agentSystem] = await Promise.all([getProjectAgentSettings(db, p.id), getSystemAgentSettings(db)]);
|
const [agentOwn, agentSystem] = await Promise.all([getProjectAgentSettings(db, p.id), getSystemAgentSettings(db)]);
|
||||||
// PEP-31: the project's pool has no working subscription — agents won't start.
|
// PEP-31: the project's pool has no working subscription — agents won't start.
|
||||||
@ -290,11 +292,17 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
<EpicsPanel w={w} projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
|
<EpicsPanel w={w} projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
|
||||||
</PanelSection>
|
</PanelSection>
|
||||||
|
|
||||||
{engineer && (
|
|
||||||
<PanelSection title={t("Секреты")} count={secrets.length}>
|
<PanelSection title={t("Секреты")} count={secrets.length}>
|
||||||
<ProjectSecretsPanel projectId={p.id} secrets={secrets} back={back} />
|
<ProjectSecretsPanel
|
||||||
|
projectId={p.id}
|
||||||
|
secrets={secrets}
|
||||||
|
back={back}
|
||||||
|
agentsEnabled={agentSecrets}
|
||||||
|
services={new Map(secretReport.map((r) => [r.name, { serviceName: r.serviceName, connectionName: r.connectionName }]))}
|
||||||
|
hints={secretNameHints()}
|
||||||
|
engineer={engineer}
|
||||||
|
/>
|
||||||
</PanelSection>
|
</PanelSection>
|
||||||
)}
|
|
||||||
|
|
||||||
{engineer && (
|
{engineer && (
|
||||||
<PanelSection title={t("Бюджет стори")}>
|
<PanelSection title={t("Бюджет стори")}>
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { ShieldCheck } from "lucide-react";
|
import { ShieldCheck } from "lucide-react";
|
||||||
import { isSuperadmin, secretsAudit, type PlatformSecretRow } from "@peppa/core";
|
import { isSuperadmin, secretsAudit, secretsAgentReport, type PlatformSecretRow } from "@peppa/core";
|
||||||
import { Hidden } from "@/components/cards";
|
import { Hidden } from "@/components/cards";
|
||||||
import { Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
import { Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
@ -56,6 +56,8 @@ export default async function Secrets({ searchParams }: { searchParams: Promise<
|
|||||||
if (!(await isSuperadmin(db, user))) notFound();
|
if (!(await isSuperadmin(db, user))) notFound();
|
||||||
const q = await searchParams;
|
const q = await searchParams;
|
||||||
const a = await secretsAudit(db);
|
const a = await secretsAudit(db);
|
||||||
|
// PEP-253: service keys in project secrets, those still reaching agents first.
|
||||||
|
const keys = (await secretsAgentReport(db)).filter((r) => r.serviceId).sort((x, y) => Number(y.inAgentEnv && !y.connectionId) - Number(x.inAgentEnv && !x.connectionId));
|
||||||
const enc = a.encryption;
|
const enc = a.encryption;
|
||||||
// The link sits inside the sentence: split the translated text around {link}.
|
// The link sits inside the sentence: split the translated text around {link}.
|
||||||
const reissue = t("Перевыпуск — в {link}: «Переподключить» запускает новый вход, старый токен Claude отзывается в claude.ai → Settings → Claude Code.").split("{link}");
|
const reissue = t("Перевыпуск — в {link}: «Переподключить» запускает новый вход, старый токен Claude отзывается в claude.ai → Settings → Claude Code.").split("{link}");
|
||||||
@ -202,6 +204,30 @@ export default async function Secrets({ searchParams }: { searchParams: Promise<
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
|
<Section title={t("Ключи сервисов в секретах проектов")} count={keys.length}>
|
||||||
|
<p className="m-0 mb-2 text-xs text-muted-foreground">
|
||||||
|
{t("Секреты, в которых узнан ключ сервиса из каталога подключений. Пока ключ уходит агентам, агент может его прочитать; владелец переносит его кнопкой «Сделать подключением» в настройках проекта. Сообщить владельцам один раз: peppa secrets agent-report --notify.")}
|
||||||
|
</p>
|
||||||
|
{keys.length === 0 ? (
|
||||||
|
<Empty>{t("Ключей сервисов в секретах проектов нет.")}</Empty>
|
||||||
|
) : (
|
||||||
|
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||||
|
{keys.map((r) => (
|
||||||
|
<li key={`${r.projectId}:${r.name}`} className="flex flex-wrap items-center gap-2 rounded-md border px-3 py-2">
|
||||||
|
<a href={`/p/${r.projectKey}`} className="font-mono font-medium">
|
||||||
|
{r.projectKey}
|
||||||
|
</a>
|
||||||
|
<span className="font-mono text-[13px]">{r.name}</span>
|
||||||
|
<Badge variant="outline">{r.serviceName}</Badge>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{r.connectionName ? t("стал подключением «{name}»", { name: r.connectionName }) : r.inAgentEnv ? t("уходит агентам") : t("только продукту")}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
</div>
|
</div>
|
||||||
</Workspace>
|
</Workspace>
|
||||||
);
|
);
|
||||||
|
|||||||
@ -3,9 +3,10 @@ import type { ProjectSecretView } from "@peppa/core";
|
|||||||
import { Hidden } from "@/components/cards";
|
import { Hidden } from "@/components/cards";
|
||||||
import { ago } from "@/components/common";
|
import { ago } from "@/components/common";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input, Textarea } from "@/components/ui/input";
|
import { Textarea } from "@/components/ui/input";
|
||||||
|
import { SecretNameHint } from "@/components/SecretNameHint";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { deleteProjectSecretAction, saveProjectSecretAction } from "@/app/(app)/actions";
|
import { deleteProjectSecretAction, saveProjectSecretAction, secretToConnectionAction, setAgentSecretsAction, setSecretAudienceAction } from "@/app/(app)/actions";
|
||||||
import { Fragment, type ReactNode } from "react";
|
import { Fragment, type ReactNode } from "react";
|
||||||
|
|
||||||
/** A translated sentence with {name} placeholders replaced by inline elements. */
|
/** A translated sentence with {name} placeholders replaced by inline elements. */
|
||||||
@ -13,44 +14,121 @@ function rich(text: string, parts: Record<string, ReactNode>): ReactNode {
|
|||||||
return text.split(/\{(\w+)\}/).map((piece, i) => <Fragment key={i}>{i % 2 ? (parts[piece] ?? `{${piece}}`) : piece}</Fragment>);
|
return text.split(/\{(\w+)\}/).map((piece, i) => <Fragment key={i}>{i % 2 ? (parts[piece] ?? `{${piece}}`) : piece}</Fragment>);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-54: the project's secrets for agents and (PEP-112) for the deployed product — names only; values are write-only. */
|
/**
|
||||||
export async function ProjectSecretsPanel({ projectId, secrets, back }: { projectId: number; secrets: ProjectSecretView[]; back: string }) {
|
* PEP-54: the project's secrets for agents and (PEP-112) for the deployed product — names only; values are write-only.
|
||||||
|
* PEP-253: where each secret goes (only the product / also agents), the project setting «Агенты получают секреты
|
||||||
|
* в окружение», and keys of catalog services with «Сделать подключением».
|
||||||
|
*/
|
||||||
|
export async function ProjectSecretsPanel({
|
||||||
|
projectId,
|
||||||
|
secrets,
|
||||||
|
back,
|
||||||
|
agentsEnabled,
|
||||||
|
services,
|
||||||
|
hints,
|
||||||
|
engineer,
|
||||||
|
}: {
|
||||||
|
projectId: number;
|
||||||
|
secrets: ProjectSecretView[];
|
||||||
|
back: string;
|
||||||
|
agentsEnabled: boolean;
|
||||||
|
/** secret name → the recognised catalog service and the connection it became. */
|
||||||
|
services: Map<string, { serviceName: string | null; connectionName: string | null }>;
|
||||||
|
hints: Array<{ prefix: string; exact: boolean; service: string }>;
|
||||||
|
engineer: boolean;
|
||||||
|
}) {
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
|
<form action={setAgentSecretsAction} className="flex flex-col gap-1.5 rounded-md border bg-background/40 px-2.5 py-2 text-sm">
|
||||||
|
<Hidden fields={{ projectId, back, on: agentsEnabled ? "0" : "1" }} />
|
||||||
|
<span className="font-medium">
|
||||||
|
{t("Агенты получают секреты в окружение")}: {agentsEnabled ? t("да") : t("нет")}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{agentsEnabled
|
||||||
|
? t("Агент видит ключи с пометкой «агенту и продукту» и может их напечатать или унести. Внешние сервисы безопаснее давать подключениями.")
|
||||||
|
: t("Агенты не получают ни одного секрета; продукт получает все. Внешние сервисы агентам — через подключения.")}
|
||||||
|
</span>
|
||||||
|
<Button size="sm" variant="outline" className="self-start">
|
||||||
|
{agentsEnabled ? t("Не давать агентам секреты") : t("Давать агентам секреты «агенту и продукту»")}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
{secrets.length > 0 && (
|
{secrets.length > 0 && (
|
||||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm" aria-label={t("Секреты проекта")}>
|
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm" aria-label={t("Секреты проекта")}>
|
||||||
{secrets.map((s) => (
|
{secrets.map((s) => {
|
||||||
<li key={s.id} className="flex items-center gap-2 rounded-md border bg-background/40 px-2.5 py-1.5">
|
const svc = services.get(s.name);
|
||||||
<span className="flex min-w-0 flex-1 flex-col">
|
const toAgent = s.agentEnv && agentsEnabled;
|
||||||
<span className="truncate font-mono text-[13px]">{s.name}</span>
|
const canMove = !!svc?.serviceName && !s.connectionId;
|
||||||
<span className="text-xs text-muted-foreground">
|
return (
|
||||||
{t("изменён {ago}", { ago: ago(s.updatedAt, t) })}
|
<li key={s.id} className="flex flex-col gap-1.5 rounded-md border bg-background/40 px-2.5 py-1.5">
|
||||||
{s.updatedBy ? ` · ${s.updatedBy}` : ""} · {s.lastUsedAt ? t("выдан агенту {ago}", { ago: ago(s.lastUsedAt, t) }) : t("агентам ещё не выдавался")}
|
<div className="flex items-center gap-2">
|
||||||
</span>
|
<span className="flex min-w-0 flex-1 flex-col">
|
||||||
</span>
|
<span className="truncate font-mono text-[13px]">{s.name}</span>
|
||||||
<form action={deleteProjectSecretAction}>
|
<span className="text-xs text-muted-foreground">
|
||||||
<Hidden fields={{ projectId, name: s.name, back }} />
|
{s.agentEnv ? t("агенту и продукту") : t("только продукту")}
|
||||||
<Button variant="ghost" size="icon" aria-label={t("Удалить {name}", { name: s.name })} title={t("Удалить {name}", { name: s.name })}>
|
{s.agentEnv && !agentsEnabled ? ` (${t("агентам секреты не выдаются")})` : ""}
|
||||||
<Trash2 />
|
{" · "}
|
||||||
</Button>
|
{t("изменён {ago}", { ago: ago(s.updatedAt, t) })}
|
||||||
</form>
|
{s.updatedBy ? ` · ${s.updatedBy}` : ""}
|
||||||
</li>
|
{toAgent ? ` · ${s.lastUsedAt ? t("выдан агенту {ago}", { ago: ago(s.lastUsedAt, t) }) : t("агентам ещё не выдавался")}` : ""}
|
||||||
))}
|
</span>
|
||||||
|
</span>
|
||||||
|
<form action={deleteProjectSecretAction}>
|
||||||
|
<Hidden fields={{ projectId, name: s.name, back }} />
|
||||||
|
<Button variant="ghost" size="icon" aria-label={t("Удалить {name}", { name: s.name })} title={t("Удалить {name}", { name: s.name })}>
|
||||||
|
<Trash2 />
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{svc?.connectionName && <span className="text-xs text-muted-foreground">{t("Стал подключением «{name}»: агент работает с сервисом, не видя ключа.", { name: svc.connectionName })}</span>}
|
||||||
|
{canMove && (
|
||||||
|
<span className={`text-xs ${toAgent ? "text-amber-600 dark:text-amber-400" : "text-muted-foreground"}`}>
|
||||||
|
{toAgent
|
||||||
|
? t("Это ключ {service}, и агент его видит. Сделайте подключение: агент будет работать с сервисом, не видя ключа, продукт получит ключ как раньше.", { service: svc!.serviceName! })
|
||||||
|
: t("Это ключ {service}. Агенту его можно дать подключением — ключ он не увидит.", { service: svc!.serviceName! })}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{canMove && (
|
||||||
|
<form action={secretToConnectionAction}>
|
||||||
|
<Hidden fields={{ projectId, name: s.name, back }} />
|
||||||
|
<Button size="sm">{t("Сделать подключением")}</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
<form action={setSecretAudienceAction}>
|
||||||
|
<Hidden fields={{ projectId, name: s.name, back, audience: s.agentEnv ? "product" : "agent" }} />
|
||||||
|
<Button size="sm" variant="ghost">{s.agentEnv ? t("Только продукту") : t("Дать и агенту (видит ключ)")}</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
<form action={saveProjectSecretAction} className="flex flex-col gap-2" autoComplete="off">
|
<form action={saveProjectSecretAction} className="flex flex-col gap-2" autoComplete="off">
|
||||||
<Hidden fields={{ projectId, back }} />
|
<Hidden fields={{ projectId, back }} />
|
||||||
<Input name="name" required placeholder="STRIPE_TEST_KEY" aria-label={t("Имя секрета")} pattern="[A-Z][A-Z0-9_]{0,63}" className="font-mono" autoComplete="off" spellCheck={false} />
|
<SecretNameHint hints={hints} label={t("Имя секрета")} />
|
||||||
<Textarea name="value" required rows={2} placeholder={t("Значение — после сохранения его не увидит никто")} aria-label={t("Значение секрета")} className="font-mono" autoComplete="off" spellCheck={false} />
|
<Textarea name="value" required rows={2} placeholder={t("Значение — после сохранения его не увидит никто")} aria-label={t("Значение секрета")} className="font-mono" autoComplete="off" spellCheck={false} />
|
||||||
|
<fieldset className="m-0 flex flex-col gap-1 border-0 p-0 text-sm">
|
||||||
|
<legend className="mb-1 text-xs text-muted-foreground">{t("Кому")}</legend>
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<input type="radio" name="audience" value="product" defaultChecked /> {t("Только продукту")}
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-2">
|
||||||
|
<input type="radio" name="audience" value="agent" /> {t("Агенту и продукту (агент видит ключ)")}
|
||||||
|
</label>
|
||||||
|
</fieldset>
|
||||||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||||||
</form>
|
</form>
|
||||||
<p className="m-0 text-xs text-muted-foreground">
|
{engineer && (
|
||||||
{rich(
|
<p className="m-0 text-xs text-muted-foreground">
|
||||||
t("Секреты получают агенты проекта (при следующем запуске сессии) и сам выкаченный продукт — как переменные окружения с тем же именем; после изменения FORGE через пару минут перезапускает продукт. Имена {a}, {c}, {o} идут только в продукт. Имя существующего секрета заменяет его значение. Значение хранится зашифрованным и больше не показывается; в терминале и ленте шагов оно заменяется на «••••». Агент видит только имена ({list})."),
|
{rich(
|
||||||
{ a: <code>ANTHROPIC_…</code>, c: <code>CLAUDE_…</code>, o: <code>OPENCODE_…</code>, list: <code>list_secrets</code> },
|
t("Все секреты получает выкаченный продукт — как переменные окружения с тем же именем; после изменения FORGE через пару минут перезапускает продукт. Агенты проекта (при следующем запуске сессии) получают только секреты «агенту и продукту» и только при включённой настройке выше; имена {a}, {c}, {o} идут только в продукт. Имя существующего секрета заменяет его значение. Значение хранится зашифрованным и больше не показывается; в терминале и ленте шагов оно заменяется на «••••». Агент видит только имена ({list})."),
|
||||||
)}
|
{ a: <code>ANTHROPIC_…</code>, c: <code>CLAUDE_…</code>, o: <code>OPENCODE_…</code>, list: <code>list_secrets</code> },
|
||||||
</p>
|
)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
34
apps/web/components/SecretNameHint.tsx
Normal file
34
apps/web/components/SecretNameHint.tsx
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
"use client";
|
||||||
|
// PEP-253: the secret name field with a live hint «это ключ <Сервис> — агенту лучше дать подключение».
|
||||||
|
// The rules come from the server (`secretNameHints`), so no core code reaches the browser.
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { useT } from "@/components/I18n";
|
||||||
|
|
||||||
|
export function SecretNameHint({ hints, label }: { hints: Array<{ prefix: string; exact: boolean; service: string }>; label: string }) {
|
||||||
|
const t = useT();
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const n = name.trim().toUpperCase();
|
||||||
|
const hit = n ? hints.find((h) => (h.exact ? n === h.prefix : n.startsWith(h.prefix))) : undefined;
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<Input
|
||||||
|
name="name"
|
||||||
|
required
|
||||||
|
placeholder="MAPS_API_KEY"
|
||||||
|
aria-label={label}
|
||||||
|
pattern="[A-Z][A-Z0-9_]{0,63}"
|
||||||
|
className="font-mono"
|
||||||
|
autoComplete="off"
|
||||||
|
spellCheck={false}
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
/>
|
||||||
|
{hit && (
|
||||||
|
<p className="m-0 text-xs text-amber-600 dark:text-amber-400" role="status">
|
||||||
|
{t("Это ключ {service} — агенту лучше дать подключение: он будет работать с сервисом, не видя ключа. Сохраните ключ здесь «только продукту» и нажмите «Сделать подключением».", { service: hit.service })}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -47,6 +47,8 @@ import {
|
|||||||
setUserPassword,
|
setUserPassword,
|
||||||
giteaForBot,
|
giteaForBot,
|
||||||
secretsAudit,
|
secretsAudit,
|
||||||
|
secretsAgentReport,
|
||||||
|
shouldMove,
|
||||||
newSecretKey,
|
newSecretKey,
|
||||||
reencryptAll,
|
reencryptAll,
|
||||||
markSecretRotated,
|
markSecretRotated,
|
||||||
@ -70,7 +72,7 @@ import {
|
|||||||
} from "@peppa/core";
|
} from "@peppa/core";
|
||||||
import { createDb, migrateDb } from "@peppa/db";
|
import { createDb, migrateDb } from "@peppa/db";
|
||||||
import { checkHost, ensureSshKey, pushImage, sshArgs, tmux } from "@peppa/runner";
|
import { checkHost, ensureSshKey, pushImage, sshArgs, tmux } from "@peppa/runner";
|
||||||
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner";
|
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings, notifySecretsReport } from "@peppa/runner";
|
||||||
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
|
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
|
||||||
import { createEdgeTunnel, edgeConfig, edgeHosts, formatEdgeSync, syncEdge, isProjectPaused, setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
import { createEdgeTunnel, edgeConfig, edgeHosts, formatEdgeSync, syncEdge, isProjectPaused, setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
||||||
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
||||||
@ -163,6 +165,8 @@ const USAGE = `peppa — FORGE software factory CLI
|
|||||||
peppa secrets revoke-client <clientId> (revoke every MCP token of an OAuth client)
|
peppa secrets revoke-client <clientId> (revoke every MCP token of an OAuth client)
|
||||||
peppa secrets check-gitea (who GITEA_TOKEN is; warns about admin rights)
|
peppa secrets check-gitea (who GITEA_TOKEN is; warns about admin rights)
|
||||||
peppa secrets list <KEY> (PEP-54: names of a project's secrets; values are set in the web)
|
peppa secrets list <KEY> (PEP-54: names of a project's secrets; values are set in the web)
|
||||||
|
peppa secrets agent-report [--project KEY] [--notify]
|
||||||
|
(PEP-253: which secrets reach agents, which are keys of catalog services; --notify: one message per project)
|
||||||
peppa web login-link <gitea-login> (one-time admin login, 10 minutes)
|
peppa web login-link <gitea-login> (one-time admin login, 10 minutes)
|
||||||
peppa web logout-all [--no-welcome] (PEP-95: every web session ends — everyone signs in again and sees «О FORGE» once)
|
peppa web logout-all [--no-welcome] (PEP-95: every web session ends — everyone signs in again and sees «О FORGE» once)
|
||||||
peppa watchdog [--once] [--interval <sec>] [--stall <min>]
|
peppa watchdog [--once] [--interval <sec>] [--stall <min>]
|
||||||
@ -203,6 +207,8 @@ const { values: opts, positionals } = parseArgs({
|
|||||||
"log-file": { type: "string" },
|
"log-file": { type: "string" },
|
||||||
"commits-file": { type: "string" },
|
"commits-file": { type: "string" },
|
||||||
"secrets-only": { type: "boolean" },
|
"secrets-only": { type: "boolean" },
|
||||||
|
notify: { type: "boolean" },
|
||||||
|
project: { type: "string" },
|
||||||
alert: { type: "boolean" },
|
alert: { type: "boolean" },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@ -981,6 +987,19 @@ async function main(): Promise<void> {
|
|||||||
if (!r.ok) process.exitCode = 2;
|
if (!r.ok) process.exitCode = 2;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case "secrets agent-report": {
|
||||||
|
// PEP-253: keys of catalog services in project secrets; --notify tells each project once.
|
||||||
|
const rows = (await secretsAgentReport(db, opts.project ? { projectIds: [(await getProject(db, String(opts.project))).id] } : {})).filter((r) => r.serviceId || r.inAgentEnv);
|
||||||
|
if (!rows.length) console.log("Секретов, которые уходят агентам или похожи на ключ сервиса, нет.");
|
||||||
|
for (const r of rows) console.log(`${r.projectKey.padEnd(8)} ${r.name.padEnd(28)} ${(r.serviceName ?? "—").padEnd(16)} ${r.connectionName ? `подключение «${r.connectionName}»` : r.inAgentEnv ? "АГЕНТУ" : "только продукту"}${r.unreadable ? " (не читается)" : ""}${!r.agentsGetSecrets ? " · проекту выдача выключена" : ""}`);
|
||||||
|
const move = rows.filter(shouldMove);
|
||||||
|
console.log(`\nСделать подключением: ${move.length}`);
|
||||||
|
if (opts.notify) {
|
||||||
|
const sent = await notifySecretsReport(db);
|
||||||
|
console.log(sent.length ? `Сообщено в обсуждение: ${sent.map((x) => x.projectKey).join(", ")}` : "Новых сообщений нет (все уже получили или нечего переносить).");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "secrets list": {
|
case "secrets list": {
|
||||||
const [key] = withKey(args, 0);
|
const [key] = withKey(args, 0);
|
||||||
const p = await getProject(db, key);
|
const p = await getProject(db, key);
|
||||||
|
|||||||
@ -49,6 +49,7 @@ import {
|
|||||||
ensureProjectChat,
|
ensureProjectChat,
|
||||||
needsText,
|
needsText,
|
||||||
productOnlySecret,
|
productOnlySecret,
|
||||||
|
agentSecretsEnabled,
|
||||||
agentConnections,
|
agentConnections,
|
||||||
callConnection,
|
callConnection,
|
||||||
guardUntrusted,
|
guardUntrusted,
|
||||||
@ -388,10 +389,9 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
tool(
|
tool(
|
||||||
"list_secrets",
|
"list_secrets",
|
||||||
"List the names of this project's secrets (API keys and accesses the PM stored in FORGE). They are already in your environment as variables of the same name — use them as $NAME, never print, log or commit their values. Values are not available here. Missing a secret? ask_pm to add it in «⋯ Настройки проекта → Секреты» (the next session start gets it).",
|
"List the names of this project's secrets (API keys and accesses the owner stored in FORGE) and which of them are in your environment (use those as $NAME; never print, log or commit their values). Values are not available here. Secrets marked «deployed product only» reach only the deployed product. A key of an external service (Stripe, OpenAI, GitHub…) is NOT given as a secret: use list_connections / call_connection — FORGE adds the key itself. Missing a secret the product needs? declare_needs.",
|
||||||
{},
|
{},
|
||||||
async () => {
|
async () => {
|
||||||
// PEP-54: only the project of this session (or this repo), names only.
|
// PEP-54: only the project of this session (or this repo), names only.
|
||||||
@ -399,7 +399,12 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
|||||||
const rows = await listProjectSecrets(db, p.id);
|
const rows = await listProjectSecrets(db, p.id);
|
||||||
if (!rows.length) return `${p.key} has no secrets.`;
|
if (!rows.length) return `${p.key} has no secrets.`;
|
||||||
// PEP-112: ANTHROPIC_*/CLAUDE_*/OPENCODE_* go to the deployed product only.
|
// PEP-112: ANTHROPIC_*/CLAUDE_*/OPENCODE_* go to the deployed product only.
|
||||||
return [`Secrets of ${p.key} (in your env; every one of them also reaches the deployed product as env of the same name):`, ...rows.map((r) => `- ${r.name}${productOnlySecret(r.name) ? " (deployed product only — not in your env)" : ""}`)].join("\n");
|
// PEP-253: so does every secret not marked for agents, and all of them when the project's agents get no secrets.
|
||||||
|
const agentsGet = await agentSecretsEnabled(db, p.id);
|
||||||
|
const head = agentsGet
|
||||||
|
? `Secrets of ${p.key} (every one of them reaches the deployed product as env of the same name):`
|
||||||
|
: `Secrets of ${p.key}: this project's agents get no secrets in their env — all of them reach only the deployed product. External services: list_connections.`;
|
||||||
|
return [head, ...rows.map((r) => `- ${r.name}${agentsGet && r.agentEnv && !productOnlySecret(r.name) ? " (in your env)" : " (deployed product only — not in your env)"}${r.connectionId ? " — use the Access Hub connection instead" : ""}`)].join("\n");
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@ -193,7 +193,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
|
|||||||
const p = await ownedProject(project);
|
const p = await ownedProject(project);
|
||||||
const rows = await listProjectSecrets(db, p.id);
|
const rows = await listProjectSecrets(db, p.id);
|
||||||
if (!rows.length) return `${p.key} has no secrets.`;
|
if (!rows.length) return `${p.key} has no secrets.`;
|
||||||
return rows.map((r) => `- ${r.name} · updated ${r.updatedAt.toISOString().slice(0, 10)}${r.updatedBy ? ` by ${r.updatedBy}` : ""}${r.lastUsedAt ? ` · last given to an agent ${r.lastUsedAt.toISOString().slice(0, 16).replace("T", " ")}` : ""}`).join("\n");
|
return rows.map((r) => `- ${r.name} · ${r.agentEnv ? "agents and product" : "product only"}${r.connectionId ? " · moved to a connection" : ""} · updated ${r.updatedAt.toISOString().slice(0, 10)}${r.updatedBy ? ` by ${r.updatedBy}` : ""}${r.lastUsedAt ? ` · last given to an agent ${r.lastUsedAt.toISOString().slice(0, 16).replace("T", " ")}` : ""}`).join("\n");
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user