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(cms): connect a brand's Framer project for Send to CMS (#1331) (#1575)

Cihan1a556ae2fc51
diff --git a/server/.env.example b/server/.env.example
index 40431759f..b658f6544 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -208,14 +208,21 @@ AI_VOLUME_MULTIPLIER=0.45
# COMPOSIO_GMC_AUTH_CONFIG_ID=
# 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 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.
+# Send to CMS's WordPress and Framer connections (#1331): the key that
+# encrypts a store's or a WordPress site's sign-in, and a Framer project's
+# API key, 32 bytes in base64 (openssl rand -base64 32). Only this server
+# holds it; the web app never sees a sign-in. Optional: without it,
+# Settings says store connections, WordPress and Framer 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=
+# Framer's client (framer-api) writes to the console itself, past this
+# server's logger: at its default level (warn) an error Framer sends on an
+# open connection is printed with Framer's own words (silent prints nothing).
+# silent, error, warn, info or debug; read once, when the server starts.
+# FRAMER_API_LOG_LEVEL=warn
+
# How long a run waits for Cloro's FIRST result before giving up (default 90
# min). Nothing has come back yet at that point, so the stall and ghost exits
# below — which compare successive pending counts — have nothing to measure.
diff --git a/server/package-lock.json b/server/package-lock.json
index fa383c1e4..32e98ae02 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@ansvisor/ansvisor-server",
- "version": "0.2.0",
+ "version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ansvisor/ansvisor-server",
- "version": "0.2.0",
+ "version": "0.3.0",
"license": "MIT",
"dependencies": {
"@ai-sdk/anthropic": "^3.0.58",
@@ -23,6 +23,7 @@
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-rate-limit": "^7.1.4",
+ "framer-api": "^5.1.0",
"helmet": "^7.1.0",
"htmlparser2": "^10.1.0",
"node-cron": "^4.2.1",
@@ -2551,6 +2552,13 @@
"url": "https://github.com/sponsors/fb55"
}
},
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "license": "MIT",
+ "peer": true
+ },
"node_modules/culvert": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/culvert/-/culvert-0.1.2.tgz",
@@ -2631,6 +2639,12 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
+ "node_modules/devalue": {
+ "version": "5.9.4",
+ "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz",
+ "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==",
+ "license": "MIT"
+ },
"node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
@@ -3515,6 +3529,28 @@
"node": ">= 0.6"
}
},
+ "node_modules/framer-api": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/framer-api/-/framer-api-5.1.0.tgz",
+ "integrity": "sha512-L3CAdLRtulyX0OfCs+cAyo+kE1OfG408fIvHOCrqnwWXneZ/Ko2Nw4DdjlFWxomF7SkpaoONdoOKT5etSi5j2g==",
+ "license": "MIT",
+ "dependencies": {
+ "devalue": "^5.8.1",
+ "std-env": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "peerDependencies": {
+ "csstype": "^3.1.1"
+ }
+ },
+ "node_modules/framer-api/node_modules/std-env": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
+ "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
+ "license": "MIT"
+ },
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
diff --git a/server/package.json b/server/package.json
index daea204d1..7c26ec3e8 100644
--- a/server/package.json
+++ b/server/package.json
@@ -37,6 +37,7 @@
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-rate-limit": "^7.1.4",
+ "framer-api": "^5.1.0",
"helmet": "^7.1.0",
"htmlparser2": "^10.1.0",
"node-cron": "^4.2.1",
diff --git a/server/src/lib/cms/framer.js b/server/src/lib/cms/framer.js
new file mode 100644
index 000000000..bd5809bb7
--- /dev/null
+++ b/server/src/lib/cms/framer.js
@@ -0,0 +1,381 @@
+import {
+ FramerAPIError,
+ FramerPluginClosedError,
+ FramerPluginError,
+ connect as framerConnect,
+} from 'framer-api';
+
+/**
+ * Framer for Send to CMS (#1331, phase 2; 00295): a project's CMS through
+ * Framer's Server API (framer-api), with an API key made in the project
+ * (Site Settings › General). The key reaches that project only and acts as
+ * the user who made it; Framer has no API to revoke it.
+ *
+ * Each use opens a WebSocket to Framer (wss://api.framer.com) and closes it
+ * once done (withProject): one left open keeps the process from exiting.
+ *
+ * The key is never put in a message, a log or an answer. Our answers and
+ * logs carry our own words, never Framer's messages; framer-api's own
+ * console output (FRAMER_API_LOG_LEVEL, server/.env.example) is apart.
+ */
+
+export class FramerError extends Error {
+ /**
+ * @param {'invalid'|'auth_failed'|'no_access'|'not_found'|'busy'|'unreachable'|'failed'} code
+ * 'auth_failed': Framer refused the key (the person connects again)
+ * @param {string} message
+ */
+ constructor(code, message) {
+ super(message);
+ this.name = 'FramerError';
+ this.code = code;
+ }
+}
+
+/** The longest published address kept (brand_cms_connections.site_url). */
+export const SITE_URL_MAX = 2048;
+
+/** How long one use of a project may take, its connection included. */
+const TIMEOUT_MS = 30_000;
+/** How long closing waits for Framer's goodbye (framer-api waits up to 15 s) before the answer goes. */
+const CLOSE_WAIT_MS = 5_000;
+
+/** A project id as framer-api (5.1.0) reads it: 20 letters and digits. */
+const PROJECT_ID = /^[A-Za-z0-9]{20}$/;
+const FRAMER_HOSTS = new Set(['framer.com', 'www.framer.com']);
+
+/**
+ * The project the person pasted, as Framer connects to it: its id, from
+ * the project's address (https://framer.com/projects/Name--<id>…, as the
+ * editor shows it) or the id itself. Anything else is refused before Framer
+ * is called. A branch in the address is left out: pages go to the main one.
+ */
+export function projectRef(input) {
+ const text = String(input ?? '').trim();
+ if (PROJECT_ID.test(text)) return text;
+ const invalid = new FramerError(
+ 'invalid',
+ 'Paste the project’s address from Framer (framer.com/projects/…) or its id.',
+ );
+ let url;
+ try {
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`);
+ } catch {
+ throw invalid;
+ }
+ if (
+ url.protocol !== 'https:' ||
+ !FRAMER_HOSTS.has(url.hostname) ||
+ url.username ||
+ url.password ||
+ url.port
+ ) {
+ throw invalid;
+ }
+ const [first, second] = url.pathname.split('/').filter(Boolean);
+ if (first?.toLowerCase() !== 'projects' || !second) throw invalid;
+ let segment;
+ try {
+ segment = decodeURIComponent(second);
+ } catch {
+ throw invalid;
+ }
+ // "Name--<id>", maybe with more after the id: read as framer-api reads it.
+ const id = segment.match(/^.+--([A-Za-z0-9]+)/)?.[1] ?? segment;
+ if (!PROJECT_ID.test(id)) throw invalid;
+ return id;
+}
+
+/** framer-api's error codes, in our words. */
+const API_ERRORS = {
+ UNAUTHORIZED: [
+ 'auth_failed',
+ 'Framer refused the API key. Make a new one in the project’s Site Settings › General.',
+ ],
+ PROJECT_CLOSED: [
+ 'not_found',
+ 'Framer couldn’t open the project. Check its address, and that the API key was made in it.',
+ ],
+ NODE_NOT_FOUND: [
+ 'not_found',
+ 'Framer couldn’t find that in the project: it may have been removed.',
+ ],
+ TOKEN_SESSION_LIMIT: [
+ 'busy',
+ 'Framer has too many connections open with this key. Try again in a minute.',
+ ],
+ POOL_EXHAUSTED: ['busy', 'Framer is busy. Try again in a minute.'],
+ TIMEOUT: ['unreachable', 'Framer didn’t answer in time. Try again.'],
+ INVALID_REQUEST: [
+ 'invalid',
+ 'Framer didn’t take the request. Check the project’s address and the API key.',
+ ],
+};
+
+const CLOSED = 'Framer closed the connection. Try again.';
+
+/**
+ * A failed call to Framer, in our words; an error of our own code goes on
+ * as it is. `opened`: the connection was open, so a project closed is a
+ * connection dropped mid-call, not a project Framer couldn't open.
+ */
+function framerError(err, opened) {
+ if (err instanceof FramerError) return err;
+ if (err instanceof FramerAPIError) {
+ if (opened && err.code === 'PROJECT_CLOSED') return new FramerError('unreachable', CLOSED);
+ const [code, message] = API_ERRORS[err.code] ?? [
+ 'failed',
+ 'Framer didn’t answer as expected. Try again.',
+ ];
+ return new FramerError(code, message);
+ }
+ if (err instanceof FramerPluginClosedError) return new FramerError('unreachable', CLOSED);
+ // A call Framer refused: its message is Framer's, so it stays out.
+ if (err instanceof FramerPluginError) {
+ return new FramerError('failed', 'Framer didn’t answer as expected. Try again.');
+ }
+ return err;
+}
+
+/** Closes a connection, its failure aside; the answer doesn't wait long for Framer's goodbye. */
+async function close(framer) {
+ let timer;
+ await Promise.race([
+ Promise.resolve()
+ .then(() => framer.disconnect())
+ .catch(() => {}),
+ new Promise((resolve) => {
+ timer = setTimeout(resolve, CLOSE_WAIT_MS);
+ timer.unref?.();
+ }),
+ ]);
+ clearTimeout(timer);
+}
+
+/**
+ * Connects to a project, runs `fn` with it and closes the connection,
+ * whatever happened. A use that takes longer than `timeoutMs` fails
+ * ('unreachable'), and a connection that opens after that is closed as it
+ * opens. `connect` replaces framer-api's in tests.
+ *
+ * @template T
+ * @param {string} project from projectRef()
+ * @param {string} apiKey
+ * @param {(framer: import('framer-api').Framer) => Promise<T>} fn
+ * @returns {Promise<T>}
+ */
+export async function withProject(
+ project,
+ apiKey,
+ fn,
+ { connect = framerConnect, timeoutMs = TIMEOUT_MS } = {},
+) {
+ let framer = null;
+ let late = false;
+ let timer;
+ const work = (async () => {
+ const opened = await connect(project, apiKey);
+ if (late) {
+ await close(opened);
+ return undefined;
+ }
+ framer = opened;
+ return fn(opened);
+ })();
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(() => {
+ late = true;
+ reject(new FramerError('unreachable', 'Framer didn’t answer in time. Try again.'));
+ }, timeoutMs);
+ });
+ try {
+ return await Promise.race([work, timeout]);
+ } catch (err) {
+ throw framerError(err, framer !== null);
+ } finally {
+ clearTimeout(timer);
+ // A use that timed out still settles: its end is nobody's to read.
+ work.catch(() => {});
+ if (framer) await close(framer);
+ }
+}
+
+/** A name as kept: trimmed, cut to `max`, or null. */
+const nameOf = (value, max) =>
+ typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : null;
+
+/** The project's published address (https only, as site_url keeps it), or null. */
+function siteUrlOf(publish) {
+ const raw = typeof publish?.url === 'string' ? publish.url.trim() : '';
+ if (!raw) return null;
+ try {
+ const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`);
+ if (url.protocol !== 'https:') return null;
+ const address = `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
+ return address.length <= SITE_URL_MAX ? address : null;
+ } catch {
+ return null;
+ }
+}
+
+/** What a send needs to do to a user's collection. */
+const EDIT_CMS = ['Collection.addItems', 'CollectionItem.setAttributes'];
+
+/**
+ * Checks a project and a key before they're kept: Framer opens the project
+ * with the key, and the key's user can edit its CMS. framer-api 5.1.0 keeps
+ * `isAllowedTo` to plugins: when the connection has none, the check is
+ * left to the send.
+ *
+ * @param {string} project from projectRef()
+ * @returns {Promise<{ projectId: string, projectName: string|null, account: string|null,
+ * siteUrl: string|null }>} projectId: the id Framer connects to, as given
+ */
+export async function checkProject(project, apiKey, opts) {
+ return withProject(
+ project,
+ apiKey,
+ async (framer) => {
+ if (typeof framer.isAllowedTo === 'function' && !framer.isAllowedTo(...EDIT_CMS)) {
+ throw new FramerError(
+ 'no_access',
+ 'This key’s user can’t edit the CMS of the project. Make the key as a user who can.',
+ );
+ }
+ const [info, user, published] = await Promise.all([
+ framer.getProjectInfo(),
+ framer.getCurrentUser(),
+ framer.getPublishInfo(),
+ ]);
+ return {
+ projectId: project,
+ projectName: nameOf(info?.name, 300),
+ account: nameOf(user?.name, 200),
+ siteUrl: siteUrlOf(published?.production),
+ };
+ },
+ opts,
+ );
+}
+
+/**
+ * A collection as Send to CMS shows it: its fields with their Framer types
+ * as they are (the web offers the ones a part may go to), dividers left out,
+ * and whether each is required (the types that can't be have no flag).
+ * `titleField`: the field its items' slugs are made from.
+ */
+async function collectionShape(collection) {
+ const fields = await collection.getFields();
+ return {
+ id: collection.id,
+ name: nameOf(collection.name, 300) ?? collection.id,
+ titleField: collection.slugFieldBasedOn ?? null,
+ fields: fields
+ .filter((f) => f.type !== 'divider')
+ .map((f) => ({ id: f.id, name: f.name, type: f.type, required: f.required === true })),
+ };
+}
+
+/** The user's collections: a plugin's are read-only, so pages can't go to them. */
+const usersOwn = (collections) => collections.filter((c) => c.managedBy === 'user');
+
+/** The project's collections pages may go to, with their fields. */
+export async function listCollections(project, apiKey, opts) {
+ return withProject(
+ project,
+ apiKey,
+ async (framer) => Promise.all(usersOwn(await framer.getCollections()).map(collectionShape)),
+ opts,
+ );
+}
+
+/**
+ * One of the project's collections pages may go to, with its fields; read
+ * from the list, so an id that isn't one of them never reaches Framer as one.
+ */
+export async function collectionOf(project, apiKey, collectionId, opts) {
+ return withProject(
+ project,
+ apiKey,
+ async (framer) => {
+ const collection = usersOwn(await framer.getCollections()).find((c) => c.id === collectionId);
+ if (!collection) {
+ throw new FramerError(
+ 'not_found',
+ 'The project has no such collection, or a plugin manages it. Pick another.',
+ );
+ }
+ return collectionShape(collection);
+ },
+ opts,
+ );
+}
+
+/** The parts of a page a field map places, and the Framer field types each may go to. */
+const PART_TYPES = {
+ title: ['string'],
+ body: ['formattedText'],
+ metaTitle: ['string'],
+ metaDescription: ['string'],
+ jsonLd: ['string'],
+};
+const PAGE_PARTS = Object.keys(PART_TYPES);
+/** The parts every map places. */
+const NEEDED = {
+ title: 'title: pick the text field a page’s title goes to',
+ body: 'body: pick the formatted text field a page goes to',
+};
+/**
+ * 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(['title', 'body', 'metaTitle', 'metaDescription']);
+
+/**
+ * Whether a field map fits the collection: a page's title and body each
+ * have a 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.
+ *
+ * @param {Record<string, string|null|undefined>} fieldMap part → field id
+ * @param {{ id: string, name: string, type: string, required?: boolean }[]} fields
+ * @returns {{ ok: true, map: Record<string, string> } | { ok: false, problems: string[] }}
+ */
+export function checkFieldMap(fieldMap, fields) {
+ const byId = new Map(fields.map((f) => [f.id, f]));
+ const problems = [];
+ const map = {};
+ const used = new Set();
+ for (const part of PAGE_PARTS) {
+ const id = fieldMap?.[part];
+ if (id === undefined || id === null || id === '') {
+ if (NEEDED[part]) problems.push(NEEDED[part]);
+ continue;
+ }
+ const field = byId.get(id);
+ if (!field) {
+ problems.push(`${part}: the collection has no field "${String(id).slice(0, 100)}"`);
+ } else if (!PART_TYPES[part].includes(field.type)) {
+ problems.push(
+ `${part}: ${field.name} is ${field.type}, not ${PART_TYPES[part].join(' or ')}`,
+ );
+ } else if (used.has(id)) {
+ problems.push(`${part}: ${field.name} already takes another part`);
+ } else {
+ map[part] = id;
+ used.add(id);
+ }
+ }
+ const filled = new Set(
+ Object.entries(map)
+ .filter(([part]) => ALWAYS_FILLED.has(part))
+ .map(([, id]) => id),
+ );
+ const unfilled = fields.filter((f) => f.required && !filled.has(f.id));
+ 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 Framer, or pick another collection`,
+ );
+ }
+ return problems.length ? { ok: false, problems } : { ok: true, map };
+}
diff --git a/server/src/lib/cms/framer.test.js b/server/src/lib/cms/framer.test.js
new file mode 100644
index 000000000..4f75c0b45
--- /dev/null
+++ b/server/src/lib/cms/framer.test.js
@@ -0,0 +1,480 @@
+import { describe, expect, it, vi } from 'vitest';
+import { FramerAPIError, FramerPluginClosedError, FramerPluginError } from 'framer-api';
+import {
+ FramerError,
+ checkFieldMap,
+ checkProject,
+ collectionOf,
+ listCollections,
+ projectRef,
+ withProject,
+} from './framer.js';
+
+/**
+ * Framer's Server API for Send to CMS (#1331, phase 2): a project's address
+ * read, a project and key checked before they're kept, and its collections
+ * listed, against a fake of framer-api's connection (its answers as its
+ * types describe them). Nothing here reaches Framer.
+ */
+
+const PROJECT = 'AbCdEfGhIj0123456789';
+const KEY = 'fr_key_0123456789abcdefSECRET';
+
+// `required` as framer-api has it: on the types that can be required only.
+const field = (id, name, type, required) => ({
+ id,
+ name,
+ type,
+ ...(required === undefined ? {} : { required }),
+});
+const BLOG_FIELDS = [
+ field('fTitle', 'Title', 'string', true),
+ field('fDiv', '', 'divider'),
+ field('fBody', 'Content', 'formattedText', false),
+ field('fSeo', 'SEO Title', 'string', false),
+ field('fCover', 'Cover', 'image', false),
+ field('fOdd', 'Odd', 'unsupported'),
+];
+const collection = (id, name, managedBy, fields = BLOG_FIELDS, slugFieldBasedOn = 'fTitle') => ({
+ id,
+ name,
+ managedBy,
+ slugFieldBasedOn,
+ getFields: vi.fn(async () => fields),
+});
+
+/** A project as framer-api opens it, and a connect that opens it. */
+function fakeProject({
+ allowed = true,
+ production = { url: 'https://acme.framer.website/' },
+ projectName = ' Acme Coffee ',
+ userName = 'Ada Editor',
+} = {}) {
+ const framer = {
+ disconnect: vi.fn(async () => {}),
+ isAllowedTo: vi.fn(() => allowed),
+ getProjectInfo: vi.fn(async () => ({ id: 'hashed-id', name: projectName })),
+ getCurrentUser: vi.fn(async () => ({ id: 'u-hash', name: userName })),
+ getPublishInfo: vi.fn(async () => ({ production, staging: null })),
+ getCollections: vi.fn(async () => [
+ collection('cBlog', 'Blog', 'user'),
+ collection('cSynced', 'Synced', 'anotherPlugin'),
+ collection('cMine', 'Mine', 'thisPlugin'),
+ collection('cNews', 'News', 'user', [field('n1', 'Headline', 'string')], null),
+ ]),
+ };
+ return { framer, connect: vi.fn(async () => framer) };
+}
+
+/** A promise settled from outside. */
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+describe('projectRef', () => {
+ it('reads the project’s id from its address, or takes the id itself', () => {
+ expect(projectRef(PROJECT)).toBe(PROJECT);
+ expect(projectRef(` https://framer.com/projects/Acme-Site--${PROJECT} `)).toBe(PROJECT);
+ expect(projectRef(`https://www.framer.com/projects/Acme--${PROJECT}-x9Zq1?node=a1#b`)).toBe(
+ PROJECT,
+ );
+ expect(projectRef(`framer.com/projects/${PROJECT}/`)).toBe(PROJECT);
+ expect(projectRef(`https://framer.com/projects/My%20Site--${PROJECT}`)).toBe(PROJECT);
+ });
+
+ it('leaves a branch out: pages go to the main one', () => {
+ expect(projectRef(`https://framer.com/projects/Acme--${PROJECT}?branch=feature-x`)).toBe(
+ PROJECT,
+ );
+ });
+
+ it('reads the id after the last "--" of a name that has more than one', () => {
+ expect(projectRef(`https://framer.com/projects/Acme--Coffee--Blog--${PROJECT}`)).toBe(PROJECT);
+ expect(projectRef(`https://framer.com/projects/A--B--${PROJECT}-x9Zq1`)).toBe(PROJECT);
+ });
+
+ it('refuses anything else before Framer is called', () => {
+ for (const input of [
+ '',
+ 'not a project',
+ `http://framer.com/projects/Acme--${PROJECT}`,
+ `https://evil.example/projects/Acme--${PROJECT}`,
+ `https://framer.com.evil.example/projects/Acme--${PROJECT}`,
+ `https://user:[email protected]/projects/Acme--${PROJECT}`,
+ `https://framer.com:8443/projects/Acme--${PROJECT}`,
+ `https://framer.com/sites/Acme--${PROJECT}`,
+ 'https://framer.com/projects/',
+ 'https://framer.com/projects/Acme--short1234',
+ 'AbCdEfGhIj012345678',
+ 'AbCdEfGhIj0123456789X',
+ 'https://framer.com/projects/%E0%A4%A',
+ ]) {
+ expect(() => projectRef(input), input).toThrow(FramerError);
+ try {
+ projectRef(input);
+ } catch (err) {
+ expect(err.code).toBe('invalid');
+ }
+ }
+ });
+});
+
+describe('withProject', () => {
+ it('connects with the project and key, runs, and closes the connection', async () => {
+ const { framer, connect } = fakeProject();
+ const result = await withProject(PROJECT, KEY, async (f) => f.getProjectInfo(), { connect });
+ expect(result.name).toBe(' Acme Coffee ');
+ expect(connect).toHaveBeenCalledWith(PROJECT, KEY);
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('closes the connection when the work fails, and a failed close changes nothing', async () => {
+ const { framer, connect } = fakeProject();
+ framer.disconnect.mockRejectedValue(new Error('socket gone'));
+ await expect(
+ withProject(
+ PROJECT,
+ KEY,
+ async () => {
+ throw new FramerAPIError('Node not found', 'NODE_NOT_FOUND');
+ },
+ { connect },
+ ),
+ ).rejects.toMatchObject({ code: 'not_found' });
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ await expect(withProject(PROJECT, KEY, async () => 'done', { connect })).resolves.toBe('done');
+ });
+
+ it('says what Framer’s errors mean, in our words, never with the key', async () => {
+ const cases = [
+ ['UNAUTHORIZED', 'auth_failed'],
+ ['PROJECT_CLOSED', 'not_found'],
+ ['NODE_NOT_FOUND', 'not_found'],
+ ['TOKEN_SESSION_LIMIT', 'busy'],
+ ['POOL_EXHAUSTED', 'busy'],
+ ['TIMEOUT', 'unreachable'],
+ ['INVALID_REQUEST', 'invalid'],
+ ['INTERNAL', 'failed'],
+ ['EXPECTED_BRANCH_MISSING', 'failed'],
+ ];
+ for (const [framerCode, code] of cases) {
+ const connect = vi.fn(async () => {
+ throw new FramerAPIError(`Rejected token ${KEY} for ${PROJECT}`, framerCode);
+ });
+ const err = await withProject(PROJECT, KEY, async () => 'never', { connect }).catch((e) => e);
+ expect(err, framerCode).toBeInstanceOf(FramerError);
+ expect(err.code, framerCode).toBe(code);
+ expect(err.message).not.toContain(KEY);
+ expect(String(err.stack)).not.toContain(KEY);
+ }
+ });
+
+ it('reads a project closed mid-call as a dropped connection, not a missing project', async () => {
+ const { framer, connect } = fakeProject();
+ const dropped = await withProject(
+ PROJECT,
+ KEY,
+ async () => {
+ throw new FramerAPIError('Connection closed', 'PROJECT_CLOSED');
+ },
+ { connect },
+ ).catch((e) => e);
+ expect(dropped).toMatchObject({
+ code: 'unreachable',
+ message: 'Framer closed the connection. Try again.',
+ });
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ const opening = vi.fn(async () => {
+ throw new FramerAPIError(
+ 'Connection to the server was closed (code: 1006)',
+ 'PROJECT_CLOSED',
+ );
+ });
+ await expect(
+ withProject(PROJECT, KEY, async () => 'never', { connect: opening }),
+ ).rejects.toMatchObject({ code: 'not_found' });
+ });
+
+ it('reads a refused call and a closed connection, without Framer’s message', async () => {
+ const { connect } = fakeProject();
+ const refused = await withProject(
+ PROJECT,
+ KEY,
+ async () => {
+ throw new FramerPluginError(`Not allowed for ${KEY}`);
+ },
+ { connect },
+ ).catch((e) => e);
+ expect(refused).toMatchObject({ code: 'failed' });
+ expect(refused.message).not.toContain(KEY);
+ const closed = await withProject(
+ PROJECT,
+ KEY,
+ async () => {
+ throw new FramerPluginClosedError('closed');
+ },
+ { connect },
+ ).catch((e) => e);
+ expect(closed).toMatchObject({ code: 'unreachable' });
+ });
+
+ it('lets an error of our own code through as it is', async () => {
+ const { framer, connect } = fakeProject();
+ const bug = new TypeError('x is not a function');
+ await expect(
+ withProject(
+ PROJECT,
+ KEY,
+ async () => {
+ throw bug;
+ },
+ { connect },
+ ),
+ ).rejects.toBe(bug);
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('gives up on a connection that doesn’t open in time, and closes it when it opens', async () => {
+ const { framer } = fakeProject();
+ const opening = deferred();
+ const connect = vi.fn(() => opening.promise);
+ const fn = vi.fn();
+ const err = await withProject(PROJECT, KEY, fn, { connect, timeoutMs: 20 }).catch((e) => e);
+ expect(err).toMatchObject({ code: 'unreachable' });
+ expect(framer.disconnect).not.toHaveBeenCalled();
+ opening.resolve(framer);
+ await vi.waitFor(() => expect(framer.disconnect).toHaveBeenCalledTimes(1));
+ expect(fn).not.toHaveBeenCalled();
+ });
+
+ it('leaves no unhandled error behind a connection that opens or fails late', async () => {
+ const unhandled = vi.fn();
+ process.on('unhandledRejection', unhandled);
+ try {
+ const { framer } = fakeProject();
+ framer.disconnect.mockRejectedValue(new Error('socket gone'));
+ const opening = deferred();
+ const late = await withProject(PROJECT, KEY, vi.fn(), {
+ connect: () => opening.promise,
+ timeoutMs: 10,
+ }).catch((e) => e);
+ expect(late).toMatchObject({ code: 'unreachable' });
+ opening.resolve(framer);
+ await vi.waitFor(() => expect(framer.disconnect).toHaveBeenCalledTimes(1));
+ const failing = deferred();
+ await withProject(PROJECT, KEY, vi.fn(), {
+ connect: () => failing.promise,
+ timeoutMs: 10,
+ }).catch(() => {});
+ failing.reject(new FramerAPIError(`Unauthorized ${KEY}`, 'UNAUTHORIZED'));
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(unhandled).not.toHaveBeenCalled();
+ } finally {
+ process.off('unhandledRejection', unhandled);
+ }
+ });
+
+ it('gives up on work that doesn’t end in time, and closes the connection', async () => {
+ const { framer, connect } = fakeProject();
+ const err = await withProject(PROJECT, KEY, () => new Promise(() => {}), {
+ connect,
+ timeoutMs: 20,
+ }).catch((e) => e);
+ expect(err).toMatchObject({ code: 'unreachable' });
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('has nothing to close when the connection fails', async () => {
+ const connect = vi.fn(async () => {
+ throw new FramerAPIError('Unauthorized', 'UNAUTHORIZED');
+ });
+ await expect(withProject(PROJECT, KEY, async () => 'never', { connect })).rejects.toMatchObject(
+ { code: 'auth_failed' },
+ );
+ });
+});
+
+describe('checkProject', () => {
+ it('reads the project, the key’s user and the published address', async () => {
+ const { framer, connect } = fakeProject();
+ expect(await checkProject(PROJECT, KEY, { connect })).toEqual({
+ projectId: PROJECT,
+ projectName: 'Acme Coffee',
+ account: 'Ada Editor',
+ siteUrl: 'https://acme.framer.website',
+ });
+ expect(framer.isAllowedTo).toHaveBeenCalledWith(
+ 'Collection.addItems',
+ 'CollectionItem.setAttributes',
+ );
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps no address for a project not published', async () => {
+ const { connect } = fakeProject({ production: null });
+ expect((await checkProject(PROJECT, KEY, { connect })).siteUrl).toBeNull();
+ });
+
+ it('keeps the published address as an https address, or none', async () => {
+ const siteOf = async (url) =>
+ (await checkProject(PROJECT, KEY, { connect: fakeProject({ production: { url } }).connect }))
+ .siteUrl;
+ expect(await siteOf('acme.framer.website')).toBe('https://acme.framer.website');
+ expect(await siteOf('https://www.acme.example/blog/')).toBe('https://www.acme.example/blog');
+ expect(await siteOf('http://acme.framer.website')).toBeNull();
+ expect(await siteOf(`https://acme.example/${'a'.repeat(2048)}`)).toBeNull();
+ expect(await siteOf(' ')).toBeNull();
+ });
+
+ it('cuts the names to what the row keeps', async () => {
+ const { connect } = fakeProject({ projectName: 'P'.repeat(400), userName: 'U'.repeat(250) });
+ const checked = await checkProject(PROJECT, KEY, { connect });
+ expect(checked.projectName).toBe('P'.repeat(300));
+ expect(checked.account).toBe('U'.repeat(200));
+ const blank = fakeProject({ projectName: ' ', userName: null });
+ expect(await checkProject(PROJECT, KEY, { connect: blank.connect })).toMatchObject({
+ projectName: null,
+ account: null,
+ });
+ });
+
+ it('refuses a key whose user can’t edit the CMS', async () => {
+ const { framer, connect } = fakeProject({ allowed: false });
+ await expect(checkProject(PROJECT, KEY, { connect })).rejects.toMatchObject({
+ code: 'no_access',
+ });
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves the edit check to the send when the connection can’t tell (framer-api 5.1.0)', async () => {
+ const { framer, connect } = fakeProject();
+ delete framer.isAllowedTo;
+ expect((await checkProject(PROJECT, KEY, { connect })).projectName).toBe('Acme Coffee');
+ });
+});
+
+describe('listCollections', () => {
+ it('lists the user’s collections only, their fields as Framer types them, dividers left out', async () => {
+ const { framer, connect } = fakeProject();
+ expect(await listCollections(PROJECT, KEY, { connect })).toEqual([
+ {
+ id: 'cBlog',
+ name: 'Blog',
+ titleField: 'fTitle',
+ fields: [
+ { id: 'fTitle', name: 'Title', type: 'string', required: true },
+ { id: 'fBody', name: 'Content', type: 'formattedText', required: false },
+ { id: 'fSeo', name: 'SEO Title', type: 'string', required: false },
+ { id: 'fCover', name: 'Cover', type: 'image', required: false },
+ { id: 'fOdd', name: 'Odd', type: 'unsupported', required: false },
+ ],
+ },
+ {
+ id: 'cNews',
+ name: 'News',
+ titleField: null,
+ fields: [{ id: 'n1', name: 'Headline', type: 'string', required: false }],
+ },
+ ]);
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('collectionOf', () => {
+ it('reads one of the user’s collections', async () => {
+ const { connect } = fakeProject();
+ expect(await collectionOf(PROJECT, KEY, 'cNews', { connect })).toMatchObject({
+ id: 'cNews',
+ name: 'News',
+ });
+ });
+
+ it('finds none that is a plugin’s, or not the project’s', async () => {
+ const { framer, connect } = fakeProject();
+ for (const id of ['cSynced', 'cMine', 'cGone']) {
+ await expect(collectionOf(PROJECT, KEY, id, { connect }), id).rejects.toMatchObject({
+ code: 'not_found',
+ });
+ }
+ expect(framer.disconnect).toHaveBeenCalledTimes(3);
+ });
+});
+
+describe('checkFieldMap', () => {
+ const fields = BLOG_FIELDS.filter((f) => f.type !== 'divider').map((f) => ({
+ ...f,
+ required: false,
+ }));
+
+ it('keeps a map that fits, the parts left empty out', () => {
+ expect(
+ checkFieldMap(
+ { title: 'fTitle', body: 'fBody', metaTitle: 'fSeo', metaDescription: '', jsonLd: null },
+ fields,
+ ),
+ ).toEqual({ ok: true, map: { title: 'fTitle', body: 'fBody', metaTitle: 'fSeo' } });
+ });
+
+ it('says which part doesn’t fit', () => {
+ expect(checkFieldMap({ title: 'fBody', body: 'fTitle' }, fields)).toEqual({
+ ok: false,
+ problems: [
+ 'title: Content is formattedText, not string',
+ 'body: Title is string, not formattedText',
+ ],
+ });
+ expect(checkFieldMap({ title: 'fTitle', body: 'fBody', metaTitle: 'fTitle' }, fields)).toEqual({
+ ok: false,
+ problems: ['metaTitle: Title already takes another part'],
+ });
+ expect(checkFieldMap({ title: 'fTitle', body: 'nope' }, fields)).toEqual({
+ ok: false,
+ problems: ['body: the collection has no field "nope"'],
+ });
+ expect(checkFieldMap({ jsonLd: 'fCover' }, fields)).toEqual({
+ ok: false,
+ problems: [
+ 'title: pick the text field a page’s title goes to',
+ 'body: pick the formatted text field a page goes to',
+ 'jsonLd: Cover is image, not string',
+ ],
+ });
+ });
+
+ it('keeps a map that fills every field the collection requires', () => {
+ const required = fields.map((f) => (f.id === 'fTitle' ? { ...f, required: true } : f));
+ expect(checkFieldMap({ title: 'fTitle', body: 'fBody' }, required)).toEqual({
+ ok: true,
+ map: { title: 'fTitle', body: 'fBody' },
+ });
+ });
+
+ it('refuses a collection that requires a field Send to CMS doesn’t fill', () => {
+ const required = fields.map((f) =>
+ ['fCover', 'fSeo'].includes(f.id) ? { ...f, required: true } : f,
+ );
+ expect(checkFieldMap({ title: 'fTitle', body: 'fBody' }, required)).toEqual({
+ ok: false,
+ problems: [
+ 'The collection requires SEO Title, Cover, which Send to CMS doesn’t fill: make them optional in Framer, or pick another collection',
+ ],
+ });
+ // A page may have no JSON-LD: the field it goes to can't be required.
+ const cover = fields.map((f) => (f.id === 'fCover' ? { ...f, required: true } : f));
+ const seo = fields.map((f) => (f.id === 'fSeo' ? { ...f, required: true } : f));
+ expect(checkFieldMap({ title: 'fTitle', body: 'fBody' }, cover).problems).toEqual([
+ 'The collection requires Cover, which Send to CMS doesn’t fill: make it optional in Framer, or pick another collection',
+ ]);
+ expect(checkFieldMap({ title: 'fTitle', body: 'fBody', jsonLd: 'fSeo' }, seo).problems).toEqual(
+ [
+ 'The collection requires SEO Title, which Send to CMS doesn’t fill: make it optional in Framer, or pick another collection',
+ ],
+ );
+ });
+});
diff --git a/server/src/middleware/subscription.js b/server/src/middleware/subscription.js
index 6e46fdbb0..7cb5859c0 100644
--- a/server/src/middleware/subscription.js
+++ b/server/src/middleware/subscription.js
@@ -61,6 +61,8 @@ export const COST_STOPPING = [
// Disconnects a brand's WordPress site (cms-wordpress.js): its Application
// Password is revoked where the site allows.
{ method: 'DELETE', path: /^\/cms\/brands\/[^/]+\/wordpress\/?$/ },
+ // Disconnects a brand's Framer project (cms-framer.js): its API key is deleted.
+ { method: 'DELETE', path: /^\/cms\/brands\/[^/]+\/framer\/?$/ },
// 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 at
diff --git a/server/src/middleware/subscription.test.js b/server/src/middleware/subscription.test.js
index 762cf59ae..03e6701a6 100644
--- a/server/src/middleware/subscription.test.js
+++ b/server/src/middleware/subscription.test.js
@@ -158,6 +158,7 @@ describe('requireActiveSubscription', () => {
['DELETE', '/integrations/google-analytics'],
['DELETE', '/cms/brands/b1/webflow'],
['DELETE', '/cms/brands/b1/wordpress'],
+ ['DELETE', '/cms/brands/b1/framer'],
['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'],
@@ -184,6 +185,9 @@ describe('requireActiveSubscription', () => {
['POST', '/cms/brands/b1/webflow'],
['POST', '/cms/brands/b1/wordpress'],
['DELETE', '/cms/brands/b1/wordpress/extra'],
+ ['POST', '/cms/brands/b1/framer'],
+ ['PUT', '/cms/brands/b1/framer'],
+ ['DELETE', '/cms/brands/b1/framer/collections'],
['POST', '/bots/connections/b1'],
['DELETE', '/bots/connections/b1'],
['POST', '/catalog/sources'],
@@ -197,7 +201,7 @@ describe('requireActiveSubscription', () => {
expect(res.status).toHaveBeenCalledWith(402);
}
// Both Google disconnects are one route.
- expect(COST_STOPPING).toHaveLength(7);
+ expect(COST_STOPPING).toHaveLength(8);
});
it('lets an organization off a plan delete a brand, and nothing near it', async () => {
diff --git a/server/src/routes/cms-framer.js b/server/src/routes/cms-framer.js
new file mode 100644
index 000000000..39ba2f700
--- /dev/null
+++ b/server/src/routes/cms-framer.js
@@ -0,0 +1,326 @@
+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 {
+ FramerError,
+ checkFieldMap,
+ checkProject,
+ collectionOf,
+ listCollections,
+ projectRef,
+} from '../lib/cms/framer.js';
+import { cmsLimiter } from '../middleware/rate-limiter.js';
+import { assertWriter, brandOf } from './cms.js';
+
+/**
+ * A brand's Framer connection for Send to CMS (#1331, phase 2; 00295).
+ * Members read a brand's connection; admins and managers connect the
+ * brand's project with an API key made in it, pick the collection pages go
+ * to and its fields, and disconnect:
+ * GET /api/cms/brands/:brandId/framer the connection, or none
+ * POST /api/cms/brands/:brandId/framer { project, apiKey } connect, or replace the key
+ * GET /api/cms/brands/:brandId/framer/collections the project's collections, with their fields
+ * PUT /api/cms/brands/:brandId/framer { collectionId, fieldMap } where pages go
+ * DELETE /api/cms/brands/:brandId/framer disconnect
+ * The key passes through here once: it is checked with Framer, then sealed
+ * by the API (lib/cms/credentials.js). It is never stored in the clear,
+ * logged or sent back. Framer can't revoke a key through its API: the
+ * person deletes it in the project.
+ */
+
+const router = Router();
+
+const PROVIDER = 'framer';
+const COLUMNS =
+ 'id, brand_id, status, site_id, site_name, site_url, account, collection_id, collection_name, field_map, created_at, updated_at';
+
+const connectInput = z.object({
+ // The project's address (framer.com/projects/…) or its id, read by projectRef().
+ project: z.string().trim().min(1).max(2048),
+ // A Framer API key: no spaces.
+ apiKey: z.string().trim().min(8).max(512).regex(/^\S+$/),
+});
+// A Framer id (a collection's, a field's): compared with the project's own, never trusted.
+const framerId = z
+ .string()
+ .trim()
+ .max(100)
+ .regex(/^[\x21-\x7e]*$/);
+const part = framerId.nullable().optional();
+const mapInput = z.object({
+ collectionId: framerId.min(1),
+ // The parts of a page, each a field's id or none; no other key.
+ fieldMap: z
+ .object({ title: part, body: part, metaTitle: part, metaDescription: part, jsonLd: part })
+ .strict(),
+});
+
+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 key. */
+const shape = (row) =>
+ row
+ ? {
+ status: row.status,
+ projectId: row.site_id,
+ projectName: row.site_name,
+ siteUrl: row.site_url,
+ account: row.account,
+ collectionId: row.collection_id,
+ collectionName: row.collection_name,
+ fieldMap: row.field_map ?? {},
+ connectedAt: row.created_at,
+ updatedAt: row.updated_at,
+ }
+ : null;
+
+/** A brand that must have a connection to go on. */
+async function connected(id) {
+ const row = await connectionOf(id);
+ if (!row) {
+ const err = new Error('Connect Framer first.');
+ err.status = 409;
+ err.code = 'not_connected';
+ throw err;
+ }
+ return row;
+}
+
+/**
+ * Sets the status of the connection as it was read: one connected again
+ * 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('id', row.id)
+ .eq('provider', PROVIDER)
+ .eq('updated_at', row.updated_at);
+ if (error) throw new Error(error.message);
+}
+
+/**
+ * The connection's key, or 'auth_failed' when it has none the API can open.
+ * A failed read throws as it is: the key may be fine.
+ */
+async function keyOf(row) {
+ const credentials = await readCmsCredentials(row.id);
+ if (!credentials?.apiKey) {
+ throw new FramerError('auth_failed', 'The Framer API key can’t be read. Connect Framer again.');
+ }
+ return credentials.apiKey;
+}
+
+const FRAMER_STATUS = {
+ invalid: 400,
+ no_access: 403,
+ not_found: 404,
+ busy: 429,
+ unreachable: 502,
+ failed: 502,
+};
+
+/**
+ * Answers a failure: a key Framer refuses marks the connection that was
+ * read (`row`) auth_failed, so Settings asks for a new one. Logged by name
+ * only, since a message may quote what the person typed.
+ */
+async function fail(req, res, err, what, row) {
+ if (err instanceof FramerError) {
+ if (err.code === 'auth_failed' && row) {
+ await setStatus(row, 'auth_failed').catch((e) =>
+ req.log.warn({ err: { name: e?.name } }, 'cms framer refusal not kept'),
+ );
+ }
+ return res.status(FRAMER_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 Framer', code: 'failed' });
+}
+
+// The API keeps Framer's key encrypted, under CONNECTOR_CREDENTIALS_KEY.
+const notConfigured = (res) =>
+ res.status(503).json({ error: 'Framer 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/framer', 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 framer read error');
+ }
+});
+
+// POST — connect the brand's project, or replace its key: checked with Framer first.
+router.post('/brands/:brandId/framer', 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: 'Paste the project’s address and an API key made in it.',
+ code: 'invalid',
+ });
+ }
+ try {
+ await assertWriter(id, req.user.id);
+ if (!credentialsConfigured()) return notConfigured(res);
+ const project = projectRef(parsed.data.project);
+ const { apiKey } = parsed.data;
+ const checked = await checkProject(project, apiKey);
+ // A new key for the same project keeps where pages go; another project starts over.
+ const before = await connectionOf(id);
+ const kept = before?.site_id === checked.projectId ? before : null;
+ const { data: row, error } = await supabaseAdmin
+ .from('brand_cms_connections')
+ .upsert(
+ {
+ brand_id: id,
+ provider: PROVIDER,
+ site_id: checked.projectId,
+ site_name: checked.projectName,
+ site_url: checked.siteUrl,
+ account: checked.account,
+ collection_id: kept?.collection_id ?? null,
+ collection_name: kept?.collection_name ?? null,
+ field_map: kept?.field_map ?? {},
+ 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, { apiKey }, { setBy: req.user.id });
+ } catch (err) {
+ // Connected without its key, a send would use the one it replaced, maybe another project's.
+ await supabaseAdmin
+ .from('brand_cms_connections')
+ .update({ status: 'auth_failed', updated_at: new Date().toISOString() })
+ .eq('id', row.id);
+ throw err;
+ }
+ return res.json({ connection: shape(row) });
+ } catch (err) {
+ return fail(req, res, err, 'cms framer connect error');
+ }
+});
+
+// GET — the project's collections pages may go to, with their fields.
+router.get('/brands/:brandId/framer/collections', cmsLimiter, async (req, res) => {
+ const id = brandOf(req, res);
+ if (!id) return;
+ let row = null;
+ try {
+ await assertWriter(id, req.user.id);
+ if (!credentialsConfigured()) return notConfigured(res);
+ row = await connected(id);
+ const collections = await listCollections(row.site_id, await keyOf(row));
+ // Framer took the key again: a connection marked refused is connected.
+ if (row.status === 'auth_failed') await setStatus(row, 'connected');
+ return res.json({ collections });
+ } catch (err) {
+ return fail(req, res, err, 'cms framer collections error', row);
+ }
+});
+
+// PUT — where the brand's pages go: the collection and its fields.
+router.put('/brands/:brandId/framer', cmsLimiter, async (req, res) => {
+ const id = brandOf(req, res);
+ if (!id) return;
+ let row = null;
+ try {
+ await assertWriter(id, req.user.id);
+ if (!credentialsConfigured()) 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 { collectionId, fieldMap } = parsed.data;
+ const collection = await collectionOf(row.site_id, await keyOf(row), 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',
+ collection_id: collection.id,
+ collection_name: collection.name,
+ field_map: checked.map,
+ updated_at: new Date().toISOString(),
+ })
+ .eq('id', row.id)
+ .eq('provider', PROVIDER)
+ // The connection it was checked with: one connected again or removed meanwhile isn't overwritten.
+ .eq('updated_at', row.updated_at)
+ .select(COLUMNS)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!saved) {
+ const err = new Error(
+ 'Framer’s connection changed while this was saved. Reload and try again.',
+ );
+ err.status = 409;
+ err.code = 'changed';
+ throw err;
+ }
+ return res.json({ connection: shape(saved) });
+ } catch (err) {
+ return fail(req, res, err, 'cms framer settings error', row);
+ }
+});
+
+// DELETE — disconnect: the row goes, its key with it.
+router.delete('/brands/:brandId/framer', 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) {
+ const { error } = await supabaseAdmin.from('brand_cms_connections').delete().eq('id', row.id);
+ if (error) throw new Error(error.message);
+ }
+ // Framer has no API to revoke a key: the person deletes it in the project's Site Settings › General.
+ return res.json({ success: true, revoked: false });
+ } catch (err) {
+ return fail(req, res, err, 'cms framer disconnect error');
+ }
+});
+
+export default router;
diff --git a/server/src/routes/cms-framer.test.js b/server/src/routes/cms-framer.test.js
new file mode 100644
index 000000000..ddfa7bcaa
--- /dev/null
+++ b/server/src/routes/cms-framer.test.js
@@ -0,0 +1,549 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * /api/cms/brands/:brandId/framer (Send to CMS, #1331 phase 2, 00295): a
+ * brand's Framer connection. Members read it; admins and managers connect a
+ * project with an API key made in it, checked with Framer first, pick the
+ * collection and its fields, and disconnect; the key is never kept in the
+ * clear, logged or sent back.
+ */
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const PROJECT = 'AbCdEfGhIj0123456789';
+const OTHER_PROJECT = 'ZzYyXxWwVv9876543210';
+const KEY = 'fr_key_0123456789abcdefSECRET';
+
+let role;
+let rows;
+let configured;
+const assertBrandAccess = vi.fn();
+const credentials = { save: vi.fn(), read: vi.fn() };
+const framer = { checkProject: vi.fn(), listCollections: vi.fn(), collectionOf: 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/framer.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ checkProject: (...args) => framer.checkProject(...args),
+ listCollections: (...args) => framer.listCollections(...args),
+ collectionOf: (...args) => framer.collectionOf(...args),
+}));
+vi.mock('../middleware/rate-limiter.js', () => ({ cmsLimiter: (_req, _res, next) => next() }));
+
+const { default: router } = await import('./cms-framer.js');
+const { FramerError } = await import('../lib/cms/framer.js');
+
+let server;
+let base;
+let logged;
+
+const BLOG = {
+ id: 'cBlog',
+ name: 'Blog',
+ titleField: 'fTitle',
+ fields: [
+ { id: 'fTitle', name: 'Title', type: 'string' },
+ { id: 'fBody', name: 'Content', type: 'formattedText' },
+ { id: 'fSeo', name: 'SEO Title', type: 'string' },
+ { id: 'fCover', name: 'Cover', type: 'image' },
+ ],
+};
+
+beforeEach(async () => {
+ role = 'manager';
+ rows = [];
+ logged = [];
+ configured = true;
+ assertBrandAccess.mockReset().mockResolvedValue({ orgId: 'o1' });
+ credentials.save.mockReset().mockResolvedValue(undefined);
+ credentials.read.mockReset().mockResolvedValue({ apiKey: KEY });
+ framer.checkProject.mockReset().mockResolvedValue({
+ projectId: PROJECT,
+ projectName: 'Acme Coffee',
+ account: 'Ada Editor',
+ siteUrl: 'https://acme.framer.website',
+ });
+ framer.listCollections.mockReset().mockResolvedValue([BLOG]);
+ framer.collectionOf.mockReset().mockResolvedValue(BLOG);
+ 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}/framer`;
+});
+
+afterEach(() => new Promise((resolve) => server.close(resolve)));
+
+const call = (method, body, path = '') =>
+ fetch(`${base}${path}`, {
+ method,
+ headers: { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+const input = { project: `https://framer.com/projects/Acme-Site--${PROJECT}`, apiKey: KEY };
+const connectedRow = (extra = {}) => ({
+ id: 'cn1',
+ brand_id: BRAND,
+ provider: 'framer',
+ status: 'connected',
+ site_id: PROJECT,
+ site_name: 'Acme Coffee',
+ site_url: 'https://acme.framer.website',
+ account: 'Ada Editor',
+ collection_id: 'cBlog',
+ collection_name: 'Blog',
+ field_map: { title: 'fTitle', body: 'fBody' },
+ 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',
+ projectId: PROJECT,
+ projectName: 'Acme Coffee',
+ siteUrl: 'https://acme.framer.website',
+ account: 'Ada Editor',
+ collectionId: 'cBlog',
+ collectionName: 'Blog',
+ fieldMap: { title: 'fTitle', body: 'fBody' },
+ 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 project, keeps the connection and seals the key, 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(KEY);
+ expect(JSON.parse(text).connection).toMatchObject({
+ status: 'connected',
+ projectId: PROJECT,
+ projectName: 'Acme Coffee',
+ siteUrl: 'https://acme.framer.website',
+ account: 'Ada Editor',
+ collectionId: null,
+ fieldMap: {},
+ });
+ expect(framer.checkProject).toHaveBeenCalledWith(PROJECT, KEY);
+ expect(rows).toEqual([
+ expect.objectContaining({
+ brand_id: BRAND,
+ provider: 'framer',
+ site_id: PROJECT,
+ status: 'connected',
+ connected_by: 'u1',
+ }),
+ ]);
+ expect(JSON.stringify(rows)).not.toContain(KEY);
+ expect(credentials.save).toHaveBeenCalledWith('cn1', { apiKey: KEY }, { setBy: 'u1' });
+ });
+
+ it('keeps the collection and its fields for a new key to the same project', async () => {
+ rows = [connectedRow({ status: 'auth_failed' })];
+ await call('POST', input);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ status: 'connected',
+ collection_id: 'cBlog',
+ collection_name: 'Blog',
+ field_map: { title: 'fTitle', body: 'fBody' },
+ });
+ });
+
+ it('starts over for another project', async () => {
+ rows = [connectedRow()];
+ framer.checkProject.mockResolvedValueOnce({
+ projectId: OTHER_PROJECT,
+ projectName: 'Other',
+ account: 'Ada Editor',
+ siteUrl: null,
+ });
+ const res = await call('POST', { ...input, project: OTHER_PROJECT });
+ expect((await res.json()).connection).toMatchObject({
+ projectId: OTHER_PROJECT,
+ siteUrl: null,
+ collectionId: null,
+ collectionName: null,
+ fieldMap: {},
+ });
+ expect(framer.checkProject).toHaveBeenCalledWith(OTHER_PROJECT, KEY);
+ });
+
+ it('asks to connect again when the key 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');
+ });
+
+ it('keeps nothing when Framer refuses, and says why in its words', async () => {
+ framer.checkProject.mockRejectedValueOnce(
+ new FramerError('auth_failed', 'Framer refused the API key.'),
+ );
+ const res = await call('POST', input);
+ expect(res.status).toBe(409);
+ expect(await res.json()).toEqual({ error: 'Framer refused the API key.', code: 'auth_failed' });
+ expect(rows).toEqual([]);
+ expect(credentials.save).not.toHaveBeenCalled();
+ });
+
+ it('answers Framer’s other failures with their own statuses', async () => {
+ for (const [code, status] of [
+ ['invalid', 400],
+ ['no_access', 403],
+ ['not_found', 404],
+ ['busy', 429],
+ ['unreachable', 502],
+ ['failed', 502],
+ ]) {
+ framer.checkProject.mockRejectedValueOnce(new FramerError(code, 'no'));
+ const res = await call('POST', input);
+ expect(res.status, code).toBe(status);
+ expect((await res.json()).code).toBe(code);
+ }
+ });
+
+ it('refuses an address that isn’t a Framer project’s before calling Framer', async () => {
+ const res = await call('POST', {
+ ...input,
+ project: `https://evil.example/projects/${PROJECT}`,
+ });
+ expect(res.status).toBe(400);
+ expect((await res.json()).code).toBe('invalid');
+ expect(framer.checkProject).not.toHaveBeenCalled();
+ });
+
+ it('asks for the project and a key', async () => {
+ for (const body of [
+ {},
+ { project: input.project },
+ { ...input, apiKey: 'short' },
+ { ...input, apiKey: 'has a space in it' },
+ { ...input, project: '' },
+ ]) {
+ const res = await call('POST', body);
+ expect(res.status).toBe(400);
+ }
+ expect(framer.checkProject).not.toHaveBeenCalled();
+ });
+
+ it('is for admins and managers', async () => {
+ role = 'analyst';
+ const res = await call('POST', input);
+ expect(res.status).toBe(403);
+ expect(framer.checkProject).not.toHaveBeenCalled();
+ });
+
+ it('says Framer isn’t set up on a server that can’t keep a key', async () => {
+ configured = false;
+ const res = await call('POST', input);
+ expect(res.status).toBe(503);
+ expect((await res.json()).code).toBe('not_configured');
+ expect(framer.checkProject).not.toHaveBeenCalled();
+ });
+
+ it('logs a crash by name only', async () => {
+ framer.checkProject.mockRejectedValueOnce(new Error(`bad ${KEY}`));
+ const res = await call('POST', input);
+ expect(res.status).toBe(500);
+ expect(await res.text()).not.toContain(KEY);
+ expect(logged.join('')).not.toContain(KEY);
+ });
+});
+
+describe('GET collections', () => {
+ it('lists the project’s collections with the kept key', async () => {
+ rows = [connectedRow()];
+ const res = await call('GET', undefined, '/collections');
+ expect(await res.json()).toEqual({ collections: [BLOG] });
+ expect(credentials.read).toHaveBeenCalledWith('cn1');
+ expect(framer.listCollections).toHaveBeenCalledWith(PROJECT, KEY);
+ });
+
+ it('marks the connection refused when Framer refuses its key', async () => {
+ rows = [connectedRow()];
+ framer.listCollections.mockRejectedValueOnce(
+ new FramerError('auth_failed', 'Framer refused the API key.'),
+ );
+ const res = await call('GET', undefined, '/collections');
+ expect(res.status).toBe(409);
+ expect((await res.json()).code).toBe('auth_failed');
+ expect(rows[0].status).toBe('auth_failed');
+ });
+
+ it('leaves a connection made again meanwhile as it is', async () => {
+ rows = [connectedRow()];
+ framer.listCollections.mockImplementationOnce(async () => {
+ rows[0].updated_at = '2026-10-27T11:00:00Z';
+ throw new FramerError('auth_failed', 'Framer refused the API key.');
+ });
+ await call('GET', undefined, '/collections');
+ expect(rows[0].status).toBe('connected');
+ });
+
+ it('marks it refused when its key can’t be read', async () => {
+ rows = [connectedRow()];
+ credentials.read.mockResolvedValueOnce(null);
+ const res = await call('GET', undefined, '/collections');
+ expect(res.status).toBe(409);
+ expect(rows[0].status).toBe('auth_failed');
+ expect(framer.listCollections).not.toHaveBeenCalled();
+ });
+
+ it('answers a failed read of the key as a crash, the connection left as it is', async () => {
+ rows = [connectedRow()];
+ credentials.read.mockRejectedValueOnce(new Error('brand_cms_credentials read: 57014'));
+ const res = await call('GET', undefined, '/collections');
+ expect(res.status).toBe(500);
+ expect(rows[0].status).toBe('connected');
+ expect(framer.listCollections).not.toHaveBeenCalled();
+ });
+
+ it('connects a refused connection again once Framer takes its key', async () => {
+ rows = [connectedRow({ status: 'auth_failed' })];
+ expect((await call('GET', undefined, '/collections')).status).toBe(200);
+ expect(rows[0].status).toBe('connected');
+ });
+
+ it('asks to connect first, and is for admins and managers', async () => {
+ const res = await call('GET', undefined, '/collections');
+ expect(res.status).toBe(409);
+ expect((await res.json()).code).toBe('not_connected');
+ role = 'analyst';
+ rows = [connectedRow()];
+ expect((await call('GET', undefined, '/collections')).status).toBe(403);
+ expect(framer.listCollections).not.toHaveBeenCalled();
+ });
+});
+
+describe('PUT where pages go', () => {
+ it('keeps a field map that fits the collection, with its name', async () => {
+ rows = [connectedRow({ collection_id: null, collection_name: null, field_map: {} })];
+ const res = await call('PUT', {
+ collectionId: 'cBlog',
+ fieldMap: { title: 'fTitle', body: 'fBody', metaTitle: 'fSeo', metaDescription: null },
+ });
+ expect(res.status).toBe(200);
+ expect((await res.json()).connection).toMatchObject({
+ collectionId: 'cBlog',
+ collectionName: 'Blog',
+ fieldMap: { title: 'fTitle', body: 'fBody', metaTitle: 'fSeo' },
+ });
+ expect(framer.collectionOf).toHaveBeenCalledWith(PROJECT, KEY, 'cBlog');
+ });
+
+ it('refuses a part on a field of the wrong type, and a field taken twice', async () => {
+ rows = [connectedRow()];
+ const wrong = await call('PUT', {
+ collectionId: 'cBlog',
+ fieldMap: { title: 'fTitle', body: 'fCover' },
+ });
+ expect(wrong.status).toBe(400);
+ expect(await wrong.json()).toMatchObject({
+ code: 'invalid_map',
+ problems: ['body: Cover is image, not formattedText'],
+ });
+ const twice = await call('PUT', {
+ collectionId: 'cBlog',
+ fieldMap: { title: 'fTitle', body: 'fBody', metaTitle: 'fTitle' },
+ });
+ expect(twice.status).toBe(400);
+ expect((await twice.json()).problems).toEqual(['metaTitle: Title already takes another part']);
+ expect(rows[0].field_map).toEqual({ title: 'fTitle', body: 'fBody' });
+ });
+
+ it('refuses a collection that isn’t one pages may go to', async () => {
+ rows = [connectedRow()];
+ framer.collectionOf.mockRejectedValueOnce(
+ new FramerError('not_found', 'The project has no such collection.'),
+ );
+ const res = await call('PUT', { collectionId: 'cSynced', fieldMap: {} });
+ expect(res.status).toBe(404);
+ expect(rows[0].collection_id).toBe('cBlog');
+ });
+
+ it('refuses settings that aren’t a collection and a map of the page’s parts', async () => {
+ rows = [connectedRow()];
+ for (const body of [
+ {},
+ { collectionId: '', fieldMap: {} },
+ { collectionId: 'cBlog' },
+ { collectionId: 'cBlog', fieldMap: { title: 'fTitle', body: 'fBody', author: 'fSeo' } },
+ { collectionId: 'cBlog', fieldMap: { title: 'f Title', body: 'fBody' } },
+ ]) {
+ const res = await call('PUT', body);
+ expect(res.status).toBe(400);
+ expect((await res.json()).code).toBe('invalid');
+ }
+ expect(framer.collectionOf).not.toHaveBeenCalled();
+ });
+
+ it('marks the connection refused when Framer refuses its key', async () => {
+ rows = [connectedRow()];
+ framer.collectionOf.mockRejectedValueOnce(
+ new FramerError('auth_failed', 'Framer refused the API key.'),
+ );
+ const res = await call('PUT', {
+ collectionId: 'cBlog',
+ fieldMap: { title: 'fTitle', body: 'fBody' },
+ });
+ expect(res.status).toBe(409);
+ expect((await res.json()).code).toBe('auth_failed');
+ expect(rows[0].status).toBe('auth_failed');
+ });
+
+ it('asks to connect first, is for admins and managers, and needs a server that keeps keys', async () => {
+ const body = { collectionId: 'cBlog', fieldMap: { title: 'fTitle', body: 'fBody' } };
+ const none = await call('PUT', body);
+ expect(none.status).toBe(409);
+ expect((await none.json()).code).toBe('not_connected');
+ rows = [connectedRow()];
+ role = 'analyst';
+ expect((await call('PUT', body)).status).toBe(403);
+ role = 'manager';
+ configured = false;
+ const off = await call('PUT', body);
+ expect(off.status).toBe(503);
+ expect((await off.json()).code).toBe('not_configured');
+ expect(framer.collectionOf).not.toHaveBeenCalled();
+ });
+
+ it('doesn’t overwrite a connection made again meanwhile', async () => {
+ rows = [connectedRow()];
+ framer.collectionOf.mockImplementationOnce(async () => {
+ rows[0].updated_at = '2026-10-27T11:00:00Z';
+ return BLOG;
+ });
+ const res = await call('PUT', {
+ collectionId: 'cBlog',
+ fieldMap: { title: 'fTitle', body: 'fBody', metaTitle: 'fSeo' },
+ });
+ expect(res.status).toBe(409);
+ expect((await res.json()).code).toBe('changed');
+ expect(rows[0].field_map).toEqual({ title: 'fTitle', body: 'fBody' });
+ });
+});
+
+describe('DELETE', () => {
+ it('removes the connection, and says Framer’s key isn’t revoked', async () => {
+ rows = [connectedRow()];
+ const res = await call('DELETE');
+ expect(await res.json()).toEqual({ success: true, revoked: false });
+ expect(rows).toEqual([]);
+ expect(await (await call('DELETE')).json()).toEqual({ success: true, revoked: false });
+ });
+
+ 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/index.js b/server/src/routes/index.js
index ed82f105a..a1ea35587 100644
--- a/server/src/routes/index.js
+++ b/server/src/routes/index.js
@@ -19,6 +19,7 @@ import brandFactRoutes from './brand-facts.js';
import catalogRoutes from './catalog.js';
import cmsRoutes from './cms.js';
import cmsWordPressRoutes from './cms-wordpress.js';
+import cmsFramerRoutes from './cms-framer.js';
const router = Router();
@@ -42,6 +43,7 @@ router.use('/brand-facts', brandFactRoutes);
router.use('/catalog', catalogRoutes);
router.use('/cms', cmsRoutes);
router.use('/cms', cmsWordPressRoutes);
+router.use('/cms', cmsFramerRoutes);
router.get('/health', (req, res) => {
res.json({ status: 'ok', user: req.user?.id });
diff --git a/supabase/migrations/00295_cms_framer.sql b/supabase/migrations/00295_cms_framer.sql
new file mode 100644
index 000000000..24ff0b0b4
--- /dev/null
+++ b/supabase/migrations/00295_cms_framer.sql
@@ -0,0 +1,134 @@
+-- ============================================================================
+-- 00295: Framer for Send to CMS (#1331, phase 2)
+-- ============================================================================
+-- After Webflow (00283, 00284) and WordPress (00294), a brand connects its
+-- Framer project: the project's address (or its id) and an API key made in
+-- the project (Site Settings › General). The API reaches it through Framer's
+-- Server API, and pages go to one of the project's CMS collections.
+--
+-- * brand_cms_connections takes provider 'framer'. A Framer connection
+-- keeps the project's id (`site_id`, the one Framer connects to), its
+-- name (`site_name`), its published address (`site_url`, empty while the
+-- project isn't published) and the user the key acts as (`account`).
+-- The collection and `field_map` are picked as Webflow's are, the map
+-- naming field ids: { title, body, metaTitle, metaDescription, jsonLd }.
+-- * The API key is kept in brand_cms_credentials, sealed as WordPress's
+-- sign-in is (00294); the table itself doesn't change.
+-- * content_draft_deliveries.target takes 'framer'. `target_collection`
+-- keeps the collection the item was written to, as it keeps Webflow's.
+-- * reserve_content_deliveries: as 00294, a page already queued for the
+-- same CMS (Webflow, WordPress or Framer) 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', 'framer'));
+
+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
+ when 'framer' then site_id is not null
+ else false
+ end
+ );
+
+comment on column public.brand_cms_connections.site_id is
+ 'Webflow: the site pages go to (00283). Framer (00295): the project''s id, as Framer connects to it.';
+comment on column public.brand_cms_connections.site_name is
+ 'The site''s name (Webflow, WordPress), or the Framer project''s (00295).';
+comment on column public.brand_cms_connections.site_url is
+ 'WordPress (00294): the site''s address, its REST API at /wp-json/. Framer (00295): the project''s published address, null while it isn''t published.';
+comment on column public.brand_cms_connections.account is
+ 'WordPress (00294): the user the connection signs in as, with an Application Password. Framer (00295): the user the API key acts as. Both kept in brand_cms_credentials.';
+comment on column public.brand_cms_connections.field_map is
+ 'Which of the collection''s fields takes each part of a page: Webflow (00283) { body, metaTitle, metaDescription, jsonLd } → field slugs; Framer (00295) { title, body, metaTitle, metaDescription, jsonLd } → field ids.';
+
+comment on table public.brand_cms_credentials is
+ 'Send to CMS (#1331, 00294, 00295): a CMS connection''s sign-in (WordPress: the user and the Application Password; Framer: the project''s API key), 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', 'framer'));
+
+comment on column public.content_draft_deliveries.target is
+ 'Where the page was sent (00284, 00294, 00295): the brand''s webhook, its Webflow collection, its WordPress site or its Framer collection (00283).';
+comment on column public.content_draft_deliveries.target_collection is
+ 'The Webflow or Framer collection (00284, 00295), or the WordPress site''s address (00294), the page''s item or post was written to; its id is external_id.';
+
+-- ----------------------------------------------------------------------------
+-- As 00294, with Framer among the CMSs a page isn't sent to twice at once.
+-- ----------------------------------------------------------------------------
+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', 'framer') 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.sql
index 705a75a4c..9460b94d0 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -41752,6 +41752,144 @@ grant execute on function public.reserve_content_deliveries(uuid, uuid, uuid, uu
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00295_cms_framer.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00295: Framer for Send to CMS (#1331, phase 2)
+-- ============================================================================
+-- After Webflow (00283, 00284) and WordPress (00294), a brand connects its
+-- Framer project: the project's address (or its id) and an API key made in
+-- the project (Site Settings › General). The API reaches it through Framer's
+-- Server API, and pages go to one of the project's CMS collections.
+--
+-- * brand_cms_connections takes provider 'framer'. A Framer connection
+-- keeps the project's id (`site_id`, the one Framer connects to), its
+-- name (`site_name`), its published address (`site_url`, empty while the
+-- project isn't published) and the user the key acts as (`account`).
+-- The collection and `field_map` are picked as Webflow's are, the map
+-- naming field ids: { title, body, metaTitle, metaDescription, jsonLd }.
+-- * The API key is kept in brand_cms_credentials, sealed as WordPress's
+-- sign-in is (00294); the table itself doesn't change.
+-- * content_draft_deliveries.target takes 'framer'. `target_collection`
+-- keeps the collection the item was written to, as it keeps Webflow's.
+-- * reserve_content_deliveries: as 00294, a page already queued for the
+-- same CMS (Webflow, WordPress or Framer) 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', 'framer'));
+
+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
+ when 'framer' then site_id is not null
+ else false
+ end
+ );
+
+comment on column public.brand_cms_connections.site_id is
+ 'Webflow: the site pages go to (00283). Framer (00295): the project''s id, as Framer connects to it.';
+comment on column public.brand_cms_connections.site_name is
+ 'The site''s name (Webflow, WordPress), or the Framer project''s (00295).';
+comment on column public.brand_cms_connections.site_url is
+ 'WordPress (00294): the site''s address, its REST API at /wp-json/. Framer (00295): the project''s published address, null while it isn''t published.';
+comment on column public.brand_cms_connections.account is
+ 'WordPress (00294): the user the connection signs in as, with an Application Password. Framer (00295): the user the API key acts as. Both kept in brand_cms_credentials.';
+comment on column public.brand_cms_connections.field_map is
+ 'Which of the collection''s fields takes each part of a page: Webflow (00283) { body, metaTitle, metaDescription, jsonLd } → field slugs; Framer (00295) { title, body, metaTitle, metaDescription, jsonLd } → field ids.';
+
+comment on table public.brand_cms_credentials is
+ 'Send to CMS (#1331, 00294, 00295): a CMS connection''s sign-in (WordPress: the user and the Application Password; Framer: the project''s API key), 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', 'framer'));
+
+comment on column public.content_draft_deliveries.target is
+ 'Where the page was sent (00284, 00294, 00295): the brand''s webhook, its Webflow collection, its WordPress site or its Framer collection (00283).';
+comment on column public.content_draft_deliveries.target_collection is
+ 'The Webflow or Framer collection (00284, 00295), or the WordPress site''s address (00294), the page''s item or post was written to; its id is external_id.';
+
+-- ----------------------------------------------------------------------------
+-- As 00294, with Framer among the CMSs a page isn't sent to twice at once.
+-- ----------------------------------------------------------------------------
+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', 'framer') 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
-- ─────────────────────────────────────────────────────────────────────────