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(content): send Content Editor pages to the brand's webhook as content packages, and take back where they went live (Send to CMS #1331, part 1: server) (#1437)

Cihan128e82257ad3
diff --git a/server/src/lib/content-delivery.js b/server/src/lib/content-delivery.js
new file mode 100644
index 000000000..ea470e16c
--- /dev/null
+++ b/server/src/lib/content-delivery.js
@@ -0,0 +1,475 @@
+import crypto from 'node:crypto';
+import * as cheerio from 'cheerio';
+import { z } from 'zod';
+import supabaseAdmin from '../config/supabase.js';
+import { logger } from './logger.js';
+import { PageFetchError } from './safe-fetch.js';
+import { languageCodeOf } from './languages.js';
+import { postJson } from './safe-post.js';
+
+/**
+ * Send to CMS, phase 1 (#1331): an admin or manager sends Content Editor
+ * pages to the brand's webhook, each as a content package (schemaVersion 1)
+ * the workspace's own automation turns into a post: its publishable HTML
+ * (built in the browser as Export builds it, CE-057, and cleaned here once
+ * more), title, slug, meta and page fields. A page's slug and meta are kept
+ * on the draft. Each send is a content_draft_deliveries row (00262): queued
+ * when reserved against the workspace's 200 a day, then sent or failed, and
+ * published once the callback names the live address.
+ *
+ * One page is sent while the request waits; a bulk send (up to 25) goes on
+ * in the background, one page after another, and the Library follows its
+ * rows. A row a restarted server left queued is closed as interrupted by
+ * the workspace's next send (reserve_content_deliveries).
+ */
+
+export const DELIVERY_EVENT = 'content_draft.sent';
+export const PACKAGE_VERSION = 1;
+/** Deliveries a workspace may send in 24 hours. */
+export const DAILY_DELIVERIES = 200;
+/** Pages one send may take. */
+export const PAGES_PER_SEND = 25;
+/** Between a batch's pages: a CMS's per-minute cap (#1331, "with a short pause"). */
+export const PAUSE_MS = 2_000;
+const MAX_HTML_CHARS = 1_000_000;
+const EXCERPT_CHARS = 2000;
+
+export const deliveryPage = z.object({
+ draftId: z.guid(),
+ title: z.string().trim().min(1).max(300),
+ // As a URL's last segment: letters, digits, '-', '_' and single dots.
+ slug: z
+ .string()
+ .trim()
+ .min(1)
+ .max(200)
+ .regex(/^(?!.*\.\.)[\p{L}\p{N}._-]+$/u),
+ metaTitle: z.string().trim().max(300).default(''),
+ metaDescription: z.string().trim().max(500).default(''),
+ html: z.string().min(1).max(MAX_HTML_CHARS),
+ author: z.string().trim().max(200).nullable().default(null),
+ featuredImage: z
+ .object({ src: z.url({ protocol: /^https$/ }).max(2048), alt: z.string().max(500) })
+ .nullable()
+ .default(null),
+});
+
+export const sendInput = z.object({
+ // guid, not uuid: brand ids aren't all RFC 4122 versions (seeded ones).
+ brandId: z.guid(),
+ pages: z.array(deliveryPage).min(1).max(PAGES_PER_SEND),
+});
+
+/** A send that can't go, with the code the web names to the person. */
+export class DeliveryError extends Error {
+ /** @param {'no_webhook'|'webhook_not_subscribed'|'not_found'|'daily_limit'} code */
+ constructor(code, message, status) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ }
+}
+
+/** Attributes that hold a URL. */
+const URL_ATTRS = new Set([
+ 'href',
+ 'src',
+ 'xlink:href',
+ 'action',
+ 'formaction',
+ 'srcset',
+ 'poster',
+ 'cite',
+]);
+/** The schemes a published page's links may use; others are dropped. */
+const SAFE_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);
+
+/**
+ * Whether a URL attribute may stay: http(s), mailto, tel or relative; a data:
+ * image for an image's src. Browsers ignore tabs and newlines in a URL and
+ * leading control characters, so they are taken out before its scheme is
+ * read ("java	script:" is javascript:).
+ */
+function safeUrl(value, { image }) {
+ const bare = String(value)
+ .replace(/[\t\n\r]/g, '')
+ // eslint-disable-next-line no-control-regex
+ .replace(/^[\x00-\x20]+/, '');
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(bare)?.[1]?.toLowerCase();
+ if (!scheme) return true;
+ if (scheme === 'data') return image && /^data:image\/(png|jpe?g|gif|webp|avif)[;,]/i.test(bare);
+ return SAFE_SCHEMES.has(scheme);
+}
+
+/**
+ * The page's HTML once more on the server, as a second guard behind the
+ * browser's (DOMPurify, CE-057): no script but JSON-LD, no frames, forms,
+ * document-level tags or SVG animation (which can set a link), no event
+ * handlers, and links only to the schemes a page needs (safeUrl).
+ */
+/** A script that holds JSON-LD, its type written however the page wrote it. */
+const isJsonLd = ($, el) =>
+ ($(el).attr('type') ?? '').trim().toLowerCase() === 'application/ld+json';
+
+export function cleanPublishHtml(html) {
+ const $ = cheerio.load(html, null, false);
+ $('script').each((_, el) => {
+ if (!isJsonLd($, el)) $(el).remove();
+ });
+ $(
+ 'iframe, frame, frameset, object, embed, applet, form, base, meta, link, style, animate, set, animateMotion, animateTransform',
+ ).remove();
+ $('*').each((_, el) => {
+ for (const [name, value] of Object.entries(el.attribs ?? {})) {
+ const attr = name.toLowerCase();
+ if (attr.startsWith('on')) {
+ $(el).removeAttr(name);
+ } else if (URL_ATTRS.has(attr)) {
+ const image = attr === 'src' && el.tagName?.toLowerCase() === 'img';
+ if (!safeUrl(value, { image })) $(el).removeAttr(name);
+ }
+ }
+ });
+ return $.html();
+}
+
+/** `sha256=<hex>`: the body signed with the webhook's secret, for X-Ansvisor-Signature. */
+export function signBody(secret, body) {
+ return `sha256=${crypto.createHmac('sha256', secret).update(body).digest('hex')}`;
+}
+
+function serverUrl() {
+ return process.env.PUBLIC_SERVER_URL || `http://localhost:${process.env.PORT || 3001}`;
+}
+
+/** The JSON-LD in a page's cleaned HTML: a CMS's rich-text field drops <script>. */
+function jsonLdOf(html) {
+ const $ = cheerio.load(html, null, false);
+ return $('script')
+ .toArray()
+ .filter((el) => isJsonLd($, el))
+ .flatMap((el) => {
+ try {
+ return [JSON.parse($(el).text())];
+ } catch {
+ return [];
+ }
+ });
+}
+
+/**
+ * The package a page goes as (schemaVersion 1). The callback is offered only
+ * to a webhook with a secret: the secret is what authenticates it. What the
+ * draft is (method, live address, page type, language) comes from its row,
+ * not the browser: an optimized page's workflow updates its post.
+ */
+export function contentPackage({ delivery, page, brand, html, jsonLd, callback = true }) {
+ return {
+ event: DELIVERY_EVENT,
+ schemaVersion: PACKAGE_VERSION,
+ delivery: {
+ id: delivery.id,
+ batchId: delivery.batch_id ?? null,
+ sentAt: new Date().toISOString(),
+ },
+ page: {
+ draftId: page.draftId,
+ title: page.title,
+ slug: page.slug,
+ metaTitle: page.metaTitle || page.title,
+ metaDescription: page.metaDescription,
+ html,
+ jsonLd: jsonLd ?? jsonLdOf(html),
+ author: page.author,
+ featuredImage: page.featuredImage,
+ method: page.method ?? null,
+ sourceUrl: page.sourceUrl ?? null,
+ pageType: page.pageType ?? null,
+ language: page.language ?? null,
+ },
+ brand: { id: brand.id, name: brand.name, domain: brand.domain, industry: brand.industry },
+ callback_url: callback ? `${serverUrl()}/webhooks/content-drafts/${delivery.id}/status` : null,
+ callback_method: callback ? 'POST' : null,
+ };
+}
+
+async function webhooksFor(brandId) {
+ const { data, error } = await supabaseAdmin
+ .from('webhook_configs')
+ .select('id, webhook_url, webhook_secret, events')
+ .eq('brand_id', brandId)
+ .eq('is_active', true);
+ if (error) throw new Error(error.message);
+ const configs = data ?? [];
+ if (!configs.length) {
+ throw new DeliveryError('no_webhook', 'No workflow connected', 409);
+ }
+ const subscribed = configs.filter((c) => c.events?.includes(DELIVERY_EVENT));
+ if (!subscribed.length) {
+ throw new DeliveryError(
+ 'webhook_not_subscribed',
+ 'Webhook is not subscribed to Content page sent events.',
+ 409,
+ );
+ }
+ return subscribed;
+}
+
+async function brandFor(brandId) {
+ const [{ data: brand }, { data: domains }] = await Promise.all([
+ supabaseAdmin.from('brands').select('id, name, industry, language').eq('id', brandId).single(),
+ supabaseAdmin
+ .from('brand_domains')
+ .select('domain')
+ .eq('brand_id', brandId)
+ .eq('is_primary', true)
+ .limit(1),
+ ]);
+ return {
+ id: brand?.id ?? brandId,
+ name: brand?.name ?? '',
+ domain: domains?.[0]?.domain ?? '',
+ industry: brand?.industry ?? '',
+ language: brand?.language ?? null,
+ };
+}
+
+/**
+ * Sends one queued delivery to the brand's webhooks and writes how it went:
+ * sent once any of them takes it (with that one's answer), else failed with
+ * the last reason. A callback can land before the webhook answers (an
+ * automation that publishes, or fails, first): then the delivery keeps what
+ * the callback said, and that is what comes back.
+ */
+async function deliver({ delivery, page, brand, configs }) {
+ const html = cleanPublishHtml(page.html);
+ const jsonLd = jsonLdOf(html);
+ let taken = null;
+ let last = null;
+ let failure = null;
+ for (const config of configs) {
+ const signed = Boolean(config.webhook_secret);
+ const body = JSON.stringify(
+ contentPackage({ delivery, page, brand, html, jsonLd, callback: signed }),
+ );
+ const headers = {};
+ if (signed) {
+ // The secret as the other webhooks send it, and the body signed with it.
+ headers['X-Webhook-Secret'] = config.webhook_secret;
+ headers['X-Ansvisor-Signature'] = signBody(config.webhook_secret, body);
+ }
+ try {
+ const res = await postJson(config.webhook_url, body, { headers });
+ last = res;
+ if (res.status >= 200 && res.status < 300) taken ??= res;
+ else failure = `The webhook answered ${res.status}`;
+ } catch (err) {
+ failure = err instanceof PageFetchError ? err.message : 'The webhook could not be reached';
+ logger.warn(
+ { err, configId: config.id, deliveryId: delivery.id },
+ '[content-delivery] send failed',
+ );
+ }
+ }
+ const answered = taken ?? last;
+ const update = {
+ status: taken ? 'sent' : 'failed',
+ http_status: answered?.status ?? null,
+ response_excerpt: answered?.answer ? answered.answer.slice(0, EXCERPT_CHARS) : null,
+ error: taken ? null : (failure ?? 'Not sent').slice(0, 500),
+ sent_at: new Date().toISOString(),
+ };
+ const { data: written, error } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .update(update)
+ .eq('id', delivery.id)
+ .eq('status', 'queued')
+ .select('id');
+ if (error) {
+ logger.error({ err: error, deliveryId: delivery.id }, '[content-delivery] write failed');
+ } else if (written && !written.length) {
+ // A callback had its word first.
+ const { data: told } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .select('status, error, published_url')
+ .eq('id', delivery.id)
+ .maybeSingle();
+ if (told) return { id: delivery.id, draftId: page.draftId, ...update, ...told };
+ }
+ return { id: delivery.id, draftId: page.draftId, ...update };
+}
+
+/** A queued delivery that doesn't go, closed as failed with the reason. */
+async function closeQueued(delivery, reason) {
+ const { error } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .update({ status: 'failed', error: reason, sent_at: new Date().toISOString() })
+ .eq('id', delivery.id)
+ .eq('status', 'queued');
+ if (error) {
+ logger.error({ err: error, deliveryId: delivery.id }, '[content-delivery] write failed');
+ }
+}
+
+/** The batch's pages, one after another; one deleted or archived before its turn doesn't go. */
+async function deliverBatch(going, { brand, configs, batchId }) {
+ for (const [i, item] of going.entries()) {
+ // A short pause between pages, none before the first.
+ if (i > 0) await new Promise((resolve) => setTimeout(resolve, PAUSE_MS));
+ try {
+ const { data: still } = await supabaseAdmin
+ .from('content_drafts')
+ .select('id')
+ .eq('id', item.page.draftId)
+ .is('archived_at', null)
+ .maybeSingle();
+ if (!still) {
+ await closeQueued(item.delivery, 'The page was deleted or archived before it was sent');
+ continue;
+ }
+ await deliver({ ...item, brand, configs });
+ } catch (err) {
+ logger.error(
+ { err, batchId, deliveryId: item.delivery.id },
+ '[content-delivery] send crashed',
+ );
+ await closeQueued(item.delivery, 'Not sent: something went wrong').catch(() => {});
+ }
+ }
+}
+
+/** A draft no one has set rules on: the workspace's My rules apply (rules.ts effectiveRules). */
+function untouched(rules) {
+ return (
+ !rules ||
+ (rules.source == null &&
+ !Object.keys(rules.overrides ?? {}).length &&
+ !(rules.textRules ?? []).length)
+ );
+}
+
+/** The workspace's My rules (00214) for these drafts' types, by type; none when unread. */
+async function myRuleSets(orgId, drafts) {
+ const types = [...new Set(drafts.map((d) => d.rules?.set ?? d.page_type).filter(Boolean))];
+ if (!types.length) return new Map();
+ const { data, error } = await supabaseAdmin
+ .from('content_rule_sets')
+ .select('page_type, overrides')
+ .eq('organization_id', orgId)
+ .in('page_type', types);
+ if (error) logger.warn({ err: error }, '[content-delivery] My rules not read');
+ return new Map((data ?? []).map((set) => [set.page_type, set]));
+}
+
+/**
+ * Sends pages of one brand: checks they are the brand's (not archived), that
+ * a webhook takes the event, reserves them against the day's cap (those past
+ * it don't go), keeps each page's slug and meta on its draft, then sends
+ * them. One page is sent before this returns; more go on in the background,
+ * so a CMS isn't sent 25 posts at once.
+ *
+ * @returns {Promise<{ batchId: string|null, deliveries: object[], skipped: number }>}
+ * deliveries: the sent one (one page) or the queued ones (more); skipped:
+ * pages past the day's cap
+ */
+export async function sendContentPages({ orgId, brandId, userId, pages: asked }) {
+ // A page named twice goes once.
+ const byId = new Map(asked.map((p) => [p.draftId, p]));
+ const pages = [...byId.values()];
+ const ids = [...byId.keys()];
+ const { data: drafts, error } = await supabaseAdmin
+ .from('content_drafts')
+ .select('id, method, source_url, page_type, rules')
+ .eq('brand_id', brandId)
+ .is('archived_at', null)
+ .in('id', ids);
+ if (error) throw new Error(error.message);
+ if ((drafts ?? []).length !== ids.length) {
+ throw new DeliveryError('not_found', 'A page to send is not in this brand', 404);
+ }
+ const configs = await webhooksFor(brandId);
+
+ const batchId = pages.length > 1 ? crypto.randomUUID() : null;
+ const { data: queued, error: reserveError } = await supabaseAdmin.rpc(
+ 'reserve_content_deliveries',
+ {
+ p_organization_id: orgId,
+ p_brand_id: brandId,
+ p_sent_by: userId,
+ p_batch_id: batchId,
+ p_items: pages.map((p) => ({ draft_id: p.draftId, title: p.title, slug: p.slug })),
+ p_limit: DAILY_DELIVERIES,
+ },
+ );
+ if (reserveError) throw new Error(reserveError.message);
+ const rows = queued ?? [];
+ if (!rows.length) {
+ throw new DeliveryError(
+ 'daily_limit',
+ `This workspace has sent ${DAILY_DELIVERIES} pages in the last 24 hours. Try again later.`,
+ 429,
+ );
+ }
+
+ // The reserved pages, in the order they go; their slug and meta stay on the draft.
+ const order = new Map(ids.map((id, i) => [id, i]));
+ const going = rows
+ .map((row) => ({ delivery: row, page: byId.get(row.draft_id) }))
+ .sort((a, b) => order.get(a.page.draftId) - order.get(b.page.draftId));
+ const kept = await Promise.all(
+ going.map(({ page }) =>
+ supabaseAdmin
+ .from('content_drafts')
+ .update({
+ slug: page.slug,
+ meta_title: page.metaTitle || null,
+ meta_description: page.metaDescription || null,
+ })
+ .eq('id', page.draftId),
+ ),
+ );
+ for (const result of kept) {
+ if (result?.error)
+ logger.warn({ err: result.error }, '[content-delivery] slug and meta not kept');
+ }
+
+ // What each draft is, from its row: method, live address, page type, and
+ // the language its Language rule names (its own, or the workspace's My
+ // rules for a draft no one has set rules on, as the editor reads them),
+ // else the brand's.
+ const rowOf = new Map((drafts ?? []).map((d) => [d.id, d]));
+ const [brand, mine] = await Promise.all([
+ brandFor(brandId),
+ myRuleSets(
+ orgId,
+ going.map((item) => rowOf.get(item.page.draftId)).filter((d) => d && untouched(d.rules)),
+ ),
+ ]);
+ for (const item of going) {
+ const draft = rowOf.get(item.page.draftId) ?? {};
+ const rules = untouched(draft.rules)
+ ? mine.get(draft.rules?.set ?? draft.page_type)
+ : draft.rules;
+ const rule = rules?.overrides?.language;
+ item.page = {
+ ...item.page,
+ method: draft.method ?? null,
+ sourceUrl: draft.source_url ?? null,
+ pageType: draft.page_type ?? null,
+ language:
+ (rule?.on !== false && languageCodeOf(rule?.value)) ||
+ languageCodeOf(brand.language) ||
+ 'en',
+ };
+ }
+ if (pages.length === 1) {
+ const sent = await deliver({ ...going[0], brand, configs });
+ return { batchId, deliveries: [sent], skipped: 0 };
+ }
+ void deliverBatch(going, { brand, configs, batchId });
+ return {
+ batchId,
+ deliveries: rows.map((r) => ({ id: r.id, draftId: r.draft_id, status: r.status })),
+ skipped: pages.length - rows.length,
+ };
+}
diff --git a/server/src/lib/content-delivery.test.js b/server/src/lib/content-delivery.test.js
new file mode 100644
index 000000000..e52b2f9cb
--- /dev/null
+++ b/server/src/lib/content-delivery.test.js
@@ -0,0 +1,433 @@
+import crypto from 'node:crypto';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Send to CMS (#1331): pages go to the brand's webhook as content packages,
+ * reserved against the workspace's 200 a day, each one a delivery row.
+ */
+
+const db = {
+ brand: {},
+ drafts: [],
+ ruleSets: [],
+ // What a callback that landed first left on the delivery.
+ told: null,
+ configs: [],
+ queued: [],
+ updates: [],
+ rpc: [],
+};
+
+function from(table) {
+ const q = { table, filters: [], update: null };
+ const result = () => {
+ if (q.update) {
+ db.updates.push({ table, update: q.update, filters: q.filters });
+ // A callback first: the queued row isn't there to write.
+ if (table === 'content_draft_deliveries' && db.told) return { data: [], error: null };
+ return { data: null, error: null };
+ }
+ if (table === 'content_draft_deliveries') {
+ return { data: db.told ? [{ id: 'd-1', ...db.told }] : null, error: null };
+ }
+ if (table === 'content_rule_sets') {
+ const types = q.filters.find(([op]) => op === 'in')?.[2] ?? [];
+ return { data: db.ruleSets.filter((r) => types.includes(r.page_type)), error: null };
+ }
+ if (table === 'content_drafts') {
+ const ids = q.filters.find(([op]) => op === 'in')?.[2];
+ return { data: db.drafts.filter((d) => !ids || ids.includes(d.id)), error: null };
+ }
+ if (table === 'webhook_configs') return { data: db.configs, error: null };
+ if (table === 'brands') return { data: db.brand, error: null };
+ if (table === 'brand_domains') return { data: [{ domain: 'acme.example' }], error: null };
+ return { data: null, error: null };
+ };
+ const chain = {
+ select: () => chain,
+ eq: (col, value) => (q.filters.push(['eq', col, value]), chain),
+ neq: (col, value) => (q.filters.push(['neq', col, value]), chain),
+ is: (col, value) => (q.filters.push(['is', col, value]), chain),
+ in: (col, value) => (q.filters.push(['in', col, value]), chain),
+ limit: () => chain,
+ single: async () => result(),
+ maybeSingle: async () => {
+ const { data } = result();
+ const id = q.filters.find(([op, col]) => op === 'eq' && col === 'id')?.[2];
+ return { data: (data ?? []).find((d) => d.id === id) ?? null, error: null };
+ },
+ update: (row) => ((q.update = row), chain),
+ then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),
+ };
+ return chain;
+}
+
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (t) => from(t),
+ rpc: async (fn, args) => {
+ db.rpc.push({ fn, args });
+ return { data: db.queued, error: null };
+ },
+ },
+}));
+const postJson = vi.fn();
+vi.mock('./safe-post.js', () => ({ postJson: (...args) => postJson(...args) }));
+
+const { DAILY_DELIVERIES, DeliveryError, PAUSE_MS, cleanPublishHtml, sendContentPages, signBody } =
+ await import('./content-delivery.js');
+
+const page = (over = {}) => ({
+ draftId: 'c0ffee00-0000-4000-8000-000000000001',
+ title: 'Best AEO tools (2026)',
+ slug: 'best-aeo-tools',
+ metaTitle: 'Best AEO tools',
+ metaDescription: 'The tools that help AI answers cite you.',
+ html: '<h2>Why</h2><p>Because.</p>',
+ author: 'Ada Lovelace',
+ featuredImage: null,
+ ...over,
+});
+const row = (draftId, over = {}) => ({
+ id: `d-${draftId.slice(-1)}`,
+ draft_id: draftId,
+ batch_id: null,
+ status: 'queued',
+ ...over,
+});
+
+const draft = (id, over = {}) => ({
+ id,
+ method: 'create',
+ source_url: null,
+ page_type: 'blog_post',
+ rules: null,
+ ...over,
+});
+
+beforeEach(() => {
+ db.brand = { id: 'b1', name: 'Acme Coffee', industry: 'Coffee', language: null };
+ db.drafts = [draft(page().draftId)];
+ db.ruleSets = [];
+ db.told = null;
+ db.configs = [
+ {
+ id: 'w1',
+ webhook_url: 'https://hooks.acme.example/cms',
+ webhook_secret: 's3cret',
+ events: ['content_draft.sent'],
+ },
+ ];
+ db.queued = [row(page().draftId)];
+ db.updates = [];
+ db.rpc = [];
+ postJson.mockReset().mockResolvedValue({ status: 200, answer: '{"ok":true}' });
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+const send = (pages = [page()]) =>
+ sendContentPages({ orgId: 'o1', brandId: 'b1', userId: 'u1', pages });
+
+describe('cleanPublishHtml', () => {
+ it('keeps the page and its JSON-LD, without scripts, frames, handlers or script links', () => {
+ const html = cleanPublishHtml(
+ '<p onclick="steal()">Hi <a href="javascript:alert(1)">x</a> <a href="https://a.example">ok</a></p>' +
+ '<script>alert(1)</script><script type="application/ld+json">{"@type":"Article"}</script>' +
+ '<iframe src="https://evil.example"></iframe><img src="data:image/png;base64,AAA" alt="dot">' +
+ '<img src="data:text/html,x">',
+ );
+ expect(html).toBe(
+ '<p>Hi <a>x</a> <a href="https://a.example">ok</a></p>' +
+ '<script type="application/ld+json">{"@type":"Article"}</script>' +
+ '<img src="data:image/png;base64,AAA" alt="dot"><img>',
+ );
+ });
+});
+
+describe('cleanPublishHtml, against links that hide their scheme', () => {
+ it.each([
+ ['<a href="java&#9;script:alert(1)">x</a>', '<a>x</a>'],
+ ['<a href="jav&#x0A;ascript:alert(1)">x</a>', '<a>x</a>'],
+ ['<a href="&#1;javascript:alert(1)">x</a>', '<a>x</a>'],
+ ['<a href="vbscript:x">x</a>', '<a>x</a>'],
+ [
+ '<svg><a><animate attributeName="href" values="javascript:alert(1)"></animate></a></svg>',
+ '<svg><a></a></svg>',
+ ],
+ ['<a href="mailto:[email protected]">x</a>', '<a href="mailto:[email protected]">x</a>'],
+ ['<a href="/pricing#plans">x</a>', '<a href="/pricing#plans">x</a>'],
+ ['<a href="data:image/png;base64,AAA">x</a>', '<a>x</a>'],
+ ])('%s', (html, clean) => {
+ expect(cleanPublishHtml(html)).toBe(clean);
+ });
+});
+
+describe('signBody', () => {
+ it('signs the body with the webhook’s secret, as sha256=<hex>', () => {
+ const expected = crypto.createHmac('sha256', 's3cret').update('{"a":1}').digest('hex');
+ expect(signBody('s3cret', '{"a":1}')).toBe(`sha256=${expected}`);
+ });
+});
+
+describe('sendContentPages', () => {
+ it('sends one page as a package, signed, and keeps its slug and meta on the draft', async () => {
+ const sent = await send();
+ expect(db.rpc).toEqual([
+ {
+ fn: 'reserve_content_deliveries',
+ args: {
+ p_organization_id: 'o1',
+ p_brand_id: 'b1',
+ p_sent_by: 'u1',
+ p_batch_id: null,
+ p_items: [{ draft_id: page().draftId, title: page().title, slug: 'best-aeo-tools' }],
+ p_limit: DAILY_DELIVERIES,
+ },
+ },
+ ]);
+ const [address, body, { headers }] = postJson.mock.calls[0];
+ expect(address).toBe('https://hooks.acme.example/cms');
+ expect(headers['X-Webhook-Secret']).toBe('s3cret');
+ expect(headers['X-Ansvisor-Signature']).toBe(signBody('s3cret', body));
+ expect(JSON.parse(body)).toMatchObject({
+ event: 'content_draft.sent',
+ schemaVersion: 1,
+ delivery: { id: 'd-1', batchId: null },
+ page: {
+ draftId: page().draftId,
+ title: 'Best AEO tools (2026)',
+ slug: 'best-aeo-tools',
+ metaTitle: 'Best AEO tools',
+ html: '<h2>Why</h2><p>Because.</p>',
+ jsonLd: [],
+ author: 'Ada Lovelace',
+ method: 'create',
+ sourceUrl: null,
+ pageType: 'blog_post',
+ language: 'en',
+ },
+ brand: { id: 'b1', name: 'Acme Coffee', domain: 'acme.example', industry: 'Coffee' },
+ callback_url: expect.stringMatching(/\/webhooks\/content-drafts\/d-1\/status$/),
+ callback_method: 'POST',
+ });
+ expect(db.updates).toEqual([
+ {
+ table: 'content_drafts',
+ update: {
+ slug: 'best-aeo-tools',
+ meta_title: 'Best AEO tools',
+ meta_description: 'The tools that help AI answers cite you.',
+ },
+ filters: [['eq', 'id', page().draftId]],
+ },
+ {
+ table: 'content_draft_deliveries',
+ update: expect.objectContaining({ status: 'sent', http_status: 200, error: null }),
+ // A callback that landed first keeps what it said.
+ filters: [
+ ['eq', 'id', 'd-1'],
+ ['eq', 'status', 'queued'],
+ ],
+ },
+ ]);
+ expect(sent).toMatchObject({
+ batchId: null,
+ skipped: 0,
+ deliveries: [{ id: 'd-1', status: 'sent' }],
+ });
+ });
+
+ it('offers no callback to a webhook without a secret, and keeps the answer of the one that took it', async () => {
+ db.configs = [
+ {
+ id: 'w1',
+ webhook_url: 'https://a.example',
+ webhook_secret: null,
+ events: ['content_draft.sent'],
+ },
+ {
+ id: 'w2',
+ webhook_url: 'https://b.example',
+ webhook_secret: 's',
+ events: ['content_draft.sent'],
+ },
+ ];
+ postJson
+ .mockResolvedValueOnce({ status: 200, answer: 'taken' })
+ .mockResolvedValueOnce({ status: 500, answer: 'boom' });
+ const sent = await send();
+ const [unsigned, signed] = postJson.mock.calls;
+ expect(JSON.parse(unsigned[1])).toMatchObject({ callback_url: null, callback_method: null });
+ expect(unsigned[2].headers).toEqual({});
+ expect(JSON.parse(signed[1]).callback_url).toMatch(/\/status$/);
+ expect(sent.deliveries[0]).toMatchObject({
+ status: 'sent',
+ http_status: 200,
+ response_excerpt: 'taken',
+ });
+ });
+
+ it('tells what the page is from its row: method, live address, page type, language and JSON-LD', async () => {
+ const ld = { '@context': 'https://schema.org', '@type': 'FAQPage' };
+ db.drafts = [
+ draft(page().draftId, {
+ method: 'optimize',
+ source_url: 'https://acme.example/blog/aeo',
+ page_type: 'guide',
+ rules: { overrides: { language: { on: true, value: 'German' } } },
+ }),
+ ];
+ db.brand.language = 'tr';
+ // The browser's own claims about the page don't count.
+ await send([
+ page({
+ method: 'create',
+ html: `<p>Hi</p><script type="application/ld+json">${JSON.stringify(ld)}</script>`,
+ }),
+ ]);
+ let sent = JSON.parse(postJson.mock.calls[0][1]).page;
+ expect(sent).toMatchObject({
+ method: 'optimize',
+ sourceUrl: 'https://acme.example/blog/aeo',
+ pageType: 'guide',
+ language: 'de',
+ jsonLd: [ld],
+ });
+
+ // The rule turned off: the brand's language.
+ db.drafts[0].rules.overrides.language.on = false;
+ await send();
+ sent = JSON.parse(postJson.mock.calls[1][1]).page;
+ expect(sent.language).toBe('tr');
+ });
+
+ it('reads the language from My rules for a draft no one has set rules on, as the editor does', async () => {
+ db.ruleSets = [{ page_type: 'blog_post', overrides: { language: { value: 'French' } } }];
+ await send();
+ expect(JSON.parse(postJson.mock.calls[0][1]).page.language).toBe('fr');
+
+ // The draft's own choices win once it has any.
+ db.drafts[0].rules = { source: 'default', overrides: {}, textRules: [] };
+ await send();
+ expect(JSON.parse(postJson.mock.calls[1][1]).page.language).toBe('en');
+ });
+
+ it('takes JSON-LD however its script type is written, as the clean keeps it', async () => {
+ const ld = { '@type': 'Article' };
+ await send([
+ page({ html: `<script type=" Application/LD+JSON ">${JSON.stringify(ld)}</script><p>x</p>` }),
+ ]);
+ expect(JSON.parse(postJson.mock.calls[0][1]).page.jsonLd).toEqual([ld]);
+ });
+
+ it('keeps what a callback said before the webhook answered, and answers with it', async () => {
+ db.told = { status: 'failed', error: 'Slug already taken', published_url: null };
+ const sent = await send();
+ expect(sent.deliveries[0]).toMatchObject({ status: 'failed', error: 'Slug already taken' });
+ });
+
+ it('writes a delivery failed when the webhook answers an error or can’t be reached', async () => {
+ postJson.mockResolvedValue({ status: 500, answer: 'boom' });
+ let sent = await send();
+ expect(sent.deliveries[0]).toMatchObject({
+ status: 'failed',
+ http_status: 500,
+ error: 'The webhook answered 500',
+ response_excerpt: 'boom',
+ });
+
+ postJson.mockRejectedValue(new Error('ECONNRESET'));
+ sent = await send();
+ expect(sent.deliveries[0]).toMatchObject({
+ status: 'failed',
+ error: 'The webhook could not be reached',
+ });
+ });
+
+ it('sends more pages in the background, one after another with a short pause, under one batch', async () => {
+ vi.useFakeTimers();
+ const second = page({ draftId: 'c0ffee00-0000-4000-8000-000000000002', slug: 'second' });
+ db.drafts = [draft(page().draftId), draft(second.draftId)];
+ // The reserved rows may come back in any order: they go in the pages' order.
+ db.queued = [row(second.draftId, { batch_id: 'x' }), row(page().draftId, { batch_id: 'x' })];
+ let release;
+ postJson.mockImplementationOnce(() => new Promise((resolve) => (release = resolve)));
+
+ const sent = await send([page(), second, page()]);
+ expect(db.rpc[0].args.p_batch_id).toEqual(expect.any(String));
+ // Named twice, it goes once.
+ expect(db.rpc[0].args.p_items.map((i) => i.draft_id)).toEqual([page().draftId, second.draftId]);
+ expect(sent).toMatchObject({
+ skipped: 0,
+ deliveries: [{ status: 'queued' }, { status: 'queued' }],
+ });
+
+ // The first is still sending: the second waits for it, then for the pause.
+ await vi.advanceTimersByTimeAsync(0);
+ expect(postJson).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(postJson.mock.calls[0][1]).page.draftId).toBe(page().draftId);
+ release({ status: 200, answer: '' });
+ await vi.advanceTimersByTimeAsync(PAUSE_MS - 1);
+ expect(postJson).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ await vi.waitFor(() => expect(postJson).toHaveBeenCalledTimes(2));
+ expect(JSON.parse(postJson.mock.calls[1][1]).page.draftId).toBe(second.draftId);
+ });
+
+ it('closes a page deleted before its turn in a batch, and sends the rest', async () => {
+ vi.useFakeTimers();
+ const second = page({ draftId: 'c0ffee00-0000-4000-8000-000000000002', slug: 'second' });
+ db.drafts = [draft(page().draftId), draft(second.draftId)];
+ db.queued = [row(page().draftId), row(second.draftId)];
+ let release;
+ postJson.mockImplementationOnce(() => new Promise((resolve) => (release = resolve)));
+ await send([page(), second]);
+ await vi.waitFor(() => expect(postJson).toHaveBeenCalledTimes(1));
+ // The second is deleted while the first is sending: it doesn't go.
+ db.drafts = [draft(page().draftId)];
+ release({ status: 200, answer: '' });
+ await vi.advanceTimersByTimeAsync(PAUSE_MS);
+ await vi.waitFor(() =>
+ expect(db.updates).toContainEqual({
+ table: 'content_draft_deliveries',
+ update: expect.objectContaining({
+ status: 'failed',
+ error: 'The page was deleted or archived before it was sent',
+ }),
+ filters: [
+ ['eq', 'id', 'd-2'],
+ ['eq', 'status', 'queued'],
+ ],
+ }),
+ );
+ expect(postJson).toHaveBeenCalledTimes(1);
+ });
+
+ it('counts the pages past the day’s cap as skipped, and refuses once nothing is left', async () => {
+ const second = page({ draftId: 'c0ffee00-0000-4000-8000-000000000002', slug: 'second' });
+ db.drafts = [draft(page().draftId), draft(second.draftId)];
+ db.queued = [row(page().draftId)];
+ expect((await send([page(), second])).skipped).toBe(1);
+
+ db.queued = [];
+ await expect(send()).rejects.toMatchObject({ code: 'daily_limit', status: 429 });
+ });
+
+ it('refuses a page of another brand, and a brand with no webhook taking the event', async () => {
+ db.drafts = [];
+ await expect(send()).rejects.toBeInstanceOf(DeliveryError);
+ await expect(send()).rejects.toMatchObject({ code: 'not_found', status: 404 });
+
+ db.drafts = [draft(page().draftId)];
+ db.configs = [];
+ await expect(send()).rejects.toMatchObject({ code: 'no_webhook', status: 409 });
+
+ db.configs = [{ id: 'w1', webhook_url: 'https://x.example', events: ['opportunity.sent'] }];
+ await expect(send()).rejects.toMatchObject({ code: 'webhook_not_subscribed', status: 409 });
+ expect(db.rpc).toEqual([]);
+ expect(postJson).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/lib/languages.js b/server/src/lib/languages.js
index e0918abbc..1a305377a 100644
--- a/server/src/lib/languages.js
+++ b/server/src/lib/languages.js
@@ -17,3 +17,23 @@ export const LANGUAGE_NAMES = {
export function getLanguageName(code) {
return LANGUAGE_NAMES[code] || 'English';
}
+
+/**
+ * A language as a brand or a Language rule names it ("tr", "pt-BR",
+ * "Turkish", "English (US)", "US English") as its two-letter code, or null
+ * for one not known here. A code on its own ("pl", "pl-PL") is taken as it
+ * is; a two-letter word before a name is a region ("US", "UK"), not one.
+ */
+export function languageCodeOf(value) {
+ const text = String(value ?? '')
+ .trim()
+ .toLowerCase();
+ const words = text.split(/[^\p{L}]+/u).filter(Boolean);
+ if (!words.length) return null;
+ if (LANGUAGE_NAMES[words[0]]) return words[0];
+ const code = Object.keys(LANGUAGE_NAMES).find((c) =>
+ words.includes(LANGUAGE_NAMES[c].toLowerCase()),
+ );
+ if (code) return code;
+ return /^[a-z]{2}(?:[-_][a-z]{2,4})?$/.test(text) ? words[0] : null;
+}
diff --git a/server/src/lib/languages.test.js b/server/src/lib/languages.test.js
index 05be1d59d..3946b1fe1 100644
--- a/server/src/lib/languages.test.js
+++ b/server/src/lib/languages.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { getLanguageName, LANGUAGE_NAMES } from './languages.js';
+import { getLanguageName, languageCodeOf, LANGUAGE_NAMES } from './languages.js';
describe('languages', () => {
it('should return correct language names', () => {
@@ -15,4 +15,21 @@ describe('languages', () => {
expect(LANGUAGE_NAMES).toBeDefined();
expect(LANGUAGE_NAMES.en).toBe('English');
});
+
+ it('reads a language as a code, as a brand or a Language rule names it', () => {
+ expect(languageCodeOf('tr')).toBe('tr');
+ expect(languageCodeOf('pt-BR')).toBe('pt');
+ expect(languageCodeOf('Turkish')).toBe('tr');
+ expect(languageCodeOf('English (US)')).toBe('en');
+ // A region before the name isn't a language ("UK" is Ukrainian's code).
+ expect(languageCodeOf('US English')).toBe('en');
+ expect(languageCodeOf('UK English')).toBe('en');
+ expect(languageCodeOf('in German')).toBe('de');
+ // A code not listed here, on its own, is taken as it is.
+ expect(languageCodeOf('pl')).toBe('pl');
+ expect(languageCodeOf('pl-PL')).toBe('pl');
+ expect(languageCodeOf('Klingon')).toBeNull();
+ expect(languageCodeOf('xx yy')).toBeNull();
+ expect(languageCodeOf(null)).toBeNull();
+ });
});
diff --git a/server/src/lib/safe-fetch.js b/server/src/lib/safe-fetch.js
index b07f74946..83c09ea66 100644
--- a/server/src/lib/safe-fetch.js
+++ b/server/src/lib/safe-fetch.js
@@ -71,6 +71,9 @@ for (const [address, prefix] of [
for (const [address, prefix] of [
['::', 128],
['::1', 128],
+ // IPv4-compatible (::a.b.c.d) and IPv4-translated (::ffff:0:a.b.c.d) forms.
+ ['::', 96],
+ ['::ffff:0:0:0', 96],
['64:ff9b::', 96],
['100::', 64],
['2001::', 32],
diff --git a/server/src/lib/safe-post.js b/server/src/lib/safe-post.js
new file mode 100644
index 000000000..e795eca5a
--- /dev/null
+++ b/server/src/lib/safe-post.js
@@ -0,0 +1,111 @@
+/**
+ * Posting JSON to an address a workspace configured (Send to CMS, #1331).
+ * On Ansvisor Cloud it never reaches anything private, as fetchPage reads a
+ * page:
+ * * http(s) only, with no credentials in it; any port, since a workspace's
+ * own automation (n8n, a CMS) often listens on one of its own;
+ * * every address its host resolves to must be public, checked in the
+ * connection's own DNS lookup (no DNS rebinding);
+ * * no redirect is followed: a 3xx is an answer, as any other non-2xx;
+ * * a time limit for the whole request, and only the start of the answer
+ * is read back.
+ * Self-hosted, a private address is the workspace's own network (n8n at
+ * http://n8n:5678), as its other webhooks reach it: only the scheme and
+ * credentials are checked. Failures carry PageFetchError's codes:
+ * invalid_url, blocked, unreachable, timeout.
+ */
+
+import http from 'node:http';
+import https from 'node:https';
+import { isCloud } from '../config/plans.js';
+import { PageFetchError, checkPageUrl, publicOnlyLookup } from './safe-fetch.js';
+
+export const POST_TIMEOUT_MS = 15_000;
+/** How much of an answer is read back: enough to keep with the delivery. */
+export const MAX_ANSWER_BYTES = 8 * 1024;
+
+const USER_AGENT = 'Ansvisor-Webhook/1.0 (+https://ansvisor.com)';
+
+/**
+ * A webhook address, checked as a page's is but on any port; throws
+ * 'invalid_url' or 'blocked'. `privateOk` (self-hosted) takes a private one.
+ */
+export function checkWebhookUrl(value, { privateOk = false } = {}) {
+ let url;
+ try {
+ url = new URL(String(value).trim());
+ } catch {
+ throw new PageFetchError('invalid_url', 'Not a URL');
+ }
+ if (!privateOk) return checkPageUrl(value, [url.port]);
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ throw new PageFetchError('invalid_url', 'Only http and https addresses can be posted to');
+ }
+ if (url.username || url.password) {
+ throw new PageFetchError('invalid_url', 'URLs with credentials are not posted to');
+ }
+ return url;
+}
+
+/**
+ * POSTs `body` (a string, already JSON) to the address.
+ * @param {string} address
+ * @param {string} body
+ * @param {{ headers?: Record<string, string>, timeoutMs?: number, lookup?: Function }} [opts]
+ * `lookup` replaces the public-only lookup; tests use it to reach a local server.
+ * @returns {Promise<{ status: number, answer: string }>} the HTTP status and the start of the answer
+ */
+export async function postJson(address, body, opts = {}) {
+ const cloud = isCloud();
+ const url = checkWebhookUrl(address, { privateOk: !cloud });
+ const { headers = {}, timeoutMs = POST_TIMEOUT_MS } = opts;
+ // The test's lookup, else the public-only one on Cloud, else the system's.
+ const lookup = opts.lookup ?? (cloud ? publicOnlyLookup : undefined);
+ const signal = AbortSignal.timeout(timeoutMs);
+ return new Promise((resolve, reject) => {
+ const client = url.protocol === 'https:' ? https : http;
+ const req = client.request(
+ url,
+ {
+ method: 'POST',
+ agent: false,
+ lookup,
+ signal,
+ headers: {
+ 'user-agent': USER_AGENT,
+ 'content-type': 'application/json',
+ 'content-length': Buffer.byteLength(body),
+ ...headers,
+ },
+ },
+ (res) => {
+ const status = res.statusCode ?? 0;
+ const chunks = [];
+ let size = 0;
+ const done = () => resolve({ status, answer: Buffer.concat(chunks).toString('utf8') });
+ res.on('data', (chunk) => {
+ if (size >= MAX_ANSWER_BYTES) return;
+ chunks.push(chunk.subarray(0, MAX_ANSWER_BYTES - size));
+ size += chunk.length;
+ // The rest of a long answer isn't read.
+ if (size >= MAX_ANSWER_BYTES) {
+ res.destroy();
+ done();
+ }
+ });
+ res.on('end', done);
+ res.on('error', (err) => reject(err));
+ },
+ );
+ req.on('error', (err) => {
+ if (err instanceof PageFetchError) return reject(err);
+ if (signal.aborted) {
+ return reject(new PageFetchError('timeout', 'The webhook took too long to answer'));
+ }
+ reject(
+ new PageFetchError('unreachable', 'The webhook could not be reached', { errno: err?.code }),
+ );
+ });
+ req.end(body);
+ });
+}
diff --git a/server/src/lib/safe-post.test.js b/server/src/lib/safe-post.test.js
new file mode 100644
index 000000000..6ec6aef6d
--- /dev/null
+++ b/server/src/lib/safe-post.test.js
@@ -0,0 +1,128 @@
+import http from 'node:http';
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { PageFetchError, publicOnlyLookup } from './safe-fetch.js';
+import { MAX_ANSWER_BYTES, checkWebhookUrl, postJson } from './safe-post.js';
+
+/**
+ * Posting a content package to a workspace's webhook (Send to CMS, #1331)
+ * must never reach a private address, follows no redirect, and stops at its
+ * time limit, reading back only the start of an answer.
+ */
+
+describe('checkWebhookUrl', () => {
+ it('takes http(s) on any port, as a workspace’s own automation listens on its own', () => {
+ expect(checkWebhookUrl('https://hooks.zapier.com/hooks/catch/1/abc').hostname).toBe(
+ 'hooks.zapier.com',
+ );
+ expect(checkWebhookUrl('http://n8n.acme.example:5678/webhook/x').port).toBe('5678');
+ });
+
+ it.each([
+ ['ftp://acme.example/x', 'invalid_url'],
+ ['https://user:[email protected]/', 'invalid_url'],
+ ['not a url', 'invalid_url'],
+ ['http://127.0.0.1:8080/hook', 'blocked'],
+ ['http://169.254.169.254/latest', 'blocked'],
+ ['http://[::127.0.0.1]/hook', 'blocked'],
+ ['http://[::ffff:0:127.0.0.1]/hook', 'blocked'],
+ ])('refuses %s', (address, code) => {
+ expect(() => checkWebhookUrl(address)).toThrow(expect.objectContaining({ code }));
+ });
+});
+
+describe('postJson', () => {
+ let server;
+ let port;
+ const received = [];
+ const routes = {
+ '/hook': (req, res, body) => {
+ received.push({ headers: req.headers, body });
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end('{"ok":true}');
+ },
+ '/teapot': (_req, res) => {
+ res.writeHead(418);
+ res.end('no');
+ },
+ '/moved': (_req, res) => {
+ res.writeHead(302, { location: 'http://localhost/admin' });
+ res.end();
+ },
+ '/long': (_req, res) => {
+ res.writeHead(200);
+ res.end('x'.repeat(MAX_ANSWER_BYTES * 3));
+ },
+ '/slow': (_req, res) => setTimeout(() => res.end('late'), 300),
+ };
+
+ beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ let body = '';
+ req.on('data', (chunk) => (body += chunk));
+ req.on('end', () => routes[req.url](req, res, body));
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ port = server.address().port;
+ });
+ afterAll(() => new Promise((resolve) => server.close(resolve)));
+
+ // site.test is the local server; any other name goes through the real check.
+ const lookup = (hostname, options, callback) => {
+ const done = typeof options === 'function' ? options : callback;
+ const all = typeof options === 'object' && options.all;
+ if (hostname !== 'site.test') return publicOnlyLookup(hostname, options, callback);
+ return all ? done(null, [{ address: '127.0.0.1', family: 4 }]) : done(null, '127.0.0.1', 4);
+ };
+ const post = (path, opts = {}) =>
+ postJson(`http://site.test:${port}${path}`, '{"event":"content_draft.sent"}', {
+ lookup,
+ ...opts,
+ });
+
+ it('posts the JSON with its headers, and answers the status and the answer', async () => {
+ await expect(post('/hook', { headers: { 'X-Webhook-Secret': 's3cret' } })).resolves.toEqual({
+ status: 200,
+ answer: '{"ok":true}',
+ });
+ const [last] = received.slice(-1);
+ expect(last.body).toBe('{"event":"content_draft.sent"}');
+ expect(last.headers['content-type']).toBe('application/json');
+ expect(last.headers['x-webhook-secret']).toBe('s3cret');
+ });
+
+ it('answers a non-2xx and a redirect as they are, following none', async () => {
+ await expect(post('/teapot')).resolves.toEqual({ status: 418, answer: 'no' });
+ await expect(post('/moved')).resolves.toMatchObject({ status: 302 });
+ });
+
+ it('reads back only the start of a long answer', async () => {
+ const { answer } = await post('/long');
+ expect(answer.length).toBe(MAX_ANSWER_BYTES);
+ });
+
+ it('gives up on a slow webhook', async () => {
+ await expect(post('/slow', { timeoutMs: 50 })).rejects.toMatchObject({ code: 'timeout' });
+ });
+
+ afterEach(() => vi.unstubAllEnvs());
+
+ it('never reaches a name that resolves to a private address on Cloud', async () => {
+ vi.stubEnv('IS_CLOUD', 'true');
+ const err = await postJson(`http://localhost:${port}/hook`, '{}').catch((e) => e);
+ expect(err).toBeInstanceOf(PageFetchError);
+ expect(err.code).toBe('blocked');
+ await expect(postJson(`http://127.0.0.1:${port}/hook`, '{}')).rejects.toMatchObject({
+ code: 'blocked',
+ });
+ });
+
+ it('reaches the workspace’s own network when self-hosted, as its other webhooks do', async () => {
+ vi.stubEnv('IS_CLOUD', 'false');
+ await expect(postJson(`http://127.0.0.1:${port}/hook`, '{}')).resolves.toMatchObject({
+ status: 200,
+ });
+ expect(() => checkWebhookUrl('ftp://n8n:21/x', { privateOk: true })).toThrow(
+ expect.objectContaining({ code: 'invalid_url' }),
+ );
+ });
+});
diff --git a/server/src/routes/content-drafts-send.test.js b/server/src/routes/content-drafts-send.test.js
new file mode 100644
index 000000000..76abdc96d
--- /dev/null
+++ b/server/src/routes/content-drafts-send.test.js
@@ -0,0 +1,134 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * POST /api/content-drafts/send (Send to CMS, #1331): admins and managers
+ * send pages of their brand; the reasons a send can't go keep their codes.
+ */
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const DRAFT = '77777777-7777-7777-7777-777777777777';
+
+let role;
+const assertBrandAccess = vi.fn();
+const sendContentPages = vi.fn();
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: () => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ single: async () => ({ data: { role }, error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));
+vi.mock('../lib/content-delivery.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ sendContentPages: (...args) => sendContentPages(...args),
+}));
+
+const { default: router } = await import('./content-drafts.js');
+const { DeliveryError } = await import('../lib/content-delivery.js');
+
+let server;
+let baseUrl;
+
+beforeEach(async () => {
+ role = 'manager';
+ assertBrandAccess.mockReset().mockResolvedValue({ orgId: 'o1' });
+ sendContentPages
+ .mockReset()
+ .mockResolvedValue({ batchId: null, skipped: 0, deliveries: [{ id: 'd1', status: 'sent' }] });
+ const app = express();
+ app.use(express.json({ limit: '5mb' }));
+ app.use((req, _res, next) => {
+ req.user = { id: 'u1' };
+ req.log = { error: vi.fn() };
+ next();
+ });
+ app.use('/api/content-drafts', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/api/content-drafts`;
+});
+
+afterEach(() => new Promise((resolve) => server.close(resolve)));
+
+const page = {
+ draftId: DRAFT,
+ title: 'Best AEO tools',
+ slug: 'best-aeo-tools',
+ html: '<p>Hi</p>',
+};
+const send = (body) =>
+ fetch(`${baseUrl}/send`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+describe('POST /api/content-drafts/send', () => {
+ it('sends the brand’s pages for a manager, with the defaults filled in', async () => {
+ const res = await send({ brandId: BRAND, pages: [page] });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ batchId: null,
+ skipped: 0,
+ deliveries: [{ id: 'd1', status: 'sent' }],
+ });
+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');
+ expect(sendContentPages).toHaveBeenCalledWith({
+ orgId: 'o1',
+ brandId: BRAND,
+ userId: 'u1',
+ pages: [{ ...page, metaTitle: '', metaDescription: '', author: null, featuredImage: null }],
+ });
+ });
+
+ it('leaves it to admins and managers', async () => {
+ role = 'analyst';
+ const res = await send({ brandId: BRAND, pages: [page] });
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: 'forbidden' });
+ expect(sendContentPages).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [{ brandId: BRAND, pages: [] }],
+ [{ brandId: BRAND, pages: Array.from({ length: 26 }, () => page) }],
+ [{ brandId: BRAND, pages: [{ ...page, slug: 'a/b' }] }],
+ [
+ {
+ brandId: BRAND,
+ pages: [{ ...page, featuredImage: { src: 'http://x.example/a.png', alt: '' } }],
+ },
+ ],
+ [{ brandId: 'nope', pages: [page] }],
+ ])('turns away a send it can’t take', async (body) => {
+ const res = await send(body);
+ expect(res.status).toBe(400);
+ expect(sendContentPages).not.toHaveBeenCalled();
+ });
+
+ it('answers why a send can’t go, with its code', async () => {
+ sendContentPages.mockRejectedValue(
+ new DeliveryError('webhook_not_subscribed', 'Not subscribed', 409),
+ );
+ let res = await send({ brandId: BRAND, pages: [page] });
+ expect(res.status).toBe(409);
+ expect(await res.json()).toEqual({ error: 'Not subscribed', code: 'webhook_not_subscribed' });
+
+ sendContentPages.mockRejectedValue(new DeliveryError('daily_limit', 'Try later', 429));
+ res = await send({ brandId: BRAND, pages: [page] });
+ expect(res.status).toBe(429);
+
+ sendContentPages.mockRejectedValue(new Error('db down'));
+ res = await send({ brandId: BRAND, pages: [page] });
+ expect(res.status).toBe(502);
+ expect(await res.json()).toMatchObject({ code: 'failed' });
+ });
+});
diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.js
index edae92e76..6f8658725 100644
--- a/server/src/routes/content-drafts.js
+++ b/server/src/routes/content-drafts.js
@@ -3,6 +3,7 @@ import { z } from 'zod';
import { assertBrandAccess } from '../lib/access.js';
import { fixDraftRules, fixRulesInput } from '../lib/content-agent.js';
import { rebuildDraftBrief, rebuildSources } from '../lib/content-brief.js';
+import { DeliveryError, sendContentPages, sendInput } from '../lib/content-delivery.js';
import { stopDraftRun } from '../lib/content-runs.js';
import { startDraftWriting, writeDraftInput } from '../lib/content-writer.js';
import supabaseAdmin from '../config/supabase.js';
@@ -12,8 +13,9 @@ import { PlanLimitError } from '../lib/plan-guard.js';
* Content Editor drafts: Rebuild outline in the editor's Brief tab writes
* the draft's brief from the sources the person kept (CE-007); Fix open
* rules with agent leaves the Content Agent's suggestions for review
- * (CE-018); Start's Agent has the Content Agent do the page (CE-015); and
- * Stop ends the agent's run under way, changing nothing (v1.1 CE-027).
+ * (CE-018); Start's Agent has the Content Agent do the page (CE-015);
+ * Stop ends the agent's run under way, changing nothing (v1.1 CE-027); and
+ * Send to CMS sends pages to the brand's webhook (#1331).
*/
const router = Router();
@@ -21,6 +23,55 @@ const router = Router();
/** The person-facing reason, by status, when the error names none. */
const ERROR_CODES = { 403: 'forbidden', 404: 'not_found', 409: 'conflict', 422: 'invalid' };
+/** Who may send pages to the brand's CMS (#1331): as who may change its webhook. */
+const SEND_ROLES = ['admin', 'manager'];
+
+async function assertSender(userId) {
+ const { data: profile } = await supabaseAdmin
+ .from('profiles')
+ .select('role')
+ .eq('id', userId)
+ .single();
+ if (!SEND_ROLES.includes(profile?.role)) {
+ const err = new Error('Only admins and managers can send pages to the CMS.');
+ err.status = 403;
+ throw err;
+ }
+}
+
+/**
+ * POST /api/content-drafts/send
+ * Body: { brandId, pages: [{ draftId, title, slug, metaTitle, metaDescription, html, author, featuredImage }] }
+ * One page is sent before this answers: { deliveries: [{ id, status, http_status, error }] };
+ * more (up to 25) go on in the background: { batchId, deliveries: queued, skipped }.
+ */
+router.post('/send', async (req, res) => {
+ const parsed = sendInput.safeParse(req.body ?? {});
+ if (!parsed.success) {
+ // Which page and field, so the dialog can say what to fix.
+ const field = parsed.error.issues[0]?.path.join('.') ?? null;
+ return res.status(400).json({ error: 'Invalid request', code: 'invalid', field });
+ }
+ const { brandId, pages } = parsed.data;
+ try {
+ const { orgId } = await assertBrandAccess(brandId, req.user.id);
+ await assertSender(req.user.id);
+ const sent = await sendContentPages({ orgId, brandId, userId: req.user.id, pages });
+ return res.json(sent);
+ } catch (err) {
+ if (err instanceof DeliveryError) {
+ return res.status(err.status).json({ error: err.message, code: err.code });
+ }
+ if (ERROR_CODES[err?.status]) {
+ return res
+ .status(err.status)
+ .json({ error: err.message, code: err.code ?? ERROR_CODES[err.status] });
+ }
+ req.log.error({ err }, 'content draft send error');
+ return res.status(502).json({ error: 'The pages could not be sent', code: 'failed' });
+ }
+});
+
const rebuildBody = z.object({
// guid, not uuid: brand ids aren't all RFC 4122 versions (seeded ones).
brandId: z.guid(),
diff --git a/server/src/routes/webhook-content-draft-callback.js b/server/src/routes/webhook-content-draft-callback.js
new file mode 100644
index 000000000..07e795243
--- /dev/null
+++ b/server/src/routes/webhook-content-draft-callback.js
@@ -0,0 +1,194 @@
+import { Router } from 'express';
+import { z } from 'zod';
+import supabaseAdmin from '../config/supabase.js';
+import { DELIVERY_EVENT } from '../lib/content-delivery.js';
+import {
+ webhookCallbackLimiter,
+ webhookCallbackAuthFailureLimiter,
+} from '../middleware/rate-limiter.js';
+import { webhookSecretsMatch } from '../lib/webhook-secret.js';
+
+/**
+ * Send to CMS's callback (#1331): the workspace's automation tells how a sent
+ * page went in the CMS: published at an address, or failed (Zapier and Make
+ * answer the send before their CMS step runs, so a post the CMS refused is
+ * told here). Public by design, as /webhooks/content is: the webhook's own
+ * secret (X-Webhook-Secret) authenticates it, the opportunity callback's
+ * limiters (each secret's budget, failed attempts by IP) cover it too. A
+ * delivery id with its webhook's secret proves the package arrived, so the
+ * callback counts whatever the delivery reads: an automation may call back
+ * before it answers the send, or after the send gave up waiting.
+ */
+
+const router = Router();
+
+router.use(webhookCallbackLimiter, webhookCallbackAuthFailureLimiter);
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const DENIED = { error: 'Invalid webhook credentials' };
+const MAX_URL = 2048;
+
+/** A field a workflow left unmapped (Zapier and Make send "" or null) reads as left out. */
+const mapped = (schema) =>
+ z.preprocess(
+ (value) => (value === null || (typeof value === 'string' && !value.trim()) ? undefined : value),
+ schema.optional(),
+ );
+
+const statusBody = z.object({
+ status: z.preprocess(
+ (value) => (typeof value === 'string' ? value.trim().toLowerCase() : value),
+ z.enum(['published', 'failed']),
+ ),
+ // Read as the browser would, then held to the column's length (00262).
+ url: mapped(
+ z
+ .string()
+ .trim()
+ .max(MAX_URL * 4),
+ ),
+ // The CMS's own id for the post, for the workflow's later updates: a
+ // number where the CMS counts its posts (WordPress, Ghost).
+ externalId: mapped(
+ z.union([z.string().trim().max(200), z.number().int().nonnegative().transform(String)]),
+ ),
+ // Why it failed, as the workflow says it.
+ reason: mapped(z.string().trim().max(500)),
+});
+
+/**
+ * An http(s) address as the browser reads it (no stray whitespace kept),
+ * without sign-in details (they'd be stored and shown as a link), or null.
+ */
+function liveAddress(value) {
+ try {
+ const url = new URL(value);
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
+ if (url.username || url.password) return null;
+ return url.href.length <= MAX_URL ? url.href : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * POST /webhooks/content-drafts/:deliveryId/status
+ * Body: { status: "published", url, externalId? } or { status: "failed", reason?, externalId? }.
+ * Published marks the delivery published at that address, and its page too
+ * when it is the page's latest delivery (an older one's late callback doesn't
+ * move the page's address back), keeping the page in History as a "publish"
+ * version unless History's latest version is already this page.
+ * Failed marks the delivery failed with the workflow's reason, unless it was
+ * already published.
+ */
+router.post('/:deliveryId/status', async (req, res) => {
+ try {
+ const { deliveryId } = req.params;
+ // A malformed id, an unknown delivery, no webhook and a wrong secret all
+ // answer the same, so this route doesn't tell which deliveries exist.
+ if (!UUID.test(deliveryId)) return res.status(401).json(DENIED);
+
+ const { data: delivery, error } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .select('id, brand_id, draft_id, status, published_url')
+ .eq('id', deliveryId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!delivery) return res.status(401).json(DENIED);
+
+ const { data: configs, error: configError } = await supabaseAdmin
+ .from('webhook_configs')
+ .select('webhook_secret, events')
+ .eq('brand_id', delivery.brand_id)
+ .eq('is_active', true);
+ if (configError) throw new Error(configError.message);
+ const provided = req.get('X-Webhook-Secret');
+ const matches = (configs ?? []).some(
+ (c) => c.events?.includes(DELIVERY_EVENT) && webhookSecretsMatch(c.webhook_secret, provided),
+ );
+ if (!matches) return res.status(401).json(DENIED);
+
+ const parsed = statusBody.safeParse(req.body ?? {});
+ const url = parsed.success && parsed.data.url ? liveAddress(parsed.data.url) : null;
+ if (!parsed.success || (parsed.data.status === 'published' && !url)) {
+ return res.status(400).json({
+ error:
+ 'Send { status: "published", url } with the http(s) address the page is live at (up to 2,048 characters, no sign-in details), or { status: "failed", reason? }.',
+ });
+ }
+ const { status, externalId, reason } = parsed.data;
+ const now = new Date().toISOString();
+ const own = externalId ? { external_id: externalId } : {};
+
+ if (status === 'failed') {
+ // A page the CMS already said is live stays so (a later step's failure),
+ // even when the two callbacks land together.
+ const { data: failed, error: failError } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .update({
+ status: 'failed',
+ error: reason ?? 'Your workflow said the page wasn’t published',
+ ...own,
+ })
+ .eq('id', delivery.id)
+ .neq('status', 'published')
+ .select('id');
+ if (failError) throw new Error(failError.message);
+ return res.json({ success: true, status: failed?.length ? 'failed' : 'published' });
+ }
+
+ // This delivery said so already (a workflow's retry): nothing changes,
+ // its time included, but a CMS id the retry adds. A new delivery of a
+ // page live at the same address (the post updated in place) is the page
+ // as published again.
+ if (delivery.status === 'published' && delivery.published_url === url) {
+ if (externalId) {
+ const { error: idError } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .update(own)
+ .eq('id', delivery.id);
+ if (idError) throw new Error(idError.message);
+ }
+ return res.json({ success: true, status: 'published' });
+ }
+ if (delivery.draft_id) {
+ const { data: latest, error: latestError } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .select('id')
+ .eq('draft_id', delivery.draft_id)
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (latestError) throw new Error(latestError.message);
+ if (latest?.id === delivery.id) {
+ const { error: draftError } = await supabaseAdmin
+ .from('content_drafts')
+ .update({ status: 'published', published_url: url, published_at: now })
+ .eq('id', delivery.draft_id);
+ if (draftError) throw new Error(draftError.message);
+ // The page as published, in History (00215 keeps "publish" for the
+ // server), unless History's latest version is already this page.
+ const { error: keepError } = await supabaseAdmin.rpc('content_draft_snapshot', {
+ p_draft_id: delivery.draft_id,
+ p_origin: 'publish',
+ });
+ if (keepError) {
+ req.log?.warn?.({ err: keepError }, 'content draft publish version not kept');
+ }
+ }
+ }
+ // The delivery last: a write above that fails answers 500, and the
+ // workflow's retry, finding it not yet published, does it all again.
+ const { error: deliveryError } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .update({ status: 'published', published_url: url, published_at: now, ...own })
+ .eq('id', delivery.id);
+ if (deliveryError) throw new Error(deliveryError.message);
+ return res.json({ success: true, status: 'published' });
+ } catch (error) {
+ req.log?.error?.({ err: error }, 'content draft status callback error');
+ return res.status(500).json({ error: 'Failed to record the page’s status' });
+ }
+});
+
+export default router;
diff --git a/server/src/routes/webhook-content-draft-callback.test.js b/server/src/routes/webhook-content-draft-callback.test.js
new file mode 100644
index 000000000..64aaa08dc
--- /dev/null
+++ b/server/src/routes/webhook-content-draft-callback.test.js
@@ -0,0 +1,291 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * Send to CMS's callback (#1331): the workspace's automation tells how a sent
+ * page went in the CMS (live at an address, or failed), with its webhook's
+ * secret.
+ */
+
+const { state } = vi.hoisted(() => ({
+ state: { deliveries: [], configs: [], drafts: [], rpcs: [] },
+}));
+
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ rpc: async (name, args) => (state.rpcs.push({ name, args }), { data: 'v1', error: null }),
+ from: (name) => {
+ const rows =
+ name === 'content_draft_deliveries'
+ ? state.deliveries
+ : name === 'content_drafts'
+ ? state.drafts
+ : state.configs;
+ const q = { filters: [], update: null, order: null };
+ const matched = () => {
+ const found = rows.filter((row) => q.filters.every((f) => f(row)));
+ if (q.order) found.sort((a, b) => (a[q.order] < b[q.order] ? 1 : -1));
+ return found;
+ };
+ const run = (single) => {
+ // A draft write that fails once (state.failDraft).
+ if (q.update && name === 'content_drafts' && state.failDraft) {
+ state.failDraft = false;
+ return { data: null, error: { message: 'down' } };
+ }
+ const found = matched();
+ if (q.update) for (const row of found) Object.assign(row, q.update);
+ return { data: single ? (found[0] ?? null) : found, error: null };
+ };
+ const chain = {
+ select: () => chain,
+ eq: (column, value) => (q.filters.push((row) => row[column] === value), chain),
+ neq: (column, value) => (q.filters.push((row) => row[column] !== value), chain),
+ update: (row) => ((q.update = row), chain),
+ order: (column) => ((q.order = column), chain),
+ limit: () => chain,
+ maybeSingle: async () => run(true),
+ then: (resolve, reject) => Promise.resolve(run(false)).then(resolve, reject),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('../middleware/rate-limiter.js', () => ({
+ webhookCallbackLimiter: (_req, _res, next) => next(),
+ webhookCallbackAuthFailureLimiter: (_req, _res, next) => next(),
+}));
+
+const { default: router } = await import('./webhook-content-draft-callback.js');
+
+const DELIVERY = '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29';
+let server;
+let baseUrl;
+
+beforeEach(async () => {
+ state.deliveries = [
+ {
+ id: DELIVERY,
+ brand_id: 'b1',
+ draft_id: 'd1',
+ status: 'sent',
+ created_at: '2026-10-24T10:00:00Z',
+ },
+ ];
+ state.drafts = [{ id: 'd1', status: 'ready', published_url: null }];
+ state.rpcs = [];
+ state.configs = [
+ {
+ brand_id: 'b1',
+ is_active: true,
+ webhook_secret: 's3cret',
+ events: ['content_draft.sent'],
+ },
+ ];
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.log = { error: vi.fn(), warn: vi.fn() };
+ next();
+ });
+ app.use('/webhooks/content-drafts', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/webhooks/content-drafts`;
+});
+
+afterEach(() => new Promise((resolve) => server.close(resolve)));
+
+const call = (body, { id = DELIVERY, secret = 's3cret' } = {}) =>
+ fetch(`${baseUrl}/${id}/status`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(secret ? { 'X-Webhook-Secret': secret } : {}),
+ },
+ body: JSON.stringify(body),
+ });
+
+const published = (url, more = {}) => call({ status: 'published', url, ...more });
+
+describe('POST /webhooks/content-drafts/:deliveryId/status', () => {
+ it('marks the delivery and its page published at the address, keeping a publish version', async () => {
+ const res = await published('https://acme.example/blog/best-aeo-tools', { externalId: '812' });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ success: true, status: 'published' });
+ expect(state.deliveries[0]).toMatchObject({
+ status: 'published',
+ published_url: 'https://acme.example/blog/best-aeo-tools',
+ published_at: expect.any(String),
+ external_id: '812',
+ });
+ expect(state.drafts[0]).toMatchObject({
+ status: 'published',
+ published_url: 'https://acme.example/blog/best-aeo-tools',
+ });
+ expect(state.rpcs).toEqual([
+ { name: 'content_draft_snapshot', args: { p_draft_id: 'd1', p_origin: 'publish' } },
+ ]);
+ });
+
+ it('keeps no second version, nor a new time, when the workflow says it again', async () => {
+ await published('https://acme.example/live');
+ const at = state.deliveries[0].published_at;
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ await published('https://acme.example/live');
+ expect(state.rpcs).toHaveLength(1);
+ expect(state.deliveries[0].published_at).toBe(at);
+ });
+
+ it('keeps the page as published again when a new send goes live at the same address', async () => {
+ // Published once; the page changed and was sent again, the post updated in place.
+ state.deliveries[0] = {
+ ...state.deliveries[0],
+ status: 'published',
+ published_url: 'https://acme.example/live',
+ };
+ state.drafts[0] = { id: 'd1', status: 'published', published_url: 'https://acme.example/live' };
+ const NEWER = '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a30';
+ state.deliveries.push({
+ id: NEWER,
+ brand_id: 'b1',
+ draft_id: 'd1',
+ status: 'sent',
+ created_at: '2026-10-24T12:00:00Z',
+ });
+ const res = await call(
+ { status: 'published', url: 'https://acme.example/live' },
+ { id: NEWER },
+ );
+ expect(res.status).toBe(200);
+ expect(state.rpcs).toEqual([
+ { name: 'content_draft_snapshot', args: { p_draft_id: 'd1', p_origin: 'publish' } },
+ ]);
+ expect(state.drafts[0].published_at).toEqual(expect.any(String));
+ });
+
+ it('marks the delivery failed with the workflow’s reason, the page left as it is', async () => {
+ const res = await call({ status: 'failed', reason: 'Slug already taken', externalId: '812' });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ success: true, status: 'failed' });
+ expect(state.deliveries[0]).toMatchObject({
+ status: 'failed',
+ error: 'Slug already taken',
+ external_id: '812',
+ });
+ expect(state.drafts[0]).toMatchObject({ status: 'ready', published_url: null });
+ expect(state.rpcs).toEqual([]);
+
+ await call({ status: 'failed' });
+ expect(state.deliveries[0].error).toBe('Your workflow said the page wasn’t published');
+ });
+
+ it('keeps a published page published when a failure comes after', async () => {
+ await published('https://acme.example/live');
+ const res = await call({ status: 'failed', reason: 'Later step' });
+ expect(await res.json()).toEqual({ success: true, status: 'published' });
+ expect(state.deliveries[0]).toMatchObject({
+ status: 'published',
+ published_url: 'https://acme.example/live',
+ });
+ });
+
+ it('answers the same for a wrong secret, an unknown or malformed delivery, and a webhook not taking the event', async () => {
+ const denied = { error: 'Invalid webhook credentials' };
+ for (const res of [
+ await call({ status: 'published', url: 'https://a.example/x' }, { secret: 'wrong' }),
+ await call({ status: 'published', url: 'https://a.example/x' }, { secret: null }),
+ await call(
+ { status: 'published', url: 'https://a.example/x' },
+ { id: '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a30' },
+ ),
+ await call({ status: 'published', url: 'https://a.example/x' }, { id: 'not-an-id' }),
+ ]) {
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual(denied);
+ }
+ state.configs[0].events = ['opportunity.sent'];
+ const res = await published('https://a.example/x');
+ expect(res.status).toBe(401);
+ expect(state.deliveries[0].status).toBe('sent');
+ });
+
+ it('reads what a workflow left unmapped as left out, and a CMS’s number as its id', async () => {
+ const res = await call({
+ status: ' Published ',
+ url: 'https://acme.example/live',
+ externalId: 812,
+ reason: '',
+ });
+ expect(res.status).toBe(200);
+ expect(state.deliveries[0]).toMatchObject({ status: 'published', external_id: '812' });
+
+ state.deliveries[0].status = 'sent';
+ await call({ status: 'failed', url: null, externalId: ' ', reason: null });
+ expect(state.deliveries[0]).toMatchObject({
+ status: 'failed',
+ error: 'Your workflow said the page wasn’t published',
+ external_id: '812',
+ });
+ expect((await call({ status: 'failed', externalId: 1.5 })).status).toBe(400);
+ });
+
+ it('takes only an http(s) address up to 2,048 characters, as the browser reads it', async () => {
+ expect((await published('javascript:alert(1)')).status).toBe(400);
+ // Sign-in details would be kept and shown as a link.
+ expect((await published('https://admin:[email protected]/live')).status).toBe(400);
+ expect((await call({ status: 'published' })).status).toBe(400);
+ expect((await call({ url: 'https://acme.example/x' })).status).toBe(400);
+ expect((await call({ status: 'live', url: 'https://acme.example/x' })).status).toBe(400);
+ // Under the limit as sent, past it once the browser escapes the spaces.
+ const spaced = `https://acme.example/${' x'.repeat(1000)}`;
+ expect(spaced.length).toBeLessThan(2048);
+ expect((await published(spaced)).status).toBe(400);
+ expect(state.deliveries[0].status).toBe('sent');
+ expect((await published('https://acme.example/a\nb')).status).toBe(200);
+ expect(state.deliveries[0].published_url).toBe('https://acme.example/ab');
+ });
+
+ it('counts a callback that lands before the send’s answer, or after it gave up', async () => {
+ for (const status of ['queued', 'failed']) {
+ state.deliveries[0].status = status;
+ const res = await published('https://acme.example/live');
+ expect(res.status).toBe(200);
+ expect(state.deliveries[0].status).toBe('published');
+ }
+ });
+
+ it('does it all again on the retry of a callback whose page write failed', async () => {
+ state.failDraft = true;
+ expect((await published('https://acme.example/live')).status).toBe(500);
+ expect(state.deliveries[0].status).toBe('sent');
+ expect((await published('https://acme.example/live')).status).toBe(200);
+ expect(state.drafts[0]).toMatchObject({ status: 'published' });
+ expect(state.deliveries[0]).toMatchObject({ status: 'published' });
+ expect(state.rpcs).toHaveLength(1);
+ });
+
+ it('keeps a CMS id a retry adds, and nothing else', async () => {
+ await published('https://acme.example/live');
+ const at = state.deliveries[0].published_at;
+ await published('https://acme.example/live', { externalId: '812' });
+ expect(state.deliveries[0]).toMatchObject({ external_id: '812', published_at: at });
+ expect(state.rpcs).toHaveLength(1);
+ });
+
+ it('moves the page’s address only for its latest delivery', async () => {
+ state.deliveries.push({
+ id: 'newer',
+ brand_id: 'b1',
+ draft_id: 'd1',
+ status: 'sent',
+ created_at: '2026-10-24T11:00:00Z',
+ });
+ const res = await published('https://acme.example/old');
+ expect(res.status).toBe(200);
+ expect(state.deliveries[0].published_url).toBe('https://acme.example/old');
+ expect(state.drafts[0]).toMatchObject({ status: 'ready', published_url: null });
+ expect(state.rpcs).toEqual([]);
+ });
+});
diff --git a/server/src/server.js b/server/src/server.js
index 0240aeedc..141078a72 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -32,6 +32,7 @@ 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 webhookContentDraftCallbackRoutes from './routes/webhook-content-draft-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';
@@ -716,6 +717,7 @@ 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);
+app.use('/webhooks/content-drafts', webhookContentDraftCallbackRoutes);
// --- Authenticated API routes ---
app.use('/api', Middleware.decodeToken.bind(Middleware), routes);
diff --git a/supabase/migrations/00262_content_draft_deliveries.sql b/supabase/migrations/00262_content_draft_deliveries.sql
new file mode 100644
index 000000000..ec701db9e
--- /dev/null
+++ b/supabase/migrations/00262_content_draft_deliveries.sql
@@ -0,0 +1,245 @@
+-- ============================================================================
+-- 00262: Send to CMS, phase 1 (webhook) — #1331
+-- ============================================================================
+-- An admin or manager sends a Content Editor page to the brand's webhook as a
+-- content package (its publishable HTML, title, slug, meta and page fields);
+-- the workspace's own automation (Zapier, Make, n8n, its CMS) takes it from
+-- there and may call back with how it went: the address it published at (and
+-- the CMS's id for the post), or that it failed.
+--
+-- content_drafts gets the page's slug and meta, filled from the page and
+-- editable in the Send dialog, and where it went live. A send is a row of
+-- content_draft_deliveries: queued when reserved, then sent or failed, and
+-- published once the callback names the live address. A table of its own,
+-- not columns on content_drafts: a page is sent many times, and each send's
+-- answer is kept (the draft gets only its slug, meta and live address).
+-- A callback that says it failed marks the delivery failed.
+
+alter table public.content_drafts
+ add column if not exists slug text
+ check (slug is null or (char_length(slug) between 1 and 200 and slug !~ '[/\s]')),
+ add column if not exists meta_title text
+ check (meta_title is null or char_length(meta_title) <= 300),
+ add column if not exists meta_description text
+ check (meta_description is null or char_length(meta_description) <= 500),
+ add column if not exists published_url text
+ check (
+ published_url is null
+ or (char_length(published_url) <= 2048 and published_url ~* '^https?://')
+ ),
+ add column if not exists published_at timestamptz;
+
+comment on column public.content_drafts.slug is
+ 'The page''s URL slug for its CMS (Send to CMS, 00262): filled from the page, editable in the Send dialog.';
+comment on column public.content_drafts.published_url is
+ 'Where the page went live: what the CMS called back with after a Send to CMS (00262).';
+
+create table if not exists public.content_draft_deliveries (
+ id uuid primary key default gen_random_uuid(),
+ organization_id uuid not null references public.organizations(id) on delete cascade,
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ -- Kept when the draft goes (its title stays below), as the day's count does.
+ draft_id uuid references public.content_drafts(id) on delete set null,
+ sent_by uuid references public.profiles(id) on delete set null,
+ -- A bulk send's deliveries share one, so the Library can follow them.
+ batch_id uuid,
+ status text not null default 'queued'
+ check (status in ('queued', 'sent', 'failed', 'published')),
+ title text not null check (char_length(title) between 1 and 300),
+ slug text check (slug is null or char_length(slug) <= 200),
+ -- What the webhook answered: its HTTP status and the start of its body.
+ http_status smallint,
+ response_excerpt text check (response_excerpt is null or char_length(response_excerpt) <= 2000),
+ error text check (error is null or char_length(error) <= 500),
+ published_url text check (
+ published_url is null
+ or (char_length(published_url) <= 2048 and published_url ~* '^https?://')
+ ),
+ -- The CMS's own id for the post, when the callback names it.
+ external_id text check (external_id is null or char_length(external_id) between 1 and 200),
+ created_at timestamptz not null default now(),
+ sent_at timestamptz,
+ published_at timestamptz
+);
+
+create index if not exists content_draft_deliveries_org_created
+ on public.content_draft_deliveries (organization_id, created_at desc);
+create index if not exists content_draft_deliveries_draft_created
+ on public.content_draft_deliveries (draft_id, created_at desc);
+create index if not exists content_draft_deliveries_batch
+ on public.content_draft_deliveries (batch_id) where batch_id is not null;
+-- The next send closes a workspace's sends left queued (below): only those rows.
+create index if not exists content_draft_deliveries_queued
+ on public.content_draft_deliveries (organization_id) where status = 'queued';
+
+alter table public.content_draft_deliveries enable row level security;
+revoke all on table public.content_draft_deliveries from anon, authenticated;
+grant select on table public.content_draft_deliveries to authenticated;
+grant all on table public.content_draft_deliveries to service_role;
+
+-- Members read their workspace's deliveries; the server writes them.
+drop policy if exists "content_draft_deliveries: member select" on public.content_draft_deliveries;
+create policy "content_draft_deliveries: member select"
+ on public.content_draft_deliveries
+ for select
+ using (organization_id in (select p.organization_id from public.profiles p where p.id = auth.uid()));
+
+comment on table public.content_draft_deliveries is
+ 'Send to CMS (#1331, 00262): each page sent to the brand''s webhook, as queued, sent, failed or published. Written by the server; read by the editor and the Library.';
+
+-- Each page's last send, one row a page, for the Library's marks: a read of
+-- the table itself stops at PostgREST's 1,000 rows, which a workspace that
+-- re-sends often passes. Read through the member's policy: only their
+-- workspace's sends answer.
+create or replace function public.content_draft_last_deliveries(p_draft_ids uuid[])
+returns setof public.content_draft_deliveries
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ select distinct on (d.draft_id) d.*
+ from public.content_draft_deliveries d
+ where d.draft_id = any (p_draft_ids[1:500])
+ order by d.draft_id, d.created_at desc;
+$$;
+
+revoke execute on function public.content_draft_last_deliveries(uuid[]) from public, anon;
+grant execute on function public.content_draft_last_deliveries(uuid[]) to authenticated, service_role;
+
+-- ----------------------------------------------------------------------------
+-- The day's cap: reserve_content_deliveries queues as many of the pages as the
+-- workspace's last 24 hours leave room for (p_limit, 200), under a lock per
+-- organization so sends at once can't pass it together (as 00243). It returns
+-- the queued rows; pages past the cap get none.
+-- p_items: [{ "draft_id", "title", "slug" }], in the order they go.
+-- A row still queued after 30 minutes was left by a server that stopped
+-- mid-batch: the next send closes it as interrupted (as 00249 closes runs),
+-- so the Library tells it from one still going. It still counts for the day.
+-- ----------------------------------------------------------------------------
+create or replace function public.reserve_content_deliveries(
+ p_organization_id uuid,
+ p_brand_id uuid,
+ p_sent_by uuid,
+ p_batch_id uuid,
+ p_items jsonb,
+ p_limit integer
+)
+returns setof public.content_draft_deliveries
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ used integer;
+ room integer;
+begin
+ perform pg_advisory_xact_lock(hashtext('content_deliveries:' || p_organization_id::text));
+
+ -- sent_at stays empty: it was never sent, and its time stays its own.
+ update public.content_draft_deliveries
+ set status = 'failed', error = 'Not sent: interrupted'
+ where organization_id = p_organization_id
+ and status = 'queued'
+ and created_at < now() - interval '30 minutes';
+
+ select count(*) into used
+ from public.content_draft_deliveries
+ where organization_id = p_organization_id
+ and created_at > now() - interval '24 hours';
+
+ room := greatest(0, p_limit - used);
+ if room = 0 or jsonb_typeof(p_items) <> 'array' then
+ return;
+ end if;
+
+ return query
+ insert into public.content_draft_deliveries
+ (organization_id, brand_id, draft_id, sent_by, batch_id, title, slug)
+ select p_organization_id, p_brand_id, (item ->> 'draft_id')::uuid, p_sent_by, p_batch_id,
+ left(item ->> 'title', 300), nullif(left(item ->> 'slug', 200), '')
+ from jsonb_array_elements(p_items) with ordinality as items(item, position)
+ order by position
+ limit room
+ returning *;
+end;
+$$;
+
+revoke all on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer)
+ from public, anon, authenticated;
+grant execute on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer)
+ to service_role;
+
+-- ----------------------------------------------------------------------------
+-- Where the page went live is the server's: the callback writes it, with the
+-- service role. guard_content_draft_server_columns (00247) refuses a member's
+-- write of it, as of the other columns the server keeps; slug and meta stay
+-- the members' to edit.
+-- ----------------------------------------------------------------------------
+create or replace function public.guard_content_draft_server_columns()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ -- A role that bypasses RLS is server-side (service role, migrations).
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then
+ return new;
+ end if;
+
+ if tg_op = 'INSERT' then
+ if new.score_before is not null or new.score_after is not null then
+ raise exception 'content draft scores are set server-side'
+ using errcode = '42501';
+ end if;
+ if new.action_id is not null then
+ raise exception 'content draft action is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.agent_state is not null or new.agent_state_at is not null
+ or new.agent_run is not null then
+ raise exception 'content draft agent state is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.published_url is not null or new.published_at is not null then
+ raise exception 'content draft live address is set server-side'
+ using errcode = '42501';
+ end if;
+ elsif new.brand_id is distinct from old.brand_id
+ or new.author is distinct from old.author
+ or new.created_by is distinct from old.created_by
+ or new.created_at is distinct from old.created_at
+ or new.score_before is distinct from old.score_before
+ or new.score_after is distinct from old.score_after
+ or new.action_id is distinct from old.action_id
+ or new.agent_state is distinct from old.agent_state
+ or new.agent_state_at is distinct from old.agent_state_at
+ or new.agent_run is distinct from old.agent_run
+ or new.published_url is distinct from old.published_url
+ or new.published_at is distinct from old.published_at
+ then
+ raise exception 'content draft column is managed server-side'
+ using errcode = '42501';
+ end if;
+ return new;
+end;
+$$;
+
+-- ----------------------------------------------------------------------------
+-- Webhooks: a page sent is an event a webhook subscribes to (00198's list).
+-- ----------------------------------------------------------------------------
+alter table public.webhook_configs
+ drop constraint if exists webhook_configs_events_allowed;
+
+alter table public.webhook_configs
+ add constraint webhook_configs_events_allowed
+ check (
+ events <@ array[
+ 'opportunity.sent', 'daily_pulse.created', 'action_task.sent', 'content_draft.sent'
+ ]::text[]
+ );
+
+comment on column public.webhook_configs.events is
+ 'Event types subscribed to by this webhook (opportunity.sent, daily_pulse.created, action_task.sent, content_draft.sent). webhook.test is always sent by the test action and is not stored here.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index b7bd9eb24..01cd0fd73 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -38055,3 +38055,252 @@ alter table public.brands
comment on column public.brands.content_byline is
'Content Editor Quality (CE-057): add one byline line under the H1 in exports, for a CMS with no author field. Off by default.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00262_content_draft_deliveries.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00262: Send to CMS, phase 1 (webhook) — #1331
+-- ============================================================================
+-- An admin or manager sends a Content Editor page to the brand's webhook as a
+-- content package (its publishable HTML, title, slug, meta and page fields);
+-- the workspace's own automation (Zapier, Make, n8n, its CMS) takes it from
+-- there and may call back with how it went: the address it published at (and
+-- the CMS's id for the post), or that it failed.
+--
+-- content_drafts gets the page's slug and meta, filled from the page and
+-- editable in the Send dialog, and where it went live. A send is a row of
+-- content_draft_deliveries: queued when reserved, then sent or failed, and
+-- published once the callback names the live address. A table of its own,
+-- not columns on content_drafts: a page is sent many times, and each send's
+-- answer is kept (the draft gets only its slug, meta and live address).
+-- A callback that says it failed marks the delivery failed.
+
+alter table public.content_drafts
+ add column if not exists slug text
+ check (slug is null or (char_length(slug) between 1 and 200 and slug !~ '[/\s]')),
+ add column if not exists meta_title text
+ check (meta_title is null or char_length(meta_title) <= 300),
+ add column if not exists meta_description text
+ check (meta_description is null or char_length(meta_description) <= 500),
+ add column if not exists published_url text
+ check (
+ published_url is null
+ or (char_length(published_url) <= 2048 and published_url ~* '^https?://')
+ ),
+ add column if not exists published_at timestamptz;
+
+comment on column public.content_drafts.slug is
+ 'The page''s URL slug for its CMS (Send to CMS, 00262): filled from the page, editable in the Send dialog.';
+comment on column public.content_drafts.published_url is
+ 'Where the page went live: what the CMS called back with after a Send to CMS (00262).';
+
+create table if not exists public.content_draft_deliveries (
+ id uuid primary key default gen_random_uuid(),
+ organization_id uuid not null references public.organizations(id) on delete cascade,
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ -- Kept when the draft goes (its title stays below), as the day's count does.
+ draft_id uuid references public.content_drafts(id) on delete set null,
+ sent_by uuid references public.profiles(id) on delete set null,
+ -- A bulk send's deliveries share one, so the Library can follow them.
+ batch_id uuid,
+ status text not null default 'queued'
+ check (status in ('queued', 'sent', 'failed', 'published')),
+ title text not null check (char_length(title) between 1 and 300),
+ slug text check (slug is null or char_length(slug) <= 200),
+ -- What the webhook answered: its HTTP status and the start of its body.
+ http_status smallint,
+ response_excerpt text check (response_excerpt is null or char_length(response_excerpt) <= 2000),
+ error text check (error is null or char_length(error) <= 500),
+ published_url text check (
+ published_url is null
+ or (char_length(published_url) <= 2048 and published_url ~* '^https?://')
+ ),
+ -- The CMS's own id for the post, when the callback names it.
+ external_id text check (external_id is null or char_length(external_id) between 1 and 200),
+ created_at timestamptz not null default now(),
+ sent_at timestamptz,
+ published_at timestamptz
+);
+
+create index if not exists content_draft_deliveries_org_created
+ on public.content_draft_deliveries (organization_id, created_at desc);
+create index if not exists content_draft_deliveries_draft_created
+ on public.content_draft_deliveries (draft_id, created_at desc);
+create index if not exists content_draft_deliveries_batch
+ on public.content_draft_deliveries (batch_id) where batch_id is not null;
+-- The next send closes a workspace's sends left queued (below): only those rows.
+create index if not exists content_draft_deliveries_queued
+ on public.content_draft_deliveries (organization_id) where status = 'queued';
+
+alter table public.content_draft_deliveries enable row level security;
+revoke all on table public.content_draft_deliveries from anon, authenticated;
+grant select on table public.content_draft_deliveries to authenticated;
+grant all on table public.content_draft_deliveries to service_role;
+
+-- Members read their workspace's deliveries; the server writes them.
+drop policy if exists "content_draft_deliveries: member select" on public.content_draft_deliveries;
+create policy "content_draft_deliveries: member select"
+ on public.content_draft_deliveries
+ for select
+ using (organization_id in (select p.organization_id from public.profiles p where p.id = auth.uid()));
+
+comment on table public.content_draft_deliveries is
+ 'Send to CMS (#1331, 00262): each page sent to the brand''s webhook, as queued, sent, failed or published. Written by the server; read by the editor and the Library.';
+
+-- Each page's last send, one row a page, for the Library's marks: a read of
+-- the table itself stops at PostgREST's 1,000 rows, which a workspace that
+-- re-sends often passes. Read through the member's policy: only their
+-- workspace's sends answer.
+create or replace function public.content_draft_last_deliveries(p_draft_ids uuid[])
+returns setof public.content_draft_deliveries
+language sql
+stable
+security invoker
+set search_path = public
+as $$
+ select distinct on (d.draft_id) d.*
+ from public.content_draft_deliveries d
+ where d.draft_id = any (p_draft_ids[1:500])
+ order by d.draft_id, d.created_at desc;
+$$;
+
+revoke execute on function public.content_draft_last_deliveries(uuid[]) from public, anon;
+grant execute on function public.content_draft_last_deliveries(uuid[]) to authenticated, service_role;
+
+-- ----------------------------------------------------------------------------
+-- The day's cap: reserve_content_deliveries queues as many of the pages as the
+-- workspace's last 24 hours leave room for (p_limit, 200), under a lock per
+-- organization so sends at once can't pass it together (as 00243). It returns
+-- the queued rows; pages past the cap get none.
+-- p_items: [{ "draft_id", "title", "slug" }], in the order they go.
+-- A row still queued after 30 minutes was left by a server that stopped
+-- mid-batch: the next send closes it as interrupted (as 00249 closes runs),
+-- so the Library tells it from one still going. It still counts for the day.
+-- ----------------------------------------------------------------------------
+create or replace function public.reserve_content_deliveries(
+ p_organization_id uuid,
+ p_brand_id uuid,
+ p_sent_by uuid,
+ p_batch_id uuid,
+ p_items jsonb,
+ p_limit integer
+)
+returns setof public.content_draft_deliveries
+language plpgsql
+security definer
+set search_path = public
+as $$
+declare
+ used integer;
+ room integer;
+begin
+ perform pg_advisory_xact_lock(hashtext('content_deliveries:' || p_organization_id::text));
+
+ -- sent_at stays empty: it was never sent, and its time stays its own.
+ update public.content_draft_deliveries
+ set status = 'failed', error = 'Not sent: interrupted'
+ where organization_id = p_organization_id
+ and status = 'queued'
+ and created_at < now() - interval '30 minutes';
+
+ select count(*) into used
+ from public.content_draft_deliveries
+ where organization_id = p_organization_id
+ and created_at > now() - interval '24 hours';
+
+ room := greatest(0, p_limit - used);
+ if room = 0 or jsonb_typeof(p_items) <> 'array' then
+ return;
+ end if;
+
+ return query
+ insert into public.content_draft_deliveries
+ (organization_id, brand_id, draft_id, sent_by, batch_id, title, slug)
+ select p_organization_id, p_brand_id, (item ->> 'draft_id')::uuid, p_sent_by, p_batch_id,
+ left(item ->> 'title', 300), nullif(left(item ->> 'slug', 200), '')
+ from jsonb_array_elements(p_items) with ordinality as items(item, position)
+ order by position
+ limit room
+ returning *;
+end;
+$$;
+
+revoke all on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer)
+ from public, anon, authenticated;
+grant execute on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer)
+ to service_role;
+
+-- ----------------------------------------------------------------------------
+-- Where the page went live is the server's: the callback writes it, with the
+-- service role. guard_content_draft_server_columns (00247) refuses a member's
+-- write of it, as of the other columns the server keeps; slug and meta stay
+-- the members' to edit.
+-- ----------------------------------------------------------------------------
+create or replace function public.guard_content_draft_server_columns()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ -- A role that bypasses RLS is server-side (service role, migrations).
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then
+ return new;
+ end if;
+
+ if tg_op = 'INSERT' then
+ if new.score_before is not null or new.score_after is not null then
+ raise exception 'content draft scores are set server-side'
+ using errcode = '42501';
+ end if;
+ if new.action_id is not null then
+ raise exception 'content draft action is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.agent_state is not null or new.agent_state_at is not null
+ or new.agent_run is not null then
+ raise exception 'content draft agent state is set server-side'
+ using errcode = '42501';
+ end if;
+ if new.published_url is not null or new.published_at is not null then
+ raise exception 'content draft live address is set server-side'
+ using errcode = '42501';
+ end if;
+ elsif new.brand_id is distinct from old.brand_id
+ or new.author is distinct from old.author
+ or new.created_by is distinct from old.created_by
+ or new.created_at is distinct from old.created_at
+ or new.score_before is distinct from old.score_before
+ or new.score_after is distinct from old.score_after
+ or new.action_id is distinct from old.action_id
+ or new.agent_state is distinct from old.agent_state
+ or new.agent_state_at is distinct from old.agent_state_at
+ or new.agent_run is distinct from old.agent_run
+ or new.published_url is distinct from old.published_url
+ or new.published_at is distinct from old.published_at
+ then
+ raise exception 'content draft column is managed server-side'
+ using errcode = '42501';
+ end if;
+ return new;
+end;
+$$;
+
+-- ----------------------------------------------------------------------------
+-- Webhooks: a page sent is an event a webhook subscribes to (00198's list).
+-- ----------------------------------------------------------------------------
+alter table public.webhook_configs
+ drop constraint if exists webhook_configs_events_allowed;
+
+alter table public.webhook_configs
+ add constraint webhook_configs_events_allowed
+ check (
+ events <@ array[
+ 'opportunity.sent', 'daily_pulse.created', 'action_task.sent', 'content_draft.sent'
+ ]::text[]
+ );
+
+comment on column public.webhook_configs.events is
+ 'Event types subscribed to by this webhook (opportunity.sent, daily_pulse.created, action_task.sent, content_draft.sent). webhook.test is always sent by the test action and is not stored here.';
+
+notify pgrst, 'reload schema';
+