PEP-253: секрет «только продукту» / «агенту», настройка проекта, угадывание сервиса, переезд в подключение, отчёт

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-24 12:58:15 +00:00
parent 54693f8c65
commit e8a651a3b8
10 changed files with 5578 additions and 10 deletions

View File

@ -85,6 +85,7 @@ export * from "./budgets.ts";
export * from "./analytics.ts";
export * from "./audit.ts";
export * from "./secrets.ts";
export * from "./secret-services.ts";
export * from "./product-needs.ts";
export * from "./product-review.ts";
export * from "./secrets-audit.ts";

View File

@ -0,0 +1,185 @@
// PEP-253: project secrets that are keys of Access Hub catalog services (PEP-249). An agent should
// reach such a service through the gateway (PEP-234) and never hold the key, so FORGE recognises
// them, reports them and moves them to a connection with one button. The value is looked at only
// for its prefix — it is never printed, logged or returned.
import { m as tr } from "@peppa/shared/i18n";
import { connections, projects, projectSecrets, type Db } from "@peppa/db";
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
import { logEvent } from "./audit.ts";
import { catalogService, type CatalogService } from "./connection-catalog.ts";
import { createConnection, grantConnection } from "./connections.ts";
import { decrypt } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { agentSecretsEnabled, productOnlySecret } from "./secrets.ts";
import { setSetting } from "./settings.ts";
import { projectForUser } from "./users.ts";
interface ServiceRule {
service: string;
/** Name prefixes (also exact names). */
names: string[];
/** Value prefixes / shapes that identify the service even under another name. */
values?: RegExp[];
}
// Order matters: Anthropic's `sk-ant-` before OpenAI's `sk-`.
const RULES: ServiceRule[] = [
{ service: "stripe", names: ["STRIPE_"], values: [/^(sk|rk)_(test|live)_[A-Za-z0-9]{8,}$/] },
{ service: "anthropic", names: ["ANTHROPIC_API_KEY"], values: [/^sk-ant-[A-Za-z0-9_-]{8,}$/] },
{ service: "openai", names: ["OPENAI_"], values: [/^sk-(proj-)?[A-Za-z0-9_-]{16,}$/] },
{ service: "github", names: ["GITHUB_", "GH_TOKEN"], values: [/^(ghp|gho|ghu|ghs)_[A-Za-z0-9]{20,}$/, /^github_pat_[A-Za-z0-9_]{20,}$/] },
{ service: "slack", names: ["SLACK_"], values: [/^xox[bpa]-[A-Za-z0-9-]{10,}$/] },
{ service: "sendgrid", names: ["SENDGRID_"], values: [/^SG\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}$/] },
{ service: "resend", names: ["RESEND_"], values: [/^re_[A-Za-z0-9_]{16,}$/] },
{ service: "telegram", names: ["TELEGRAM_BOT_TOKEN", "TG_BOT_TOKEN", "BOT_TOKEN"], values: [/^\d{6,12}:[A-Za-z0-9_-]{30,}$/] },
{ service: "notion", names: ["NOTION_"], values: [/^(secret|ntn)_[A-Za-z0-9]{20,}$/] },
{ service: "airtable", names: ["AIRTABLE_"], values: [/^pat[A-Za-z0-9]{10,}\.[A-Za-z0-9]{20,}$/] },
{ service: "cloudflare", names: ["CLOUDFLARE_API_TOKEN", "CF_API_TOKEN"] },
{ service: "sentry", names: ["SENTRY_AUTH_TOKEN"], values: [/^sntrys_[A-Za-z0-9_=-]{20,}$/] },
{ service: "twilio", names: ["TWILIO_"] },
{ service: "kaspi", names: ["KASPI_"] },
{ service: "2gis", names: ["DGIS_", "TWOGIS_", "GIS2_"] },
{ service: "google-sheets", names: ["GOOGLE_SHEETS_", "SHEETS_API_KEY"] },
{ service: "google-drive", names: ["GOOGLE_DRIVE_"] },
{ service: "google-calendar", names: ["GOOGLE_CALENDAR_"] },
];
/** Names that sit under a service prefix but are not an API key of it (webhook signing, DSN, ids, addresses). */
const NOT_A_KEY = /(WEBHOOK|SIGNING|_DSN$|_URL$|_HOST$|_ID$|_PUBLISHABLE|_PUBLIC|_ORG$|_PROJECT$|_ENDPOINT$|_REGION$|_CHAT_ID$|_USERNAME$)/;
const NOT_A_KEY_VALUE = /^(whsec_|pk_(test|live)_|https?:\/\/)/;
function usable(card: CatalogService | null): card is CatalogService {
// One button can't make a connection that needs the user's own address.
return !!card && !card.baseEditable;
}
const nameMatches = (name: string, rule: ServiceRule) => rule.names.some((p) => (p.endsWith("_") ? name.startsWith(p) : name === p));
/**
* The catalog service a secret is a key of, or null. By name first, then by the value's shape.
* A value that clearly isn't a key (webhook secret, publishable key, address) is never a match.
*/
export function guessSecretService(name: string, value?: string | null): CatalogService | null {
const v = value?.trim() ?? "";
if (v && NOT_A_KEY_VALUE.test(v)) return null;
if (NOT_A_KEY.test(name)) return null;
const byValue = v ? RULES.find((r) => r.values?.some((re) => re.test(v))) : undefined;
if (byValue) return usable(catalogService(byValue.service)) ? catalogService(byValue.service) : null;
const byName = RULES.find((r) => nameMatches(name, r));
if (!byName) return null;
const card = catalogService(byName.service);
if (!usable(card)) return null;
// Basic auth needs «login:password» in one value — a lone token can't become such a connection.
if (card.auth === "basic" && v && !/^[^:]+:.+$/.test(v)) return null;
return card;
}
/** For the web form's live hint (no core in the browser): name prefix → service name. */
export function secretNameHints(): Array<{ prefix: string; exact: boolean; service: string }> {
return RULES.flatMap((r) => {
const card = catalogService(r.service);
return usable(card) ? r.names.map((p) => ({ prefix: p, exact: !p.endsWith("_"), service: card.name })) : [];
});
}
export interface SecretReportRow {
projectId: number;
projectKey: string;
ownerId: number | null;
name: string;
/** Marked «агенту и продукту». */
agentEnv: boolean;
/** The project's agents get secrets at all (PEP-253 setting). */
agentsGetSecrets: boolean;
/** Reaches agents' env right now. */
inAgentEnv: boolean;
serviceId: string | null;
serviceName: string | null;
connectionId: number | null;
connectionName: string | null;
unreadable: boolean;
}
/**
* Every project secret (live projects; `projectIds` narrows) with where it goes and the service
* it is a key of. No values.
*/
export async function secretsAgentReport(db: Db, o: { projectIds?: number[] } = {}): Promise<SecretReportRow[]> {
if (o.projectIds && !o.projectIds.length) return [];
const rows = await db
.select({ s: projectSecrets, key: projects.key, ownerId: projects.ownerId, connectionName: connections.name })
.from(projectSecrets)
.innerJoin(projects, eq(projects.id, projectSecrets.projectId))
.leftJoin(connections, eq(connections.id, projectSecrets.connectionId))
.where(and(isNull(projects.deletedAt), o.projectIds ? inArray(projects.id, o.projectIds) : undefined))
.orderBy(asc(projects.key), asc(projectSecrets.name));
const enabled = new Map<number, boolean>();
const out: SecretReportRow[] = [];
for (const r of rows) {
if (!enabled.has(r.s.projectId)) enabled.set(r.s.projectId, await agentSecretsEnabled(db, r.s.projectId));
let value: string | null = null;
let unreadable = false;
try {
value = decrypt(r.s.valueEnc);
} catch {
unreadable = true;
}
const card = guessSecretService(r.s.name, value);
const agentsGetSecrets = enabled.get(r.s.projectId)!;
out.push({
projectId: r.s.projectId,
projectKey: r.key,
ownerId: r.ownerId,
name: r.s.name,
agentEnv: r.s.agentEnv,
agentsGetSecrets,
inAgentEnv: agentsGetSecrets && r.s.agentEnv && !productOnlySecret(r.s.name),
serviceId: card?.id ?? null,
serviceName: card?.name ?? null,
connectionId: r.s.connectionId,
connectionName: r.connectionName ?? null,
unreadable,
});
}
return out;
}
/** A secret the owner should move: a service key that still reaches agents and isn't a connection yet. */
export const shouldMove = (r: SecretReportRow) => !!r.serviceId && r.inAgentEnv && !r.connectionId && !r.unreadable;
/**
* «Сделать подключением»: a connection of the recognised catalog service with the secret's key,
* owned by the person who pressed; a grant to the whole project with reading and writing at once
* (an agent with the key in env could do anything); the secret stays, but only for the product.
*/
export async function secretToConnection(db: Db, userId: number, projectId: number, name: string): Promise<{ connectionId: number; connectionName: string }> {
const project = await projectForUser(db, userId, projectId);
const [s] = await db.select().from(projectSecrets).where(and(eq(projectSecrets.projectId, projectId), eq(projectSecrets.name, name)));
if (!s) throw new PeppaError(tr("Секрета {name} нет", { name }));
if (s.connectionId) throw new PeppaError(tr("Этот ключ уже стал подключением"));
let value: string;
try {
value = decrypt(s.valueEnc);
} catch {
throw new PeppaError(tr("Значение секрета не читается — сохраните его заново"));
}
const card = guessSecretService(name, value);
if (!card) throw new PeppaError(tr("Не удалось понять, ключ какого сервиса в секрете {name}", { name }));
const mine = await db.select({ name: connections.name }).from(connections).where(eq(connections.ownerId, userId));
const taken = new Set(mine.map((c) => c.name));
let connName = card.name;
if (taken.has(connName)) connName = `${card.name} · ${project.key}`;
for (let i = 2; taken.has(connName); i++) connName = `${card.name} · ${project.key} ${i}`;
const conn = await createConnection(db, userId, { catalogId: card.id, name: connName, secret: value.trim() });
await grantConnection(db, userId, conn.id, { projectId, agentId: null, readMode: "auto", writeMode: "auto" });
await db.update(projectSecrets).set({ agentEnv: false, connectionId: conn.id, updatedBy: userId, updatedAt: new Date() }).where(eq(projectSecrets.id, s.id));
await logEvent(db, { projectId, type: "secret_to_connection", payload: { name, connectionId: conn.id, service: card.id } });
return { connectionId: conn.id, connectionName: conn.name };
}
/** `settings` key: the owner of the project was told about service keys in secrets (once). */
export const secretsReportNoticeKey = (projectId: number) => `secrets.report:${projectId}`;
export async function markSecretsReportNoticed(db: Db, projectId: number, names: string[]): Promise<void> {
await setSetting(db, secretsReportNoticeKey(projectId), { at: Date.now(), names });
}

