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(server): keep a workspace read-only once its plan has ended (#1589)

Cihan6e34ade66431
diff --git a/server/src/lib/action-center/execution/run.js b/server/src/lib/action-center/execution/run.js
index d5cd09cc8..b8dc03559 100644
--- a/server/src/lib/action-center/execution/run.js
+++ b/server/src/lib/action-center/execution/run.js
@@ -31,6 +31,8 @@
*/
import supabaseAdmin from '../../../config/supabase.js';
+import { isCloud } from '../../../config/plans.js';
+import { ACTIVE_SUBSCRIPTION_STATUSES } from '../../active-subscriptions.js';
import { logger } from '../../logger.js';
import { APPROVAL_PERMISSIONS, AUTOMATABLE_MODES, getTask } from '../tasks/registry.js';
import { resolveBrandSources } from '../sources.js';
@@ -267,9 +269,18 @@ export async function sweepTaskExecution({ now = new Date() } = {}) {
// Candidate tasks: not finished, on an action nobody has closed. The tool
// and dependency checks belong to `runTask`, which records what it refused.
- const { data: rows, error } = await supabaseAdmin
- .from('action_tasks')
- .select('id, task_key, action_id, actions!inner(status)')
+ // On the cloud, only for organizations still on a plan: a tool reads
+ // outside services on the organization's behalf. Filtered in the query, so
+ // the old tasks of an organization whose plan ended can't fill the read.
+ let query = supabaseAdmin.from('action_tasks');
+ query = isCloud()
+ ? query
+ .select(
+ 'id, task_key, action_id, actions!inner(status, brands!inner(organizations!inner(subscription_status)))',
+ )
+ .in('actions.brands.organizations.subscription_status', ACTIVE_SUBSCRIPTION_STATUSES)
+ : query.select('id, task_key, action_id, actions!inner(status)');
+ const { data: rows, error } = await query
.in('status', RUNNABLE_STATUSES)
.not('actions.status', 'in', '("completed","dismissed")')
.order('created_at', { ascending: true })
diff --git a/server/src/lib/action-center/execution/run.test.js b/server/src/lib/action-center/execution/run.test.js
index f96e7466d..d5d7bbed5 100644
--- a/server/src/lib/action-center/execution/run.test.js
+++ b/server/src/lib/action-center/execution/run.test.js
@@ -425,4 +425,110 @@ describe('sweepTaskExecution', () => {
expect(summary.succeeded + summary.failed).toBe(2);
});
+
+ /**
+ * The sweep reads the 1,000 oldest candidates. On the cloud the query
+ * itself keeps to organizations on a plan, so an organization's old tasks
+ * can't fill the read and push out the tasks of one that pays.
+ */
+ function mockPlanSweep(rows) {
+ const asked = { filters: [] };
+ from.mockImplementation((table) => {
+ const sweep = table === 'action_tasks' && asked.select === undefined;
+ const builder = {
+ select: (columns) => {
+ if (sweep) asked.select = columns;
+ return builder;
+ },
+ eq: () => builder,
+ in: (column, values) => {
+ if (sweep) asked.filters.push([column, values]);
+ return builder;
+ },
+ not: () => builder,
+ order: () => builder,
+ limit: (max) => {
+ if (sweep) asked.limit = max;
+ return builder;
+ },
+ single: () =>
+ Promise.resolve({
+ data:
+ table === 'actions'
+ ? { id: ACTION, brand_id: BRAND, payload: {} }
+ : { ...task({ id: 'paying' }), task_key: 'validate' },
+ error: null,
+ }),
+ insert: () => Promise.resolve({ error: null }),
+ update: () => builder,
+ then: (resolve, reject) => {
+ let data = [];
+ if (sweep) {
+ const plan = asked.filters.find(
+ ([column]) => column === 'actions.brands.organizations.subscription_status',
+ );
+ data = rows
+ .filter(
+ (row) =>
+ !plan || plan[1].includes(row.actions.brands.organizations.subscription_status),
+ )
+ .slice(0, asked.limit);
+ }
+ return Promise.resolve({ data, error: null }).then(resolve, reject);
+ },
+ };
+ return builder;
+ });
+ return asked;
+ }
+
+ const onPlan = (status) => ({
+ status: 'open',
+ brands: { organizations: { subscription_status: status } },
+ });
+ const lapsedThenPaying = () => [
+ ...Array.from({ length: 1000 }, (_, i) => ({
+ id: `lapsed-${i}`,
+ task_key: 'validate',
+ action_id: ACTION,
+ actions: onPlan('canceled'),
+ })),
+ { id: 'paying', task_key: 'validate', action_id: ACTION, actions: onPlan('active') },
+ ];
+
+ it("reads past an organization's 1,000 old tasks once its plan has ended (cloud)", async () => {
+ vi.stubEnv('IS_CLOUD', 'true');
+ try {
+ const asked = mockPlanSweep(lapsedThenPaying());
+
+ const summary = await sweepTaskExecution({ now: NOW });
+
+ expect(asked.select).toContain(
+ 'actions!inner(status, brands!inner(organizations!inner(subscription_status)))',
+ );
+ expect(asked.filters).toContainEqual([
+ 'actions.brands.organizations.subscription_status',
+ ['active', 'trialing'],
+ ]);
+ // The paying organization's task, and only it, is carried out.
+ expect(summary.succeeded + summary.failed + summary.blocked).toBe(1);
+ expect(summary.skippedForCeiling).toBe(0);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
+ it('filters nothing by plan self-hosted', async () => {
+ vi.stubEnv('IS_CLOUD', 'false');
+ try {
+ const asked = mockPlanSweep(lapsedThenPaying());
+ await sweepTaskExecution({ now: NOW });
+ expect(asked.select).toBe('id, task_key, action_id, actions!inner(status)');
+ expect(asked.filters.map(([column]) => column)).not.toContain(
+ 'actions.brands.organizations.subscription_status',
+ );
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
});
diff --git a/server/src/lib/active-subscriptions.js b/server/src/lib/active-subscriptions.js
new file mode 100644
index 000000000..1c754778e
--- /dev/null
+++ b/server/src/lib/active-subscriptions.js
@@ -0,0 +1,89 @@
+/**
+ * Which organizations the paid nightly work may still run for (2026-10-27).
+ *
+ * On the cloud, an organization whose free trial ended or whose plan was
+ * cancelled is read-only: its people can look around, and the nightly
+ * database-only upkeep (rollups, counters, retention) still runs for it, but
+ * nothing that costs: no tracking, no AI, no agent, no scraping, no sync
+ * with an outside service. Those sweeps, and the job recovery, keep to the
+ * ids these let through, as webflow-status.js and brand-facts-sweep.js
+ * already did.
+ *
+ * Self-hosted, everything is let through (billing doesn't apply), and
+ * nothing is read.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { isCloud, isSubscriptionActive } from '../config/plans.js';
+import { selectInChunks } from './chunked-in.js';
+
+/**
+ * The subscription statuses isSubscriptionActive takes as active, for a
+ * filter in a query (`.in(...)`); kept equal to it by a test.
+ */
+export const ACTIVE_SUBSCRIPTION_STATUSES = ['active', 'trialing'];
+
+const everyone = () => true;
+
+function uniqueIds(ids) {
+ return [...new Set((ids ?? []).filter(Boolean))];
+}
+
+/**
+ * A test for the ids among `orgIds`: whether the organization has an active
+ * or trialing subscription. Throws when the organizations can't be read: a
+ * sweep that can't tell runs for nobody.
+ *
+ * @param {string[]} orgIds
+ * @returns {Promise<(orgId: string) => boolean>}
+ */
+export async function activeOrgFilter(orgIds) {
+ if (!isCloud()) return everyone;
+ const ids = uniqueIds(orgIds);
+ if (ids.length === 0) return () => false;
+ const { data, error } = await selectInChunks(ids, (chunk) =>
+ supabaseAdmin.from('organizations').select('id, subscription_status').in('id', chunk),
+ );
+ if (error) throw new Error(`organizations read: ${error.message}`);
+ const active = new Set(
+ (data ?? [])
+ .filter((org) => isSubscriptionActive(org.subscription_status))
+ .map((org) => org.id),
+ );
+ return (orgId) => active.has(orgId);
+}
+
+/**
+ * A test for the ids among `brandIds`: whether the brand's organization has
+ * an active or trialing subscription. Throws when the brands can't be read.
+ *
+ * @param {string[]} brandIds
+ * @returns {Promise<(brandId: string) => boolean>}
+ */
+export async function activeBrandFilter(brandIds) {
+ if (!isCloud()) return everyone;
+ const ids = uniqueIds(brandIds);
+ if (ids.length === 0) return () => false;
+ const { data, error } = await selectInChunks(ids, (chunk) =>
+ supabaseAdmin.from('brands').select('id, organizations(subscription_status)').in('id', chunk),
+ );
+ if (error) throw new Error(`brands read: ${error.message}`);
+ const active = new Set(
+ (data ?? [])
+ .filter((brand) => isSubscriptionActive(brand.organizations?.subscription_status))
+ .map((brand) => brand.id),
+ );
+ return (brandId) => active.has(brandId);
+}
+
+/**
+ * Whether one organization has an active or trialing subscription (always,
+ * self-hosted): for a route that reads what is kept instead of starting a
+ * read that costs.
+ *
+ * @param {string} orgId
+ * @returns {Promise<boolean>}
+ */
+export async function isOrgActive(orgId) {
+ return (await activeOrgFilter([orgId]))(orgId);
+}
diff --git a/server/src/lib/active-subscriptions.test.js b/server/src/lib/active-subscriptions.test.js
new file mode 100644
index 000000000..c6a062692
--- /dev/null
+++ b/server/src/lib/active-subscriptions.test.js
@@ -0,0 +1,171 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Which organizations the nightly work may still run for (2026-10-27): on
+ * the cloud, those with an active or trialing subscription; self-hosted,
+ * every one, without a read.
+ */
+
+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.in = [column, ids];
+ return chain;
+ },
+ then: (resolve, reject) =>
+ Promise.resolve(
+ failWith
+ ? { data: null, error: { message: failWith } }
+ : {
+ data: (rows[table] ?? []).filter((row) => ids(read).includes(row.id)),
+ error: null,
+ },
+ ).then(resolve, reject),
+ };
+ return chain;
+ },
+ },
+}));
+
+const ids = (read) => read.in?.[1] ?? [];
+
+const { ACTIVE_SUBSCRIPTION_STATUSES, activeBrandFilter, activeOrgFilter, isOrgActive } =
+ await import('./active-subscriptions.js');
+const { isSubscriptionActive } = await import('../config/plans.js');
+
+beforeEach(() => {
+ reads.length = 0;
+ failWith = null;
+ rows = {
+ organizations: [
+ { id: 'trialing', subscription_status: 'trialing' },
+ { id: 'active', subscription_status: 'active' },
+ { id: 'canceled', subscription_status: 'canceled' },
+ { id: 'past-due', subscription_status: 'past_due' },
+ { id: 'incomplete', subscription_status: 'incomplete' },
+ ],
+ brands: [
+ { id: 'b-active', organizations: { subscription_status: 'active' } },
+ { id: 'b-trialing', organizations: { subscription_status: 'trialing' } },
+ { id: 'b-canceled', organizations: { subscription_status: 'canceled' } },
+ { id: 'b-orphan', organizations: null },
+ ],
+ };
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('self-hosted', () => {
+ beforeEach(() => vi.stubEnv('IS_CLOUD', 'false'));
+
+ it('lets every organization and brand through without reading anything', async () => {
+ const isOrgActive = await activeOrgFilter(['canceled', 'anything']);
+ const isBrandActive = await activeBrandFilter(['b-canceled']);
+
+ expect(isOrgActive('canceled')).toBe(true);
+ expect(isOrgActive(undefined)).toBe(true);
+ expect(isBrandActive('b-canceled')).toBe(true);
+ expect(reads).toHaveLength(0);
+ });
+});
+
+describe('cloud', () => {
+ beforeEach(() => vi.stubEnv('IS_CLOUD', 'true'));
+
+ it('lets through only the organizations with an active or trialing subscription', async () => {
+ const isActive = await activeOrgFilter([
+ 'trialing',
+ 'active',
+ 'canceled',
+ 'past-due',
+ 'incomplete',
+ 'missing',
+ 'active',
+ null,
+ ]);
+
+ expect(
+ ['trialing', 'active', 'canceled', 'past-due', 'incomplete', 'missing'].filter(isActive),
+ ).toEqual(['trialing', 'active']);
+ // One read, each id once.
+ expect(reads).toEqual([
+ {
+ table: 'organizations',
+ columns: 'id, subscription_status',
+ in: ['id', ['trialing', 'active', 'canceled', 'past-due', 'incomplete', 'missing']],
+ },
+ ]);
+ });
+
+ it('lets through only the brands whose organization has one', async () => {
+ const isActive = await activeBrandFilter(['b-active', 'b-trialing', 'b-canceled', 'b-orphan']);
+
+ expect(['b-active', 'b-trialing', 'b-canceled', 'b-orphan'].filter(isActive)).toEqual([
+ 'b-active',
+ 'b-trialing',
+ ]);
+ expect(reads[0]).toMatchObject({
+ table: 'brands',
+ columns: 'id, organizations(subscription_status)',
+ });
+ });
+
+ it('reads nothing and lets nothing through for no ids', async () => {
+ expect((await activeOrgFilter([]))('active')).toBe(false);
+ expect((await activeBrandFilter([null]))('b-active')).toBe(false);
+ expect(reads).toHaveLength(0);
+ });
+
+ it('throws when it cannot tell, so a sweep runs for nobody', async () => {
+ failWith = 'statement timeout';
+ await expect(activeOrgFilter(['active'])).rejects.toThrow(
+ 'organizations read: statement timeout',
+ );
+ await expect(activeBrandFilter(['b-active'])).rejects.toThrow('brands read: statement timeout');
+ });
+});
+
+describe('isOrgActive', () => {
+ it('tells one organization, on the cloud by its subscription, self-hosted always', async () => {
+ vi.stubEnv('IS_CLOUD', 'true');
+ expect(await isOrgActive('trialing')).toBe(true);
+ expect(await isOrgActive('canceled')).toBe(false);
+ vi.stubEnv('IS_CLOUD', 'false');
+ reads.length = 0;
+ expect(await isOrgActive('canceled')).toBe(true);
+ expect(reads).toHaveLength(0);
+ });
+});
+
+describe('ACTIVE_SUBSCRIPTION_STATUSES', () => {
+ it('is what isSubscriptionActive takes as active, for a filter in a query', () => {
+ vi.stubEnv('IS_CLOUD', 'true');
+ const statuses = [
+ 'active',
+ 'trialing',
+ 'past_due',
+ 'canceled',
+ 'unpaid',
+ 'incomplete',
+ 'incomplete_expired',
+ 'paused',
+ null,
+ ];
+ expect(statuses.filter((status) => isSubscriptionActive(status))).toEqual(
+ ACTIVE_SUBSCRIPTION_STATUSES,
+ );
+ });
+});
diff --git a/server/src/lib/brand-facts.js b/server/src/lib/brand-facts.js
index f58423aec..6abfa67d9 100644
--- a/server/src/lib/brand-facts.js
+++ b/server/src/lib/brand-facts.js
@@ -922,11 +922,20 @@ export function refreshOnce(brandId, options) {
* kept: { facts, pages, checkedAt, recheckAt, paused, noDomain }. A page
* that didn't answer last time is read again behind the answer (after
* RECHECK_MS): the ask doesn't wait on the site. Each pending fact with what
- * it would replace: the approved fact in its slot ("Was $49").
+ * it would replace: the approved fact in its slot ("Was $49"). `keptOnly`
+ * (an organization whose plan has ended) never reads the site: as kept, if
+ * anything is.
*/
export async function readBrandFacts(
brandId,
- { orgId, refresh = false, now = Date.now(), db = supabaseAdmin, fetcher = fetchPage } = {},
+ {
+ orgId,
+ refresh = false,
+ keptOnly = false,
+ now = Date.now(),
+ db = supabaseAdmin,
+ fetcher = fetchPage,
+ } = {},
) {
const { data: kept, error } = await db
.from('brand_fact_pages')
@@ -936,7 +945,9 @@ export async function readBrandFacts(
const last = Math.max(0, ...(kept ?? []).map((p) => Date.parse(p.checked_at)));
const due = now - last >= RECHECK_MS;
let result = { noDomain: false, paused: false };
- if (!kept?.length || (refresh && due)) {
+ if (keptOnly) {
+ // As kept: the site isn't read.
+ } else if (!kept?.length || (refresh && due)) {
result = await refreshOnce(brandId, { orgId, now, db, fetcher });
} else if (due && kept.some((p) => p.status === 'failed')) {
refreshOnce(brandId, { orgId, now, db, fetcher }).catch((err) =>
diff --git a/server/src/lib/brand-facts.test.js b/server/src/lib/brand-facts.test.js
index 026be4fef..4ff3a678c 100644
--- a/server/src/lib/brand-facts.test.js
+++ b/server/src/lib/brand-facts.test.js
@@ -923,6 +923,44 @@ describe('readBrandFacts', () => {
expect(fetcher).not.toHaveBeenCalled();
});
+ it('never reads the site once the plan has ended: as kept, if anything is', async () => {
+ const fetcher = vi.fn();
+ const empty = fakeDb(tables({ brand_fact_pages: [], brand_facts: [], brand_domains: [] }));
+ const none = await readBrandFacts('b1', {
+ orgId: 'o1',
+ now: NOW,
+ db: empty.db,
+ fetcher,
+ keptOnly: true,
+ });
+ expect(none).toMatchObject({ facts: [], pages: [], checkedAt: null, noDomain: false });
+ expect(empty.reads).not.toContain('brand_domains');
+
+ const stale = fakeDb(
+ tables({
+ brand_fact_pages: [
+ {
+ kind: 'pricing',
+ url: null,
+ status: 'failed',
+ checked_at: new Date(NOW - 60 * 60_000).toISOString(),
+ },
+ ],
+ }),
+ );
+ const kept = await readBrandFacts('b1', {
+ orgId: 'o1',
+ now: NOW,
+ db: stale.db,
+ fetcher,
+ refresh: true,
+ keptOnly: true,
+ });
+ expect(kept.facts.map((f) => f.id)).toEqual(['a', 'b']);
+ expect(stale.reads).not.toContain('brand_domains');
+ expect(fetcher).not.toHaveBeenCalled();
+ });
+
it('reads the site on the first ask, two asks at once once', async () => {
const { db, reads } = fakeDb(tables({ brand_fact_pages: [], brand_domains: [] }));
const [one, two] = await Promise.all([
diff --git a/server/src/lib/ga-sync.js b/server/src/lib/ga-sync.js
index a45052de8..4adf247e0 100644
--- a/server/src/lib/ga-sync.js
+++ b/server/src/lib/ga-sync.js
@@ -18,6 +18,7 @@
*/
import supabaseAdmin from '../config/supabase.js';
+import { activeOrgFilter } from './active-subscriptions.js';
import { isComposioConfigured, runGaReport } from './composio.js';
import { AI_SOURCES_VERSION, classifyAiSurface } from './ai-sources.js';
import {
@@ -576,7 +577,10 @@ export async function runGaSync({ organizationId, brandId, aiHistory = false } =
if (organizationId) connQuery = connQuery.eq('organization_id', organizationId);
const { data: connections, error: connError } = await connQuery;
if (connError) throw new Error(connError.message);
- const connectedOrgIds = [...new Set((connections || []).map((c) => c.organization_id))];
+ // …on an active subscription: once the plan has ended, nothing is synced.
+ const orgIds = [...new Set((connections || []).map((c) => c.organization_id))];
+ const isActive = await activeOrgFilter(orgIds);
+ const connectedOrgIds = orgIds.filter(isActive);
if (connectedOrgIds.length === 0) return { synced: 0, skipped: 0, results: [] };
// …and their active brands with a mapped property.
diff --git a/server/src/lib/ga-sync.test.js b/server/src/lib/ga-sync.test.js
index 2c0aecce1..a865451a7 100644
--- a/server/src/lib/ga-sync.test.js
+++ b/server/src/lib/ga-sync.test.js
@@ -2,13 +2,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
// The module imports the supabase admin client, whose config hard-exits when
// SUPABASE_* env is absent (as in CI) — stub it before the import chain. The
-// stub records deletes and their filters.
+// stub records deletes and their filters, and answers reads from `tables`.
const deletes = [];
+const calls = [];
let deleteError = null;
+let tables = {};
vi.mock('../config/supabase.js', () => ({
default: {
from: (table) => {
const call = { table, filters: [] };
+ calls.push(call);
const filter = (op) => (col, val) => {
call.filters.push([op, col, val]);
return chain;
@@ -18,16 +21,23 @@ vi.mock('../config/supabase.js', () => ({
deletes.push(call);
return chain;
},
+ select: () => chain,
eq: filter('eq'),
is: filter('is'),
gte: filter('gte'),
lte: filter('lte'),
- then: (resolve) => resolve({ error: deleteError }),
+ lt: filter('lt'),
+ in: filter('in'),
+ not: filter('not'),
+ then: (resolve) => resolve({ data: tables[table] ?? [], error: deleteError }),
};
return chain;
},
},
}));
+vi.mock('./composio.js', () => ({ isComposioConfigured: () => true, runGaReport: vi.fn() }));
+const activeOrgFilter = vi.hoisted(() => vi.fn());
+vi.mock('./active-subscriptions.js', () => ({ activeOrgFilter }));
import { AI_SOURCES_VERSION } from './ai-sources.js';
import { GA_AI_SOURCE_PATTERN, classifyGaSource, gaAiPlatform } from './ga-sources.js';
@@ -42,6 +52,7 @@ import {
mapItemRows,
mapPageRows,
readReportRows,
+ runGaSync,
unclassifiedSources,
} from './ga-sync.js';
@@ -587,3 +598,38 @@ describe('unclassifiedSources', () => {
]);
});
});
+
+/**
+ * Once an organization's plan has ended (2026-10-27), the nightly sync
+ * leaves it out: nothing is read from Analytics for it.
+ */
+describe('runGaSync', () => {
+ beforeEach(() => {
+ calls.length = 0;
+ deleteError = null;
+ tables = {
+ integration_connections: [
+ { organization_id: 'paying' },
+ { organization_id: 'lapsed' },
+ { organization_id: 'paying' },
+ ],
+ brands: [],
+ };
+ activeOrgFilter.mockReset().mockResolvedValue((orgId) => orgId === 'paying');
+ });
+
+ it('syncs only the organizations still on a plan', async () => {
+ await runGaSync();
+
+ expect(activeOrgFilter).toHaveBeenCalledWith(['paying', 'lapsed']);
+ const brands = calls.find((call) => call.table === 'brands');
+ expect(brands.filters).toContainEqual(['in', 'organization_id', ['paying']]);
+ });
+
+ it('reads no brand when no connected organization is on a plan', async () => {
+ activeOrgFilter.mockResolvedValue(() => false);
+
+ expect(await runGaSync()).toEqual({ synced: 0, skipped: 0, results: [] });
+ expect(calls.some((call) => call.table === 'brands')).toBe(false);
+ });
+});
diff --git a/server/src/lib/gsc-sync.js b/server/src/lib/gsc-sync.js
index c7f008506..ba71f9458 100644
--- a/server/src/lib/gsc-sync.js
+++ b/server/src/lib/gsc-sync.js
@@ -14,6 +14,7 @@
*/
import supabaseAdmin from '../config/supabase.js';
+import { activeOrgFilter } from './active-subscriptions.js';
import { isComposioConfigured, queryGscSearchAnalytics } from './composio.js';
import { logger } from './logger.js';
@@ -222,7 +223,10 @@ export async function runGscSync({ organizationId, brandId } = {}) {
if (organizationId) connQuery = connQuery.eq('organization_id', organizationId);
const { data: connections, error: connError } = await connQuery;
if (connError) throw new Error(connError.message);
- const connectedOrgIds = [...new Set((connections || []).map((c) => c.organization_id))];
+ // …on an active subscription: once the plan has ended, nothing is synced.
+ const orgIds = [...new Set((connections || []).map((c) => c.organization_id))];
+ const isActive = await activeOrgFilter(orgIds);
+ const connectedOrgIds = orgIds.filter(isActive);
if (connectedOrgIds.length === 0) return { synced: 0, skipped: 0, results: [] };
// …and their active brands with a mapped property.
diff --git a/server/src/lib/gsc-sync.test.js b/server/src/lib/gsc-sync.test.js
index 3359a5796..8d8dac7be 100644
--- a/server/src/lib/gsc-sync.test.js
+++ b/server/src/lib/gsc-sync.test.js
@@ -1,8 +1,42 @@
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
// gsc-sync imports the supabase admin client, whose config module hard-exits
// when SUPABASE_* env is absent (as in CI) — stub it before the import chain.
-vi.mock('../config/supabase.js', () => ({ default: {} }));
+// The stub answers from `tables` and records each read's filters.
+const calls = [];
+let tables = {};
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const call = { table, filters: [] };
+ calls.push(call);
+ const filter =
+ (op) =>
+ (...args) => {
+ call.filters.push([op, ...args]);
+ return chain;
+ };
+ const chain = {
+ select: filter('select'),
+ eq: filter('eq'),
+ not: filter('not'),
+ in: filter('in'),
+ lt: filter('lt'),
+ delete: filter('delete'),
+ then: (resolve, reject) =>
+ Promise.resolve({ data: tables[table] ?? [], error: null }).then(resolve, reject),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('./composio.js', () => ({
+ isComposioConfigured: () => true,
+ queryGscSearchAnalytics: vi.fn(),
+}));
+const activeOrgFilter = vi.hoisted(() => vi.fn());
+vi.mock('./active-subscriptions.js', () => ({ activeOrgFilter }));
+vi.mock('./logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
import {
mapAnalyticsRows,
@@ -11,6 +45,7 @@ import {
PAGE_WINDOW_DAYS,
pageWindows,
pagesSyncPlan,
+ runGscSync,
} from './gsc-sync.js';
describe('mapAnalyticsRows', () => {
@@ -212,3 +247,37 @@ describe('pagesSyncPlan', () => {
});
});
});
+
+/**
+ * Once an organization's plan has ended (2026-10-27), the nightly sync
+ * leaves it out: nothing is read from Search Console for it.
+ */
+describe('runGscSync', () => {
+ beforeEach(() => {
+ calls.length = 0;
+ tables = {
+ integration_connections: [
+ { organization_id: 'paying' },
+ { organization_id: 'lapsed' },
+ { organization_id: 'paying' },
+ ],
+ brands: [],
+ };
+ activeOrgFilter.mockReset().mockResolvedValue((orgId) => orgId === 'paying');
+ });
+
+ it('syncs only the organizations still on a plan', async () => {
+ await runGscSync();
+
+ expect(activeOrgFilter).toHaveBeenCalledWith(['paying', 'lapsed']);
+ const brands = calls.find((call) => call.table === 'brands');
+ expect(brands.filters).toContainEqual(['in', 'organization_id', ['paying']]);
+ });
+
+ it('reads no brand when no connected organization is on a plan', async () => {
+ activeOrgFilter.mockResolvedValue(() => false);
+
+ expect(await runGscSync()).toEqual({ synced: 0, skipped: 0, results: [] });
+ expect(calls.some((call) => call.table === 'brands')).toBe(false);
+ });
+});
diff --git a/server/src/lib/job-manager.js b/server/src/lib/job-manager.js
index 88e921426..9e13c4919 100644
--- a/server/src/lib/job-manager.js
+++ b/server/src/lib/job-manager.js
@@ -119,7 +119,7 @@ export async function listWaitingJobs({ idleMs, maxAgeMs }) {
const now = Date.now();
const { data, error } = await supabaseAdmin
.from('jobs')
- .select('id, type')
+ .select('id, type, brand_id')
.eq('status', 'waiting')
.lt('updated_at', new Date(now - idleMs).toISOString())
.gt('created_at', new Date(now - maxAgeMs).toISOString())
@@ -164,6 +164,30 @@ export async function cancelJob(jobId) {
if (controller) controller.abort();
}
+/**
+ * Cancel a job that is still waiting, saying why (`reason`, kept in
+ * failed_reason): one already started, finished or cancelled is left as it
+ * is. Returns whether it was cancelled.
+ */
+export async function cancelWaitingJob(jobId, reason) {
+ const { data, error } = await supabaseAdmin
+ .from('jobs')
+ .update({
+ status: 'cancelled',
+ failed_reason: reason,
+ updated_at: new Date().toISOString(),
+ })
+ .eq('id', jobId)
+ .eq('status', 'waiting')
+ .select('id');
+
+ if (error) {
+ logger.error({ err: error, jobId }, 'failed to cancel waiting job');
+ return false;
+ }
+ return (data ?? []).length > 0;
+}
+
/** Register an active job's AbortController. */
export function registerActiveJob(jobId, abortController) {
activeJobs.set(jobId, abortController);
diff --git a/server/src/lib/job-manager.test.js b/server/src/lib/job-manager.test.js
new file mode 100644
index 000000000..2fa5c6000
--- /dev/null
+++ b/server/src/lib/job-manager.test.js
@@ -0,0 +1,67 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Cancelling a waiting job (2026-10-27): only while it still waits, with
+ * why it was cancelled kept on the row.
+ */
+
+const updates = [];
+let answer;
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const update = { table, filters: [] };
+ const chain = {
+ update: (patch) => {
+ update.patch = patch;
+ updates.push(update);
+ return chain;
+ },
+ eq: (column, value) => {
+ update.filters.push([column, value]);
+ return chain;
+ },
+ select: () => chain,
+ then: (resolve, reject) => Promise.resolve(answer).then(resolve, reject),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('./logger.js', () => ({ default: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+
+const { cancelWaitingJob } = await import('./job-manager.js');
+
+beforeEach(() => {
+ updates.length = 0;
+ answer = { data: [{ id: 'j1' }], error: null };
+});
+
+describe('cancelWaitingJob', () => {
+ it('cancels a job only while it still waits, and keeps why', async () => {
+ expect(await cancelWaitingJob('j1', 'subscription_inactive')).toBe(true);
+ expect(updates).toEqual([
+ {
+ table: 'jobs',
+ patch: expect.objectContaining({
+ status: 'cancelled',
+ failed_reason: 'subscription_inactive',
+ }),
+ filters: [
+ ['id', 'j1'],
+ ['status', 'waiting'],
+ ],
+ },
+ ]);
+ });
+
+ it('says so when the job had already started or ended', async () => {
+ answer = { data: [], error: null };
+ expect(await cancelWaitingJob('j1', 'subscription_inactive')).toBe(false);
+ });
+
+ it('says it did not cancel when the write fails', async () => {
+ answer = { data: null, error: { message: 'timeout' } };
+ expect(await cancelWaitingJob('j1', 'subscription_inactive')).toBe(false);
+ });
+});
diff --git a/server/src/lib/job-runner.js b/server/src/lib/job-runner.js
index 223c26838..59d5a55c1 100644
--- a/server/src/lib/job-runner.js
+++ b/server/src/lib/job-runner.js
@@ -6,6 +6,7 @@
import {
getJob,
+ cancelWaitingJob,
claimWaitingJob,
listWaitingJobs,
completeJob,
@@ -14,6 +15,7 @@ import {
registerActiveJob,
unregisterActiveJob,
} from './job-manager.js';
+import { activeBrandFilter } from './active-subscriptions.js';
import { processTrackingJob } from '../workers/tracking-worker.js';
import { processContentJob } from '../workers/content-worker.js';
import { generatePulseForBrand } from './pulse/engine.js';
@@ -42,6 +44,7 @@ const queuedJobs = new Set();
// either started or is about to.
const RECOVERY_IDLE_MS = 2 * 60_000;
const RECOVERY_MAX_AGE_MS = 20 * 60 * 60_000;
+const RECOVERABLE_TYPES = new Set(['tracking', 'content']);
/**
* Create a mock job object that mirrors the Bull job interface
@@ -284,22 +287,36 @@ 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.
*/
export async function recoverWaitingJobs(io) {
- const jobs = await listWaitingJobs({
- idleMs: RECOVERY_IDLE_MS,
- maxAgeMs: RECOVERY_MAX_AGE_MS,
- });
+ const jobs = (
+ await listWaitingJobs({
+ idleMs: RECOVERY_IDLE_MS,
+ maxAgeMs: RECOVERY_MAX_AGE_MS,
+ })
+ ).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));
let recovered = 0;
+ let cancelled = 0;
for (const job of jobs) {
- if (queuedJobs.has(job.id)) continue;
+ if (!isActive(job.brand_id)) {
+ if (await cancelWaitingJob(job.id, 'subscription_inactive')) cancelled++;
+ continue;
+ }
if (job.type === 'tracking') runTrackingJob(job.id, io);
- else if (job.type === 'content') runContentJob(job.id, io);
- else continue;
+ else runContentJob(job.id, io);
recovered++;
}
+ if (cancelled > 0) {
+ logger.info({ cancelled }, 'cancelled waiting jobs of organizations without an active plan');
+ }
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 4037677f6..52524dfbf 100644
--- a/server/src/lib/job-runner.test.js
+++ b/server/src/lib/job-runner.test.js
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const manager = vi.hoisted(() => ({
+ cancelWaitingJob: vi.fn(),
claimWaitingJob: vi.fn(),
listWaitingJobs: vi.fn(),
getJob: vi.fn(),
@@ -12,8 +13,10 @@ const manager = vi.hoisted(() => ({
}));
const processTrackingJob = vi.hoisted(() => vi.fn());
const processContentJob = vi.hoisted(() => vi.fn());
+const activeBrandFilter = vi.hoisted(() => vi.fn());
vi.mock('./job-manager.js', () => manager);
+vi.mock('./active-subscriptions.js', () => ({ activeBrandFilter }));
vi.mock('../workers/tracking-worker.js', () => ({ processTrackingJob }));
vi.mock('../workers/content-worker.js', () => ({ processContentJob }));
vi.mock('./pulse/engine.js', () => ({ generatePulseForBrand: vi.fn() }));
@@ -54,6 +57,8 @@ beforeEach(() => {
for (const fn of Object.values(manager)) fn.mockReset();
processTrackingJob.mockReset();
processContentJob.mockReset();
+ // Every organization on a plan unless a test says otherwise.
+ activeBrandFilter.mockReset().mockResolvedValue(() => true);
// The claim resolves a tick later, as a network call would.
manager.claimWaitingJob.mockImplementation(async (id) => {
await Promise.resolve();
@@ -139,5 +144,41 @@ describe('recoverWaitingJobs', () => {
manager.listWaitingJobs.mockResolvedValue([]);
expect(await recoverWaitingJobs()).toBe(0);
expect(manager.claimWaitingJob).not.toHaveBeenCalled();
+ expect(activeBrandFilter).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');
+ manager.cancelWaitingJob.mockResolvedValue(true);
+ manager.listWaitingJobs.mockResolvedValue([
+ { id: 'kept', type: 'tracking', brand_id: 'paying' },
+ { id: 'lapsed-tracking', type: 'tracking', brand_id: 'lapsed' },
+ { id: 'lapsed-content', type: 'content', brand_id: 'lapsed' },
+ ]);
+
+ const recovered = await recoverWaitingJobs();
+ await flush();
+
+ expect(recovered).toBe(1);
+ expect(activeBrandFilter).toHaveBeenCalledWith(['paying', 'lapsed', 'lapsed']);
+ // Only while still waiting, saying why.
+ expect(manager.cancelWaitingJob.mock.calls).toEqual([
+ ['lapsed-tracking', 'subscription_inactive'],
+ ['lapsed-content', 'subscription_inactive'],
+ ]);
+ expect(manager.claimWaitingJob.mock.calls.map(([id]) => id)).toEqual(['kept']);
+ expect(processContentJob).not.toHaveBeenCalled();
+ await drain(releases);
+ });
+
+ it('runs nothing when it cannot tell which organizations are on a plan', async () => {
+ activeBrandFilter.mockRejectedValue(new Error('organizations read: timeout'));
+ manager.listWaitingJobs.mockResolvedValue([{ id: 'lost', type: 'tracking', brand_id: 'b' }]);
+
+ await expect(recoverWaitingJobs()).rejects.toThrow('organizations read');
+ expect(manager.claimWaitingJob).not.toHaveBeenCalled();
+ expect(manager.cancelWaitingJob).not.toHaveBeenCalled();
});
});
diff --git a/server/src/lib/page-opportunities.js b/server/src/lib/page-opportunities.js
index ed172e3a2..7cb5e81c1 100644
--- a/server/src/lib/page-opportunities.js
+++ b/server/src/lib/page-opportunities.js
@@ -27,6 +27,7 @@
*/
import supabaseAdmin from '../config/supabase.js';
+import { activeOrgFilter } from './active-subscriptions.js';
import { isExcludedPath } from './page-paths.js';
import { logger } from './logger.js';
import { resolve } from '../config/action-engine.js';
@@ -328,8 +329,9 @@ export async function detectPageOpportunitiesInWindow(
}
/**
- * Detect for every brand with synced GA data; optionally scoped to one
- * organization. Per-brand failures are logged and skipped.
+ * Detect for every brand with synced GA data, on an active subscription;
+ * optionally scoped to one organization. Per-brand failures are logged and
+ * skipped.
*/
export async function runPageOpportunityDetection({ organizationId } = {}) {
let brandQuery = supabaseAdmin
@@ -338,9 +340,12 @@ export async function runPageOpportunityDetection({ organizationId } = {}) {
.eq('is_active', true)
.not('ga_property_id', 'is', null);
if (organizationId) brandQuery = brandQuery.eq('organization_id', organizationId);
- const { data: brands, error } = await brandQuery;
+ const { data: rows, error } = await brandQuery;
if (error) throw new Error(error.message);
- if (!brands?.length) return { scanned: 0, results: [] };
+ // Once the plan has ended, nothing new is found for the organization.
+ const isActive = await activeOrgFilter((rows ?? []).map((b) => b.organization_id));
+ const brands = (rows ?? []).filter((b) => isActive(b.organization_id));
+ if (!brands.length) return { scanned: 0, results: [] };
const results = [];
for (const brand of brands) {
diff --git a/server/src/lib/page-opportunities.test.js b/server/src/lib/page-opportunities.test.js
index d226560d4..80f9e4735 100644
--- a/server/src/lib/page-opportunities.test.js
+++ b/server/src/lib/page-opportunities.test.js
@@ -4,6 +4,9 @@ import { describe, expect, it, vi } from 'vitest';
// SUPABASE_* env is absent (as in CI) — stub it before the import chain.
const db = vi.hoisted(() => ({ rpc: vi.fn(), from: vi.fn() }));
vi.mock('../config/supabase.js', () => ({ default: db }));
+const activeOrgFilter = vi.hoisted(() => vi.fn(async () => () => true));
+vi.mock('./active-subscriptions.js', () => ({ activeOrgFilter }));
+vi.mock('./logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
import {
classifyCitationState,
@@ -11,6 +14,7 @@ import {
detectPageOpportunitiesInWindow,
mapVisibilityRows,
pickValueSignal,
+ runPageOpportunityDetection,
scorePages,
} from './page-opportunities.js';
@@ -443,3 +447,55 @@ describe('detectPageOpportunitiesInWindow', () => {
await expect(detectPageOpportunitiesInWindow('b1')).rejects.toThrow('timeout');
});
});
+
+/**
+ * Once an organization's plan has ended (2026-10-27), the nightly detection
+ * leaves its brands out: nothing new is found for it.
+ */
+describe('runPageOpportunityDetection', () => {
+ const brandsRead = (rows) => {
+ const tables = [];
+ db.rpc.mockReset();
+ db.from.mockReset().mockImplementation((table) => {
+ tables.push(table);
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ not: () => chain,
+ then: (resolve) => resolve({ data: table === 'brands' ? rows : [], error: null }),
+ };
+ return chain;
+ });
+ return tables;
+ };
+
+ it('finds nothing for a brand whose organization is off a plan', async () => {
+ const tables = brandsRead([
+ { id: 'b-lapsed', organization_id: 'lapsed' },
+ { id: 'b-lapsed-2', organization_id: 'lapsed' },
+ ]);
+ activeOrgFilter.mockResolvedValueOnce((orgId) => orgId === 'paying');
+
+ expect(await runPageOpportunityDetection()).toEqual({ scanned: 0, results: [] });
+ expect(activeOrgFilter).toHaveBeenLastCalledWith(['lapsed', 'lapsed']);
+ // Only the brand list was read: no page of theirs.
+ expect(tables).toEqual(['brands']);
+ expect(db.rpc).not.toHaveBeenCalled();
+ });
+
+ it('keeps to the brands on a plan', async () => {
+ brandsRead([
+ { id: 'b-paying', organization_id: 'paying' },
+ { id: 'b-lapsed', organization_id: 'lapsed' },
+ ]);
+ activeOrgFilter.mockResolvedValueOnce((orgId) => orgId === 'paying');
+ db.rpc.mockReset().mockReturnValue({
+ order: () => ({ range: async () => ({ data: null, error: { message: 'stop here' } }) }),
+ });
+
+ const result = await runPageOpportunityDetection();
+
+ expect(result.scanned).toBe(1);
+ expect(result.results.map((r) => r.brandId)).toEqual(['b-paying']);
+ });
+});
diff --git a/server/src/lib/signals/pass.js b/server/src/lib/signals/pass.js
index cc89b4df8..11ce9c68a 100644
--- a/server/src/lib/signals/pass.js
+++ b/server/src/lib/signals/pass.js
@@ -19,6 +19,7 @@
*/
import supabaseAdmin from '../../config/supabase.js';
+import { activeBrandFilter } from '../active-subscriptions.js';
import { logger } from '../logger.js';
import { recordSignalsForBrand } from './record.js';
import { generateActionsForBrand } from '../action-center/generate.js';
@@ -171,12 +172,20 @@ export async function runSignalCatchUp({ now = new Date() } = {}) {
.gte('tracking_run_at', since);
if (passErr) throw new Error(passErr.message);
const done = new Set((passes ?? []).map((row) => `${row.brand_id}|${row.tracking_run_at}`));
+ // Once the plan has ended, no pass is caught up: its actions, and the
+ // tasks written for them, are work the organization no longer pays for.
+ const isActive = await activeBrandFilter([...latestByBrand.keys()]);
let recovered = 0;
let healthy = 0;
let failed = 0;
+ let inactive = 0;
for (const [brandId, completedAt] of latestByBrand) {
+ if (!isActive(brandId)) {
+ inactive += 1;
+ continue;
+ }
if (done.has(`${brandId}|${completedAt}`)) {
healthy += 1;
continue;
@@ -193,9 +202,9 @@ export async function runSignalCatchUp({ now = new Date() } = {}) {
}
if (recovered > 0 || failed > 0) {
- logger.info({ recovered, healthy, failed }, '[signals] catch-up sweep completed');
+ logger.info({ recovered, healthy, failed, inactive }, '[signals] catch-up sweep completed');
}
- return { recovered, healthy, failed };
+ return { recovered, healthy, failed, inactive };
} catch (err) {
logger.error({ err }, '[signals] catch-up sweep failed');
return { error: true };
diff --git a/server/src/lib/signals/pass.test.js b/server/src/lib/signals/pass.test.js
index 308a8ccb8..e68f2d004 100644
--- a/server/src/lib/signals/pass.test.js
+++ b/server/src/lib/signals/pass.test.js
@@ -16,6 +16,10 @@ const rescoreBrandActions = vi.fn();
vi.mock('../action-center/priority-data.js', () => ({
rescoreBrandActions: (...a) => rescoreBrandActions(...a),
}));
+const activeBrandFilter = vi.fn();
+vi.mock('../active-subscriptions.js', () => ({
+ activeBrandFilter: (...a) => activeBrandFilter(...a),
+}));
import { runFirstSignalPass, runSignalCatchUp, runSignalPass } from './pass.js';
@@ -63,6 +67,8 @@ beforeEach(() => {
rescoreBrandActions.mockResolvedValue(3);
recordSignalsForBrand.mockResolvedValue({ inserted: 2, refreshed: 1 });
generateActionsForBrand.mockResolvedValue({ created: 1, refreshed: 0 });
+ // Every brand's organization on a plan unless a test says otherwise.
+ activeBrandFilter.mockReset().mockResolvedValue(() => true);
});
describe('runSignalPass', () => {
@@ -214,6 +220,24 @@ describe('runSignalCatchUp', () => {
expect(summary.recovered).toBe(1);
});
+ it("catches up no pass for a brand whose organization's plan has ended", async () => {
+ const writes = mockDb({
+ runs: [
+ { brand_id: 'paying', completed_at: RUN_AT },
+ { brand_id: 'lapsed', completed_at: RUN_AT },
+ ],
+ });
+ activeBrandFilter.mockResolvedValue((brandId) => brandId === 'paying');
+
+ const summary = await runSignalCatchUp({ now: NOW });
+
+ expect(activeBrandFilter).toHaveBeenCalledWith(['paying', 'lapsed']);
+ expect(summary).toMatchObject({ recovered: 1, healthy: 0, failed: 0, inactive: 1 });
+ expect(recordSignalsForBrand).toHaveBeenCalledTimes(1);
+ expect(recordSignalsForBrand.mock.calls[0][0]).toBe('paying');
+ expect(writes.map((w) => w.row.brand_id)).toEqual(['paying']);
+ });
+
it('reports rather than throws when the sweep itself fails', async () => {
from.mockImplementation(() => {
throw new Error('connection refused');
diff --git a/server/src/lib/site-trust.js b/server/src/lib/site-trust.js
index 0fdc80b1f..da58c76a7 100644
--- a/server/src/lib/site-trust.js
+++ b/server/src/lib/site-trust.js
@@ -390,12 +390,16 @@ const reading = new Map();
* (site_trust.scraped_at), whoever asks and however often: a read within the
* day keeps what that one showed.
*
- * @returns {Promise<{ checks: object, score: number, complete: boolean, checkedAt: string }>}
+ * `keptOnly` (an organization whose plan has ended) answers the kept read
+ * however old, and null when none is kept: the site is never read for it.
+ *
+ * @returns {Promise<{ checks: object, score: number, complete: boolean, checkedAt: string } | null>}
*/
export async function readSiteTrust(
brandId,
{
refresh = false,
+ keptOnly = false,
db = supabaseAdmin,
fetcher = fetchPage,
scraper = process.env.SCRAPEDO_API_KEY ? scrapeHome : null,
@@ -408,17 +412,17 @@ export async function readSiteTrust(
.eq('brand_id', brandId)
.maybeSingle();
if (error) throw new Error(error.message);
+ const keptRead = kept && {
+ checks: kept.checks,
+ score: kept.score,
+ complete: kept.complete !== false,
+ checkedAt: kept.checked_at,
+ };
+ if (keptOnly) return keptRead || null;
if (kept) {
const age = now - Date.parse(kept.checked_at);
const holds = refresh || kept.complete === false ? RECHECK_MS : SITE_TRUST_TTL_MS;
- if (age < holds) {
- return {
- checks: kept.checks,
- score: kept.score,
- complete: kept.complete !== false,
- checkedAt: kept.checked_at,
- };
- }
+ if (age < holds) return keptRead;
}
let pending = reading.get(brandId);
if (!pending) {
diff --git a/server/src/lib/site-trust.test.js b/server/src/lib/site-trust.test.js
index cb8ea0361..f67d29267 100644
--- a/server/src/lib/site-trust.test.js
+++ b/server/src/lib/site-trust.test.js
@@ -400,6 +400,34 @@ describe('readSiteTrust', () => {
});
});
+ it('answers only the kept read, however old, once the plan has ended', async () => {
+ const fetcher = vi.fn();
+ const scraper = vi.fn();
+ let { db, writes } = fakeDb({ ...base, site_trust: kept(SITE_TRUST_TTL_MS * 30, false) });
+ const read = await readSiteTrust('b1', {
+ db,
+ fetcher,
+ scraper,
+ now: NOW,
+ refresh: true,
+ keptOnly: true,
+ });
+ expect(read).toEqual({
+ checks: { about: { ok: true, url: 'https://acme.com/about' } },
+ score: 1,
+ complete: false,
+ checkedAt: new Date(NOW - SITE_TRUST_TTL_MS * 30).toISOString(),
+ });
+
+ ({ db, writes } = fakeDb({ ...base, site_trust: null }));
+ expect(await readSiteTrust('b1', { db, fetcher, scraper, now: NOW, keptOnly: true })).toBe(
+ null,
+ );
+ expect(fetcher).not.toHaveBeenCalled();
+ expect(scraper).not.toHaveBeenCalled();
+ expect(writes).toEqual([]);
+ });
+
it('reads a partial read again after a few minutes, and says it is partial', async () => {
let { db, writes } = fakeDb({ ...base, site_trust: kept(60_000, false) });
expect((await readSiteTrust('b1', { db, fetcher: vi.fn(), now: NOW })).complete).toBe(false);
diff --git a/server/src/middleware/subscription.js b/server/src/middleware/subscription.js
new file mode 100644
index 000000000..b02c9ec32
--- /dev/null
+++ b/server/src/middleware/subscription.js
@@ -0,0 +1,179 @@
+import supabaseAdmin from '../config/supabase.js';
+import { isCloud, isSubscriptionActive } from '../config/plans.js';
+import logger from '../lib/logger.js';
+
+/**
+ * Read-only once the plan has ended (2026-10-27).
+ *
+ * On the cloud, an organization whose free trial ended or whose plan was
+ * cancelled can still sign in and look around, but nothing it asks for may
+ * change anything or start a cost: tracking, scraping, AI, agents, audits,
+ * outside services, sends. So every signed-in request that writes — any
+ * method but GET, HEAD and OPTIONS — is refused with 402 until a plan is
+ * chosen, but for these, named route by route:
+ * - billing (/billing/…): choosing, or cancelling, a plan;
+ * - COST_STOPPING: stopping work under way, and taking back the access to
+ * an outside account (Google, a CMS, a bot log) the person gave us;
+ * - ONBOARDING_ROUTES, for an organization that never had a subscription:
+ * setup suggests the brand's topics, prompts and competitors before the
+ * plan step, and again when the person comes back from it.
+ * A person's own profile and signing out are the web app's, through
+ * Supabase; neither comes through this API. A request with no signed-in
+ * person is refused too: decodeToken answers it first.
+ *
+ * Self-hosted, nothing is refused: billing doesn't apply.
+ *
+ * An active organization is remembered per person for ACTIVE_CACHE_MS, so a
+ * busy session doesn't read it on every request; an inactive one never is,
+ * so a plan chosen this minute works on the very next request.
+ */
+
+const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
+
+/** Paths, under /api, that stay open whatever the plan. */
+const OPEN_PATHS = ['/billing'];
+
+/**
+ * Requests, under /api, that end a cost or an access, never start one: open
+ * whatever the plan. Named route by route, so a new route is never let
+ * through by its name alone.
+ */
+export const COST_STOPPING = [
+ // Cancels a tracking job (tracking.js): no more scraping or answers to analyze.
+ { method: 'DELETE', path: /^\/tracking\/job\/[^/]+\/?$/ },
+ // Stops the Content Agent's run on a draft (content-drafts.js, CE-027).
+ { method: 'POST', path: /^\/content-drafts\/[^/]+\/stop\/?$/ },
+ // Disconnects Search Console or Analytics (integrations.js).
+ { method: 'DELETE', path: /^\/integrations\/[^/]+\/?$/ },
+ // Disconnects a brand's Webflow site (cms.js).
+ { method: 'DELETE', path: /^\/cms\/brands\/[^/]+\/webflow\/?$/ },
+ // Removes an AI-bot log connection (bots.js): its secret stops working.
+ { method: 'DELETE', path: /^\/bots\/connections\/[^/]+\/[^/]+\/?$/ },
+];
+
+/**
+ * The writes onboarding asks of this API (web/src/lib/ai-brand-setup.ts):
+ * open to an organization that never had a subscription, so setup works
+ * before the plan step. The brand, topics, prompts and competitors
+ * themselves are saved by the web app, through Supabase.
+ */
+export const ONBOARDING_ROUTES = [
+ // The brand's topics (topics.js).
+ { method: 'POST', path: /^\/topics\/suggest\/?$/ },
+ // Prompts for the chosen topics (prompts.js).
+ { method: 'POST', path: /^\/prompts\/from-topics\/?$/ },
+ // The brand's competitors, and whether it sells online (competitors.js).
+ { method: 'POST', path: /^\/competitors\/suggest\/?$/ },
+];
+
+/** How long an active organization is taken as still active. */
+export const ACTIVE_CACHE_MS = 30_000;
+/** People remembered at most; the oldest goes first. */
+export const MAX_ENTRIES = 5000;
+
+/** The answer to a write once the plan has ended. */
+export const SUBSCRIPTION_INACTIVE = {
+ success: false,
+ error: 'plan_limit',
+ code: 'subscription_inactive',
+ message: 'Your plan has ended. Choose a plan to use Ansvisor again.',
+};
+
+/** Person id → until when their organization is taken as active. */
+const activeUntil = new Map();
+
+function matches(routes, { method, path }) {
+ return routes.some((route) => route.method === method && route.path.test(path));
+}
+
+function isOpen(req) {
+ return (
+ OPEN_PATHS.some((open) => req.path === open || req.path.startsWith(`${open}/`)) ||
+ matches(COST_STOPPING, req)
+ );
+}
+
+function isCachedActive(userId, now) {
+ const until = activeUntil.get(userId);
+ if (until === undefined) return false;
+ if (until <= now) {
+ activeUntil.delete(userId);
+ return false;
+ }
+ return true;
+}
+
+function rememberActive(userId, now) {
+ // Only a new person makes room: two requests of one person at once both
+ // remember them.
+ if (!activeUntil.has(userId) && activeUntil.size >= MAX_ENTRIES) {
+ activeUntil.delete(activeUntil.keys().next().value);
+ }
+ activeUntil.set(userId, now + ACTIVE_CACHE_MS);
+}
+
+/**
+ * Where a person's organization stands: 'active' (an active or trialing
+ * subscription), 'never_subscribed' (no subscription yet: setting up, or
+ * back from the plan step) or 'inactive' (its subscription ended, or no
+ * profile to tell by).
+ *
+ * Never having had a subscription is the organization's Stripe subscription
+ * id, which only the server writes, not the profile's onboarding flag, which
+ * the person can set back themselves.
+ *
+ * @param {string} userId
+ * @returns {Promise<'active' | 'never_subscribed' | 'inactive'>}
+ */
+export async function subscriptionAccess(userId) {
+ const { data: profile, error } = await supabaseAdmin
+ .from('profiles')
+ .select('organization_id')
+ .eq('id', userId)
+ .maybeSingle();
+ if (error) throw new Error(`profiles read: ${error.message}`);
+ if (!profile) return 'inactive';
+ // Onboarding creates the organization with the brand, before it asks for
+ // anything here: without one, nothing was ever subscribed.
+ if (!profile.organization_id) return 'never_subscribed';
+
+ const { data: org, error: orgError } = await supabaseAdmin
+ .from('organizations')
+ .select('subscription_status, stripe_subscription_id')
+ .eq('id', profile.organization_id)
+ .maybeSingle();
+ if (orgError) throw new Error(`organizations read: ${orgError.message}`);
+ if (!org) return 'inactive';
+ if (isSubscriptionActive(org.subscription_status)) return 'active';
+ return org.stripe_subscription_id ? 'inactive' : 'never_subscribed';
+}
+
+/**
+ * Express middleware: refuses a signed-in person's writes while their
+ * organization has no active subscription. Runs after decodeToken.
+ */
+export async function requireActiveSubscription(req, res, next) {
+ if (!isCloud() || READ_METHODS.has(req.method) || isOpen(req)) return next();
+ const userId = req.user?.id;
+ if (!userId) return res.status(401).json({ message: 'Unauthorized API Request' });
+
+ const now = Date.now();
+ if (isCachedActive(userId, now)) return next();
+ try {
+ const access = await subscriptionAccess(userId);
+ if (access === 'active') {
+ rememberActive(userId, now);
+ return next();
+ }
+ if (access === 'never_subscribed' && matches(ONBOARDING_ROUTES, req)) return next();
+ return res.status(402).json(SUBSCRIPTION_INACTIVE);
+ } catch (err) {
+ (req.log ?? logger).error({ err }, 'subscription check failed');
+ return res.status(500).json({ message: 'Internal Error' });
+ }
+}
+
+// Test hook — what passes depends on what is remembered.
+export function clearSubscriptionCache() {
+ activeUntil.clear();
+}
diff --git a/server/src/middleware/subscription.test.js b/server/src/middleware/subscription.test.js
new file mode 100644
index 000000000..f1a0ebafd
--- /dev/null
+++ b/server/src/middleware/subscription.test.js
@@ -0,0 +1,414 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { readFile } from 'node:fs/promises';
+import express from 'express';
+
+/**
+ * Read-only once the plan has ended (2026-10-27): on the cloud, a signed-in
+ * person's writes are refused while their organization has no active or
+ * trialing subscription, but for billing, the routes that stop a cost or
+ * take back an access, and onboarding's routes for an organization that
+ * never subscribed.
+ */
+
+const reads = [];
+let profile;
+let org;
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ reads.push(table);
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ maybeSingle: async () => ({ data: table === 'profiles' ? profile : org, error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('../lib/logger.js', () => ({
+ default: { error: vi.fn(), warn: vi.fn(), info: vi.fn() },
+}));
+
+const {
+ ACTIVE_CACHE_MS,
+ COST_STOPPING,
+ MAX_ENTRIES,
+ ONBOARDING_ROUTES,
+ SUBSCRIPTION_INACTIVE,
+ clearSubscriptionCache,
+ requireActiveSubscription,
+ subscriptionAccess,
+} = await import('./subscription.js');
+
+function makeRes() {
+ const res = { status: vi.fn(), json: vi.fn() };
+ res.status.mockReturnValue(res);
+ return res;
+}
+
+async function run({ method = 'POST', path = '/prompts/suggest', user = { id: 'u1' } } = {}) {
+ const res = makeRes();
+ const next = vi.fn();
+ await requireActiveSubscription({ method, path, user }, res, next);
+ return { res, next };
+}
+
+const ended = { subscription_status: 'canceled', stripe_subscription_id: 'sub_1' };
+const neverSubscribed = { subscription_status: 'incomplete', stripe_subscription_id: null };
+
+const ONBOARDING = [
+ ['POST', '/topics/suggest'],
+ ['POST', '/prompts/from-topics'],
+ ['POST', '/competitors/suggest'],
+];
+
+beforeEach(() => {
+ vi.stubEnv('IS_CLOUD', 'true');
+ reads.length = 0;
+ clearSubscriptionCache();
+ profile = { organization_id: 'org-1' };
+ org = { subscription_status: 'active', stripe_subscription_id: 'sub_1' };
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllEnvs();
+});
+
+describe('requireActiveSubscription', () => {
+ it('lets an active or trialing organization write', async () => {
+ for (const status of ['active', 'trialing']) {
+ clearSubscriptionCache();
+ org = { subscription_status: status, stripe_subscription_id: 'sub_1' };
+ const { res, next } = await run();
+ expect(next).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ }
+ });
+
+ it('refuses a write with 402 once the trial ended or the plan was cancelled', async () => {
+ for (const status of ['canceled', 'past_due', 'unpaid', 'incomplete_expired']) {
+ org = { subscription_status: status, stripe_subscription_id: 'sub_1' };
+ for (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) {
+ const { res, next } = await run({ method });
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(402);
+ expect(res.json).toHaveBeenCalledWith(SUBSCRIPTION_INACTIVE);
+ }
+ }
+ expect(SUBSCRIPTION_INACTIVE).toEqual({
+ success: false,
+ error: 'plan_limit',
+ code: 'subscription_inactive',
+ message: 'Your plan has ended. Choose a plan to use Ansvisor again.',
+ });
+ });
+
+ it('lets reads through without reading the organization', async () => {
+ org = ended;
+ for (const method of ['GET', 'HEAD', 'OPTIONS']) {
+ const { res, next } = await run({ method });
+ expect(next).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ }
+ expect(reads).toHaveLength(0);
+ });
+
+ it('leaves billing open, so a plan can be chosen or cancelled', async () => {
+ org = ended;
+ for (const path of ['/billing', '/billing/cancel-feedback']) {
+ const { next } = await run({ path });
+ expect(next).toHaveBeenCalledOnce();
+ }
+ // A path that only starts with the word is not billing.
+ const { res } = await run({ path: '/billingx' });
+ expect(res.status).toHaveBeenCalledWith(402);
+ });
+
+ it('lets an organization off a plan stop work and take back access, and nothing else', async () => {
+ org = ended;
+ const open = [
+ ['DELETE', '/tracking/job/9b2c1e40-0000-4000-8000-000000000001'],
+ ['POST', '/content-drafts/9b2c1e40-0000-4000-8000-000000000002/stop'],
+ ['DELETE', '/integrations/google-search-console'],
+ ['DELETE', '/integrations/google-analytics'],
+ ['DELETE', '/cms/brands/b1/webflow'],
+ ['DELETE', '/bots/connections/b1/c1'],
+ ];
+ for (const [method, path] of open) {
+ const { res, next } = await run({ method, path });
+ expect(next, `${method} ${path}`).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ }
+ // The same paths with another method, their neighbours, and lookalikes stay closed.
+ for (const [method, path] of [
+ ['POST', '/tracking/job/j1'],
+ ['POST', '/tracking/check'],
+ ['DELETE', '/tracking/job/j1/extra'],
+ ['DELETE', '/content-drafts/d1/stop'],
+ ['POST', '/content-drafts/d1/write'],
+ ['POST', '/content-drafts/d1/stop/now'],
+ ['POST', '/content-drafts/stop'],
+ ['POST', '/content/d1/stop'],
+ ['POST', '/action-center/tasks/t1/cancel'],
+ ['POST', '/integrations/google-search-console/connect'],
+ ['POST', '/integrations/google-search-console/sync'],
+ ['PUT', '/cms/brands/b1/webflow'],
+ ['POST', '/cms/brands/b1/webflow'],
+ ['POST', '/bots/connections/b1'],
+ ['DELETE', '/bots/connections/b1'],
+ // A brand is deleted only on a plan (product decision, 2026-10-27).
+ ['DELETE', '/brands/b1'],
+ ]) {
+ const { res, next } = await run({ method, path });
+ expect(next, `${method} ${path}`).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(402);
+ }
+ // Both Google disconnects are one route.
+ expect(COST_STOPPING).toHaveLength(5);
+ });
+
+ it("opens onboarding's routes, and only them, to an organization that never subscribed", async () => {
+ // Setting up, before the plan step; and back from it (onboarding marked
+ // done, still no subscription): the flag is not read.
+ org = neverSubscribed;
+ for (const [method, path] of ONBOARDING) {
+ const { res, next } = await run({ method, path });
+ expect(next, `${method} ${path}`).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ }
+ for (const [method, path] of [
+ ['POST', '/prompts/suggest'],
+ ['POST', '/tracking/check'],
+ ['POST', '/volumes/bootstrap'],
+ ['POST', '/brand-facts/fetch'],
+ ['PUT', '/topics/suggest'],
+ ['POST', '/topics/suggest/extra'],
+ ]) {
+ const { res, next } = await run({ method, path });
+ expect(next, `${method} ${path}`).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(402);
+ }
+ expect(ONBOARDING_ROUTES).toHaveLength(ONBOARDING.length);
+
+ // Before the organization exists, too.
+ profile = { organization_id: null };
+ expect((await run({ path: '/topics/suggest' })).next).toHaveBeenCalledOnce();
+ });
+
+ it("keeps onboarding's routes closed once the organization has had a subscription", async () => {
+ org = ended;
+ for (const [method, path] of ONBOARDING) {
+ const { res, next } = await run({ method, path });
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(402);
+ }
+ });
+
+ it('refuses a person with no profile, or whose organization is gone', async () => {
+ profile = null;
+ expect((await run({ path: '/topics/suggest' })).res.status).toHaveBeenCalledWith(402);
+ profile = { organization_id: 'org-1' };
+ org = null;
+ expect((await run({ path: '/topics/suggest' })).res.status).toHaveBeenCalledWith(402);
+ });
+
+ it('refuses a write with no signed-in person', async () => {
+ const { res, next } = await run({ user: null });
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(401);
+ expect(reads).toHaveLength(0);
+ });
+
+ it('refuses nothing self-hosted', async () => {
+ vi.stubEnv('IS_CLOUD', 'false');
+ org = ended;
+ const { res, next } = await run();
+ expect(next).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ expect(reads).toHaveLength(0);
+ });
+});
+
+describe('subscriptionAccess', () => {
+ it('tells active, never subscribed and ended apart, without the onboarding flag', async () => {
+ expect(await subscriptionAccess('u1')).toBe('active');
+ org = neverSubscribed;
+ expect(await subscriptionAccess('u1')).toBe('never_subscribed');
+ org = ended;
+ expect(await subscriptionAccess('u1')).toBe('inactive');
+ profile = null;
+ expect(await subscriptionAccess('u1')).toBe('inactive');
+ });
+});
+
+describe('the cache', () => {
+ it('remembers an active organization for a short while', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ await run();
+ await run();
+ expect(reads).toEqual(['profiles', 'organizations']);
+
+ // The plan ends: within the window, still the remembered answer…
+ org = ended;
+ vi.advanceTimersByTime(ACTIVE_CACHE_MS - 1);
+ expect((await run()).next).toHaveBeenCalledOnce();
+
+ // …after it, read again and refused.
+ vi.advanceTimersByTime(1);
+ const { res } = await run();
+ expect(res.status).toHaveBeenCalledWith(402);
+ expect(ACTIVE_CACHE_MS).toBeLessThanOrEqual(30_000);
+ });
+
+ it('never remembers a refusal, so a plan chosen now works on the next request', async () => {
+ org = ended;
+ expect((await run()).res.status).toHaveBeenCalledWith(402);
+
+ org = { subscription_status: 'trialing', stripe_subscription_id: 'sub_1' };
+ const { res, next } = await run();
+ expect(next).toHaveBeenCalledOnce();
+ expect(res.status).not.toHaveBeenCalled();
+ });
+
+ it('is kept per person', async () => {
+ await run({ user: { id: 'u1' } });
+ org = ended;
+ expect((await run({ user: { id: 'u2' } })).res.status).toHaveBeenCalledWith(402);
+ expect((await run({ user: { id: 'u1' } })).next).toHaveBeenCalledOnce();
+ });
+
+ it('makes room only for a new person, not when one already remembered is again', async () => {
+ for (let i = 0; i < MAX_ENTRIES; i++) await run({ user: { id: `u${i}` } });
+ // Two requests of a new person at once: both read, both remember them.
+ await Promise.all([run({ user: { id: 'new' } }), run({ user: { id: 'new' } })]);
+
+ reads.length = 0;
+ // The oldest made room for the new person once…
+ await run({ user: { id: 'u0' } });
+ expect(reads).toEqual(['profiles', 'organizations']);
+ // …and the second remembering took nobody else's place.
+ reads.length = 0;
+ await run({ user: { id: 'u2' } });
+ await run({ user: { id: 'new' } });
+ expect(reads).toEqual([]);
+ });
+});
+
+describe('when the check cannot be read', () => {
+ it('answers 500 and never lets the write through', async () => {
+ const supabase = (await import('../config/supabase.js')).default;
+ const from = supabase.from;
+ supabase.from = () => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ maybeSingle: async () => ({ data: null, error: { message: 'timeout' } }),
+ };
+ return chain;
+ };
+ try {
+ await expect(subscriptionAccess('u1')).rejects.toThrow('profiles read: timeout');
+
+ const res = makeRes();
+ const next = vi.fn();
+ const log = { error: vi.fn() };
+ await requireActiveSubscription(
+ { method: 'POST', path: '/prompts/suggest', user: { id: 'u1' }, log },
+ res,
+ next,
+ );
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(500);
+ expect(log.error).toHaveBeenCalledOnce();
+ } finally {
+ supabase.from = from;
+ }
+ });
+});
+
+/**
+ * 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.
+ */
+describe("server.js's mount", () => {
+ it('puts every API route behind the person and then the plan', async () => {
+ const source = await readFile(new URL('../server.js', import.meta.url), 'utf8');
+ const mounts = source
+ .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);",
+ ]);
+ expect(source).toMatch(
+ /import \{ requireActiveSubscription \} from '\.\/middleware\/subscription\.js';/,
+ );
+ expect(source).toMatch(/app\.use\('\/webhooks\/content-drafts', /);
+ });
+});
+
+/**
+ * Mounted as server.js mounts it: after the person is known, on /api only.
+ * The content-draft webhook, mounted outside /api, never meets it.
+ */
+describe('mounted like the server', () => {
+ let server;
+ let baseUrl;
+
+ beforeEach(async () => {
+ org = ended;
+ const app = express();
+ app.use(express.json());
+ app.use('/webhooks/content-drafts', (req, res) => res.json({ ok: true }));
+ const auth = (req, _res, next) => {
+ req.user = { id: 'u1' };
+ next();
+ };
+ const routes = express.Router();
+ routes.get('/prompts', (req, res) => res.json({ prompts: [] }));
+ routes.post('/prompts/suggest', (req, res) => res.json({ suggested: true }));
+ routes.post('/billing/cancel-feedback', (req, res) => res.json({ kept: true }));
+ routes.delete('/tracking/job/:jobId', (req, res) => res.json({ cancelled: true }));
+ routes.post('/content-drafts/:draftId/stop', (req, res) => res.json({ stopped: true }));
+ routes.post('/content-drafts/:draftId/write', (req, res) => res.json({ writing: true }));
+ app.use('/api', auth, requireActiveSubscription, routes);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}`;
+ });
+
+ afterEach(() => new Promise((resolve) => server.close(resolve)));
+
+ const post = (path) =>
+ fetch(`${baseUrl}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: '{}',
+ });
+
+ it('refuses the write, and only the write', async () => {
+ const refused = await post('/api/prompts/suggest');
+ expect(refused.status).toBe(402);
+ expect(await refused.json()).toEqual(SUBSCRIPTION_INACTIVE);
+
+ expect((await fetch(`${baseUrl}/api/prompts`)).status).toBe(200);
+ expect((await post('/api/billing/cancel-feedback')).status).toBe(200);
+ });
+
+ it('lets work under way be stopped, but not started', async () => {
+ const cancel = await fetch(`${baseUrl}/api/tracking/job/j1`, { method: 'DELETE' });
+ expect(cancel.status).toBe(200);
+ expect((await post('/api/content-drafts/d1/stop')).status).toBe(200);
+ expect((await post('/api/content-drafts/d1/write')).status).toBe(402);
+ });
+
+ it('leaves the webhook alone', async () => {
+ const res = await post('/webhooks/content-drafts/d1/status');
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true });
+ });
+});
diff --git a/server/src/routes/action-center-tasks.test.js b/server/src/routes/action-center-tasks.test.js
index ad500b05a..5da00a59f 100644
--- a/server/src/routes/action-center-tasks.test.js
+++ b/server/src/routes/action-center-tasks.test.js
@@ -33,7 +33,12 @@ class TaskWriterError extends Error {
this.status = status;
}
}
-class PlanLimitError extends Error {}
+class PlanLimitError extends Error {
+ constructor(message, statusCode = 403) {
+ super(message);
+ this.statusCode = statusCode;
+ }
+}
vi.mock('../lib/plan-guard.js', () => ({ PlanLimitError }));
vi.mock('../lib/action-center/task-writer/index.js', () => ({
TaskWriterError,
@@ -98,12 +103,23 @@ describe('regenerateTasks', () => {
});
it('says the budget is spent, as a code the drawer words', async () => {
- writeTasksForAction.mockRejectedValueOnce(new PlanLimitError('Budget used up'));
+ writeTasksForAction.mockRejectedValueOnce(new PlanLimitError('Budget used up', 429));
await expect(regenerateTasks('a1', 'u1')).rejects.toMatchObject({
status: 429,
code: 'budget',
});
});
+
+ it('says there is no plan, not a spent budget, once the plan has ended', async () => {
+ writeTasksForAction.mockRejectedValueOnce(
+ new PlanLimitError('An active subscription or free trial is required.', 402),
+ );
+ await expect(regenerateTasks('a1', 'u1')).rejects.toMatchObject({
+ status: 402,
+ code: 'plan_limit',
+ message: 'An active subscription or free trial is required.',
+ });
+ });
});
describe('sendTask', () => {
diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.js
index 968b95c8f..8a25f9815 100644
--- a/server/src/routes/action-center.js
+++ b/server/src/routes/action-center.js
@@ -92,8 +92,13 @@ export async function regenerateTasks(actionId, userId) {
try {
result = await writeTasksForAction(actionId, { trigger: 'regenerate', userId });
} catch (err) {
- // The month's AI budget, shared with the Improve tab, is spent.
- if (err instanceof PlanLimitError) throw new TaskWriterError('budget', err.message, 429);
+ if (err instanceof PlanLimitError) {
+ // No plan (the trial ended, or it was cancelled): one to choose, not a
+ // budget to wait for.
+ if (err.statusCode === 402) throw new TaskWriterError('plan_limit', err.message, 402);
+ // The month's AI budget, shared with the Improve tab, is spent.
+ throw new TaskWriterError('budget', err.message, 429);
+ }
throw err;
}
if (result.status !== 'written') {
diff --git a/server/src/routes/audits-settings.test.js b/server/src/routes/audits-settings.test.js
index c98173eff..b3b4f6d21 100644
--- a/server/src/routes/audits-settings.test.js
+++ b/server/src/routes/audits-settings.test.js
@@ -11,6 +11,7 @@ let tables;
let writes;
let quota;
const readSiteTrust = vi.fn();
+const isOrgActive = vi.fn();
let server;
let baseUrl;
@@ -83,6 +84,7 @@ async function startApp() {
generateRecommendations: vi.fn(),
}));
vi.doMock('../lib/site-trust.js', () => ({ readSiteTrust }));
+ vi.doMock('../lib/active-subscriptions.js', () => ({ isOrgActive }));
vi.doMock('../lib/logger.js', () => {
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
return { default: logger, logger };
@@ -108,6 +110,7 @@ const otherBrand = '44444444-4444-4444-4444-444444444444';
beforeEach(async () => {
writes = [];
+ isOrgActive.mockReset().mockResolvedValue(true);
readSiteTrust.mockReset().mockResolvedValue({
checks: { about: { ok: true, url: 'https://acme.com/about' } },
score: 1,
@@ -300,9 +303,25 @@ describe('GET /api/audits/site-trust', () => {
complete: false,
checkedAt: '2026-10-23T12:00:00.000Z',
});
- expect(readSiteTrust).toHaveBeenLastCalledWith(brandId, { refresh: false });
+ expect(readSiteTrust).toHaveBeenLastCalledWith(brandId, { refresh: false, keptOnly: false });
res = await fetch(`${baseUrl}/site-trust?brandId=${brandId}&refresh=1`);
- expect(readSiteTrust).toHaveBeenLastCalledWith(brandId, { refresh: true });
+ expect(readSiteTrust).toHaveBeenLastCalledWith(brandId, { refresh: true, keptOnly: false });
+ expect(isOrgActive).toHaveBeenCalledWith('org-1');
+ });
+
+ it('answers only the kept read once the plan has ended, and 402 when none is kept', async () => {
+ isOrgActive.mockResolvedValue(false);
+ let res = await fetch(`${baseUrl}/site-trust?brandId=${brandId}&refresh=1`);
+ expect(res.status).toBe(200);
+ expect(readSiteTrust).toHaveBeenLastCalledWith(brandId, { refresh: true, keptOnly: true });
+
+ readSiteTrust.mockResolvedValueOnce(null);
+ res = await fetch(`${baseUrl}/site-trust?brandId=${brandId}`);
+ expect(res.status).toBe(402);
+ expect(await res.json()).toMatchObject({
+ error: 'plan_limit',
+ code: 'subscription_inactive',
+ });
});
it('wants a brand id', async () => {
diff --git a/server/src/routes/audits.js b/server/src/routes/audits.js
index dac169d3d..b5079b027 100644
--- a/server/src/routes/audits.js
+++ b/server/src/routes/audits.js
@@ -48,6 +48,8 @@ import {
import { AUTO_AUDIT } from '../lib/audit/auto-audit.js';
import { rankOpportunities } from '../lib/audit/priority.js';
import { readSiteTrust } from '../lib/site-trust.js';
+import { isOrgActive } from '../lib/active-subscriptions.js';
+import { SUBSCRIPTION_INACTIVE } from '../middleware/subscription.js';
import { buildTemplates, templateOf, templateOpportunities } from '../lib/audit/templates.js';
import { ENGINE_THRESHOLDS } from '../config/action-engine.js';
import { runSignals } from '../lib/audit/engine.js';
@@ -1166,15 +1168,21 @@ router.get('/auto-runs/latest', async (req, res) => {
// GET /api/audits/site-trust?brandId=…&refresh=1 — the brand's five site
// trust checks (Content Editor Quality, CE-043): the day's read, or a new
-// one when asked again (site-trust.js). Registered before /:id.
+// one when asked again (site-trust.js). Once the plan has ended, only the
+// kept read, however old: 402 when none is kept. Registered before /:id.
router.get('/site-trust', async (req, res) => {
const parsed = z.guid().safeParse(req.query.brandId);
if (!parsed.success) {
return res.status(400).json({ success: false, message: 'brandId is required' });
}
try {
- await assertBrandAccess(parsed.data, req.user?.id);
- const trust = await readSiteTrust(parsed.data, { refresh: req.query.refresh === '1' });
+ const { orgId } = await assertBrandAccess(parsed.data, req.user?.id);
+ const keptOnly = !(await isOrgActive(orgId));
+ const trust = await readSiteTrust(parsed.data, {
+ refresh: req.query.refresh === '1',
+ keptOnly,
+ });
+ if (!trust) return res.status(402).json(SUBSCRIPTION_INACTIVE);
return res.json({ success: true, ...trust });
} catch (err) {
return sendAuditError(req, res, err, 'site trust read failed');
diff --git a/server/src/routes/brand-facts.js b/server/src/routes/brand-facts.js
index 96a23264c..95dec0cb5 100644
--- a/server/src/routes/brand-facts.js
+++ b/server/src/routes/brand-facts.js
@@ -2,6 +2,7 @@ import { Router } from 'express';
import { z } from 'zod';
import supabaseAdmin from '../config/supabase.js';
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 { brandFactsLimiter } from '../middleware/rate-limiter.js';
@@ -30,14 +31,16 @@ 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.
+// 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.
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);
- return res.json(await readBrandFacts(parsed.data, { orgId }));
+ const keptOnly = !(await isOrgActive(orgId));
+ 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 d867e79d0..0945a026e 100644
--- a/server/src/routes/brand-facts.test.js
+++ b/server/src/routes/brand-facts.test.js
@@ -14,6 +14,7 @@ const logError = vi.fn();
const assertBrandAccess = vi.fn();
const readBrandFacts = vi.fn();
const setFactStatus = vi.fn();
+const isOrgActive = vi.fn();
vi.mock('../config/supabase.js', () => ({
default: {
@@ -35,6 +36,10 @@ vi.mock('../lib/brand-facts.js', () => ({
setFactStatus: (...args) => setFactStatus(...args),
}));
+vi.mock('../lib/active-subscriptions.js', () => ({
+ isOrgActive: (...args) => isOrgActive(...args),
+}));
+
const { default: router } = await import('./brand-facts.js');
let server;
@@ -46,6 +51,7 @@ beforeEach(async () => {
assertBrandAccess.mockReset().mockResolvedValue({ orgId: 'o1' });
readBrandFacts.mockReset().mockResolvedValue({ facts: [], pages: [], paused: false });
setFactStatus.mockReset().mockResolvedValue({ id: FACT, status: 'approved' });
+ isOrgActive.mockReset().mockResolvedValue(true);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
@@ -72,11 +78,19 @@ const send = (path, method, body) =>
});
describe('/api/brand-facts', () => {
+ it('reads only what is kept once the plan has ended', async () => {
+ isOrgActive.mockResolvedValue(false);
+ const res = await send(`?brandId=${BRAND}`, 'GET');
+ expect(res.status).toBe(200);
+ expect(isOrgActive).toHaveBeenCalledWith('o1');
+ 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);
expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');
- expect(readBrandFacts).toHaveBeenCalledWith(BRAND, { orgId: 'o1' });
+ expect(readBrandFacts).toHaveBeenCalledWith(BRAND, { orgId: 'o1', keptOnly: false });
await send('/fetch', 'POST', { brandId: BRAND });
expect(readBrandFacts).toHaveBeenLastCalledWith(BRAND, { orgId: 'o1', refresh: true });
});
diff --git a/server/src/routes/content-pages.js b/server/src/routes/content-pages.js
index 5128d84ce..fc25c02bb 100644
--- a/server/src/routes/content-pages.js
+++ b/server/src/routes/content-pages.js
@@ -145,13 +145,26 @@ const sourceClassesBody = z.object({
sites: z.array(z.string().trim().toLowerCase().min(1).max(300)).min(1).max(MAX_SOURCE_SITES),
});
+/**
+ * A PlanLimitError's answer, as the editor's other routes give it
+ * (content-drafts.js): 402 no_subscription when there is no plan, else 429
+ * ai_budget for a spent budget.
+ */
+function planLimit(res, err) {
+ if (err.statusCode === 402) {
+ return res.status(402).json({ error: err.message, code: 'no_subscription' });
+ }
+ return res.status(429).json({ error: err.message, code: 'ai_budget' });
+}
+
/**
* POST /api/content-pages/source-classes { draftId, sites } (Quality CE-046,
* part b): the kind of each site the editor's rules can't place, read once
* by the model and kept for every workspace. Only sites the draft links, as
* saved, are read: the route reads no other site. Off until Quality's phase
* 2 is live (CONTENT_QUALITY_PHASE). A spent AI budget answers 429
- * ai_budget: the editor leaves those sources out of Trust.
+ * ai_budget: the editor leaves those sources out of Trust (402
+ * no_subscription without a plan).
*/
router.post('/source-classes', qualityCheckLimiter, async (req, res) => {
if (qualityPhase() < 2) return res.status(404).json({ error: 'Not available', code: 'off' });
@@ -185,9 +198,7 @@ router.post('/source-classes', qualityCheckLimiter, async (req, res) => {
});
return res.json(result);
} catch (err) {
- if (err instanceof PlanLimitError) {
- return res.status(429).json({ error: err.message, code: 'ai_budget' });
- }
+ if (err instanceof PlanLimitError) return planLimit(res, err);
if (err?.status === 403 || err?.status === 404) {
return res.status(err.status).json({ error: err.message, code: 'forbidden' });
}
@@ -212,7 +223,7 @@ const claimsBody = z.object({
* a source for, read by the model a paragraph at a time and kept by the
* paragraph (content_quality_claims). Off until Quality's phase 2 is live.
* A spent AI budget answers 429 ai_budget: the editor leaves the claims it
- * hasn't read out of Trust.
+ * hasn't read out of Trust (402 no_subscription without a plan).
*/
router.post('/claims', claimsLimiter, async (req, res) => {
if (qualityPhase() < 2) return res.status(404).json({ error: 'Not available', code: 'off' });
@@ -235,9 +246,7 @@ router.post('/claims', claimsLimiter, async (req, res) => {
});
return res.json(result);
} catch (err) {
- if (err instanceof PlanLimitError) {
- return res.status(429).json({ error: err.message, code: 'ai_budget' });
- }
+ if (err instanceof PlanLimitError) return planLimit(res, err);
if (err?.status === 403 || err?.status === 404) {
return res.status(err.status).json({ error: err.message, code: 'forbidden' });
}
diff --git a/server/src/routes/content-pages.test.js b/server/src/routes/content-pages.test.js
index a14b59bc0..1efccc245 100644
--- a/server/src/routes/content-pages.test.js
+++ b/server/src/routes/content-pages.test.js
@@ -285,6 +285,13 @@ describe('POST /api/content-pages/source-classes (Quality CE-046)', () => {
expect((await res.json()).code).toBe('ai_budget');
});
+ it('says there is no plan, not a spent budget, once the plan has ended', async () => {
+ readSourceClasses.mockRejectedValueOnce(new PlanLimitError('No plan', 402));
+ const res = await ask({ draftId: DRAFT, sites: ['coffee-blog.example'] });
+ expect(res.status).toBe(402);
+ expect(await res.json()).toEqual({ error: 'No plan', code: 'no_subscription' });
+ });
+
it('refuses another workspace’s draft and a malformed ask', async () => {
org = 'o2';
expect((await ask({ draftId: DRAFT, sites: ['coffee-blog.example'] })).status).toBe(403);
@@ -345,6 +352,13 @@ describe('POST /api/content-pages/claims (Quality CE-045)', () => {
expect((await res.json()).code).toBe('ai_budget');
});
+ it('says there is no plan, not a spent budget, once the plan has ended', async () => {
+ readDraftClaims.mockRejectedValueOnce(new PlanLimitError('No plan', 402));
+ const res = await ask({ draftId: DRAFT });
+ expect(res.status).toBe(402);
+ expect(await res.json()).toEqual({ error: 'No plan', code: 'no_subscription' });
+ });
+
it('refuses another workspace’s draft and a malformed ask', async () => {
org = 'o2';
expect((await ask({ draftId: DRAFT })).status).toBe(403);
diff --git a/server/src/server.js b/server/src/server.js
index d124a4b86..b7c85b097 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -11,6 +11,7 @@ import logger from './lib/logger.js';
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 routes from './routes/index.js';
import trafficRoutes from './routes/traffic.js';
import botIngestRoutes from './routes/bot-ingest.js';
@@ -745,7 +746,10 @@ app.use('/webhooks/content', webhookContentCallbackRoutes);
app.use('/webhooks/content-drafts', webhookContentDraftCallbackRoutes);
// --- Authenticated API routes ---
-app.use('/api', Middleware.decodeToken.bind(Middleware), 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);
// Health check
app.get('/', (req, res) => {