peppa/packages/core/src/secret-services.ts

186 lines
9.7 KiB
TypeScript
Raw 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-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 });
}