View File

@ -1,4 +1,5 @@
// PEP-54: a project's secrets for its agents. Values are AES-256-GCM encrypted with
// PEP-54: a project's secrets for its agents.
// PEP-253: and/or only for the deployed product (`agent_env`); keys of catalog services move to Access Hub. Values are AES-256-GCM encrypted with
// PEPPA_SECRET, never shown after saving, handed to agent sessions as env by the runner
// and masked in the web terminal and agent steps.
import { m as tr } from "@peppa/shared/i18n";
@ -7,7 +8,7 @@ import { and, asc, eq, inArray } from "drizzle-orm";
import { logEvent } from "./audit.ts";
import { decrypt, encrypt } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { setSetting } from "./settings.ts";
import { getSetting, setSetting } from "./settings.ts";
import { projectForUser } from "./users.ts";
export const SECRET_NAME_RE = /^[A-Z][A-Z0-9_]{0,63}$/;
@ -26,6 +27,23 @@ const RESERVED_PREFIX = ["PEPPA_", "LD_", "DYLD_", "TMUX"];
*/
const PRODUCT_ONLY_PREFIX = ["CLAUDE_", "ANTHROPIC_", "OPENCODE_"];
export const productOnlySecret = (name: string) => PRODUCT_ONLY_PREFIX.some((p) => name.startsWith(p));
/**
* PEP-253: «Агенты получают секреты в окружение». No row = on (projects made before PEP-253 work
* as they did); `provisionProject` writes off for every new project.
*/
export const agentSecretsKey = (projectId: number) => `project.agent-secrets:${projectId}`;
export async function agentSecretsEnabled(db: Db, projectId: number): Promise<boolean> {
return (await getSetting<{ on?: boolean }>(db, agentSecretsKey(projectId)))?.on !== false;
}
/** Owner and members; the change applies from the next agent start. */
export async function setAgentSecretsEnabled(db: Db, userId: number | null, projectId: number, on: boolean): Promise<void> {
if (userId != null) await projectForUser(db, userId, projectId);
await setSetting(db, agentSecretsKey(projectId), { on, at: Date.now() });
if (userId != null) await logEvent(db, { projectId, type: "agent_secrets_setting", payload: { on } });
}
/** `settings` key: when the project's secrets last changed and deployed versions need a restart. */
export const secretsChangedKey = (projectId: number) => `product.redeploy:${projectId}`;
@ -41,12 +59,16 @@ export interface ProjectSecretView {
updatedAt: Date;
updatedBy: string | null;
lastUsedAt: Date | null;
/** PEP-253: also into agents' env (else only to the deployed product). */
agentEnv: boolean;
/** PEP-253: the Access Hub connection the key moved to. */
connectionId: number | null;
}
/** Secrets of a project without values (web, MCP). */
export async function listProjectSecrets(db: Db, projectId: number): Promise<ProjectSecretView[]> {
const rows = await db
.select({ id: projectSecrets.id, name: projectSecrets.name, updatedAt: projectSecrets.updatedAt, updatedBy: users.login, lastUsedAt: projectSecrets.lastUsedAt })
.select({ id: projectSecrets.id, name: projectSecrets.name, updatedAt: projectSecrets.updatedAt, updatedBy: users.login, lastUsedAt: projectSecrets.lastUsedAt, agentEnv: projectSecrets.agentEnv, connectionId: projectSecrets.connectionId })
.from(projectSecrets)
.leftJoin(users, eq(users.id, projectSecrets.updatedBy))
.where(eq(projectSecrets.projectId, projectId))
@ -54,8 +76,12 @@ export async function listProjectSecrets(db: Db, projectId: number): Promise<Pro
return rows;
}
/** Creates or replaces a secret; owner and members of the project only. */
export async function setProjectSecret(db: Db, userId: number, projectId: number, name: string, value: string): Promise<ProjectSecretView> {
/**
* Creates or replaces a secret; owner and members of the project only. PEP-253: a new secret goes
* only to the deployed product unless `agent: true`; replacing a value keeps where it goes unless
* `agent` is given.
*/
export async function setProjectSecret(db: Db, userId: number, projectId: number, name: string, value: string, o: { agent?: boolean } = {}): Promise<ProjectSecretView> {
await projectForUser(db, userId, projectId);
name = name.trim();
const err = secretNameError(name);
@ -65,13 +91,21 @@ export async function setProjectSecret(db: Db, userId: number, projectId: number
if (Buffer.byteLength(value) > SECRET_MAX_BYTES) throw new PeppaError(tr("Значение секрета больше 16 КБ"));
const valueEnc = encrypt(value);
const [existing] = await db.select({ id: projectSecrets.id }).from(projectSecrets).where(and(eq(projectSecrets.projectId, projectId), eq(projectSecrets.name, name)));
if (existing) await db.update(projectSecrets).set({ valueEnc, updatedBy: userId, updatedAt: new Date() }).where(eq(projectSecrets.id, existing.id));
else await db.insert(projectSecrets).values({ projectId, name, valueEnc, createdBy: userId, updatedBy: userId });
await logEvent(db, { projectId, type: "secret_set", payload: { name, replaced: !!existing } });
if (existing) await db.update(projectSecrets).set({ valueEnc, updatedBy: userId, updatedAt: new Date(), ...(o.agent != null ? { agentEnv: o.agent } : {}) }).where(eq(projectSecrets.id, existing.id));
else await db.insert(projectSecrets).values({ projectId, name, valueEnc, createdBy: userId, updatedBy: userId, agentEnv: o.agent ?? false });
await logEvent(db, { projectId, type: "secret_set", payload: { name, replaced: !!existing, ...(o.agent != null ? { agent: o.agent } : {}) } });
await setSetting(db, secretsChangedKey(projectId), { at: Date.now() });
return (await listProjectSecrets(db, projectId)).find((s) => s.name === name)!;
}
/** PEP-253: «только продукту» (false) or «агенту и продукту» (true); owner and members. */
export async function setSecretAudience(db: Db, userId: number, projectId: number, name: string, agent: boolean): Promise<void> {
await projectForUser(db, userId, projectId);
const done = await db.update(projectSecrets).set({ agentEnv: agent, updatedBy: userId, updatedAt: new Date() }).where(and(eq(projectSecrets.projectId, projectId), eq(projectSecrets.name, name))).returning({ id: projectSecrets.id });
if (!done.length) throw new PeppaError(tr("Секрета {name} нет", { name }));
await logEvent(db, { projectId, type: "secret_audience", payload: { name, agent } });
}
export async function deleteProjectSecret(db: Db, userId: number, projectId: number, name: string): Promise<void> {
await projectForUser(db, userId, projectId);
const gone = await db.delete(projectSecrets).where(and(eq(projectSecrets.projectId, projectId), eq(projectSecrets.name, name))).returning({ id: projectSecrets.id });
@ -84,13 +118,16 @@ export async function deleteProjectSecret(db: Db, userId: number, projectId: num
* name → value for an agent session or for a deploy of the product (runner only). Unreadable
* values (wrong key) are skipped and reported, so one broken secret never blocks a session.
* PEP-112: product-only names (ANTHROPIC_*, …) are left out of agent sessions.
* PEP-253: an agent gets only secrets marked «агенту и продукту», and none at all when the
* project's «Агенты получают секреты в окружение» is off. A deploy gets every secret.
*/
export async function projectSecretEnv(db: Db, projectId: number, target: "agent" | "deploy" = "agent"): Promise<{ env: Record<string, string>; unreadable: string[] }> {
if (target === "agent" && !(await agentSecretsEnabled(db, projectId))) return { env: {}, unreadable: [] };
const rows = await db.select().from(projectSecrets).where(eq(projectSecrets.projectId, projectId)).orderBy(asc(projectSecrets.name));
const env: Record<string, string> = {};
const unreadable: string[] = [];
for (const r of rows) {
if (target === "agent" && productOnlySecret(r.name)) continue;
if (target === "agent" && (productOnlySecret(r.name) || !r.agentEnv)) continue;
try {
env[r.name] = decrypt(r.valueEnc);
} catch {

View File

@ -0,0 +1,2 @@
ALTER TABLE `project_secrets` ADD `agent_env` integer DEFAULT true NOT NULL;--> statement-breakpoint
ALTER TABLE `project_secrets` ADD `connection_id` integer REFERENCES connections(id);

File diff suppressed because it is too large Load Diff

View File

@ -218,6 +218,13 @@
"when": 1795512094088,
"tag": "0030_access_hub_journal",
"breakpoints": true
},
{
"idx": 31,
"version": "6",
"when": 1795524871580,
"tag": "0031_secrets_agent_env",
"breakpoints": true
}
]
}

View File

@ -660,6 +660,11 @@ export const projectSecrets = sqliteTable(
updatedAt: updatedAt(),
// Last time a session got it in its env.
lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
// PEP-253: also into agent sessions' env (1) or only to the deployed product (0). Rows made
// before PEP-253 keep 1; new ones are 0 unless the owner chose otherwise.
agentEnv: integer("agent_env", { mode: "boolean" }).notNull().default(true),
// PEP-253: the Access Hub connection this key moved to («Сделать подключением»).
connectionId: integer("connection_id").references((): AnySQLiteColumn => connections.id, { onDelete: "set null" }),
},
(t) => [uniqueIndex("project_secrets_project_name").on(t.projectId, t.name)],
);

View File

@ -82,3 +82,4 @@ export * from "./edge-dns.ts";
export * from "./workspace-paths.ts";
export * from "./codex-trust.ts";
export * from "./codex-screen.ts";
export * from "./secrets-report.ts";

View File

@ -5,7 +5,7 @@ import { m } from "@peppa/shared/i18n";
import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createProject, NEW_PROJECT_AUTONOMY, NEW_PROJECT_PUBLISH, setPublishMode, logEvent, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
import { createProject, setAgentSecretsEnabled, NEW_PROJECT_AUTONOMY, NEW_PROJECT_PUBLISH, setPublishMode, logEvent, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core";
import { projects, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { eq, or } from "drizzle-orm";
@ -178,6 +178,8 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise<Pro
if (own) await setProjectPool(db, project.id, own.id);
// PEP-84: every new story of a new project goes through «продакт» and «аналитик» first.
await setIntakeSettings(db, project.id, { enabled: true });
// PEP-253: agents of a new project get no secrets in env — external services go through Access Hub.
await setAgentSecretsEnabled(db, null, project.id, false);
// PEP-191: after the first commit only peppa-bot writes to the default branch. Best effort:
// the project works without it; the superadmin is told once and the watchdog retries daily.
log("protect branch");

View File

@ -0,0 +1,33 @@
// PEP-253: one message to each project whose secrets still hand keys of catalog services to agents
// («сделайте их подключениями»). Sent by the superadmin with `peppa secrets agent-report --notify`,
// once per project (`secrets.report:<id>`), in the project's discussion from FORGE — it reaches the
// owner and members like any message there. Paused projects are skipped (and asked again later).
import { m as tr, asIs } from "@peppa/shared/i18n";
import { ensureProjectChat, getProject, getSetting, isProjectPaused, markSecretsReportNoticed, secretsAgentReport, secretsReportNoticeKey, shouldMove } from "@peppa/core";
import type { Db } from "@peppa/db";
import { sayInDiscussion } from "./analyst-chat.ts";
export function secretsReportText(items: Array<{ name: string; serviceName: string }>, link: string): string {
const list = items.map((i) => `• ${asIs(i.name)} — ${asIs(i.serviceName)}`).join("\n");
return `${tr("Агенты проекта видят ключи внешних сервисов: {n}. Безопаснее сделать их подключениями — агент будет работать с сервисом, не видя ключа, а продукт получит ключ как раньше.", { n: items.length })}\n${list}\n${tr("Откройте «⋯ Настройки проекта → Секреты» и нажмите «Сделать подключением» у каждого ключа: {link}", { link })}`;
}
export async function notifySecretsReport(db: Db, o: { log?: (m: string) => void } = {}): Promise<Array<{ projectKey: string; names: string[] }>> {
const rows = (await secretsAgentReport(db)).filter(shouldMove);
const byProject = new Map<number, typeof rows>();
for (const r of rows) byProject.set(r.projectId, [...(byProject.get(r.projectId) ?? []), r]);
const sent: Array<{ projectKey: string; names: string[] }> = [];
for (const [projectId, items] of byProject) {
if (await getSetting(db, secretsReportNoticeKey(projectId))) continue;
if (await isProjectPaused(db, projectId)) continue;
const project = await getProject(db, items[0]!.projectKey);
const chat = await ensureProjectChat(db, projectId);
const link = `${process.env.PEPPA_WEB_URL ?? ""}/p/${project.key}`;
await sayInDiscussion(db, project, chat.id, secretsReportText(items.map((i) => ({ name: i.name, serviceName: i.serviceName! })), link), null);
const names = items.map((i) => i.name);
await markSecretsReportNoticed(db, projectId, names);
o.log?.(`${project.key}: ${names.join(", ")}`);
sent.push({ projectKey: project.key, names });
}
return sent;
}