peppa/packages/core/src/connections.ts
peppa-bot f3d10a4c25 PEP-243: платформа называется FORGE — название во всех текстах для людей и подсказках агентам, адрес forge.telecom.quest
«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках
агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя».
Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:18:49 +05:00

597 lines
29 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-234 Access Hub: a user's own external services («Подключения»). The key is stored
// encrypted (crypto.ts, rotated with PEPPA_SECRET — secrets-audit encryptedColumns) and is
// decrypted only here, in the server-side gateway `callConnection`, right before the request.
// No function returns it: not to the owner, a superadmin, an agent, the journal or MCP.
// Deny by default: an agent may call an operation only with an explicit grant of the owner for
// the agent's project (and the agent, or any agent of the project). See the change
// pep-234-access-hub (design.md — threat model).
import { m as tr } from "@peppa/shared/i18n";
import { agents, connectionGrants, connectionLog, connections, projects, sessions, type Db } from "@peppa/db";
import { and, asc, count, desc, eq, gt, inArray } from "drizzle-orm";
import { lookup as dnsLookup, type LookupAddress } from "node:dns";
import { request as httpRequest, type IncomingMessage } from "node:http";
import { request as httpsRequest } from "node:https";
import { isIP } from "node:net";
import { logEvent } from "./audit.ts";
import { decrypt, encrypt } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { maskSecrets } from "./secrets.ts";
import { projectForUser } from "./users.ts";
export const CONNECTION_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;
export type ConnectionMethod = (typeof CONNECTION_METHODS)[number];
export const CONNECTION_NAME_MAX = 60;
export const CONNECTION_SECRET_MAX_BYTES = 8 * 1024;
export const CONNECTION_BODY_MAX_BYTES = 64 * 1024;
export const CONNECTION_RESPONSE_MAX_BYTES = 256 * 1024;
export const CONNECTION_TIMEOUT_MS = 15_000;
/** Gateway calls per session per minute. */
export const CONNECTION_RATE_PER_MIN = 60;
export const CONNECTION_MAX_OPERATIONS = 20;
/** Why a call was refused or failed — stored in the journal, words for people in REASON_TEXT. */
export type ConnectionReason =
| "no_session"
| "not_isolated"
| "unknown_connection"
| "ambiguous_connection"
| "revoked"
| "no_grant"
| "operation_denied"
| "bad_path"
| "bad_request"
| "rate_limited"
| "blocked_address"
| "redirect"
| "too_large"
| "timeout"
| "upstream_error";
export const CONNECTION_REASON_TEXT: Record<ConnectionReason, string> = {
no_session: tr("запрос не от агента FORGE"),
not_isolated: tr("агент работает без изоляции"),
unknown_connection: tr("нет такого подключения"),
ambiguous_connection: tr("несколько подключений с таким названием"),
revoked: tr("подключение отозвано"),
no_grant: tr("нет разрешения для проекта или агента"),
operation_denied: tr("операция не разрешена"),
bad_path: tr("недопустимый путь"),
bad_request: tr("недопустимый запрос"),
rate_limited: tr("слишком много запросов"),
blocked_address: tr("адрес сервиса недоступен"),
redirect: tr("сервис перенаправил запрос"),
too_large: tr("слишком большой ответ"),
timeout: tr("сервис не ответил вовремя"),
upstream_error: tr("сервис недоступен"),
};
export interface ConnectionView {
id: number;
name: string;
baseUrl: string;
authKind: "bearer" | "header";
authHeader: string | null;
status: "active" | "revoked";
hasKey: boolean;
revokedAt: Date | null;
lastUsedAt: Date | null;
createdAt: Date;
grants: ConnectionGrantView[];
}
export interface ConnectionGrantView {
id: number;
projectId: number;
projectKey: string;
projectName: string;
agentId: number | null;
agentName: string | null;
operations: string[];
createdAt: Date;
}
export interface ConnectionLogView {
id: number;
connectionId: number | null;
connectionName: string | null;
projectKey: string | null;
agentName: string | null;
sessionId: number | null;
method: string;
path: string;
decision: "allowed" | "denied" | "failed";
reason: string | null;
statusCode: number | null;
createdAt: Date;
}
const allowPrivate = (env: NodeJS.ProcessEnv = process.env) => env.PEPPA_CONNECTIONS_ALLOW_PRIVATE === "1";
const allowUnisolated = (env: NodeJS.ProcessEnv = process.env) => env.PEPPA_CONNECTIONS_UNISOLATED === "on";
// ---------- addresses ----------
/** The service address of a connection: https, no login/password, no query or fragment. */
export function parseBaseUrl(raw: string, env: NodeJS.ProcessEnv = process.env): string {
const bad = () => new PeppaError(tr("Адрес сервиса должен начинаться с https:// и не содержать логин, пароль, «?» и «#»"));
let u: URL;
try {
u = new URL(raw.trim());
} catch {
throw bad();
}
if (u.protocol !== "https:" && !(u.protocol === "http:" && allowPrivate(env))) throw bad();
if (u.username || u.password || u.search || u.hash || raw.includes("?") || raw.includes("#")) throw bad();
if (!u.hostname) throw bad();
if (!allowPrivate(env) && (isBlockedAddress(u.hostname.replace(/^\[|\]$/g, "")) || /^(localhost|.*\.localhost|.*\.local|.*\.internal)$/i.test(u.hostname))) throw new PeppaError(tr("Этот адрес сервиса недоступен: укажите адрес в интернете"));
return u.origin + u.pathname.replace(/\/+$/, "");
}
/** Loopback, private, link-local, CGNAT, ULA, multicast, unspecified, metadata: not reachable. */
export function isBlockedAddress(ip: string): boolean {
const v = isIP(ip);
if (v === 4) {
const [a, b] = ip.split(".").map(Number) as [number, number];
return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224;
}
if (v === 6) {
const s = ip.toLowerCase();
const mapped = s.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
if (mapped) return isBlockedAddress(mapped[1]!);
if (/^::ffff:/.test(s)) return true; // hex-mapped forms: refuse rather than decode
return s === "::" || s === "::1" || /^f[cd]/.test(s) || /^fe[89ab]/.test(s) || /^ff/.test(s) || /^64:ff9b:/.test(s) || /^2001:db8:/.test(s);
}
return false; // a host name: checked after resolving
}
/**
* A path from an agent → the clean path (with its query) or null. Refuses everything that could
* step out of the base address or confuse a server: dot segments, `//`, `\`, encoded dots and
* slashes, control characters, a scheme or `@`.
*/
export function cleanPath(raw: string): { path: string; query: string } | null {
if (typeof raw !== "string" || !raw.startsWith("/") || raw.length > 2048) return null;
if (/[\u0000-\u001f\u007f\s\\#@]/.test(raw)) return null;
const [path, ...rest] = raw.split("?");
const query = rest.join("?");
if (!path || path.includes("//") || /%(2e|2f|5c|25|00)/i.test(path)) return null;
if (/:/.test(path)) return null;
if (path.split("/").some((seg) => seg === "." || seg === "..")) return null;
if (/[^A-Za-z0-9\-._~!$&'()*+,;=:@%/]/.test(path)) return null;
if (/[^A-Za-z0-9\-._~!$&'()*+,;=:@%/?]/.test(query)) return null;
return { path, query };
}
/** "GET /items/" → {method, prefix}; null when malformed. */
export function parseOperation(op: string): { method: ConnectionMethod; prefix: string } | null {
const m = op.trim().match(/^([A-Za-z]+)\s+(\/\S*)$/);
if (!m) return null;
const method = m[1]!.toUpperCase() as ConnectionMethod;
if (!CONNECTION_METHODS.includes(method)) return null;
const c = cleanPath(m[2]!);
if (!c || c.query) return null;
const prefix = c.path.length > 1 ? c.path.replace(/\/+$/, "") : "/";
return { method, prefix };
}
/** Prefix match on a segment boundary: "/items" covers "/items" and "/items/5", not "/itemsX". */
export function operationAllows(ops: string[], method: string, path: string): boolean {
return ops.some((o) => {
const p = parseOperation(o);
if (!p || p.method !== method.toUpperCase()) return false;
return p.prefix === "/" || path === p.prefix || path.startsWith(`${p.prefix}/`);
});
}
export function normalizeOperations(raw: string[] | string): string[] {
const list = (Array.isArray(raw) ? raw : raw.split(/\r?\n|,/)).map((s) => s.trim()).filter(Boolean);
if (!list.length) throw new PeppaError(tr("Укажите хотя бы одну операцию, например «GET /items»"));
if (list.length > CONNECTION_MAX_OPERATIONS) throw new PeppaError(tr("Не больше {n} операций в одном разрешении", { n: CONNECTION_MAX_OPERATIONS }));
const out: string[] = [];
for (const o of list) {
const p = parseOperation(o);
if (!p) throw new PeppaError(tr("Операция «{op}» не распознана: нужен метод (GET, POST, PUT, PATCH, DELETE) и путь с «/»", { op: o.slice(0, 80) }));
out.push(`${p.method} ${p.prefix}`);
}
return [...new Set(out)];
}
// ---------- owner's management ----------
async function ownConnection(db: Db, userId: number, connectionId: number) {
const [c] = await db.select().from(connections).where(eq(connections.id, connectionId));
// No superadmin bypass: a connection is its owner's alone.
if (!c || c.ownerId !== userId) throw new PeppaError(tr("Подключение не найдено"));
return c;
}
function nameError(name: string): string | null {
if (!name || name.length > CONNECTION_NAME_MAX) return tr("Название подключения: от 1 до {n} символов", { n: CONNECTION_NAME_MAX });
if (/[\u0000-\u001f\u007f]/.test(name)) return tr("Название подключения содержит недопустимые символы");
return null;
}
function secretError(secret: string): string | null {
if (!secret) return tr("Ключ доступа пустой");
if (Buffer.byteLength(secret) > CONNECTION_SECRET_MAX_BYTES) return tr("Ключ доступа больше 8 КБ");
if (/[\r\n\u0000]/.test(secret)) return tr("Ключ доступа должен быть одной строкой");
return null;
}
const HEADER_RE = /^[A-Za-z][A-Za-z0-9-]{0,63}$/;
const FORBIDDEN_HEADERS = new Set(["host", "content-length", "content-type", "transfer-encoding", "connection", "cookie", "accept-encoding"]);
export interface ConnectionInput {
name: string;
baseUrl: string;
secret: string;
authKind?: "bearer" | "header";
authHeader?: string | null;
}
export async function createConnection(db: Db, userId: number, i: ConnectionInput): Promise<ConnectionView> {
const name = i.name.trim();
const err = nameError(name) ?? secretError(i.secret);
if (err) throw new PeppaError(err);
const baseUrl = parseBaseUrl(i.baseUrl);
const authKind = i.authKind === "header" ? "header" : "bearer";
const authHeader = authKind === "header" ? (i.authHeader ?? "").trim() : null;
if (authKind === "header" && (!HEADER_RE.test(authHeader!) || FORBIDDEN_HEADERS.has(authHeader!.toLowerCase()))) throw new PeppaError(tr("Имя заголовка для ключа: латинские буквы, цифры и дефис, например X-Api-Key"));
const [dup] = await db.select({ id: connections.id }).from(connections).where(and(eq(connections.ownerId, userId), eq(connections.name, name)));
if (dup) throw new PeppaError(tr("Подключение «{name}» уже есть", { name }));
const [row] = await db.insert(connections).values({ ownerId: userId, name, baseUrl, authKind, authHeader, secretEnc: encrypt(i.secret) }).returning({ id: connections.id });
return (await listConnections(db, userId)).find((c) => c.id === row!.id)!;
}
/** Replaces the key; also brings a revoked connection back with its grants. */
export async function replaceConnectionSecret(db: Db, userId: number, connectionId: number, secret: string): Promise<void> {
await ownConnection(db, userId, connectionId);
const err = secretError(secret);
if (err) throw new PeppaError(err);
await db.update(connections).set({ secretEnc: encrypt(secret), status: "active", revokedAt: null }).where(eq(connections.id, connectionId));
}
/**
* Instant revoke: the stored key is wiped, so the very next gateway call is refused (`revoked`)
* and even a copy of the database no longer holds it. Grants stay visible to the owner and
* start working again only after a new key (`replaceConnectionSecret`).
*/
export async function revokeConnection(db: Db, userId: number, connectionId: number): Promise<void> {
const c = await ownConnection(db, userId, connectionId);
await db.update(connections).set({ status: "revoked", secretEnc: null, revokedAt: new Date() }).where(eq(connections.id, c.id));
const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id));
for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_revoked", payload: { connectionId: c.id } });
}
export async function deleteConnection(db: Db, userId: number, connectionId: number): Promise<void> {
await revokeConnection(db, userId, connectionId);
await db.delete(connectionGrants).where(eq(connectionGrants.connectionId, connectionId));
await db.delete(connections).where(eq(connections.id, connectionId));
}
export async function grantConnection(db: Db, userId: number, connectionId: number, g: { projectId: number; agentId?: number | null; operations: string[] | string }): Promise<ConnectionGrantView> {
const c = await ownConnection(db, userId, connectionId);
if (c.status !== "active") throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа"));
await projectForUser(db, userId, g.projectId); // the owner gives access only to their projects
const agentId = g.agentId ?? null;
if (agentId != null) {
const [a] = await db.select({ id: agents.id }).from(agents).where(eq(agents.id, agentId));
if (!a) throw new PeppaError(tr("Агент не найден"));
}
const operations = normalizeOperations(g.operations);
const existing = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, c.id), eq(connectionGrants.projectId, g.projectId)))).find((x) => x.agentId === agentId);
let id: number;
if (existing) {
await db.update(connectionGrants).set({ operations, createdBy: userId }).where(eq(connectionGrants.id, existing.id));
id = existing.id;
} else {
const [row] = await db.insert(connectionGrants).values({ connectionId: c.id, projectId: g.projectId, agentId, operations, createdBy: userId }).returning({ id: connectionGrants.id });
id = row!.id;
}
await logEvent(db, { projectId: g.projectId, type: "connection_granted", payload: { connectionId: c.id, agentId, operations } });
return (await grantViews(db, [c.id])).find((x) => x.id === id)!;
}
export async function revokeGrant(db: Db, userId: number, grantId: number): Promise<void> {
const [g] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grantId));
if (!g) throw new PeppaError(tr("Разрешение не найдено"));
await ownConnection(db, userId, g.connectionId);
await db.delete(connectionGrants).where(eq(connectionGrants.id, grantId));
await logEvent(db, { projectId: g.projectId, type: "connection_grant_revoked", payload: { connectionId: g.connectionId, agentId: g.agentId } });
}
async function grantViews(db: Db, connectionIds: number[]): Promise<Array<ConnectionGrantView & { connectionId: number }>> {
if (!connectionIds.length) return [];
return db
.select({
id: connectionGrants.id,
connectionId: connectionGrants.connectionId,
projectId: connectionGrants.projectId,
projectKey: projects.key,
projectName: projects.name,
agentId: connectionGrants.agentId,
agentName: agents.name,
operations: connectionGrants.operations,
createdAt: connectionGrants.createdAt,
})
.from(connectionGrants)
.innerJoin(projects, eq(projects.id, connectionGrants.projectId))
.leftJoin(agents, eq(agents.id, connectionGrants.agentId))
.where(inArray(connectionGrants.connectionId, connectionIds))
.orderBy(asc(projects.key), asc(connectionGrants.id));
}
/** The user's own connections with grants; never the key. */
export async function listConnections(db: Db, userId: number): Promise<ConnectionView[]> {
const rows = await db.select().from(connections).where(eq(connections.ownerId, userId)).orderBy(asc(connections.name));
const grants = await grantViews(db, rows.map((r) => r.id));
return rows.map((r) => ({
id: r.id,
name: r.name,
baseUrl: r.baseUrl,
authKind: r.authKind,
authHeader: r.authHeader,
status: r.status,
hasKey: !!r.secretEnc,
revokedAt: r.revokedAt,
lastUsedAt: r.lastUsedAt,
createdAt: r.createdAt,
grants: grants.filter((g) => g.connectionId === r.id).map(({ connectionId: _, ...g }) => g),
}));
}
/** The owner's journal (all their connections, or one). */
export async function connectionJournal(db: Db, userId: number, o: { connectionId?: number; limit?: number } = {}): Promise<ConnectionLogView[]> {
return db
.select({
id: connectionLog.id,
connectionId: connectionLog.connectionId,
connectionName: connectionLog.connectionName,
projectKey: projects.key,
agentName: connectionLog.agentName,
sessionId: connectionLog.sessionId,
method: connectionLog.method,
path: connectionLog.path,
decision: connectionLog.decision,
reason: connectionLog.reason,
statusCode: connectionLog.statusCode,
createdAt: connectionLog.createdAt,
})
.from(connectionLog)
.leftJoin(projects, eq(projects.id, connectionLog.projectId))
.where(and(eq(connectionLog.ownerId, userId), o.connectionId != null ? eq(connectionLog.connectionId, o.connectionId) : undefined))
.orderBy(desc(connectionLog.id))
.limit(Math.min(o.limit ?? 100, 500));
}
/** Agents to choose from in a grant (the platform's team). */
export async function grantableAgents(db: Db): Promise<Array<{ id: number; name: string }>> {
return db.select({ id: agents.id, name: agents.name }).from(agents).orderBy(asc(agents.name));
}
// ---------- agent side ----------
interface SessionCtx {
id: number;
projectId: number;
agentId: number | null;
agentName: string | null;
container: string | null;
}
const agentIsolated = (s: SessionCtx, env: NodeJS.ProcessEnv = process.env) => !!s.container || allowUnisolated(env);
/** false: the session's agent runs outside a container and the gateway refuses it. */
export async function sessionIsolated(db: Db, sessionId: number): Promise<boolean> {
const s = await sessionCtx(db, sessionId);
return !!s && agentIsolated(s);
}
async function sessionCtx(db: Db, sessionId: number | null | undefined): Promise<SessionCtx | null> {
if (sessionId == null) return null;
const [s] = await db
.select({ id: sessions.id, projectId: sessions.projectId, agentId: sessions.agentId, agentName: agents.name, container: sessions.container })
.from(sessions)
.leftJoin(agents, eq(agents.id, sessions.agentId))
.where(eq(sessions.id, sessionId));
return s ?? null;
}
export interface AgentConnection {
id: number;
name: string;
operations: string[];
}
/** What this session's agent may use: active connections granted to its project and agent. */
export async function agentConnections(db: Db, sessionId: number): Promise<AgentConnection[]> {
const s = await sessionCtx(db, sessionId);
// Like the gateway: an unisolated agent is refused, so it is shown nothing.
if (!s || !agentIsolated(s)) return [];
const rows = await db
.select({ id: connections.id, name: connections.name, agentId: connectionGrants.agentId, operations: connectionGrants.operations })
.from(connectionGrants)
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
.where(and(eq(connectionGrants.projectId, s.projectId), eq(connections.status, "active")))
.orderBy(asc(connections.name));
const by = new Map<number, AgentConnection>();
for (const r of rows) {
if (r.agentId != null && r.agentId !== s.agentId) continue;
const c = by.get(r.id) ?? { id: r.id, name: r.name, operations: [] };
c.operations = [...new Set([...c.operations, ...r.operations])];
by.set(r.id, c);
}
return [...by.values()];
}
export interface ConnectionCall {
sessionId: number | null | undefined;
/** Connection id or its name (when only one granted connection has it). */
connection: string | number;
method: string;
path: string;
body?: string | null;
contentType?: string | null;
}
export type ConnectionResult =
| { ok: true; status: number; contentType: string | null; body: string; truncated: boolean }
| { ok: false; reason: ConnectionReason; status?: number };
/** One outbound request, injectable in tests. */
export type ConnectionFetch = (o: { url: URL; method: string; headers: Record<string, string>; body: Buffer | null }) => Promise<{ status: number; contentType: string | null; body: Buffer; truncated: boolean; location?: boolean }>;
class Refused extends Error {
reason: ConnectionReason;
constructor(reason: ConnectionReason) {
super(reason);
this.reason = reason;
}
}
/**
* Real request: a fresh socket per call (no keep-alive reuse past the address check), no redirects, every address the host resolves to at connect time is checked
* (so DNS rebinding can't swap a public name for 127.0.0.1), size and time limits.
*/
export const defaultConnectionFetch: ConnectionFetch = ({ url, method, headers, body }) =>
new Promise((resolve, reject) => {
const guardedLookup = (host: string, opts: object, cb: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void) => {
dnsLookup(host, { ...opts, all: true }, (err, addrs) => {
if (err) return cb(err, "", 4);
const list = addrs as LookupAddress[];
if (!list.length || (!allowPrivate() && list.some((a) => isBlockedAddress(a.address)))) return cb(Object.assign(new Error("blocked address"), { code: "PEPPA_BLOCKED" }), "", 4);
if ((opts as { all?: boolean }).all) return cb(null, list);
cb(null, list[0]!.address, list[0]!.family);
});
};
const literal = url.hostname.replace(/^\[|\]$/g, "");
if (isIP(literal) && !allowPrivate() && isBlockedAddress(literal)) return reject(new Refused("blocked_address"));
const req = (url.protocol === "https:" ? httpsRequest : httpRequest)(url, { method, headers, lookup: guardedLookup as never, timeout: CONNECTION_TIMEOUT_MS, agent: false }, (res: IncomingMessage) => {
const chunks: Buffer[] = [];
let size = 0;
let truncated = false;
res.on("data", (c: Buffer) => {
if (truncated) return;
size += c.length;
if (size > CONNECTION_RESPONSE_MAX_BYTES) {
truncated = true;
chunks.push(c.subarray(0, c.length - (size - CONNECTION_RESPONSE_MAX_BYTES)));
res.destroy();
return;
}
chunks.push(c);
});
const done = () => resolve({ status: res.statusCode ?? 0, contentType: (res.headers["content-type"] as string | undefined) ?? null, body: Buffer.concat(chunks), truncated, location: !!res.headers.location });
res.on("end", done);
res.on("close", done);
res.on("error", () => (truncated ? done() : reject(new Refused("upstream_error"))));
});
req.on("timeout", () => req.destroy(new Refused("timeout")));
req.on("error", (e: NodeJS.ErrnoException) => reject(e instanceof Refused ? e : new Refused(e.code === "PEPPA_BLOCKED" ? "blocked_address" : "upstream_error")));
if (body) req.write(body);
req.end();
});
const CONTENT_TYPE_RE = /^[a-z]+\/[a-z0-9.+-]+(;\s*charset=[a-z0-9-]+)?$/i;
/**
* The gateway: decides, injects the key, calls the service, masks the key in the answer and
* writes one journal row (method, path without query, decision, reason — never a key or a body).
*/
export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: ConnectionFetch; now?: Date; env?: NodeJS.ProcessEnv } = {}): Promise<ConnectionResult> {
const now = o.now ?? new Date();
const method = String(call.method ?? "").toUpperCase();
const rawPath = String(call.path ?? "");
const logPath = (rawPath.split("?")[0] ?? "").slice(0, 300) || "/";
const s = await sessionCtx(db, call.sessionId);
let conn: typeof connections.$inferSelect | null = null;
const record = async (decision: "allowed" | "denied" | "failed", reason: ConnectionReason | null, statusCode: number | null) => {
if (!conn) return; // nothing to attribute: an unknown connection is not someone's journal
await db.insert(connectionLog).values({
ownerId: conn.ownerId,
connectionId: conn.id,
connectionName: conn.name,
projectId: s?.projectId ?? null,
sessionId: s?.id ?? null,
agentId: s?.agentId ?? null,
agentName: s?.agentName ?? null,
method: method.slice(0, 10) || "?",
path: logPath,
decision,
reason,
statusCode,
createdAt: now,
});
};
const deny = async (reason: ConnectionReason): Promise<ConnectionResult> => {
await record("denied", reason, null);
return { ok: false, reason };
};
if (!s) return { ok: false, reason: "no_session" };
// Find the connection among those granted to this project (never by a bare id of someone else).
const granted = await db
.select({ c: connections, agentId: connectionGrants.agentId, operations: connectionGrants.operations })
.from(connectionGrants)
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
.where(eq(connectionGrants.projectId, s.projectId));
const want = String(call.connection).trim();
const byId = /^\d+$/.test(want) ? granted.filter((g) => g.c.id === Number(want)) : [];
const matches = byId.length ? byId : granted.filter((g) => g.c.name === want);
const ids = new Set(matches.map((g) => g.c.id));
if (ids.size > 1) return { ok: false, reason: "ambiguous_connection" };
if (!ids.size) return { ok: false, reason: "unknown_connection" };
conn = matches[0]!.c;
if (!agentIsolated(s, o.env)) return deny("not_isolated");
if (conn.status !== "active" || !conn.secretEnc) return deny("revoked");
const mine = matches.filter((g) => g.agentId == null || g.agentId === s.agentId);
if (!mine.length) return deny("no_grant");
if (!CONNECTION_METHODS.includes(method as ConnectionMethod)) return deny("bad_request");
const clean = cleanPath(rawPath);
if (!clean) return deny("bad_path");
if (!operationAllows(mine.flatMap((g) => g.operations), method, clean.path)) return deny("operation_denied");
const body = call.body == null || call.body === "" ? null : Buffer.from(String(call.body));
if (body && (body.length > CONNECTION_BODY_MAX_BYTES || method === "GET")) return deny("bad_request");
const contentType = call.contentType?.trim() || (body ? "application/json" : null);
if (contentType && !CONTENT_TYPE_RE.test(contentType)) return deny("bad_request");
const [{ n }] = (await db.select({ n: count() }).from(connectionLog).where(and(eq(connectionLog.sessionId, s.id), gt(connectionLog.createdAt, new Date(now.getTime() - 60_000))))) as [{ n: number }];
if (n >= CONNECTION_RATE_PER_MIN) return deny("rate_limited");
// Target = base + path; the host and the base path must survive URL parsing unchanged.
const base = new URL(conn.baseUrl);
const url = new URL(base.href.replace(/\/$/, "") + clean.path + (clean.query ? `?${clean.query}` : ""));
if (url.origin !== base.origin || !(url.pathname === base.pathname || url.pathname.startsWith(base.pathname.replace(/\/$/, "") + "/"))) return deny("bad_path");
let secret: string;
try {
secret = decrypt(conn.secretEnc);
} catch {
await record("failed", "upstream_error", null);
return { ok: false, reason: "upstream_error" };
}
// Only these headers reach the service: the agent can't add or override any other.
const headers: Record<string, string> = { "user-agent": "PeppaFactory-AccessHub/1", accept: "*/*" };
if (contentType) headers["content-type"] = contentType;
if (body) headers["content-length"] = String(body.length);
if (conn.authKind === "header" && conn.authHeader) headers[conn.authHeader.toLowerCase()] = secret;
else headers.authorization = `Bearer ${secret}`;
try {
const res = await (o.fetch ?? defaultConnectionFetch)({ url, method, headers, body });
if (res.status >= 300 && res.status < 400 && res.location) {
await record("failed", "redirect", res.status);
return { ok: false, reason: "redirect", status: res.status };
}
await record("allowed", res.truncated ? "too_large" : null, res.status);
await db.update(connections).set({ lastUsedAt: now }).where(eq(connections.id, conn.id));
const text = maskSecrets(res.body.toString("utf8"), secret.length >= 4 ? [secret] : []);
return { ok: true, status: res.status, contentType: res.contentType, body: text, truncated: res.truncated };
} catch (e) {
const reason = e instanceof Refused ? e.reason : "upstream_error";
await record(reason === "blocked_address" ? "denied" : "failed", reason, null);
return { ok: false, reason };
}
}