// PEP-17: the agent relay — the only way an agent in a runner container (here or on a host, // PEP-40) reaches Peppa. Bearer = the run's token (core agentRelayToken). Hooks run here as the // real peppa-hook; MCP is the agent server of the session's project (injected by the caller); // git and the Gitea API are proxied only to the project's repo with the bot token, which never // leaves Peppa. Request → Response handlers: Next routes and the test server share them. import { spawn } from "node:child_process"; import { mkdirSync, writeFileSync } from "node:fs"; import { createServer, type Server } from "node:http"; import { join } from "node:path"; import { Readable } from "node:stream"; import { FINISHED_SESSION_STATUSES, getSession, parseAgentRelayToken, type Project, type SessionView } from "@peppa/core"; import { projects, type Db } from "@peppa/db"; import { loadEnv, peppaHome } from "@peppa/shared"; import { eq } from "drizzle-orm"; import { HOOK_BIN } from "./providers.ts"; /** Hook requests are answered within this time; a longer wait (a blocking question) is resumed by `rid`. */ const RELAY_WAIT_MS = () => Number(process.env.PEPPA_RELAY_WAIT_MS ?? 25_000); const MAX_BODY = 12 * 1024 * 1024; export interface RelayContext { session: SessionView; project: Project; } export type RelayMcpHandler = (db: Db, ctx: RelayContext, req: Request) => Promise; const jsonRes = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } }); /** The run behind the Bearer token: current generation; `alive` — the session is not finished. */ export async function relayAuth(db: Db, req: Request, opts: { alive: boolean }): Promise { const token = req.headers.get("authorization")?.match(/^Bearer\s+(\S+)$/i)?.[1]; const t = parseAgentRelayToken(token); if (!t) return null; const session = await getSession(db, t.sessionId).catch(() => null); if (!session || session.generation !== t.generation) return null; if (opts.alive && FINISHED_SESSION_STATUSES.includes(session.status)) return null; const [project] = await db.select().from(projects).where(eq(projects.id, session.projectId)); return project ? { session, project } : null; } // ── hooks ────────────────────────────────────────────────────────────────────── interface HookCall { sessionId: number; done: Promise<{ stdout: string }>; result?: { stdout: string }; expires: number; } type Pending = Map; const pending: Pending = ((globalThis as { __peppaRelayHooks?: Pending }).__peppaRelayHooks ??= new Map()); function runHook(ctx: RelayContext, event: string, args: string[], stdin: string): Promise<{ stdout: string }> { const env = loadEnv(); return new Promise((resolve) => { const p = spawn(HOOK_BIN(), [event, ...args], { stdio: ["pipe", "pipe", "ignore"], env: { ...process.env, PEPPA_SESSION_ID: String(ctx.session.id), PEPPA_GENERATION: String(ctx.session.generation), PEPPA_DB: env.PEPPA_DB, PEPPA_RELAYED: "1", }, }); let out = ""; p.stdout.setEncoding("utf8").on("data", (d) => (out += d)); // A hook never breaks the agent: whatever happens, an answer (maybe empty) goes back. p.on("error", () => resolve({ stdout: "" })); p.on("close", () => resolve({ stdout: out })); p.stdin.on("error", () => {}); p.stdin.end(stdin); }); } /** The transcript lives in the container: the shim sends its tail, the hook reads this copy. */ function withTranscript(ctx: RelayContext, stdin: string, transcript: unknown): string { if (typeof transcript !== "string" || !transcript) return stdin; try { const input = JSON.parse(stdin) as Record; const dir = join(peppaHome(), "relay", `s${ctx.session.id}`); mkdirSync(dir, { recursive: true, mode: 0o700 }); const file = join(dir, "transcript.jsonl"); writeFileSync(file, transcript.slice(-8 * 1024 * 1024)); return JSON.stringify({ ...input, transcript_path: file }); } catch { return stdin; } } async function waitFor(call: HookCall, ms: number): Promise<{ stdout: string } | null> { if (call.result) return call.result; let timer: NodeJS.Timeout | undefined; const r = await Promise.race([call.done, new Promise((res) => (timer = setTimeout(() => res(null), ms)))]); clearTimeout(timer); return r; } async function hookRequest(db: Db, req: Request): Promise { const ctx = await relayAuth(db, req, { alive: true }); if (!ctx) return jsonRes({ error: "invalid agent token" }, 401); const body = (await req.json().catch(() => null)) as { event?: string; args?: unknown; stdin?: unknown; transcript?: unknown; rid?: string } | null; if (!body) return jsonRes({ error: "bad request" }, 400); const now = Date.now(); for (const [k, c] of pending) if (c.expires < now) pending.delete(k); let rid = body.rid; let call = rid ? pending.get(rid) : undefined; if (rid && (!call || call.sessionId !== ctx.session.id)) return jsonRes({ error: "unknown rid" }, 404); if (!call) { if (!body.event || !/^[a-z-]{1,40}$/.test(body.event)) return jsonRes({ error: "bad event" }, 400); const args = Array.isArray(body.args) ? body.args.filter((a): a is string => typeof a === "string").slice(0, 4) : []; const stdin = withTranscript(ctx, typeof body.stdin === "string" ? body.stdin : "", body.transcript); rid = crypto.randomUUID(); const c: HookCall = { sessionId: ctx.session.id, done: runHook(ctx, body.event, args, stdin), expires: now + 20 * 60_000 }; void c.done.then((r) => (c.result = r)); call = c; pending.set(rid, call); } const r = await waitFor(call, RELAY_WAIT_MS()); if (!r) return jsonRes({ wait: true, rid }); pending.delete(rid!); return jsonRes({ stdout: r.stdout }); } // ── git / Gitea proxy ────────────────────────────────────────────────────────── /** Only the session project's repo: git over HTTP (`owner/repo[.git]/…`) and its API (`api/v1/repos/owner/repo…`). */ export function allowedGitPath(project: Pick, path: string): boolean { const p = path.replace(/^\/+/, ""); // PEP-133: no dot segments in any spelling (`%2e%2e`, `%252e…`), no encoded slashes or backslashes — // fetch() would fold them into a path outside the project's repo, with the bot's token. if (/\\|%(?:2e|2f|5c|25)/i.test(p) || p.split("/").some((seg) => seg === ".." || seg === ".")) return false; const repo = `${project.giteaOwner}/${project.giteaRepo}`.toLowerCase(); const lower = p.toLowerCase(); return lower.startsWith(`${repo}.git/`) || lower.startsWith(`${repo}/`) || lower === `api/v1/repos/${repo}` || lower.startsWith(`api/v1/repos/${repo}/`); } const FORWARD_HEADERS = ["content-type", "content-encoding", "accept", "git-protocol", "content-length"]; const BACK_HEADERS = ["content-type", "cache-control", "expires", "pragma", "link", "x-total-count"]; async function gitRequest(db: Db, req: Request, rest: string): Promise { // The generation is enough here: a resumed runner's clone is made again before it is alive. const ctx = await relayAuth(db, req, { alive: false }); if (!ctx) return new Response("invalid agent token\n", { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="peppa-agent"' } }); if (!allowedGitPath(ctx.project, rest)) return new Response("forbidden: only this project's repository\n", { status: 403 }); const env = loadEnv(); const token = (env as Record).GITEA_TOKEN; const url = `${env.GITEA_URL.replace(/\/$/, "")}/${rest.replace(/^\/+/, "")}${new URL(req.url).search}`; const headers = new Headers(); for (const h of FORWARD_HEADERS) { const v = req.headers.get(h); if (v) headers.set(h, v); } // Undecoded bytes both ways (fetch would gunzip a response but keep its header). headers.set("accept-encoding", "identity"); if (token) headers.set("authorization", `token ${token}`); const hasBody = req.method !== "GET" && req.method !== "HEAD"; const up = await fetch(url, { method: req.method, headers, body: hasBody ? req.body : undefined, duplex: "half", redirect: "manual" } as RequestInit); const back = new Headers(); for (const h of BACK_HEADERS) { const v = up.headers.get(h); if (v) back.set(h, v); } return new Response(up.body, { status: up.status, headers: back }); } // ── entry ────────────────────────────────────────────────────────────────────── /** `path` — after /api/agent (e.g. "/hook", "/mcp", "/git/owner/repo.git/info/refs"). */ export async function handleAgentRelay(db: Db, req: Request, path: string, opts: { mcp?: RelayMcpHandler } = {}): Promise { try { if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY) return jsonRes({ error: "too large" }, 413); if (path === "/hook" && req.method === "POST") return await hookRequest(db, req); if (path === "/mcp") { if (req.method !== "POST") return new Response("Method Not Allowed (stateless server: POST only)", { status: 405, headers: { Allow: "POST" } }); const ctx = await relayAuth(db, req, { alive: true }); if (!ctx) return jsonRes({ error: "invalid agent token" }, 401); if (!opts.mcp) return jsonRes({ error: "mcp not served here" }, 501); return await opts.mcp(db, ctx, req); } if (path.startsWith("/git/")) return await gitRequest(db, req, path.slice(5)); return jsonRes({ error: "not found" }, 404); } catch (e) { return jsonRes({ error: (e as Error).message }, 500); } } /** The relay on node:http (tests; a standalone relay if the web is not reachable from hosts). */ export function serveAgentRelay(db: Db, port: number, opts: { mcp?: RelayMcpHandler; host?: string } = {}): Promise { const server = createServer(async (req, res) => { const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`); const path = url.pathname.replace(/^\/api\/agent/, ""); const hasBody = req.method !== "GET" && req.method !== "HEAD"; const request = new Request(url, { method: req.method, headers: Object.entries(req.headers).flatMap(([k, v]) => (v === undefined ? [] : (Array.isArray(v) ? v : [v]).map((x) => [k, x] as [string, string]))), body: hasBody ? (Readable.toWeb(req) as ReadableStream) : undefined, duplex: "half", } as RequestInit); const r = await handleAgentRelay(db, request, path, opts); res.writeHead(r.status, Object.fromEntries(r.headers)); if (r.body) for await (const chunk of r.body as unknown as AsyncIterable) res.write(chunk); res.end(); }); return new Promise((resolve) => server.listen(port, opts.host ?? "127.0.0.1", () => resolve(server))); }