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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(cms): connect a brand's WordPress site with an Application Password and send pages to it as draft posts (#1331) (#1569)
Cihan85c42033de78
diff --git a/server/.env.example b/server/.env.exampleindex 2bdba5eb4..40431759f 100644--- a/server/.env.example+++ b/server/.env.example@@ -207,12 +207,13 @@ AI_VOLUME_MULTIPLIER=0.45# (registerGcp). Without it, Merchant Center shows "not configured".# COMPOSIO_GMC_AUTH_CONFIG_ID=-# Store connections for the product catalog (#1263, CONNECTORS.md): the key-# a store's sign-in is encrypted with, 32 bytes in base64+# Store connections for the product catalog (#1263, CONNECTORS.md), and+# Send to CMS's WordPress connection (#1331): the key a store's or a+# WordPress site's sign-in is encrypted with, 32 bytes in base64# (openssl rand -base64 32). Only this server holds it; the web app never-# sees a store's sign-in. Optional: without it, Settings says store-# connections aren't set up, and feeds and uploads work as before. Changing-# it makes the saved sign-ins unreadable until they're entered again.+# sees a sign-in. Optional: without it, Settings says store connections and+# WordPress aren't set up, and feeds, uploads and the webhook work as before.+# Changing it makes the saved sign-ins unreadable until they're entered again.# CONNECTOR_CREDENTIALS_KEY=# How long a run waits for Cloro's FIRST result before giving up (default 90diff --git a/server/src/lib/cms/credentials.js b/server/src/lib/cms/credentials.jsnew file mode 100644index 000000000..7871547f4--- /dev/null+++ b/server/src/lib/cms/credentials.js@@ -0,0 +1,42 @@+import supabaseAdmin from '../../config/supabase.js';+import { openCredentials, sealCredentials } from '../catalog/credentials.js';++/**+ * A CMS connection's sign-in (Send to CMS #1331, 00294): WordPress's user+ * and Application Password. Kept in `brand_cms_credentials`, which only the+ * service role reads, sealed as a store's sign-in is (lib/catalog/credentials.js:+ * AES-256-GCM under CONNECTOR_CREDENTIALS_KEY). The envelope is bound to+ * `cms:<connection id>`, so it opens on its own connection only, never on+ * another's row nor as a store source's.+ *+ * Credentials never go in a log, an error message or a response.+ */++const bound = (connectionId) => `cms:${connectionId}`;++/** Keeps (or replaces) a connection's credentials. */+export async function saveCmsCredentials(+ connectionId,+ credentials,+ { setBy = null, db = supabaseAdmin } = {},+) {+ const secret = sealCredentials(bound(connectionId), credentials);+ const { error } = await db+ .from('brand_cms_credentials')+ .upsert(+ { connection_id: connectionId, secret, set_at: new Date().toISOString(), set_by: setBy },+ { onConflict: 'connection_id' },+ );+ if (error) throw new Error(`brand_cms_credentials write: ${error.code ?? 'error'}`);+}++/** A connection's credentials, or null when it has none it can open. */+export async function readCmsCredentials(connectionId, { db = supabaseAdmin } = {}) {+ const { data, error } = await db+ .from('brand_cms_credentials')+ .select('secret')+ .eq('connection_id', connectionId)+ .maybeSingle();+ if (error) throw new Error(`brand_cms_credentials read: ${error.code ?? 'error'}`);+ return data?.secret ? openCredentials(bound(connectionId), data.secret) : null;+}diff --git a/server/src/lib/cms/credentials.test.js b/server/src/lib/cms/credentials.test.jsnew file mode 100644index 000000000..01b38333e--- /dev/null+++ b/server/src/lib/cms/credentials.test.js@@ -0,0 +1,57 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../../config/supabase.js', () => ({ default: {} }));++const { readCmsCredentials, saveCmsCredentials } = await import('./credentials.js');+const { sealCredentials } = await import('../catalog/credentials.js');++/**+ * A CMS connection's sign-in (00294): sealed by the API as a store's is,+ * bound to its own connection.+ */++const rows = new Map();+const db = {+ from: (table) => ({+ upsert: async (row) => {+ rows.set(row.connection_id, { table, ...row });+ return { error: null };+ },+ select: () => ({+ eq: (_column, id) => ({+ maybeSingle: async () => ({ data: rows.get(id) ?? null, error: null }),+ }),+ }),+ }),+};+const signIn = { username: 'editor', password: 'abcd efgh ijkl mnop qrst uvwx' };++beforeEach(() => {+ rows.clear();+ vi.stubEnv('CONNECTOR_CREDENTIALS_KEY', Buffer.alloc(32, 7).toString('base64'));+});+afterEach(() => vi.unstubAllEnvs());++describe('CMS credentials', () => {+ it('keeps the sign-in sealed, and reads it back', async () => {+ await saveCmsCredentials('cn1', signIn, { setBy: 'u1', db });+ const kept = rows.get('cn1');+ expect(kept).toMatchObject({ table: 'brand_cms_credentials', set_by: 'u1' });+ expect(kept.secret).not.toContain('abcd');+ expect(kept.secret).not.toContain('editor');+ expect(await readCmsCredentials('cn1', { db })).toEqual(signIn);+ });++ it('opens on its own connection only, never as another’s nor as a store’s', async () => {+ await saveCmsCredentials('cn1', signIn, { db });+ rows.set('cn2', { ...rows.get('cn1'), connection_id: 'cn2' });+ expect(await readCmsCredentials('cn2', { db })).toBeNull();+ // A store source's envelope, for the same id, isn't a CMS sign-in.+ rows.set('cn3', { connection_id: 'cn3', secret: sealCredentials('cn3', signIn) });+ expect(await readCmsCredentials('cn3', { db })).toBeNull();+ });++ it('reads none for a connection with none kept', async () => {+ expect(await readCmsCredentials('cn9', { db })).toBeNull();+ });+});diff --git a/server/src/lib/cms/wordpress-delivery.js b/server/src/lib/cms/wordpress-delivery.jsnew file mode 100644index 000000000..3ac2bea5f--- /dev/null+++ b/server/src/lib/cms/wordpress-delivery.js@@ -0,0 +1,142 @@+import * as cheerio from 'cheerio';+import supabaseAdmin from '../../config/supabase.js';+import { logger } from '../logger.js';+import { readCmsCredentials } from './credentials.js';+import { WordPressError, createPost, readPost, updatePost } from './wordpress.js';++/**+ * Send to CMS to WordPress (#1331, phase 2; 00294): a page goes to the+ * brand's WordPress site as a draft post, or updates the post its last+ * WordPress send made on that site while that post is still a draft.+ *+ * WordPress has no draft of a live post: a published post written to is+ * live at once. Send to CMS sends drafts only, so a page whose post is+ * live (or scheduled, or private) goes as a new draft post, and the send+ * says so; the person moves it over by hand. content-delivery.js reserves,+ * writes and batches the deliveries as it does for the webhook.+ *+ * The page's JSON-LD stays out: WordPress keeps a <script> only for users+ * allowed unfiltered HTML, and for the others strips the tags and leaves the+ * JSON in the post as text.+ */++/** A post still a draft: written to, it stays one. */+const DRAFT_STATUSES = new Set(['draft', 'pending', 'auto-draft']);++/**+ * The post the page's last WordPress send made on this site, if any,+ * whatever became of that send. The site is its whole address (the+ * delivery's target_collection): two sites in folders of one domain, or of+ * one multisite, number their posts each from 1.+ */+async function lastPost(draftId, site, deliveryId) {+ const { data, error } = await supabaseAdmin+ .from('content_draft_deliveries')+ .select('external_id')+ .eq('draft_id', draftId)+ .eq('target', 'wordpress')+ .eq('target_collection', site)+ .not('external_id', 'is', null)+ .neq('id', deliveryId)+ .order('created_at', { ascending: false })+ .limit(1)+ .maybeSingle();+ if (error) throw new Error(error.message);+ return data?.external_id ?? null;+}++/**+ * The sign-in the send was refused with: Settings asks for a new one. Only+ * the connection as the send read it: one connected again meanwhile keeps+ * its new sign-in.+ */+async function markRefused(connection) {+ const { error } = await supabaseAdmin+ .from('brand_cms_connections')+ .update({ status: 'auth_failed', updated_at: new Date().toISOString() })+ .eq('id', connection.id)+ .eq('provider', 'wordpress')+ .eq('updated_at', connection.updated_at);+ if (error) logger.warn({ err: error }, '[content-delivery] wordpress refusal not kept');+}++/** The page's HTML as WordPress takes it, its JSON-LD out; how many blocks went. */+export function toWordPressHtml(html) {+ const $ = cheerio.load(html, null, false);+ const jsonLd = $('script').filter(+ (_, el) => String($(el).attr('type') ?? '').toLowerCase() === 'application/ld+json',+ );+ const count = jsonLd.length;+ jsonLd.remove();+ return { html: count ? $.html() : html, jsonLd: count };+}++/**+ * Sends one page to the brand's WordPress site. What went wrong is said in+ * our words.+ *+ * @param {{ delivery: { id: string }, page: object, html: string,+ * connection: { id: string, site_url: string, updated_at: string }, request?: Function }} input+ * @returns {Promise<{ taken: boolean, failure?: string, refused?: boolean, externalId?: string,+ * collectionId?: string, updated?: boolean, live?: boolean, changed?: { jsonLd: number } }>}+ * live: the page's post was live, so a new draft was made (with its slug: published,+ * WordPress gives it "-2"); changed: the JSON-LD blocks left out+ */+export async function sendToWordPress({ delivery, page, html, connection, request }) {+ const site = connection.site_url;+ const { html: content, jsonLd } = toWordPressHtml(html);+ const post = {+ title: page.title,+ // Empty, WordPress makes one from the title.+ ...(page.slug ? { slug: page.slug } : {}),+ content,+ excerpt: page.metaDescription || '',+ };+ try {+ const credentials = await readCmsCredentials(connection.id);+ if (!credentials?.username || !credentials?.password) {+ await markRefused(connection);+ return {+ taken: false,+ failure: 'The WordPress sign-in can’t be read. Connect WordPress again.',+ refused: true,+ };+ }+ const before = await lastPost(page.draftId, site, delivery.id);+ const current = before ? await readPost(site, credentials, before, { request }) : null;+ const live = Boolean(+ current && current.status !== 'trash' && !DRAFT_STATUSES.has(current.status),+ );+ let written = null;+ if (current && !live && current.status !== 'trash') {+ try {+ written = await updatePost(site, credentials, before, post, { request });+ } catch (err) {+ if (!(err instanceof WordPressError && err.code === 'not_found')) throw err;+ }+ }+ const updated = Boolean(written);+ written ??= await createPost(site, credentials, post, { request });+ return {+ taken: true,+ externalId: String(written.id),+ collectionId: site,+ updated,+ live,+ changed: { jsonLd },+ };+ } catch (err) {+ if (err instanceof WordPressError) {+ if (err.code === 'auth_failed') {+ await markRefused(connection);+ return { taken: false, failure: err.message, refused: true };+ }+ return { taken: false, failure: err.message };+ }+ logger.warn(+ { err: { name: err?.name }, deliveryId: delivery.id },+ '[content-delivery] wordpress send failed',+ );+ return { taken: false, failure: 'WordPress could not be reached' };+ }+}diff --git a/server/src/lib/cms/wordpress-delivery.test.js b/server/src/lib/cms/wordpress-delivery.test.jsnew file mode 100644index 000000000..12d9d607a--- /dev/null+++ b/server/src/lib/cms/wordpress-delivery.test.js@@ -0,0 +1,231 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Send to CMS to WordPress (#1331, phase 2; 00294): a page goes to the+ * brand's site as a draft post, updates the post its last send made there+ * while it's still a draft, and never writes over a live post.+ */++let previous;+const queries = [];+const updates = [];+vi.mock('../../config/supabase.js', () => ({+ default: {+ from: (table) => {+ const q = { table, filters: [] };+ const chain = {+ select: () => chain,+ eq: (col, value) => (q.filters.push(['eq', col, value]), chain),+ neq: (col, value) => (q.filters.push(['neq', col, value]), chain),+ not: (col, op, value) => (q.filters.push(['not', col, op, value]), chain),+ order: () => chain,+ limit: () => chain,+ update: (row) => (updates.push({ table, row, filters: q.filters }), chain),+ maybeSingle: async () => {+ queries.push(q);+ return { data: previous ? { external_id: previous } : null, error: null };+ },+ then: (resolve) => resolve({ data: null, error: null }),+ };+ return chain;+ },+ },+}));+const logged = [];+vi.mock('../logger.js', () => ({+ logger: { warn: (...args) => logged.push(JSON.stringify(args)) },+}));+let credentials;+vi.mock('./credentials.js', () => ({ readCmsCredentials: async () => credentials }));+const wordpress = { createPost: vi.fn(), readPost: vi.fn(), updatePost: vi.fn() };+vi.mock('./wordpress.js', async (importOriginal) => ({+ ...(await importOriginal()),+ createPost: (...args) => wordpress.createPost(...args),+ readPost: (...args) => wordpress.readPost(...args),+ updatePost: (...args) => wordpress.updatePost(...args),+}));++const { sendToWordPress } = await import('./wordpress-delivery.js');+const { WordPressError } = await import('./wordpress.js');++const SITE = 'https://blog.acme.example';+const connection = {+ id: 'cn1',+ brand_id: 'b1',+ site_url: SITE,+ updated_at: '2026-10-27T09:00:00Z',+};+const signIn = { username: 'editor', password: 'abcd efgh ijkl mnop qrst uvwx' };+const HTML =+ '<h2>Why</h2><p>Smooth.</p><script type="application/ld+json">{"@type":"Article"}</script>';+const send = (over = {}) =>+ sendToWordPress({+ delivery: { id: 'd2345678-0000-0000-0000-000000000000' },+ page: {+ draftId: 'dr1',+ title: 'Cold brew at home',+ slug: 'cold-brew-at-home',+ metaTitle: '',+ metaDescription: 'How to make it.',+ ...over,+ },+ html: HTML,+ connection,+ });+// The JSON-LD stays out: kses would leave it in the post as text.+const POST = {+ title: 'Cold brew at home',+ slug: 'cold-brew-at-home',+ content: '<h2>Why</h2><p>Smooth.</p>',+ excerpt: 'How to make it.',+};++beforeEach(() => {+ previous = null;+ credentials = signIn;+ queries.length = 0;+ updates.length = 0;+ logged.length = 0;+ wordpress.createPost.mockReset().mockResolvedValue({ id: 41, status: 'draft', link: null });+ wordpress.readPost.mockReset().mockResolvedValue({ id: 7, status: 'draft', link: null });+ wordpress.updatePost.mockReset().mockResolvedValue({ id: 7, status: 'draft', link: null });+});++describe('sendToWordPress', () => {+ it('makes a draft post of a page never sent to the site, its JSON-LD left out', async () => {+ expect(await send()).toEqual({+ taken: true,+ externalId: '41',+ collectionId: SITE,+ updated: false,+ live: false,+ changed: { jsonLd: 1 },+ });+ expect(wordpress.createPost).toHaveBeenCalledWith(SITE, signIn, POST, { request: undefined });+ expect(wordpress.readPost).not.toHaveBeenCalled();+ // The last send looked for: this page's, on this site, not this delivery.+ expect(queries[0].filters).toEqual(+ expect.arrayContaining([+ ['eq', 'draft_id', 'dr1'],+ ['eq', 'target', 'wordpress'],+ ['eq', 'target_collection', SITE],+ ['neq', 'id', 'd2345678-0000-0000-0000-000000000000'],+ ]),+ );+ });++ it('looks for the last post on this site, not another in a folder of its domain', async () => {+ await sendToWordPress({+ delivery: { id: 'd2345678-0000-0000-0000-000000000000' },+ page: { draftId: 'dr1', title: 'Kalter Kaffee', slug: 'kalter-kaffee', metaDescription: '' },+ html: '<p>x</p>',+ connection: { ...connection, site_url: 'https://acme.example/de' },+ });+ expect(queries[0].filters).toContainEqual([+ 'eq',+ 'target_collection',+ 'https://acme.example/de',+ ]);+ });++ it('updates the post its last send made while it is still a draft, or pending review', async () => {+ previous = '7';+ wordpress.readPost.mockResolvedValueOnce({ id: 7, status: 'pending', link: null });+ expect(await send()).toMatchObject({ updated: true });+ previous = '7';+ expect(await send({ title: 'Cold brew, step by step' })).toMatchObject({+ taken: true,+ externalId: '7',+ updated: true,+ live: false,+ });+ expect(wordpress.updatePost).toHaveBeenCalledWith(+ SITE,+ signIn,+ '7',+ { ...POST, title: 'Cold brew, step by step' },+ { request: undefined },+ );+ expect(wordpress.createPost).not.toHaveBeenCalled();+ expect(wordpress.updatePost).toHaveBeenCalledTimes(2);+ });++ it('makes a new draft rather than write over a live post, and says so', async () => {+ for (const status of ['publish', 'future', 'private']) {+ previous = '7';+ wordpress.readPost.mockResolvedValueOnce({ id: 7, status, link: `${SITE}/cold-brew/` });+ expect(await send()).toMatchObject({+ taken: true,+ externalId: '41',+ updated: false,+ live: true,+ });+ }+ expect(wordpress.updatePost).not.toHaveBeenCalled();+ expect(wordpress.createPost).toHaveBeenCalledTimes(3);+ });++ it('makes a new post when the last one is gone or in the trash', async () => {+ previous = '7';+ wordpress.readPost.mockResolvedValueOnce(null);+ expect(await send()).toMatchObject({ externalId: '41', updated: false, live: false });+ wordpress.readPost.mockResolvedValueOnce({ id: 7, status: 'trash', link: null });+ expect(await send()).toMatchObject({ externalId: '41', updated: false, live: false });+ expect(wordpress.updatePost).not.toHaveBeenCalled();+ });++ it('makes a new post when the draft was deleted between the read and the write', async () => {+ previous = '7';+ wordpress.updatePost.mockRejectedValueOnce(new WordPressError('not_found', 'gone'));+ expect(await send()).toMatchObject({ externalId: '41', updated: false });+ });++ it('leaves the slug to WordPress when the page has none', async () => {+ await send({ slug: '' });+ expect(wordpress.createPost.mock.calls[0][2]).not.toHaveProperty('slug');+ });++ it('marks the connection refused when WordPress refuses the sign-in', async () => {+ wordpress.createPost.mockRejectedValueOnce(+ new WordPressError('auth_failed', 'WordPress refused the user or the Application Password.'),+ );+ expect(await send()).toEqual({+ taken: false,+ failure: 'WordPress refused the user or the Application Password.',+ refused: true,+ });+ expect(updates).toEqual([+ {+ table: 'brand_cms_connections',+ row: expect.objectContaining({ status: 'auth_failed' }),+ // The connection as the send read it: one connected again meanwhile keeps its sign-in.+ filters: [+ ['eq', 'id', 'cn1'],+ ['eq', 'provider', 'wordpress'],+ ['eq', 'updated_at', '2026-10-27T09:00:00Z'],+ ],+ },+ ]);+ });++ it('asks to connect again when the kept sign-in can’t be read', async () => {+ credentials = null;+ expect(await send()).toMatchObject({ taken: false, refused: true });+ expect(wordpress.createPost).not.toHaveBeenCalled();+ expect(updates[0].row.status).toBe('auth_failed');+ });++ it('says what WordPress answered, and keeps the connection', async () => {+ wordpress.createPost.mockRejectedValueOnce(+ new WordPressError('failed', 'WordPress answered 500.'),+ );+ expect(await send()).toEqual({ taken: false, failure: 'WordPress answered 500.' });+ expect(updates).toEqual([]);+ });++ it('says WordPress couldn’t be reached on anything else, logging no message', async () => {+ wordpress.createPost.mockRejectedValueOnce(new Error('password=secret'));+ expect(await send()).toEqual({ taken: false, failure: 'WordPress could not be reached' });+ expect(logged.join('')).not.toContain('secret');+ });+});diff --git a/server/src/lib/cms/wordpress.js b/server/src/lib/cms/wordpress.jsnew file mode 100644index 000000000..841126b33--- /dev/null+++ b/server/src/lib/cms/wordpress.js@@ -0,0 +1,329 @@+import * as cheerio from 'cheerio';+import { ConnectorHttpError, requestJson } from '../../connectors/http.js';++/**+ * WordPress for Send to CMS (#1331, phase 2; 00294): the site's REST API+ * (`/wp-json/`), signed in with a user's Application Password (WordPress+ * 5.6+, Users › Profile › Application Passwords) in an Authorization header.+ *+ * Every call goes through the connectors' HTTP client (connectors/http.js):+ * public https addresses only, so the password never crosses the network in+ * the clear, no redirect followed, and a POST never sent twice. Pages go as+ * draft posts: nothing here publishes.+ *+ * The password is never put in a message, a log or an answer, and goes only+ * to a site that answers as WordPress (checkSite).+ */++export class WordPressError extends Error {+ /**+ * @param {'invalid'|'not_wordpress'|'no_app_passwords'|'auth_failed'|'header_dropped'|+ * 'users_hidden'|'site_refused'|'redirect'|'no_access'|'not_found'|'unreachable'|'failed'} code+ * 'auth_failed': the user or password is refused (the person connects again)+ * @param {string} message+ * @param {number} [status] the HTTP status WordPress answered, when it did+ */+ constructor(code, message, status) {+ super(message);+ this.name = 'WordPressError';+ this.code = code;+ this.status = status;+ }+}++/** The longest site address kept (brand_cms_connections.site_url). */+export const SITE_URL_MAX = 2048;++/**+ * The site's address as the person typed it, as the API is reached at:+ * https (added when left out) on its standard port, no user, query or hash,+ * and no `/wp-admin`, `/wp-json` or trailing slash copied with it. A site in+ * a folder keeps it.+ */+export function siteAddress(input) {+ let text = String(input ?? '').trim();+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) text = `https://${text}`;+ let url;+ try {+ url = new URL(text);+ } catch {+ throw new WordPressError('invalid', 'That isn’t a web address.');+ }+ if (url.protocol !== 'https:') {+ throw new WordPressError(+ 'invalid',+ 'WordPress takes an Application Password over https only: use the site’s https address.',+ );+ }+ if (url.username || url.password) {+ throw new WordPressError('invalid', 'Leave the user and password out of the address.');+ }+ // The connectors' client reaches the standard port only.+ if (url.port) {+ throw new WordPressError('invalid', 'Use the site’s address without a port.');+ }+ const path = url.pathname.replace(/\/(wp-admin|wp-json|wp-login\.php)(\/.*)?$/i, '');+ const address = `${url.origin}${path.replace(/\/+$/, '')}`;+ if (address.length > SITE_URL_MAX) {+ throw new WordPressError('invalid', 'That address is too long.');+ }+ return address;+}++/** The Basic sign-in WordPress takes an Application Password with; its spaces are its own. */+function authorization({ username, password }) {+ const clear = `${username}:${String(password).replace(/\s+/g, '')}`;+ return `Basic ${Buffer.from(clear, 'utf8').toString('base64')}`;+}++/** WordPress's answer to a call that failed, in our words. */+function wordPressError(err) {+ if (err instanceof WordPressError) return err;+ if (!(err instanceof ConnectorHttpError)) return err;+ const { status } = err;+ switch (err.code) {+ case 'auth':+ return status === 403+ ? new WordPressError(+ 'no_access',+ 'The connected user isn’t allowed to do that on this site.',+ status,+ )+ : new WordPressError(+ 'auth_failed',+ 'WordPress refused the user or the Application Password.',+ status,+ );+ case 'invalid_url':+ case 'blocked':+ return new WordPressError('unreachable', err.message);+ case 'timeout':+ case 'unreachable':+ return new WordPressError('unreachable', 'WordPress couldn’t be reached.');+ case 'rate_limited':+ return new WordPressError('unreachable', 'WordPress asked to wait. Try again later.', status);+ case 'http_error':+ if (status >= 300 && status < 400) {+ return new WordPressError(+ 'redirect',+ 'The site sends the request on to another address. Use the address it goes to (with or without www).',+ status,+ );+ }+ if (status === 404 || status === 410) {+ return new WordPressError('not_found', 'WordPress has no such post.', status);+ }+ return new WordPressError('failed', `WordPress answered ${status}.`, status);+ default:+ return new WordPressError('failed', 'WordPress didn’t answer as expected.', status);+ }+}++/**+ * One call to the site's REST API. `request` replaces the HTTP client in+ * tests (connectors/testing.js).+ */+async function call(site, route, { credentials, method = 'GET', query, body, request }) {+ const headers = credentials ? { authorization: authorization(credentials) } : {};+ try {+ const { data } = await (request ?? requestJson)(`${site}/wp-json${route}`, {+ method,+ headers,+ query,+ body,+ });+ return data;+ } catch (err) {+ throw wordPressError(err);+ }+}++/** What the site check reads of the REST index (it can run to megabytes with many plugins). */+const INDEX = { _fields: 'name,namespaces,authentication' };++const notWordPress = (site) =>+ new WordPressError(+ 'not_wordpress',+ `There’s no WordPress REST API at ${site}/wp-json/. Check the address, and that Settings › Permalinks isn’t set to Plain.`,+ );++/** A failed read of the REST index, in the words of that step. */+function indexError(site, err) {+ if (!(err instanceof WordPressError)) return err;+ if (['redirect', 'unreachable', 'auth_failed'].includes(err.code)) return err;+ if (err.code === 'no_access') {+ return new WordPressError(+ 'site_refused',+ 'The site refused the request: a firewall or a security plugin may block its REST API.',+ err.status,+ );+ }+ if (err.code === 'failed' && err.status >= 500) return err;+ return notWordPress(site);+}++/** The index of a WordPress site, or why it isn't one. */+function assertWordPress(site, index) {+ if (!Array.isArray(index?.namespaces) || !index.namespaces.includes('wp/v2')) {+ throw notWordPress(site);+ }+ return index;+}++/** The site's name as WordPress shows it, its HTML entities read (WordPress keeps it escaped). */+function siteNameOf(index) {+ if (typeof index.name !== 'string') return null;+ const name = cheerio.load(index.name, null, false).text().trim().slice(0, 300);+ return name || null;+}++/**+ * Checks a site and a sign-in before they're kept: the site answers as+ * WordPress, takes Application Passwords, and the user can write posts.+ * The password is sent only once the site has answered as WordPress, or+ * keeps its API from visitors (401, 403).+ *+ * @param {string} site from siteAddress()+ * @param {{ username: string, password: string }} credentials+ * @returns {Promise<{ siteName: string|null, account: string }>}+ */+export async function checkSite(site, credentials, { request } = {}) {+ let index = null;+ try {+ index = assertWordPress(site, await call(site, '/', { query: INDEX, request }));+ } catch (err) {+ // A site that keeps its API from visitors is asked again, signed in.+ if (!(err instanceof WordPressError && ['auth_failed', 'no_access'].includes(err.code))) {+ throw indexError(site, err);+ }+ }+ if (!index) {+ try {+ index = assertWordPress(site, await call(site, '/', { credentials, query: INDEX, request }));+ } catch (err) {+ throw indexError(site, err);+ }+ }+ if (!index.authentication?.['application-passwords']) {+ throw new WordPressError(+ 'no_app_passwords',+ 'This site has Application Passwords turned off. WordPress 5.6 and later have them; a security plugin may turn them off.',+ );+ }+ let me;+ try {+ me = await call(site, '/wp/v2/users/me', { credentials, query: { context: 'edit' }, request });+ } catch (err) {+ if (err instanceof WordPressError && err.code === 'auth_failed') {+ // A wrong password fails every call to the API. One only this call+ // refuses never reached WordPress: the server dropped the header.+ const reached = await call(site, '/', { credentials, query: INDEX, request }).then(+ () => true,+ () => false,+ );+ if (reached) {+ throw new WordPressError(+ 'header_dropped',+ 'The site’s server didn’t pass the sign-in on to WordPress. Save Settings › Permalinks once, or ask your host to pass the Authorization header (Apache: SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 in .htaccess).',+ err.status,+ );+ }+ }+ if (err instanceof WordPressError && err.code === 'not_found') {+ throw new WordPressError(+ 'users_hidden',+ 'The site hides its users from the REST API (a security plugin may). Let signed-in users reach /wp-json/wp/v2/users/me.',+ err.status,+ );+ }+ throw err;+ }+ if (!me?.capabilities?.edit_posts) {+ throw new WordPressError(+ 'no_access',+ 'This user can’t write posts on the site. Use an Author, an Editor or an Administrator.',+ );+ }+ return { siteName: siteNameOf(index), account: credentials.username };+}++/** A post as Send to CMS keeps it. */+const postOf = (data) => ({+ id: Number(data?.id),+ status: typeof data?.status === 'string' ? data.status : null,+ link: typeof data?.link === 'string' ? data.link : null,+});++/** A post id as WordPress takes it in a path, or null. */+const postId = (id) => (/^[1-9]\d{0,18}$/.test(String(id)) ? String(id) : null);++/**+ * A new draft post.+ * @param {{ title: string, slug?: string|null, content: string, excerpt?: string }} post+ */+export async function createPost(site, credentials, post, { request } = {}) {+ const data = await call(site, '/wp/v2/posts', {+ credentials,+ method: 'POST',+ body: { ...post, status: 'draft' },+ request,+ });+ const created = postOf(data);+ if (!Number.isInteger(created.id) || created.id <= 0) {+ throw new WordPressError('failed', 'WordPress didn’t say which post it made.');+ }+ return created;+}++/** A post as it stands, or null when it's gone (deleted for good, never there) or not the user's to edit. */+export async function readPost(site, credentials, id, { request } = {}) {+ const path = postId(id);+ if (!path) return null;+ try {+ return postOf(+ await call(site, `/wp/v2/posts/${path}`, {+ credentials,+ query: { context: 'edit' },+ request,+ }),+ );+ } catch (err) {+ // Gone, or another user's that this one can't edit: not this connection's post.+ if (err instanceof WordPressError && ['not_found', 'no_access'].includes(err.code)) return null;+ throw err;+ }+}++/** Writes a post's title, slug, content and excerpt; its status stays as it is. */+export async function updatePost(site, credentials, id, post, { request } = {}) {+ const path = postId(id);+ if (!path) throw new WordPressError('not_found', 'WordPress has no such post.');+ return postOf(+ await call(site, `/wp/v2/posts/${path}`, { credentials, method: 'POST', body: post, request }),+ );+}++/**+ * Revokes the Application Password the connection signs in with, where the+ * site allows it (WordPress 5.7+ tells a password its own id). Best effort:+ * false when it couldn't, and the connection goes anyway.+ */+export async function revokePassword(site, credentials, { request } = {}) {+ try {+ const own = await call(site, '/wp/v2/users/me/application-passwords/introspect', {+ credentials,+ request,+ });+ const uuid =+ typeof own?.uuid === 'string' && /^[0-9a-f-]{36}$/i.test(own.uuid) ? own.uuid : null;+ if (!uuid) return false;+ await call(site, `/wp/v2/users/me/application-passwords/${uuid}`, {+ credentials,+ method: 'DELETE',+ request,+ });+ return true;+ } catch {+ return false;+ }+}diff --git a/server/src/lib/cms/wordpress.test.js b/server/src/lib/cms/wordpress.test.jsnew file mode 100644index 000000000..3bc646460--- /dev/null+++ b/server/src/lib/cms/wordpress.test.js@@ -0,0 +1,290 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++// The harness reaches the Supabase admin client at import time.+vi.mock('../../config/supabase.js', () => ({ default: {} }));++const { startFakeApi } = await import('../../connectors/testing.js');+const { WordPressError, checkSite, createPost, readPost, revokePassword, siteAddress, updatePost } =+ await import('./wordpress.js');++/**+ * WordPress's REST API for Send to CMS (#1331, phase 2): a site checked+ * before its sign-in is kept, draft posts written, and the password revoked+ * on disconnect, against a fake of the API (its answers as WordPress's+ * handbook shows them).+ */++const signIn = { username: 'editor', password: 'abcd efgh ijkl mnop qrst uvwx' };+// Basic editor:abcdefghijklmnopqrstuvwx — WordPress takes the password without its spaces.+const BASIC = `Basic ${Buffer.from('editor:abcdefghijklmnopqrstuvwx').toString('base64')}`;+const INDEX = {+ name: 'Acme Coffee Blog',+ namespaces: ['oembed/1.0', 'wp/v2', 'wp-site-health/v1'],+ authentication: {+ 'application-passwords': {+ endpoints: { authorization: 'https://blog.acme.example/wp-admin/authorize-application.php' },+ },+ },+};+const ME = { id: 3, name: 'Editor', slug: 'editor', capabilities: { edit_posts: true } };++let api;+afterEach(() => api?.close());++const start = async (routes) => {+ api = await startFakeApi(routes);+ return { site: api.origin, request: api.request };+};++describe('siteAddress', () => {+ it('reads the address as the site, https, with what was copied around it taken off', () => {+ expect(siteAddress('blog.acme.example')).toBe('https://blog.acme.example');+ expect(siteAddress(' https://blog.acme.example/ ')).toBe('https://blog.acme.example');+ expect(siteAddress('https://acme.example/blog/wp-admin/post-new.php?x=1#y')).toBe(+ 'https://acme.example/blog',+ );+ expect(siteAddress('https://acme.example/wp-json/wp/v2/posts')).toBe('https://acme.example');+ });++ it('refuses http, a sign-in in the address and what isn’t one', () => {+ for (const input of [+ 'http://blog.acme.example',+ 'https://u:[email protected]',+ 'https://',+ '',+ ]) {+ expect(() => siteAddress(input)).toThrow(WordPressError);+ }+ expect(() => siteAddress('http://blog.acme.example')).toThrow(/https only/);+ expect(() => siteAddress('https://blog.acme.example:8443')).toThrow(/without a port/);+ });+});++describe('checkSite', () => {+ const FIELDS = { _fields: 'name,namespaces,authentication' };+ // A wrong password fails every call to the API, as WordPress's+ // rest_application_password_check_errors does; none is a visitor.+ const signedIn = (call, json) =>+ call.headers.authorization === BASIC || !call.headers.authorization+ ? { json }+ : { status: 401, json: { code: 'incorrect_password' } };++ it('takes a WordPress site whose user can write posts, the password sent once it answered as one', async () => {+ const { site, request } = await start({+ 'GET /wp-json/': (call) => signedIn(call, INDEX),+ 'GET /wp-json/wp/v2/users/me': () => ({ json: ME }),+ });+ expect(await checkSite(site, signIn, { request })).toEqual({+ siteName: 'Acme Coffee Blog',+ account: 'editor',+ });+ expect(api.calls.map((c) => [c.method, c.path, c.query, c.headers.authorization])).toEqual([+ ['GET', '/wp-json/', FIELDS, undefined],+ ['GET', '/wp-json/wp/v2/users/me', { context: 'edit' }, BASIC],+ ]);+ });++ it('sends no password to an address that isn’t WordPress', async () => {+ for (const routes of [+ {},+ { 'GET /wp-json/': () => ({ text: '<html>Hello</html>' }) },+ { 'GET /wp-json/': () => ({ json: { namespaces: ['wc/v3'] } }) },+ ]) {+ const checked = await start(routes);+ await expect(+ checkSite(checked.site, signIn, { request: checked.request }),+ ).rejects.toMatchObject({+ code: 'not_wordpress',+ });+ expect(api.calls.every((c) => !c.headers.authorization)).toBe(true);+ api.close();+ }+ api = null;+ });++ it('asks a site that keeps its API from visitors again, signed in', async () => {+ const { site, request } = await start({+ 'GET /wp-json/': (call) =>+ call.headers.authorization+ ? signedIn(call, INDEX)+ : { status: 401, json: { code: 'rest_forbidden' } },+ 'GET /wp-json/wp/v2/users/me': () => ({ json: ME }),+ });+ expect(await checkSite(site, signIn, { request })).toMatchObject({ account: 'editor' });+ expect(api.calls.map((c) => Boolean(c.headers.authorization))).toEqual([false, true, true]);+ });++ it('says the user or the password is refused, never repeating it', async () => {+ const { site, request } = await start({+ 'GET /wp-json/': (call) =>+ call.headers.authorization+ ? { status: 401, json: { code: 'incorrect_password' } }+ : { json: INDEX },+ 'GET /wp-json/wp/v2/users/me': () => ({ status: 401, json: { code: 'incorrect_password' } }),+ });+ const err = await checkSite(site, signIn, { request }).catch((e) => e);+ expect(err).toMatchObject({ code: 'auth_failed' });+ expect(err.message).not.toMatch(/abcd|editor/);+ });++ it('tells a server that drops the sign-in from a wrong password', async () => {+ // The header never reaches WordPress: every call is a visitor's.+ const { site, request } = await start({+ 'GET /wp-json/': () => ({ json: INDEX }),+ 'GET /wp-json/wp/v2/users/me': () => ({ status: 401, json: { code: 'rest_not_logged_in' } }),+ });+ const err = await checkSite(site, signIn, { request }).catch((e) => e);+ expect(err).toMatchObject({ code: 'header_dropped' });+ expect(err.message).toMatch(/Permalinks/);+ });++ it('says what stopped it at each step, in that step’s words', async () => {+ const cases = [+ [+ { 'GET /wp-json/': () => ({ status: 301, headers: { location: 'https://www.x/' } }) },+ 'redirect',+ ],+ [{ 'GET /wp-json/': () => ({ status: 403, json: {} }) }, 'site_refused'],+ [{ 'GET /wp-json/': () => ({ status: 500, json: {} }) }, 'failed'],+ [+ {+ 'GET /wp-json/': () => ({ json: INDEX }),+ 'GET /wp-json/wp/v2/users/me': () => ({ status: 404, json: { code: 'rest_no_route' } }),+ },+ 'users_hidden',+ ],+ [{ 'GET /wp-json/': () => ({ json: { ...INDEX, authentication: [] } }) }, 'no_app_passwords'],+ [+ {+ 'GET /wp-json/': () => ({ json: INDEX }),+ 'GET /wp-json/wp/v2/users/me': () => ({ json: { ...ME, capabilities: { read: true } } }),+ },+ 'no_access',+ ],+ ];+ for (const [routes, code] of cases) {+ const checked = await start(routes);+ await expect(+ checkSite(checked.site, signIn, { request: checked.request }),+ ).rejects.toMatchObject({+ code,+ });+ api.close();+ }+ api = null;+ });++ it('reads the site’s name as WordPress escapes it', async () => {+ const { site, request } = await start({+ 'GET /wp-json/': () => ({ json: { ...INDEX, name: 'Acme & Co’s Blog' } }),+ 'GET /wp-json/wp/v2/users/me': () => ({ json: ME }),+ });+ expect((await checkSite(site, signIn, { request })).siteName).toBe('Acme & Co’s Blog');+ });+});++describe('posts', () => {+ it('makes a draft post, whatever the post asked', async () => {+ const { site, request } = await start({+ 'POST /wp-json/wp/v2/posts': (call) => ({+ status: 201,+ json: { id: 41, status: call.body.status, link: 'https://blog.acme.example/?p=41' },+ }),+ });+ const post = { title: 'Cold brew', slug: 'cold-brew', content: '<p>x</p>', excerpt: 'How.' };+ expect(await createPost(site, signIn, post, { request })).toEqual({+ id: 41,+ status: 'draft',+ link: 'https://blog.acme.example/?p=41',+ });+ expect(api.calls[0]).toMatchObject({+ method: 'POST',+ body: { ...post, status: 'draft' },+ headers: { authorization: BASIC, 'content-type': 'application/json' },+ });+ });++ it('writes a post without touching its status, and reads one as it stands', async () => {+ const { site, request } = await start({+ 'POST /wp-json/wp/v2/posts/7': () => ({ json: { id: 7, status: 'draft', link: null } }),+ 'GET /wp-json/wp/v2/posts/7': () => ({+ json: { id: 7, status: 'publish', link: 'https://blog.acme.example/cold-brew/' },+ }),+ });+ await updatePost(site, signIn, '7', { title: 'Cold brew', content: '<p>y</p>' }, { request });+ expect(api.calls[0].body).toEqual({ title: 'Cold brew', content: '<p>y</p>' });+ expect(await readPost(site, signIn, '7', { request })).toEqual({+ id: 7,+ status: 'publish',+ link: 'https://blog.acme.example/cold-brew/',+ });+ expect(api.calls[1].query).toEqual({ context: 'edit' });+ });++ it('reads another user’s post, which this one can’t edit, as none', async () => {+ const { site, request } = await start({+ 'GET /wp-json/wp/v2/posts/7': () => ({+ status: 403,+ json: { code: 'rest_forbidden_context' },+ }),+ });+ expect(await readPost(site, signIn, '7', { request })).toBeNull();+ });++ it('reads a post deleted for good as none, and an id that isn’t one as none', async () => {+ const { site, request } = await start({+ 'GET /wp-json/wp/v2/posts/7': () => ({+ status: 404,+ json: { code: 'rest_post_invalid_id', message: 'Invalid post ID.' },+ }),+ });+ expect(await readPost(site, signIn, '7', { request })).toBeNull();+ expect(await readPost(site, signIn, '../users', { request })).toBeNull();+ expect(api.calls).toHaveLength(1);+ await expect(updatePost(site, signIn, '7/x', {}, { request })).rejects.toMatchObject({+ code: 'not_found',+ });+ });++ it('says the user can’t, and tries a POST only once', async () => {+ const { site, request } = await start({+ 'POST /wp-json/wp/v2/posts': () => ({ status: 403, json: { code: 'rest_cannot_create' } }),+ });+ await expect(+ createPost(site, signIn, { title: 't', content: 'c' }, { request }),+ ).rejects.toMatchObject({+ code: 'no_access',+ });+ api.close();+ const again = await start({ 'POST /wp-json/wp/v2/posts': () => ({ status: 503 }) });+ await expect(+ createPost(again.site, signIn, { title: 't', content: 'c' }, { request: again.request }),+ ).rejects.toMatchObject({ code: 'failed', message: 'WordPress answered 503.' });+ expect(api.calls).toHaveLength(1);+ });+});++describe('revokePassword', () => {+ const UUID = '6b2b6c3e-2f1b-4f5a-9d7e-1c2b3a4d5e6f';++ it('revokes the Application Password the connection signs in with', async () => {+ const { site, request } = await start({+ 'GET /wp-json/wp/v2/users/me/application-passwords/introspect': () => ({+ json: { uuid: UUID, name: 'Ansvisor' },+ }),+ [`DELETE /wp-json/wp/v2/users/me/application-passwords/${UUID}`]: () => ({+ json: { deleted: true },+ }),+ });+ expect(await revokePassword(site, signIn, { request })).toBe(true);+ expect(api.calls.map((c) => `${c.method} ${c.path}`)).toEqual([+ 'GET /wp-json/wp/v2/users/me/application-passwords/introspect',+ `DELETE /wp-json/wp/v2/users/me/application-passwords/${UUID}`,+ ]);+ });++ it('says it couldn’t on a site that doesn’t tell a password its id', async () => {+ const { site, request } = await start({});+ expect(await revokePassword(site, signIn, { request })).toBe(false);+ });+});diff --git a/server/src/lib/content-delivery.js b/server/src/lib/content-delivery.jsindex 71a81ec54..6611c7973 100644--- a/server/src/lib/content-delivery.js+++ b/server/src/lib/content-delivery.js@@ -7,7 +7,9 @@ import { PageFetchError } from './safe-fetch.js';import { brandSiteType, rulesLanguage, untouchedRules } from './content-language.js';import { postJson } from './safe-post.js';import { isWebflowConfigured } from './composio.js';+import { credentialsConfigured } from './catalog/credentials.js';import { sendToWebflow } from './cms/webflow-delivery.js';+import { sendToWordPress } from './cms/wordpress-delivery.js';/*** Send to CMS, phase 1 (#1331): an admin or manager sends Content Editor@@ -25,8 +27,9 @@ import { sendToWebflow } from './cms/webflow-delivery.js';* the workspace's next send (reserve_content_deliveries).** Phase 2: a page can go to the brand's Webflow collection instead (00283,- * cms/webflow-delivery.js), as a draft item, under the same cap, batches- * and delivery rows; a delivery says where it went (`target`, 00284).+ * cms/webflow-delivery.js), as a draft item, or to its WordPress site+ * (00294, cms/wordpress-delivery.js), as a draft post, under the same cap,+ * batches and delivery rows; a delivery says where it went (`target`).*/export const DELIVERY_EVENT = 'content_draft.sent';@@ -60,8 +63,8 @@ export const deliveryPage = z.object({.default(null),});-/** Where pages go: the brand's webhook (phase 1) or its Webflow collection (phase 2). */-const DELIVERY_TARGETS = ['webhook', 'webflow'];+/** Where pages go: the brand's webhook (phase 1), its Webflow collection or its WordPress site (phase 2). */+const DELIVERY_TARGETS = ['webhook', 'webflow', 'wordpress'];export const sendInput = z.object({// guid, not uuid: brand ids aren't all RFC 4122 versions (seeded ones).@@ -74,7 +77,8 @@ export const sendInput = z.object({export class DeliveryError extends Error {/*** @param {'no_webhook'|'webhook_not_subscribed'|'webflow_not_configured'|'no_webflow'|- * 'webflow_refused'|'webflow_not_ready'|'in_progress'|'not_found'|'daily_limit'} code+ * 'webflow_refused'|'webflow_not_ready'|'wordpress_not_configured'|'no_wordpress'|+ * 'wordpress_refused'|'in_progress'|'not_found'|'daily_limit'} code*/constructor(code, message, status) {super(message);@@ -260,6 +264,41 @@ async function webflowFor(brandId) {return data;}+/** The brand's WordPress connection, its sign-in kept by the API (00294). */+async function wordpressFor(brandId) {+ if (!credentialsConfigured()) {+ throw new DeliveryError(+ 'wordpress_not_configured',+ 'WordPress is not set up on this server.',+ 503,+ );+ }+ const { data, error } = await supabaseAdmin+ .from('brand_cms_connections')+ .select('id, brand_id, status, site_url, updated_at')+ .eq('brand_id', brandId)+ .eq('provider', 'wordpress')+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!data) {+ throw new DeliveryError('no_wordpress', 'Connect WordPress in Settings › Integrations.', 409);+ }+ if (data.status === 'auth_failed') {+ throw new DeliveryError(+ 'wordpress_refused',+ 'WordPress refused the sign-in. Connect it again in Settings › Integrations.',+ 409,+ );+ }+ return data;+}++/** A CMS a page goes to itself, not through the webhook: its connection, and how a page is sent. */+const NATIVE = {+ webflow: { label: 'Webflow', connect: webflowFor, send: sendToWebflow },+ wordpress: { label: 'WordPress', connect: wordpressFor, send: sendToWordPress },+};+async function brandFor(brandId) {const [{ data: brand }, { data: domains }] = await Promise.all([supabaseAdmin@@ -329,18 +368,19 @@ async function sendToWebhooks({ delivery, page, brand, html, jsonLd, configs })}/**- * Sends one queued delivery, to the brand's webhooks or its Webflow- * collection, and writes how it went: sent, or failed with the reason. A- * Webflow item's id and collection are kept on the delivery, so the page's- * next send updates the item. A webhook's callback can land before the+ * Sends one queued delivery, to the brand's webhooks or its CMS (a Webflow+ * collection, a WordPress site), and writes how it went: sent, or failed+ * with the reason. A Webflow item's or WordPress post's id, and its+ * collection or site, are kept on the delivery, so the page's next send+ * updates it. A webhook's 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, webflow }) {+async function deliver({ delivery, page, brand, configs, native }) {const html = cleanPublishHtml(page.html);const jsonLd = jsonLdOf(html);- const sent = webflow- ? await sendToWebflow({ delivery, page, html, jsonLd, connection: webflow })+ const sent = native+ ? await native.send({ delivery, page, html, jsonLd, connection: native.connection }): await sendToWebhooks({ delivery, page, brand, html, jsonLd, configs });const update = {status: sent.taken ? 'sent' : 'failed',@@ -351,10 +391,11 @@ async function deliver({ delivery, page, brand, configs, webflow }) {? { external_id: sent.externalId, target_collection: sent.collectionId }: {}),};- // How Webflow took it, for the one page's answer (and the batch); not kept.- const how = webflow+ // How the CMS took it, for the one page's answer (and the batch); not kept.+ // live: WordPress had the page's post live, so a new draft was made.+ const how = native? sent.taken- ? { updated: sent.updated, changed: sent.changed }+ ? { updated: sent.updated, changed: sent.changed, live: sent.live }: { refused: Boolean(sent.refused) }: {};const { data: written, error } = await supabaseAdmin@@ -364,8 +405,9 @@ async function deliver({ delivery, page, brand, configs, webflow }) {.eq('status', 'queued').select('id');if (sent.externalId && (error || (written && !written.length))) {- // The item is in Webflow whatever the row says: its id is kept, or the- // page's next send makes a second item and fails on its slug.+ // The item (or post) is in the CMS whatever the row says: its id is+ // kept, or the page's next send makes a second one (Webflow refusing it+ // on its slug).const { error: idError } = await supabaseAdmin.from('content_draft_deliveries').update({ external_id: sent.externalId, target_collection: sent.collectionId })@@ -405,9 +447,9 @@ async function closeQueued(delivery, reason) {/*** The batch's pages, one after another; one deleted or archived before its- * turn doesn't go, and once Webflow refuses the token, the rest don't either.+ * turn doesn't go, and once the CMS refuses the sign-in, the rest don't either.*/-async function deliverBatch(going, { brand, configs, webflow, batchId }) {+async function deliverBatch(going, { brand, configs, native, batchId }) {let refused = null;for (const [i, item] of going.entries()) {if (refused) {@@ -427,8 +469,8 @@ async function deliverBatch(going, { brand, configs, webflow, batchId }) {await closeQueued(item.delivery, 'The page was deleted or archived before it was sent');continue;}- const sent = await deliver({ ...item, brand, configs, webflow });- if (sent.refused) refused = sent.error ?? 'Webflow refused the site token';+ const sent = await deliver({ ...item, brand, configs, native });+ if (sent.refused) refused = sent.error ?? `${native?.label ?? 'The CMS'} refused the sign-in`;} catch (err) {logger.error({ err, batchId, deliveryId: item.delivery.id },@@ -463,8 +505,8 @@ async function myRuleSets(orgId, siteType, drafts) {/*** Sends pages of one brand: checks they are the brand's (not archived), that- * a webhook takes the event (or the brand's Webflow collection is ready, for- * target 'webflow'), reserves them against the day's cap (those past+ * a webhook takes the event (or the brand's Webflow collection is ready, or+ * its WordPress site connected, for those targets), 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.@@ -494,8 +536,9 @@ export async function sendContentPages({if ((drafts ?? []).length !== ids.length) {throw new DeliveryError('not_found', 'A page to send is not in this brand', 404);}- const webflow = target === 'webflow' ? await webflowFor(brandId) : null;- const configs = webflow ? [] : await webhooksFor(brandId);+ const cms = NATIVE[target] ?? null;+ const native = cms ? { ...cms, connection: await cms.connect(brandId) } : null;+ const configs = native ? [] : await webhooksFor(brandId);const batchId = pages.length > 1 ? crypto.randomUUID() : null;const { data: queued, error: reserveError } = await supabaseAdmin.rpc(@@ -511,11 +554,11 @@ export async function sendContentPages({},);if (reserveError) {- // 00284: a page already on its way to Webflow isn't sent again meanwhile.+ // 00284, 00294: a page already on its way to the CMS isn't sent there again meanwhile.if (/delivery_in_progress/.test(reserveError.message ?? '')) {throw new DeliveryError('in_progress',- 'A page is already being sent to Webflow. Wait for it, then send again.',+ `A page is already being sent to ${cms?.label ?? 'the CMS'}. Wait for it, then send again.`,409,);}@@ -578,10 +621,10 @@ export async function sendContentPages({};}if (pages.length === 1) {- const sent = await deliver({ ...going[0], brand, configs, webflow });+ const sent = await deliver({ ...going[0], brand, configs, native });return { batchId, deliveries: [sent], skipped: 0 };}- void deliverBatch(going, { brand, configs, webflow, batchId });+ void deliverBatch(going, { brand, configs, native, batchId });return {batchId,deliveries: rows.map((r) => ({ id: r.id, draftId: r.draft_id, status: r.status })),diff --git a/server/src/lib/content-delivery.test.js b/server/src/lib/content-delivery.test.jsindex 8faecf5d7..e2ffb0c37 100644--- a/server/src/lib/content-delivery.test.js+++ b/server/src/lib/content-delivery.test.js@@ -16,6 +16,9 @@ const db = {// The brand's Webflow connection (00283), and whether this server has Webflow set up.webflow: null,webflowConfigured: true,+ // Its WordPress connection (00294), and whether this server can keep its sign-in.+ wordpress: null,+ wordpressConfigured: true,queued: [],updates: [],rpc: [],@@ -48,7 +51,10 @@ function from(table) {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 === 'brand_cms_connections') return { data: db.webflow, error: null };+ if (table === 'brand_cms_connections') {+ const provider = q.filters.find(([op, col]) => op === 'eq' && col === 'provider')?.[2];+ return { data: provider === 'wordpress' ? db.wordpress : db.webflow, error: null };+ }if (table === 'brands') {db.brandReads += 1;return { data: db.brand, error: null };@@ -92,6 +98,13 @@ const sendToWebflow = vi.fn();vi.mock('./cms/webflow-delivery.js', () => ({sendToWebflow: (...args) => sendToWebflow(...args),}));+vi.mock('./catalog/credentials.js', () => ({+ credentialsConfigured: () => db.wordpressConfigured,+}));+const sendToWordPress = vi.fn();+vi.mock('./cms/wordpress-delivery.js', () => ({+ sendToWordPress: (...args) => sendToWordPress(...args),+}));const { DAILY_DELIVERIES, DeliveryError, PAUSE_MS, cleanPublishHtml, sendContentPages, signBody } =await import('./content-delivery.js');@@ -143,9 +156,12 @@ beforeEach(() => {db.rpc = [];db.webflow = null;db.webflowConfigured = true;+ db.wordpress = null;+ db.wordpressConfigured = true;db.rpcError = null;postJson.mockReset().mockResolvedValue({ status: 200, answer: '{"ok":true}' });sendToWebflow.mockReset();+ sendToWordPress.mockReset();});afterEach(() => {@@ -608,3 +624,98 @@ describe('sendContentPages to Webflow (phase 2)', () => {});});});++describe('sendContentPages to WordPress (phase 2, 00294)', () => {+ const connection = {+ id: 'cn1',+ brand_id: 'b1',+ status: 'connected',+ site_url: 'https://blog.acme.example',+ };+ const toWordPress = (pages = [page()]) =>+ sendContentPages({ orgId: 'o1', brandId: 'b1', userId: 'u1', pages, target: 'wordpress' });++ it('sends a page to the brand’s site, not its webhooks, and keeps the post on the delivery', async () => {+ db.wordpress = connection;+ sendToWordPress.mockResolvedValue({+ taken: true,+ externalId: '41',+ collectionId: 'blog.acme.example',+ updated: false,+ live: true,+ });+ const sent = await toWordPress();+ expect(db.rpc[0].args.p_target).toBe('wordpress');+ expect(postJson).not.toHaveBeenCalled();+ expect(sendToWebflow).not.toHaveBeenCalled();+ expect(sendToWordPress).toHaveBeenCalledWith(+ expect.objectContaining({+ connection,+ html: '<h2>Why</h2><p>Because.</p>',+ page: expect.objectContaining({ draftId: page().draftId, slug: 'best-aeo-tools' }),+ }),+ );+ const write = db.updates.find((u) => u.table === 'content_draft_deliveries');+ expect(write.update).toMatchObject({+ status: 'sent',+ external_id: '41',+ target_collection: 'blog.acme.example',+ });+ // Its post was live: the page went as a new draft, and the answer says so.+ expect(sent.deliveries[0]).toMatchObject({ status: 'sent', updated: false, live: true });+ });++ it('refuses before reserving when WordPress isn’t connected or set up', async () => {+ db.wordpressConfigured = false;+ await expect(toWordPress()).rejects.toMatchObject({+ code: 'wordpress_not_configured',+ status: 503,+ });+ db.wordpressConfigured = true;+ await expect(toWordPress()).rejects.toMatchObject({ code: 'no_wordpress', status: 409 });+ db.wordpress = { ...connection, status: 'auth_failed' };+ await expect(toWordPress()).rejects.toMatchObject({ code: 'wordpress_refused', status: 409 });+ // A Webflow connection isn't a WordPress one.+ db.wordpress = null;+ db.webflow = {+ brand_id: 'b1',+ status: 'connected',+ collection_id: 'c1',+ field_map: { body: 'b' },+ };+ await expect(toWordPress()).rejects.toMatchObject({ code: 'no_wordpress' });+ expect(db.rpc).toEqual([]);+ expect(sendToWordPress).not.toHaveBeenCalled();+ });++ it('refuses a page already on its way to WordPress, naming it', async () => {+ db.wordpress = connection;+ db.rpcError = { message: 'delivery_in_progress' };+ await expect(toWordPress()).rejects.toMatchObject({+ code: 'in_progress',+ message: 'A page is already being sent to WordPress. Wait for it, then send again.',+ });+ });++ it('stops a batch once WordPress refuses the sign-in, closing the rest with the reason', async () => {+ vi.useFakeTimers();+ db.wordpress = connection;+ 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)];+ sendToWordPress.mockResolvedValue({+ taken: false,+ failure: 'WordPress refused the user or the Application Password.',+ refused: true,+ });+ await toWordPress([page(), second]);+ await vi.runAllTimersAsync();+ expect(sendToWordPress).toHaveBeenCalledTimes(1);+ const closed = db.updates.filter(+ (u) =>+ u.table === 'content_draft_deliveries' &&+ u.update.error === 'WordPress refused the user or the Application Password.',+ );+ expect(closed).toHaveLength(2);+ });+});diff --git a/server/src/middleware/subscription.js b/server/src/middleware/subscription.jsindex 6202000c9..6e46fdbb0 100644--- a/server/src/middleware/subscription.js+++ b/server/src/middleware/subscription.js@@ -58,6 +58,9 @@ export const COST_STOPPING = [{ method: 'DELETE', path: /^\/integrations\/[^/]+\/?$/ },// Disconnects a brand's Webflow site (cms.js).{ method: 'DELETE', path: /^\/cms\/brands\/[^/]+\/webflow\/?$/ },+ // Disconnects a brand's WordPress site (cms-wordpress.js): its Application+ // Password is revoked where the site allows.+ { method: 'DELETE', path: /^\/cms\/brands\/[^/]+\/wordpress\/?$/ },// Removes an AI-bot log connection (bots.js): its secret stops working.{ method: 'DELETE', path: /^\/bots\/connections\/[^/]+\/[^/]+\/?$/ },// Removes a store from the catalog (catalog.js): its sign-in is revoked atdiff --git a/server/src/middleware/subscription.test.js b/server/src/middleware/subscription.test.jsindex 13ea108aa..762cf59ae 100644--- a/server/src/middleware/subscription.test.js+++ b/server/src/middleware/subscription.test.js@@ -157,6 +157,7 @@ describe('requireActiveSubscription', () => {['DELETE', '/integrations/google-search-console'],['DELETE', '/integrations/google-analytics'],['DELETE', '/cms/brands/b1/webflow'],+ ['DELETE', '/cms/brands/b1/wordpress'],['DELETE', '/bots/connections/b1/c1'],// A store's sign-in is revoked at the store as it is removed.['DELETE', '/catalog/sources/9b2c1e40-0000-4000-8000-000000000003'],@@ -181,6 +182,8 @@ describe('requireActiveSubscription', () => {['POST', '/integrations/google-search-console/sync'],['PUT', '/cms/brands/b1/webflow'],['POST', '/cms/brands/b1/webflow'],+ ['POST', '/cms/brands/b1/wordpress'],+ ['DELETE', '/cms/brands/b1/wordpress/extra'],['POST', '/bots/connections/b1'],['DELETE', '/bots/connections/b1'],['POST', '/catalog/sources'],@@ -194,7 +197,7 @@ describe('requireActiveSubscription', () => {expect(res.status).toHaveBeenCalledWith(402);}// Both Google disconnects are one route.- expect(COST_STOPPING).toHaveLength(6);+ expect(COST_STOPPING).toHaveLength(7);});it('lets an organization off a plan delete a brand, and nothing near it', async () => {diff --git a/server/src/routes/cms-wordpress.js b/server/src/routes/cms-wordpress.jsnew file mode 100644index 000000000..355aedb90--- /dev/null+++ b/server/src/routes/cms-wordpress.js@@ -0,0 +1,193 @@+import { Router } from 'express';+import { z } from 'zod';+import supabaseAdmin from '../config/supabase.js';+import { assertBrandAccess } from '../lib/access.js';+import { credentialsConfigured } from '../lib/catalog/credentials.js';+import { readCmsCredentials, saveCmsCredentials } from '../lib/cms/credentials.js';+import { WordPressError, checkSite, revokePassword, siteAddress } from '../lib/cms/wordpress.js';+import { cmsLimiter } from '../middleware/rate-limiter.js';+import { assertWriter, brandOf } from './cms.js';++/**+ * A brand's WordPress connection for Send to CMS (#1331, phase 2; 00294).+ * Members read a brand's connection; admins and managers connect the+ * brand's site with a user's Application Password, and disconnect:+ * GET /api/cms/brands/:brandId/wordpress the connection, or none+ * POST /api/cms/brands/:brandId/wordpress { siteUrl, username, password } connect, or replace the sign-in+ * DELETE /api/cms/brands/:brandId/wordpress disconnect+ * The password passes through here once: it is checked with the site, then+ * sealed by the API (lib/cms/credentials.js). It is never stored in the+ * clear, logged or sent back.+ */++const router = Router();++const PROVIDER = 'wordpress';+const COLUMNS = 'id, brand_id, status, site_url, site_name, account, created_at, updated_at';++const connectInput = z.object({+ siteUrl: z.string().trim().min(1).max(2048),+ // A WordPress user name, or the user's e-mail: WordPress takes either.+ username: z.string().trim().min(1).max(200),+ // An Application Password: 24 letters and digits, shown in groups of four.+ password: z.string().trim().min(16).max(200),+});++async function connectionOf(id) {+ const { data, error } = await supabaseAdmin+ .from('brand_cms_connections')+ .select(COLUMNS)+ .eq('brand_id', id)+ .eq('provider', PROVIDER)+ .maybeSingle();+ if (error) throw new Error(error.message);+ return data;+}++/** The connection as the web shows it: never the password. */+const shape = (row) =>+ row+ ? {+ status: row.status,+ siteUrl: row.site_url,+ siteName: row.site_name,+ account: row.account,+ connectedAt: row.created_at,+ updatedAt: row.updated_at,+ }+ : null;++/**+ * Whether a new sign-in replaces the kept one: another site, user or+ * password (its spaces aside, as WordPress reads it). The same one typed+ * again isn't revoked.+ */+function replaced(before, old, site, credentials) {+ const bare = (password) => String(password ?? '').replace(/\s+/g, '');+ return (+ before.site_url !== site ||+ old.username !== credentials.username ||+ bare(old.password) !== bare(credentials.password)+ );+}++const WORDPRESS_STATUS = { invalid: 400, unreachable: 502, failed: 502 };++/** Answers a failure; logged by name only, since a message may quote what the person typed. */+function fail(req, res, err, what) {+ if (err instanceof WordPressError) {+ return res+ .status(WORDPRESS_STATUS[err.code] ?? 409)+ .json({ error: err.message, code: err.code });+ }+ if (err?.status && err.status < 500) {+ return res.status(err.status).json({+ error: err.message,+ code: err.code ?? (err.status === 404 ? 'not_found' : 'forbidden'),+ });+ }+ req.log.error({ err: { name: err?.name } }, what);+ return res.status(500).json({ error: 'Something went wrong with WordPress', code: 'failed' });+}++// The API keeps WordPress's sign-in encrypted, under CONNECTOR_CREDENTIALS_KEY.+const notConfigured = (res) =>+ res+ .status(503)+ .json({ error: 'WordPress is not set up on this server.', code: 'not_configured' });++// GET — the brand's connection, for every member (Settings, the Send dialog).+router.get('/brands/:brandId/wordpress', async (req, res) => {+ const id = brandOf(req, res);+ if (!id) return;+ try {+ await assertBrandAccess(id, req.user.id);+ return res.json({+ configured: credentialsConfigured(),+ connection: shape(await connectionOf(id)),+ });+ } catch (err) {+ return fail(req, res, err, 'cms wordpress read error');+ }+});++// POST — connect the brand's site, or replace its sign-in: checked with the site first.+router.post('/brands/:brandId/wordpress', cmsLimiter, async (req, res) => {+ const id = brandOf(req, res);+ if (!id) return;+ const parsed = connectInput.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res.status(400).json({+ error: 'Enter the site’s address, a user and its Application Password.',+ code: 'invalid',+ });+ }+ try {+ await assertWriter(id, req.user.id);+ if (!credentialsConfigured()) return notConfigured(res);+ const site = siteAddress(parsed.data.siteUrl);+ const credentials = { username: parsed.data.username, password: parsed.data.password };+ const { siteName, account } = await checkSite(site, credentials);+ // The sign-in this one replaces, if any: revoked below once the new one is kept.+ const before = await connectionOf(id);+ const old = before ? await readCmsCredentials(before.id).catch(() => null) : null;+ const { data: row, error } = await supabaseAdmin+ .from('brand_cms_connections')+ .upsert(+ {+ brand_id: id,+ provider: PROVIDER,+ site_url: site,+ site_name: siteName,+ account,+ status: 'connected',+ connected_by: req.user.id,+ updated_at: new Date().toISOString(),+ },+ { onConflict: 'brand_id,provider' },+ )+ .select(COLUMNS)+ .single();+ if (error) throw new Error(error.message);+ try {+ await saveCmsCredentials(row.id, credentials, { setBy: req.user.id });+ } catch (err) {+ // Connected without its sign-in, a send would use the one it replaced, on the new site.+ await supabaseAdmin+ .from('brand_cms_connections')+ .update({ status: 'auth_failed', updated_at: new Date().toISOString() })+ .eq('id', row.id);+ throw err;+ }+ if (old && replaced(before, old, site, credentials)) {+ await revokePassword(before.site_url, old);+ }+ return res.json({ connection: shape(row) });+ } catch (err) {+ return fail(req, res, err, 'cms wordpress connect error');+ }+});++// DELETE — disconnect: the Application Password revoked where the site allows, then the row (its sign-in with it).+router.delete('/brands/:brandId/wordpress', cmsLimiter, async (req, res) => {+ const id = brandOf(req, res);+ if (!id) return;+ try {+ await assertWriter(id, req.user.id);+ const row = await connectionOf(id);+ if (!row) return res.json({ success: true, revoked: false });+ let revoked = false;+ if (credentialsConfigured()) {+ const credentials = await readCmsCredentials(row.id).catch(() => null);+ if (credentials) revoked = await revokePassword(row.site_url, credentials);+ }+ const { error } = await supabaseAdmin.from('brand_cms_connections').delete().eq('id', row.id);+ if (error) throw new Error(error.message);+ // Not revoked: the person deletes the password under Users › Profile in WordPress.+ return res.json({ success: true, revoked });+ } catch (err) {+ return fail(req, res, err, 'cms wordpress disconnect error');+ }+});++export default router;diff --git a/server/src/routes/cms-wordpress.test.js b/server/src/routes/cms-wordpress.test.jsnew file mode 100644index 000000000..ac8137429--- /dev/null+++ b/server/src/routes/cms-wordpress.test.js@@ -0,0 +1,334 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * /api/cms/brands/:brandId/wordpress (Send to CMS, #1331 phase 2, 00294): a+ * brand's WordPress connection. Members read it; admins and managers connect+ * a site with a user's Application Password, checked with the site first,+ * and disconnect; the password is never kept in the clear, logged or sent+ * back.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';+const PASSWORD = 'abcd efgh ijkl mnop qrst uvwx';++let role;+let rows;+let configured;+const assertBrandAccess = vi.fn();+const credentials = { save: vi.fn(), read: vi.fn() };+const wordpress = { checkSite: vi.fn(), revokePassword: vi.fn() };++/** brand_cms_connections in memory: the queries the routes make. */+function table() {+ let filters = [];+ let write = null;+ const matches = (row) => filters.every(([col, value]) => row[col] === value);+ const run = () => {+ if (write?.kind === 'upsert') {+ const at = rows.findIndex(+ (r) => r.brand_id === write.row.brand_id && r.provider === write.row.provider,+ );+ const row = {+ id: 'cn1',+ created_at: '2026-10-27T10:00:00Z',+ ...(at >= 0 ? rows[at] : {}),+ ...write.row,+ };+ if (at >= 0) rows[at] = row;+ else rows.push(row);+ return [row];+ }+ if (write?.kind === 'update') {+ const hit = rows.filter(matches);+ for (const row of hit) Object.assign(row, write.fields);+ return hit;+ }+ if (write?.kind === 'delete') {+ const hit = rows.filter(matches);+ rows = rows.filter((r) => !matches(r));+ return hit;+ }+ return rows.filter(matches);+ };+ const answer = () => run().map((row) => ({ ...row }));+ const chain = {+ select: () => chain,+ eq: (col, value) => {+ filters.push([col, value]);+ return chain;+ },+ upsert: (row) => {+ write = { kind: 'upsert', row };+ return chain;+ },+ update: (fields) => {+ write = { kind: 'update', fields };+ return chain;+ },+ delete: () => {+ write = { kind: 'delete' };+ return chain;+ },+ maybeSingle: async () => ({ data: answer()[0] ?? null, error: null }),+ single: async () => ({ data: answer()[0] ?? null, error: null }),+ then: (resolve) => resolve({ data: answer(), error: null }),+ };+ return chain;+}++vi.mock('../config/supabase.js', () => ({+ default: {+ from: (name) => {+ if (name === 'profiles') {+ const chain = {+ select: () => chain,+ eq: () => chain,+ single: async () => ({ data: { role } }),+ };+ return chain;+ }+ return table();+ },+ },+}));+vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));+vi.mock('../lib/composio.js', () => ({+ isWebflowConfigured: () => false,+ connectWebflowToken: vi.fn(),+ deleteConnection: vi.fn(),+ forgetWebflowAccounts: vi.fn(),+}));+vi.mock('../lib/catalog/credentials.js', () => ({ credentialsConfigured: () => configured }));+vi.mock('../lib/cms/credentials.js', () => ({+ saveCmsCredentials: (...args) => credentials.save(...args),+ readCmsCredentials: (...args) => credentials.read(...args),+}));+vi.mock('../lib/cms/wordpress.js', async (importOriginal) => ({+ ...(await importOriginal()),+ checkSite: (...args) => wordpress.checkSite(...args),+ revokePassword: (...args) => wordpress.revokePassword(...args),+}));+vi.mock('../middleware/rate-limiter.js', () => ({ cmsLimiter: (_req, _res, next) => next() }));++const { default: router } = await import('./cms-wordpress.js');+const { WordPressError } = await import('../lib/cms/wordpress.js');++let server;+let base;+let logged;++beforeEach(async () => {+ role = 'manager';+ rows = [];+ logged = [];+ configured = true;+ assertBrandAccess.mockReset().mockResolvedValue({ orgId: 'o1' });+ credentials.save.mockReset().mockResolvedValue(undefined);+ credentials.read.mockReset().mockResolvedValue({ username: 'editor', password: PASSWORD });+ wordpress.checkSite+ .mockReset()+ .mockResolvedValue({ siteName: 'Acme Coffee Blog', account: 'editor' });+ wordpress.revokePassword.mockReset().mockResolvedValue(true);+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ const log = (...args) => logged.push(JSON.stringify(args));+ req.log = { error: log, warn: log, info: log };+ next();+ });+ app.use('/api/cms', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ base = `http://127.0.0.1:${server.address().port}/api/cms/brands/${BRAND}/wordpress`;+});++afterEach(() => new Promise((resolve) => server.close(resolve)));++const call = (method, body) =>+ fetch(base, {+ method,+ headers: { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+const input = { siteUrl: 'blog.acme.example/wp-admin/', username: 'editor', password: PASSWORD };+const connectedRow = (extra = {}) => ({+ id: 'cn1',+ brand_id: BRAND,+ provider: 'wordpress',+ status: 'connected',+ site_url: 'https://blog.acme.example',+ site_name: 'Acme Coffee Blog',+ account: 'editor',+ created_at: '2026-10-20T10:00:00Z',+ updated_at: '2026-10-20T10:00:00Z',+ ...extra,+});++describe('GET', () => {+ it('reads the brand’s connection for any member, and says whether the server can keep one', async () => {+ role = 'analyst';+ rows = [connectedRow()];+ const res = await call('GET');+ expect(await res.json()).toEqual({+ configured: true,+ connection: {+ status: 'connected',+ siteUrl: 'https://blog.acme.example',+ siteName: 'Acme Coffee Blog',+ account: 'editor',+ connectedAt: '2026-10-20T10:00:00Z',+ updatedAt: '2026-10-20T10:00:00Z',+ },+ });+ configured = false;+ rows = [];+ expect(await (await call('GET')).json()).toEqual({ configured: false, connection: null });+ });+});++describe('POST', () => {+ it('checks the site, keeps the connection and seals the sign-in, never answering with it', async () => {+ const res = await call('POST', input);+ expect(res.status).toBe(200);+ const text = await res.text();+ expect(text).not.toContain('abcd');+ expect(JSON.parse(text).connection).toMatchObject({+ status: 'connected',+ siteUrl: 'https://blog.acme.example',+ siteName: 'Acme Coffee Blog',+ account: 'editor',+ });+ expect(wordpress.checkSite).toHaveBeenCalledWith('https://blog.acme.example', {+ username: 'editor',+ password: PASSWORD,+ });+ expect(rows).toEqual([+ expect.objectContaining({+ brand_id: BRAND,+ provider: 'wordpress',+ site_url: 'https://blog.acme.example',+ status: 'connected',+ connected_by: 'u1',+ }),+ ]);+ expect(rows[0]).not.toHaveProperty('password');+ expect(credentials.save).toHaveBeenCalledWith(+ 'cn1',+ { username: 'editor', password: PASSWORD },+ { setBy: 'u1' },+ );+ });++ it('replaces a refused sign-in, connected again, and revokes the password it replaces', async () => {+ rows = [connectedRow({ status: 'auth_failed' })];+ const old = { username: 'editor', password: 'zzzz yyyy xxxx wwww vvvv uuuu' };+ credentials.read.mockResolvedValueOnce(old);+ await call('POST', input);+ expect(rows).toHaveLength(1);+ expect(rows[0].status).toBe('connected');+ expect(credentials.save.mock.calls[0][0]).toBe('cn1');+ expect(wordpress.revokePassword).toHaveBeenCalledWith('https://blog.acme.example', old);+ });++ it('revokes nothing when the same sign-in is typed again', async () => {+ rows = [connectedRow()];+ credentials.read.mockResolvedValueOnce({+ username: 'editor',+ password: PASSWORD.replace(/ /g, ''),+ });+ await call('POST', input);+ expect(wordpress.revokePassword).not.toHaveBeenCalled();+ });++ it('asks to connect again when the sign-in can’t be kept', async () => {+ credentials.save.mockRejectedValueOnce(new Error('brand_cms_credentials write: 42501'));+ const res = await call('POST', input);+ expect(res.status).toBe(500);+ expect(rows[0].status).toBe('auth_failed');+ expect(wordpress.revokePassword).not.toHaveBeenCalled();+ });++ it('keeps nothing when the site refuses, and says why in its words', async () => {+ wordpress.checkSite.mockRejectedValueOnce(+ new WordPressError('auth_failed', 'WordPress refused the user or the Application Password.'),+ );+ const res = await call('POST', input);+ expect(res.status).toBe(409);+ expect(await res.json()).toEqual({+ error: 'WordPress refused the user or the Application Password.',+ code: 'auth_failed',+ });+ expect(rows).toEqual([]);+ expect(credentials.save).not.toHaveBeenCalled();+ });++ it('refuses an http address before calling the site', async () => {+ const res = await call('POST', { ...input, siteUrl: 'http://blog.acme.example' });+ expect(res.status).toBe(400);+ expect((await res.json()).code).toBe('invalid');+ expect(wordpress.checkSite).not.toHaveBeenCalled();+ });++ it('asks for the three fields', async () => {+ for (const body of [{}, { ...input, password: 'short' }, { ...input, username: '' }]) {+ const res = await call('POST', body);+ expect(res.status).toBe(400);+ }+ expect(wordpress.checkSite).not.toHaveBeenCalled();+ });++ it('is for admins and managers', async () => {+ role = 'analyst';+ const res = await call('POST', input);+ expect(res.status).toBe(403);+ expect(wordpress.checkSite).not.toHaveBeenCalled();+ });++ it('says WordPress isn’t set up on a server that can’t keep a sign-in', async () => {+ configured = false;+ const res = await call('POST', input);+ expect(res.status).toBe(503);+ expect((await res.json()).code).toBe('not_configured');+ });++ it('logs a crash by name only', async () => {+ wordpress.checkSite.mockRejectedValueOnce(new Error(`bad ${PASSWORD}`));+ const res = await call('POST', input);+ expect(res.status).toBe(500);+ expect(logged.join('')).not.toContain('abcd');+ });+});++describe('DELETE', () => {+ it('revokes the Application Password, then removes the connection', async () => {+ rows = [connectedRow()];+ const res = await call('DELETE');+ expect(await res.json()).toEqual({ success: true, revoked: true });+ expect(wordpress.revokePassword).toHaveBeenCalledWith('https://blog.acme.example', {+ username: 'editor',+ password: PASSWORD,+ });+ expect(rows).toEqual([]);+ });++ it('removes the connection when the password can’t be revoked, and says so', async () => {+ rows = [connectedRow()];+ wordpress.revokePassword.mockResolvedValueOnce(false);+ expect(await (await call('DELETE')).json()).toEqual({ success: true, revoked: false });+ expect(rows).toEqual([]);+ rows = [connectedRow()];+ credentials.read.mockResolvedValueOnce(null);+ expect(await (await call('DELETE')).json()).toEqual({ success: true, revoked: false });+ expect(rows).toEqual([]);+ });++ it('is for admins and managers', async () => {+ role = 'analyst';+ rows = [connectedRow()];+ expect((await call('DELETE')).status).toBe(403);+ expect(rows).toHaveLength(1);+ });+});diff --git a/server/src/routes/cms.js b/server/src/routes/cms.jsindex 02e3624aa..2bccef4c1 100644--- a/server/src/routes/cms.js+++ b/server/src/routes/cms.js@@ -65,7 +65,8 @@ function routeError(message, status, code) {return err;}-async function assertWriter(id, userId) {+/** Admins and managers of the brand's organization only (WordPress's routes too, cms-wordpress.js). */+export async function assertWriter(id, userId) {await assertBrandAccess(id, userId);const { data: profile } = await supabaseAdmin.from('profiles')@@ -178,7 +179,7 @@ const notConfigured = (res) =>res.status(503).json({ error: 'Webflow is not set up on this server.', code: 'not_configured' });/** The brand from the path, or a 400. */-function brandOf(req, res) {+export function brandOf(req, res) {const parsed = brandId.safeParse(req.params.brandId);if (!parsed.success) {res.status(400).json({ error: 'Invalid brand', code: 'invalid' });diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.jsindex b201f7cc4..0fa987e77 100644--- a/server/src/routes/content-drafts.js+++ b/server/src/routes/content-drafts.js@@ -22,7 +22,7 @@ import { PlanLimitError } from '../lib/plan-guard.js';* (CE-018); Hand off has it fix the page's open Quality checks (CE-051);* 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 or its Webflow collection (#1331).+ * Send to CMS sends pages to the brand's webhook, its Webflow collection or its WordPress site (#1331).*/const router = Router();@@ -48,7 +48,7 @@ async function assertSender(userId) {/*** POST /api/content-drafts/send- * Body: { brandId, target?: 'webhook' | 'webflow', pages: [{ draftId, title, slug, metaTitle, metaDescription, html, author, featuredImage }] }+ * Body: { brandId, target?: 'webhook' | 'webflow' | 'wordpress', 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 }.*/diff --git a/server/src/routes/index.js b/server/src/routes/index.jsindex a35d8de1c..ed82f105a 100644--- a/server/src/routes/index.js+++ b/server/src/routes/index.js@@ -18,6 +18,7 @@ import billingRoutes from './billing.js';import brandFactRoutes from './brand-facts.js';import catalogRoutes from './catalog.js';import cmsRoutes from './cms.js';+import cmsWordPressRoutes from './cms-wordpress.js';const router = Router();@@ -40,6 +41,7 @@ router.use('/billing', billingRoutes);router.use('/brand-facts', brandFactRoutes);router.use('/catalog', catalogRoutes);router.use('/cms', cmsRoutes);+router.use('/cms', cmsWordPressRoutes);router.get('/health', (req, res) => {res.json({ status: 'ok', user: req.user?.id });diff --git a/supabase/migrations/00294_cms_wordpress.sql b/supabase/migrations/00294_cms_wordpress.sqlnew file mode 100644index 000000000..9230701bd--- /dev/null+++ b/supabase/migrations/00294_cms_wordpress.sql@@ -0,0 +1,150 @@+-- ============================================================================+-- 00294: WordPress for Send to CMS (#1331, phase 2)+-- ============================================================================+-- After Webflow (00283, 00284), a brand connects its WordPress site: the+-- site's address, a user and an Application Password (WordPress 5.6+, made+-- under Users › Profile). Pages go to it through the REST API as draft posts.+--+-- * brand_cms_connections takes provider 'wordpress'. Composio's ids are+-- Webflow's only (Composio keeps its token); a WordPress connection has+-- the site's address (`site_url`), its name (`site_name`) and the user+-- it signs in as (`account`).+-- * brand_cms_credentials: the connection's sign-in (the user and the+-- Application Password), encrypted by the API as a store's is+-- (catalog_source_credentials, 00282): AES-256-GCM under+-- CONNECTOR_CREDENTIALS_KEY, bound to the connection's id. Service role+-- only; removed with its connection.+-- * content_draft_deliveries.target takes 'wordpress'. `target_collection`+-- keeps the site's address the post was written to, as it keeps+-- Webflow's collection: a page sent again updates its post on that site+-- only (two sites in folders of one domain number their posts each from+-- 1), so it takes an address's length now.+-- * reserve_content_deliveries: as 00284, a page already queued for the+-- same CMS (Webflow or WordPress) isn't sent there again meanwhile.++alter table public.brand_cms_connections+ drop constraint if exists brand_cms_connections_provider_check,+ add constraint brand_cms_connections_provider_check+ check (provider in ('webflow', 'wordpress')),+ alter column composio_account_id drop not null,+ alter column composio_entity_id drop not null,+ add column if not exists site_url text+ check (site_url is null or (char_length(site_url) <= 2048 and site_url ~* '^https://')),+ add column if not exists account text+ check (account is null or char_length(account) between 1 and 200);++alter table public.brand_cms_connections+ drop constraint if exists brand_cms_connections_provider_fields,+ add constraint brand_cms_connections_provider_fields check (+ case provider+ when 'webflow' then composio_account_id is not null and composio_entity_id is not null+ when 'wordpress' then site_url is not null and account is not null+ else false+ end+ );++comment on column public.brand_cms_connections.site_url is+ 'WordPress (00294): the site''s address, its REST API at /wp-json/.';+comment on column public.brand_cms_connections.account is+ 'WordPress (00294): the user the connection signs in as, with an Application Password (kept in brand_cms_credentials).';++create table if not exists public.brand_cms_credentials (+ connection_id uuid primary key references public.brand_cms_connections(id) on delete cascade,+ secret text not null check (char_length(secret) between 1 and 16384),+ set_at timestamptz not null default now(),+ set_by uuid references public.profiles(id) on delete set null+);++alter table public.brand_cms_credentials enable row level security;+revoke all on table public.brand_cms_credentials from public, anon, authenticated;+grant all on table public.brand_cms_credentials to service_role;++comment on table public.brand_cms_credentials is+ 'Send to CMS (#1331, 00294): a CMS connection''s sign-in (WordPress: the user and the Application Password), encrypted by the API (AES-256-GCM, bound to the connection id). Service role only; removed with its connection.';++alter table public.content_draft_deliveries+ drop constraint if exists content_draft_deliveries_target_check,+ add constraint content_draft_deliveries_target_check+ check (target in ('webhook', 'webflow', 'wordpress')),+ drop constraint if exists content_draft_deliveries_target_collection_check,+ add constraint content_draft_deliveries_target_collection_check+ check (target_collection is null or char_length(target_collection) between 1 and 2048);++comment on column public.content_draft_deliveries.target is+ 'Where the page was sent (00284, 00294): the brand''s webhook, its Webflow collection or its WordPress site (00283).';+comment on column public.content_draft_deliveries.target_collection is+ 'The Webflow collection (00284), or the WordPress site''s address (00294), the page''s item or post was written to; its id is external_id.';++-- ----------------------------------------------------------------------------+-- As 00284, with no second send of a page to the same CMS while one is queued.+-- ----------------------------------------------------------------------------+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,+ p_target text default 'webhook'+)+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;++ -- Under the lock, so two sends of one page can't both pass: both would+ -- make an item (Webflow refuses the second on its slug) or a post.+ if p_target in ('webflow', 'wordpress') and exists (+ select 1+ from public.content_draft_deliveries d+ join jsonb_array_elements(p_items) as items(item)+ on d.draft_id = (item ->> 'draft_id')::uuid+ where d.organization_id = p_organization_id+ and d.target = p_target+ and d.status = 'queued'+ ) then+ raise exception 'delivery_in_progress' using errcode = 'P0001';+ end if;++ return query+ insert into public.content_draft_deliveries+ (organization_id, brand_id, draft_id, sent_by, batch_id, title, slug, target)+ 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), ''),+ coalesce(p_target, 'webhook')+ 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, text)+ from public, anon, authenticated;+grant execute on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer, text)+ to service_role;++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 0fb3b3621..705a75a4c 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -41598,6 +41598,160 @@ comment on function public.approve_action_task_review(uuid, text, jsonb) isnotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00294_cms_wordpress.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00294: WordPress for Send to CMS (#1331, phase 2)+-- ============================================================================+-- After Webflow (00283, 00284), a brand connects its WordPress site: the+-- site's address, a user and an Application Password (WordPress 5.6+, made+-- under Users › Profile). Pages go to it through the REST API as draft posts.+--+-- * brand_cms_connections takes provider 'wordpress'. Composio's ids are+-- Webflow's only (Composio keeps its token); a WordPress connection has+-- the site's address (`site_url`), its name (`site_name`) and the user+-- it signs in as (`account`).+-- * brand_cms_credentials: the connection's sign-in (the user and the+-- Application Password), encrypted by the API as a store's is+-- (catalog_source_credentials, 00282): AES-256-GCM under+-- CONNECTOR_CREDENTIALS_KEY, bound to the connection's id. Service role+-- only; removed with its connection.+-- * content_draft_deliveries.target takes 'wordpress'. `target_collection`+-- keeps the site's address the post was written to, as it keeps+-- Webflow's collection: a page sent again updates its post on that site+-- only (two sites in folders of one domain number their posts each from+-- 1), so it takes an address's length now.+-- * reserve_content_deliveries: as 00284, a page already queued for the+-- same CMS (Webflow or WordPress) isn't sent there again meanwhile.++alter table public.brand_cms_connections+ drop constraint if exists brand_cms_connections_provider_check,+ add constraint brand_cms_connections_provider_check+ check (provider in ('webflow', 'wordpress')),+ alter column composio_account_id drop not null,+ alter column composio_entity_id drop not null,+ add column if not exists site_url text+ check (site_url is null or (char_length(site_url) <= 2048 and site_url ~* '^https://')),+ add column if not exists account text+ check (account is null or char_length(account) between 1 and 200);++alter table public.brand_cms_connections+ drop constraint if exists brand_cms_connections_provider_fields,+ add constraint brand_cms_connections_provider_fields check (+ case provider+ when 'webflow' then composio_account_id is not null and composio_entity_id is not null+ when 'wordpress' then site_url is not null and account is not null+ else false+ end+ );++comment on column public.brand_cms_connections.site_url is+ 'WordPress (00294): the site''s address, its REST API at /wp-json/.';+comment on column public.brand_cms_connections.account is+ 'WordPress (00294): the user the connection signs in as, with an Application Password (kept in brand_cms_credentials).';++create table if not exists public.brand_cms_credentials (+ connection_id uuid primary key references public.brand_cms_connections(id) on delete cascade,+ secret text not null check (char_length(secret) between 1 and 16384),+ set_at timestamptz not null default now(),+ set_by uuid references public.profiles(id) on delete set null+);++alter table public.brand_cms_credentials enable row level security;+revoke all on table public.brand_cms_credentials from public, anon, authenticated;+grant all on table public.brand_cms_credentials to service_role;++comment on table public.brand_cms_credentials is+ 'Send to CMS (#1331, 00294): a CMS connection''s sign-in (WordPress: the user and the Application Password), encrypted by the API (AES-256-GCM, bound to the connection id). Service role only; removed with its connection.';++alter table public.content_draft_deliveries+ drop constraint if exists content_draft_deliveries_target_check,+ add constraint content_draft_deliveries_target_check+ check (target in ('webhook', 'webflow', 'wordpress')),+ drop constraint if exists content_draft_deliveries_target_collection_check,+ add constraint content_draft_deliveries_target_collection_check+ check (target_collection is null or char_length(target_collection) between 1 and 2048);++comment on column public.content_draft_deliveries.target is+ 'Where the page was sent (00284, 00294): the brand''s webhook, its Webflow collection or its WordPress site (00283).';+comment on column public.content_draft_deliveries.target_collection is+ 'The Webflow collection (00284), or the WordPress site''s address (00294), the page''s item or post was written to; its id is external_id.';++-- ----------------------------------------------------------------------------+-- As 00284, with no second send of a page to the same CMS while one is queued.+-- ----------------------------------------------------------------------------+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,+ p_target text default 'webhook'+)+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;++ -- Under the lock, so two sends of one page can't both pass: both would+ -- make an item (Webflow refuses the second on its slug) or a post.+ if p_target in ('webflow', 'wordpress') and exists (+ select 1+ from public.content_draft_deliveries d+ join jsonb_array_elements(p_items) as items(item)+ on d.draft_id = (item ->> 'draft_id')::uuid+ where d.organization_id = p_organization_id+ and d.target = p_target+ and d.status = 'queued'+ ) then+ raise exception 'delivery_in_progress' using errcode = 'P0001';+ end if;++ return query+ insert into public.content_draft_deliveries+ (organization_id, brand_id, draft_id, sent_by, batch_id, title, slug, target)+ 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), ''),+ coalesce(p_target, 'webhook')+ 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, text)+ from public, anon, authenticated;+grant execute on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer, text)+ to service_role;++notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00296_catalog_item_issues.sql-- ─────────────────────────────────────────────────────────────────────────