Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

chore(security): verify Cloro webhook signatures on /cloro/callback (#229)

Gökhan Geyik8c8615cfeafd
diff --git a/server/.env.example b/server/.env.example
index d1558ac2e..98b607a90 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -37,6 +37,15 @@ CLORO_API_KEY=
# and scales without blocking workers). Leave empty to fall back to inline polling.
CLORO_WEBHOOK_URL=
+# Cloro webhook signing secret (whsec_…). Generated when you enable signed
+# deliveries at https://dashboard.cloro.dev/webhooks — shown exactly once, store
+# it here. When set, /cloro/callback rejects any delivery without a valid
+# HMAC signature (401) or with a stale timestamp (400). Leave empty to accept
+# unsigned deliveries (the default; required while dashboard signing is off).
+# IMPORTANT: flip the dashboard switch and set this value together — setting
+# only one of the two breaks webhook delivery.
+CLORO_WEBHOOK_SECRET=
+
# Platform provider for web scrapers (default: cloro)
PLATFORM_PROVIDER=cloro
diff --git a/server/src/lib/cloro-webhook-verify.js b/server/src/lib/cloro-webhook-verify.js
new file mode 100644
index 000000000..9f1d0b073
--- /dev/null
+++ b/server/src/lib/cloro-webhook-verify.js
@@ -0,0 +1,68 @@
+import crypto from 'crypto';
+
+const DEFAULT_TOLERANCE_SECONDS = 5 * 60;
+
+/**
+ * Verify a signed Cloro webhook delivery (HMAC-SHA256 over `${timestamp}.${rawBody}`).
+ *
+ * Cloro ships three headers on signed deliveries (https://docs.cloro.dev/guides/webhooks):
+ * X-Cloro-Signature — `v1=<hex hmac>`
+ * X-Cloro-Timestamp — unix seconds at send time
+ * X-Cloro-Webhook-Id — unique delivery id (dedup; not part of the signature)
+ *
+ * The `whsec_…` secret is used as-is (no prefix stripping, no base64 decoding),
+ * matching Cloro's own reference implementation.
+ *
+ * Pure function — no env access, clock injectable via `nowMs` — so it stays
+ * trivially unit-testable.
+ *
+ * @param {object} params
+ * @param {Buffer|string} params.rawBody Exact request body bytes (pre-JSON-parse)
+ * @param {string|undefined} params.signatureHeader X-Cloro-Signature value
+ * @param {string|undefined} params.timestampHeader X-Cloro-Timestamp value
+ * @param {string} params.secret Signing secret from the Cloro dashboard
+ * @param {number} [params.toleranceSeconds] Replay window (default 5 minutes)
+ * @param {number} [params.nowMs] Clock override for tests
+ * @returns {{ ok: true } | { ok: false, status: number, reason: string }}
+ */
+export function verifyCloroWebhook({
+ rawBody,
+ signatureHeader,
+ timestampHeader,
+ secret,
+ toleranceSeconds = DEFAULT_TOLERANCE_SECONDS,
+ nowMs = Date.now(),
+}) {
+ if (!signatureHeader || !timestampHeader) {
+ return { ok: false, status: 401, reason: 'missing signature headers' };
+ }
+
+ const timestamp = Number(timestampHeader);
+ if (!Number.isFinite(timestamp)) {
+ return { ok: false, status: 400, reason: 'invalid timestamp' };
+ }
+
+ if (Math.abs(nowMs / 1000 - timestamp) > toleranceSeconds) {
+ return { ok: false, status: 400, reason: 'stale timestamp' };
+ }
+
+ const provided = String(signatureHeader).replace(/^v1=/, '');
+ const expected = crypto
+ .createHmac('sha256', secret)
+ .update(`${timestamp}.`)
+ .update(rawBody)
+ .digest('hex');
+
+ // timingSafeEqual throws on length mismatch, so gate on length first.
+ // The length check itself leaks nothing useful (hex digest length is public).
+ const providedBuf = Buffer.from(provided, 'utf8');
+ const expectedBuf = Buffer.from(expected, 'utf8');
+ if (
+ providedBuf.length !== expectedBuf.length ||
+ !crypto.timingSafeEqual(providedBuf, expectedBuf)
+ ) {
+ return { ok: false, status: 401, reason: 'signature mismatch' };
+ }
+
+ return { ok: true };
+}
diff --git a/server/src/server.js b/server/src/server.js
index 559415c53..3851abec2 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -15,6 +15,7 @@ import { createJob, cleanupStaleJobs, cleanupOldJobs } from './lib/job-manager.j
import { runTrackingJob } from './lib/job-runner.js';
import { parseScraperResponse } from './lib/cloro-scraper.js';
import { handleScraperResult } from './lib/cloro-result-handler.js';
+import { verifyCloroWebhook } from './lib/cloro-webhook-verify.js';
import { generateBriefForOpportunity } from './routes/content.js';
import supabaseAdmin from './config/supabase.js';
import { getPlan, hasFeature, isCloud, isSubscriptionActive } from './config/plans.js';
@@ -24,6 +25,10 @@ app.set('trust proxy', 1);
const server = http.createServer(app);
// --- Body parsing (before all routes) ---
+// /cloro/callback gets the raw body bytes: HMAC signature verification needs the
+// payload exactly as sent, and express.json()'s parse/re-serialize would break it.
+// Mounted first so the global JSON parser skips this path (body already consumed).
+app.use('/cloro/callback', express.raw({ type: 'application/json', limit: '50mb' }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
@@ -230,13 +235,42 @@ app.post('/api/internal/trigger-tracking', async (req, res) => {
}
});
-// --- Cloro webhook callback (public, no auth — security via task_id entropy + DB lookup) ---
+// --- Cloro webhook callback ---
+// Signature verification (HMAC-SHA256, see lib/cloro-webhook-verify.js) runs when
+// CLORO_WEBHOOK_SECRET is set. When it's unset (self-hosted installs, or signing not
+// yet enabled in the Cloro dashboard) we fall back to the original defence:
+// task_id entropy + cloro_pending_tasks lookup.
app.post('/cloro/callback', async (req, res) => {
+ const webhookSecret = process.env.CLORO_WEBHOOK_SECRET;
+ if (webhookSecret) {
+ const verdict = verifyCloroWebhook({
+ rawBody: Buffer.isBuffer(req.body) ? req.body : Buffer.from(''),
+ signatureHeader: req.headers['x-cloro-signature'],
+ timestampHeader: req.headers['x-cloro-timestamp'],
+ secret: webhookSecret,
+ });
+ if (!verdict.ok) {
+ console.warn(
+ `[cloro/callback] Rejected delivery: ${verdict.reason} | webhook_id: ${req.headers['x-cloro-webhook-id'] || 'n/a'} | ip: ${req.ip}`,
+ );
+ return res.status(verdict.status).json({ error: verdict.reason });
+ }
+ }
+
+ // Parse only after the signature check has passed (raw body arrives as a Buffer).
+ let payload;
+ try {
+ payload = Buffer.isBuffer(req.body) ? JSON.parse(req.body.toString('utf8') || '{}') : req.body;
+ } catch {
+ console.warn(`[cloro/callback] Rejected delivery: malformed JSON body | ip: ${req.ip}`);
+ return res.status(400).json({ error: 'malformed JSON body' });
+ }
+
// Always ack quickly so Cloro doesn't retry on slow processing
res.status(200).send();
try {
- const { task, response } = req.body || {};
+ const { task, response } = payload || {};
const taskId = task?.id;
const status = task?.status;