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(demo): keep the demo brand's sample data from changing or costing anything (demo brand, part 4) (#1737)

Cihan077e9258e94a
diff --git a/server/src/lib/active-subscriptions.js b/server/src/lib/active-subscriptions.js
index 6eda2bc54..84a5ee0ba 100644
--- a/server/src/lib/active-subscriptions.js
+++ b/server/src/lib/active-subscriptions.js
@@ -61,17 +61,24 @@ export async function activeOrgFilter(orgIds) {
return (orgId) => active.has(orgId);
}
+/** Why no work may start for a brand: a demo brand's sample data (00380). */
+export const DEMO_BRAND_REASON = 'demo_brand';
+/** Why no work may start for a brand: its organization has no active plan. */
+export const SUBSCRIPTION_INACTIVE_REASON = 'subscription_inactive';
+
/**
- * A test for the ids among `brandIds`: whether the brand is a real one (not
- * a demo brand) whose organization has an active or trialing subscription
- * (any, self-hosted). Throws when the brands can't be read.
+ * For the ids among `brandIds`, why no work may start for the brand, or null
+ * when it may: DEMO_BRAND_REASON for a demo brand (on the cloud or
+ * self-hosted), SUBSCRIPTION_INACTIVE_REASON for a brand whose organization
+ * has no active or trialing subscription (on the cloud), or that wasn't
+ * found. Throws when the brands can't be read.
*
* @param {string[]} brandIds
- * @returns {Promise<(brandId: string) => boolean>}
+ * @returns {Promise<(brandId: string) => string|null>}
*/
-export async function activeBrandFilter(brandIds) {
+export async function brandStopReasons(brandIds) {
const ids = uniqueIds(brandIds);
- if (ids.length === 0) return () => false;
+ if (ids.length === 0) return () => SUBSCRIPTION_INACTIVE_REASON;
const cloud = isCloud();
const { data, error } = await selectInChunks(ids, (chunk) =>
supabaseAdmin
@@ -80,16 +87,40 @@ export async function activeBrandFilter(brandIds) {
.in('id', chunk),
);
if (error) throw new Error(`brands read: ${error.message}`);
- const active = new Set(
- (data ?? [])
- .filter(
- (brand) =>
- !brand.is_demo &&
- (!cloud || isSubscriptionActive(brand.organizations?.subscription_status)),
- )
- .map((brand) => brand.id),
+ const reasons = new Map(
+ (data ?? []).map((brand) => {
+ if (brand.is_demo) return [brand.id, DEMO_BRAND_REASON];
+ if (cloud && !isSubscriptionActive(brand.organizations?.subscription_status)) {
+ return [brand.id, SUBSCRIPTION_INACTIVE_REASON];
+ }
+ return [brand.id, null];
+ }),
);
- return (brandId) => active.has(brandId);
+ return (brandId) => (reasons.has(brandId) ? reasons.get(brandId) : SUBSCRIPTION_INACTIVE_REASON);
+}
+
+/**
+ * A test for the ids among `brandIds`: whether the brand is a real one (not
+ * a demo brand) whose organization has an active or trialing subscription
+ * (any, self-hosted). Throws when the brands can't be read.
+ *
+ * @param {string[]} brandIds
+ * @returns {Promise<(brandId: string) => boolean>}
+ */
+export async function activeBrandFilter(brandIds) {
+ const reasonFor = await brandStopReasons(brandIds);
+ return (brandId) => reasonFor(brandId) === null;
+}
+
+/**
+ * Why no work may start for one brand, or null when it may (brandStopReasons):
+ * for a job that starts work for one brand, and says why it didn't.
+ *
+ * @param {string} brandId
+ * @returns {Promise<string|null>}
+ */
+export async function brandStopReason(brandId) {
+ return (await brandStopReasons([brandId]))(brandId);
}
/**
diff --git a/server/src/lib/active-subscriptions.test.js b/server/src/lib/active-subscriptions.test.js
index 230ed58c4..970932100 100644
--- a/server/src/lib/active-subscriptions.test.js
+++ b/server/src/lib/active-subscriptions.test.js
@@ -47,6 +47,8 @@ const {
MAX_CACHED_ANSWERS,
activeBrandFilter,
activeOrgFilter,
+ brandStopReason,
+ brandStopReasons,
clearCachedAnswers,
isBrandActive,
isBrandActiveCached,
@@ -159,6 +161,32 @@ describe('cloud', () => {
});
});
+describe('brandStopReasons and brandStopReason', () => {
+ it('says why no work may start: demo_brand before an ended plan, null when it may', async () => {
+ vi.stubEnv('IS_CLOUD', 'true');
+ const reasonFor = await brandStopReasons(['b-active', 'b-canceled', 'b-orphan', 'b-demo']);
+ expect(['b-active', 'b-canceled', 'b-orphan', 'b-demo', 'b-missing'].map(reasonFor)).toEqual([
+ null,
+ 'subscription_inactive',
+ 'subscription_inactive',
+ 'demo_brand',
+ 'subscription_inactive',
+ ]);
+ expect(reads).toHaveLength(1);
+ });
+
+ it('self-hosted, stops only a demo brand', async () => {
+ vi.stubEnv('IS_CLOUD', 'false');
+ expect(await brandStopReason('b-canceled')).toBe(null);
+ expect(await brandStopReason('b-demo')).toBe('demo_brand');
+ });
+
+ it('reads nothing for no ids', async () => {
+ expect((await brandStopReasons([]))('b-active')).toBe('subscription_inactive');
+ expect(reads).toHaveLength(0);
+ });
+});
+
describe('isOrgActive', () => {
it('tells one organization, on the cloud by its subscription, self-hosted always', async () => {
vi.stubEnv('IS_CLOUD', 'true');
diff --git a/server/src/lib/demo/idle-sweep.js b/server/src/lib/demo/idle-sweep.js
new file mode 100644
index 000000000..464656fb5
--- /dev/null
+++ b/server/src/lib/demo/idle-sweep.js
@@ -0,0 +1,101 @@
+import supabaseAdmin from '../../config/supabase.js';
+import { logger } from '../logger.js';
+import { clearDemoData } from './index.js';
+
+/**
+ * A demo brand nobody opened for a while doesn't keep its sample data
+ * (00380): every organization gets one, so the rows would pile up for
+ * workspaces that left. A visit rebuilds the demo every few days
+ * (DEMO_MAX_AGE_MS), so one built over IDLE_DAYS ago wasn't opened since.
+ * The daily run clears its data the way a rebuild does (clearDemoData, in
+ * the modules' reverse order, so rows go before the rows they point to)
+ * and keeps the brand row with no version and no build time: the next
+ * visit builds it again in place, with the same deterministic ids, so
+ * links to it still work.
+ *
+ * A clear holds the brand as a build does (demo_version null, demo_built_at
+ * now), so a visit at the same moment waits for it instead of reading half
+ * the data, then rebuilds.
+ */
+
+/** A demo brand built longer ago than this is cleared. */
+export const IDLE_DAYS = 14;
+/** Demo brands cleared per daily run at most; the rest waits a day. */
+export const MAX_CLEARED = 200;
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/**
+ * Takes the brand for the clear, only if its row is still as read: a visit
+ * that started a build meanwhile keeps it.
+ */
+async function claim(db, brand, now) {
+ let query = db
+ .from('brands')
+ .update({ demo_version: null, demo_built_at: now.toISOString() })
+ .eq('id', brand.id)
+ .eq('is_demo', true)
+ .eq('demo_built_at', brand.demo_built_at);
+ query =
+ brand.demo_version === null || brand.demo_version === undefined
+ ? query.is('demo_version', null)
+ : query.eq('demo_version', brand.demo_version);
+ const { data, error } = await query.select('id');
+ if (error) throw new Error(`demo brand claim: ${error.message}`);
+ return (data ?? []).length > 0;
+}
+
+/** Leaves the brand with no build time: the next visit rebuilds it at once. */
+async function release(db, brandId, now) {
+ const { error } = await db
+ .from('brands')
+ .update({ demo_built_at: null })
+ .eq('id', brandId)
+ .is('demo_version', null)
+ .eq('demo_built_at', now.toISOString());
+ // The build lease runs out on its own; the next visit rebuilds then.
+ if (error) logger.warn({ brandId, err: error }, '[demo] cleared brand not released');
+}
+
+/**
+ * Clears the data of the demo brands built over IDLE_DAYS ago, MAX_CLEARED
+ * a run at most, and says how many it cleared. Never throws: a failure is
+ * logged.
+ *
+ * @param {{ db?: object, now?: Date, clear?: (brandId: string) => Promise<void> }} [options]
+ * @returns {Promise<number>}
+ */
+export async function sweepIdleDemoBrands({
+ db = supabaseAdmin,
+ now = new Date(),
+ clear = clearDemoData,
+} = {}) {
+ const cutoff = new Date(now.getTime() - IDLE_DAYS * DAY_MS).toISOString();
+ const { data: brands, error } = await db
+ .from('brands')
+ .select('id, demo_version, demo_built_at')
+ .eq('is_demo', true)
+ .lt('demo_built_at', cutoff)
+ .order('demo_built_at', { ascending: true })
+ .limit(MAX_CLEARED);
+ if (error) {
+ logger.error({ err: error }, '[demo] idle demo brands not read');
+ return 0;
+ }
+
+ let cleared = 0;
+ for (const brand of brands ?? []) {
+ try {
+ if (!(await claim(db, brand, now))) continue;
+ await clear(brand.id);
+ await release(db, brand.id, now);
+ cleared++;
+ } catch (err) {
+ // Held as a build that failed: a visit rebuilds it once the lease is
+ // up, and the sweep clears it again IDLE_DAYS on.
+ logger.error({ err, brandId: brand.id }, '[demo] idle demo brand not cleared');
+ }
+ }
+ if (cleared > 0) logger.info({ cleared }, '[demo] idle demo brands cleared');
+ return cleared;
+}
diff --git a/server/src/lib/demo/idle-sweep.test.js b/server/src/lib/demo/idle-sweep.test.js
new file mode 100644
index 000000000..a79453dd6
--- /dev/null
+++ b/server/src/lib/demo/idle-sweep.test.js
@@ -0,0 +1,174 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../config/supabase.js', () => ({ default: {} }));
+vi.mock('../logger.js', () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+const { IDLE_DAYS, MAX_CLEARED, sweepIdleDemoBrands } = await import('./idle-sweep.js');
+const { demoState } = await import('./index.js');
+
+/**
+ * Demo brands nobody opened for IDLE_DAYS lose their sample data, not their
+ * row: the next visit builds them again in place.
+ */
+
+const NOW = new Date('2026-10-28T03:00:00Z');
+const daysAgo = (days) => new Date(NOW.getTime() - days * 24 * 60 * 60 * 1000).toISOString();
+
+/** The brands table, enough for the sweep's reads and conditional updates. */
+function fakeDb(brands, { failUpdate = false } = {}) {
+ const updates = [];
+ const matches = (row, filters) =>
+ filters.every(([op, column, value]) => {
+ if (op === 'eq') return row[column] === value;
+ if (op === 'is') return row[column] === value;
+ return row[column] !== null && row[column] < value;
+ });
+ const db = {
+ updates,
+ from: (table) => {
+ expect(table).toBe('brands');
+ const filters = [];
+ let values = null;
+ let limit = Infinity;
+ const chain = {
+ select: () => chain,
+ update: (next) => {
+ values = next;
+ return chain;
+ },
+ eq: (column, value) => {
+ filters.push(['eq', column, value]);
+ return chain;
+ },
+ is: (column, value) => {
+ filters.push(['is', column, value]);
+ return chain;
+ },
+ lt: (column, value) => {
+ filters.push(['lt', column, value]);
+ return chain;
+ },
+ order: () => chain,
+ limit: (n) => {
+ limit = n;
+ return chain;
+ },
+ then: (resolve, reject) => {
+ const found = brands.filter((row) => matches(row, filters));
+ if (values) {
+ if (failUpdate) return Promise.resolve({ data: null, error: { message: 'down' } });
+ for (const row of found) Object.assign(row, values);
+ updates.push({ values, ids: found.map((row) => row.id) });
+ return Promise.resolve({ data: found.map(({ id }) => ({ id })), error: null }).then(
+ resolve,
+ reject,
+ );
+ }
+ const data = found
+ .sort((a, b) => a.demo_built_at.localeCompare(b.demo_built_at))
+ .slice(0, limit)
+ .map((row) => ({ ...row }));
+ return Promise.resolve({ data, error: null }).then(resolve, reject);
+ },
+ };
+ return chain;
+ },
+ };
+ return db;
+}
+
+let brands;
+beforeEach(() => {
+ brands = [
+ { id: 'idle', is_demo: true, demo_version: 1, demo_built_at: daysAgo(IDLE_DAYS + 3) },
+ { id: 'recent', is_demo: true, demo_version: 1, demo_built_at: daysAgo(IDLE_DAYS - 1) },
+ { id: 'cleared', is_demo: true, demo_version: null, demo_built_at: null },
+ { id: 'real', is_demo: false, demo_version: null, demo_built_at: null },
+ ];
+});
+
+describe('sweepIdleDemoBrands', () => {
+ it("clears an idle demo brand's data and keeps its row, unbuilt", async () => {
+ const db = fakeDb(brands);
+ const clear = vi.fn(async (brandId) => {
+ // Held as a build while its rows go: a visit now waits.
+ const row = brands.find((brand) => brand.id === brandId);
+ expect(row.demo_version).toBe(null);
+ expect(demoState(row, NOW)).toBe('building');
+ });
+
+ expect(await sweepIdleDemoBrands({ db, now: NOW, clear })).toBe(1);
+
+ expect(clear.mock.calls).toEqual([['idle']]);
+ expect(brands[0]).toMatchObject({ id: 'idle', demo_version: null, demo_built_at: null });
+ // The next visit rebuilds it at once.
+ expect(demoState(brands[0], NOW)).toBe('stale');
+ // The others are as they were.
+ expect(brands[1].demo_version).toBe(1);
+ expect(brands[2]).toMatchObject({ demo_version: null, demo_built_at: null });
+ });
+
+ it('leaves a brand that a visit started building meanwhile', async () => {
+ const db = fakeDb(brands);
+ // The visit's claim lands between the sweep's read and its own.
+ const from = db.from;
+ let reads = 0;
+ db.from = (table) => {
+ const chain = from(table);
+ if (reads++ === 1) {
+ Object.assign(brands[0], { demo_version: null, demo_built_at: NOW.toISOString() });
+ }
+ return chain;
+ };
+ const clear = vi.fn();
+
+ expect(await sweepIdleDemoBrands({ db, now: NOW, clear })).toBe(0);
+ expect(clear).not.toHaveBeenCalled();
+ });
+
+ it('keeps the brand held when its clear fails, and goes on to the next', async () => {
+ brands.push({ id: 'idle-2', is_demo: true, demo_version: 1, demo_built_at: daysAgo(30) });
+ const db = fakeDb(brands);
+ const clear = vi.fn(async (brandId) => {
+ if (brandId === 'idle-2') throw new Error('timeout');
+ });
+
+ expect(await sweepIdleDemoBrands({ db, now: NOW, clear })).toBe(1);
+ const failed = brands.find((brand) => brand.id === 'idle-2');
+ expect(failed).toMatchObject({ demo_version: null, demo_built_at: NOW.toISOString() });
+ expect(brands[0]).toMatchObject({ demo_version: null, demo_built_at: null });
+ });
+
+ it('clears MAX_CLEARED brands a run at most, the oldest first', async () => {
+ brands = Array.from({ length: MAX_CLEARED + 5 }, (_, i) => ({
+ id: `b${i}`,
+ is_demo: true,
+ demo_version: 1,
+ demo_built_at: daysAgo(IDLE_DAYS + 1 + i),
+ }));
+ const clear = vi.fn();
+ expect(await sweepIdleDemoBrands({ db: fakeDb(brands), now: NOW, clear })).toBe(MAX_CLEARED);
+ expect(clear.mock.calls[0]).toEqual([`b${MAX_CLEARED + 4}`]);
+ });
+
+ it('never throws: a failed read clears nothing', async () => {
+ const db = {
+ from: () => ({
+ select: () => ({
+ eq: () => ({
+ lt: () => ({
+ order: () => ({
+ limit: async () => ({ data: null, error: { message: 'down' } }),
+ }),
+ }),
+ }),
+ }),
+ }),
+ };
+ const clear = vi.fn();
+ expect(await sweepIdleDemoBrands({ db, now: NOW, clear })).toBe(0);
+ expect(clear).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/lib/demo/write-guard.test.js b/server/src/lib/demo/write-guard.test.js
new file mode 100644
index 000000000..661a8af8d
--- /dev/null
+++ b/server/src/lib/demo/write-guard.test.js
@@ -0,0 +1,238 @@
+import { readdirSync, readFileSync } from 'fs';
+import { describe, expect, it } from 'vitest';
+import { brandScopedTables } from './coverage.js';
+
+/**
+ * People can't write the demo brand's data (00381): every table they can
+ * write under RLS that belongs to a brand carries refuse_demo_brand_writes,
+ * which lets only a role that bypasses RLS (the server) through. Read from
+ * the migrations, as coverage.test.js reads the brand-scoped tables: a new
+ * table people can write fails here until its migration attaches it.
+ */
+
+const dir = new URL('../../../../supabase/migrations/', import.meta.url);
+const files = readdirSync(dir)
+ .filter((file) => file.endsWith('.sql'))
+ .sort();
+const migrations = files.map((file) => readFileSync(new URL(file, dir), 'utf8'));
+
+/** Tables people can write that belong to no brand, and why they need no trigger. */
+const NOT_A_BRAND_ROW = {
+ api_keys: "The organization's API keys.",
+ brands:
+ "The brands themselves: their policies refuse a demo brand's insert, update and delete (00380).",
+ chat_auto_choices:
+ "A person's \"Don't ask again\" ticks in Chat (00401), by tool, in their workspace: no brand's.",
+ chat_user_prefs: "A person's own Chat preferences (00400): no brand's.",
+ content_authors: "The organization's authors, shared by its brands.",
+ content_rule_sets: "The organization's content rules per page type, shared by its brands.",
+ integration_connections: "The organization's Google connections.",
+ invitations: "The organization's invitations.",
+ organizations: 'The organization itself.',
+ profiles: "A person's own profile.",
+};
+
+/**
+ * Tables with a brand_id that people may write on a demo brand too, and why:
+ * nothing of the demo's sample data, and nothing that costs.
+ */
+const OPEN_ON_A_DEMO_BRAND = {
+ prompt_table_views:
+ "A person's column layout of the Tracked Prompts table (00363): it changes no sample data and costs nothing; the web keeps it open while read-only too.",
+};
+
+const name = (raw) =>
+ raw
+ .replace(/"/g, '')
+ .replace(/^public\./i, '')
+ .toLowerCase();
+
+const roles = (raw) =>
+ raw
+ .replace(/"/g, '')
+ .toLowerCase()
+ .split(',')
+ .map((role) => role.trim());
+
+/** Each migration's statements, comments and function bodies left out. */
+function statements(sql) {
+ return sql
+ .replace(/--[^\n]*/g, '')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/\$(\w*)\$[\s\S]*?\$\1\$/g, "''")
+ .split(';')
+ .map((statement) => statement.replace(/\s+/g, ' ').trim());
+}
+
+/**
+ * The tables people can write once the migrations have run: those with a
+ * policy for insert, update, delete or all (none named means all) for a role
+ * other than service_role, as pg_policies would list them.
+ */
+function writableTables() {
+ const policies = new Map();
+ const policy = (table) => {
+ if (!policies.has(table)) policies.set(table, new Map());
+ return policies.get(table);
+ };
+ for (const sql of migrations) {
+ for (const statement of statements(sql)) {
+ let m;
+ if ((m = statement.match(/^create policy ("[^"]+"|\S+) on ([\w."]+)(.*)$/i))) {
+ const rest = m[3];
+ policy(name(m[2])).set(name(m[1]), {
+ cmd: (
+ rest.match(/\bfor (all|select|insert|update|delete)\b/i)?.[1] ?? 'all'
+ ).toLowerCase(),
+ roles: roles(rest.match(/\bto ([\w", ]+?)(?: using| with check|$)/i)?.[1] ?? 'public'),
+ });
+ } else if ((m = statement.match(/^drop policy (?:if exists )?("[^"]+"|\S+) on ([\w."]+)/i))) {
+ policies.get(name(m[2]))?.delete(name(m[1]));
+ } else if ((m = statement.match(/^alter policy ("[^"]+"|\S+) on ([\w."]+) (.*)$/i))) {
+ const kept = policies.get(name(m[2]));
+ const found = kept?.get(name(m[1]));
+ const to = m[3].match(/^to ([\w", ]+?)(?: using| with check|$)/i);
+ const renamed = m[3].match(/^rename to ("[^"]+"|\S+)/i);
+ if (found && to) found.roles = roles(to[1]);
+ if (found && renamed) {
+ kept.delete(name(m[1]));
+ kept.set(name(renamed[1]), found);
+ }
+ } else if (
+ (m = statement.match(/^drop table (?:if exists )?([\w.", ]+?)(?: cascade| restrict)?$/i))
+ ) {
+ for (const table of m[1].split(',')) policies.delete(name(table.trim()));
+ } else if (
+ (m = statement.match(
+ /^alter table (?:if exists )?(?:only )?([\w."]+) rename to ([\w."]+)/i,
+ ))
+ ) {
+ const kept = policies.get(name(m[1]));
+ policies.delete(name(m[1]));
+ if (kept) policies.set(name(m[2]), kept);
+ }
+ }
+ }
+ return new Set(
+ [...policies]
+ .filter(([, kept]) =>
+ [...kept.values()].some(
+ (p) => p.cmd !== 'select' && p.roles.some((role) => role !== 'service_role'),
+ ),
+ )
+ .map(([table]) => table),
+ );
+}
+
+/** Table → the trigger's arguments (the way to its brand; [] for its own brand_id). */
+function guardedTables() {
+ const guarded = new Map();
+ for (const sql of migrations) {
+ for (const statement of statements(sql)) {
+ const m = statement.match(
+ /^create (?:or replace )?trigger \w+ before insert or update or delete on ([\w."]+) for each row execute function public\.refuse_demo_brand_writes\(([^)]*)\)$/i,
+ );
+ if (m) {
+ guarded.set(
+ name(m[1]),
+ m[2]
+ .split(',')
+ .map((arg) => arg.trim().replace(/^'|'$/g, ''))
+ .filter(Boolean),
+ );
+ }
+ }
+ }
+ return guarded;
+}
+
+const brandTables = brandScopedTables(migrations);
+const writable = writableTables();
+const guarded = guardedTables();
+
+describe('people cannot write a demo brand’s rows', () => {
+ it('finds the tables people can write', () => {
+ expect(writable.size).toBeGreaterThan(30);
+ for (const table of ['prompts', 'competitors', 'topics', 'content_drafts', 'brands']) {
+ expect(writable.has(table), table).toBe(true);
+ }
+ // Written by the server only.
+ for (const table of ['prompt_results', 'jobs', 'site_pages']) {
+ expect(writable.has(table), table).toBe(false);
+ }
+ });
+
+ it('guards every table with a brand_id that people can write, by its own brand_id', () => {
+ const missing = [...writable].filter(
+ (table) =>
+ brandTables.has(table) &&
+ guarded.get(table)?.length !== 0 &&
+ !(table in OPEN_ON_A_DEMO_BRAND),
+ );
+ // A table here is new: attach refuse_demo_brand_writes() in its migration,
+ // or name it in OPEN_ON_A_DEMO_BRAND with why.
+ expect(missing).toEqual([]);
+ for (const table of Object.keys(OPEN_ON_A_DEMO_BRAND)) {
+ expect(writable.has(table), table).toBe(true);
+ expect(brandTables.has(table), table).toBe(true);
+ expect(guarded.has(table), table).toBe(false);
+ }
+ });
+
+ it('guards every other table people can write, through its brand, unless it has none', () => {
+ const missing = [...writable].filter(
+ (table) => !brandTables.has(table) && !guarded.has(table) && !(table in NOT_A_BRAND_ROW),
+ );
+ // A table here belongs to a brand through another row: attach
+ // refuse_demo_brand_writes('<column>', '<table>', …) leading to it. Or it
+ // belongs to no brand: add it to NOT_A_BRAND_ROW with why.
+ expect(missing).toEqual([]);
+ for (const table of Object.keys(NOT_A_BRAND_ROW)) {
+ expect(writable.has(table), table).toBe(true);
+ expect(brandTables.has(table), table).toBe(false);
+ expect(guarded.has(table), table).toBe(false);
+ }
+ });
+
+ it('leads each table without a brand_id to a table with one', () => {
+ for (const [table, path] of guarded) {
+ if (path.length === 0) {
+ expect(brandTables.has(table), table).toBe(true);
+ continue;
+ }
+ expect(path.length % 2, table).toBe(0);
+ const tables = path.filter((_, i) => i % 2 === 1);
+ for (const step of tables.slice(0, -1)) expect(brandTables.has(step), step).toBe(false);
+ expect(brandTables.has(tables.at(-1)), table).toBe(true);
+ }
+ expect(guarded.get('prompts')).toEqual(['prompt_set_id', 'prompt_sets']);
+ expect(guarded.get('prompt_notes')).toEqual([
+ 'prompt_id',
+ 'prompts',
+ 'prompt_set_id',
+ 'prompt_sets',
+ ]);
+ });
+
+ it('lets a role that bypasses RLS through first: the server, which writes the demo', () => {
+ const migration = readFileSync(new URL('00381_demo_brand_writes.sql', dir), 'utf8');
+ const body = migration.slice(migration.indexOf('as $$'), migration.indexOf('end;\n$$;'));
+ const bypass = body.indexOf(
+ 'rolbypassrls from pg_catalog.pg_roles where rolname = current_user',
+ );
+ expect(bypass).toBeGreaterThan(0);
+ expect(bypass).toBeLessThan(body.indexOf("raise exception 'demo_brand'"));
+ // …but not the owner of a SECURITY DEFINER function a person called
+ // straight (current_user is then its owner): the session's role decides,
+ // unless the write comes from inside another trigger (a cascade).
+ const check = body.slice(bypass, body.indexOf('\n then\n', bypass));
+ expect(check).toMatch(/and \(\s*pg_catalog\.pg_trigger_depth\(\) > 1\s*or /);
+ expect(check).toMatch(
+ /coalesce\(pg_catalog\.current_setting\('role', true\), 'none'\)\s*not in \('authenticated', 'anon'\)/,
+ );
+ expect(body).toMatch(/using errcode = '42501'/);
+ // The demo generator (lib/demo) writes with the service role key.
+ const client = readFileSync(new URL('../../config/supabase.js', import.meta.url), 'utf8');
+ expect(client).toMatch(/createClient\(supabaseUrl, supabaseServiceRoleKey,/);
+ });
+});
diff --git a/server/src/lib/job-runner.js b/server/src/lib/job-runner.js
index 35e51573a..4e5c8407a 100644
--- a/server/src/lib/job-runner.js
+++ b/server/src/lib/job-runner.js
@@ -16,7 +16,7 @@ import {
registerActiveJob,
unregisterActiveJob,
} from './job-manager.js';
-import { activeBrandFilter, isBrandActive } from './active-subscriptions.js';
+import { brandStopReason, brandStopReasons } from './active-subscriptions.js';
import { processTrackingJob } from '../workers/tracking-worker.js';
import { processContentJob } from '../workers/content-worker.js';
import { generatePulseForBrand } from './pulse/engine.js';
@@ -73,22 +73,25 @@ function createJobProxy(jobId, signal) {
}
/**
- * Whether a claimed job's organization has no active plan, cancelling the
- * job if so (2026-10-27): every way a job starts (the nightly run, the
- * internal trigger, a retry, the recovery) ends in a claim, so this is where
- * an ended plan stops tracking and content generation, with no Cloro, AI or
- * scraping spent. A read that fails throws, and the job retries as after any
- * failure.
+ * Whether a claimed job may not run, cancelling it if so: its organization
+ * has no active plan (2026-10-27), or its brand is a demo brand (00380),
+ * whose data is sample data. Every way a job starts (the nightly run, "Run
+ * now", the internal trigger, a retry, the recovery) ends in a claim, so
+ * this is where tracking and content generation stop, with no Cloro, AI or
+ * scraping spent and nothing counted: the job's own row is all that is left
+ * (failed_reason says why). A read that fails throws, and the job retries as
+ * after any failure.
*/
-async function skipUnpaid(jobId, brandId) {
- if (await isBrandActive(brandId)) return false;
- if (await cancelClaimedJob(jobId, 'subscription_inactive')) {
- logger.info({ jobId, brandId }, 'cancelled a job of an organization without an active plan');
+async function skipStopped(jobId, brandId) {
+ const reason = await brandStopReason(brandId);
+ if (!reason) return false;
+ if (await cancelClaimedJob(jobId, reason)) {
+ logger.info({ jobId, brandId, reason }, 'cancelled a job that may not run');
} else {
// Not cancelled (the write failed, or the row moved on): never left
// 'active', where nothing would end it.
- logger.warn({ jobId, brandId }, 'could not cancel a job without an active plan; failing it');
- await failJob(jobId, 'subscription_inactive');
+ logger.warn({ jobId, brandId, reason }, 'could not cancel a job that may not run; failing it');
+ await failJob(jobId, reason);
}
return true;
}
@@ -133,7 +136,7 @@ async function attemptTrackingJob(jobId, io, priority = false) {
try {
const { brandId, promptId, promptIds, immediate } = jobRow.data;
- if (await skipUnpaid(jobId, brandId)) return;
+ if (await skipStopped(jobId, brandId)) return;
const proxy = createJobProxy(jobId, abortController.signal);
const result = await processTrackingJob({
@@ -281,7 +284,7 @@ async function attemptContentJob(jobId, io) {
try {
const { brandId, model, request } = jobRow.data;
- if (await skipUnpaid(jobId, brandId)) return;
+ if (await skipStopped(jobId, brandId)) return;
const proxy = createJobProxy(jobId, abortController.signal);
const result = await processContentJob({ brandId, model, job: proxy, request });
@@ -333,9 +336,10 @@ async function attemptContentJob(jobId, io) {
* Restart waiting jobs that have no run chain in this process. Runs at
* startup and every minute (server.js). Returns how many it restarted.
*
- * A job whose organization's plan has ended is cancelled instead: it would
- * track, scrape or write for an organization that no longer pays for it, and
- * left waiting it would only be found again the next minute.
+ * A job that may not run is cancelled instead, saying why: its
+ * organization's plan has ended (it would track, scrape or write for an
+ * organization that no longer pays for it), or its brand is a demo brand.
+ * Left waiting, it would only be found again the next minute.
*/
export async function recoverWaitingJobs(io) {
const jobs = (
@@ -345,13 +349,14 @@ export async function recoverWaitingJobs(io) {
})
).filter((job) => !queuedJobs.has(job.id) && RECOVERABLE_TYPES.has(job.type));
if (jobs.length === 0) return 0;
- const isActive = await activeBrandFilter(jobs.map((job) => job.brand_id));
+ const reasonFor = await brandStopReasons(jobs.map((job) => job.brand_id));
let recovered = 0;
let cancelled = 0;
for (const job of jobs) {
- if (!isActive(job.brand_id)) {
- if (await cancelWaitingJob(job.id, 'subscription_inactive')) cancelled++;
+ const reason = reasonFor(job.brand_id);
+ if (reason) {
+ if (await cancelWaitingJob(job.id, reason)) cancelled++;
continue;
}
if (job.type === 'tracking') {
@@ -362,9 +367,7 @@ export async function recoverWaitingJobs(io) {
recovered++;
}
- if (cancelled > 0) {
- logger.info({ cancelled }, 'cancelled waiting jobs of organizations without an active plan');
- }
+ if (cancelled > 0) logger.info({ cancelled }, 'cancelled waiting jobs that may not run');
if (recovered > 0) logger.warn({ recovered }, 'restarted waiting jobs that had no run chain');
return recovered;
}
diff --git a/server/src/lib/job-runner.test.js b/server/src/lib/job-runner.test.js
index 791c5a58b..3a7f7bcbc 100644
--- a/server/src/lib/job-runner.test.js
+++ b/server/src/lib/job-runner.test.js
@@ -14,15 +14,15 @@ const manager = vi.hoisted(() => ({
}));
const processTrackingJob = vi.hoisted(() => vi.fn());
const processContentJob = vi.hoisted(() => vi.fn());
-const activeBrandFilter = vi.hoisted(() => vi.fn());
-const isBrandActive = vi.hoisted(() => vi.fn());
+const brandStopReasons = vi.hoisted(() => vi.fn());
+const brandStopReason = vi.hoisted(() => vi.fn());
vi.mock('./job-manager.js', () => manager);
// A retry sets its job back to waiting itself.
vi.mock('../config/supabase.js', () => ({
default: { from: () => ({ update: () => ({ eq: async () => ({ error: null }) }) }) },
}));
-vi.mock('./active-subscriptions.js', () => ({ activeBrandFilter, isBrandActive }));
+vi.mock('./active-subscriptions.js', () => ({ brandStopReasons, brandStopReason }));
vi.mock('../workers/tracking-worker.js', () => ({ processTrackingJob }));
vi.mock('../workers/content-worker.js', () => ({ processContentJob }));
vi.mock('./pulse/engine.js', () => ({ generatePulseForBrand: vi.fn() }));
@@ -64,8 +64,8 @@ beforeEach(() => {
processTrackingJob.mockReset();
processContentJob.mockReset();
// Every organization on a plan unless a test says otherwise.
- activeBrandFilter.mockReset().mockResolvedValue(() => true);
- isBrandActive.mockReset().mockResolvedValue(true);
+ brandStopReasons.mockReset().mockResolvedValue(() => null);
+ brandStopReason.mockReset().mockResolvedValue(null);
manager.cancelClaimedJob.mockResolvedValue(true);
// The claim resolves a tick later, as a network call would.
manager.claimWaitingJob.mockImplementation(async (id) => {
@@ -227,12 +227,14 @@ describe('runTrackingJob, the first run after a payment', () => {
describe('a job of an organization whose plan has ended', () => {
it('is cancelled once claimed, not tracked, and gives its slot back', async () => {
const releases = heldRuns();
- isBrandActive.mockImplementation(async (brandId) => brandId !== 'brand-lapsed');
+ brandStopReason.mockImplementation(async (brandId) =>
+ brandId === 'brand-lapsed' ? 'subscription_inactive' : null,
+ );
for (const id of ['lapsed', 'a', 'b']) runTrackingJob(id);
await vi.advanceTimersByTimeAsync(5000);
- expect(isBrandActive).toHaveBeenCalledWith('brand-lapsed');
+ expect(brandStopReason).toHaveBeenCalledWith('brand-lapsed');
expect(manager.cancelClaimedJob).toHaveBeenCalledWith('lapsed', 'subscription_inactive');
expect(processTrackingJob.mock.calls.map(([job]) => job.brandId)).toEqual([
'brand-a',
@@ -244,7 +246,7 @@ describe('a job of an organization whose plan has ended', () => {
});
it('is failed, never left active, when it cannot be cancelled', async () => {
- isBrandActive.mockResolvedValue(false);
+ brandStopReason.mockResolvedValue('subscription_inactive');
manager.cancelClaimedJob.mockResolvedValue(false);
const { default: logger } = await import('./logger.js');
vi.mocked(logger.warn).mockClear();
@@ -259,7 +261,7 @@ describe('a job of an organization whose plan has ended', () => {
});
it('is only cancelled, not failed, when the cancel is written', async () => {
- isBrandActive.mockResolvedValue(false);
+ brandStopReason.mockResolvedValue('subscription_inactive');
manager.cancelClaimedJob.mockResolvedValue(true);
runTrackingJob('cancelled');
@@ -269,7 +271,7 @@ describe('a job of an organization whose plan has ended', () => {
});
it('writes no content either', async () => {
- isBrandActive.mockResolvedValue(false);
+ brandStopReason.mockResolvedValue('subscription_inactive');
runContentJob('lapsed-content');
await flush();
@@ -284,7 +286,7 @@ describe('a job of an organization whose plan has ended', () => {
it('is not retried once the plan ends between two attempts', async () => {
processTrackingJob.mockRejectedValueOnce(new Error('cloro down'));
manager.getJob.mockResolvedValue({ attempts: 1, max_attempts: 3 });
- isBrandActive.mockResolvedValueOnce(true).mockResolvedValue(false);
+ brandStopReason.mockResolvedValueOnce(null).mockResolvedValue('subscription_inactive');
runTrackingJob('retry');
await flush();
@@ -298,7 +300,7 @@ describe('a job of an organization whose plan has ended', () => {
});
it('tracks nothing when it cannot tell, and retries as after any failure', async () => {
- isBrandActive.mockRejectedValueOnce(new Error('brands read: timeout'));
+ brandStopReason.mockRejectedValueOnce(new Error('brands read: timeout'));
manager.getJob.mockResolvedValue({ attempts: 1, max_attempts: 3 });
processTrackingJob.mockResolvedValue({ resultCount: 0, stamped: false });
@@ -314,6 +316,55 @@ describe('a job of an organization whose plan has ended', () => {
});
});
+/**
+ * A demo brand (00380): its data is sample data, so a job for it ("Run now",
+ * the internal trigger) is cancelled once claimed, saying so, before
+ * anything is tracked, generated or counted.
+ */
+describe('a job of a demo brand', () => {
+ it('is cancelled as demo_brand, not as an ended plan, and nothing runs', async () => {
+ brandStopReason.mockImplementation(async (brandId) =>
+ brandId === 'brand-demo' || brandId === 'brand-demo-content' ? 'demo_brand' : null,
+ );
+
+ runTrackingJob('demo');
+ runContentJob('demo-content');
+ await flush();
+
+ expect(manager.cancelClaimedJob.mock.calls).toEqual([
+ ['demo', 'demo_brand'],
+ ['demo-content', 'demo_brand'],
+ ]);
+ expect(processTrackingJob).not.toHaveBeenCalled();
+ expect(processContentJob).not.toHaveBeenCalled();
+ expect(manager.completeJob).not.toHaveBeenCalled();
+ expect(manager.failJob).not.toHaveBeenCalled();
+ });
+
+ it('is failed as demo_brand when it cannot be cancelled', async () => {
+ brandStopReason.mockResolvedValue('demo_brand');
+ manager.cancelClaimedJob.mockResolvedValue(false);
+
+ runTrackingJob('demo-stuck');
+ await flush();
+
+ expect(manager.failJob).toHaveBeenCalledWith('demo-stuck', 'demo_brand');
+ expect(processTrackingJob).not.toHaveBeenCalled();
+ });
+
+ it('is cancelled as demo_brand when the recovery finds it waiting', async () => {
+ brandStopReasons.mockResolvedValue((brandId) => (brandId === 'demo' ? 'demo_brand' : null));
+ manager.cancelWaitingJob.mockResolvedValue(true);
+ manager.listWaitingJobs.mockResolvedValue([
+ { id: 'demo-tracking', type: 'tracking', brand_id: 'demo' },
+ ]);
+
+ expect(await recoverWaitingJobs()).toBe(0);
+ expect(manager.cancelWaitingJob.mock.calls).toEqual([['demo-tracking', 'demo_brand']]);
+ expect(manager.claimWaitingJob).not.toHaveBeenCalled();
+ });
+});
+
describe('recoverWaitingJobs', () => {
it('restarts waiting jobs with no run chain here, routed by type', async () => {
const releases = heldRuns();
@@ -348,13 +399,15 @@ describe('recoverWaitingJobs', () => {
manager.listWaitingJobs.mockResolvedValue([]);
expect(await recoverWaitingJobs()).toBe(0);
expect(manager.claimWaitingJob).not.toHaveBeenCalled();
- expect(activeBrandFilter).not.toHaveBeenCalled();
+ expect(brandStopReasons).not.toHaveBeenCalled();
});
it('cancels, rather than runs, the waiting jobs of an organization whose plan has ended', async () => {
const releases = heldRuns();
processContentJob.mockResolvedValue({ generated: 0 });
- activeBrandFilter.mockResolvedValue((brandId) => brandId === 'paying');
+ brandStopReasons.mockResolvedValue((brandId) =>
+ brandId === 'paying' ? null : 'subscription_inactive',
+ );
manager.cancelWaitingJob.mockResolvedValue(true);
manager.listWaitingJobs.mockResolvedValue([
{ id: 'kept', type: 'tracking', brand_id: 'paying' },
@@ -366,7 +419,7 @@ describe('recoverWaitingJobs', () => {
await flush();
expect(recovered).toBe(1);
- expect(activeBrandFilter).toHaveBeenCalledWith(['paying', 'lapsed', 'lapsed']);
+ expect(brandStopReasons).toHaveBeenCalledWith(['paying', 'lapsed', 'lapsed']);
// Only while still waiting, saying why.
expect(manager.cancelWaitingJob.mock.calls).toEqual([
['lapsed-tracking', 'subscription_inactive'],
@@ -378,7 +431,7 @@ describe('recoverWaitingJobs', () => {
});
it('runs nothing when it cannot tell which organizations are on a plan', async () => {
- activeBrandFilter.mockRejectedValue(new Error('organizations read: timeout'));
+ brandStopReasons.mockRejectedValue(new Error('organizations read: timeout'));
manager.listWaitingJobs.mockResolvedValue([{ id: 'lost', type: 'tracking', brand_id: 'b' }]);
await expect(recoverWaitingJobs()).rejects.toThrow('organizations read');
diff --git a/server/src/middleware/demo-brand.js b/server/src/middleware/demo-brand.js
new file mode 100644
index 000000000..144e4723b
--- /dev/null
+++ b/server/src/middleware/demo-brand.js
@@ -0,0 +1,475 @@
+import supabaseAdmin from '../config/supabase.js';
+import { selectInChunks } from '../lib/chunked-in.js';
+import logger from '../lib/logger.js';
+
+/**
+ * The demo brand is read-only (00380).
+ *
+ * A demo brand is an ordinary brand row in the organization, filled with
+ * sample data by the server (lib/demo). People explore every page of it,
+ * but nothing they ask of it may change that data or start a cost:
+ * tracking, scraping, AI, audits, outside services, sends. So every
+ * signed-in request that writes (any method but GET, HEAD and OPTIONS) and
+ * names a demo brand is refused with 402 demo_brand, on the cloud and
+ * self-hosted alike, whatever the plan: the web app opens the plan dialog
+ * with the demo's offer.
+ *
+ * Every write route under /api is named here, route by route:
+ * - DEMO_GUARDED: where the request names its brand (the path, the body,
+ * the query, or a row of the brand's it acts on). The request is
+ * refused when that brand is a demo brand.
+ * - DEMO_OPEN: routes that name no brand (the organization's own, or
+ * onboarding's), or that stop work and never start any, or that answer
+ * a demo brand themselves; each with the reason.
+ * demo-brand.test.js reads the route files and fails on a write route that
+ * is in neither list, so a new one can't ship without saying which it is.
+ * Reads and exports stay open.
+ *
+ * A row the request names that isn't found (or an id of the wrong shape) is
+ * left to the route, which answers 400 or 404 itself.
+ */
+
+const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
+
+/** The answer to a write or a cost on a demo brand. */
+export const DEMO_BRAND = {
+ success: false,
+ error: 'plan_limit',
+ code: 'demo_brand',
+ message:
+ 'This is the demo brand, with sample data to explore. Choose a plan to do this for your own brand.',
+};
+
+// ─── Where a request names its brand ────────────────────────────────────────
+
+/** The brand's id itself: in the path (a `:name` of the route), the body or the query. */
+const brandIn = (where, key = 'brandId') => ({ where, key });
+
+/**
+ * A row (or rows: an array of ids) of `table` whose brand the request acts
+ * on, by its id in the path, the body or the query.
+ */
+const rowIn = (table, where, key = 'id') => ({ table, where, key });
+
+/** How a row of a table without its own brand_id reaches its brand. */
+const OWNERS = {
+ // Prompts belong to a brand through their prompt set.
+ prompts: { select: 'id, prompt_sets!inner(brand_id)', brand: (row) => row.prompt_sets?.brand_id },
+ // Tasks belong to a brand through their action.
+ action_tasks: { select: 'id, actions!inner(brand_id)', brand: (row) => row.actions?.brand_id },
+};
+const BRAND_COLUMN = { select: 'id, brand_id', brand: (row) => row.brand_id };
+
+/** `METHOD /path` (Express's own path syntax, under /api) and where it names its brand. */
+const guard = (route, ...sources) => ({ route, sources });
+
+/** `METHOD /path` that names no demo brand to refuse, and why. */
+const open = (route, why) => ({ route, why });
+
+/**
+ * The write routes refused on a demo brand: every one that changes a
+ * brand's data or starts work for it.
+ */
+export const DEMO_GUARDED = [
+ // Action Center (action-center.js).
+ guard('POST /action-center/signals/:id/rescore', rowIn('signals', 'path')),
+ guard('POST /action-center/actions/:id/tasks/regenerate', rowIn('actions', 'path')),
+ guard('DELETE /action-center/actions/:id', rowIn('actions', 'path')),
+ guard('POST /action-center/tasks/:id/send', rowIn('action_tasks', 'path')),
+ guard('POST /action-center/tasks/:id/check', rowIn('action_tasks', 'path')),
+ guard('POST /action-center/pages', brandIn('body')),
+ guard('POST /action-center/audits', brandIn('body')),
+ guard('POST /action-center/products', brandIn('body')),
+ guard('POST /action-center/content-drafts', brandIn('body')),
+
+ // Site Audit (audits.js).
+ guard('POST /audits', brandIn('body')),
+ guard('POST /audits/bulk', brandIn('body')),
+ guard('PUT /audits/opportunities/prefs', brandIn('body')),
+ guard('PUT /audits/settings', brandIn('body')),
+ guard('DELETE /audits/:id', rowIn('site_audits', 'path')),
+
+ // AI-bot log connections (bots.js): the demo's are samples; removing one
+ // would revoke a secret that was never given out.
+ guard('POST /bots/connections/:brandId', brandIn('path')),
+ guard('DELETE /bots/connections/:brandId/:id', brandIn('path')),
+
+ // Brand facts (brand-facts.js): reading the site again, approving a fact.
+ guard('POST /brand-facts/fetch', brandIn('body')),
+ guard('PATCH /brand-facts/:id', rowIn('brand_facts', 'path')),
+
+ // Brands (brands.js): reading the site's home page, and AI, for its kind.
+ guard('POST /brands/:id/detect-site-type', brandIn('path', 'id')),
+
+ // Product catalog (catalog.js): the demo's stores are samples, so neither
+ // connecting, syncing nor removing one may reach a store.
+ guard('POST /catalog/sources', brandIn('body')),
+ guard('PUT /catalog/sources/:id/credentials', rowIn('catalog_sources', 'path')),
+ guard('DELETE /catalog/sources/:id', rowIn('catalog_sources', 'path')),
+ guard('POST /catalog/sources/:id/sync', rowIn('catalog_sources', 'path')),
+ guard('PUT /catalog/categories', brandIn('body')),
+ guard('DELETE /catalog/categories', brandIn('query')),
+ guard('POST /catalog/upload', brandIn('query')),
+
+ // Webflow (cms.js): the demo's connection is a sample.
+ guard('POST /cms/brands/:brandId/webflow', brandIn('path')),
+ guard('PUT /cms/brands/:brandId/webflow', brandIn('path')),
+ guard('DELETE /cms/brands/:brandId/webflow', brandIn('path')),
+
+ // WordPress and Framer (cms-wordpress.js, cms-framer.js): a connection
+ // would reach a real site.
+ guard('POST /cms/brands/:brandId/wordpress', brandIn('path')),
+ guard('DELETE /cms/brands/:brandId/wordpress', brandIn('path')),
+ guard('POST /cms/brands/:brandId/framer', brandIn('path')),
+ guard('PUT /cms/brands/:brandId/framer', brandIn('path')),
+ guard('DELETE /cms/brands/:brandId/framer', brandIn('path')),
+
+ // Content Editor (content-drafts.js): the draft's brand is in the body;
+ // the draft itself is checked too.
+ guard('POST /content-drafts/send', brandIn('body')),
+ guard('POST /content-drafts/:draftId/publish', rowIn('content_drafts', 'path', 'draftId')),
+ guard('POST /content-drafts/webflow-status', brandIn('body')),
+ guard('POST /content-drafts/wordpress-status', brandIn('body')),
+ guard('POST /content-drafts/framer-status', brandIn('body')),
+ guard(
+ 'POST /content-drafts/:draftId/brief',
+ brandIn('body'),
+ rowIn('content_drafts', 'path', 'draftId'),
+ ),
+ guard(
+ 'POST /content-drafts/:draftId/shopping-path',
+ brandIn('body'),
+ rowIn('content_drafts', 'path', 'draftId'),
+ ),
+ guard(
+ 'POST /content-drafts/:draftId/suggestions',
+ brandIn('body'),
+ rowIn('content_drafts', 'path', 'draftId'),
+ ),
+ guard(
+ 'POST /content-drafts/:draftId/handoff',
+ brandIn('body'),
+ rowIn('content_drafts', 'path', 'draftId'),
+ ),
+ guard(
+ 'POST /content-drafts/:draftId/write',
+ brandIn('body'),
+ rowIn('content_drafts', 'path', 'draftId'),
+ ),
+ guard(
+ 'POST /content-drafts/:draftId/rewrite',
+ brandIn('body'),
+ rowIn('content_drafts', 'path', 'draftId'),
+ ),
+
+ // The editor's page checks (content-pages.js): pages read, AI asked.
+ guard('POST /content-pages/import', brandIn('body')),
+ guard('POST /content-pages/links', rowIn('content_drafts', 'body', 'draftId')),
+ guard('POST /content-pages/source-classes', rowIn('content_drafts', 'body', 'draftId')),
+ guard('POST /content-pages/claims', rowIn('content_drafts', 'body', 'draftId')),
+ guard('POST /content-pages/page-read', rowIn('content_drafts', 'body', 'draftId')),
+
+ // Content opportunities (content.js).
+ guard('POST /content/generate', brandIn('body')),
+ guard('POST /content/opportunities/generate', brandIn('body')),
+ guard('POST /content/:id/alternative', rowIn('content_opportunities', 'path')),
+ guard('POST /content/prompts/:promptId/suggest', rowIn('prompts', 'path', 'promptId')),
+ guard('POST /content/bulk/status', rowIn('content_opportunities', 'body', 'ids')),
+ guard('POST /content/bulk/delete', rowIn('content_opportunities', 'body', 'ids')),
+ guard('POST /content/bulk/send-webhook', rowIn('content_opportunities', 'body', 'ids')),
+ guard('PATCH /content/:id/status', rowIn('content_opportunities', 'path')),
+ guard('POST /content/:id/send-webhook', rowIn('content_opportunities', 'path')),
+ guard('POST /content/webhook-test', brandIn('body')),
+ guard('POST /content/:id/brief', rowIn('content_opportunities', 'path')),
+ guard('POST /content/:id/action', rowIn('content_opportunities', 'path')),
+
+ // Search Console and Analytics (integrations.js): one brand's sync. Without
+ // a brand, the organization's sync, which skips demo brands itself.
+ guard('POST /integrations/google-search-console/sync', brandIn('body')),
+ guard('POST /integrations/google-analytics/sync', brandIn('body')),
+
+ // Mentions (mentions.js).
+ guard('POST /mentions/action', brandIn('body')),
+
+ // Prompts (prompts.js).
+ guard('POST /prompts/suggestions/:brandId/refresh', brandIn('path')),
+ guard('POST /prompts/suggestions/:brandId/page', brandIn('path')),
+ guard('POST /prompts/suggestions/:id/dismiss', rowIn('prompt_suggestions', 'path')),
+ guard('POST /prompts/suggestions/:id/accept', rowIn('prompt_suggestions', 'path')),
+ guard('POST /prompts/:promptId/improve', rowIn('prompts', 'path', 'promptId')),
+ guard('POST /prompts/:promptId/improve/action', rowIn('prompts', 'path', 'promptId')),
+
+ // Reports (reports.js): an AI summary.
+ guard('POST /reports/summary', brandIn('body')),
+
+ // Topics (topics.js).
+ guard('POST /topics/suggestions/:brandId/refresh', brandIn('path')),
+ guard('POST /topics/suggestions/:id/dismiss', rowIn('topic_suggestions', 'path')),
+ guard('POST /topics/suggestions/:id/accept', rowIn('topic_suggestions', 'path')),
+ guard('POST /topics/:id/gap-action', rowIn('topics', 'path')),
+ guard('POST /topics/:id/opportunity-action', rowIn('topics', 'path')),
+
+ // Tracking (tracking.js): "Run now" and the new prompts' first run.
+ guard('POST /tracking/check', brandIn('body')),
+ guard('POST /tracking/analyze-new', brandIn('body')),
+
+ // Volumes (volumes.js): DataForSEO and the model.
+ guard('POST /volumes/analyze', rowIn('prompts', 'body', 'promptId')),
+ guard('POST /volumes/analyze-batch', brandIn('body')),
+ guard('POST /volumes/bootstrap', brandIn('body')),
+ guard('POST /volumes/refresh', brandIn('body')),
+];
+
+/** The write routes left open on a demo brand, and why. */
+export const DEMO_OPEN = [
+ open(
+ 'POST /billing/cancel-feedback',
+ "The organization's own: why its plan is cancelled. Names no brand.",
+ ),
+ open(
+ 'DELETE /brands/:id',
+ 'brands.js answers a demo brand itself (409 demo_brand): it is hidden, not deleted, and the web app shows that as information, not as the plan dialog.',
+ ),
+ open(
+ 'POST /competitors/suggest',
+ "Onboarding's suggestions from a brand's name and site, before the brand exists. Names no brand; the plan check bounds them.",
+ ),
+ open(
+ 'POST /content-drafts/:draftId/stop',
+ "Stops the Content Agent's run on a draft: it never starts one, and no run is ever under way on a demo brand.",
+ ),
+ open('POST /demo', 'Opens (creates or rebuilds) the demo brand itself.'),
+ open('PATCH /demo', 'Hides or shows the demo brand itself.'),
+ open(
+ 'POST /integrations/:provider/connect',
+ "Connects the organization's own Google account. Names no brand.",
+ ),
+ open('DELETE /integrations/:provider', "Disconnects the organization's own Google account."),
+ open(
+ 'POST /prompts/suggest',
+ "Onboarding's prompt ideas from a brand's name, before the brand exists. Names no brand.",
+ ),
+ open(
+ 'POST /prompts/from-topics',
+ "Onboarding's prompts for the chosen topics, before the brand exists. Names no brand.",
+ ),
+ open(
+ 'POST /prompts/fanout-intents',
+ "Classifies fan-out queries into a cache shared by every brand. Names no brand; the demo's queries are the same for every organization, so they are classified once.",
+ ),
+ open(
+ 'POST /topics/suggest',
+ "Onboarding's topics from a brand's name and site, before the brand exists. Names no brand.",
+ ),
+ open(
+ 'DELETE /tracking/job/:jobId',
+ 'Cancels a tracking job: it never starts one, and a demo brand has none (its jobs are cancelled when claimed).',
+ ),
+];
+
+// ─── Matching a request ─────────────────────────────────────────────────────
+
+/** Express's path syntax as a regex: `:name` matches one segment, a trailing slash is optional. */
+function compile(route) {
+ const [method, path] = route.split(' ');
+ const params = [];
+ const pattern = path
+ .split('/')
+ .map((segment) => {
+ if (!segment.startsWith(':')) return segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ params.push(segment.slice(1));
+ return `(?<${segment.slice(1)}>[^/]+)`;
+ })
+ .join('/');
+ // Express matches paths case-insensitively by default.
+ return { method, regex: new RegExp(`^${pattern}/?$`, 'i'), params: params.length };
+}
+
+const COMPILED_GUARDED = DEMO_GUARDED.map((entry) => ({ ...entry, ...compile(entry.route) }));
+const COMPILED_OPEN = DEMO_OPEN.map((entry) => ({ ...entry, ...compile(entry.route) }));
+
+/**
+ * The entry a request reaches, as Express would route it: of the routes its
+ * method and path match, the one with the fewest `:params` (a fixed segment,
+ * like /content/bulk/status, is defined before the `:id` it would also match).
+ */
+function routeOf(entries, { method, path }) {
+ let best = null;
+ for (const entry of entries) {
+ if (entry.method !== method) continue;
+ const match = entry.regex.exec(path);
+ if (!match) continue;
+ if (!best || entry.params < best.entry.params) best = { entry, match };
+ }
+ return best;
+}
+
+/** Which guarded or open route a write request reaches, or null for none. */
+export function demoRouteFor(req) {
+ const guarded = routeOf(COMPILED_GUARDED, req);
+ const opened = routeOf(COMPILED_OPEN, req);
+ if (guarded && (!opened || guarded.entry.params <= opened.entry.params)) {
+ return { guarded: true, entry: guarded.entry, match: guarded.match };
+ }
+ if (opened) return { guarded: false, entry: opened.entry, match: opened.match };
+ return null;
+}
+
+// ─── Which brands are demo brands ───────────────────────────────────────────
+
+/**
+ * A uuid as Postgres reads one: 32 hex digits, upper or lower case, in
+ * braces or not, with or without its hyphens. The demo's seeded ids aren't
+ * RFC 4122 versions, so any digits go.
+ */
+const UUID_INPUT = /^(\{)?([0-9a-f-]+)(\})?$/i;
+
+/**
+ * The id in its usual form (lowercase, 8-4-4-4-12), or null when it isn't
+ * one: a route passes the others to Postgres, which reads them as the same
+ * row, so they are checked the same.
+ */
+function guidOf(value) {
+ if (typeof value !== 'string') return null;
+ const m = UUID_INPUT.exec(value);
+ if (!m || Boolean(m[1]) !== Boolean(m[3])) return null;
+ const hex = m[2].replace(/-/g, '').toLowerCase();
+ if (!/^[0-9a-f]{32}$/.test(hex)) return null;
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
+
+/**
+ * Ids a request may name at once (the bulk routes). A request naming more
+ * is refused with 400: each one would be read here, and the route's own
+ * read of them all at once wouldn't fit a request anyway.
+ */
+export const MAX_IDS = 500;
+
+/** A request that names more than MAX_IDS ids. */
+class TooManyIds extends Error {}
+
+/** Brands remembered at most; the oldest goes first. */
+export const MAX_CACHED_BRANDS = 10_000;
+
+/**
+ * Brand id → whether it is a demo brand. Kept for good: a brand never turns
+ * into a demo brand or back (00380: only the server creates one, and people
+ * can't change is_demo).
+ */
+const demoByBrand = new Map();
+
+function remember(brandId, isDemo) {
+ if (!demoByBrand.has(brandId) && demoByBrand.size >= MAX_CACHED_BRANDS) {
+ demoByBrand.delete(demoByBrand.keys().next().value);
+ }
+ demoByBrand.set(brandId, isDemo);
+}
+
+/** The ids in `value` (one, or an array), in their usual form; others are left out. */
+function guids(value) {
+ return (Array.isArray(value) ? value : [value]).map(guidOf).filter(Boolean);
+}
+
+/** The ids a request names in one place: guids(), at most MAX_IDS of them. */
+function requestGuids(value) {
+ if (Array.isArray(value) && value.length > MAX_IDS) throw new TooManyIds();
+ return guids(value);
+}
+
+/**
+ * Whether any of `brandIds` is a demo brand. Throws when the brands can't be
+ * read. The one check every demo guard goes through (this middleware, the
+ * internal endpoints the MCP calls, a read that would otherwise fetch).
+ *
+ * @param {string|string[]} brandIds
+ * @returns {Promise<boolean>}
+ */
+export async function isDemoBrand(brandIds) {
+ const ids = [...new Set(guids(brandIds))];
+ if (ids.some((id) => demoByBrand.get(id) === true)) return true;
+ const unknown = ids.filter((id) => !demoByBrand.has(id));
+ if (unknown.length === 0) return false;
+ const { data, error } = await selectInChunks(unknown, (chunk) =>
+ supabaseAdmin.from('brands').select('id, is_demo').in('id', chunk),
+ );
+ if (error) throw new Error(`brands read: ${error.message}`);
+ for (const brand of data ?? []) remember(brand.id, Boolean(brand.is_demo));
+ return (data ?? []).some((brand) => brand.is_demo);
+}
+
+/** The brands of the rows of `table` whose ids are `ids`. */
+async function brandsOfRows(table, ids) {
+ const owner = OWNERS[table] ?? BRAND_COLUMN;
+ const { data, error } = await selectInChunks(ids, (chunk) =>
+ supabaseAdmin.from(table).select(owner.select).in('id', chunk),
+ );
+ if (error) throw new Error(`${table} read: ${error.message}`);
+ return (data ?? []).map(owner.brand).filter(Boolean);
+}
+
+/**
+ * Whether any of the rows of `table` whose ids are `ids` belongs to a demo
+ * brand: for a caller that names a row rather than a brand (the internal
+ * endpoints the MCP calls). Rows that aren't found answer false.
+ *
+ * @param {string} table
+ * @param {string|string[]} ids
+ * @returns {Promise<boolean>}
+ */
+export async function isDemoBrandRow(table, ids) {
+ const brands = await brandsOfRows(table, guids(ids));
+ return brands.length > 0 && isDemoBrand(brands);
+}
+
+function valueAt(req, match, { where, key }) {
+ if (where === 'path') return match.groups?.[key];
+ if (where === 'body') return req.body?.[key];
+ return req.query?.[key];
+}
+
+/**
+ * The brands a guarded request names, by its route's sources.
+ *
+ * @returns {Promise<string[]>}
+ */
+export async function brandsNamedBy(req, { entry, match }) {
+ const brands = [];
+ for (const source of entry.sources) {
+ const ids = requestGuids(valueAt(req, match, source));
+ if (ids.length === 0) continue;
+ if (source.table) brands.push(...(await brandsOfRows(source.table, ids)));
+ else brands.push(...ids);
+ }
+ return brands;
+}
+
+/**
+ * Express middleware: refuses a signed-in person's writes on a demo brand
+ * with 402 demo_brand. Runs after decodeToken, before the plan's check, so
+ * the demo brand's answer is the same with a plan or without one.
+ */
+export async function refuseDemoBrandWrites(req, res, next) {
+ if (READ_METHODS.has(req.method)) return next();
+ const route = demoRouteFor(req);
+ if (!route?.guarded) return next();
+ try {
+ const brands = await brandsNamedBy(req, route);
+ if (brands.length > 0 && (await isDemoBrand(brands))) {
+ return res.status(402).json(DEMO_BRAND);
+ }
+ return next();
+ } catch (err) {
+ if (err instanceof TooManyIds) {
+ return res
+ .status(400)
+ .json({ success: false, error: 'invalid', message: `At most ${MAX_IDS} ids at once` });
+ }
+ (req.log ?? logger).error({ err }, 'demo brand check failed');
+ return res.status(500).json({ message: 'Internal Error' });
+ }
+}
+
+// Test hook — what is refused depends on what is remembered.
+export function clearDemoBrandCache() {
+ demoByBrand.clear();
+}
diff --git a/server/src/middleware/demo-brand.test.js b/server/src/middleware/demo-brand.test.js
new file mode 100644
index 000000000..9bb7611cb
--- /dev/null
+++ b/server/src/middleware/demo-brand.test.js
@@ -0,0 +1,435 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { readFile, readdir } from 'node:fs/promises';
+
+/**
+ * The demo brand is read-only (00380): a signed-in person's writes that name
+ * a demo brand are refused with 402 demo_brand, whatever the plan; every
+ * write route under /api is either guarded or open with a reason.
+ */
+
+const reads = [];
+let rows;
+let failWith = null;
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const read = { table };
+ reads.push(read);
+ const chain = {
+ select: (columns) => {
+ read.columns = columns;
+ return chain;
+ },
+ in: (column, ids) => {
+ read.ids = ids;
+ read.wanted = new Set(ids);
+ return chain;
+ },
+ then: (resolve, reject) =>
+ Promise.resolve(
+ failWith
+ ? { data: null, error: { message: failWith } }
+ : {
+ data: (rows[table] ?? []).filter((row) => read.wanted.has(row.id)),
+ error: null,
+ },
+ ).then(resolve, reject),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('../lib/logger.js', () => ({
+ default: { error: vi.fn(), warn: vi.fn(), info: vi.fn() },
+}));
+
+const {
+ DEMO_BRAND,
+ DEMO_GUARDED,
+ DEMO_OPEN,
+ MAX_CACHED_BRANDS,
+ MAX_IDS,
+ clearDemoBrandCache,
+ demoRouteFor,
+ isDemoBrand,
+ isDemoBrandRow,
+ refuseDemoBrandWrites,
+} = await import('./demo-brand.js');
+
+// Seeded ids, as the demo's are: GUID-shaped, not RFC 4122 versions.
+const DEMO = '00000000-0000-0000-0000-00000000de30';
+const REAL = '11111111-1111-1111-1111-111111111111';
+const DEMO_DRAFT = '00000000-0000-0000-0000-0000000d4af7';
+const REAL_DRAFT = '11111111-1111-1111-1111-1111111d4af7';
+const DEMO_PROMPT = '00000000-0000-0000-0000-0000000000a1';
+const DEMO_TASK = '00000000-0000-0000-0000-00000000005a';
+const DEMO_OPP = '00000000-0000-0000-0000-0000000000b1';
+const REAL_OPP = '11111111-1111-1111-1111-1111111111b1';
+const MISSING = '22222222-2222-2222-2222-222222222222';
+
+function makeRes() {
+ const res = { status: vi.fn(), json: vi.fn() };
+ res.status.mockReturnValue(res);
+ return res;
+}
+
+async function run({ method = 'POST', path, body = {}, query = {}, log } = {}) {
+ const res = makeRes();
+ const next = vi.fn();
+ await refuseDemoBrandWrites({ method, path, body, query, log }, res, next);
+ return { res, next };
+}
+
+function expectRefused({ res, next }, label) {
+ expect(next, label).not.toHaveBeenCalled();
+ expect(res.status, label).toHaveBeenCalledWith(402);
+ expect(res.json, label).toHaveBeenCalledWith(DEMO_BRAND);
+}
+
+function expectPassed({ res, next }, label) {
+ expect(next, label).toHaveBeenCalledOnce();
+ expect(res.status, label).not.toHaveBeenCalled();
+}
+
+beforeEach(() => {
+ reads.length = 0;
+ failWith = null;
+ clearDemoBrandCache();
+ rows = {
+ brands: [
+ { id: DEMO, is_demo: true },
+ { id: REAL, is_demo: false },
+ ],
+ content_drafts: [
+ { id: DEMO_DRAFT, brand_id: DEMO },
+ { id: REAL_DRAFT, brand_id: REAL },
+ ],
+ content_opportunities: [
+ { id: DEMO_OPP, brand_id: DEMO },
+ { id: REAL_OPP, brand_id: REAL },
+ ],
+ prompts: [{ id: DEMO_PROMPT, prompt_sets: { brand_id: DEMO } }],
+ action_tasks: [{ id: DEMO_TASK, actions: { brand_id: DEMO } }],
+ };
+});
+
+describe('refuseDemoBrandWrites', () => {
+ it('refuses a write naming a demo brand in the path, the body or the query', async () => {
+ expectRefused(await run({ path: `/prompts/suggestions/${DEMO}/refresh` }), 'path');
+ expectRefused(await run({ path: '/tracking/check', body: { brandId: DEMO } }), 'body');
+ expectRefused(
+ await run({ path: '/catalog/upload', query: { brandId: DEMO, format: 'csv' } }),
+ 'query',
+ );
+ expect(DEMO_BRAND).toEqual({
+ success: false,
+ error: 'plan_limit',
+ code: 'demo_brand',
+ message:
+ 'This is the demo brand, with sample data to explore. Choose a plan to do this for your own brand.',
+ });
+ });
+
+ it("refuses a write on a demo brand's row, through its brand", async () => {
+ expectRefused(
+ await run({ path: `/content-drafts/${DEMO_DRAFT}/publish` }),
+ 'content_drafts by path',
+ );
+ expectRefused(
+ await run({ path: '/content-pages/claims', body: { draftId: DEMO_DRAFT } }),
+ 'content_drafts by body',
+ );
+ expectRefused(await run({ path: `/prompts/${DEMO_PROMPT}/improve` }), 'prompts');
+ expectRefused(await run({ path: `/action-center/tasks/${DEMO_TASK}/check` }), 'tasks');
+ expectRefused(
+ await run({ method: 'PATCH', path: `/content/${DEMO_OPP}/status` }),
+ 'opportunity',
+ );
+ expect(reads.find((read) => read.table === 'prompts').columns).toBe(
+ 'id, prompt_sets!inner(brand_id)',
+ );
+ expect(reads.find((read) => read.table === 'action_tasks').columns).toBe(
+ 'id, actions!inner(brand_id)',
+ );
+ });
+
+ it('refuses a bulk write when any of its rows is a demo brand’s', async () => {
+ expectRefused(
+ await run({ path: '/content/bulk/status', body: { ids: [REAL_OPP, DEMO_OPP] } }),
+ 'bulk',
+ );
+ // /content/bulk/send-webhook is the bulk route, not /content/:id/send-webhook.
+ expectRefused(
+ await run({ path: '/content/bulk/send-webhook', body: { ids: [DEMO_OPP] } }),
+ 'bulk send',
+ );
+ });
+
+ it('refuses a demo brand named in any form Postgres reads as its uuid', async () => {
+ const bare = DEMO.replace(/-/g, '');
+ for (const id of [
+ DEMO.toUpperCase(),
+ bare,
+ `{${DEMO}}`,
+ `{${bare.toUpperCase()}}`,
+ `${bare.slice(0, 4)}-${bare.slice(4, 8)}-${bare.slice(8)}`,
+ ]) {
+ expectRefused(await run({ path: '/tracking/check', body: { brandId: id } }), id);
+ expectRefused(await run({ path: `/prompts/suggestions/${id}/refresh` }), `path ${id}`);
+ }
+ expectRefused(
+ await run({ path: '/content/bulk/delete', body: { ids: [DEMO_OPP.replace(/-/g, '')] } }),
+ 'bare row id',
+ );
+ // Not uuids, to Postgres either: left to the route.
+ for (const id of [`{${DEMO}`, `${DEMO}0`, ` ${DEMO}`]) {
+ expectPassed(await run({ path: '/tracking/check', body: { brandId: id } }), id);
+ }
+ });
+
+ it('refuses a bulk write naming more ids than it checks, wherever the demo row is', async () => {
+ const ids = [...Array.from({ length: MAX_IDS }, () => REAL_OPP), DEMO_OPP];
+ const { res, next } = await run({ path: '/content/bulk/delete', body: { ids } });
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(400);
+ expect(reads).toEqual([]);
+ expectPassed(
+ await run({ path: '/content/bulk/delete', body: { ids: ids.slice(0, MAX_IDS) } }),
+ 'at the cap',
+ );
+ });
+
+ it('refuses when either of two sources names a demo brand', async () => {
+ // A real brand in the body, a demo draft in the path.
+ expectRefused(
+ await run({ path: `/content-drafts/${DEMO_DRAFT}/write`, body: { brandId: REAL } }),
+ 'draft',
+ );
+ expectPassed(
+ await run({ path: `/content-drafts/${REAL_DRAFT}/write`, body: { brandId: REAL } }),
+ 'real draft',
+ );
+ });
+
+ it("lets a real brand's writes through", async () => {
+ expectPassed(await run({ path: '/tracking/check', body: { brandId: REAL } }), 'body');
+ expectPassed(await run({ path: `/content/${REAL_OPP}/brief` }), 'row');
+ expectPassed(await run({ method: 'DELETE', path: `/cms/brands/${REAL}/webflow` }), 'path');
+ });
+
+ it('lets reads through without reading anything', async () => {
+ for (const method of ['GET', 'HEAD', 'OPTIONS']) {
+ expectPassed(await run({ method, path: `/prompts/suggestions/${DEMO}/refresh` }), method);
+ }
+ expect(reads).toEqual([]);
+ });
+
+ it('lets the open routes and unknown routes through without reading anything', async () => {
+ for (const [method, path] of [
+ ['POST', '/demo'],
+ ['PATCH', '/demo'],
+ ['DELETE', `/brands/${DEMO}`],
+ ['DELETE', `/tracking/job/${MISSING}`],
+ ['POST', `/content-drafts/${DEMO_DRAFT}/stop`],
+ ['POST', '/prompts/fanout-intents'],
+ ['POST', '/nowhere'],
+ ]) {
+ expectPassed(await run({ method, path, body: { brandId: DEMO } }), `${method} ${path}`);
+ }
+ expect(reads).toEqual([]);
+ });
+
+ it('leaves a missing row, a missing brand or a malformed id to the route', async () => {
+ expectPassed(await run({ path: `/content/${MISSING}/brief` }), 'missing row');
+ expectPassed(await run({ path: '/tracking/check', body: { brandId: MISSING } }), 'missing');
+ expectPassed(await run({ path: '/tracking/check', body: {} }), 'none');
+ expectPassed(await run({ path: '/tracking/check', body: { brandId: 'demo' } }), 'malformed');
+ expectPassed(await run({ path: '/content/bulk/delete', body: { ids: 'nope' } }), 'not ids');
+ // Org-wide syncs name no brand: the sync itself skips demo brands.
+ expectPassed(await run({ path: '/integrations/google-search-console/sync' }), 'org sync');
+ });
+
+ it('answers 500 and never lets the write through when it cannot tell', async () => {
+ failWith = 'timeout';
+ const log = { error: vi.fn() };
+ const { res, next } = await run({ path: '/tracking/check', body: { brandId: DEMO }, log });
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(500);
+ expect(log.error).toHaveBeenCalledOnce();
+ });
+
+ it('matches paths as Express does: any case, with or without a trailing slash', async () => {
+ expectRefused(await run({ path: '/Tracking/Check/', body: { brandId: DEMO } }), 'case');
+ });
+});
+
+describe('isDemoBrand', () => {
+ it('remembers each brand for good: a brand never turns into a demo brand or back', async () => {
+ expect(await isDemoBrand([REAL, DEMO])).toBe(true);
+ expect(await isDemoBrand(REAL)).toBe(false);
+ expect(await isDemoBrand(DEMO)).toBe(true);
+ expect(reads).toHaveLength(1);
+ // A missing brand isn't remembered.
+ expect(await isDemoBrand(MISSING)).toBe(false);
+ expect(await isDemoBrand(MISSING)).toBe(false);
+ expect(reads).toHaveLength(3);
+ });
+
+ it('reads nothing for no ids or malformed ones', async () => {
+ expect(await isDemoBrand([])).toBe(false);
+ expect(await isDemoBrand([null, 'x'])).toBe(false);
+ expect(reads).toEqual([]);
+ });
+
+ it('forgets the oldest brand first once full', async () => {
+ const ids = Array.from(
+ { length: MAX_CACHED_BRANDS },
+ (_, i) => `33333333-3333-3333-3333-${String(i).padStart(12, '0')}`,
+ );
+ rows.brands.push(...ids.map((id) => ({ id, is_demo: false })));
+ await isDemoBrand(DEMO);
+ // A call looks at 500 ids at most.
+ for (let i = 0; i < ids.length; i += 500) await isDemoBrand(ids.slice(i, i + 500));
+ reads.length = 0;
+ await isDemoBrand(ids[ids.length - 1]);
+ expect(reads).toHaveLength(0);
+ await isDemoBrand(DEMO);
+ expect(reads).toHaveLength(1);
+ });
+});
+
+describe('isDemoBrandRow', () => {
+ it('tells whether a row belongs to a demo brand, through its brand', async () => {
+ expect(await isDemoBrandRow('content_opportunities', DEMO_OPP)).toBe(true);
+ expect(await isDemoBrandRow('content_opportunities', REAL_OPP)).toBe(false);
+ expect(await isDemoBrandRow('prompts', DEMO_PROMPT)).toBe(true);
+ expect(await isDemoBrandRow('content_opportunities', MISSING)).toBe(false);
+ });
+});
+
+/**
+ * The internal endpoints the MCP calls trust CRON_SECRET and never meet the
+ * middleware (server.js mounts them before /api). server.js can't be
+ * imported here, so each one is read: it answers a demo brand with 402
+ * demo_brand before it starts its work.
+ */
+describe("the MCP's internal endpoints", () => {
+ it('refuse a demo brand before the work starts', async () => {
+ const source = await readFile(new URL('../server.js', import.meta.url), 'utf8');
+ const handler = (route) => {
+ const start = source.indexOf(`app.post('${route}'`);
+ expect(start, route).toBeGreaterThan(0);
+ return source.slice(start, source.indexOf('\n});\n', start));
+ };
+ for (const [route, check, work] of [
+ [
+ '/api/internal/content/:id/brief',
+ "isDemoBrandRow('content_opportunities', id)",
+ 'generateBriefForOpportunity(',
+ ],
+ ['/api/internal/site-audits', 'isDemoBrand(brandId)', 'startSiteAuditForBrand('],
+ [
+ '/api/internal/prompts/:promptId/improve/action',
+ "isDemoBrandRow('prompts', req.params.promptId)",
+ 'sendImproveActionForKeyUser(',
+ ],
+ [
+ '/api/internal/content-drafts/:draftId/publish',
+ "isDemoBrandRow('content_drafts', draftId.data)",
+ 'publishDraftForKeyUser(',
+ ],
+ ]) {
+ const body = handler(route);
+ expect(body.indexOf(check), route).toBeGreaterThan(0);
+ expect(body.indexOf(check), route).toBeLessThan(body.indexOf(work));
+ expect(body, route).toMatch(/res\.status\(402\)\.json\(DEMO_BRAND\)/);
+ }
+ });
+});
+
+/**
+ * Every write route under /api, read from the route files as routes/index.js
+ * mounts them: each is guarded or open with a reason, never both, and each
+ * entry names a route that exists.
+ */
+describe('coverage of the write routes', () => {
+ const routesDir = new URL('../routes/', import.meta.url);
+
+ async function writeRoutes() {
+ const index = await readFile(new URL('index.js', routesDir), 'utf8');
+ const files = new Map(
+ [...index.matchAll(/^import (\w+) from '\.\/([\w-]+\.js)';$/gm)].map((m) => [m[1], m[2]]),
+ );
+ const mounts = [...index.matchAll(/^router\.use\('([^']+)', (\w+)\);$/gm)];
+ expect(mounts.length).toBeGreaterThan(15);
+ const routes = [];
+ for (const [, prefix, name] of mounts) {
+ const source = await readFile(new URL(files.get(name), routesDir), 'utf8');
+ // Every route is router.<method>(path, …): no router.all or router.route
+ // this reading would miss.
+ expect(source, files.get(name)).not.toMatch(/router\.(all|route)\(/);
+ for (const m of source.matchAll(/^router\.(post|put|patch|delete)\(\s*'([^']*)'/gm)) {
+ const path = m[2] === '/' ? prefix : `${prefix}${m[2]}`;
+ routes.push(`${m[1].toUpperCase()} ${path}`);
+ }
+ }
+ return routes;
+ }
+
+ it('names every write route once, as guarded or as open', async () => {
+ const routes = await writeRoutes();
+ const guarded = DEMO_GUARDED.map((entry) => entry.route);
+ const opened = DEMO_OPEN.map((entry) => entry.route);
+
+ const unnamed = routes.filter((route) => !guarded.includes(route) && !opened.includes(route));
+ expect(unnamed, 'write routes neither guarded nor open: add them to demo-brand.js').toEqual([]);
+ const stale = [...guarded, ...opened].filter((route) => !routes.includes(route));
+ expect(stale, 'entries naming no route').toEqual([]);
+ expect(guarded.filter((route) => opened.includes(route))).toEqual([]);
+ expect(new Set(guarded).size).toBe(guarded.length);
+ expect(new Set(opened).size).toBe(opened.length);
+ expect(routes.length).toBe(guarded.length + opened.length);
+ });
+
+ it('gives every open route a reason', () => {
+ for (const entry of DEMO_OPEN) expect(entry.why.length, entry.route).toBeGreaterThan(20);
+ });
+
+ it('reads each guarded brand from a part of the request the route has', () => {
+ for (const { route, sources } of DEMO_GUARDED) {
+ expect(sources.length, route).toBeGreaterThan(0);
+ for (const source of sources) {
+ expect(['path', 'body', 'query'], route).toContain(source.where);
+ if (source.where === 'path') expect(route, route).toContain(`/:${source.key}`);
+ }
+ }
+ });
+
+ it('reaches, for each route, its own entry', async () => {
+ const routes = await writeRoutes();
+ const sample = (route) => route.replace(/:\w+/g, MISSING).split(' ');
+ for (const route of routes) {
+ const [method, path] = sample(route);
+ expect(demoRouteFor({ method, path })?.entry.route, route).toBe(route);
+ }
+ });
+
+ it('leaves the routes of webhooks, callbacks and public beacons to their own mounts', async () => {
+ const files = (await readdir(routesDir)).filter(
+ (file) => file.endsWith('.js') && !file.endsWith('.test.js'),
+ );
+ const index = await readFile(new URL('index.js', routesDir), 'utf8');
+ const outside = files.filter(
+ (file) => file !== 'index.js' && !index.includes(`from './${file}'`),
+ );
+ expect(outside.sort()).toEqual([
+ 'bot-ingest.js',
+ 'cloro-callback.js',
+ // The first run after a payment (CRON_SECRET): refuses a demo brand itself.
+ 'internal-trigger-tracking.js',
+ 'traffic.js',
+ 'webhook-content-callback.js',
+ 'webhook-content-draft-callback.js',
+ ]);
+ });
+});
diff --git a/server/src/middleware/subscription.test.js b/server/src/middleware/subscription.test.js
index 7a36be31b..891966bdc 100644
--- a/server/src/middleware/subscription.test.js
+++ b/server/src/middleware/subscription.test.js
@@ -529,19 +529,28 @@ describe('when the check cannot be read', () => {
/**
* server.js can't be imported here (it listens and starts the crons), so its
- * mount is read: the API's routes are reached only through decodeToken and
- * then this middleware, and the webhooks are mounted outside /api.
+ * mount is read: the API's routes are reached only through decodeToken, the
+ * demo brand's check (demo-brand.js) and then this middleware, and the
+ * webhooks are mounted outside /api.
*/
describe("server.js's mount", () => {
- it('puts every API route behind the person and then the plan', async () => {
+ it('puts every API route behind the person, the demo brand and then the plan', async () => {
const source = await readFile(new URL('../server.js', import.meta.url), 'utf8');
- const mounts = source
+ // One call per line, however Prettier wraps it.
+ const flat = source
+ .replace(/\(\s+/g, '(')
+ .replace(/,\s+/g, ', ')
+ .replace(/,?\s+\)/g, ')');
+ const mounts = flat
.split('\n')
.map((line) => line.trim())
.filter((line) => /^app\.use\(.*\broutes\);$/.test(line));
expect(mounts).toEqual([
- "app.use('/api', Middleware.decodeToken.bind(Middleware), requireActiveSubscription, routes);",
+ "app.use('/api', Middleware.decodeToken.bind(Middleware), refuseDemoBrandWrites, requireActiveSubscription, routes);",
]);
+ expect(source).toMatch(
+ /import \{[^}]*\brefuseDemoBrandWrites\b[^}]*\} from '\.\/middleware\/demo-brand\.js';/,
+ );
expect(source).toMatch(
/import \{ requireActiveSubscription \} from '\.\/middleware\/subscription\.js';/,
);
diff --git a/server/src/routes/brand-facts.js b/server/src/routes/brand-facts.js
index 95dec0cb5..cca186470 100644
--- a/server/src/routes/brand-facts.js
+++ b/server/src/routes/brand-facts.js
@@ -5,6 +5,7 @@ import { assertBrandAccess } from '../lib/access.js';
import { isOrgActive } from '../lib/active-subscriptions.js';
import { readBrandFacts, setFactStatus } from '../lib/brand-facts.js';
import { qualityPhase } from '../lib/content-quality.js';
+import { isDemoBrand } from '../middleware/demo-brand.js';
import { brandFactsLimiter } from '../middleware/rate-limiter.js';
/**
@@ -32,14 +33,15 @@ function failed(req, res, err, what) {
// GET /api/brand-facts?brandId=… — the facts, read from the site on the
// first ask (once, however many ask), else as kept: the editor reads it
// each time its tab comes back, so it has no bucket of its own. Once the
-// plan has ended, only as kept: the site isn't read for it.
+// plan has ended, and on a demo brand (sample facts, 00380), only as kept:
+// the site isn't read for it.
router.get('/', async (req, res) => {
if (qualityPhase() < 2) return off(res);
const parsed = z.guid().safeParse(req.query.brandId);
if (!parsed.success) return res.status(400).json({ error: 'invalid', code: 'invalid' });
try {
const { orgId } = await assertBrandAccess(parsed.data, req.user.id);
- const keptOnly = !(await isOrgActive(orgId));
+ const keptOnly = !(await isOrgActive(orgId)) || (await isDemoBrand(parsed.data));
return res.json(await readBrandFacts(parsed.data, { orgId, keptOnly }));
} catch (err) {
return failed(req, res, err, 'brand facts read error');
diff --git a/server/src/routes/brand-facts.test.js b/server/src/routes/brand-facts.test.js
index 0945a026e..8e3fd5a1f 100644
--- a/server/src/routes/brand-facts.test.js
+++ b/server/src/routes/brand-facts.test.js
@@ -15,6 +15,7 @@ const assertBrandAccess = vi.fn();
const readBrandFacts = vi.fn();
const setFactStatus = vi.fn();
const isOrgActive = vi.fn();
+const isDemoBrand = vi.fn();
vi.mock('../config/supabase.js', () => ({
default: {
@@ -39,6 +40,9 @@ vi.mock('../lib/brand-facts.js', () => ({
vi.mock('../lib/active-subscriptions.js', () => ({
isOrgActive: (...args) => isOrgActive(...args),
}));
+vi.mock('../middleware/demo-brand.js', () => ({
+ isDemoBrand: (...args) => isDemoBrand(...args),
+}));
const { default: router } = await import('./brand-facts.js');
@@ -52,6 +56,7 @@ beforeEach(async () => {
readBrandFacts.mockReset().mockResolvedValue({ facts: [], pages: [], paused: false });
setFactStatus.mockReset().mockResolvedValue({ id: FACT, status: 'approved' });
isOrgActive.mockReset().mockResolvedValue(true);
+ isDemoBrand.mockReset().mockResolvedValue(false);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
@@ -86,6 +91,14 @@ describe('/api/brand-facts', () => {
expect(readBrandFacts).toHaveBeenCalledWith(BRAND, { orgId: 'o1', keptOnly: true });
});
+ it('reads only what is kept on a demo brand: its facts are sample data', async () => {
+ isDemoBrand.mockResolvedValue(true);
+ const res = await send(`?brandId=${BRAND}`, 'GET');
+ expect(res.status).toBe(200);
+ expect(isDemoBrand).toHaveBeenCalledWith(BRAND);
+ expect(readBrandFacts).toHaveBeenCalledWith(BRAND, { orgId: 'o1', keptOnly: true });
+ });
+
it('reads the facts for a member, and reads the site again when asked', async () => {
const res = await send(`?brandId=${BRAND}`, 'GET');
expect(res.status).toBe(200);
diff --git a/server/src/routes/internal-trigger-tracking.js b/server/src/routes/internal-trigger-tracking.js
index 0545a08f8..cae8c111a 100644
--- a/server/src/routes/internal-trigger-tracking.js
+++ b/server/src/routes/internal-trigger-tracking.js
@@ -7,7 +7,8 @@
* finds the run already started gets its id back with `created: false`. The
* call that starts the run also starts the brand's volume analysis, here
* rather than from the web app, so a caller that gives up waiting for the
- * answer still gets both.
+ * answer still gets both. Never on a demo brand (00380): 402 demo_brand,
+ * before any job is written.
*
* Mounted in server.js before the authenticated /api routes.
*/
@@ -17,6 +18,7 @@ import { z } from 'zod';
import { startFirstRun } from '../lib/first-run.js';
import { runTrackingJob } from '../lib/job-runner.js';
import { analyzeBrandVolumes } from '../lib/volume-analysis.js';
+import { DEMO_BRAND, isDemoBrand } from '../middleware/demo-brand.js';
const router = Router();
@@ -40,6 +42,7 @@ router.post('/', async (req, res) => {
const { brandId } = parsed.data;
try {
+ if (await isDemoBrand(brandId)) return res.status(402).json(DEMO_BRAND);
const { job, created } = await startFirstRun(parsed.data);
if (created) {
runTrackingJob(job.id, req.app.get('io'), { priority: true });
diff --git a/server/src/routes/internal-trigger-tracking.test.js b/server/src/routes/internal-trigger-tracking.test.js
index f45e9a4f9..51f584abb 100644
--- a/server/src/routes/internal-trigger-tracking.test.js
+++ b/server/src/routes/internal-trigger-tracking.test.js
@@ -9,12 +9,18 @@ import express from 'express';
const startFirstRun = vi.fn();
const runTrackingJob = vi.fn();
const analyzeBrandVolumes = vi.fn();
+const isDemoBrand = vi.fn();
vi.mock('../lib/first-run.js', () => ({ startFirstRun: (...args) => startFirstRun(...args) }));
vi.mock('../lib/job-runner.js', () => ({ runTrackingJob: (...args) => runTrackingJob(...args) }));
vi.mock('../lib/volume-analysis.js', () => ({
analyzeBrandVolumes: (...args) => analyzeBrandVolumes(...args),
}));
+vi.mock('../middleware/demo-brand.js', () => ({
+ DEMO_BRAND: { code: 'demo_brand' },
+ isDemoBrand: (...args) => isDemoBrand(...args),
+}));
+
const { default: router } = await import('./internal-trigger-tracking.js');
const io = { emit: vi.fn() };
@@ -27,6 +33,7 @@ beforeEach(async () => {
startFirstRun.mockReset().mockResolvedValue({ job: { id: 'job1' }, created: true });
runTrackingJob.mockReset();
analyzeBrandVolumes.mockReset().mockResolvedValue({});
+ isDemoBrand.mockReset().mockResolvedValue(false);
log.error.mockReset();
const app = express();
app.set('io', io);
@@ -95,6 +102,17 @@ describe('POST /api/internal/trigger-tracking', () => {
expect(startFirstRun).not.toHaveBeenCalled();
});
+ it('refuses a demo brand with 402, starting nothing', async () => {
+ isDemoBrand.mockResolvedValue(true);
+ const res = await send({ brandId: 'demo' });
+
+ expect(res.status).toBe(402);
+ expect(await res.json()).toMatchObject({ code: 'demo_brand' });
+ expect(isDemoBrand).toHaveBeenCalledWith('demo');
+ expect(startFirstRun).not.toHaveBeenCalled();
+ expect(analyzeBrandVolumes).not.toHaveBeenCalled();
+ });
+
it('refuses a caller without the secret', async () => {
const res = await send({ brandId: 'b1' }, 'wrong');
diff --git a/server/src/server.js b/server/src/server.js
index e2b94e451..2eb0eab21 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -13,6 +13,12 @@ import Middleware from './middleware/index.js';
import { apiLimiter } from './middleware/rate-limiter.js';
import requestIdMiddleware from './middleware/request-id.js';
import { requireActiveSubscription } from './middleware/subscription.js';
+import {
+ DEMO_BRAND,
+ isDemoBrand,
+ isDemoBrandRow,
+ refuseDemoBrandWrites,
+} from './middleware/demo-brand.js';
import routes from './routes/index.js';
import trafficRoutes from './routes/traffic.js';
import botIngestRoutes from './routes/bot-ingest.js';
@@ -34,6 +40,7 @@ import { sweepActionValidation } from './lib/action-center/validate.js';
import { sweepImproveOutcomes } from './lib/action-center/improve-outcome.js';
import { sweepBrandFacts } from './lib/brand-facts-sweep.js';
import { purgeRemovedCatalogProducts } from './lib/catalog/purge.js';
+import { sweepIdleDemoBrands } from './lib/demo/idle-sweep.js';
import { sweepCatalogSources } from './lib/catalog/sources.js';
import { sweepShoppingCardMatches } from './lib/catalog/card-match.js';
import { sweepFramerPublished } from './lib/cms/framer-status.js';
@@ -335,6 +342,12 @@ async function runDailyTracking() {
logger.error({ err }, '[content-history] daily prune failed');
});
+ // Demo brands nobody opened for two weeks (00380): their sample rows go,
+ // the brand row stays, and the next visit builds them again.
+ sweepIdleDemoBrands().catch((err) => {
+ logger.error({ err }, '[demo] idle sweep failed');
+ });
+
// Catalog feed URLs (#1263): read again once a day, never blocking tracking.
// Then the products removed from their source over 90 days ago are
// deleted: after the sweep, so it isn't deleting while a sync brings one back.
@@ -441,7 +454,8 @@ app.post('/api/internal/daily-tracking', async (req, res) => {
// key belongs to the same org as the opportunity. So this endpoint just
// trusts the secret and runs the LLM. Always passes force=true to bypass
// the cached-brief early-return (MCP callers want a fresh brief; for
-// cached reads they should use get_content_opportunity instead).
+// cached reads they should use get_content_opportunity instead). Never on
+// a demo brand (00380): 402 demo_brand, as the API answers.
app.post('/api/internal/content/:id/brief', async (req, res) => {
const secret = req.headers.authorization?.replace('Bearer ', '');
if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {
@@ -450,6 +464,9 @@ app.post('/api/internal/content/:id/brief', async (req, res) => {
try {
const { id } = req.params;
+ if (await isDemoBrandRow('content_opportunities', id)) {
+ return res.status(402).json(DEMO_BRAND);
+ }
const { force, model } = req.body || {};
const result = await generateBriefForOpportunity(id, {
force: Boolean(force),
@@ -482,7 +499,7 @@ app.post('/api/internal/content/:id/brief', async (req, res) => {
// before reaching here, so this endpoint just trusts the secret, resolves the
// brand's org, enforces the monthly Site Audit quota, and starts the detached
// audit job — returning the new `running` audit (the MCP caller then polls
-// get_site_audit for the result).
+// get_site_audit for the result). Never on a demo brand (00380).
app.post('/api/internal/site-audits', async (req, res) => {
const secret = req.headers.authorization?.replace('Bearer ', '');
if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {
@@ -494,6 +511,7 @@ app.post('/api/internal/site-audits', async (req, res) => {
if (!brandId || !url) {
return res.status(400).json({ success: false, message: 'brandId and url are required' });
}
+ if (await isDemoBrand(brandId)) return res.status(402).json(DEMO_BRAND);
const audit = await startSiteAuditForBrand(brandId, url);
return res.status(202).json({ success: true, audit });
} catch (err) {
@@ -592,6 +610,7 @@ app.get('/api/internal/integrations-config', (req, res) => {
// before reaching here and passes the key's user, so this endpoint trusts the
// secret, checks the user's plan includes prompt_improve and creates the
// Action Center action exactly as the Improve tab's "Send Actions" does.
+// Never on a demo brand's prompt (00380).
app.post('/api/internal/prompts/:promptId/improve/action', async (req, res) => {
const secret = req.headers.authorization?.replace('Bearer ', '');
if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {
@@ -603,6 +622,9 @@ app.post('/api/internal/prompts/:promptId/improve/action', async (req, res) => {
if (!userId) {
return res.status(400).json({ success: false, message: 'userId is required' });
}
+ if (await isDemoBrandRow('prompts', req.params.promptId)) {
+ return res.status(402).json(DEMO_BRAND);
+ }
const result = await sendImproveActionForKeyUser({
promptId: req.params.promptId,
userId,
@@ -631,7 +653,8 @@ app.post('/api/internal/prompts/:promptId/improve/action', async (req, res) => {
// A page marked Published at its live address for an MCP API key
// (`mark_content_draft_published`), as the editor's Mark published does
// (POST /api/content-drafts/:draftId/publish). The web MCP layer passes the
-// key's organization and user; the draft must be that organization's.
+// key's organization and user; the draft must be that organization's. Never
+// on a demo brand's draft (00380).
const internalPublishBody = z.object({
url: z.string().max(8192),
userId: z.guid(),
@@ -658,6 +681,9 @@ app.post('/api/internal/content-drafts/:draftId/publish', async (req, res) => {
});
}
try {
+ if (await isDemoBrandRow('content_drafts', draftId.data)) {
+ return res.status(402).json(DEMO_BRAND);
+ }
const result = await publishDraftForKeyUser({
draftId: draftId.data,
url,
@@ -717,10 +743,18 @@ app.use('/webhooks/content', webhookContentCallbackRoutes);
app.use('/webhooks/content-drafts', webhookContentDraftCallbackRoutes);
// --- Authenticated API routes ---
-// Read-only once the plan has ended (middleware/subscription.js): checked
-// once the person is known, before any route. The webhooks, callbacks and
-// internal endpoints above never reach it.
-app.use('/api', Middleware.decodeToken.bind(Middleware), requireActiveSubscription, routes);
+// The demo brand is read-only (middleware/demo-brand.js), and so is a
+// workspace whose plan has ended (middleware/subscription.js): both checked
+// once the person is known, before any route, the demo brand first so its
+// answer is the same with a plan or without one. The webhooks, callbacks and
+// internal endpoints above never reach them.
+app.use(
+ '/api',
+ Middleware.decodeToken.bind(Middleware),
+ refuseDemoBrandWrites,
+ requireActiveSubscription,
+ routes,
+);
// Health check
app.get('/', (req, res) => {
diff --git a/supabase/migrations/00381_demo_brand_writes.sql b/supabase/migrations/00381_demo_brand_writes.sql
new file mode 100644
index 000000000..c6a845af8
--- /dev/null
+++ b/supabase/migrations/00381_demo_brand_writes.sql
@@ -0,0 +1,265 @@
+-- ============================================================================
+-- 00381: people can't write the demo brand's data (demo-guard)
+-- ============================================================================
+-- The demo brand (00380) is sample data the server writes (server/src/lib/
+-- demo) with the service role. People explore it, but nothing of theirs may
+-- change it: the API refuses its writes (402 demo_brand, server/src/
+-- middleware/demo-brand.js) and so does the web app's lock, but members can
+-- also write a brand's rows straight through Supabase, under RLS. This
+-- refuses those writes in the database.
+--
+-- refuse_demo_brand_writes() is a BEFORE INSERT/UPDATE/DELETE row trigger:
+-- * a role that bypasses RLS (the service role the server and the demo
+-- generator use, migrations, the table owner behind a cascade) passes,
+-- as in the other server-column guards (00204, 00228). Not, though, a
+-- SECURITY DEFINER function a person calls (approve_action_task_review,
+-- content_draft_restore, override_mention_sentiment, seed_kpi_presets):
+-- it runs as its owner, who bypasses RLS, but the write is the person's.
+-- So the session's own role decides (the one PostgREST sets per request:
+-- authenticated or anon is a person), unless the write comes from inside
+-- another trigger (a cascade, or a trigger of the server's);
+-- * otherwise, a row of a demo brand is refused with SQLSTATE 42501 and
+-- the message 'demo_brand' (an update is checked on its old and new row,
+-- so a row can't be moved into or out of the demo brand either).
+-- With no arguments, the row's brand is its own brand_id. A table without a
+-- brand_id names the way to it: (column, table) pairs, each table's row found
+-- by its id, the last one's brand_id being the brand, e.g. prompt_notes:
+-- prompt_id → prompts, prompt_set_id → prompt_sets.
+--
+-- It is attached to every table people can write under RLS (an insert,
+-- update, delete or all policy for a role other than service_role) that
+-- belongs to a brand. server/src/lib/demo/write-guard.test.js reads the
+-- migrations and fails on such a table without it: a new one attaches it in
+-- its own migration.
+--
+-- It reads the brand (and a parent row) as the person, under RLS: a row of a
+-- brand they can't see is refused by RLS itself. The brands themselves are
+-- guarded by their own policies (00380).
+
+create or replace function public.refuse_demo_brand_writes()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+declare
+ v_keys text[] := '{}';
+ v_key text;
+ v_column text;
+ i integer;
+begin
+ -- A role that bypasses RLS is server-side (service role, migrations), unless
+ -- it is the owner of a SECURITY DEFINER function a person called directly.
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user)
+ and (
+ pg_catalog.pg_trigger_depth() > 1
+ or coalesce(pg_catalog.current_setting('role', true), 'none')
+ not in ('authenticated', 'anon')
+ )
+ then
+ if tg_op = 'DELETE' then
+ return old;
+ end if;
+ return new;
+ end if;
+
+ if tg_nargs = 0 then
+ if tg_op <> 'INSERT' then
+ v_keys := v_keys || old.brand_id::text;
+ end if;
+ if tg_op <> 'DELETE' then
+ v_keys := v_keys || new.brand_id::text;
+ end if;
+ else
+ if tg_op <> 'INSERT' then
+ execute format('select ($1).%I::text', tg_argv[0]) into v_key using old;
+ v_keys := v_keys || v_key;
+ end if;
+ if tg_op <> 'DELETE' then
+ execute format('select ($1).%I::text', tg_argv[0]) into v_key using new;
+ v_keys := v_keys || v_key;
+ end if;
+ -- From each table on the way to the next one's id, the last one's brand_id.
+ i := 1;
+ while i < tg_nargs loop
+ v_column := case when i + 1 < tg_nargs then tg_argv[i + 1] else 'brand_id' end;
+ execute format(
+ 'select coalesce(array_agg(distinct t.%I::text), ''{}'') '
+ || 'from public.%I t where t.id = any ($1::uuid[])',
+ v_column,
+ tg_argv[i]
+ ) into v_keys using v_keys;
+ i := i + 2;
+ end loop;
+ end if;
+
+ if exists (
+ select 1 from public.brands b
+ where b.id = any (v_keys::uuid[])
+ and b.is_demo
+ ) then
+ raise exception 'demo_brand'
+ using errcode = '42501',
+ detail = 'The demo brand holds sample data and can''t be changed.',
+ hint = 'Choose a plan to do this for your own brand.';
+ end if;
+ if tg_op = 'DELETE' then
+ return old;
+ end if;
+ return new;
+end;
+$$;
+
+comment on function public.refuse_demo_brand_writes() is
+ 'Demo brand (00381): refuses a write to a demo brand''s row (42501, ''demo_brand'') unless the role bypasses RLS (the server, which writes the demo''s sample data) and isn''t a person''s SECURITY DEFINER call. No arguments: the row''s brand_id; else (column, table) pairs leading to the brand.';
+
+-- ─── Tables with a brand_id ────────────────────────────────────────────────
+
+create or replace trigger actions_refuse_demo_brand_writes
+ before insert or update or delete on public.actions
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger agent_conversations_refuse_demo_brand_writes
+ before insert or update or delete on public.agent_conversations
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger brand_domains_refuse_demo_brand_writes
+ before insert or update or delete on public.brand_domains
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger brand_facts_refuse_demo_brand_writes
+ before insert or update or delete on public.brand_facts
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger brand_platforms_refuse_demo_brand_writes
+ before insert or update or delete on public.brand_platforms
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger catalog_sources_refuse_demo_brand_writes
+ before insert or update or delete on public.catalog_sources
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger competitors_refuse_demo_brand_writes
+ before insert or update or delete on public.competitors
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger content_author_defaults_refuse_demo_brand_writes
+ before insert or update or delete on public.content_author_defaults
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger content_drafts_refuse_demo_brand_writes
+ before insert or update or delete on public.content_drafts
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger content_opportunities_refuse_demo_brand_writes
+ before insert or update or delete on public.content_opportunities
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger content_plan_marks_refuse_demo_brand_writes
+ before insert or update or delete on public.content_plan_marks
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger getting_started_refuse_demo_brand_writes
+ before insert or update or delete on public.getting_started
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger getting_started_steps_refuse_demo_brand_writes
+ before insert or update or delete on public.getting_started_steps
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger kpi_definitions_refuse_demo_brand_writes
+ before insert or update or delete on public.kpi_definitions
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger prompt_sets_refuse_demo_brand_writes
+ before insert or update or delete on public.prompt_sets
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger prompt_suggestions_refuse_demo_brand_writes
+ before insert or update or delete on public.prompt_suggestions
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger pulse_settings_refuse_demo_brand_writes
+ before insert or update or delete on public.pulse_settings
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger reports_refuse_demo_brand_writes
+ before insert or update or delete on public.reports
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger sentiment_overrides_refuse_demo_brand_writes
+ before insert or update or delete on public.sentiment_overrides
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger signals_refuse_demo_brand_writes
+ before insert or update or delete on public.signals
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger site_audits_refuse_demo_brand_writes
+ before insert or update or delete on public.site_audits
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger topic_suggestions_refuse_demo_brand_writes
+ before insert or update or delete on public.topic_suggestions
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger topics_refuse_demo_brand_writes
+ before insert or update or delete on public.topics
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger webhook_configs_refuse_demo_brand_writes
+ before insert or update or delete on public.webhook_configs
+ for each row execute function public.refuse_demo_brand_writes();
+
+-- ─── Tables that reach their brand through another row ────────────────────
+
+create or replace trigger action_events_refuse_demo_brand_writes
+ before insert or update or delete on public.action_events
+ for each row execute function public.refuse_demo_brand_writes('action_id', 'actions');
+
+create or replace trigger action_task_reviews_refuse_demo_brand_writes
+ before insert or update or delete on public.action_task_reviews
+ for each row execute function public.refuse_demo_brand_writes('action_id', 'actions');
+
+create or replace trigger action_tasks_refuse_demo_brand_writes
+ before insert or update or delete on public.action_tasks
+ for each row execute function public.refuse_demo_brand_writes('action_id', 'actions');
+
+create or replace trigger agent_messages_refuse_demo_brand_writes
+ before insert or update or delete on public.agent_messages
+ for each row execute function public.refuse_demo_brand_writes('conversation_id', 'agent_conversations');
+
+create or replace trigger audit_signal_results_refuse_demo_brand_writes
+ before insert or update or delete on public.audit_signal_results
+ for each row execute function public.refuse_demo_brand_writes('audit_id', 'site_audits');
+
+create or replace trigger content_draft_confirmations_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_confirmations
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger content_draft_inputs_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_inputs
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger content_draft_own_images_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_own_images
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger content_draft_ready_log_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_ready_log
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger content_draft_sources_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_sources
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger prompts_refuse_demo_brand_writes
+ before insert or update or delete on public.prompts
+ for each row execute function public.refuse_demo_brand_writes('prompt_set_id', 'prompt_sets');
+
+create or replace trigger prompt_notes_refuse_demo_brand_writes
+ before insert or update or delete on public.prompt_notes
+ for each row execute function public.refuse_demo_brand_writes('prompt_id', 'prompts', 'prompt_set_id', 'prompt_sets');
+
+create or replace trigger prompt_target_urls_refuse_demo_brand_writes
+ before insert or update or delete on public.prompt_target_urls
+ for each row execute function public.refuse_demo_brand_writes('prompt_id', 'prompts', 'prompt_set_id', 'prompt_sets');
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 42d0fca10..9531fae4d 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -43885,6 +43885,275 @@ grant execute on function public.fanout_coverage_by_platform(timestamptz, timest
comment on function public.fanout_coverage_by_platform(timestamptz, timestamptz) is
'Answers and answers with observed query fan-out per platform in [p_since, p_until), across all brands but demo ones (00140, 00380). Read by the daily health report.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00381_demo_brand_writes.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00381: people can't write the demo brand's data (demo-guard)
+-- ============================================================================
+-- The demo brand (00380) is sample data the server writes (server/src/lib/
+-- demo) with the service role. People explore it, but nothing of theirs may
+-- change it: the API refuses its writes (402 demo_brand, server/src/
+-- middleware/demo-brand.js) and so does the web app's lock, but members can
+-- also write a brand's rows straight through Supabase, under RLS. This
+-- refuses those writes in the database.
+--
+-- refuse_demo_brand_writes() is a BEFORE INSERT/UPDATE/DELETE row trigger:
+-- * a role that bypasses RLS (the service role the server and the demo
+-- generator use, migrations, the table owner behind a cascade) passes,
+-- as in the other server-column guards (00204, 00228). Not, though, a
+-- SECURITY DEFINER function a person calls (approve_action_task_review,
+-- content_draft_restore, override_mention_sentiment, seed_kpi_presets):
+-- it runs as its owner, who bypasses RLS, but the write is the person's.
+-- So the session's own role decides (the one PostgREST sets per request:
+-- authenticated or anon is a person), unless the write comes from inside
+-- another trigger (a cascade, or a trigger of the server's);
+-- * otherwise, a row of a demo brand is refused with SQLSTATE 42501 and
+-- the message 'demo_brand' (an update is checked on its old and new row,
+-- so a row can't be moved into or out of the demo brand either).
+-- With no arguments, the row's brand is its own brand_id. A table without a
+-- brand_id names the way to it: (column, table) pairs, each table's row found
+-- by its id, the last one's brand_id being the brand, e.g. prompt_notes:
+-- prompt_id → prompts, prompt_set_id → prompt_sets.
+--
+-- It is attached to every table people can write under RLS (an insert,
+-- update, delete or all policy for a role other than service_role) that
+-- belongs to a brand. server/src/lib/demo/write-guard.test.js reads the
+-- migrations and fails on such a table without it: a new one attaches it in
+-- its own migration.
+--
+-- It reads the brand (and a parent row) as the person, under RLS: a row of a
+-- brand they can't see is refused by RLS itself. The brands themselves are
+-- guarded by their own policies (00380).
+
+create or replace function public.refuse_demo_brand_writes()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+declare
+ v_keys text[] := '{}';
+ v_key text;
+ v_column text;
+ i integer;
+begin
+ -- A role that bypasses RLS is server-side (service role, migrations), unless
+ -- it is the owner of a SECURITY DEFINER function a person called directly.
+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user)
+ and (
+ pg_catalog.pg_trigger_depth() > 1
+ or coalesce(pg_catalog.current_setting('role', true), 'none')
+ not in ('authenticated', 'anon')
+ )
+ then
+ if tg_op = 'DELETE' then
+ return old;
+ end if;
+ return new;
+ end if;
+
+ if tg_nargs = 0 then
+ if tg_op <> 'INSERT' then
+ v_keys := v_keys || old.brand_id::text;
+ end if;
+ if tg_op <> 'DELETE' then
+ v_keys := v_keys || new.brand_id::text;
+ end if;
+ else
+ if tg_op <> 'INSERT' then
+ execute format('select ($1).%I::text', tg_argv[0]) into v_key using old;
+ v_keys := v_keys || v_key;
+ end if;
+ if tg_op <> 'DELETE' then
+ execute format('select ($1).%I::text', tg_argv[0]) into v_key using new;
+ v_keys := v_keys || v_key;
+ end if;
+ -- From each table on the way to the next one's id, the last one's brand_id.
+ i := 1;
+ while i < tg_nargs loop
+ v_column := case when i + 1 < tg_nargs then tg_argv[i + 1] else 'brand_id' end;
+ execute format(
+ 'select coalesce(array_agg(distinct t.%I::text), ''{}'') '
+ || 'from public.%I t where t.id = any ($1::uuid[])',
+ v_column,
+ tg_argv[i]
+ ) into v_keys using v_keys;
+ i := i + 2;
+ end loop;
+ end if;
+
+ if exists (
+ select 1 from public.brands b
+ where b.id = any (v_keys::uuid[])
+ and b.is_demo
+ ) then
+ raise exception 'demo_brand'
+ using errcode = '42501',
+ detail = 'The demo brand holds sample data and can''t be changed.',
+ hint = 'Choose a plan to do this for your own brand.';
+ end if;
+ if tg_op = 'DELETE' then
+ return old;
+ end if;
+ return new;
+end;
+$$;
+
+comment on function public.refuse_demo_brand_writes() is
+ 'Demo brand (00381): refuses a write to a demo brand''s row (42501, ''demo_brand'') unless the role bypasses RLS (the server, which writes the demo''s sample data) and isn''t a person''s SECURITY DEFINER call. No arguments: the row''s brand_id; else (column, table) pairs leading to the brand.';
+
+-- ─── Tables with a brand_id ────────────────────────────────────────────────
+
+create or replace trigger actions_refuse_demo_brand_writes
+ before insert or update or delete on public.actions
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger agent_conversations_refuse_demo_brand_writes
+ before insert or update or delete on public.agent_conversations
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger brand_domains_refuse_demo_brand_writes
+ before insert or update or delete on public.brand_domains
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger brand_facts_refuse_demo_brand_writes
+ before insert or update or delete on public.brand_facts
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger brand_platforms_refuse_demo_brand_writes
+ before insert or update or delete on public.brand_platforms
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger catalog_sources_refuse_demo_brand_writes
+ before insert or update or delete on public.catalog_sources
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger competitors_refuse_demo_brand_writes
+ before insert or update or delete on public.competitors
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger content_author_defaults_refuse_demo_brand_writes
+ before insert or update or delete on public.content_author_defaults
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger content_drafts_refuse_demo_brand_writes
+ before insert or update or delete on public.content_drafts
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger content_opportunities_refuse_demo_brand_writes
+ before insert or update or delete on public.content_opportunities
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger content_plan_marks_refuse_demo_brand_writes
+ before insert or update or delete on public.content_plan_marks
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger getting_started_refuse_demo_brand_writes
+ before insert or update or delete on public.getting_started
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger getting_started_steps_refuse_demo_brand_writes
+ before insert or update or delete on public.getting_started_steps
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger kpi_definitions_refuse_demo_brand_writes
+ before insert or update or delete on public.kpi_definitions
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger prompt_sets_refuse_demo_brand_writes
+ before insert or update or delete on public.prompt_sets
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger prompt_suggestions_refuse_demo_brand_writes
+ before insert or update or delete on public.prompt_suggestions
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger pulse_settings_refuse_demo_brand_writes
+ before insert or update or delete on public.pulse_settings
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger reports_refuse_demo_brand_writes
+ before insert or update or delete on public.reports
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger sentiment_overrides_refuse_demo_brand_writes
+ before insert or update or delete on public.sentiment_overrides
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger signals_refuse_demo_brand_writes
+ before insert or update or delete on public.signals
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger site_audits_refuse_demo_brand_writes
+ before insert or update or delete on public.site_audits
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger topic_suggestions_refuse_demo_brand_writes
+ before insert or update or delete on public.topic_suggestions
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger topics_refuse_demo_brand_writes
+ before insert or update or delete on public.topics
+ for each row execute function public.refuse_demo_brand_writes();
+
+create or replace trigger webhook_configs_refuse_demo_brand_writes
+ before insert or update or delete on public.webhook_configs
+ for each row execute function public.refuse_demo_brand_writes();
+
+-- ─── Tables that reach their brand through another row ────────────────────
+
+create or replace trigger action_events_refuse_demo_brand_writes
+ before insert or update or delete on public.action_events
+ for each row execute function public.refuse_demo_brand_writes('action_id', 'actions');
+
+create or replace trigger action_task_reviews_refuse_demo_brand_writes
+ before insert or update or delete on public.action_task_reviews
+ for each row execute function public.refuse_demo_brand_writes('action_id', 'actions');
+
+create or replace trigger action_tasks_refuse_demo_brand_writes
+ before insert or update or delete on public.action_tasks
+ for each row execute function public.refuse_demo_brand_writes('action_id', 'actions');
+
+create or replace trigger agent_messages_refuse_demo_brand_writes
+ before insert or update or delete on public.agent_messages
+ for each row execute function public.refuse_demo_brand_writes('conversation_id', 'agent_conversations');
+
+create or replace trigger audit_signal_results_refuse_demo_brand_writes
+ before insert or update or delete on public.audit_signal_results
+ for each row execute function public.refuse_demo_brand_writes('audit_id', 'site_audits');
+
+create or replace trigger content_draft_confirmations_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_confirmations
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger content_draft_inputs_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_inputs
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger content_draft_own_images_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_own_images
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger content_draft_ready_log_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_ready_log
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger content_draft_sources_refuse_demo_brand_writes
+ before insert or update or delete on public.content_draft_sources
+ for each row execute function public.refuse_demo_brand_writes('draft_id', 'content_drafts');
+
+create or replace trigger prompts_refuse_demo_brand_writes
+ before insert or update or delete on public.prompts
+ for each row execute function public.refuse_demo_brand_writes('prompt_set_id', 'prompt_sets');
+
+create or replace trigger prompt_notes_refuse_demo_brand_writes
+ before insert or update or delete on public.prompt_notes
+ for each row execute function public.refuse_demo_brand_writes('prompt_id', 'prompts', 'prompt_set_id', 'prompt_sets');
+
+create or replace trigger prompt_target_urls_refuse_demo_brand_writes
+ before insert or update or delete on public.prompt_target_urls
+ for each row execute function public.refuse_demo_brand_writes('prompt_id', 'prompts', 'prompt_set_id', 'prompt_sets');
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00400_chat_core.sql
-- ─────────────────────────────────────────────────────────────────────────