Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(server): return a workspace's stored data on reads while its plan has ended, bound setup suggestions without a plan, and name billing's open writes (#1611)
Cihandcd1d953ddbe
diff --git a/server/src/lib/plan-guard-no-plan.test.js b/server/src/lib/plan-guard-no-plan.test.jsnew file mode 100644index 000000000..1ba99790c--- /dev/null+++ b/server/src/lib/plan-guard-no-plan.test.js@@ -0,0 +1,284 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Read-only once the plan has ended (2026-10-27): the reads that cost+ * nothing take `readOnly`, and an organization without an active plan then+ * reads as the plan it was on with every allowance 0 and `noPlan: true`, so+ * what it stored still comes back instead of a 402. Without `readOnly`, as+ * on every write, it is still refused. requireFeature does the same for a+ * route given `readOnly`, against the features of the plan it was on.+ */++let org;+let counts;+let settings;+let improveRows;+let reads;++function query(table) {+ const builder = {+ select: () => builder,+ eq: () => builder,+ gte: () => builder,+ or: () => builder,+ order: () => builder,+ limit: () => builder,+ single: () => builder,+ maybeSingle: () => builder,+ then: (resolve) => {+ reads.push(table);+ if (table === 'organizations') return resolve({ data: org, error: null });+ if (table === 'profiles') return resolve({ data: { organization_id: 'o1' }, error: null });+ if (table === 'site_audit_settings') return resolve({ data: settings, error: null });+ if (table === 'site_audit_auto_runs') return resolve({ data: [], error: null });+ if (table === 'prompt_improve_usage') return resolve({ data: improveRows, error: null });+ return resolve({ count: counts[table] ?? 0, data: null, error: null });+ },+ };+ return builder;+}++const ended = { plan: 'growth', subscription_status: 'canceled', plan_overrides: null };+const active = {+ plan: 'growth',+ subscription_status: 'active',+ plan_overrides: null,+ subscription_ends_at: '2026-11-20T09:00:00Z',+};++let guard;++beforeEach(async () => {+ vi.resetModules();+ process.env.IS_CLOUD = 'true';+ org = ended;+ counts = { volume_usage: 3, brief_usage: 4, opportunity_usage: 2, site_audit_usage: 7 };+ settings = { auto_audit: true, email_after_run: true };+ improveRows = [{ cost_usd: '0.4', feature: 'improve' }];+ reads = [];+ vi.doMock('../config/supabase.js', () => ({ default: { from: (t) => query(t) } }));+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-10-23T12:00:00Z'));+ guard = await import('./plan-guard.js');+});++afterEach(() => {+ vi.useRealTimers();+ delete process.env.IS_CLOUD;+ vi.doUnmock('../config/supabase.js');+});++describe('a read without an active plan', () => {+ it('reads the volume quota as nothing left, with what was used', async () => {+ expect(await guard.getVolumeQuotaStatus('u1', { readOnly: true })).toEqual({+ used: 3,+ limit: 0,+ remaining: 0,+ noPlan: true,+ });+ });++ it('reads the content counts as nothing left, under the plan it was on', async () => {+ const usage = await guard.getContentUsage('o1', { readOnly: true });+ expect(usage).toMatchObject({+ plan: 'growth',+ planName: 'Growth',+ noPlan: true,+ opportunities: { used: 2, limit: 0, remaining: 0, perRequest: 0, noPlan: true },+ briefs: { used: 4, limit: 0, remaining: 0, noPlan: true },+ });+ // Without a subscription, the calendar month.+ expect(usage.periodStart.slice(0, 10)).toBe('2026-10-01');+ expect(await guard.getBriefQuotaStatus('o1', { readOnly: true })).toEqual({+ used: 4,+ limit: 0,+ remaining: 0,+ noPlan: true,+ });+ });++ it('reads Site Audit as a limit of 0 with auto-audit off, keeping the settings', async () => {+ const quota = await guard.getSiteAuditQuotaStatus('o1', { readOnly: true });+ expect(quota).toMatchObject({ used: 7, limit: 0, remaining: 0, noPlan: true });+ // The org's own choice and e-mail stay; no run is due or kept back.+ expect(quota.auto).toMatchObject({+ enabled: false,+ setting: true,+ emailAfterRun: true,+ perRun: 0,+ reserved: 0,+ nextRun: null,+ due: null,+ });+ });++ it("reads Improve's budget as spent", async () => {+ expect(await guard.getImproveQuotaStatus('o1', 'm1', { readOnly: true })).toMatchObject({+ unlimited: false,+ budgetUsd: 0,+ remainingUsd: 0,+ generationsLeft: 0,+ percentLeft: 0,+ trial: false,+ noPlan: true,+ });+ });++ it('reads the AI-bot caps as 0', async () => {+ expect(await guard.getBotCaps('o1', { readOnly: true })).toEqual({+ cap: 0,+ rawCap: 0,+ noPlan: true,+ });+ });++ it('reads an unlimited plan that ended as 0, not unlimited', async () => {+ org = {+ plan: 'enterprise',+ subscription_status: 'canceled',+ plan_overrides: { maxSiteAudits: 900 },+ };+ expect(await guard.getBriefQuotaStatus('o1', { readOnly: true })).toMatchObject({+ limit: 0,+ remaining: 0,+ });+ expect(await guard.getSiteAuditQuotaStatus('o1', { readOnly: true })).toMatchObject({+ limit: 0,+ noPlan: true,+ });+ });++ it('reads a limit an override set as text as 0 too', async () => {+ org = {+ plan: 'enterprise',+ subscription_status: 'canceled',+ plan_overrides: { maxSiteAudits: '1000', maxBriefGenerations: '50' },+ };+ expect(await guard.getSiteAuditQuotaStatus('o1', { readOnly: true })).toMatchObject({+ limit: 0,+ remaining: 0,+ });+ expect(await guard.getBriefQuotaStatus('o1', { readOnly: true })).toMatchObject({+ limit: 0,+ remaining: 0,+ });+ });++ it('is refused without the organization’s row, readOnly or not', async () => {+ org = null;+ const refused = { name: 'PlanLimitError', statusCode: 402 };+ await expect(guard.getBriefQuotaStatus('o1', { readOnly: true })).rejects.toMatchObject(+ refused,+ );+ await expect(guard.getSiteAuditQuotaStatus('o1', { readOnly: true })).rejects.toMatchObject(+ refused,+ );+ await expect(guard.getBotCaps('o1', { readOnly: true })).rejects.toMatchObject(refused);+ });++ it('is still refused without readOnly, as every write is', async () => {+ const refused = { name: 'PlanLimitError', statusCode: 402 };+ await expect(guard.getVolumeQuotaStatus('u1')).rejects.toMatchObject(refused);+ await expect(guard.getContentUsage('o1')).rejects.toMatchObject(refused);+ await expect(guard.getSiteAuditQuotaStatus('o1')).rejects.toMatchObject(refused);+ await expect(guard.getImproveQuotaStatus('o1', 'm1')).rejects.toMatchObject(refused);+ await expect(guard.getBotEventCap('o1')).rejects.toMatchObject(refused);+ await expect(guard.enforceBriefQuota('o1')).rejects.toMatchObject(refused);+ });+});++describe('a read on an active plan', () => {+ it('reads the same with or without readOnly, and has no noPlan', async () => {+ org = active;+ settings = { auto_audit: null, email_after_run: false };+ const pairs = [+ [+ () => guard.getVolumeQuotaStatus('u1'),+ () => guard.getVolumeQuotaStatus('u1', { readOnly: true }),+ ],+ [() => guard.getContentUsage('o1'), () => guard.getContentUsage('o1', { readOnly: true })],+ [+ () => guard.getSiteAuditQuotaStatus('o1'),+ () => guard.getSiteAuditQuotaStatus('o1', { readOnly: true }),+ ],+ [+ () => guard.getImproveQuotaStatus('o1', 'm1'),+ () => guard.getImproveQuotaStatus('o1', 'm1', { readOnly: true }),+ ],+ ];+ for (const [plain, readOnly] of pairs) {+ const answer = await plain();+ expect(await readOnly()).toEqual(answer);+ expect(answer).not.toHaveProperty('noPlan');+ }+ expect(await guard.getBotCaps('o1', { readOnly: true })).toEqual({+ cap: 2_000_000,+ rawCap: 20_000_000,+ });+ expect((await guard.getContentUsage('o1')).briefs).toEqual({+ used: 4,+ limit: 50,+ remaining: 46,+ });+ });+});++describe('self-hosted', () => {+ it('reads unlimited without looking at the organization', async () => {+ process.env.IS_CLOUD = 'false';+ expect(await guard.getBriefQuotaStatus('o1', { readOnly: true })).toEqual({+ used: 0,+ limit: -1,+ remaining: -1,+ });+ expect(await guard.getBotCaps('o1', { readOnly: true })).toEqual({ cap: -1, rawCap: -1 });+ expect(reads).not.toContain('organizations');+ });+});++describe('requireFeature', () => {+ async function call(method, feature, options) {+ const res = { status: vi.fn(), json: vi.fn() };+ res.status.mockReturnValue(res);+ const next = vi.fn();+ await guard.requireFeature(feature, options)({ method, user: { id: 'u1' } }, res, next);+ return { res, next };+ }++ it("lets a readOnly route through on the plan it was on, so what's kept comes back", async () => {+ for (const feature of ['prompt_improve', 'prompt_volumes', 'content_optimization']) {+ const { res, next } = await call('GET', feature, { readOnly: true });+ expect(next, feature).toHaveBeenCalledOnce();+ expect(res.status).not.toHaveBeenCalled();+ }+ });++ it('refuses a route not given readOnly with 402, a GET too: never by its method', async () => {+ for (const method of ['GET', 'HEAD', 'POST', 'DELETE']) {+ const { res, next } = await call(method, 'prompt_improve');+ expect(next, method).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(402);+ }+ });++ it('still refuses a feature that plan never had', async () => {+ const { res, next } = await call('GET', 'white_label', { readOnly: true });+ expect(next).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(403);+ });++ it('refuses a readOnly route without the organization’s row', async () => {+ org = null;+ const { res, next } = await call('GET', 'prompt_improve', { readOnly: true });+ expect(next).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(402);+ });++ it('is unchanged on an active plan', async () => {+ org = active;+ expect((await call('GET', 'prompt_improve')).next).toHaveBeenCalledOnce();+ expect((await call('GET', 'prompt_improve', { readOnly: true })).next).toHaveBeenCalledOnce();+ expect((await call('POST', 'prompt_improve')).next).toHaveBeenCalledOnce();+ expect((await call('GET', 'white_label')).res.status).toHaveBeenCalledWith(403);+ });+});diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.jsindex fbb466b55..c41b4e202 100644--- a/server/src/lib/plan-guard.js+++ b/server/src/lib/plan-guard.js@@ -73,11 +73,34 @@ export function applyPlanOverrides(plan, org) {return plan;}+/**+ * An organization without an active plan, as a read that costs nothing sees+ * it (read-only once the plan has ended, 2026-10-27): the plan it was on (or,+ * never subscribed, the one it would start on) with every allowance 0, marked+ * `noPlan`. Its stored data still comes back, with nothing left to spend; its+ * features stay, naming what that data covers. Lists (features, the allowed+ * scrapers and models) are kept; every other value, a number or one an+ * override set as text, is 0.+ */+function noPlanOf(org) {+ const plan = applyPlanOverrides(getPlan(org.plan), org);+ const limits = Object.fromEntries(+ Object.entries(plan.limits).map(([key, value]) => [key, Array.isArray(value) ? value : 0]),+ );+ return { ...plan, noPlan: true, limits };+}++/** What an answer read from noPlanOf's plan adds: `noPlan: true`, and nothing on a plan. */+const noPlanMark = (plan) => (plan.noPlan ? { noPlan: true } : {});+/*** Resolve an organization's plan directly by org id.* Self-hosted → returns self_hosted plan (unlimited).+ *+ * Without an active subscription it throws PlanLimitError (402), unless+ * `readOnly`, for a read that costs nothing: then the plan is noPlanOf's.*/-async function resolveOrgPlanByOrgId(orgId) {+async function resolveOrgPlanByOrgId(orgId, { readOnly = false } = {}) {if (!isCloud()) return getPlan('self_hosted');const { data: org } = await supabaseAdmin@@ -91,6 +114,8 @@ async function resolveOrgPlanByOrgId(orgId) {// granted billed features (volume fetch, content generation, etc.) to// unsubscribed signups.if (!isSubscriptionActive(org?.subscription_status)) {+ // Without the organization's row there is nothing kept to read.+ if (readOnly && org) return noPlanOf(org);throw new PlanLimitError('An active subscription or free trial is required. Please choose a plan to continue.',402,@@ -132,8 +157,9 @@ export async function getOrgIdForUser(userId) {/*** Resolve the user's organization plan from the database.* Self-hosted → returns self_hosted plan (unlimited).+ * `readOnly` as resolveOrgPlanByOrgId.*/-async function resolveOrgPlan(userId) {+async function resolveOrgPlan(userId, options) {if (!isCloud()) return getPlan('self_hosted');const orgId = await getOrgIdForUser(userId);@@ -141,15 +167,16 @@ async function resolveOrgPlan(userId) {throw new PlanLimitError('No organization found for user.', 400);}- return resolveOrgPlanByOrgId(orgId);+ return resolveOrgPlanByOrgId(orgId, options);}/*** Enforce that the user's plan includes a specific feature.- * Throws PlanLimitError if not.+ * Throws PlanLimitError if not. `readOnly` as resolveOrgPlanByOrgId: without+ * an active plan, the features of the plan it was on.*/-export async function enforceFeature(userId, feature) {- const plan = await resolveOrgPlan(userId);+export async function enforceFeature(userId, feature, options) {+ const plan = await resolveOrgPlan(userId, options);if (!hasFeature(plan, feature)) {throw new PlanLimitError(`Your ${plan.name} plan does not include "${feature}". Please upgrade.`,@@ -219,10 +246,11 @@ export async function enforceVolumeQuota(userId) {/*** Get current volume quota status without enforcing.- * Returns { used, limit, remaining }.+ * Returns { used, limit, remaining }. `readOnly`: without an active plan,+ * limit and remaining 0 and `noPlan: true`, rather than a 402.*/-export async function getVolumeQuotaStatus(userId) {- const plan = await resolveOrgPlan(userId);+export async function getVolumeQuotaStatus(userId, { readOnly = false } = {}) {+ const plan = await resolveOrgPlan(userId, { readOnly });const maxAnalyses = plan.limits.maxVolumeAnalyses;if (maxAnalyses === -1) return { used: 0, limit: -1, remaining: -1 };@@ -243,6 +271,7 @@ export async function getVolumeQuotaStatus(userId) {.gte('used_at', periodStart.toISOString());const used = count || 0;+ if (plan.noPlan) return { used, limit: 0, remaining: 0, noPlan: true };return { used, limit: maxAnalyses, remaining: maxAnalyses - used };}@@ -314,15 +343,16 @@ export async function enforceBriefQuota(orgId) {/*** Get current brief quota status without enforcing.- * Returns { used, limit, remaining }.+ * Returns { used, limit, remaining }. `readOnly` as resolveOrgPlanByOrgId:+ * without an active plan, limit 0 and `noPlan: true`.*/-export async function getBriefQuotaStatus(orgId) {- const plan = await resolveOrgPlanByOrgId(orgId);+export async function getBriefQuotaStatus(orgId, { readOnly = false } = {}) {+ const plan = await resolveOrgPlanByOrgId(orgId, { readOnly });const max = plan.limits.maxBriefGenerations;if (max === -1) return { used: 0, limit: -1, remaining: -1 };const used = await countBriefUsageThisMonth(orgId);- return { used, limit: max, remaining: Math.max(0, max - used) };+ return { used, limit: max, remaining: Math.max(0, max - used), ...noPlanMark(plan) };}/** How many of the org's latest calls its typical cost is the median of. */@@ -349,10 +379,12 @@ async function improveSpendThisPeriod(orgId) {* (plan.limits.improveMonthlyBudgetUsd: Starter $5, Growth $25, Enterprise* $50 or a customer's own set by Ansvisor, the free trial $1), charged with each* generation's real token cost so the budget holds for any model. Users see- * an estimate of generations left, not dollars. -1 is unlimited.+ * an estimate of generations left, not dollars. -1 is unlimited. `readOnly`+ * as resolveOrgPlanByOrgId: without an active plan, a budget of 0 and+ * `noPlan: true`.*/-export async function getImproveQuotaStatus(orgId, modelId) {- const plan = await resolveOrgPlanByOrgId(orgId);+export async function getImproveQuotaStatus(orgId, modelId, { readOnly = false } = {}) {+ const plan = await resolveOrgPlanByOrgId(orgId, { readOnly });const budget = plan.limits.improveMonthlyBudgetUsd ?? -1;if (budget === -1) return { unlimited: true, planName: plan.name };const { spent, typical } = await improveSpendThisPeriod(orgId);@@ -366,6 +398,7 @@ export async function getImproveQuotaStatus(orgId, modelId) {remainingUsd: remaining,generationsLeft: estimateGenerationsLeft(remaining, typical ?? typicalCostUsd(modelId)),percentLeft: budget > 0 ? Math.round((remaining / budget) * 100) : 0,+ ...noPlanMark(plan),};}@@ -656,15 +689,16 @@ async function countOpportunityUsage(orgId, since) {/*** Get the monthly content opportunity quota without enforcing (CONTENT-001).- * Returns { used, limit, remaining }; limit -1 is unlimited.+ * Returns { used, limit, remaining }; limit -1 is unlimited. `readOnly` as+ * resolveOrgPlanByOrgId: without an active plan, limit 0 and `noPlan: true`.*/-export async function getOpportunityQuotaStatus(orgId) {- const plan = await resolveOrgPlanByOrgId(orgId);+export async function getOpportunityQuotaStatus(orgId, { readOnly = false } = {}) {+ const plan = await resolveOrgPlanByOrgId(orgId, { readOnly });const max = plan.limits.maxOpportunitiesPerMonth ?? -1;if (max === -1) return { used: 0, limit: -1, remaining: -1 };const used = await countOpportunityUsage(orgId, await quotaPeriodStart(orgId));- return { used, limit: max, remaining: Math.max(0, max - used) };+ return { used, limit: max, remaining: Math.max(0, max - used), ...noPlanMark(plan) };}/**@@ -731,18 +765,21 @@ export async function releaseOpportunitySlots(ids) {/*** Both monthly content counters with the period they belong to, for the* Content page and GET /content/usage (CONTENT-001). Opportunities and briefs- * are separate pools that renew together with the subscription.+ * are separate pools that renew together with the subscription. `readOnly`+ * as resolveOrgPlanByOrgId: without an active plan, every count's limit 0+ * and `noPlan: true`.*/-export async function getContentUsage(orgId) {- const plan = await resolveOrgPlanByOrgId(orgId);+export async function getContentUsage(orgId, { readOnly = false } = {}) {+ const plan = await resolveOrgPlanByOrgId(orgId, { readOnly });const periodStart = await quotaPeriodStart(orgId);const [opportunities, briefs] = await Promise.all([- getOpportunityQuotaStatus(orgId),- getBriefQuotaStatus(orgId),+ getOpportunityQuotaStatus(orgId, { readOnly }),+ getBriefQuotaStatus(orgId, { readOnly }),]);return {plan: plan.id,planName: plan.name,+ ...noPlanMark(plan),periodStart: periodStart.toISOString(),periodEnd: shiftMonthClamped(periodStart, 1).toISOString(),opportunities: {@@ -814,7 +851,7 @@ async function readSiteAuditSettings(orgId) {* each run's share, the five runs and which are recorded, the share the runs* still to come keep out of the user's pool, and the run whose turn it is.*/-async function siteAuditAutoStatus(orgId, limit, periodStart, now) {+async function siteAuditAutoStatus(orgId, limit, periodStart, now, { noPlan = false } = {}) {const [settings, { data: runRows, error }] = await Promise.all([readSiteAuditSettings(orgId),supabaseAdmin@@ -825,7 +862,8 @@ async function siteAuditAutoStatus(orgId, limit, periodStart, now) {]);if (error) throw new Error(error.message);- const enabled = autoAuditEnabled(settings.autoAudit, limit);+ // No plan, no runs: the morning sweep skips an organization without one.+ const enabled = !noPlan && autoAuditEnabled(settings.autoAudit, limit);const perRun = perRunSlots(limit);const periodEnd = shiftMonthClamped(periodStart, 1);const schedule = runSchedule(periodStart, periodEnd);@@ -860,17 +898,18 @@ async function siteAuditAutoStatus(orgId, limit, periodStart, now) {/*** The org's Site Audit quota this period: completed and running audits* against plan.limits.maxSiteAudits (Starter 100, Growth 500,- * Enterprise/Self-hosted unlimited), and the auto-audit share.+ * Enterprise/Self-hosted unlimited), and the auto-audit share. `readOnly` as+ * resolveOrgPlanByOrgId: without an active plan, a limit of 0 and no runs.*/-async function siteAuditQuota(orgId, now) {- const plan = await resolveOrgPlanByOrgId(orgId);+async function siteAuditQuota(orgId, now, { readOnly = false } = {}) {+ const plan = await resolveOrgPlanByOrgId(orgId, { readOnly });const limit = plan.limits.maxSiteAudits;const periodStart = await quotaPeriodStart(orgId, now);const [{ used, autoUsed }, running, autoRunning, auto] = await Promise.all([limit === -1 ? { used: 0, autoUsed: 0 } : countSiteAuditUsage(orgId, periodStart),limit === -1 ? 0 : countRunningSiteAudits(orgId),limit === -1 ? 0 : countRunningSiteAudits(orgId, 'auto'),- siteAuditAutoStatus(orgId, limit, periodStart, now),+ siteAuditAutoStatus(orgId, limit, periodStart, now, { noPlan: plan.noPlan === true }),]);// The quota card tells the runs' audits (done and running) from the user's.return { plan, limit, used, running, auto: { ...auto, used: autoUsed, running: autoRunning } };@@ -929,10 +968,11 @@ export async function enforceSiteAuditQuota(* Returns { used, running, limit, remaining, auto }: remaining is the user's* pool, with running audits and the auto-audit runs still to come taken out;* auto is where auto-audit stands (siteAuditAutoStatus, plus what its runs- * used this period and have running).+ * used this period and have running). `readOnly` as siteAuditQuota, with+ * `noPlan: true`.*/-export async function getSiteAuditQuotaStatus(orgId, { now = new Date() } = {}) {- const { limit, used, running, auto } = await siteAuditQuota(orgId, now);+export async function getSiteAuditQuotaStatus(orgId, { now = new Date(), readOnly = false } = {}) {+ const { plan, limit, used, running, auto } = await siteAuditQuota(orgId, now, { readOnly });if (limit === -1) return { used: 0, running: 0, limit: -1, remaining: -1, auto };return {used,@@ -940,6 +980,7 @@ export async function getSiteAuditQuotaStatus(orgId, { now = new Date() } = {})limit,remaining: Math.max(0, limit - used - running - auto.reserved),auto,+ ...noPlanMark(plan),};}@@ -963,6 +1004,21 @@ export async function getBotRawCap(orgId) {return plan.limits.maxBotRawRecordsPerMonth ?? 0;}+/**+ * Both AI-bot caps, from one plan read, for the connections page:+ * { cap, rawCap } as getBotEventCap and getBotRawCap. `readOnly` as+ * resolveOrgPlanByOrgId: without an active plan, 0 and 0 with `noPlan: true`,+ * so the connections and this month's use still come back.+ */+export async function getBotCaps(orgId, { readOnly = false } = {}) {+ const plan = await resolveOrgPlanByOrgId(orgId, { readOnly });+ return {+ cap: plan.limits.maxBotEventsPerMonth ?? 0,+ rawCap: plan.limits.maxBotRawRecordsPerMonth ?? 0,+ ...noPlanMark(plan),+ };+}+/*** Express middleware that attaches req.plan from the authenticated user.* Must run after auth middleware (req.user must exist).@@ -988,11 +1044,17 @@ export function attachPlan() {/*** Express middleware factory — blocks the request if the plan lacks a feature.* Usage: router.post('/suggest', requireFeature('prompt_suggestions'), handler)+ *+ * `readOnly`, named route by route (as the middleware's open routes are, so+ * none is let through by its method alone): a route that only reads what is+ * kept. An organization without an active plan is then checked against the+ * features of the plan it was on (read-only once the plan has ended,+ * 2026-10-27), so what it stored still comes back; without it, a 402.*/-export function requireFeature(feature) {+export function requireFeature(feature, { readOnly = false } = {}) {return async (req, res, next) => {try {- await enforceFeature(req.user.id, feature);+ await enforceFeature(req.user.id, feature, { readOnly });next();} catch (err) {if (err instanceof PlanLimitError) {diff --git a/server/src/middleware/subscription.js b/server/src/middleware/subscription.jsindex b02c9ec32..025afb66a 100644--- a/server/src/middleware/subscription.js+++ b/server/src/middleware/subscription.js@@ -11,12 +11,13 @@ import logger from '../lib/logger.js';* 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;+ * - BILLING_ROUTES: telling us why a plan is cancelled;* - 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;+ * an outside account (Google, a CMS, a bot log, a store) 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.+ * plan step, and again when the person comes back from it, up to+ * ONBOARDING_DAILY_CALLS a day for the organization (429 past them).* 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.@@ -30,8 +31,16 @@ import logger from '../lib/logger.js';const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);-/** Paths, under /api, that stay open whatever the plan. */-const OPEN_PATHS = ['/billing'];+/**+ * Billing's writes, under /api: open whatever the plan. The plan itself is+ * chosen and cancelled by the web app, through Stripe. Named route by route,+ * as the others are, so a billing route that costs is never let through by+ * its path alone.+ */+export const BILLING_ROUTES = [+ // Why a plan is cancelled, kept and e-mailed to the team (billing.js).+ { method: 'POST', path: /^\/billing\/cancel-feedback\/?$/ },+];/*** Requests, under /api, that end a cost or an access, never start one: open@@ -49,6 +58,9 @@ export const COST_STOPPING = [{ method: 'DELETE', path: /^\/cms\/brands\/[^/]+\/webflow\/?$/ },// Removes an AI-bot log connection (bots.js): its secret stops working.{ method: 'DELETE', path: /^\/bots\/connections\/[^/]+\/[^/]+\/?$/ },+ // Removes a store from the catalog (catalog.js): its sign-in is revoked at+ // the store, then deleted with its products. Feeds and uploads go through RLS.+ { method: 'DELETE', path: /^\/catalog\/sources\/[^/]+\/?$/ },];/**@@ -66,6 +78,14 @@ export const ONBOARDING_ROUTES = [{ method: 'POST', path: /^\/competitors\/suggest\/?$/ },];+/**+ * Onboarding's calls an organization that never subscribed may make a day+ * (UTC), all three routes together: a setup asks each once, so this leaves+ * room for several setups and retries, and bounds what a workspace without a+ * plan can spend on AI. Counted in this process's memory.+ */+export const ONBOARDING_DAILY_CALLS = 20;+/** 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. */@@ -79,18 +99,50 @@ export const SUBSCRIPTION_INACTIVE = {message: 'Your plan has ended. Choose a plan to use Ansvisor again.',};+/** The answer to an onboarding call past the day's ONBOARDING_DAILY_CALLS. */+export const ONBOARDING_LIMIT_REACHED = {+ success: false,+ error: 'rate_limited',+ code: 'onboarding_daily_limit',+ message: 'Setup suggestions are used up for today. Try again tomorrow, or choose a plan.',+};++const DAY_MS = 24 * 60 * 60 * 1000;+/** Person id → until when their organization is taken as active. */const activeUntil = new Map();+/** `org:<id>` (`user:<id>` before the organization exists) → { day, calls } */+const onboardingCalls = 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)- );+ return matches(BILLING_ROUTES, req) || matches(COST_STOPPING, req);+}++/**+ * Counts one onboarding call for `key` today (UTC): false once the day's+ * ONBOARDING_DAILY_CALLS are used. A count from an earlier day starts over,+ * at the end of the map: the counts are kept in the order their day began,+ * so the oldest goes first when MAX_ENTRIES are kept.+ */+function takeOnboardingCall(key, now) {+ const day = Math.floor(now / DAY_MS);+ const kept = onboardingCalls.get(key);+ if (kept?.day === day) {+ if (kept.calls >= ONBOARDING_DAILY_CALLS) return false;+ kept.calls += 1;+ return true;+ }+ onboardingCalls.delete(key);+ if (onboardingCalls.size >= MAX_ENTRIES) {+ onboardingCalls.delete(onboardingCalls.keys().next().value);+ }+ onboardingCalls.set(key, { day, calls: 1 });+ return true;}function isCachedActive(userId, now) {@@ -126,26 +178,32 @@ function rememberActive(userId, now) {* @returns {Promise<'active' | 'never_subscribed' | 'inactive'>}*/export async function subscriptionAccess(userId) {+ return (await readAccess(userId)).access;+}++/** subscriptionAccess, with the organization it read (null without one). */+async function readAccess(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';+ if (!profile) return { access: 'inactive', orgId: null };// 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 orgId = profile.organization_id;+ if (!orgId) return { access: 'never_subscribed', orgId: null };const { data: org, error: orgError } = await supabaseAdmin.from('organizations').select('subscription_status, stripe_subscription_id')- .eq('id', profile.organization_id)+ .eq('id', orgId).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';+ if (!org) return { access: 'inactive', orgId };+ if (isSubscriptionActive(org.subscription_status)) return { access: 'active', orgId };+ return { access: org.stripe_subscription_id ? 'inactive' : 'never_subscribed', orgId };}/**@@ -160,12 +218,17 @@ export async function requireActiveSubscription(req, res, next) {const now = Date.now();if (isCachedActive(userId, now)) return next();try {- const access = await subscriptionAccess(userId);+ const { access, orgId } = await readAccess(userId);if (access === 'active') {rememberActive(userId, now);return next();}- if (access === 'never_subscribed' && matches(ONBOARDING_ROUTES, req)) return next();+ if (access === 'never_subscribed' && matches(ONBOARDING_ROUTES, req)) {+ if (takeOnboardingCall(orgId ? `org:${orgId}` : `user:${userId}`, now)) return next();+ const tomorrow = (Math.floor(now / DAY_MS) + 1) * DAY_MS;+ res.set('Retry-After', String(Math.ceil((tomorrow - now) / 1000)));+ return res.status(429).json(ONBOARDING_LIMIT_REACHED);+ }return res.status(402).json(SUBSCRIPTION_INACTIVE);} catch (err) {(req.log ?? logger).error({ err }, 'subscription check failed');@@ -173,7 +236,8 @@ export async function requireActiveSubscription(req, res, next) {}}-// Test hook — what passes depends on what is remembered.+// Test hook — what passes depends on what is remembered and counted.export function clearSubscriptionCache() {activeUntil.clear();+ onboardingCalls.clear();}diff --git a/server/src/middleware/subscription.test.js b/server/src/middleware/subscription.test.jsindex f1a0ebafd..e393f5922 100644--- a/server/src/middleware/subscription.test.js+++ b/server/src/middleware/subscription.test.js@@ -5,9 +5,9 @@ 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.+ * trialing subscription, but for billing's named routes, the routes that+ * stop a cost or take back an access, and onboarding's routes for an+ * organization that never subscribed, a few a day.*/const reads = [];@@ -32,8 +32,11 @@ vi.mock('../lib/logger.js', () => ({const {ACTIVE_CACHE_MS,+ BILLING_ROUTES,COST_STOPPING,MAX_ENTRIES,+ ONBOARDING_DAILY_CALLS,+ ONBOARDING_LIMIT_REACHED,ONBOARDING_ROUTES,SUBSCRIPTION_INACTIVE,clearSubscriptionCache,@@ -42,8 +45,9 @@ const {} = await import('./subscription.js');function makeRes() {- const res = { status: vi.fn(), json: vi.fn() };+ const res = { status: vi.fn(), json: vi.fn(), set: vi.fn() };res.status.mockReturnValue(res);+ res.set.mockReturnValue(res);return res;}@@ -115,15 +119,33 @@ describe('requireActiveSubscription', () => {expect(reads).toHaveLength(0);});- it('leaves billing open, so a plan can be chosen or cancelled', async () => {+ it("leaves billing's named routes open, and only them", async () => {org = ended;- for (const path of ['/billing', '/billing/cancel-feedback']) {- const { next } = await run({ path });- expect(next).toHaveBeenCalledOnce();+ for (const [method, path] of [+ ['POST', '/billing/cancel-feedback'],+ ['POST', '/billing/cancel-feedback/'],+ // Billing's reads, as every read.+ ['GET', '/billing/ai-usage'],+ ['GET', '/billing/ai-usage/draft/d1'],+ ]) {+ const { res, next } = await run({ method, path });+ expect(next, `${method} ${path}`).toHaveBeenCalledOnce();+ expect(res.status).not.toHaveBeenCalled();}- // A path that only starts with the word is not billing.- const { res } = await run({ path: '/billingx' });- expect(res.status).toHaveBeenCalledWith(402);+ // A billing route that isn't named isn't let through by its path.+ for (const [method, path] of [+ ['POST', '/billing'],+ ['POST', '/billing/checkout'],+ ['POST', '/billing/cancel-feedback/extra'],+ ['PUT', '/billing/cancel-feedback'],+ ['DELETE', '/billing/cancel-feedback'],+ ['POST', '/billingx'],+ ]) {+ const { res, next } = await run({ method, path });+ expect(next, `${method} ${path}`).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(402);+ }+ expect(BILLING_ROUTES).toHaveLength(1);});it('lets an organization off a plan stop work and take back access, and nothing else', async () => {@@ -135,6 +157,8 @@ describe('requireActiveSubscription', () => {['DELETE', '/integrations/google-analytics'],['DELETE', '/cms/brands/b1/webflow'],['DELETE', '/bots/connections/b1/c1'],+ // A store's sign-in is revoked at the store as it is removed.+ ['DELETE', '/catalog/sources/9b2c1e40-0000-4000-8000-000000000003'],];for (const [method, path] of open) {const { res, next } = await run({ method, path });@@ -158,6 +182,11 @@ describe('requireActiveSubscription', () => {['POST', '/cms/brands/b1/webflow'],['POST', '/bots/connections/b1'],['DELETE', '/bots/connections/b1'],+ ['POST', '/catalog/sources'],+ ['POST', '/catalog/sources/s1/sync'],+ ['PUT', '/catalog/sources/s1/credentials'],+ ['DELETE', '/catalog/sources/s1/extra'],+ ['POST', '/catalog/upload'],// A brand is deleted only on a plan (product decision, 2026-10-27).['DELETE', '/brands/b1'],]) {@@ -166,7 +195,7 @@ describe('requireActiveSubscription', () => {expect(res.status).toHaveBeenCalledWith(402);}// Both Google disconnects are one route.- expect(COST_STOPPING).toHaveLength(5);+ expect(COST_STOPPING).toHaveLength(6);});it("opens onboarding's routes, and only them, to an organization that never subscribed", async () => {@@ -197,6 +226,87 @@ describe('requireActiveSubscription', () => {expect((await run({ path: '/topics/suggest' })).next).toHaveBeenCalledOnce();});+ it("holds onboarding's routes to ONBOARDING_DAILY_CALLS a day for the organization", async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-10-27T18:00:00Z'));+ org = neverSubscribed;+ // The three routes share one count.+ for (let i = 0; i < ONBOARDING_DAILY_CALLS; i++) {+ const [method, path] = ONBOARDING[i % ONBOARDING.length];+ expect((await run({ method, path })).next).toHaveBeenCalledOnce();+ }+ const { res, next } = await run({ path: '/competitors/suggest' });+ expect(next).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(429);+ expect(res.json).toHaveBeenCalledWith(ONBOARDING_LIMIT_REACHED);+ // Until midnight UTC, six hours on.+ expect(res.set).toHaveBeenCalledWith('Retry-After', String(6 * 60 * 60));+ expect(ONBOARDING_LIMIT_REACHED).toMatchObject({ error: 'rate_limited' });++ // Counted per organization: its other people wait too…+ expect(+ (await run({ path: '/topics/suggest', user: { id: 'u2' } })).res.status,+ ).toHaveBeenCalledWith(429);+ // …another organization doesn't.+ profile = { organization_id: 'org-2' };+ expect((await run({ path: '/topics/suggest' })).next).toHaveBeenCalledOnce();++ // A new day starts over.+ profile = { organization_id: 'org-1' };+ vi.setSystemTime(new Date('2026-10-28T00:00:00Z'));+ expect((await run({ path: '/topics/suggest' })).next).toHaveBeenCalledOnce();+ });++ it('makes room by the day a count began, so a count renewed today stays', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-10-27T18:00:00Z'));+ org = neverSubscribed;+ for (let i = 0; i < MAX_ENTRIES; i++) {+ profile = { organization_id: `org-${i}` };+ await run({ path: '/topics/suggest' });+ }++ // The next day the first organization uses its calls again: its count+ // moves to the end, behind every count of the day before.+ vi.setSystemTime(new Date('2026-10-28T09:00:00Z'));+ profile = { organization_id: 'org-0' };+ for (let i = 0; i < ONBOARDING_DAILY_CALLS; i++) {+ expect((await run({ path: '/topics/suggest' })).next).toHaveBeenCalledOnce();+ }+ // A new organization makes room by dropping a count of the day before…+ profile = { organization_id: 'org-new' };+ expect((await run({ path: '/topics/suggest' })).next).toHaveBeenCalledOnce();+ // …not today's, so the first organization's calls are still used up.+ profile = { organization_id: 'org-0' };+ expect((await run({ path: '/topics/suggest' })).res.status).toHaveBeenCalledWith(429);+ });++ it('counts onboarding per person before the organization exists', async () => {+ profile = { organization_id: null };+ for (let i = 0; i < ONBOARDING_DAILY_CALLS; i++) await run({ path: '/topics/suggest' });+ expect((await run({ path: '/topics/suggest' })).res.status).toHaveBeenCalledWith(429);+ expect(+ (await run({ path: '/topics/suggest', user: { id: 'u2' } })).next,+ ).toHaveBeenCalledOnce();+ });++ it("leaves an active organization's onboarding calls uncounted", async () => {+ for (let i = 0; i < ONBOARDING_DAILY_CALLS + 5; i++) {+ clearSubscriptionCache();+ const { res, next } = await run({ path: '/topics/suggest' });+ expect(next).toHaveBeenCalledOnce();+ expect(res.status).not.toHaveBeenCalled();+ }+ // And a subscription chosen after the day's calls are used lets them all+ // through (another person: the first is remembered as active).+ const user = { id: 'u3' };+ org = neverSubscribed;+ for (let i = 0; i < ONBOARDING_DAILY_CALLS; i++) await run({ path: '/topics/suggest', user });+ expect((await run({ path: '/topics/suggest', user })).res.status).toHaveBeenCalledWith(429);+ org = { subscription_status: 'trialing', stripe_subscription_id: 'sub_1' };+ expect((await run({ path: '/topics/suggest', user })).next).toHaveBeenCalledOnce();+ });+it("keeps onboarding's routes closed once the organization has had a subscription", async () => {org = ended;for (const [method, path] of ONBOARDING) {@@ -371,6 +481,7 @@ describe('mounted like the server', () => {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.post('/billing/checkout', (req, res) => res.json({ charged: 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 }));@@ -397,6 +508,8 @@ describe('mounted like the server', () => {expect((await fetch(`${baseUrl}/api/prompts`)).status).toBe(200);expect((await post('/api/billing/cancel-feedback')).status).toBe(200);+ // A billing write that isn't named is refused like any other.+ expect((await post('/api/billing/checkout')).status).toBe(402);});it('lets work under way be stopped, but not started', async () => {diff --git a/server/src/routes/audits-settings.test.js b/server/src/routes/audits-settings.test.jsindex b3b4f6d21..f7d6db9b5 100644--- a/server/src/routes/audits-settings.test.js+++ b/server/src/routes/audits-settings.test.js@@ -12,6 +12,8 @@ let writes;let quota;const readSiteTrust = vi.fn();const isOrgActive = vi.fn();+const getSiteAuditQuotaStatus = vi.fn(async () => quota);+const getOrgIdForUser = vi.fn(async () => 'org-1');let server;let baseUrl;@@ -71,8 +73,8 @@ async function startApp() {vi.doMock('../lib/plan-guard.js', () => ({requireFeature: () => (req, res, next) => next(),enforceSiteAuditQuota: vi.fn(),- getSiteAuditQuotaStatus: vi.fn(async () => quota),- getOrgIdForUser: vi.fn(),+ getSiteAuditQuotaStatus,+ getOrgIdForUser,PlanLimitError: class PlanLimitError extends Error {},}));vi.doMock('../lib/audit/context.js', () => ({ buildAuditContext: vi.fn() }));@@ -110,6 +112,7 @@ const otherBrand = '44444444-4444-4444-4444-444444444444';beforeEach(async () => {writes = [];+ getSiteAuditQuotaStatus.mockClear();isOrgActive.mockReset().mockResolvedValue(true);readSiteTrust.mockReset().mockResolvedValue({checks: { about: { ok: true, url: 'https://acme.com/about' } },@@ -183,6 +186,44 @@ describe('GET /api/audits/settings', () => {pinned: [{ key: 'acme.com/about', url: 'https://acme.com/about' }],});});++ it('reads what is kept once the plan has ended: auto-audit off at a limit of 0', async () => {+ // As plan-guard answers a read without an active plan (readOnly).+ quota = {+ used: 10,+ running: 0,+ limit: 0,+ remaining: 0,+ noPlan: true,+ auto: { enabled: false, setting: true, emailAfterRun: true, perRun: 0 },+ };+ const res = await fetch(`${baseUrl}/settings?brandId=${brandId}`);+ expect(res.status).toBe(200);+ expect((await res.json()).settings).toEqual({+ autoAudit: { enabled: false, setting: true, perRun: 0, limit: 0 },+ emailAfterRun: true,+ excludePatterns: ['/careers/*'],+ pinned: [{ key: 'acme.com/about', url: 'https://acme.com/about' }],+ });+ expect(getSiteAuditQuotaStatus).toHaveBeenCalledWith('org-1', { readOnly: true });+ });+});++describe('GET /api/audits/quota', () => {+ it('reads the quota as a read, so a plan that ended answers 200, not 402', async () => {+ quota = { used: 3, running: 0, limit: 0, remaining: 0, noPlan: true };+ const res = await fetch(`${baseUrl}/quota`);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ success: true, quota });+ expect(getSiteAuditQuotaStatus).toHaveBeenCalledWith('org-1', { readOnly: true });+ });++ it('reads nothing without an organization', async () => {+ getOrgIdForUser.mockResolvedValueOnce(null);+ const res = await fetch(`${baseUrl}/quota`);+ expect(res.status).toBe(400);+ expect(getSiteAuditQuotaStatus).not.toHaveBeenCalled();+ });});describe('PUT /api/audits/settings', () => {diff --git a/server/src/routes/audits.js b/server/src/routes/audits.jsindex b5079b027..42e3bf052 100644--- a/server/src/routes/audits.js+++ b/server/src/routes/audits.js@@ -463,7 +463,11 @@ router.post('/bulk', requireFeature('content_optimization'), async (req, res) =>router.get('/quota', async (req, res) => {try {const orgId = await getOrgIdForUser(req.user?.id);- const quota = await getSiteAuditQuotaStatus(orgId);+ if (!orgId) {+ return res.status(400).json({ success: false, message: 'No organization found for user.' });+ }+ // Read-only once the plan has ended (2026-10-27): no plan reads as a limit of 0.+ const quota = await getSiteAuditQuotaStatus(orgId, { readOnly: true });return res.json({ success: true, quota });} catch (err) {if (err instanceof PlanLimitError) {@@ -967,11 +971,12 @@ async function canChangeSettings(userId) {/*** Site Audit settings as the Settings dialog shows them (SA-006): the org's* auto-audit switch and e-mail, the brand's exclude patterns and pinned- * pages.+ * pages. Without an active plan (read-only, 2026-10-27), auto-audit reads as+ * off with a limit of 0, and the rest as kept.*/async function readAuditSettings(brandId, orgId) {const [quota, excludePatterns, { data: pinned, error }] = await Promise.all([- getSiteAuditQuotaStatus(orgId),+ getSiteAuditQuotaStatus(orgId, { readOnly: true }),readExcludePatterns(brandId),supabaseAdmin.from('site_audit_page_prefs')diff --git a/server/src/routes/bots.js b/server/src/routes/bots.jsindex 09dd35cb2..6523d29a1 100644--- a/server/src/routes/bots.js+++ b/server/src/routes/bots.js@@ -16,7 +16,7 @@ import { Router } from 'express';import { z } from 'zod';import supabaseAdmin from '../config/supabase.js';import { assertBrandAccess } from '../lib/access.js';-import { PlanLimitError, getBotEventCap, getBotRawCap } from '../lib/plan-guard.js';+import { PlanLimitError, getBotCaps, getBotEventCap } from '../lib/plan-guard.js';import {CONNECTION_KINDS,hashSecret,@@ -58,7 +58,7 @@ router.get('/connections/:brandId', async (req, res) => {try {const { brand } = await assertBrandAccess(req.params.brandId, req.user.id);const month = new Date().toISOString().slice(0, 7) + '-01';- const [{ data: connections, error }, { data: usage }, cap, rawCap] = await Promise.all([+ const [{ data: connections, error }, { data: usage }, caps] = await Promise.all([supabaseAdmin.from('ai_bot_connections').select('id, kind, created_at, last_event_at')@@ -71,10 +71,12 @@ router.get('/connections/:brandId', async (req, res) => {.eq('organization_id', brand.organization_id).eq('month', month).maybeSingle(),- getBotEventCap(brand.organization_id),- getBotRawCap(brand.organization_id),+ // Read-only once the plan has ended (2026-10-27): no plan reads as caps+ // of 0, and the connections and this month's use still come back.+ getBotCaps(brand.organization_id, { readOnly: true }),]);if (error) throw new Error(error.message);+ const { cap, rawCap, noPlan } = caps;return res.json({connections: connections ?? [],usage: {@@ -88,6 +90,7 @@ router.get('/connections/:brandId', async (req, res) => {raw: usage?.raw_records ?? 0,rawCappedAt: usage?.raw_capped_at ?? null,rawCap,+ ...(noPlan ? { noPlan: true } : {}),},});} catch (error) {diff --git a/server/src/routes/bots.test.js b/server/src/routes/bots.test.jsindex 388a1ec95..f566334c3 100644--- a/server/src/routes/bots.test.js+++ b/server/src/routes/bots.test.js@@ -9,6 +9,9 @@ import express from 'express';let role;let cap;+// What getBotCaps answers a read once the plan has ended (readOnly).+let noPlan;+const capReads = [];const inserted = [];const updates = [];@@ -86,7 +89,10 @@ vi.mock('../lib/plan-guard.js', async () => {PlanLimitError,getOrgIdForUser: async () => 'o1',getBotEventCap: async () => cap,- getBotRawCap: async () => 20_000_000,+ getBotCaps: async (orgId, options) => {+ capReads.push([orgId, options]);+ return noPlan ? { cap: 0, rawCap: 0, noPlan: true } : { cap, rawCap: 20_000_000 };+ },};});@@ -99,6 +105,8 @@ beforeEach(async () => {vi.stubEnv('PUBLIC_SERVER_URL', 'https://api.example.com');role = 'admin';cap = 2_000_000;+ noPlan = false;+ capReads.length = 0;inserted.length = 0;updates.length = 0;const app = express();@@ -193,6 +201,19 @@ describe('AI bot connections', () => {rawCap: 20_000_000,});expect(body.usage.month).toMatch(/^\d{4}-\d{2}-01$/);+ expect(body.usage).not.toHaveProperty('noPlan');+ // A read: a plan that ended doesn't refuse it.+ expect(capReads).toEqual([['o1', { readOnly: true }]]);+ });++ it('still lists the connections and their use once the plan has ended', async () => {+ noPlan = true;+ const res = await fetch(`${baseUrl}/connections/b1`);+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.connections).toHaveLength(1);+ expect(body.usage).toMatchObject({ stored: 12, counted: 15, raw: 20_000_400 });+ expect(body.usage).toMatchObject({ cap: 0, rawCap: 0, noPlan: true });});it('revokes a connection, and says when there is none', async () => {diff --git a/server/src/routes/content-read-only.test.js b/server/src/routes/content-read-only.test.jsnew file mode 100644index 000000000..7ec020687--- /dev/null+++ b/server/src/routes/content-read-only.test.js@@ -0,0 +1,138 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * The Content reads a workspace whose plan ended still gets (read-only,+ * 2026-10-27): GET /api/content/usage and GET /api/content/briefs/quota read+ * the counts as reads (plan-guard answers limits of 0 and `noPlan`, not a+ * 402), and GET /api/content/prompts/:promptId/suggestion gives+ * requireFeature `readOnly`, so the prompt's open suggestion still opens.+ */++const getBriefQuotaStatus = vi.fn();+const getContentUsage = vi.fn();+const getOrgIdForUser = vi.fn();+const openOpportunityForPrompt = vi.fn();+// The plan ended: requireFeature refuses with 402 unless the route gave it+// readOnly, as the real one does.+let planEnded = false;+let server;+let baseUrl;++beforeAll(async () => {+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError: class PlanLimitError extends Error {},+ requireFeature: (_feature, options) => (req, res, next) =>+ planEnded && !options?.readOnly ? res.status(402).json({ error: 'plan_limit' }) : next(),+ enforceBriefQuota: vi.fn(),+ getBriefQuotaStatus,+ getContentUsage,+ getOpportunityRequestAllowance: vi.fn(),+ getOrgIdForUser,+ }));+ vi.doMock('../lib/access.js', () => ({+ NOT_IN_WORKSPACE: 'Not in this workspace',+ assertBrandAccess: vi.fn(),+ assertOpportunitiesAccess: vi.fn(),+ assertOpportunityAccess: vi.fn(),+ assertPromptAccess: async () => [{ prompt_sets: { brand_id: 'b1' } }],+ }));+ vi.doMock('../lib/prompt-content-suggestion.js', () => ({+ openOpportunityForPrompt,+ promptClusterId: vi.fn(),+ promptSuggestionRequest: vi.fn(),+ runningSuggestionJob: vi.fn(),+ }));+ vi.doMock('../lib/job-manager.js', () => ({ createJob: vi.fn(), getJob: vi.fn() }));+ vi.doMock('../lib/job-runner.js', () => ({ runContentJob: vi.fn() }));+ vi.doMock('../config/supabase.js', () => ({ default: { from: vi.fn(), rpc: vi.fn() } }));+ vi.doMock('../lib/logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };+ return { default: logger, logger };+ });++ const { default: router } = await import('./content.js');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/content', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/content`;+});++afterAll(async () => {+ await new Promise((resolve) => server.close(resolve));+ for (const mod of [+ '../lib/plan-guard.js',+ '../lib/access.js',+ '../lib/prompt-content-suggestion.js',+ '../lib/job-manager.js',+ '../lib/job-runner.js',+ '../config/supabase.js',+ '../lib/logger.js',+ ]) {+ vi.doUnmock(mod);+ }+});++beforeEach(() => {+ vi.clearAllMocks();+ planEnded = false;+ getOrgIdForUser.mockResolvedValue('o1');+});++const noPlanCount = { used: 2, limit: 0, remaining: 0, noPlan: true };++describe('GET /usage', () => {+ it('reads the counts as a read, so a plan that ended answers 200', async () => {+ const usage = {+ plan: 'starter',+ planName: 'Starter',+ noPlan: true,+ periodStart: '2026-10-01T00:00:00.000Z',+ periodEnd: '2026-11-01T00:00:00.000Z',+ opportunities: { ...noPlanCount, perRequest: 0 },+ briefs: noPlanCount,+ };+ getContentUsage.mockResolvedValue(usage);+ const res = await fetch(`${baseUrl}/usage`);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual(usage);+ expect(getContentUsage).toHaveBeenCalledWith('o1', { readOnly: true });+ });+});++describe('GET /briefs/quota', () => {+ it('reads the quota as a read, so a plan that ended answers 200', async () => {+ getBriefQuotaStatus.mockResolvedValue(noPlanCount);+ const res = await fetch(`${baseUrl}/briefs/quota`);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual(noPlanCount);+ expect(getBriefQuotaStatus).toHaveBeenCalledWith('o1', { readOnly: true });+ });+});++describe('GET /prompts/:promptId/suggestion', () => {+ it("still opens the prompt's suggestion once the plan has ended, but writes none", async () => {+ planEnded = true;+ openOpportunityForPrompt.mockResolvedValue('opp-1');+ const res = await fetch(`${baseUrl}/prompts/p1/suggestion`);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ existingId: 'opp-1' });+ expect(openOpportunityForPrompt).toHaveBeenCalledWith('b1', 'p1');++ // Only the read is given readOnly: asking for a new one is refused.+ const suggest = await fetch(`${baseUrl}/prompts/p1/suggest`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ idempotencyKey: 'key-0001' }),+ });+ expect(suggest.status).toBe(402);+ });+});diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex 0ba149f31..984e389a1 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -337,7 +337,8 @@ router.post('/:id/alternative', requireFeature('content_optimization'), async (r*/router.get('/prompts/:promptId/suggestion',- requireFeature('content_optimization'),+ // Reads only: a workspace whose plan ended still opens its suggestion.+ requireFeature('content_optimization', { readOnly: true }),async (req, res) => {const { promptId } = req.params;try {@@ -1512,7 +1513,8 @@ router.get('/briefs/quota', async (req, res) => {// Self-hosted single-user setups may have no org row; no quota applies.return res.json({ used: 0, limit: -1, remaining: -1 });}- const quota = await getBriefQuotaStatus(orgId);+ // Read-only once the plan has ended (2026-10-27): no plan reads as a limit of 0.+ const quota = await getBriefQuotaStatus(orgId, { readOnly: true });return res.json(quota);} catch (error) {if (error instanceof PlanLimitError) {@@ -1549,7 +1551,8 @@ router.get('/usage', async (req, res) => {briefs: unlimited,});}- return res.json(await getContentUsage(orgId));+ // Read-only once the plan has ended (2026-10-27): no plan reads as limits of 0.+ return res.json(await getContentUsage(orgId, { readOnly: true }));} catch (error) {if (error instanceof PlanLimitError) {return res.status(error.statusCode).json({diff --git a/server/src/routes/prompts-improve-read.test.js b/server/src/routes/prompts-improve-read.test.jsnew file mode 100644index 000000000..0513f7e51--- /dev/null+++ b/server/src/routes/prompts-improve-read.test.js@@ -0,0 +1,155 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * GET /api/prompts/:promptId/improve reads the kept Improve set; it never+ * generates. Read-only once the plan has ended (2026-10-27), its quota is+ * read as a read: a workspace without an active plan gets the kept set with+ * a spent budget and `noPlan`, not an error.+ */++const getImproveQuotaStatus = vi.fn();+// The plan ended: requireFeature refuses with 402 unless the route gave it+// readOnly, as the real one does.+let planEnded = false;+const kept = {+ id: 'set-1',+ range_key: '7d',+ region: '',+ platform_states: [],+ suggestions: [{ id: 's1', title: 'Publish a comparison page' }],+ latest_result_at: '2026-10-13T08:00:00.000Z',+ generated_at: '2026-10-13T08:00:00.000Z',+ sent_actions: [],+};++function table(name) {+ const result = () => {+ if (name === 'prompts') {+ return { data: { id: 'p1', text: 'best crm', prompt_sets: { brand_id: 'b1' } }, error: null };+ }+ if (name === 'brands') return { data: { id: 'b1', organization_id: 'o1' }, error: null };+ if (name === 'profiles') return { data: { organization_id: 'o1' }, error: null };+ if (name === 'prompt_improve_suggestions') return { data: kept, error: null };+ return { data: [], error: null };+ };+ const chain = new Proxy(+ {},+ {+ get: (_t, prop) => {+ if (prop === 'then') {+ return (resolve, reject) => Promise.resolve(result()).then(resolve, reject);+ }+ if (prop === 'single' || prop === 'maybeSingle') return async () => result();+ return () => chain;+ },+ },+ );+ return chain;+}++vi.mock('../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));+vi.mock('../lib/plan-guard.js', () => ({+ PlanLimitError: class extends Error {},+ enforceFeature: vi.fn(),+ reserveAiBudget: vi.fn(),+ getImproveQuotaStatus,+ requireFeature: (_feature, options) => (req, res, next) =>+ planEnded && !options?.readOnly ? res.status(402).json({ error: 'plan_limit' }) : next(),+ reserveRelevanceAllowance: vi.fn(),+ settleRelevanceUsage: vi.fn(),+}));+vi.mock('../lib/action-center/from-prompt-improve.js', () => ({+ liveImproveSends: async () => ({ latest: null, sentSuggestionIds: [] }),+ sendImproveToActionCenter: vi.fn(),+}));++const { default: router } = await import('./prompts.js');++let server;+let baseUrl;++const read = () =>+ fetch(+ `${baseUrl}/p1/improve?${new URLSearchParams({ preset: '7d', from: '2026-10-06T00:00:00.000Z' })}`,+ );++beforeEach(async () => {+ getImproveQuotaStatus.mockReset();+ planEnded = false;+ const app = express();+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/prompts', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/prompts`;+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('GET /api/prompts/:promptId/improve', () => {+ it('returns the kept set with a spent budget once the plan has ended', async () => {+ planEnded = true;+ getImproveQuotaStatus.mockResolvedValue({+ unlimited: false,+ planName: 'Starter',+ trial: false,+ budgetUsd: 0,+ spentUsd: 0.4,+ remainingUsd: 0,+ generationsLeft: 0,+ percentLeft: 0,+ noPlan: true,+ });+ const res = await read();+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.improve.suggestions).toEqual(kept.suggestions);+ expect(body.quota).toEqual({+ unlimited: false,+ exhausted: true,+ generationsLeft: 0,+ percentLeft: 0,+ trial: false,+ noPlan: true,+ });+ expect(getImproveQuotaStatus).toHaveBeenCalledWith('o1', expect.any(String), {+ readOnly: true,+ });+ // Only the read is given readOnly: building a set is still refused.+ const build = await fetch(`${baseUrl}/p1/improve`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: '{}',+ });+ expect(build.status).toBe(402);+ });++ it('answers an active plan as before, with no noPlan', async () => {+ getImproveQuotaStatus.mockResolvedValue({+ unlimited: false,+ planName: 'Starter',+ trial: false,+ budgetUsd: 5,+ spentUsd: 1,+ remainingUsd: 4,+ generationsLeft: 80,+ percentLeft: 80,+ });+ const body = await (await read()).json();+ expect(body.quota).toEqual({+ unlimited: false,+ exhausted: false,+ generationsLeft: 80,+ percentLeft: 80,+ trial: false,+ });+ });+});diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.jsindex 971b65f68..a7b2fe33b 100644--- a/server/src/routes/prompts.js+++ b/server/src/routes/prompts.js@@ -1034,6 +1034,8 @@ function publicQuota(q) {percentLeft: q.percentLeft,// The free trial's: more comes with starting the plan, not a bigger one.trial: q.trial === true,+ // No plan (read-only, 2026-10-27): nothing left until one is chosen.+ ...(q.noPlan ? { noPlan: true } : {}),};}@@ -1045,8 +1047,10 @@ function improveModelId() {);}-// Read the cached set; never generates.-router.get('/:promptId/improve', requireFeature('prompt_improve'), async (req, res) => {+// Read the cached set; never generates. A workspace whose plan ended still+// reads it (readOnly).+const readImprove = requireFeature('prompt_improve', { readOnly: true });+router.get('/:promptId/improve', readImprove, async (req, res) => {try {const range = parseImproveRange(req.query);const { brand, brandId } = await loadImprovePrompt(req.params.promptId, req.user.id);@@ -1059,7 +1063,9 @@ router.get('/:promptId/improve', requireFeature('prompt_improve'), async (req, r.eq('region', range.region).maybeSingle(),improveResultsQuery('created_at', { promptId: req.params.promptId, brandId, range }).limit(1),- getImproveQuotaStatus(brand.organization_id, improveModelId()),+ // Read-only once the plan has ended (2026-10-27): the kept set still+ // comes back, with a budget of 0.+ getImproveQuotaStatus(brand.organization_id, improveModelId(), { readOnly: true }),]);return res.json({improve: improveResponse(diff --git a/server/src/routes/volumes.js b/server/src/routes/volumes.jsindex 3eec9c47a..8b2256c0d 100644--- a/server/src/routes/volumes.js+++ b/server/src/routes/volumes.js@@ -328,7 +328,9 @@ router.post('/bootstrap', requireFeature('prompt_volumes'), async (req, res) =>* what actually landed, which is the honest reading — the counts come from the* table either way.*/-router.get('/status/:brandId', requireFeature('prompt_volumes'), async (req, res) => {+// Reads only: a workspace whose plan ended still sees what was analyzed.+const readVolumes = requireFeature('prompt_volumes', { readOnly: true });+router.get('/status/:brandId', readVolumes, async (req, res) => {try {const { brandId } = req.params;await assertBrandAccess(brandId, req.user.id);@@ -480,10 +482,19 @@ router.get('/brand/:brandId', async (req, res) => {promptCategory: promptMap[v.prompt_id]?.category || '',}));- const quota = await getVolumeQuotaStatus(req.user.id);+ // Read-only once the plan has ended (2026-10-27): the volumes still come+ // back, with a quota of nothing left.+ const quota = await getVolumeQuotaStatus(req.user.id, { readOnly: true });return res.json({ volumes: enriched, quota });} catch (error) {+ if (error instanceof PlanLimitError) {+ return res.status(error.statusCode).json({+ success: false,+ error: 'plan_limit',+ message: error.message,+ });+ }req.log.error({ err: error }, 'fetch volumes error');return res.status(error.status || 500).json({error: 'Failed to fetch volume data',diff --git a/server/src/routes/volumes.test.js b/server/src/routes/volumes.test.jsindex 81b12d80d..18a3d8fab 100644--- a/server/src/routes/volumes.test.js+++ b/server/src/routes/volumes.test.js@@ -19,11 +19,33 @@ class PlanLimitError extends Error {}const enforceVolumeQuota = vi.fn();+const getVolumeQuotaStatus = vi.fn();const assertBrandAccess = vi.fn();const getVolumeProgress = vi.fn();const analyzeBrandVolumes = vi.fn();const insert = vi.fn();+/**+ * The plan ended: requireFeature refuses with 402 unless the route gave it+ * readOnly, as the real one does.+ */+let planEnded = false;+const requireFeature = (_feature, options) => (req, res, next) =>+ planEnded && !options?.readOnly ? res.status(402).json({ error: 'plan_limit' }) : next();++/** Rows a read of each table answers (GET /brand); a table not here only inserts. */+let rows = {};+function from(table) {+ if (!(table in rows)) return { insert };+ const chain = {+ select: () => chain,+ eq: () => chain,+ in: () => chain,+ then: (resolve) => resolve({ data: rows[table], error: null }),+ };+ return chain;+}+/** Lets a test hold a run open and decide exactly when it ends. */function deferred() {let resolve;@@ -43,8 +65,8 @@ async function startApp() {vi.doMock('../lib/plan-guard.js', () => ({PlanLimitError,enforceVolumeQuota,- getVolumeQuotaStatus: vi.fn(),- requireFeature: () => (req, res, next) => next(),+ getVolumeQuotaStatus,+ requireFeature,}));vi.doMock('../lib/access.js', () => ({assertBrandAccess,@@ -56,7 +78,7 @@ async function startApp() {mapVolumeRow: (r) => r,fetchAndSaveVolumes: vi.fn(),}));- vi.doMock('../config/supabase.js', () => ({ default: { from: () => ({ insert }) } }));+ vi.doMock('../config/supabase.js', () => ({ default: { from } }));vi.doMock('../lib/logger.js', () => {const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };return { default: logger, logger };@@ -92,6 +114,8 @@ const post = (body) =>beforeEach(async () => {vi.clearAllMocks();+ rows = {};+ planEnded = false;enforceVolumeQuota.mockResolvedValue({ remaining: -1, orgId: 'org1' });assertBrandAccess.mockResolvedValue(undefined);getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 0 });@@ -394,6 +418,15 @@ describe('POST /bootstrap', () => {});describe('GET /status/:brandId', () => {+ it('stays readable once the plan has ended (readOnly), while a run is refused', async () => {+ planEnded = true;+ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 40 });+ const res = await fetch(`${baseUrl}/status/b1`);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ running: false, total: 100, analyzed: 40, done: 40 });+ expect((await post({ brandId: 'b1' })).status).toBe(402);+ });+/*** Nothing reaches prompt_volumes until the lookup at the very end, so a* status built on row counts read 0/100 for the whole ten-minute wait and@@ -458,3 +491,45 @@ describe('GET /status/:brandId', () => {expect((await (await fetch(`${baseUrl}/status/b1`)).json()).running).toBe(false);});});++describe('GET /brand/:brandId', () => {+ beforeEach(() => {+ rows = {+ prompt_sets: [{ id: 'ps1' }],+ prompts: [{ id: 'p1', text: 'best espresso', category: 'coffee', prompt_set_id: 'ps1' }],+ prompt_volumes: [{ prompt_id: 'p1', est_ai_volume: 40 }],+ };+ });++ it('returns the kept volumes with the quota, read as a read', async () => {+ const quota = { used: 1, limit: 4, remaining: 3 };+ getVolumeQuotaStatus.mockResolvedValue(quota);+ const res = await fetch(`${baseUrl}/brand/b1`);+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.volumes).toEqual([+ { prompt_id: 'p1', est_ai_volume: 40, promptText: 'best espresso', promptCategory: 'coffee' },+ ]);+ expect(body.quota).toEqual(quota);+ // Read-only once the plan has ended: no 402 for a read.+ expect(getVolumeQuotaStatus).toHaveBeenCalledWith('u1', { readOnly: true });+ });++ it('still returns the volumes once the plan has ended', async () => {+ getVolumeQuotaStatus.mockResolvedValue({ used: 1, limit: 0, remaining: 0, noPlan: true });+ const res = await fetch(`${baseUrl}/brand/b1`);+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.volumes).toHaveLength(1);+ expect(body.quota).toEqual({ used: 1, limit: 0, remaining: 0, noPlan: true });+ });++ it('answers a plan refusal with its own status, not 500', async () => {+ getVolumeQuotaStatus.mockRejectedValue(+ new PlanLimitError('No organization found for user.', 400),+ );+ const res = await fetch(`${baseUrl}/brand/b1`);+ expect(res.status).toBe(400);+ expect(await res.json()).toMatchObject({ error: 'plan_limit' });+ });+});diff --git a/server/src/server.js b/server/src/server.jsindex 1742c3447..6c3fc90bd 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -469,7 +469,8 @@ app.get('/api/internal/site-audit-quota', async (req, res) => {if (!orgId) {return res.status(400).json({ success: false, message: 'orgId is required' });}- const quota = await getSiteAuditQuotaStatus(orgId);+ // A read, as the dashboard's: a plan that ended reads as a limit of 0.+ const quota = await getSiteAuditQuotaStatus(orgId, { readOnly: true });return res.json({ success: true, quota });} catch (err) {if (err.statusCode) {