peppa/packages/core/src/secrets.ts
2026-11-16 09:52:35 +05:00

126 lines
6.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-54: a project's secrets for its agents. 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 { 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));
/** `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} занято самой Peppa FACTORY — выберите другое", { name });
return null;
}
export interface ProjectSecretView {
id: number;
name: string;
updatedAt: Date;
updatedBy: string | null;
lastUsedAt: Date | 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 })
.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. */
export async function setProjectSecret(db: Db, userId: number, projectId: number, name: string, value: string): 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() }).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 } });
await setSetting(db, secretsChangedKey(projectId), { at: Date.now() });
return (await listProjectSecrets(db, projectId)).find((s) => s.name === name)!;
}
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.
*/
export async function projectSecretEnv(db: Db, projectId: number, target: "agent" | "deploy" = "agent"): Promise<{ env: Record<string, string>; unreadable: string[] }> {
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;
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;
}