Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(webhook): generic secret-gated inbound webhook + token status API

Chaitanya Giri0357ab03bdfc
diff --git a/src/main/config.ts b/src/main/config.ts
index eaff5395..931250f3 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -152,6 +152,15 @@ export interface HarnessConfig {
/** Local HTTP port the webhook server binds to (default 3847). */
slackPort?: number;
+ // ─── Generic inbound webhook + status API ──────────────────────────────────
+ /** Master toggle for the generic webhook HTTP API (POST → work, GET → status). */
+ webhookEnabled?: boolean;
+ /** App-generated shared secret callers echo in `x-md-webhook-secret`. Never
+ * logged, and never forwarded into the routed message/card/response. */
+ webhookSecret?: string;
+ /** Local HTTP port the generic webhook server binds to (default 3849). */
+ webhookPort?: number;
+
// ─── Memory reflection (the janitor's condense half) ───────────────────────
/** Master toggle for the in-process MemoryReflector. Default on. */
reflectEnabled?: boolean;
@@ -184,6 +193,9 @@ const DEFAULTS: HarnessConfig = {
slackBotToken: undefined,
slackChannelId: undefined,
slackPort: undefined,
+ webhookEnabled: false,
+ webhookSecret: undefined,
+ webhookPort: undefined,
// Memory reflection — preventive; nobody is over threshold today, so it sits
// dark until an agent's memory crosses one of these (the verify gate is the
// safety for the LLM step). Thresholds DECIDED by god 2026-06-06.
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 232d8b79..d7e00d7e 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -62,6 +62,11 @@ export interface HiveTask {
* done-summary reply is posted back into. Consumed OUTBOUND only; populating
* it is the inbound/kanban side's job and does not affect routing. */
slack?: { channel: string; thread_ts: string };
+ /** Set when this task originated from a generic webhook POST. Stores the SHA-256
+ * of the capability token (never the raw token — that's returned to the caller
+ * once and never persisted), so a GET status lookup can match by hashing the
+ * presented token. Read-only capability: it never widens routing or exposure. */
+ webhook?: { tokenHash: string };
}
export interface AgentMeta {
diff --git a/src/main/index.ts b/src/main/index.ts
index c899ffe5..7fb939da 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,7 +1,7 @@
import { app, BrowserWindow, clipboard, dialog, ipcMain, powerSaveBlocker, screen, shell, Notification } from 'electron';
import { spawn } from 'node:child_process';
import { rmSync, existsSync, readFileSync, readdirSync, statSync, cpSync, writeFileSync, unlinkSync } from 'node:fs';
-import { randomBytes } from 'node:crypto';
+import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
import { join, resolve, sep } from 'node:path';
import { PtyManager, type SpawnOptions } from './pty';
import {
@@ -24,6 +24,7 @@ import { enrichMessage } from './assistant';
import { readAgentUsage, readContextTokens } from './transcript';
import { listIssues, listCIRuns } from './github';
import { SlackWebhookServer, SlackReplyServer, postSlackReply } from './slack';
+import { WebhookServer, type WebhookInbound, type WebhookTaskStatus } from './webhook';
import { TelemetryCollector } from './telemetry';
import { ControlRegistry } from './control';
@@ -692,6 +693,124 @@ function stopSlackServer(): void {
try { if (existsSync(slackReplyConfigPath())) unlinkSync(slackReplyConfigPath()); } catch { /* noop */ }
}
+// ─── Generic inbound webhook + status API ────────────────────────────────────
+/** The running generic-webhook server, or null when disabled/stopped. A PUBLIC
+ * (tunnel-forwarded) surface — secret-gated, unlike the loopback /reply. */
+let webhookServer: WebhookServer | null = null;
+/** Last public tunnel URL handed out — persisted so Settings can re-show the
+ * endpoint after a reopen (loca.lt rotates it per restart). */
+let lastWebhookUrl: string | undefined;
+
+/** SHA-256 hex of a capability token. The raw token is returned to the caller
+ * exactly once (the POST response) and never persisted; only this digest lands
+ * on the kanban card, so a GET can match without the raw token ever resting. */
+function hashWebhookToken(token: string): string {
+ return createHash('sha256').update(token).digest('hex');
+}
+
+/** Turn a verified webhook POST into hive work: create ONE stamped kanban card
+ * (origin + token hash) and route the message to god/Michael's inbox as a
+ * request. Returns the raw capability token + card id to hand back to the caller
+ * (the ONLY echo of the token). The secret never reaches here. Returns null only
+ * if the card — the thing the caller will poll — could not be created. */
+function handleWebhookMessage(msg: WebhookInbound): { token: string; taskId: string } | null {
+ // 192-bit unguessable token, returned once; only its hash is stored.
+ const token = randomBytes(24).toString('hex');
+ const taskId = `webhook-${randomBytes(8).toString('hex')}`;
+ const full = msg.title ?? msg.message;
+ const title = full.length > 80 ? `${full.slice(0, 79)}…` : full;
+
+ // 1) Create the stamped card. This is the critical step — the caller's token is
+ // only useful if a card exists to poll, so a failure here fails the POST.
+ try {
+ const ledger = hive.tasks() as { tasks?: HiveTask[] };
+ const existing = Array.isArray(ledger?.tasks) ? ledger.tasks : [];
+ const card: HiveTask = {
+ id: taskId,
+ title,
+ description: msg.message,
+ status: 'todo',
+ dependsOn: [],
+ priority: 1,
+ createdAt: new Date().toISOString(),
+ webhook: { tokenHash: hashWebhookToken(token) }
+ };
+ hive.writeTasks([...existing, card]);
+ } catch (e) {
+ console.error('[webhook] could not create task card:', e instanceof Error ? e.message : e);
+ return null;
+ }
+
+ // 2) Route the work to god/Michael (god inbox request). Body carries ONLY the
+ // user message + the card id (so whoever finishes it updates that card's
+ // status/result for the caller's GET) — never the secret or the raw token.
+ // Best-effort: the card already exists and is pollable even if this hiccups.
+ try {
+ hive.send({
+ to: 'god',
+ act: 'request',
+ subject: `[webhook] ${title}`,
+ body: `${msg.message}\n\n(Inbound via the generic webhook API, tracked as kanban card ${taskId}. When this work is finished, set that card's status to 'done' and fill its 'result' so the caller's status check reflects the outcome.)`,
+ requires_reply: false
+ }, 'webhook');
+ } catch (e) {
+ console.error('[webhook] could not route to god:', e instanceof Error ? e.message : e);
+ }
+ return { token, taskId };
+}
+
+/** Resolve a capability token to its task's public status — scoped to the ONE
+ * card whose stored hash matches; never lists or leaks any other task. Returns
+ * null for any non-match (the server answers 404 either way, so a probe can't
+ * tell "unknown" from "malformed"). */
+function lookupWebhookStatus(token: string): WebhookTaskStatus | null {
+ const wanted = Buffer.from(hashWebhookToken(token));
+ let tasks: HiveTask[];
+ try {
+ const ledger = hive.tasks() as { tasks?: HiveTask[] };
+ tasks = Array.isArray(ledger?.tasks) ? ledger.tasks : [];
+ } catch { return null; }
+ for (const t of tasks) {
+ const h = t.webhook?.tokenHash;
+ if (!h) continue;
+ const have = Buffer.from(h);
+ // Both are fixed-length sha-256 hex; compare in constant time defensively.
+ if (have.length === wanted.length && timingSafeEqual(have, wanted)) {
+ return { status: t.status, title: t.title, result: t.result };
+ }
+ }
+ return null;
+}
+
+/** Build a WebhookServer from the current config and start it, replacing any
+ * running instance. No-op + error when disabled or the secret is unset. The
+ * public tunnel is opened only here — never on a default; it stays opt-in
+ * (user enables + presses Start in Settings). */
+async function startWebhookServer(): Promise<{ ok: boolean; url?: string; error?: string }> {
+ const cfg = readConfig();
+ if (!cfg.webhookEnabled || !cfg.webhookSecret) {
+ return { ok: false, error: 'webhook disabled or missing secret' };
+ }
+ webhookServer?.stop();
+ webhookServer = new WebhookServer({
+ port: cfg.webhookPort && cfg.webhookPort > 0 ? cfg.webhookPort : 3849,
+ secret: cfg.webhookSecret,
+ onMessage: handleWebhookMessage,
+ lookupStatus: lookupWebhookStatus
+ });
+ const res = await webhookServer.start();
+ if (!res.ok) { webhookServer = null; return res; }
+ if (res.url) lastWebhookUrl = res.url;
+ return res;
+}
+
+/** Stop and forget the webhook server. Best-effort; safe when not running. The
+ * last tunnel URL is retained so Settings keeps showing it. */
+function stopWebhookServer(): void {
+ try { webhookServer?.stop(); } catch (e) { console.error('[webhook] stop failed:', e); }
+ webhookServer = null;
+}
+
/** The persisted main-window geometry (kv key `window.bounds`). */
interface WindowBounds { x?: number; y?: number; width: number; height: number }
@@ -985,6 +1104,7 @@ ipcMain.handle('config:changeHome', async (_evt, payload: unknown) => {
try { hive.stopRouter(); } catch (e) { console.error('[changeHome] stopRouter:', e); }
try { hookServer.stop(); } catch (e) { console.error('[changeHome] hookServer.stop:', e); }
try { stopSlackServer(); } catch (e) { console.error('[changeHome] slack.stop:', e); }
+ try { stopWebhookServer(); } catch (e) { console.error('[changeHome] webhook.stop:', e); }
try { memory.stop(); } catch (e) { console.error('[changeHome] memory.stop:', e); }
try { reflector.stop(); } catch (e) { console.error('[changeHome] reflector.stop:', e); }
@@ -1004,6 +1124,7 @@ ipcMain.handle('config:changeHome', async (_evt, payload: unknown) => {
bootstrapHiveServices();
const cfg = readConfig();
if (cfg.slackEnabled && cfg.slackSigningSecret) void startSlackServer();
+ if (cfg.webhookEnabled && cfg.webhookSecret) void startWebhookServer();
return { ok: false, error: `Could not copy data: ${e instanceof Error ? e.message : String(e)}` };
}
}
@@ -1358,6 +1479,33 @@ ipcMain.handle('slack:setConfig', (_evt, patch: unknown) => {
return { ok: true };
});
+// ─── IPC: Generic webhook + status API ──────────────────────────────────────
+ipcMain.handle('webhook:start', () => startWebhookServer());
+ipcMain.handle('webhook:stop', () => { stopWebhookServer(); return { ok: true }; });
+/** Current state + last public endpoint URL, for the Settings badge/URL field. */
+ipcMain.handle('webhook:status', () => ({ running: webhookServer != null, url: lastWebhookUrl }));
+/** Mint a strong (256-bit) secret, persist it, and return it so Settings can show
+ * it for the user to copy into their client. The previous secret is replaced. */
+ipcMain.handle('webhook:generateSecret', () => {
+ const secret = randomBytes(32).toString('hex');
+ writeConfig({ webhookSecret: secret });
+ return { ok: true, secret };
+});
+ipcMain.handle('webhook:setConfig', (_evt, patch: unknown) => {
+ const p = (patch ?? {}) as { secret?: unknown; port?: unknown; enabled?: unknown };
+ const next: Partial<HarnessConfig> = {};
+ if (typeof p.secret === 'string') next.webhookSecret = p.secret.trim() || undefined;
+ if (typeof p.port === 'number' && Number.isFinite(p.port)) next.webhookPort = p.port;
+ if (typeof p.enabled === 'boolean') next.webhookEnabled = p.enabled;
+ writeConfig(next);
+ // Disabling (or clearing the secret) stops the public surface immediately. As
+ // with Slack we do NOT auto-(re)start — the user presses Start to open the
+ // tunnel and fetch the fresh endpoint URL.
+ const cfg = readConfig();
+ if (!cfg.webhookEnabled || !cfg.webhookSecret) stopWebhookServer();
+ return { ok: true };
+});
+
/** Start every hive-bound background service against the current harnessHome.
* Called on boot, and again to recover in place if a folder-change copy fails
* (config:changeHome tears these down before copying). No-op without a home. */
@@ -1412,6 +1560,14 @@ app.whenReady().then(() => {
else console.log('[slack] webhook listening', r.url ? `(tunnel: ${r.url})` : '(no tunnel)');
});
}
+ // Auto-start the generic webhook only when the user has explicitly enabled it
+ // AND a secret exists — never a default-on public surface. Opt-in, like Slack.
+ if (slackCfg.webhookEnabled && slackCfg.webhookSecret) {
+ void startWebhookServer().then((r) => {
+ if (!r.ok) console.error('[webhook] auto-start failed:', r.error);
+ else console.log('[webhook] listening', r.url ? `(tunnel: ${r.url})` : '(no tunnel)');
+ });
+ }
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
diff --git a/src/main/webhook.ts b/src/main/webhook.ts
new file mode 100644
index 00000000..0aa944da
--- /dev/null
+++ b/src/main/webhook.ts
@@ -0,0 +1,254 @@
+/**
+ * WebhookServer — a generic, secret-gated inbound HTTP API that turns an external
+ * POST into hive work and lets the caller poll that work's status by a token.
+ *
+ * Modeled on `SlackWebhookServer` (same zero-SDK `node:http` + `localtunnel`
+ * approach) but for arbitrary callers rather than Slack's Events API:
+ * - POST <endpoint> + `x-md-webhook-secret: <secret>` + JSON `{ message, title? }`
+ * → routes the message to god/Michael, creates a stamped kanban card, and
+ * returns a freshly-minted capability TOKEN: `{ ok, token, taskId }`.
+ * - GET <endpoint> + `x-md-webhook-token: <token>` (or `?token=`)
+ * → returns ONLY that token's task status: `{ ok, status, title, result? }`.
+ *
+ * SECURITY — this is a PUBLIC surface (tunnel-forwarded), unlike the loopback
+ * /reply endpoint, so the gate is strict:
+ * - constant-time secret comparison (`timingSafeEqual`, length-guarded),
+ * - the secret is read from options and NEVER logged, echoed, or forwarded into
+ * the routed message / card / response,
+ * - the capability token is unguessable (generated by the caller-side handler,
+ * 192-bit) and a GET reveals only the single task it maps to — no listing or
+ * enumeration of other work,
+ * - a request body cap + a basic fixed-window rate limit bound abuse before any
+ * parsing or crypto runs.
+ *
+ * Runs in the Electron main process. Deliberately free of any `electron` import so
+ * it can be unit-/smoke-tested as a plain Node module. The actual card creation +
+ * god routing + token→status lookup are injected as callbacks (they need hive
+ * access, which lives in the main entrypoint); this class owns only transport,
+ * the secret gate, rate limiting, and the tunnel.
+ */
+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
+import { timingSafeEqual } from 'node:crypto';
+import localtunnel from 'localtunnel';
+
+/** The live tunnel handle returned by localtunnel (has `url` + `close()`). */
+type Tunnel = Awaited<ReturnType<typeof localtunnel>>;
+
+/** The validated body of an accepted POST — just the work to do. The secret has
+ * already been verified and is intentionally NOT part of this shape, so it can
+ * never be forwarded onward. */
+export interface WebhookInbound {
+ message: string;
+ title?: string;
+}
+
+/** What a GET exposes for a token — mirrors the kanban's public columns only. */
+export interface WebhookTaskStatus {
+ status: string;
+ title: string;
+ result?: string;
+}
+
+export interface WebhookServerOptions {
+ /** Local TCP port the HTTP server binds to (and the tunnel forwards to). */
+ port: number;
+ /** Shared secret the caller must echo in `x-md-webhook-secret`. Required. */
+ secret: string;
+ /**
+ * Turn a verified POST into hive work. MUST create the kanban card + route to
+ * god and return the capability token to hand back (plus the card id). Return
+ * null to signal a server-side failure (→ 500). The token it returns is the
+ * ONLY thing echoed to the caller; the secret never reaches here.
+ */
+ onMessage: (msg: WebhookInbound) => { token: string; taskId: string } | null;
+ /**
+ * Resolve a capability token to its task's public status, or null when the
+ * token maps to nothing (→ 404). MUST be scoped to the one token — it must
+ * never reveal or enumerate any other task.
+ */
+ lookupStatus: (token: string) => WebhookTaskStatus | null;
+}
+
+/** Reject bodies larger than this before buffering — callers send tiny JSON; the
+ * cap stops an unauthenticated peer forcing unbounded memory use pre-auth. */
+const MAX_BODY_BYTES = 1024 * 1024; // 1 MB
+/** Cap how long we wait for the public tunnel before giving up (server stays up). */
+const TUNNEL_START_TIMEOUT_MS = 10_000;
+/** Basic abuse guard: at most this many requests per fixed window, globally. */
+const RATE_LIMIT = 120;
+const RATE_WINDOW_MS = 60_000;
+
+export class WebhookServer {
+ private server: Server | null = null;
+ private tunnel: Tunnel | null = null;
+ private readonly port: number;
+ private readonly secret: string;
+ private readonly onMessage: (msg: WebhookInbound) => { token: string; taskId: string } | null;
+ private readonly lookupStatus: (token: string) => WebhookTaskStatus | null;
+ // Fixed-window rate limiter (global; the remote IP is the tunnel's, so per-IP
+ // would be meaningless behind loca.lt).
+ private windowStart = 0;
+ private windowCount = 0;
+
+ constructor(opts: WebhookServerOptions) {
+ this.port = opts.port;
+ this.secret = opts.secret;
+ this.onMessage = opts.onMessage;
+ this.lookupStatus = opts.lookupStatus;
+ }
+
+ /**
+ * Bind the local HTTP server, then open a public tunnel to it. The HTTP handler
+ * (the security boundary) is live the instant `listen` resolves; the tunnel is
+ * opened afterwards and is non-fatal — if it can't be established the server
+ * keeps running and we report the tunnel error without a URL.
+ */
+ async start(): Promise<{ ok: boolean; url?: string; error?: string }> {
+ if (this.server) return { ok: false, error: 'already running' };
+ if (!this.secret) return { ok: false, error: 'missing webhook secret' };
+ try {
+ await this.listen();
+ } catch (e) {
+ this.stop();
+ return { ok: false, error: `failed to bind port ${this.port}: ${errMsg(e)}` };
+ }
+ try {
+ const tunnel = await this.openTunnel();
+ this.tunnel = tunnel;
+ tunnel.on('error', () => { /* tunnel hiccup — ignore, server still listening */ });
+ return { ok: true, url: tunnel.url };
+ } catch (e) {
+ return { ok: true, error: `tunnel unavailable: ${errMsg(e)}` };
+ }
+ }
+
+ /** Close the tunnel and HTTP server. Idempotent and best-effort. */
+ stop(): void {
+ try { this.tunnel?.close(); } catch { /* noop */ }
+ this.tunnel = null;
+ try { this.server?.close(); } catch { /* noop */ }
+ this.server = null;
+ }
+
+ private listen(): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ const server = createServer((req, res) => this.handleRequest(req, res));
+ const onError = (e: Error): void => reject(e);
+ server.once('error', onError);
+ server.listen(this.port, () => {
+ server.off('error', onError);
+ this.server = server;
+ resolve();
+ });
+ });
+ }
+
+ private openTunnel(): Promise<Tunnel> {
+ return new Promise<Tunnel>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('timed out')), TUNNEL_START_TIMEOUT_MS);
+ Promise.resolve(localtunnel({ port: this.port }))
+ .then((t) => { clearTimeout(timer); resolve(t); })
+ .catch((e) => { clearTimeout(timer); reject(e); });
+ });
+ }
+
+ /** Fixed-window limiter — bounds total work before any parse/crypto runs. */
+ private allowRequest(): boolean {
+ const now = Date.now();
+ if (now - this.windowStart > RATE_WINDOW_MS) { this.windowStart = now; this.windowCount = 0; }
+ this.windowCount += 1;
+ return this.windowCount <= RATE_LIMIT;
+ }
+
+ private handleRequest(req: IncomingMessage, res: ServerResponse): void {
+ // Rate limit first — cheapest possible rejection, ahead of any work.
+ if (!this.allowRequest()) { json(res, 429, { ok: false, error: 'rate limited' }); return; }
+ const method = req.method ?? '';
+ if (method === 'GET') { this.handleStatus(req, res); return; }
+ if (method === 'POST') { this.handleCreate(req, res); return; }
+ res.writeHead(405); res.end();
+ }
+
+ /** GET — return the status of the token's task (token only; never a listing). */
+ private handleStatus(req: IncomingMessage, res: ServerResponse): void {
+ const token = readToken(req);
+ if (!token) { json(res, 401, { ok: false, error: 'token required' }); return; }
+ let status: WebhookTaskStatus | null = null;
+ try { status = this.lookupStatus(token); }
+ catch { json(res, 500, { ok: false, error: 'lookup failed' }); return; }
+ // 404 for an unknown token — identical to a malformed one, so a probe can't
+ // distinguish "valid but unknown" from "wrong shape" (no enumeration signal).
+ if (!status) { json(res, 404, { ok: false, error: 'not found' }); return; }
+ json(res, 200, { ok: true, status: status.status, title: status.title, result: status.result ?? null });
+ }
+
+ /** POST — verify the secret, then buffer + dispatch the JSON body. */
+ private handleCreate(req: IncomingMessage, res: ServerResponse): void {
+ // Authenticate BEFORE reading the body so an unauthenticated peer can't even
+ // make us buffer (within the size cap). 401 on any failure — no detail leaked.
+ if (!this.verifySecret(req)) { json(res, 401, { ok: false, error: 'unauthorized' }); return; }
+
+ const chunks: Buffer[] = [];
+ let size = 0;
+ let aborted = false;
+ req.on('data', (c: Buffer) => {
+ if (aborted) return;
+ size += c.length;
+ if (size > MAX_BODY_BYTES) { aborted = true; json(res, 413, { ok: false, error: 'too large' }); req.destroy(); return; }
+ chunks.push(c);
+ });
+ req.on('end', () => {
+ if (aborted) return;
+ let parsed: { message?: unknown; title?: unknown };
+ try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
+ catch { json(res, 400, { ok: false, error: 'bad json' }); return; }
+ const message = typeof parsed.message === 'string' ? parsed.message.trim() : '';
+ if (!message) { json(res, 400, { ok: false, error: 'message required' }); return; }
+ const title = typeof parsed.title === 'string' && parsed.title.trim() ? parsed.title.trim() : undefined;
+ let out: { token: string; taskId: string } | null = null;
+ try { out = this.onMessage({ message, title }); }
+ catch { json(res, 500, { ok: false, error: 'could not create task' }); return; }
+ if (!out) { json(res, 500, { ok: false, error: 'could not create task' }); return; }
+ json(res, 200, { ok: true, token: out.token, taskId: out.taskId });
+ });
+ req.on('error', () => { if (!aborted) { try { res.writeHead(400); res.end(); } catch { /* socket gone */ } } });
+ }
+
+ /**
+ * Constant-time check that `x-md-webhook-secret` equals the configured secret.
+ * A length mismatch is itself a failure and short-circuits before the compare
+ * (timingSafeEqual throws on unequal lengths).
+ */
+ private verifySecret(req: IncomingMessage): boolean {
+ const provided = req.headers['x-md-webhook-secret'];
+ if (typeof provided !== 'string') return false;
+ const a = Buffer.from(provided);
+ const b = Buffer.from(this.secret);
+ if (a.length !== b.length) return false;
+ return timingSafeEqual(a, b);
+ }
+}
+
+/** Pull the capability token from the `x-md-webhook-token` header, falling back
+ * to a `?token=` query param. Header is preferred (kept out of URL/access logs). */
+function readToken(req: IncomingMessage): string {
+ const h = req.headers['x-md-webhook-token'];
+ if (typeof h === 'string' && h.trim()) return h.trim();
+ try {
+ const url = new URL(req.url ?? '', 'http://localhost');
+ const q = url.searchParams.get('token');
+ if (q && q.trim()) return q.trim();
+ } catch { /* malformed url → no token */ }
+ return '';
+}
+
+function json(res: ServerResponse, status: number, body: unknown): void {
+ try {
+ res.writeHead(status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify(body));
+ } catch { /* socket already gone */ }
+}
+
+function errMsg(e: unknown): string {
+ return e instanceof Error ? e.message : String(e);
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 00851b03..60db08c1 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -46,6 +46,9 @@ export interface HiveTask {
result?: string;
/** Origin thread for a Slack-sourced task (drives the done-summary reply). */
slack?: { channel: string; thread_ts: string };
+ /** SHA-256 of the capability token for a generic-webhook-sourced task (drives
+ * the GET status lookup; the raw token is never persisted). */
+ webhook?: { tokenHash: string };
}
/** A message the router just delivered, with its resolved recipient ids. Drives
@@ -120,6 +123,9 @@ export interface HarnessConfig {
slackBotToken?: string;
slackChannelId?: string;
slackPort?: number;
+ webhookEnabled?: boolean;
+ webhookSecret?: string;
+ webhookPort?: number;
costCapUsd?: number;
costCapTokens?: number;
agentTokenCaps?: Record<string, number>;
@@ -547,7 +553,27 @@ const api = {
slackSetConfig: (patch: {
signingSecret?: string; botToken?: string; channelId?: string; port?: number; enabled?: boolean;
}): Promise<{ ok: boolean }> =>
- ipcRenderer.invoke('slack:setConfig', patch)
+ ipcRenderer.invoke('slack:setConfig', patch),
+
+ // ─── Generic webhook + status API (POST → work, GET → status) ────────────────
+ /** Start the generic webhook server; returns the public endpoint URL callers
+ * POST to (secret-gated) and GET a token's status from. */
+ webhookStart: (): Promise<{ ok: boolean; url?: string; error?: string }> =>
+ ipcRenderer.invoke('webhook:start'),
+ /** Stop the generic webhook server + tunnel. */
+ webhookStop: (): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('webhook:stop'),
+ /** Current state + last endpoint URL (so Settings can hydrate the badge/URL). */
+ webhookStatus: (): Promise<{ running: boolean; url?: string }> =>
+ ipcRenderer.invoke('webhook:status'),
+ /** Mint + persist a fresh secret and return it for the user to copy. */
+ webhookGenerateSecret: (): Promise<{ ok: boolean; secret?: string }> =>
+ ipcRenderer.invoke('webhook:generateSecret'),
+ /** Persist webhook settings (and stop the server if disabled / secret cleared). */
+ webhookSetConfig: (patch: {
+ secret?: string; port?: number; enabled?: boolean;
+ }): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('webhook:setConfig', patch)
};
contextBridge.exposeInMainWorld('cth', api);
diff --git a/src/renderer/src/components/SettingsModal.tsx b/src/renderer/src/components/SettingsModal.tsx
index 9d8cd38d..874a0151 100644
--- a/src/renderer/src/components/SettingsModal.tsx
+++ b/src/renderer/src/components/SettingsModal.tsx
@@ -17,6 +17,9 @@ type SlackConfig = HarnessConfig & {
slackBotToken?: string;
slackChannelId?: string;
slackPort?: number;
+ webhookEnabled?: boolean;
+ webhookSecret?: string;
+ webhookPort?: number;
};
/** Pixel-aesthetic text input, mirroring AddAgentModal's inputStyle. */
@@ -70,6 +73,25 @@ const SLACK_CONNECT_STEPS = `Connect Munder Difflin to Slack
8. Save Changes, reinstall if Slack prompts, then invite the bot
to your channel: /invite @MunderDifflin`;
+/** The request/response contract shown behind the webhook ⓘ. `<endpoint>` is the
+ * public URL printed once the server starts; the secret/token go in headers so
+ * they stay out of URLs and access logs. */
+const WEBHOOK_API_DOC = `Generic webhook API
+
+Trigger work (POST <endpoint>):
+ header x-md-webhook-secret: <your secret>
+ body {"message": "do X for me", "title": "optional short title"}
+ → 200 {"ok": true, "token": "<capability token>", "taskId": "<card id>"}
+
+Check status (GET <endpoint>):
+ header x-md-webhook-token: <token> (or ?token=<token>)
+ → 200 {"ok": true, "status": "todo|doing|blocked|done",
+ "title": "...", "result": "<summary or null>"}
+
+The secret authorizes new work; the returned token is a read-only handle to
+that one task's status (it reveals nothing else). Keep both private. The
+endpoint URL rotates every time you press Start.`;
+
/** Clear every renderer-side persisted key so a relaunch starts truly empty. */
function clearLocalState(): void {
try {
@@ -156,6 +178,17 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
// Whether the connect-steps help panel is expanded (the ⓘ icon by the header).
const [showSlackHelp, setShowSlackHelp] = useState(false);
+ // ─── Generic webhook + status API ───────────────────────────────────────────
+ const [webhookEnabled, setWebhookEnabled] = useState(slackCfg.webhookEnabled ?? false);
+ const [webhookSecret, setWebhookSecret] = useState(slackCfg.webhookSecret ?? '');
+ const [webhookPort, setWebhookPort] = useState(String(slackCfg.webhookPort ?? 3849));
+ const [webhookUrl, setWebhookUrl] = useState('');
+ const [webhookRunning, setWebhookRunning] = useState(false);
+ const [webhookBusy, setWebhookBusy] = useState(false);
+ const [webhookNote, setWebhookNote] = useState('');
+ const [showWebhookSecret, setShowWebhookSecret] = useState(false);
+ const [showWebhookHelp, setShowWebhookHelp] = useState(false);
+
// Re-seed every editable field from the on-disk config when the modal opens.
// App's `config` prop is loaded once and never refreshed after a save, so
// without this the saved budget / velocity / slack values show blank on reopen.
@@ -172,6 +205,9 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
setSlackBotToken(cc.slackBotToken ?? '');
setSlackChannel(cc.slackChannelId ?? '');
setSlackPort(String(cc.slackPort ?? 3847));
+ setWebhookEnabled(cc.webhookEnabled ?? false);
+ setWebhookSecret(cc.webhookSecret ?? '');
+ setWebhookPort(String(cc.webhookPort ?? 3849));
}).catch(() => { /* keep prop-seeded values */ });
// Hydrate live connection state + the persisted Request URL (req B/C/D): the
// tunnel URL lives in main, so reopening Settings while connected re-shows it.
@@ -180,6 +216,11 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
setRunning(s.running);
if (s.url) setTunnelUrl(s.url);
}).catch(() => { /* status unavailable — assume not running */ });
+ window.cth.webhookStatus().then((s) => {
+ if (!alive) return;
+ setWebhookRunning(s.running);
+ if (s.url) setWebhookUrl(s.url);
+ }).catch(() => { /* status unavailable — assume not running */ });
return () => { alive = false; };
}, []);
@@ -231,6 +272,63 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
finally { setSlackBusy(false); }
};
+ // ─── Generic webhook handlers ───────────────────────────────────────────────
+ const webhookPatch = (enabled: boolean) => ({
+ secret: webhookSecret,
+ port: Number(webhookPort) || 3849,
+ enabled
+ });
+
+ const saveWebhook = async () => {
+ setWebhookBusy(true); setWebhookNote('');
+ try {
+ await window.cth.webhookSetConfig(webhookPatch(webhookEnabled));
+ setWebhookNote('saved');
+ } catch (e) {
+ setWebhookNote(e instanceof Error ? e.message : String(e));
+ } finally { setWebhookBusy(false); }
+ };
+
+ /** Mint a fresh secret in main (256-bit) and show it for copying. */
+ const generateWebhookSecret = async () => {
+ setWebhookBusy(true); setWebhookNote('');
+ try {
+ const res = await window.cth.webhookGenerateSecret();
+ if (res.ok && res.secret) { setWebhookSecret(res.secret); setShowWebhookSecret(true); setWebhookNote('new secret — copy it now'); }
+ else setWebhookNote('could not generate secret');
+ } catch (e) {
+ setWebhookNote(e instanceof Error ? e.message : String(e));
+ } finally { setWebhookBusy(false); }
+ };
+
+ const startWebhook = async () => {
+ setWebhookBusy(true); setWebhookNote('');
+ try {
+ await window.cth.webhookSetConfig(webhookPatch(true));
+ setWebhookEnabled(true);
+ const res = await window.cth.webhookStart();
+ if (res.ok) {
+ setWebhookRunning(true);
+ if (res.url) setWebhookUrl(res.url);
+ setWebhookNote(res.url ? 'listening' : (res.error ?? 'started, but tunnel unavailable'));
+ } else {
+ setWebhookNote(res.error ?? 'failed to start');
+ }
+ } catch (e) {
+ setWebhookNote(e instanceof Error ? e.message : String(e));
+ } finally { setWebhookBusy(false); }
+ };
+
+ const stopWebhook = async () => {
+ setWebhookBusy(true); setWebhookNote('');
+ try { await window.cth.webhookStop(); setWebhookRunning(false); setWebhookNote('stopped'); }
+ catch (e) { setWebhookNote(e instanceof Error ? e.message : String(e)); }
+ finally { setWebhookBusy(false); }
+ };
+
+ const copyWebhookUrl = () => { void window.cth.copyToClipboard(webhookUrl); };
+ const copyWebhookSecret = () => { void window.cth.copyToClipboard(webhookSecret); };
+
const copyTunnel = () => { void window.cth.copyToClipboard(tunnelUrl); };
const reset = async () => {
@@ -586,6 +684,131 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
<div style={{ height: 2, background: 'var(--cth-ink-300)' }} />
+ {/* Generic webhook + status API */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
+ <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 14, lineHeight: '20px', color: 'var(--cth-ink-900)' }}>
+ Webhook API
+ <button
+ type="button"
+ aria-label="Show webhook API format"
+ aria-expanded={showWebhookHelp}
+ onClick={() => setShowWebhookHelp((v) => !v)}
+ style={{
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
+ width: 16, height: 16, padding: 0, cursor: 'pointer',
+ border: 'none', borderRadius: '50%',
+ background: showWebhookHelp ? 'var(--cth-ink-700)' : 'var(--cth-ink-300)',
+ color: showWebhookHelp ? 'var(--cth-paper-100)' : 'var(--cth-ink-900)',
+ fontFamily: 'var(--cth-font-display)', fontSize: 10, lineHeight: '16px'
+ }}
+ >ⓘ</button>
+ </span>
+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>
+ A secret-gated HTTP endpoint: POST to start work and get a token, GET the token for status.
+ </span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
+ <span style={{
+ fontSize: 12, lineHeight: '16px',
+ color: webhookRunning ? 'var(--cth-mint-700, #1f7a4d)' : 'var(--cth-ink-500)'
+ }}>
+ {webhookRunning ? '● Connected' : '○ Not connected'}
+ </span>
+ <PixelButton
+ variant={webhookEnabled ? 'primary' : 'secondary'}
+ size="sm"
+ onClick={() => setWebhookEnabled((v) => !v)}
+ >
+ {webhookEnabled ? 'on' : 'off'}
+ </PixelButton>
+ </div>
+ </div>
+
+ {showWebhookHelp && (
+ <pre style={{
+ margin: 0, padding: 10, whiteSpace: 'pre-wrap',
+ background: 'var(--cth-paper-100)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)',
+ fontFamily: 'var(--cth-font-mono)', fontSize: 11, lineHeight: '16px',
+ color: 'var(--cth-ink-700)'
+ }}>{WEBHOOK_API_DOC}</pre>
+ )}
+
+ {webhookEnabled && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
+ {/* Public surface (tunnel-forwarded). Loud, not buried. */}
+ <span style={{ fontSize: 12, lineHeight: '16px', color: '#6E1423' }}>
+ ⚠ This opens a PUBLIC endpoint anyone with the secret can post to. It stays off until you press Start.
+ </span>
+
+ <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
+ <span style={slackLabelStyle}>Secret key</span>
+ <div style={{ display: 'flex', gap: 6 }}>
+ <input
+ type={showWebhookSecret ? 'text' : 'password'}
+ value={webhookSecret}
+ onChange={(e) => setWebhookSecret(e.target.value)}
+ placeholder="press Generate, or paste your own"
+ style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)' }}
+ />
+ <PixelButton variant="secondary" size="sm" onClick={() => setShowWebhookSecret((v) => !v)} disabled={!webhookSecret}>
+ {showWebhookSecret ? 'hide' : 'show'}
+ </PixelButton>
+ <PixelButton variant="secondary" size="sm" onClick={copyWebhookSecret} disabled={!webhookSecret}>copy</PixelButton>
+ <PixelButton variant="ghost" size="sm" onClick={generateWebhookSecret} disabled={webhookBusy}>generate</PixelButton>
+ </div>
+ </label>
+
+ <label style={{ display: 'flex', flexDirection: 'column', gap: 4, width: 92 }}>
+ <span style={slackLabelStyle}>Port</span>
+ <input
+ type="number"
+ value={webhookPort}
+ onChange={(e) => setWebhookPort(e.target.value)}
+ placeholder="3849"
+ style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)' }}
+ />
+ </label>
+
+ <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
+ <PixelButton variant="primary" size="sm" onClick={startWebhook} disabled={webhookBusy || !webhookSecret.trim() || webhookRunning}>
+ {webhookBusy ? '…' : webhookRunning ? 'connected' : 'start'}
+ </PixelButton>
+ <PixelButton variant="secondary" size="sm" onClick={stopWebhook} disabled={webhookBusy || !webhookRunning}>
+ stop
+ </PixelButton>
+ <PixelButton variant="ghost" size="sm" onClick={saveWebhook} disabled={webhookBusy}>
+ save
+ </PixelButton>
+ {webhookNote && (
+ <span style={{ fontSize: 12, color: 'var(--cth-ink-500)' }}>{webhookNote}</span>
+ )}
+ </div>
+
+ {(webhookRunning || webhookUrl) && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 4, opacity: webhookRunning ? 1 : 0.55 }}>
+ <span style={slackLabelStyle}>
+ {webhookRunning ? 'Endpoint URL — POST work / GET status here' : 'last endpoint URL — rotates on next Start'}
+ </span>
+ <div style={{ display: 'flex', gap: 6 }}>
+ <input
+ readOnly
+ value={webhookUrl}
+ onFocus={(e) => e.currentTarget.select()}
+ style={{ ...slackInputStyle, fontFamily: 'var(--cth-font-mono)', fontSize: 12 }}
+ />
+ <PixelButton variant="secondary" size="sm" onClick={copyWebhookUrl} disabled={!webhookUrl}>copy</PixelButton>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ <div style={{ height: 2, background: 'var(--cth-ink-300)' }} />
+
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<div style={{
fontFamily: 'var(--cth-font-display)', fontSize: 10, lineHeight: '14px',