Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(#6308): the hook route checks the body's bot and conversation again
milind-sonid5707fa6fe93
diff --git a/server/hooks.e2e.test.ts b/server/hooks.e2e.test.tsindex 5abcffdce6..1d5e3f09e7 100644--- a/server/hooks.e2e.test.ts+++ b/server/hooks.e2e.test.ts@@ -144,12 +144,21 @@ posixOnly("engine hooks e2e (fake Claude honouring the settings hooks)", () => {});posixOnly("engine hooks e2e: full tool output that arrives after its turn ended", () => {- const h = harness("late", {}, { FAKE_CLAUDE_HOOKS_AFTER_TURN_MS: "1500" });+ const h = harness("late", {}, { FAKE_CLAUDE_HOOKS_AFTER_TURN_MS: "4000" });it("is still saved on that turn's rows, each once, and the ended turn's bearer is good for nothing else", async () => {const bot = await h.runTurn();expect(bot.messages.find((m: Msg) => m.kind === "digest").digest?.hookCoverage).toBe("preview");const rows = async (): Promise<Msg[]> => (await h.getBot(bot.id)).messages.filter((m: Msg) => m.kind === "activity" && m.tool?.itemId);+ const tokenDir = createHash("sha256").update(`${bot.id}\0${bot.threadId}`).digest("hex").slice(0, 24);+ const bearer = { authorization: `Bearer ${readFileSync(join(h.home(), ".openmausbot", "hook-tokens", tokenDir, "token"), "utf8").trim()}` };++ // While the late outputs are still owed, the ended turn's bearer writes only into its own bot and conversation.+ const owed = (await rows()).find((m) => m.tool!.fullResult !== true)!;+ for (const named of [{ botId: "another-bot" }, { fromBotId: "another-bot" }, { threadId: "another-thread" }, { fromThreadId: "another-thread" }]) {+ const forged = await h.api("POST", "/api/internal/hook", { event: "PostToolUse", payload: { tool_use_id: owed.tool!.itemId, tool_response: "forged" }, ...named }, bearer);+ expect(forged.status, JSON.stringify(named)).toBe(403);+ }await h.waitFor(async () => (await rows()).every((m) => m.tool!.fullResult === true), "the late hooks to save both outputs");const digest = (await h.getBot(bot.id)).messages.find((m: Msg) => m.kind === "digest");expect(digest.digest?.hookCoverage).toBe("full");@@ -157,9 +166,8 @@ posixOnly("engine hooks e2e: full tool output that arrives after its turn ended"const root = join(h.home(), ".openmausbot", "tool-results");const spilled = readdirSync(join(root, readdirSync(root)[0]!)).map((name) => readFileSync(join(root, readdirSync(root)[0]!, name), "utf8"));expect(spilled.some((text) => text.includes(BIG.slice(0, 200)))).toBe(true);+ expect(spilled.some((text) => text.includes("forged"))).toBe(false);- const tokenDir = createHash("sha256").update(`${bot.id}\0${bot.threadId}`).digest("hex").slice(0, 24);- const bearer = { authorization: `Bearer ${readFileSync(join(h.home(), ".openmausbot", "hook-tokens", tokenDir, "token"), "utf8").trim()}` };const [first] = await rows();const again = await h.api("POST", "/api/internal/hook", { event: "PostToolUse", payload: { tool_use_id: first!.tool!.itemId, tool_response: "replaced" } }, bearer);expect(again.status).toBe(401);diff --git a/server/host/internal-body-ids.test.ts b/server/host/internal-body-ids.test.tsnew file mode 100644index 0000000000..9205052254--- /dev/null+++ b/server/host/internal-body-ids.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";++import { internalBodyRefusal } from "./internal-body-ids.ts";++describe("an internal request body's bot and conversation", () => {+ it("passes a body that names none, or only the bearer's own", () => {+ expect(internalBodyRefusal({ event: "PostToolUse", payload: { botId: "other" } }, "b1", "t1")).toBeNull();+ expect(internalBodyRefusal({ fromBotId: "b1", botId: "b1", fromThreadId: "t1", threadId: "t1" }, "b1", "t1")).toBeNull();+ for (const body of [null, undefined, "text", 42, ["b2"]]) expect(internalBodyRefusal(body, "b1", "t1")).toBeNull();+ });++ it("refuses a body that names another bot", () => {+ for (const key of ["fromBotId", "botId"]) {+ expect(internalBodyRefusal({ [key]: "b2" }, "b1", "t1")).toEqual({ status: 403, error: "the internal capability belongs to a different bot" });+ }+ });++ it("refuses a body that names another conversation", () => {+ for (const key of ["fromThreadId", "threadId"]) {+ expect(internalBodyRefusal({ [key]: "t2" }, "b1", "t1")).toEqual({ status: 403, error: "the internal capability belongs to a different conversation" });+ }+ });+});diff --git a/server/host/internal-body-ids.ts b/server/host/internal-body-ids.tsnew file mode 100644index 0000000000..0ad6e01ea6--- /dev/null+++ b/server/host/internal-body-ids.ts@@ -0,0 +1,13 @@+/** The bearer is the authority: a body that names another bot or conversation than the capability's own is refused, so+ * a turn's bearer (live, or an ended turn's for its late tool output) writes only into its own bot and thread. */+export function internalBodyRefusal(body: unknown, botId: string, threadId: string): { status: 403; error: string } | null {+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;+ const fields = body as Record<string, unknown>;+ for (const key of ["fromBotId", "botId"]) {+ if (fields[key] !== undefined && String(fields[key]) !== botId) return { status: 403, error: "the internal capability belongs to a different bot" };+ }+ for (const key of ["fromThreadId", "threadId"]) {+ if (fields[key] !== undefined && String(fields[key]) !== threadId) return { status: 403, error: "the internal capability belongs to a different conversation" };+ }+ return null;+}diff --git a/server/index.ts b/server/index.tsindex 1f908db67a..ecbd2df173 100644--- a/server/index.ts+++ b/server/index.ts@@ -649,7 +649,7 @@ import { createWebhookRoutes } from "./routes/webhooks.ts";import { withScopeHint } from "./connector-scope-hint.ts";import { connectorFileDeps, connectorFileScope, prepareConnectorFiles, withMissingFileHint } from "./connector-files.ts";import { createConnectorCards } from "./host/connector-cards.ts";-import { createLoginMailCodes } from "./host/login-mail-codes.ts"; import { createLateToolResults } from "./host/late-tool-results.ts";+import { createLoginMailCodes } from "./host/login-mail-codes.ts"; import { createLateToolResults } from "./host/late-tool-results.ts"; import { internalBodyRefusal } from "./host/internal-body-ids.ts";import { onThreadSeen, personAsks as personAskAt, sawThread } from "./thread-presence.ts"; import { createWarmSummaryHost, HARNESS_IDLE_FRACTION } from "./host/warm-summary-host.ts";const PORT = Number(process.env.OMB_PORT || process.env.OGB_PORT || 8799);@@ -12879,18 +12879,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (!internalCapabilityIsActive(internalCapability)) {throw Object.assign(new Error(TURN_ENDED_REFUSAL), { status: 401 });}- if (body && typeof body === "object" && !Array.isArray(body)) {- for (const key of ["fromBotId", "botId"] as const) {- if (body[key] !== undefined && String(body[key]) !== internalSender.id) {- throw Object.assign(new Error("the internal capability belongs to a different bot"), { status: 403 });- }- }- for (const key of ["fromThreadId", "threadId"] as const) {- if (body[key] !== undefined && String(body[key]) !== internalCapability.threadId) {- throw Object.assign(new Error("the internal capability belongs to a different conversation"), { status: 403 });- }- }- }+ const refused = internalBodyRefusal(body, internalSender.id, internalCapability.threadId);+ if (refused) throw Object.assign(new Error(refused.error), { status: refused.status });return body;};const requireActiveInternalCapability = () => {@@ -12943,6 +12933,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}if (method === "POST" && path === "/api/internal/hook") {const body = await readBody(req), turnEnded = !internalCapabilityIsActive(internalCapability); if (turnEnded && !lateToolResults.holder(req.headers.authorization)) return json(res, 401, { error: TURN_ENDED_REFUSAL });+ const refused = internalBodyRefusal(body, internalSender.id, internalCapability.threadId); if (refused) return json(res, refused.status, { error: refused.error });return json(res, 200, ingestEngineHook(internalCapability, body, req.headers.authorization, turnEnded));}if (method === "POST" && path === "/api/internal/tool-result") {