Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat: accept signed GitHub webhook events

Sebastian B08f12726e342
diff --git a/apps/docs/content/docs/features/automation.mdx b/apps/docs/content/docs/features/automation.mdx
index cb58290669..a75a1735e3 100644
--- a/apps/docs/content/docs/features/automation.mdx
+++ b/apps/docs/content/docs/features/automation.mdx
@@ -48,6 +48,42 @@ The receiver exposes only health and secret hook routes. It does not expose the
Bearer authentication is preferred because it keeps the secret out of URLs and most access logs. A capability URL is available for senders that cannot set headers.
+### GitHub events
+
+Ask your bot: "When a pull request opens in acme/widgets, review it."
+The bot first checks its connected-app events with `trigger_info action=events app=github`.
+Connect GitHub and allow the bot to use it under **Access**.
+Use the event and repository settings returned by that catalog.
+Available events and branch settings depend on Composio's event type.
+App events require OpenMausBot's managed connected apps; they do not support your own Composio key.
+
+Use a repository webhook when the catalog does not offer the event you need:
+
+1. Ask the bot to create a webhook automation for the work.
+ Include the repository, action, and branch conditions in its instructions.
+ For example: "Review acme/widgets PRs only when action is opened and the base branch is main. Stop for other events."
+2. Open the automation under **Automations** and copy its endpoint and secret.
+ The bot can also retrieve them with `trigger_info` and `include_address`.
+3. In the GitHub repository, open **Settings → Webhooks → Add webhook**.
+4. Set **Payload URL** to the endpoint followed by `/github`, such as `https://bots.example.com/hooks/wh_example/github`.
+5. Set **Content type** to `application/json` and **Secret** to the automation's secret.
+ Keep SSL verification enabled.
+6. Select the events you need, such as **Pull requests**, **Issues**, **Pushes**, **Releases**, or **Workflow runs**.
+ Save the webhook and check GitHub's recent deliveries.
+
+The signed endpoint verifies `X-Hub-Signature-256` against the raw request body before parsing it.
+It requires `X-GitHub-Delivery` and `X-GitHub-Event`.
+Retries with the same delivery ID keep the existing duplicate handling.
+The URL contains no secret. Do not append the secret to the signed URL.
+If an older automation cannot show its secret, replace its address and update GitHub's secret.
+
+The repository webhook selects the repository and event families.
+The automation's event-type list can also limit families, such as `pull_request` or `workflow_run`.
+Action and branch conditions in instructions are checked by the bot after a run starts.
+For merged PRs, require `action=closed` and `pull_request.merged=true`.
+For CI failures, require `action=completed` and `workflow_run.conclusion=failure`.
+External event content is untrusted; it does not grant the bot extra permissions.
+
### A bot that sets up its own webhook
When a bot creates a webhook automation from chat, it gets the private address in the result, and it can ask for it again later, so it can paste the address into the other app's setup itself instead of asking you to use **Copy address**. Only the bot the automation belongs to gets it, or a Chief of Staff that can reach that bot (bots with a different audience on a shared workspace cannot), and only in a conversation you drive: never in a run that a webhook or app event started, and never in a My Cloud conversation a guest drives. The address stays in that tool result; chat transcripts, step details and logs show it masked, and the Automations page keeps the secret hidden until you press **Show**. **Copy address** copies the same address the bot has, so copying never breaks a setup; **Replace address** makes a new one and the old one stops working.
diff --git a/server/webhook-address.ts b/server/webhook-address.ts
index e556bea9a0..a0c3b83cb7 100644
--- a/server/webhook-address.ts
+++ b/server/webhook-address.ts
@@ -38,7 +38,7 @@ export function webhookAddress(webhooks: Pick<WebhookManager, "currentSecret">,
url: credential.url,
endpoint: credential.endpointUrl,
bearer: credential.secret,
- note: `Paste url into the setup of the app that sends to this automation, and nowhere else: never repeat it in chat, notes, files or messages to other bots. An app that can't take the full address sends to endpoint with the header "Authorization: Bearer <bearer>".${local}`,
+ note: `Paste url into the setup of the app that sends to this automation, and nowhere else: never repeat it in chat, notes, files or messages to other bots. An app that can't take the full address sends to endpoint with the header "Authorization: Bearer <bearer>". For GitHub, use endpoint + "/github" as Payload URL, application/json as Content type, and bearer as Secret. Select the requested GitHub events; put action and branch conditions in the automation's instructions.${local}`,
};
}
diff --git a/server/webhook-github.test.ts b/server/webhook-github.test.ts
new file mode 100644
index 0000000000..b5eb7d0e60
--- /dev/null
+++ b/server/webhook-github.test.ts
@@ -0,0 +1,139 @@
+import { createHmac } from "node:crypto";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { listenWebhookIngress, MAX_WEBHOOK_BODY_BYTES, type WebhookIngress } from "./webhook-ingress.ts";
+import { WebhookManager } from "./webhooks.ts";
+
+let dir: string;
+let manager: WebhookManager;
+let ingress: WebhookIngress;
+let id: string;
+let endpointId: string;
+let secret: string;
+let pending: number;
+const queued: Array<{ prompt: string; deliveryId: string }> = [];
+const body = '{ "action": "opened", "repository": { "full_name": "acme/widgets" }, "pull_request": { "number": 7, "title": "Fix café" } }';
+const signature = (raw: string | Buffer, key = secret) => `sha256=${createHmac("sha256", key).update(raw).digest("hex")}`;
+
+function loadManager() {
+ return new WebhookManager({
+ file: join(dir, "webhooks.json"),
+ botState: () => "ready",
+ pendingRuns: () => pending,
+ enqueue: (input) => {
+ queued.push(input);
+ return { id: `run-${queued.length}` };
+ },
+ });
+}
+
+beforeEach(async () => {
+ dir = mkdtempSync(join(tmpdir(), "omb-github-webhook-"));
+ queued.length = 0;
+ pending = 0;
+ manager = loadManager();
+ const created = manager.create({ name: "Review PRs", prompt: "Review opened PRs in acme/widgets.", botId: "bot-1", eventTypes: ["pull_request"] });
+ ({ id, endpointId } = created.webhook);
+ secret = created.secret;
+ ingress = await listenWebhookIngress(manager, { port: 0 });
+});
+
+afterEach(async () => {
+ await new Promise<void>((resolve) => ingress.server.close(() => resolve()));
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function send(raw: string | Buffer = body, headers: Record<string, string> = {}, endpoint = endpointId) {
+ return fetch(`${ingress.baseUrl}/hooks/${endpoint}/github`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-github-event": "pull_request", "x-github-delivery": "delivery-1", "x-hub-signature-256": signature(raw), ...headers },
+ body: raw,
+ });
+}
+
+describe("signed GitHub webhook ingress", () => {
+ it("authenticates the raw body without a URL secret and deduplicates GitHub retries", async () => {
+ const first = await send(body, { "idempotency-key": "unrelated-1", "x-webhook-event": "push" });
+ expect(first.status).toBe(202);
+ expect(await first.json()).toMatchObject({ runId: "run-1", duplicate: false, deliveryId: "delivery-1" });
+ pending = 100;
+ const retry = await send(body, { "idempotency-key": "unrelated-2" });
+ expect(retry.status).toBe(202);
+ expect(await retry.json()).toMatchObject({ runId: "run-1", duplicate: true });
+ expect(queued).toHaveLength(1);
+ expect(queued[0]?.prompt).toContain("Event: pull_request");
+ expect(queued[0]?.prompt).toContain("Fix café");
+ expect(queued[0]?.prompt).not.toContain(secret);
+ expect(JSON.stringify(manager.list())).not.toContain(secret);
+ expect(readFileSync(join(dir, "webhooks.json"), "utf8")).not.toContain(secret);
+ });
+
+ it.each(["", "sha1=" + "a".repeat(40), "sha256=bad", "sha256=" + "0".repeat(64)])("rejects signature %j even with a bearer secret", async (value) => {
+ expect((await send(body, { "x-hub-signature-256": value, authorization: `Bearer ${secret}` })).status).toBe(401);
+ expect(queued).toHaveLength(0);
+ expect(manager.listAttempts()).toMatchObject([{ outcome: "rejected", statusCode: 401 }]);
+ });
+
+ it("rejects changed bodies and unknown endpoints before parsing JSON", async () => {
+ expect((await send(body + " ", { "x-hub-signature-256": signature(body) })).status).toBe(401);
+ expect((await send("{", { "x-hub-signature-256": signature(body) })).status).toBe(401);
+ expect((await send(body, {}, "wh_unknown")).status).toBe(401);
+ expect((await send("{")).status).toBe(400);
+ expect(queued).toHaveLength(0);
+ });
+
+ it("requires GitHub delivery and event headers", async () => {
+ for (const header of ["x-github-delivery", "x-github-event"]) {
+ expect((await send(body, { [header]: "" })).status).toBe(401);
+ }
+ expect(queued).toHaveLength(0);
+ });
+
+ it("signs bytes before UTF-8 decoding and keeps the body limit", async () => {
+ const bytes = Buffer.from([0xff, 0xfe, 0x61]);
+ expect((await send(bytes, { "content-type": "text/plain", "x-hub-signature-256": signature(bytes.toString("utf8")) })).status).toBe(401);
+ expect((await send(bytes, { "content-type": "text/plain" })).status).toBe(202);
+ expect((await send("x".repeat(MAX_WEBHOOK_BODY_BYTES + 1))).status).toBe(413);
+ expect(queued).toHaveLength(1);
+ });
+
+ it("keeps pause, event selection and queue admission checks", async () => {
+ manager.update(id, { enabled: false });
+ expect((await send()).status).toBe(409);
+ manager.update(id, { enabled: true });
+ const ignored = await send(body, { "x-github-event": "push" });
+ expect(ignored.status).toBe(202);
+ expect(await ignored.json()).toMatchObject({ ignored: true });
+ pending = 100;
+ expect((await send()).status).toBe(429);
+ expect(queued).toHaveLength(0);
+ });
+
+ it("uses the kept secret and delivery receipts after restart, and refuses an old signature after rotation", async () => {
+ expect((await send()).status).toBe(202);
+ await new Promise<void>((resolve) => ingress.server.close(() => resolve()));
+ manager = loadManager();
+ ingress = await listenWebhookIngress(manager, { port: 0 });
+ expect(await (await send()).json()).toMatchObject({ duplicate: true, runId: "run-1" });
+ const rotated = manager.rotateSecret(id)!;
+ expect((await send()).status).toBe(401);
+ secret = rotated.secret;
+ expect((await send(body, { "x-github-delivery": "delivery-2" })).status).toBe(202);
+ expect(queued).toHaveLength(2);
+ });
+
+ it("fails closed when the encrypted secret is unavailable", async () => {
+ const path = join(dir, "webhooks.json");
+ const saved = JSON.parse(readFileSync(path, "utf8"));
+ delete saved.webhooks[0].sealedSecret;
+ writeFileSync(path, JSON.stringify(saved));
+ await new Promise<void>((resolve) => ingress.server.close(() => resolve()));
+ manager = loadManager();
+ ingress = await listenWebhookIngress(manager, { port: 0 });
+ expect((await send()).status).toBe(401);
+ expect(queued).toHaveLength(0);
+ });
+});
diff --git a/server/webhook-ingress.ts b/server/webhook-ingress.ts
index 8fe1652b7a..0f01962ca2 100644
--- a/server/webhook-ingress.ts
+++ b/server/webhook-ingress.ts
@@ -24,7 +24,7 @@ function json(res: ServerResponse, status: number, body: JsonValue): void {
res.end(JSON.stringify(body));
}
-async function readRawBody(req: IncomingMessage): Promise<string> {
+async function readRawBody(req: IncomingMessage): Promise<Buffer> {
const chunks: Buffer[] = [];
let bytes = 0;
try {
@@ -41,7 +41,7 @@ async function readRawBody(req: IncomingMessage): Promise<string> {
if (parsed.success && parsed.data.status === 413) throw error;
throw Object.assign(new Error("Could not read webhook body"), { status: 400 });
}
- return Buffer.concat(chunks, bytes).toString("utf8");
+ return Buffer.concat(chunks, bytes);
}
function parsePayload(raw: string, contentType: string): JsonValue {
@@ -106,29 +106,37 @@ export function createWebhookIngressHandler(manager: WebhookManager, claimReques
let release: (() => void) | undefined;
try {
release = claimRequest?.();
+ const github = match[2] === "github";
let secret = "";
- try {
- secret = (match[2] ? decodeURIComponent(match[2]) : "") || bearerSecret(req);
- } catch {
+ let raw: Buffer | undefined;
+ if (github) {
+ if (header(req, "x-github-delivery")?.trim() && header(req, "x-github-event")?.trim()) {
+ raw = await readRawBody(req);
+ secret = manager.githubSecret(match[1], header(req, "x-hub-signature-256"), raw) ?? "";
+ }
+ } else {
+ try {
+ secret = (match[2] ? decodeURIComponent(match[2]) : "") || bearerSecret(req);
+ } catch {
+ }
}
- // Reject bad capability URLs before buffering or parsing attacker input.
if (!manager.authorize(match[1], secret)) {
manager.recordUnauthorized(match[1], {
contentType: header(req, "content-type"),
- eventName: eventName(req),
- deliveryId: deliveryId(req),
+ eventName: github ? header(req, "x-github-event") : eventName(req),
+ deliveryId: github ? header(req, "x-github-delivery") : deliveryId(req),
});
return json(res, 401, { error: "Invalid webhook URL or secret" });
}
- const raw = await readRawBody(req);
+ raw ??= await readRawBody(req);
const contentType = header(req, "content-type")?.split(";")[0]?.trim().toLowerCase() ?? "text/plain";
- const payload = parsePayload(raw, contentType);
+ const payload = parsePayload(raw.toString("utf8"), contentType);
const result = await manager.receive(match[1], secret, {
payload,
contentType,
- eventName: eventName(req),
+ eventName: github ? header(req, "x-github-event")?.trim() : eventName(req),
userAgent: header(req, "user-agent"),
- deliveryId: deliveryId(req),
+ deliveryId: github ? header(req, "x-github-delivery")?.trim() : deliveryId(req),
});
return json(res, 202, { accepted: true, ...result });
} catch (error) {
diff --git a/server/webhooks.ts b/server/webhooks.ts
index 97f7dceca6..682260ce84 100644
--- a/server/webhooks.ts
+++ b/server/webhooks.ts
@@ -1,4 +1,4 @@
-import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
+import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
import { mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { z } from "zod";
@@ -563,6 +563,16 @@ export class WebhookManager {
return Boolean(trigger && secretMatches(secret, trigger.secretHash));
}
+ /** The kept secret leaves this method only after GitHub's signature authenticates the raw request bytes. */
+ githubSecret(endpointId: string, signature: string | undefined, raw: Buffer): string | null {
+ if (!signature || !/^sha256=[a-f0-9]{64}$/.test(signature)) return null;
+ const trigger = this.webhooks.find((candidate) => candidate.endpointId === endpointId);
+ const secret = trigger && this.unseal(trigger);
+ if (!secret) return null;
+ const expected = createHmac("sha256", secret).update(raw).digest();
+ return timingSafeEqual(Buffer.from(signature.slice(7), "hex"), expected) ? secret : null;
+ }
+
receive(endpointId: string, secret: string, event: WebhookEvent): WebhookReceiveResult | Promise<WebhookReceiveResult> {
const trigger = this.webhooks.find((candidate) => candidate.endpointId === endpointId);
if (!trigger || !secretMatches(secret, trigger.secretHash)) fail(401, "Invalid webhook URL or secret");