163 lines
9.5 KiB
TypeScript
163 lines
9.5 KiB
TypeScript
// 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";
|
||
import { projectSecrets, users, type Db } from "@peppa/db";
|
||
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 { getSetting, setSetting } from "./settings.ts";
|
||
import { projectForUser } from "./users.ts";
|
||
|
||
export const SECRET_NAME_RE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
||
export const SECRET_MAX_BYTES = 16 * 1024;
|
||
/** Shorter values are not masked: they would replace ordinary words. */
|
||
export const MASK_MIN_LENGTH = 4;
|
||
export const MASK = "••••";
|
||
|
||
/** Env the runner or the shell sets itself: a project secret must not shadow it. */
|
||
const RESERVED = new Set(["PATH", "HOME", "USER", "SHELL", "PWD", "TERM", "TMPDIR", "LANG", "NODE_OPTIONS", "CODEX_HOME", "GIT_DIR", "GIT_WORK_TREE"]);
|
||
const RESERVED_PREFIX = ["PEPPA_", "LD_", "DYLD_", "TMUX"];
|
||
/**
|
||
* PEP-112: names the agents' own CLIs read. A product may need them (its own Claude API key),
|
||
* so they are stored and go to the deployed product, but never into an agent session — there
|
||
* they would replace the agent's own sign-in.
|
||
*/
|
||
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}`;
|
||
|
||
export function secretNameError(name: string): string | null {
|
||
if (!SECRET_NAME_RE.test(name)) return tr("Имя секрета: A–Z, 0–9 и _, с буквы");
|
||
if (RESERVED.has(name) || RESERVED_PREFIX.some((p) => name.startsWith(p))) return tr("Имя {name} занято самой FORGE — выберите другое", { name });
|
||
return null;
|
||
}
|
||
|
||
export interface ProjectSecretView {
|
||
id: number;
|
||
name: string;
|
||
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, agentEnv: projectSecrets.agentEnv, connectionId: projectSecrets.connectionId })
|
||
.from(projectSecrets)
|
||
.leftJoin(users, eq(users.id, projectSecrets.updatedBy))
|
||
.where(eq(projectSecrets.projectId, projectId))
|
||
.orderBy(asc(projectSecrets.name));
|
||
return rows;
|
||
}
|
||
|
||
/**
|
||
* 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);
|
||
if (err) throw new PeppaError(err);
|
||
if (!value) throw new PeppaError(tr("Значение секрета пустое"));
|
||
if (value.includes("\0")) throw new PeppaError(tr("Значение секрета содержит NUL"));
|
||
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(), ...(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 });
|
||
if (!gone.length) throw new PeppaError(tr("Секрета {name} нет", { name }));
|
||
await logEvent(db, { projectId, type: "secret_deleted", payload: { name } });
|
||
await setSetting(db, secretsChangedKey(projectId), { at: Date.now() });
|
||
}
|
||
|
||
/**
|
||
* 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) || !r.agentEnv)) continue;
|
||
try {
|
||
env[r.name] = decrypt(r.valueEnc);
|
||
} catch {
|
||
unreadable.push(r.name);
|
||
}
|
||
}
|
||
return { env, unreadable };
|
||
}
|
||
|
||
export async function markSecretsUsed(db: Db, projectId: number, names: string[], now = new Date()): Promise<void> {
|
||
if (!names.length) return;
|
||
await db.update(projectSecrets).set({ lastUsedAt: now }).where(and(eq(projectSecrets.projectId, projectId), inArray(projectSecrets.name, names)));
|
||
}
|
||
|
||
/** Replaces every value (≥ MASK_MIN_LENGTH chars) in `text` with ••••, longest first. */
|
||
export function maskSecrets(text: string, values: string[]): string {
|
||
let out = text;
|
||
for (const v of values) if (v.length >= MASK_MIN_LENGTH && out.includes(v)) out = out.split(v).join(MASK);
|
||
return out;
|
||
}
|
||
|
||
export type Masker = (text: string) => string;
|
||
|
||
/** A masker over the project's current secret values (empty project → identity). */
|
||
export async function projectSecretMasker(db: Db, projectId: number): Promise<Masker> {
|
||
// Multi-line values (PEM keys) reach the terminal line by line: mask each long line too.
|
||
const values = Object.values((await projectSecretEnv(db, projectId, "deploy")).env)
|
||
.flatMap((v) => (v.includes("\n") ? [v, ...v.split(/\r?\n/).filter((l) => l.trim().length >= 8)] : [v]))
|
||
.filter((v) => v.length >= MASK_MIN_LENGTH)
|
||
.sort((a, b) => b.length - a.length);
|
||
return values.length ? (text) => maskSecrets(text, values) : (text) => text;
|
||
}
|