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.

feat(webhooks): make callback_url callable with the webhook secret (#1240)

Sanjeev Kumarade0e4381a8c
diff --git a/docs/api-reference/webhooks.mdx b/docs/api-reference/webhooks.mdx
index 601c27f68..4d9d6c7b6 100644
--- a/docs/api-reference/webhooks.mdx
+++ b/docs/api-reference/webhooks.mdx
@@ -79,16 +79,17 @@ Payloads are flat JSON objects with an `event` field at the top level.
"callToAction": "…"
},
"brand": { "name": "Acme", "domain": "acme.example", "industry": "Software" },
- "callback_url": "https://api.example.com/api/content/<opportunity id>/status"
+ "callback_url": "https://api.example.com/webhooks/content/<opportunity id>/status",
+ "callback_method": "POST"
}
```
- `prompt` is `null` when the opportunity is not tied to a prompt.
- `data` is the evidence behind the opportunity; its fields depend on the opportunity type.
- `brief` is `null` until a content brief has been generated for the opportunity.
-- `callback_url` points at `PATCH /api/content/{id}/status`, which takes `{ "status": "in_progress" }` (or `new`, `sent`, `done`, `dismissed`). The endpoint authenticates with a dashboard user's access token — see [Authentication](/api-reference/authentication#bearer-token) — not with the webhook secret.
+- `callback_url` points at `POST /webhooks/content/{id}/status`; `callback_method` is `POST`. Send `{ "status": "in_progress" }` (or `new`, `reviewed`, `sent`, `done`, `dismissed`) as JSON and pass the same secret configured for this active webhook in the `X-Webhook-Secret` header. Configure a non-empty webhook secret in **Content → Configure Webhook** before using callbacks; callback authentication fails with 401 when no secret is configured. Callbacks are limited to 1,200 requests per 15 minutes per secret hash, with a separate per-IP limiter for failed (401) authentication attempts (10 per 15 minutes). They do not require a dashboard JWT.
-Once your endpoint responds, the opportunity is marked `sent` whatever status code you return, and that status code and the first 1,000 characters of your response body are stored on it. If the request times out or the connection fails, the opportunity keeps its previous status.
+When your endpoint responds, the opportunity is marked `sent` and the response status plus the first 1,000 characters of its body are stored only if the opportunity's status and update timestamp have not changed since delivery began. If your workflow calls `callback_url` before replying (or a user updates the opportunity during delivery), the newer status is preserved and the late response does not overwrite it. If the request times out or the connection fails, the opportunity keeps its previous status.
### `daily_pulse.created`
diff --git a/server/src/lib/opportunity-status.js b/server/src/lib/opportunity-status.js
index 31c2b5335..20b008872 100644
--- a/server/src/lib/opportunity-status.js
+++ b/server/src/lib/opportunity-status.js
@@ -9,6 +9,16 @@
export const DISMISS_REASONS = ['not_relevant', 'wrong_angle'];
+/** Status values accepted by dashboard actions and external webhook callbacks. */
+export const VALID_OPPORTUNITY_STATUSES = Object.freeze([
+ 'new',
+ 'reviewed',
+ 'sent',
+ 'in_progress',
+ 'done',
+ 'dismissed',
+]);
+
/**
* The source data to write with a status change, or null when it stays as
* it is. An unknown reason is ignored.
diff --git a/server/src/lib/opportunity-status.test.js b/server/src/lib/opportunity-status.test.js
index adf2bd956..78ff6658b 100644
--- a/server/src/lib/opportunity-status.test.js
+++ b/server/src/lib/opportunity-status.test.js
@@ -1,8 +1,21 @@
import { describe, expect, it } from 'vitest';
-import { sourceDataForStatus } from './opportunity-status.js';
+import { sourceDataForStatus, VALID_OPPORTUNITY_STATUSES } from './opportunity-status.js';
// CONTENT-006: why an opportunity was dismissed, kept only while it is.
+describe('VALID_OPPORTUNITY_STATUSES', () => {
+ it('matches the status values supported by the content workflow', () => {
+ expect(VALID_OPPORTUNITY_STATUSES).toEqual([
+ 'new',
+ 'reviewed',
+ 'sent',
+ 'in_progress',
+ 'done',
+ 'dismissed',
+ ]);
+ });
+});
+
describe('sourceDataForStatus', () => {
const sd = { promptText: 'best coffee' };
diff --git a/server/src/lib/webhook-secret.js b/server/src/lib/webhook-secret.js
new file mode 100644
index 000000000..68884e4e0
--- /dev/null
+++ b/server/src/lib/webhook-secret.js
@@ -0,0 +1,21 @@
+import crypto from 'node:crypto';
+
+/**
+ * Compare a stored webhook secret with the secret provided by a caller.
+ *
+ * The length check is necessary because timingSafeEqual throws for unequal
+ * buffers. Secret lengths are not confidential; equal-length values are
+ * compared in constant time.
+ */
+export function webhookSecretsMatch(expected, provided) {
+ if (typeof expected !== 'string' || !expected || typeof provided !== 'string' || !provided) {
+ return false;
+ }
+
+ const expectedBuffer = Buffer.from(expected, 'utf8');
+ const providedBuffer = Buffer.from(provided, 'utf8');
+ return (
+ expectedBuffer.length === providedBuffer.length &&
+ crypto.timingSafeEqual(expectedBuffer, providedBuffer)
+ );
+}
diff --git a/server/src/lib/webhook-secret.test.js b/server/src/lib/webhook-secret.test.js
new file mode 100644
index 000000000..e97f0127c
--- /dev/null
+++ b/server/src/lib/webhook-secret.test.js
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+import { webhookSecretsMatch } from './webhook-secret.js';
+
+describe('webhookSecretsMatch', () => {
+ it('rejects missing stored or supplied secrets', () => {
+ expect(webhookSecretsMatch(undefined, 'secret')).toBe(false);
+ expect(webhookSecretsMatch('secret', undefined)).toBe(false);
+ expect(webhookSecretsMatch('', 'secret')).toBe(false);
+ expect(webhookSecretsMatch('secret', '')).toBe(false);
+ });
+
+ it('rejects a wrong secret, including values with a different byte length', () => {
+ expect(webhookSecretsMatch('correct-secret', 'wrong-secret')).toBe(false);
+ expect(webhookSecretsMatch('secret', 'a much longer secret')).toBe(false);
+ });
+
+ it('accepts the exact configured secret', () => {
+ expect(webhookSecretsMatch('shared-webhook-secret', 'shared-webhook-secret')).toBe(true);
+ });
+});
diff --git a/server/src/middleware/rate-limiter.js b/server/src/middleware/rate-limiter.js
index ab0e6b143..6f132c801 100644
--- a/server/src/middleware/rate-limiter.js
+++ b/server/src/middleware/rate-limiter.js
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto';
import rateLimit from 'express-rate-limit';
import { verifiedBotConnection, verifiedUserId } from './verified-tokens.js';
@@ -91,6 +92,44 @@ export function botIngestKey(req) {
return anonymousIpKey(req.ip);
}
+/**
+ * Group public workflow callbacks by a hash of the supplied webhook secret,
+ * not the provider's shared egress IP. Missing secrets fall back to IP; a
+ * separate failed-auth limiter below keeps brute-force attempts constrained.
+ */
+export function webhookCallbackKey(req) {
+ const header = req.get?.('X-Webhook-Secret') ?? req.headers?.['x-webhook-secret'];
+ const secret = typeof header === 'string' ? header : '';
+ if (!secret) return anonymousIpKey(req.ip);
+ return 'webhook:' + createHash('sha256').update(secret).digest('hex');
+}
+
+// Workflow providers share egress IP pools and may fan out multiple callbacks
+// per opportunity. Give each configured webhook its own generous 15-minute
+// budget, independent of all other customers using the same provider IP.
+export const webhookCallbackLimiter = rateLimit({
+ windowMs: 15 * 60 * 1000,
+ max: 1200,
+ keyGenerator: webhookCallbackKey,
+ standardHeaders: true,
+ legacyHeaders: false,
+ message: { error: 'rate_limited' },
+});
+
+// Only failed authentication attempts (401) consume this small per-IP bucket.
+// Valid callbacks and unrelated 4xx/5xx responses are removed from the counter
+// after the response finishes.
+export const webhookCallbackAuthFailureLimiter = rateLimit({
+ windowMs: 15 * 60 * 1000,
+ max: 10,
+ keyGenerator: (req) => anonymousIpKey(req.ip),
+ skipSuccessfulRequests: true,
+ requestWasSuccessful: (_req, res) => res.statusCode !== 401,
+ standardHeaders: true,
+ legacyHeaders: false,
+ message: { error: 'too_many_failed_webhook_auth_attempts' },
+});
+
// AI-bot ingest: 600 requests a minute per connection. A Worker isolate
// sends a batch about every 10 s, and a Logpush job or drain a file at a
// time, so this leaves room for many of them while stopping a runaway sender.
diff --git a/server/src/middleware/rate-limiter.test.js b/server/src/middleware/rate-limiter.test.js
index 66764225e..c4dae646f 100644
--- a/server/src/middleware/rate-limiter.test.js
+++ b/server/src/middleware/rate-limiter.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'vitest';
-import { apiLimiterKey, botIngestKey } from './rate-limiter.js';
+import { apiLimiterKey, botIngestKey, webhookCallbackKey } from './rate-limiter.js';
import {
markBotSenderVerified,
markTokenVerified,
@@ -97,3 +97,22 @@ describe('rate-limiter – botIngestKey', () => {
);
});
});
+
+describe('rate-limiter – webhookCallbackKey', () => {
+ it('buckets callbacks by the secret hash across shared provider IPs', () => {
+ const a = webhookCallbackKey({ headers: { 'x-webhook-secret': 'shared-one' }, ip: '1.1.1.1' });
+ const b = webhookCallbackKey({ headers: { 'x-webhook-secret': 'shared-one' }, ip: '2.2.2.2' });
+ const other = webhookCallbackKey({
+ headers: { 'x-webhook-secret': 'shared-two' },
+ ip: '1.1.1.1',
+ });
+ expect(a).toBe(b);
+ expect(a).not.toBe(other);
+ expect(a).toMatch(/^webhook:[0-9a-f]{64}$/);
+ expect(a).not.toContain('shared-one');
+ });
+
+ it('falls back to the anonymous IP bucket when the secret is missing', () => {
+ expect(webhookCallbackKey({ headers: {}, ip: '1.1.1.1' })).toBe('ip:1.1.1.1');
+ });
+});
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index 16c08534d..415d8d4d6 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -26,7 +26,7 @@ import { loadClusters } from '../lib/prompt-clusters.js';
import { sendToActionCenter } from '../lib/action-center/from-opportunity.js';
import { IDEA_MAX_LENGTH } from '../lib/opportunity-generator.js';
import { cleanStoredOpportunity } from '../lib/opportunity-text.js';
-import { sourceDataForStatus } from '../lib/opportunity-status.js';
+import { sourceDataForStatus, VALID_OPPORTUNITY_STATUSES } from '../lib/opportunity-status.js';
import {
openOpportunityForPrompt,
promptClusterId,
@@ -750,7 +750,7 @@ router.post('/bulk/status', async (req, res) => {
return res.status(400).json({ error: 'ids must be a non-empty array' });
}
- const validStatuses = ['new', 'reviewed', 'sent', 'in_progress', 'done', 'dismissed'];
+ const validStatuses = VALID_OPPORTUNITY_STATUSES;
if (!validStatuses.includes(status)) {
return res
.status(400)
@@ -917,7 +917,8 @@ router.post('/bulk/send-webhook', async (req, res) => {
domain: domains?.[0]?.domain || '',
industry: brand?.industry || '',
},
- callback_url: `${serverUrl}/api/content/${opportunity.id}/status`,
+ callback_url: `${serverUrl}/webhooks/content/${opportunity.id}/status`,
+ callback_method: 'POST',
};
const webhookRes = await fetch(webhookConfig.webhook_url, {
@@ -929,6 +930,9 @@ router.post('/bulk/send-webhook', async (req, res) => {
const responseBody = await webhookRes.text().catch(() => '');
+ // A workflow may call callback_url before it sends its HTTP response.
+ // Guard the write with the state observed before POST so this delayed
+ // response cannot overwrite a newer in_progress/done callback.
await supabaseAdmin
.from('content_opportunities')
.update({
@@ -940,7 +944,9 @@ router.post('/bulk/send-webhook', async (req, res) => {
},
updated_at: new Date().toISOString(),
})
- .eq('id', opportunity.id);
+ .eq('id', stored.id)
+ .eq('status', stored.status)
+ .eq('updated_at', stored.updated_at);
sent++;
} catch {
@@ -967,7 +973,7 @@ router.patch('/:id/status', async (req, res) => {
const { id } = req.params;
const { status, reason } = req.body;
- const validStatuses = ['new', 'reviewed', 'sent', 'in_progress', 'done', 'dismissed'];
+ const validStatuses = VALID_OPPORTUNITY_STATUSES;
if (!validStatuses.includes(status)) {
return res
.status(400)
@@ -1093,7 +1099,8 @@ router.post('/:id/send-webhook', async (req, res) => {
domain: domains?.[0]?.domain || '',
industry: brand?.industry || '',
},
- callback_url: `${serverUrl}/api/content/${opportunity.id}/status`,
+ callback_url: `${serverUrl}/webhooks/content/${opportunity.id}/status`,
+ callback_method: 'POST',
};
const headers = { 'Content-Type': 'application/json' };
@@ -1110,7 +1117,7 @@ router.post('/:id/send-webhook', async (req, res) => {
const responseBody = await webhookRes.text().catch(() => '');
- await supabaseAdmin
+ const { data: statusUpdate } = await supabaseAdmin
.from('content_opportunities')
.update({
status: 'sent',
@@ -1121,12 +1128,29 @@ router.post('/:id/send-webhook', async (req, res) => {
},
updated_at: new Date().toISOString(),
})
- .eq('id', id);
+ .eq('id', id)
+ .eq('status', stored.status)
+ .eq('updated_at', stored.updated_at)
+ .select('status')
+ .maybeSingle();
+
+ // If the conditional write missed, a callback or user changed the record
+ // during delivery. Return the actual latest status instead of claiming it
+ // was changed to sent.
+ let opportunityStatus = statusUpdate?.status;
+ if (!statusUpdate) {
+ const { data: latest } = await supabaseAdmin
+ .from('content_opportunities')
+ .select('status')
+ .eq('id', id)
+ .maybeSingle();
+ opportunityStatus = latest?.status ?? stored.status;
+ }
return res.json({
success: true,
webhookStatus: webhookRes.status,
- opportunityStatus: 'sent',
+ opportunityStatus,
});
} catch (error) {
req.log.error({ err: error }, 'send webhook error');
diff --git a/server/src/routes/webhook-content-callback.js b/server/src/routes/webhook-content-callback.js
new file mode 100644
index 000000000..f432f30d7
--- /dev/null
+++ b/server/src/routes/webhook-content-callback.js
@@ -0,0 +1,101 @@
+import { Router } from 'express';
+import supabaseAdmin from '../config/supabase.js';
+import {
+ webhookCallbackLimiter,
+ webhookCallbackAuthFailureLimiter,
+} from '../middleware/rate-limiter.js';
+import { sourceDataForStatus, VALID_OPPORTUNITY_STATUSES } from '../lib/opportunity-status.js';
+import { webhookSecretsMatch } from '../lib/webhook-secret.js';
+
+const router = Router();
+
+// This endpoint is public by design. The supplied secret hash gives each
+// webhook its own budget; the second limiter counts failed (401) attempts by IP.
+router.use(webhookCallbackLimiter, webhookCallbackAuthFailureLimiter);
+
+/**
+ * POST /webhooks/content/:id/status
+ * Let an external workflow update an opportunity using its webhook secret.
+ */
+router.post('/:id/status', async (req, res) => {
+ try {
+ const { id } = req.params;
+ // Avoid sending malformed identifiers to Postgres (22P02). Keep its
+ // response indistinguishable from a wrong secret or unknown opportunity.
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id)) {
+ return res.status(401).json({ error: 'Invalid webhook credentials' });
+ }
+
+ const { data: current, error: opportunityError } = await supabaseAdmin
+ .from('content_opportunities')
+ .select('id, brand_id, source_data, updated_at')
+ .eq('id', id)
+ .maybeSingle();
+
+ if (opportunityError) throw new Error(opportunityError.message);
+
+ // Return the same result for an unknown opportunity, missing configuration,
+ // and an invalid secret so this public route doesn't reveal which IDs exist.
+ if (!current) return res.status(401).json({ error: 'Invalid webhook credentials' });
+
+ const { data: webhookConfig, error: configError } = await supabaseAdmin
+ .from('webhook_configs')
+ .select('webhook_secret')
+ .eq('brand_id', current.brand_id)
+ .eq('is_active', true)
+ .limit(1)
+ .maybeSingle();
+
+ if (configError) throw new Error(configError.message);
+ if (!webhookSecretsMatch(webhookConfig?.webhook_secret, req.get('X-Webhook-Secret'))) {
+ return res.status(401).json({ error: 'Invalid webhook credentials' });
+ }
+
+ const { status, reason } = req.body ?? {};
+ if (!VALID_OPPORTUNITY_STATUSES.includes(status)) {
+ return res.status(400).json({
+ error: 'Invalid status. Must be one of: ' + VALID_OPPORTUNITY_STATUSES.join(', '),
+ });
+ }
+
+ // Match the authenticated Content route's dismissal metadata and guarded
+ // write behavior, so an external callback cannot erase a concurrent edit.
+ let latest = current;
+ let data = null;
+ let error = null;
+ for (let attempt = 0; attempt < 2 && !data && !error; attempt += 1) {
+ if (attempt > 0) {
+ const fresh = await supabaseAdmin
+ .from('content_opportunities')
+ .select('id, brand_id, source_data, updated_at')
+ .eq('id', id)
+ .maybeSingle();
+ if (fresh.error) throw new Error(fresh.error.message);
+ if (!fresh.data) break;
+ latest = fresh.data;
+ }
+
+ const sourceData = sourceDataForStatus(latest.source_data, status, reason);
+ let update = supabaseAdmin
+ .from('content_opportunities')
+ .update({
+ status,
+ updated_at: new Date().toISOString(),
+ ...(sourceData ? { source_data: sourceData } : {}),
+ })
+ .eq('id', id);
+ if (sourceData) update = update.eq('updated_at', latest.updated_at);
+ ({ data, error } = await update.select('id, status').maybeSingle());
+ }
+
+ if (error) throw new Error(error.message);
+ if (!data) return res.status(404).json({ error: 'Opportunity not found' });
+
+ return res.json({ success: true, status: data.status });
+ } catch (error) {
+ req.log?.error?.({ err: error }, 'webhook status callback error');
+ return res.status(500).json({ error: 'Failed to update opportunity status' });
+ }
+});
+
+export default router;
diff --git a/server/src/routes/webhook-content-callback.test.js b/server/src/routes/webhook-content-callback.test.js
new file mode 100644
index 000000000..ca83412f8
--- /dev/null
+++ b/server/src/routes/webhook-content-callback.test.js
@@ -0,0 +1,159 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+const { mockFrom, state } = vi.hoisted(() => ({
+ mockFrom: vi.fn(),
+ state: { opportunities: [], configs: [] },
+}));
+
+vi.mock('../config/supabase.js', () => ({
+ default: { from: mockFrom },
+}));
+vi.mock('../middleware/rate-limiter.js', () => ({
+ webhookCallbackLimiter: (_req, _res, next) => next(),
+ webhookCallbackAuthFailureLimiter: (_req, _res, next) => next(),
+}));
+
+const { default: router } = await import('./webhook-content-callback.js');
+
+function table(name) {
+ const q = { op: 'select', filters: [], payload: null, returning: false };
+ const rows = () =>
+ (name === 'content_opportunities' ? state.opportunities : state.configs).filter((row) =>
+ q.filters.every((matches) => matches(row)),
+ );
+ const run = (single) => {
+ const matched = rows();
+ if (q.op === 'update') {
+ for (const row of matched) Object.assign(row, q.payload);
+ }
+ const data = single ? (matched[0] ?? null) : matched;
+ return { data: q.returning || q.op === 'select' ? data : null, error: null };
+ };
+ const chain = {
+ select: () => ((q.returning = q.op !== 'select'), chain),
+ eq: (column, value) => (q.filters.push((row) => row[column] === value), chain),
+ limit: () => chain,
+ update: (payload) => ((q.op = 'update'), (q.payload = payload), chain),
+ maybeSingle: async () => run(true),
+ then: (resolve, reject) => Promise.resolve(run(false)).then(resolve, reject),
+ };
+ return chain;
+}
+
+let server;
+let baseUrl;
+
+async function startApp() {
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.log = { error: vi.fn() };
+ next();
+ });
+ app.use('/webhooks/content', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl =
+ 'http://127.0.0.1:' +
+ server.address().port +
+ '/webhooks/content/5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29/status';
+}
+
+beforeEach(async () => {
+ state.opportunities = [
+ {
+ id: '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29',
+ brand_id: 'brand-1',
+ status: 'sent',
+ source_data: { kept: true },
+ updated_at: '2026-10-20T00:00:00.000Z',
+ },
+ ];
+ state.configs = [{ brand_id: 'brand-1', is_active: true, webhook_secret: 'shared-secret' }];
+ mockFrom.mockReset();
+ mockFrom.mockImplementation((name) => table(name));
+ await startApp();
+});
+
+afterEach(async () => {
+ await new Promise((resolve) => server.close(resolve));
+});
+
+async function send({
+ secret,
+ status = 'in_progress',
+ id = '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29',
+} = {}) {
+ const url = baseUrl.replace('5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29', id);
+ return fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(secret === undefined ? {} : { 'X-Webhook-Secret': secret }),
+ },
+ body: JSON.stringify({ status }),
+ });
+}
+
+describe('POST /webhooks/content/:id/status', () => {
+ it('rejects a missing secret', async () => {
+ const response = await send();
+ expect(response.status).toBe(401);
+ expect(state.opportunities[0].status).toBe('sent');
+ });
+
+ it('rejects a wrong secret', async () => {
+ const response = await send({ secret: 'wrong-secret' });
+ expect(response.status).toBe(401);
+ expect(state.opportunities[0].status).toBe('sent');
+ });
+
+ it('rejects a secret belonging to another brand', async () => {
+ state.configs.push({
+ brand_id: 'brand-2',
+ is_active: true,
+ webhook_secret: 'other-brand-secret',
+ });
+ const response = await send({ secret: 'other-brand-secret' });
+ expect(response.status).toBe(401);
+ expect(state.opportunities[0].status).toBe('sent');
+ });
+
+ it('rejects callbacks when the active config has no secret configured', async () => {
+ state.configs[0].webhook_secret = null;
+ const response = await send({ secret: 'shared-secret' });
+ expect(response.status).toBe(401);
+ expect(state.opportunities[0].status).toBe('sent');
+ });
+
+ it('returns 401 for a valid UUID that does not exist', async () => {
+ state.opportunities = [];
+ const response = await send({
+ secret: 'shared-secret',
+ id: '3b77bbdb-df2c-44da-aa57-823d2bccb991',
+ });
+ expect(response.status).toBe(401);
+ await expect(response.json()).resolves.toEqual({ error: 'Invalid webhook credentials' });
+ });
+
+ it('returns the same 401 for a malformed identifier without querying Postgres', async () => {
+ const response = await send({ secret: 'shared-secret', id: 'not-a-uuid' });
+ expect(response.status).toBe(401);
+ expect(mockFrom).not.toHaveBeenCalled();
+ });
+
+ it('updates the opportunity when the webhook secret matches', async () => {
+ const response = await send({ secret: 'shared-secret', status: 'done' });
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ success: true, status: 'done' });
+ expect(state.opportunities[0].status).toBe('done');
+ });
+
+ it('rejects a status outside the existing status whitelist', async () => {
+ const response = await send({ secret: 'shared-secret', status: 'delete' });
+ expect(response.status).toBe(400);
+ expect(state.opportunities[0].status).toBe('sent');
+ });
+});
diff --git a/server/src/server.js b/server/src/server.js
index be98ac017..02be3642d 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -30,6 +30,7 @@ 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 webhookContentCallbackRoutes from './routes/webhook-content-callback.js';
import { sendImproveActionForKeyUser } from './routes/prompts.js';
import { readOpportunityInbox, startAutoAudits, startSiteAuditForBrand } from './routes/audits.js';
import { sweepAutoAudits } from './lib/audit/auto-audit-sweep.js';
@@ -706,6 +707,10 @@ app.post('/cloro/callback', async (req, res) => {
}
});
+// Public, webhook-secret-authenticated status callback for external workflows.
+// It is mounted outside /api so no dashboard JWT is required; the router has its own stricter limiter.
+app.use('/webhooks/content', webhookContentCallbackRoutes);
+
// --- Authenticated API routes ---
app.use('/api', Middleware.decodeToken.bind(Middleware), routes);