Skip to content

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

feat(content): connect a brand's Webflow site for Send to CMS (Send to CMS #1331, phase 2 part 1: Webflow connection) (#1503)

Cihand4bbb21c400f
diff --git a/server/.env.example b/server/.env.example
index d460f6fb4..ed9b73c1a 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -177,6 +177,12 @@ AI_VOLUME_MULTIPLIER=0.45
# Properties past it stay listed and manually selectable.
# COMPOSIO_GA_MAX_PROPERTIES=500
# COMPOSIO_GA_STREAM_LOOKUPS=100
+# Send to CMS → Webflow (#1331, phase 2): an auth config of the Webflow
+# toolkit with API-key auth (Webflow has no Composio-managed OAuth app). Each
+# brand connects its own site token in Settings → Integrations; Composio
+# keeps the token. Without it, Webflow shows "not configured".
+# COMPOSIO_WEBFLOW_AUTH_CONFIG_ID=
+# COMPOSIO_WEBFLOW_TOOLKIT_VERSION=20260826_00
# Store connections for the product catalog (#1263, CONNECTORS.md): the key
# a store's sign-in is encrypted with, 32 bytes in base64
diff --git a/server/src/lib/cms/webflow.js b/server/src/lib/cms/webflow.js
new file mode 100644
index 000000000..217661a3c
--- /dev/null
+++ b/server/src/lib/cms/webflow.js
@@ -0,0 +1,214 @@
+import { executeWebflowTool } from '../composio.js';
+
+/**
+ * Webflow for Send to CMS (#1331, phase 2): a brand's site, its collections
+ * and their fields, read through Composio with the brand's site token
+ * (composio.js), and which of a collection's fields takes each part of a
+ * page. An item's name and slug always go to Webflow's own `name` and
+ * `slug`; the rest is the brand's field map (brand_cms_connections, 00283).
+ */
+
+/** The parts of a page a field map places, and the field types each may go to. */
+const PART_TYPES = {
+ body: ['RichText'],
+ metaTitle: ['PlainText'],
+ metaDescription: ['PlainText'],
+ jsonLd: ['PlainText'],
+};
+const PAGE_PARTS = Object.keys(PART_TYPES);
+/** Webflow's own fields: every item has them, and Send to CMS always fills them. */
+const OWN_FIELDS = new Set(['name', 'slug']);
+
+/** A Webflow call that didn't go, with the code the web names to the person. */
+export class WebflowError extends Error {
+ /** @param {'auth_failed'|'missing_scopes'|'no_access'|'not_found'|'failed'} code */
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+/** Webflow's words for a token without the scopes asked. */
+const MISSING_SCOPES = /missing[_ ]scopes?/i;
+/** The brand's account gone at Composio: connected again, it works. */
+const ACCOUNT_GONE = /connected[_ ]?account[_ ]?not[_ ]?found/i;
+/** A token Webflow refuses: a 401, never a 403 (a site or collection the token doesn't reach). */
+const REFUSED = /\b401\b|unauthori[sz]ed|not[_ ]authori[sz]ed|invalid[_ ](api[_ ])?(token|key)/i;
+const FORBIDDEN = /\b403\b|forbidden/i;
+const NOT_FOUND = /\b404\b|not[_ ]found/i;
+
+/**
+ * A Webflow tool's data. What went wrong is told in our words only: the
+ * error Composio passes on is read, never shown or logged, since it may
+ * quote the request. Only a refused token (or the brand's account gone)
+ * is auth_failed, which asks the person to connect again.
+ */
+async function run(slug, account, args) {
+ try {
+ return await executeWebflowTool(slug, account, args);
+ } catch (err) {
+ const said = `${err?.name ?? ''} ${err?.message ?? ''}`;
+ if (MISSING_SCOPES.test(said)) {
+ throw new WebflowError(
+ 'missing_scopes',
+ 'The site token needs the Sites (read) and CMS (read and write) scopes',
+ );
+ }
+ if (ACCOUNT_GONE.test(said) || REFUSED.test(said)) {
+ throw new WebflowError('auth_failed', 'Webflow refused the site token');
+ }
+ if (FORBIDDEN.test(said)) {
+ throw new WebflowError('no_access', 'The site token doesn’t reach this site or collection');
+ }
+ if (NOT_FOUND.test(said)) {
+ throw new WebflowError('not_found', 'Webflow has no such site or collection');
+ }
+ throw new WebflowError('failed', 'Webflow could not be reached');
+ }
+}
+
+/** The list a Webflow answer holds under `key`, however Composio wraps it. */
+function listOf(data, key) {
+ for (const value of [data?.[key], data?.response_data?.[key], data?.data?.[key], data]) {
+ if (Array.isArray(value)) return value;
+ }
+ return [];
+}
+
+/** The object a Webflow answer is, however Composio wraps it. */
+const objectOf = (data) => data?.response_data ?? data?.data ?? data ?? {};
+
+const text = (value, max = 300) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
+
+/** The sites the token reaches: a site token reaches its own. */
+export async function listSites(account) {
+ const data = await run('WEBFLOW_LIST_WEBFLOW_SITES', account, {});
+ return listOf(data, 'sites')
+ .filter((site) => typeof site?.id === 'string' && site.id)
+ .map((site) => ({
+ id: site.id,
+ name: text(site.displayName) || text(site.shortName) || site.id,
+ }));
+}
+
+/** A site's CMS collections. */
+export async function listCollections(account, siteId) {
+ const data = await run('WEBFLOW_LIST_COLLECTIONS', account, { site_id: siteId });
+ return listOf(data, 'collections')
+ .filter((c) => typeof c?.id === 'string' && c.id)
+ .map((c) => ({
+ id: c.id,
+ name: text(c.displayName) || text(c.slug) || c.id,
+ slug: text(c.slug),
+ }));
+}
+
+/** A collection's fields a person can fill: slug, name, type and whether it's required. */
+export async function getCollection(account, collectionId) {
+ const collection = objectOf(
+ await run('WEBFLOW_GET_COLLECTION', account, { collection_id: collectionId }),
+ );
+ const fields = (Array.isArray(collection.fields) ? collection.fields : [])
+ .filter((f) => typeof f?.slug === 'string' && f.slug && f.isEditable !== false)
+ .map((f) => ({
+ slug: f.slug,
+ name: text(f.displayName) || f.slug,
+ type: typeof f.type === 'string' ? f.type : '',
+ required: f.isRequired === true,
+ }));
+ return {
+ id: typeof collection.id === 'string' && collection.id ? collection.id : collectionId,
+ name: text(collection.displayName) || text(collection.slug) || collectionId,
+ fields,
+ };
+}
+
+/** The words a field's slug or name is read for, by part: the first field that has them is suggested. */
+const HINTS = {
+ body: [/(^|-)(post-)?body($|-)/, /content/, /article/, /rich/],
+ metaTitle: [/(meta|seo)-?title/],
+ metaDescription: [/(meta|seo)-?desc/, /summary/, /excerpt/, /description/],
+ jsonLd: [/json-?ld/, /schema/, /structured/],
+};
+
+/**
+ * The field map a collection's fields suggest: for each part, the first
+ * field of a type it may go to whose slug (or name) reads as that part, one
+ * field a part; a page's body falls back to the collection's first rich text.
+ */
+export function suggestFieldMap(fields) {
+ const map = {};
+ const taken = new Set();
+ const words = (f) => `${f.slug} ${f.name.toLowerCase().replace(/\s+/g, '-')}`;
+ for (const part of PAGE_PARTS) {
+ const fits = fields.filter(
+ (f) => PART_TYPES[part].includes(f.type) && !OWN_FIELDS.has(f.slug) && !taken.has(f.slug),
+ );
+ let pick = null;
+ for (const hint of HINTS[part]) {
+ pick = fits.find((f) => hint.test(words(f)));
+ if (pick) break;
+ }
+ if (!pick && part === 'body') pick = fits[0] ?? null;
+ if (pick) {
+ map[part] = pick.slug;
+ taken.add(pick.slug);
+ }
+ }
+ return map;
+}
+
+/**
+ * The parts every page has: its meta title falls back to its title, its
+ * meta description to its opening words. A page may have no JSON-LD, so
+ * that field can't be one the collection requires.
+ */
+const ALWAYS_FILLED = new Set(['body', 'metaTitle', 'metaDescription']);
+
+/**
+ * Whether a field map fits the collection: a page's body has a rich text
+ * field, each part a field of its own of a type it may go to, and every
+ * field the collection requires is one Send to CMS always fills.
+ *
+ * @returns {{ ok: true, map: Record<string, string> } | { ok: false, problems: string[] }}
+ */
+export function checkFieldMap(fieldMap, fields) {
+ const bySlug = new Map(fields.map((f) => [f.slug, f]));
+ const problems = [];
+ const map = {};
+ const used = new Set();
+ for (const part of PAGE_PARTS) {
+ const slug = fieldMap?.[part];
+ if (slug === undefined || slug === null || slug === '') continue;
+ const field = bySlug.get(slug);
+ if (!field || OWN_FIELDS.has(slug)) {
+ problems.push(`${part}: the collection has no field "${String(slug).slice(0, 100)}"`);
+ } else if (!PART_TYPES[part].includes(field.type)) {
+ problems.push(
+ `${part}: ${field.name} is ${field.type || 'another type'}, not ${PART_TYPES[part].join(' or ')}`,
+ );
+ } else if (used.has(slug)) {
+ problems.push(`${part}: ${field.name} already takes another part`);
+ } else {
+ map[part] = slug;
+ used.add(slug);
+ }
+ }
+ if (!map.body && !problems.some((p) => p.startsWith('body:'))) {
+ problems.push('body: pick the rich text field a page goes to');
+ }
+ const filled = new Set(
+ Object.entries(map)
+ .filter(([part]) => ALWAYS_FILLED.has(part))
+ .map(([, slug]) => slug),
+ );
+ const unfilled = fields.filter(
+ (f) => f.required && !OWN_FIELDS.has(f.slug) && !filled.has(f.slug),
+ );
+ if (unfilled.length) {
+ problems.push(
+ `The collection requires ${unfilled.map((f) => f.name).join(', ')}, which Send to CMS doesn’t fill: make ${unfilled.length === 1 ? 'it' : 'them'} optional in Webflow, or pick another collection`,
+ );
+ }
+ return problems.length ? { ok: false, problems } : { ok: true, map };
+}
diff --git a/server/src/lib/cms/webflow.test.js b/server/src/lib/cms/webflow.test.js
new file mode 100644
index 000000000..eb24d63a8
--- /dev/null
+++ b/server/src/lib/cms/webflow.test.js
@@ -0,0 +1,195 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** Webflow for Send to CMS (#1331, phase 2): reading a site through Composio, and the field map. */
+
+const executeWebflowTool = vi.fn();
+vi.mock('../composio.js', () => ({
+ executeWebflowTool: (...args) => executeWebflowTool(...args),
+}));
+
+const { WebflowError, checkFieldMap, getCollection, listCollections, listSites, suggestFieldMap } =
+ await import('./webflow.js');
+
+const account = { entityId: 'brand_b1', accountId: 'ca_1' };
+
+// A Webflow blog collection's fields, as its template makes them.
+const blog = [
+ { slug: 'name', name: 'Name', type: 'PlainText', required: true },
+ { slug: 'slug', name: 'Slug', type: 'PlainText', required: true },
+ { slug: 'post-body', name: 'Post Body', type: 'RichText', required: false },
+ { slug: 'post-summary', name: 'Post Summary', type: 'PlainText', required: false },
+ { slug: 'main-image', name: 'Main Image', type: 'Image', required: false },
+ { slug: 'featured', name: 'Featured?', type: 'Switch', required: false },
+];
+
+beforeEach(() => executeWebflowTool.mockReset());
+
+describe('reading the site', () => {
+ it('lists the token’s sites, however Composio wraps them', async () => {
+ executeWebflowTool.mockResolvedValueOnce({
+ sites: [
+ { id: 's1', displayName: 'Ansvisor', shortName: 'ansvisor' },
+ { displayName: 'no id' },
+ ],
+ });
+ expect(await listSites(account)).toEqual([{ id: 's1', name: 'Ansvisor' }]);
+ expect(executeWebflowTool).toHaveBeenCalledWith('WEBFLOW_LIST_WEBFLOW_SITES', account, {});
+
+ executeWebflowTool.mockResolvedValueOnce({
+ response_data: { sites: [{ id: 's2', shortName: 'acme' }] },
+ });
+ expect(await listSites(account)).toEqual([{ id: 's2', name: 'acme' }]);
+ });
+
+ it('lists a site’s collections, and a collection’s fields a person can fill', async () => {
+ executeWebflowTool.mockResolvedValueOnce({
+ collections: [{ id: 'c1', displayName: 'Blog Posts', slug: 'post' }],
+ });
+ expect(await listCollections(account, 's1')).toEqual([
+ { id: 'c1', name: 'Blog Posts', slug: 'post' },
+ ]);
+ expect(executeWebflowTool).toHaveBeenLastCalledWith('WEBFLOW_LIST_COLLECTIONS', account, {
+ site_id: 's1',
+ });
+
+ executeWebflowTool.mockResolvedValueOnce({
+ id: 'c1',
+ displayName: 'Blog Posts',
+ fields: [
+ {
+ slug: 'name',
+ displayName: 'Name',
+ type: 'PlainText',
+ isRequired: true,
+ isEditable: true,
+ },
+ { slug: 'post-body', displayName: 'Post Body', type: 'RichText', isEditable: true },
+ { slug: 'created-on', displayName: 'Created On', type: 'DateTime', isEditable: false },
+ ],
+ });
+ expect(await getCollection(account, 'c1')).toEqual({
+ id: 'c1',
+ name: 'Blog Posts',
+ fields: [
+ { slug: 'name', name: 'Name', type: 'PlainText', required: true },
+ { slug: 'post-body', name: 'Post Body', type: 'RichText', required: false },
+ ],
+ });
+ });
+
+ it('tells what went wrong in its own words, never Webflow’s', async () => {
+ const said = async (message) => {
+ executeWebflowTool.mockRejectedValueOnce(new Error(message));
+ return listSites(account).catch((err) => err);
+ };
+ const refused = await said('Request failed with status 401: token wf_secret_123 is not valid');
+ expect(refused).toBeInstanceOf(WebflowError);
+ expect(refused).toMatchObject({ code: 'auth_failed' });
+ expect(refused.message).not.toMatch(/wf_secret/);
+ expect(await said('{"code":"missing_scopes","message":"cms:write"}')).toMatchObject({
+ code: 'missing_scopes',
+ });
+ expect(await said('404 resource_not_found')).toMatchObject({ code: 'not_found' });
+ expect(await said('socket hang up')).toMatchObject({ code: 'failed' });
+ // A 403 is a site or collection the token doesn't reach, not a refused token.
+ expect(await said('Request failed with status 403: forbidden')).toMatchObject({
+ code: 'no_access',
+ });
+ // The brand's account gone at Composio: connecting again mends it.
+ executeWebflowTool.mockRejectedValueOnce(
+ Object.assign(new Error('No connected account ca_1'), {
+ name: 'ComposioConnectedAccountNotFoundError',
+ }),
+ );
+ expect(await listSites(account).catch((err) => err)).toMatchObject({ code: 'auth_failed' });
+ });
+});
+
+describe('suggestFieldMap', () => {
+ it('suggests the template’s fields by their names, one field a part', () => {
+ expect(suggestFieldMap(blog)).toEqual({ body: 'post-body', metaDescription: 'post-summary' });
+ expect(
+ suggestFieldMap([
+ ...blog,
+ { slug: 'seo-title', name: 'SEO Title', type: 'PlainText' },
+ { slug: 'meta-description', name: 'Meta Description', type: 'PlainText' },
+ { slug: 'schema-markup', name: 'Schema markup', type: 'PlainText' },
+ ]),
+ ).toEqual({
+ body: 'post-body',
+ metaTitle: 'seo-title',
+ metaDescription: 'meta-description',
+ jsonLd: 'schema-markup',
+ });
+ });
+
+ it('falls back to the first rich text for the body, and never suggests a field of another type', () => {
+ expect(
+ suggestFieldMap([
+ { slug: 'intro', name: 'Intro', type: 'RichText' },
+ { slug: 'summary-image', name: 'Summary image', type: 'Image' },
+ ]),
+ ).toEqual({ body: 'intro' });
+ expect(suggestFieldMap([{ slug: 'name', name: 'Name', type: 'PlainText' }])).toEqual({});
+ });
+});
+
+describe('checkFieldMap', () => {
+ it('keeps a map that fits the collection', () => {
+ expect(
+ checkFieldMap({ body: 'post-body', metaDescription: 'post-summary', jsonLd: '' }, blog),
+ ).toEqual({
+ ok: true,
+ map: { body: 'post-body', metaDescription: 'post-summary' },
+ });
+ });
+
+ it('names each part that doesn’t fit', () => {
+ const problems = (map, fields = blog) => checkFieldMap(map, fields).problems;
+ expect(problems({ body: 'post-summary' })).toEqual([
+ 'body: Post Summary is PlainText, not RichText',
+ ]);
+ expect(problems({ body: 'post-body', metaTitle: 'nope' })).toEqual([
+ 'metaTitle: the collection has no field "nope"',
+ ]);
+ expect(problems({ body: 'post-body', metaTitle: 'name' })).toEqual([
+ 'metaTitle: the collection has no field "name"',
+ ]);
+ expect(
+ problems({ body: 'post-body', metaTitle: 'post-summary', metaDescription: 'post-summary' }),
+ ).toEqual(['metaDescription: Post Summary already takes another part']);
+ expect(problems({ metaTitle: 'post-summary' })).toEqual([
+ 'body: pick the rich text field a page goes to',
+ ]);
+ });
+
+ it('refuses a collection that requires a field Send to CMS doesn’t fill', () => {
+ const fields = [
+ ...blog,
+ { slug: 'category', name: 'Category', type: 'Reference', required: true },
+ ];
+ expect(checkFieldMap({ body: 'post-body' }, fields).problems).toEqual([
+ 'The collection requires Category, which Send to CMS doesn’t fill: make it optional in Webflow, or pick another collection',
+ ]);
+ // A required field the map fills is fine.
+ expect(
+ checkFieldMap(
+ { body: 'post-body' },
+ blog.map((f) => (f.slug === 'post-body' ? { ...f, required: true } : f)),
+ ).ok,
+ ).toBe(true);
+ // A page's meta description always has words (its opening ones at least);
+ // its JSON-LD may be none.
+ const summaryRequired = blog.map((f) =>
+ f.slug === 'post-summary' ? { ...f, required: true } : f,
+ );
+ expect(
+ checkFieldMap({ body: 'post-body', metaDescription: 'post-summary' }, summaryRequired).ok,
+ ).toBe(true);
+ expect(
+ checkFieldMap({ body: 'post-body', jsonLd: 'post-summary' }, summaryRequired).problems,
+ ).toEqual([
+ 'The collection requires Post Summary, which Send to CMS doesn’t fill: make it optional in Webflow, or pick another collection',
+ ]);
+ });
+});
diff --git a/server/src/lib/composio.js b/server/src/lib/composio.js
index 55d025545..ccfe33c4b 100644
--- a/server/src/lib/composio.js
+++ b/server/src/lib/composio.js
@@ -1,4 +1,4 @@
-import { Composio } from '@composio/core';
+import { AuthScheme, Composio } from '@composio/core';
/**
* Composio managed-auth helper (#577, extended for Google Analytics in #658).
@@ -249,3 +249,68 @@ export async function runGaReport(entityId, propertyId, body) {
...body,
});
}
+
+// ─── Webflow (Send to CMS, #1331 phase 2) ───────────────────────────────────
+
+/**
+ * Webflow has no Composio-managed OAuth app, so a brand connects its site
+ * with a site token: an API-key connected account under the brand's own
+ * Composio user (a site token is one site's). Composio keeps the token; we
+ * keep the account's id (brand_cms_connections, 00283). Not in PROVIDERS:
+ * the shared connect flow above is the workspace's OAuth.
+ */
+const WEBFLOW_AUTH_CONFIG_ENV = 'COMPOSIO_WEBFLOW_AUTH_CONFIG_ID';
+
+/** Pinned as Search Console's is; manual tool execution rejects "latest". */
+const WEBFLOW_TOOLKIT_VERSION = process.env.COMPOSIO_WEBFLOW_TOOLKIT_VERSION || '20260826_00';
+
+export function isWebflowConfigured() {
+ return Boolean(process.env.COMPOSIO_API_KEY && process.env[WEBFLOW_AUTH_CONFIG_ENV]);
+}
+
+/**
+ * A connected account for a Webflow site token, under `entityId`. Returns
+ * its id; whether Webflow takes the token is the first tool call's to say.
+ * A new token is a second account until the first is removed (an API-key
+ * account is active whether Webflow takes its token or not), so more than
+ * one is allowed: forgetWebflowAccounts keeps the brand to one.
+ */
+export async function connectWebflowToken(entityId, token) {
+ const request = await getClient().connectedAccounts.initiate(
+ entityId,
+ process.env[WEBFLOW_AUTH_CONFIG_ENV],
+ { config: AuthScheme.APIKey({ api_key: token }), allowMultiple: true },
+ );
+ const id = request?.id ?? request?.connectedAccountId ?? null;
+ if (!id) throw new Error('Composio returned no connected account');
+ return id;
+}
+
+/**
+ * Removes the Webflow accounts under `entityId` but `keep` (none kept when
+ * it's null): the ones a replaced token, a refused one or a failed removal
+ * left. Throws when one can't be removed.
+ */
+export async function forgetWebflowAccounts(entityId, keep = null) {
+ const accounts = await getClient().connectedAccounts.list({
+ authConfigIds: [process.env[WEBFLOW_AUTH_CONFIG_ENV]],
+ userIds: [entityId],
+ });
+ for (const account of accounts.items ?? []) {
+ if (account.id && account.id !== keep) await deleteConnection(account.id);
+ }
+}
+
+/** A Webflow tool, run on one connected account; its data, or an error with Webflow's words. */
+export async function executeWebflowTool(slug, { entityId, accountId }, args) {
+ const result = await getClient().tools.execute(slug, {
+ userId: entityId,
+ connectedAccountId: accountId,
+ arguments: args,
+ version: WEBFLOW_TOOLKIT_VERSION,
+ });
+ if (result?.successful === false) {
+ throw new Error(result?.error || `${slug} failed`);
+ }
+ return result?.data ?? {};
+}
diff --git a/server/src/lib/composio.test.js b/server/src/lib/composio.test.js
new file mode 100644
index 000000000..688bb7cf7
--- /dev/null
+++ b/server/src/lib/composio.test.js
@@ -0,0 +1,87 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** Composio for Webflow (Send to CMS, #1331 phase 2): a brand's site token as an API-key account. */
+
+const sdk = {
+ initiate: vi.fn(),
+ list: vi.fn(),
+ delete: vi.fn(),
+ execute: vi.fn(),
+};
+vi.mock('@composio/core', () => ({
+ AuthScheme: { APIKey: (val) => ({ authScheme: 'API_KEY', val }) },
+ Composio: class {
+ connectedAccounts = {
+ initiate: (...args) => sdk.initiate(...args),
+ list: (...args) => sdk.list(...args),
+ delete: (...args) => sdk.delete(...args),
+ };
+ tools = { execute: (...args) => sdk.execute(...args) };
+ },
+}));
+
+const { connectWebflowToken, executeWebflowTool, forgetWebflowAccounts, isWebflowConfigured } =
+ await import('./composio.js');
+
+beforeEach(() => {
+ vi.stubEnv('COMPOSIO_API_KEY', 'test-composio-key');
+ vi.stubEnv('COMPOSIO_WEBFLOW_AUTH_CONFIG_ID', 'ac_webflow');
+ for (const fn of Object.values(sdk)) fn.mockReset();
+});
+
+afterAll(() => vi.unstubAllEnvs());
+
+describe('Webflow on Composio', () => {
+ it('is set up with the API key and the Webflow auth config', () => {
+ expect(isWebflowConfigured()).toBe(true);
+ vi.stubEnv('COMPOSIO_WEBFLOW_AUTH_CONFIG_ID', '');
+ expect(isWebflowConfigured()).toBe(false);
+ });
+
+ it('connects a token as one more API-key account of the brand: the one it replaces is still there', async () => {
+ sdk.initiate.mockResolvedValue({ id: 'ca_new', status: 'ACTIVE' });
+ expect(await connectWebflowToken('brand_b1', 'wf-token')).toBe('ca_new');
+ expect(sdk.initiate).toHaveBeenCalledWith('brand_b1', 'ac_webflow', {
+ config: { authScheme: 'API_KEY', val: { api_key: 'wf-token' } },
+ allowMultiple: true,
+ });
+ });
+
+ it('removes the brand’s Webflow accounts but the one kept', async () => {
+ sdk.list.mockResolvedValue({ items: [{ id: 'ca_old' }, { id: 'ca_new' }, { id: 'ca_left' }] });
+ await forgetWebflowAccounts('brand_b1', 'ca_new');
+ expect(sdk.list).toHaveBeenCalledWith({ authConfigIds: ['ac_webflow'], userIds: ['brand_b1'] });
+ expect(sdk.delete.mock.calls).toEqual([['ca_old'], ['ca_left']]);
+
+ sdk.delete.mockClear();
+ await forgetWebflowAccounts('brand_b1');
+ expect(sdk.delete).toHaveBeenCalledTimes(3);
+
+ sdk.delete.mockRejectedValueOnce(new Error('down'));
+ await expect(forgetWebflowAccounts('brand_b1')).rejects.toThrow('down');
+ });
+
+ it('runs a tool on the brand’s own account, pinned to a toolkit version', async () => {
+ sdk.execute.mockResolvedValueOnce({ successful: true, data: { sites: [] } });
+ expect(
+ await executeWebflowTool(
+ 'WEBFLOW_LIST_WEBFLOW_SITES',
+ {
+ entityId: 'brand_b1',
+ accountId: 'ca_new',
+ },
+ {},
+ ),
+ ).toEqual({ sites: [] });
+ expect(sdk.execute).toHaveBeenCalledWith('WEBFLOW_LIST_WEBFLOW_SITES', {
+ userId: 'brand_b1',
+ connectedAccountId: 'ca_new',
+ arguments: {},
+ version: '20260826_00',
+ });
+ sdk.execute.mockResolvedValueOnce({ successful: false, error: '401 Unauthorized' });
+ await expect(
+ executeWebflowTool('WEBFLOW_LIST_WEBFLOW_SITES', { entityId: 'b', accountId: 'a' }, {}),
+ ).rejects.toThrow('401 Unauthorized');
+ });
+});
diff --git a/server/src/middleware/rate-limiter.js b/server/src/middleware/rate-limiter.js
index 7553b8e83..0f86de8c1 100644
--- a/server/src/middleware/rate-limiter.js
+++ b/server/src/middleware/rate-limiter.js
@@ -131,6 +131,20 @@ export const catalogLimiter = rateLimit({
},
});
+// A brand's CMS connection (Send to CMS, #1331): each call reaches Webflow
+// through Composio, so a member's are few.
+export const cmsLimiter = rateLimit({
+ windowMs: 15 * 60 * 1000,
+ max: 60,
+ keyGenerator: apiLimiterKey,
+ standardHeaders: true,
+ legacyHeaders: false,
+ message: {
+ success: false,
+ message: 'Too many requests, please try again later.',
+ },
+});
+
export const brandFactsLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 30,
diff --git a/server/src/routes/cms.js b/server/src/routes/cms.js
new file mode 100644
index 000000000..02e3624aa
--- /dev/null
+++ b/server/src/routes/cms.js
@@ -0,0 +1,448 @@
+import { Router } from 'express';
+import { z } from 'zod';
+import supabaseAdmin from '../config/supabase.js';
+import { assertBrandAccess } from '../lib/access.js';
+import {
+ connectWebflowToken,
+ deleteConnection,
+ forgetWebflowAccounts,
+ isWebflowConfigured,
+} from '../lib/composio.js';
+import {
+ WebflowError,
+ checkFieldMap,
+ getCollection,
+ listCollections,
+ listSites,
+ suggestFieldMap,
+} from '../lib/cms/webflow.js';
+import { cmsLimiter } from '../middleware/rate-limiter.js';
+
+/**
+ * A brand's CMS connection for Send to CMS (#1331, phase 2; 00283): Webflow
+ * first. Members read a brand's connection; admins and managers connect the
+ * brand's site with a site token, pick the collection pages go to and its
+ * fields, and disconnect:
+ * GET /api/cms/brands/:brandId/webflow the connection, or none
+ * POST /api/cms/brands/:brandId/webflow { token } connect, or replace the token
+ * GET /api/cms/brands/:brandId/webflow/collections?siteId= a site's collections
+ * GET /api/cms/brands/:brandId/webflow/collections/:collectionId its fields and a suggested map
+ * PUT /api/cms/brands/:brandId/webflow { siteId?, collectionId, fieldMap }
+ * DELETE /api/cms/brands/:brandId/webflow
+ * The token passes through here once, from the browser to Composio, which
+ * keeps it: it is never stored, logged or sent back.
+ */
+
+const router = Router();
+
+const PROVIDER = 'webflow';
+const WRITE_ROLES = ['admin', 'manager'];
+const COLUMNS =
+ 'brand_id, composio_account_id, composio_entity_id, status, site_id, site_name, collection_id, collection_name, field_map, created_at, updated_at';
+
+const brandId = z.guid();
+// A Webflow site token: no spaces, as Webflow shows it.
+const tokenInput = z.object({ token: z.string().trim().min(16).max(512).regex(/^\S+$/) });
+const webflowId = z
+ .string()
+ .trim()
+ .min(1)
+ .max(100)
+ .regex(/^[A-Za-z0-9_-]+$/);
+const mapInput = z.object({
+ siteId: webflowId.optional(),
+ collectionId: webflowId,
+ fieldMap: z.record(z.string(), z.string().max(100)),
+});
+
+/** A brand's Composio user: a site token is one site's, so the brand's own. */
+const entityIdFor = (id) => `brand_${id}`;
+
+function routeError(message, status, code) {
+ const err = new Error(message);
+ err.status = status;
+ err.code = code;
+ return err;
+}
+
+async function assertWriter(id, userId) {
+ await assertBrandAccess(id, userId);
+ const { data: profile } = await supabaseAdmin
+ .from('profiles')
+ .select('role')
+ .eq('id', userId)
+ .single();
+ if (!WRITE_ROLES.includes(profile?.role)) {
+ throw routeError('Only admins and managers can connect a CMS.', 403, 'forbidden');
+ }
+}
+
+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 Composio's ids. */
+const shape = (row) =>
+ row
+ ? {
+ status: row.status,
+ siteId: row.site_id,
+ siteName: row.site_name,
+ collectionId: row.collection_id,
+ collectionName: row.collection_name,
+ fieldMap: row.field_map ?? {},
+ connectedAt: row.created_at,
+ updatedAt: row.updated_at,
+ }
+ : null;
+
+const accountOf = (row) => ({
+ entityId: row.composio_entity_id,
+ accountId: row.composio_account_id,
+});
+
+/** A brand that must have a connection to go on. */
+async function connected(id) {
+ const row = await connectionOf(id);
+ if (!row) throw routeError('Connect Webflow first.', 409, 'not_connected');
+ return row;
+}
+
+/** Remove a connected account at Composio; a failure is logged by name only. */
+async function forget(req, accountId) {
+ try {
+ await deleteConnection(accountId);
+ } catch (err) {
+ req.log.warn({ err: { name: err?.name } }, 'cms webflow account not removed');
+ }
+}
+
+/** Remove the brand's other Webflow accounts (a replaced token's, or one left before). */
+async function forgetOthers(req, entityId, keep) {
+ try {
+ await forgetWebflowAccounts(entityId, keep);
+ } catch (err) {
+ req.log.warn({ err: { name: err?.name } }, 'cms webflow old accounts not removed');
+ }
+}
+
+/**
+ * Sets the status of the connection as it was read: a token replaced
+ * meanwhile keeps its own.
+ */
+async function setStatus(row, status) {
+ const { error } = await supabaseAdmin
+ .from('brand_cms_connections')
+ .update({ status, updated_at: new Date().toISOString() })
+ .eq('brand_id', row.brand_id)
+ .eq('provider', PROVIDER)
+ .eq('composio_account_id', row.composio_account_id);
+ if (error) throw new Error(error.message);
+}
+
+/** Webflow took the token again: a connection marked refused is connected. */
+async function working(row) {
+ if (row.status === 'auth_failed') await setStatus(row, 'connected');
+}
+
+const WEBFLOW_STATUS = { failed: 502, not_found: 404, no_access: 403 };
+
+/**
+ * Answers a failure: a token Webflow refuses marks the connection that was
+ * read (`row`) auth_failed, so Settings asks for a new one. Errors are
+ * logged without their message where it may quote what the person typed.
+ */
+async function fail(req, res, err, what, row) {
+ if (err instanceof WebflowError) {
+ if (err.code === 'auth_failed' && row) await setStatus(row, 'auth_failed').catch(() => {});
+ return res.status(WEBFLOW_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 Webflow', code: 'failed' });
+}
+
+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) {
+ const parsed = brandId.safeParse(req.params.brandId);
+ if (!parsed.success) {
+ res.status(400).json({ error: 'Invalid brand', code: 'invalid' });
+ return null;
+ }
+ return parsed.data;
+}
+
+// GET — the brand's connection, for every member (Settings, the Send dialog).
+router.get('/brands/:brandId/webflow', async (req, res) => {
+ const id = brandOf(req, res);
+ if (!id) return;
+ try {
+ await assertBrandAccess(id, req.user.id);
+ return res.json({
+ configured: isWebflowConfigured(),
+ connection: shape(await connectionOf(id)),
+ });
+ } catch (err) {
+ return fail(req, res, err, 'cms webflow read error');
+ }
+});
+
+// POST — connect the brand's site with its token, or replace the token.
+router.post('/brands/:brandId/webflow', cmsLimiter, async (req, res) => {
+ const id = brandOf(req, res);
+ if (!id) return;
+ try {
+ await assertWriter(id, req.user.id);
+ if (!isWebflowConfigured()) return notConfigured(res);
+ const parsed = tokenInput.safeParse(req.body ?? {});
+ if (!parsed.success) {
+ return res
+ .status(400)
+ .json({ error: 'Paste the site token Webflow gave you.', code: 'invalid' });
+ }
+ const entityId = entityIdFor(id);
+ let accountId;
+ try {
+ accountId = await connectWebflowToken(entityId, parsed.data.token);
+ } catch (err) {
+ req.log.error({ err: { name: err?.name } }, 'cms webflow connect error');
+ return res.status(502).json({ error: 'Webflow could not be connected', code: 'failed' });
+ }
+
+ // Webflow says whether it takes the token: a token it refuses isn't kept.
+ let sites;
+ try {
+ sites = await listSites({ entityId, accountId });
+ } catch (err) {
+ await forget(req, accountId);
+ return fail(req, res, err, 'cms webflow sites error');
+ }
+ if (!sites.length) {
+ await forget(req, accountId);
+ return res
+ .status(409)
+ .json({ error: 'This token reaches no Webflow site.', code: 'no_site' });
+ }
+
+ // A new token for the same site keeps where pages go; another site starts over.
+ const before = await connectionOf(id);
+ const kept = before?.site_id && sites.some((s) => s.id === before.site_id) ? before : null;
+ const site = kept
+ ? sites.find((s) => s.id === kept.site_id)
+ : sites.length === 1
+ ? sites[0]
+ : null;
+ const now = new Date().toISOString();
+ const { data: row, error } = await supabaseAdmin
+ .from('brand_cms_connections')
+ .upsert(
+ {
+ brand_id: id,
+ provider: PROVIDER,
+ composio_account_id: accountId,
+ composio_entity_id: entityId,
+ status: 'connected',
+ site_id: site?.id ?? null,
+ site_name: site?.name ?? null,
+ collection_id: kept?.collection_id ?? null,
+ collection_name: kept?.collection_name ?? null,
+ field_map: kept?.field_map ?? {},
+ connected_by: req.user.id,
+ updated_at: now,
+ },
+ { onConflict: 'brand_id,provider' },
+ )
+ .select(COLUMNS)
+ .single();
+ if (error) {
+ await forget(req, accountId);
+ throw new Error(error.message);
+ }
+ // The replaced token's account, and any a failed removal left.
+ await forgetOthers(req, entityId, accountId);
+ return res.json({ connection: shape(row), sites });
+ } catch (err) {
+ return fail(req, res, err, 'cms webflow connect error');
+ }
+});
+
+// GET — a site's collections (the connection's site unless another is asked).
+router.get('/brands/:brandId/webflow/collections', cmsLimiter, async (req, res) => {
+ const id = brandOf(req, res);
+ if (!id) return;
+ let row = null;
+ try {
+ await assertWriter(id, req.user.id);
+ if (!isWebflowConfigured()) return notConfigured(res);
+ const asked = req.query.siteId === undefined ? null : webflowId.safeParse(req.query.siteId);
+ if (asked && !asked.success)
+ return res.status(400).json({ error: 'Invalid site', code: 'invalid' });
+ row = await connected(id);
+ const account = accountOf(row);
+ const sites = await listSites(account);
+ await working(row);
+ const siteId = asked?.data ?? row.site_id ?? (sites.length === 1 ? sites[0].id : null);
+ if (!siteId || !sites.some((s) => s.id === siteId)) {
+ return res.json({ sites, siteId: null, collections: [] });
+ }
+ return res.json({ sites, siteId, collections: await listCollections(account, siteId) });
+ } catch (err) {
+ return fail(req, res, err, 'cms webflow collections error', row);
+ }
+});
+
+/**
+ * The site a request names (else the connection's), when the token
+ * reaches it, and the collection when it's on that site; null otherwise.
+ */
+async function siteAndCollection(account, siteId, collectionId) {
+ const sites = await listSites(account);
+ const site = sites.find((s) => s.id === siteId);
+ if (!site) return null;
+ const collections = await listCollections(account, site.id);
+ return collections.some((c) => c.id === collectionId) ? site : null;
+}
+
+// GET — a collection's fields (one on the site the token reaches) and the map they suggest.
+router.get('/brands/:brandId/webflow/collections/:collectionId', cmsLimiter, async (req, res) => {
+ const id = brandOf(req, res);
+ if (!id) return;
+ const collectionId = webflowId.safeParse(req.params.collectionId);
+ const asked = req.query.siteId === undefined ? null : webflowId.safeParse(req.query.siteId);
+ if (!collectionId.success || (asked && !asked.success)) {
+ return res.status(400).json({ error: 'Invalid collection', code: 'invalid' });
+ }
+ let row = null;
+ try {
+ await assertWriter(id, req.user.id);
+ if (!isWebflowConfigured()) return notConfigured(res);
+ row = await connected(id);
+ const account = accountOf(row);
+ const site = await siteAndCollection(account, asked?.data ?? row.site_id, collectionId.data);
+ await working(row);
+ if (!site) {
+ return res
+ .status(404)
+ .json({ error: 'Pick one of the site’s collections.', code: 'not_found' });
+ }
+ const collection = await getCollection(account, collectionId.data);
+ const suggested = suggestFieldMap(collection.fields);
+ return res.json({ ...collection, suggested });
+ } catch (err) {
+ return fail(req, res, err, 'cms webflow collection error', row);
+ }
+});
+
+// PUT — where the brand's pages go: the site, the collection and its fields.
+router.put('/brands/:brandId/webflow', cmsLimiter, async (req, res) => {
+ const id = brandOf(req, res);
+ if (!id) return;
+ let row = null;
+ try {
+ await assertWriter(id, req.user.id);
+ if (!isWebflowConfigured()) return notConfigured(res);
+ const parsed = mapInput.safeParse(req.body ?? {});
+ if (!parsed.success)
+ return res.status(400).json({ error: 'Invalid settings', code: 'invalid' });
+ row = await connected(id);
+ const account = accountOf(row);
+ const { collectionId, fieldMap } = parsed.data;
+
+ // The site and the collection must be the token's.
+ const site = await siteAndCollection(account, parsed.data.siteId ?? row.site_id, collectionId);
+ if (!site) {
+ return res
+ .status(404)
+ .json({ error: 'Pick one of the site’s collections.', code: 'not_found' });
+ }
+ const collection = await getCollection(account, collectionId);
+ const checked = checkFieldMap(fieldMap, collection.fields);
+ if (!checked.ok) {
+ return res.status(400).json({
+ error: 'The fields don’t fit the collection.',
+ code: 'invalid_map',
+ problems: checked.problems,
+ });
+ }
+
+ const { data: saved, error } = await supabaseAdmin
+ .from('brand_cms_connections')
+ .update({
+ status: 'connected',
+ site_id: site.id,
+ site_name: site.name,
+ collection_id: collectionId,
+ collection_name: collection.name,
+ field_map: checked.map,
+ updated_at: new Date().toISOString(),
+ })
+ .eq('brand_id', id)
+ .eq('provider', PROVIDER)
+ // The token it was checked with: one connected or removed meanwhile isn't overwritten.
+ .eq('composio_account_id', row.composio_account_id)
+ .select(COLUMNS)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!saved) {
+ throw routeError(
+ 'Webflow’s connection changed while this was saved. Reload and try again.',
+ 409,
+ 'changed',
+ );
+ }
+ return res.json({ connection: shape(saved) });
+ } catch (err) {
+ return fail(req, res, err, 'cms webflow settings error', row);
+ }
+});
+
+// DELETE — disconnect: the brand's accounts at Composio (the token with them), then its row.
+router.delete('/brands/:brandId/webflow', 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 });
+ // The row stays until Composio has let go of the token, so a disconnect
+ // that didn't happen isn't shown as one. A server without Webflow set up
+ // can't reach Composio: its row just goes.
+ if (isWebflowConfigured()) {
+ try {
+ await forgetWebflowAccounts(row.composio_entity_id);
+ } catch (err) {
+ req.log.warn({ err: { name: err?.name } }, 'cms webflow disconnect not done');
+ return res
+ .status(502)
+ .json({ error: 'Webflow could not be disconnected. Try again.', code: 'failed' });
+ }
+ }
+ const { error } = await supabaseAdmin
+ .from('brand_cms_connections')
+ .delete()
+ .eq('brand_id', id)
+ .eq('provider', PROVIDER)
+ .eq('composio_account_id', row.composio_account_id);
+ if (error) throw new Error(error.message);
+ return res.json({ success: true });
+ } catch (err) {
+ return fail(req, res, err, 'cms webflow disconnect error');
+ }
+});
+
+export default router;
diff --git a/server/src/routes/cms.test.js b/server/src/routes/cms.test.js
new file mode 100644
index 000000000..640f0152a
--- /dev/null
+++ b/server/src/routes/cms.test.js
@@ -0,0 +1,464 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * /api/cms/brands/:brandId/webflow (Send to CMS, #1331 phase 2, 00283): a
+ * brand's Webflow connection. Members read it; admins and managers connect a
+ * site token, map a collection and disconnect; the token is never kept,
+ * logged or sent back.
+ */
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const TOKEN = 'wf_site_token_0123456789abcdef';
+
+let role;
+let rows;
+const assertBrandAccess = vi.fn();
+const composio = {
+ isWebflowConfigured: vi.fn(),
+ connectWebflowToken: vi.fn(),
+ deleteConnection: vi.fn(),
+ forgetWebflowAccounts: vi.fn(),
+};
+const webflow = { listSites: vi.fn(), listCollections: vi.fn(), getCollection: vi.fn() };
+
+/** brand_cms_connections in memory: the queries the route makes. */
+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 = {
+ created_at: '2026-10-25T10: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);
+ };
+ // As a database answers: copies, not the rows themselves.
+ 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: () => composio.isWebflowConfigured(),
+ connectWebflowToken: (...args) => composio.connectWebflowToken(...args),
+ deleteConnection: (...args) => composio.deleteConnection(...args),
+ forgetWebflowAccounts: (...args) => composio.forgetWebflowAccounts(...args),
+}));
+vi.mock('../lib/cms/webflow.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ listSites: (...args) => webflow.listSites(...args),
+ listCollections: (...args) => webflow.listCollections(...args),
+ getCollection: (...args) => webflow.getCollection(...args),
+}));
+vi.mock('../middleware/rate-limiter.js', () => ({ cmsLimiter: (_req, _res, next) => next() }));
+
+const { default: router } = await import('./cms.js');
+const { WebflowError } = await import('../lib/cms/webflow.js');
+
+const fields = [
+ { slug: 'name', name: 'Name', type: 'PlainText', required: true },
+ { slug: 'slug', name: 'Slug', type: 'PlainText', required: true },
+ { slug: 'post-body', name: 'Post Body', type: 'RichText', required: false },
+ { slug: 'post-summary', name: 'Post Summary', type: 'PlainText', required: false },
+];
+
+let server;
+let base;
+let logged;
+
+beforeEach(async () => {
+ role = 'manager';
+ rows = [];
+ logged = [];
+ assertBrandAccess.mockReset().mockResolvedValue({ orgId: 'o1' });
+ composio.isWebflowConfigured.mockReset().mockReturnValue(true);
+ composio.connectWebflowToken.mockReset().mockResolvedValue('ca_new');
+ composio.deleteConnection.mockReset().mockResolvedValue(undefined);
+ composio.forgetWebflowAccounts.mockReset().mockResolvedValue(undefined);
+ webflow.listSites.mockReset().mockResolvedValue([{ id: 's1', name: 'Ansvisor' }]);
+ webflow.listCollections
+ .mockReset()
+ .mockResolvedValue([{ id: 'c1', name: 'Blog Posts', slug: 'post' }]);
+ webflow.getCollection.mockReset().mockResolvedValue({ id: 'c1', name: 'Blog Posts', fields });
+ 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}/webflow`;
+});
+
+afterEach(() => new Promise((resolve) => server.close(resolve)));
+
+const call = (method, path = '', body) =>
+ fetch(`${base}${path}`, {
+ method,
+ headers: { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+const connectedRow = (extra = {}) => ({
+ brand_id: BRAND,
+ provider: 'webflow',
+ composio_account_id: 'ca_old',
+ composio_entity_id: `brand_${BRAND}`,
+ status: 'connected',
+ site_id: 's1',
+ site_name: 'Ansvisor',
+ collection_id: 'c1',
+ collection_name: 'Blog Posts',
+ field_map: { body: 'post-body' },
+ created_at: '2026-10-20T10:00:00Z',
+ updated_at: '2026-10-20T10:00:00Z',
+ ...extra,
+});
+
+describe('GET the connection', () => {
+ it('shows a member the brand’s connection, without Composio’s ids', async () => {
+ role = 'member';
+ expect(await (await call('GET')).json()).toEqual({ configured: true, connection: null });
+ rows.push(connectedRow());
+ const body = await (await call('GET')).json();
+ expect(body.connection).toEqual({
+ status: 'connected',
+ siteId: 's1',
+ siteName: 'Ansvisor',
+ collectionId: 'c1',
+ collectionName: 'Blog Posts',
+ fieldMap: { body: 'post-body' },
+ connectedAt: '2026-10-20T10:00:00Z',
+ updatedAt: '2026-10-20T10:00:00Z',
+ });
+ expect(JSON.stringify(body)).not.toMatch(/ca_old|brand_/);
+ });
+
+ it('refuses a brand of another workspace, and a malformed id', async () => {
+ assertBrandAccess.mockRejectedValueOnce(
+ Object.assign(new Error('nope'), { status: 403, code: 'not_in_workspace' }),
+ );
+ const res = await call('GET');
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: 'not_in_workspace' });
+ const bad = await fetch(base.replace(BRAND, 'not-a-brand'));
+ expect(bad.status).toBe(400);
+ });
+});
+
+describe('POST connect', () => {
+ it('connects a token Webflow takes, keeping its one site, and never the token', async () => {
+ const res = await call('POST', '', { token: ` ${TOKEN} ` });
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.sites).toEqual([{ id: 's1', name: 'Ansvisor' }]);
+ expect(body.connection).toMatchObject({
+ status: 'connected',
+ siteId: 's1',
+ collectionId: null,
+ });
+ expect(composio.connectWebflowToken).toHaveBeenCalledWith(`brand_${BRAND}`, TOKEN);
+ expect(webflow.listSites).toHaveBeenCalledWith({
+ entityId: `brand_${BRAND}`,
+ accountId: 'ca_new',
+ });
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ composio_account_id: 'ca_new', connected_by: 'u1' });
+ expect(JSON.stringify([rows, body, logged])).not.toContain(TOKEN);
+ });
+
+ it('keeps where pages go for a new token of the same site, and forgets the old account', async () => {
+ rows.push(connectedRow());
+ const body = await (await call('POST', '', { token: TOKEN })).json();
+ expect(body.connection).toMatchObject({ collectionId: 'c1', fieldMap: { body: 'post-body' } });
+ // The brand's other accounts go: the replaced token's, and any left before.
+ expect(composio.forgetWebflowAccounts).toHaveBeenCalledWith(`brand_${BRAND}`, 'ca_new');
+ expect(composio.deleteConnection).not.toHaveBeenCalled();
+ });
+
+ it('starts over for a token of another site', async () => {
+ rows.push(connectedRow());
+ webflow.listSites.mockResolvedValueOnce([{ id: 's2', name: 'Acme' }]);
+ const body = await (await call('POST', '', { token: TOKEN })).json();
+ expect(body.connection).toMatchObject({ siteId: 's2', collectionId: null, fieldMap: {} });
+ });
+
+ it('keeps no account for a token Webflow refuses, or one that reaches no site', async () => {
+ webflow.listSites.mockRejectedValueOnce(
+ new WebflowError('auth_failed', 'Webflow refused the site token'),
+ );
+ const refused = await call('POST', '', { token: TOKEN });
+ expect(refused.status).toBe(409);
+ expect(await refused.json()).toMatchObject({ code: 'auth_failed' });
+ expect(composio.deleteConnection).toHaveBeenCalledWith('ca_new');
+ expect(rows).toEqual([]);
+
+ webflow.listSites.mockResolvedValueOnce([]);
+ const none = await call('POST', '', { token: TOKEN });
+ expect(await none.json()).toMatchObject({ code: 'no_site' });
+ expect(rows).toEqual([]);
+ });
+
+ it('doesn’t mark a working connection refused when a new token is', async () => {
+ rows.push(connectedRow());
+ webflow.listSites.mockRejectedValueOnce(
+ new WebflowError('auth_failed', 'Webflow refused the site token'),
+ );
+ await call('POST', '', { token: TOKEN });
+ expect(rows[0]).toMatchObject({ status: 'connected', composio_account_id: 'ca_old' });
+ });
+
+ it('is for admins and managers, on a server Webflow is set up on, with a token', async () => {
+ role = 'member';
+ expect((await call('POST', '', { token: TOKEN })).status).toBe(403);
+ role = 'admin';
+ composio.isWebflowConfigured.mockReturnValueOnce(false);
+ const off = await call('POST', '', { token: TOKEN });
+ expect(off.status).toBe(503);
+ expect(await off.json()).toMatchObject({ code: 'not_configured' });
+ expect((await call('POST', '', { token: 'has a space in it 1234567' })).status).toBe(400);
+ expect(composio.connectWebflowToken).not.toHaveBeenCalled();
+ });
+
+ it('logs a Composio failure by its name only', async () => {
+ composio.connectWebflowToken.mockRejectedValueOnce(new Error(`bad key ${TOKEN}`));
+ const res = await call('POST', '', { token: TOKEN });
+ expect(res.status).toBe(502);
+ expect(logged.join('')).not.toContain(TOKEN);
+ });
+});
+
+describe('collections and their fields', () => {
+ it('asks for a connection first', async () => {
+ const res = await call('GET', '/collections');
+ expect(res.status).toBe(409);
+ expect(await res.json()).toMatchObject({ code: 'not_connected' });
+ });
+
+ it('lists the site’s collections, and a collection’s fields with the map they suggest', async () => {
+ rows.push(connectedRow({ collection_id: null, field_map: {} }));
+ expect(await (await call('GET', '/collections')).json()).toEqual({
+ sites: [{ id: 's1', name: 'Ansvisor' }],
+ siteId: 's1',
+ collections: [{ id: 'c1', name: 'Blog Posts', slug: 'post' }],
+ });
+ // A site the token doesn't reach lists nothing.
+ expect(await (await call('GET', '/collections?siteId=s9')).json()).toMatchObject({
+ siteId: null,
+ collections: [],
+ });
+ expect(await (await call('GET', '/collections/c1')).json()).toEqual({
+ id: 'c1',
+ name: 'Blog Posts',
+ fields,
+ suggested: { body: 'post-body', metaDescription: 'post-summary' },
+ });
+ });
+
+ it('marks the connection refused when Webflow no longer takes its token', async () => {
+ rows.push(connectedRow());
+ webflow.listSites.mockRejectedValueOnce(
+ new WebflowError('auth_failed', 'Webflow refused the site token'),
+ );
+ const res = await call('GET', '/collections');
+ expect(await res.json()).toMatchObject({ code: 'auth_failed' });
+ expect(rows[0].status).toBe('auth_failed');
+ });
+});
+
+describe('PUT where pages go', () => {
+ it('keeps a field map that fits the site’s collection', async () => {
+ rows.push(connectedRow({ collection_id: null, collection_name: null, field_map: {} }));
+ const res = await call('PUT', '', {
+ collectionId: 'c1',
+ fieldMap: { body: 'post-body', metaDescription: 'post-summary' },
+ });
+ expect(res.status).toBe(200);
+ expect((await res.json()).connection).toMatchObject({
+ collectionId: 'c1',
+ collectionName: 'Blog Posts',
+ fieldMap: { body: 'post-body', metaDescription: 'post-summary' },
+ });
+ });
+
+ it('refuses a collection of another site, and a map that doesn’t fit', async () => {
+ rows.push(connectedRow());
+ const elsewhere = await call('PUT', '', {
+ collectionId: 'c9',
+ fieldMap: { body: 'post-body' },
+ });
+ expect(elsewhere.status).toBe(404);
+ const bad = await call('PUT', '', { collectionId: 'c1', fieldMap: { body: 'post-summary' } });
+ expect(bad.status).toBe(400);
+ expect(await bad.json()).toMatchObject({
+ code: 'invalid_map',
+ problems: ['body: Post Summary is PlainText, not RichText'],
+ });
+ expect(rows[0].field_map).toEqual({ body: 'post-body' });
+ });
+});
+
+describe('DELETE disconnect', () => {
+ it('removes the brand’s accounts at Composio, then its connection', async () => {
+ rows.push(connectedRow());
+ const res = await call('DELETE');
+ expect(await res.json()).toEqual({ success: true });
+ expect(composio.forgetWebflowAccounts).toHaveBeenCalledWith(`brand_${BRAND}`);
+ expect(rows).toEqual([]);
+ });
+
+ it('keeps the connection when Composio can’t let go of the token, and is for admins and managers', async () => {
+ rows.push(connectedRow());
+ role = 'member';
+ expect((await call('DELETE')).status).toBe(403);
+ role = 'admin';
+ composio.forgetWebflowAccounts.mockRejectedValueOnce(new Error('down'));
+ const res = await call('DELETE');
+ expect(res.status).toBe(502);
+ expect(await res.json()).toMatchObject({ code: 'failed' });
+ expect(rows).toHaveLength(1);
+ // A server without Webflow set up can't reach Composio: the row just goes.
+ composio.isWebflowConfigured.mockReturnValue(false);
+ expect((await call('DELETE')).status).toBe(200);
+ expect(rows).toEqual([]);
+ });
+
+ it('leaves a token connected meanwhile in place', async () => {
+ rows.push(connectedRow());
+ composio.forgetWebflowAccounts.mockImplementationOnce(async () => {
+ rows[0].composio_account_id = 'ca_new';
+ });
+ await call('DELETE');
+ expect(rows).toHaveLength(1);
+ });
+});
+
+describe('races and Webflow’s answers', () => {
+ it('doesn’t save a map checked with a token replaced meanwhile', async () => {
+ rows.push(connectedRow());
+ webflow.getCollection.mockImplementationOnce(async () => {
+ Object.assign(rows[0], { composio_account_id: 'ca_new', site_id: 's2' });
+ return { id: 'c1', name: 'Blog Posts', fields };
+ });
+ const res = await call('PUT', '', { collectionId: 'c1', fieldMap: { body: 'post-body' } });
+ expect(res.status).toBe(409);
+ expect(await res.json()).toMatchObject({ code: 'changed' });
+ expect(rows[0]).toMatchObject({ site_id: 's2', composio_account_id: 'ca_new' });
+ });
+
+ it('marks refused only the token the refusal came back for', async () => {
+ rows.push(connectedRow());
+ webflow.listSites.mockImplementationOnce(async () => {
+ rows[0].composio_account_id = 'ca_new';
+ throw new WebflowError('auth_failed', 'Webflow refused the site token');
+ });
+ await call('GET', '/collections');
+ expect(rows[0].status).toBe('connected');
+ });
+
+ it('connects a refused connection again once Webflow takes its token', async () => {
+ rows.push(connectedRow({ status: 'auth_failed' }));
+ await call('GET', '/collections');
+ expect(rows[0].status).toBe('connected');
+ });
+
+ it('answers a site or collection the token doesn’t reach without marking the token refused', async () => {
+ rows.push(connectedRow());
+ webflow.listCollections.mockRejectedValueOnce(
+ new WebflowError('no_access', 'The site token doesn’t reach this site or collection'),
+ );
+ const res = await call('GET', '/collections');
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: 'no_access' });
+ expect(rows[0].status).toBe('connected');
+ });
+
+ it('gives a collection’s fields only for one on a site the token reaches', async () => {
+ rows.push(connectedRow());
+ const other = await call('GET', '/collections/c9');
+ expect(other.status).toBe(404);
+ expect(webflow.getCollection).not.toHaveBeenCalled();
+ // Another of the token's sites, named.
+ webflow.listSites.mockResolvedValueOnce([
+ { id: 's1', name: 'Ansvisor' },
+ { id: 's2', name: 'Docs' },
+ ]);
+ webflow.listCollections.mockResolvedValueOnce([{ id: 'c7', name: 'Guides', slug: 'guide' }]);
+ expect((await call('GET', '/collections/c7?siteId=s2')).status).toBe(200);
+ expect(webflow.listCollections).toHaveBeenLastCalledWith(
+ { entityId: `brand_${BRAND}`, accountId: 'ca_old' },
+ 's2',
+ );
+ });
+
+ it('names a brand that isn’t there as not found', async () => {
+ assertBrandAccess.mockRejectedValueOnce(
+ Object.assign(new Error('Brand not found'), { status: 404 }),
+ );
+ const res = await call('GET');
+ expect(res.status).toBe(404);
+ expect(await res.json()).toMatchObject({ code: 'not_found' });
+ });
+});
diff --git a/server/src/routes/index.js b/server/src/routes/index.js
index f99b936b2..a35d8de1c 100644
--- a/server/src/routes/index.js
+++ b/server/src/routes/index.js
@@ -17,6 +17,7 @@ import botRoutes from './bots.js';
import billingRoutes from './billing.js';
import brandFactRoutes from './brand-facts.js';
import catalogRoutes from './catalog.js';
+import cmsRoutes from './cms.js';
const router = Router();
@@ -38,6 +39,7 @@ router.use('/bots', botRoutes);
router.use('/billing', billingRoutes);
router.use('/brand-facts', brandFactRoutes);
router.use('/catalog', catalogRoutes);
+router.use('/cms', cmsRoutes);
router.get('/health', (req, res) => {
res.json({ status: 'ok', user: req.user?.id });
diff --git a/supabase/migrations/00283_brand_cms_connections.sql b/supabase/migrations/00283_brand_cms_connections.sql
new file mode 100644
index 000000000..1fef746d6
--- /dev/null
+++ b/supabase/migrations/00283_brand_cms_connections.sql
@@ -0,0 +1,63 @@
+-- ============================================================================
+-- 00283: a brand's CMS connection for Send to CMS (#1331, phase 2)
+-- ============================================================================
+-- Phase 1 sends pages to the brand's webhook. Phase 2 sends them to the CMS
+-- itself, Webflow first: a brand connects its Webflow site with a site token,
+-- picks the collection its pages go to and which of the collection's fields
+-- takes what.
+--
+-- * One connection a brand and CMS. A Webflow site token is one site's, so
+-- the connection is the brand's, not the workspace's.
+-- * The token never touches this table: Composio keeps it (an API-key
+-- connected account, as Search Console's OAuth tokens are kept, 00045).
+-- We keep the connected account's id and its Composio user.
+-- * `field_map`: which of the collection's fields takes each part of a page
+-- ({ body, metaTitle, metaDescription, jsonLd } → a field's slug). The
+-- item's name and slug always go to Webflow's own `name` and `slug`.
+-- * `auth_failed`: Webflow refused the saved token; the person connects again.
+-- * Members read their brands' connections (the Send dialog and Settings
+-- show them); only the server writes them, for admins and managers.
+
+create table if not exists public.brand_cms_connections (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ provider text not null check (provider in ('webflow')),
+ composio_account_id text not null check (char_length(composio_account_id) between 1 and 200),
+ composio_entity_id text not null check (char_length(composio_entity_id) between 1 and 200),
+ status text not null default 'connected' check (status in ('connected', 'auth_failed')),
+ site_id text check (site_id is null or char_length(site_id) between 1 and 100),
+ site_name text check (site_name is null or char_length(site_name) <= 300),
+ collection_id text check (collection_id is null or char_length(collection_id) between 1 and 100),
+ collection_name text check (collection_name is null or char_length(collection_name) <= 300),
+ field_map jsonb not null default '{}'::jsonb check (
+ jsonb_typeof(field_map) = 'object' and octet_length(field_map::text) <= 2048
+ ),
+ connected_by uuid references public.profiles(id) on delete set null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ -- A collection is picked on its site.
+ constraint brand_cms_connections_collection_site check (collection_id is null or site_id is not null),
+ unique (brand_id, provider)
+);
+
+alter table public.brand_cms_connections enable row level security;
+revoke all on table public.brand_cms_connections from anon, authenticated;
+grant select on table public.brand_cms_connections to authenticated;
+grant all on table public.brand_cms_connections to service_role;
+
+drop policy if exists "brand_cms_connections: member select" on public.brand_cms_connections;
+create policy "brand_cms_connections: member select"
+ on public.brand_cms_connections
+ for select
+ using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+comment on table public.brand_cms_connections is
+ 'Send to CMS, phase 2 (#1331, 00283): a brand''s CMS connection (Webflow first): its Composio connected account (the token stays at Composio), the site and collection pages go to, and field_map (body, metaTitle, metaDescription, jsonLd → the collection''s field slugs). Members read; the server writes for admins and managers.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 5ffe2d93c..ea2f9b240 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -39999,3 +39999,70 @@ comment on column public.catalog_sources.account is
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00283_brand_cms_connections.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00283: a brand's CMS connection for Send to CMS (#1331, phase 2)
+-- ============================================================================
+-- Phase 1 sends pages to the brand's webhook. Phase 2 sends them to the CMS
+-- itself, Webflow first: a brand connects its Webflow site with a site token,
+-- picks the collection its pages go to and which of the collection's fields
+-- takes what.
+--
+-- * One connection a brand and CMS. A Webflow site token is one site's, so
+-- the connection is the brand's, not the workspace's.
+-- * The token never touches this table: Composio keeps it (an API-key
+-- connected account, as Search Console's OAuth tokens are kept, 00045).
+-- We keep the connected account's id and its Composio user.
+-- * `field_map`: which of the collection's fields takes each part of a page
+-- ({ body, metaTitle, metaDescription, jsonLd } → a field's slug). The
+-- item's name and slug always go to Webflow's own `name` and `slug`.
+-- * `auth_failed`: Webflow refused the saved token; the person connects again.
+-- * Members read their brands' connections (the Send dialog and Settings
+-- show them); only the server writes them, for admins and managers.
+
+create table if not exists public.brand_cms_connections (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ provider text not null check (provider in ('webflow')),
+ composio_account_id text not null check (char_length(composio_account_id) between 1 and 200),
+ composio_entity_id text not null check (char_length(composio_entity_id) between 1 and 200),
+ status text not null default 'connected' check (status in ('connected', 'auth_failed')),
+ site_id text check (site_id is null or char_length(site_id) between 1 and 100),
+ site_name text check (site_name is null or char_length(site_name) <= 300),
+ collection_id text check (collection_id is null or char_length(collection_id) between 1 and 100),
+ collection_name text check (collection_name is null or char_length(collection_name) <= 300),
+ field_map jsonb not null default '{}'::jsonb check (
+ jsonb_typeof(field_map) = 'object' and octet_length(field_map::text) <= 2048
+ ),
+ connected_by uuid references public.profiles(id) on delete set null,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ -- A collection is picked on its site.
+ constraint brand_cms_connections_collection_site check (collection_id is null or site_id is not null),
+ unique (brand_id, provider)
+);
+
+alter table public.brand_cms_connections enable row level security;
+revoke all on table public.brand_cms_connections from anon, authenticated;
+grant select on table public.brand_cms_connections to authenticated;
+grant all on table public.brand_cms_connections to service_role;
+
+drop policy if exists "brand_cms_connections: member select" on public.brand_cms_connections;
+create policy "brand_cms_connections: member select"
+ on public.brand_cms_connections
+ for select
+ using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+comment on table public.brand_cms_connections is
+ 'Send to CMS, phase 2 (#1331, 00283): a brand''s CMS connection (Webflow first): its Composio connected account (the token stays at Composio), the site and collection pages go to, and field_map (body, metaTitle, metaDescription, jsonLd → the collection''s field slugs). Members read; the server writes for admins and managers.';
+
+notify pgrst, 'reload schema';
+