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
feat(web): refuse direct database writes from a workspace whose plan has ended, on the server (#1613)
Cihanea6a7a04185a
diff --git a/web/src/app/api/agent/conversations/[id]/route.ts b/web/src/app/api/agent/conversations/[id]/route.tsindex 477900c75..e92f56042 100644--- a/web/src/app/api/agent/conversations/[id]/route.ts+++ b/web/src/app/api/agent/conversations/[id]/route.ts@@ -45,6 +45,7 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str* DELETE /api/agent/conversations/[id]** Drop a conversation (cascades to its messages). Ownership-check first.+ * Open while the workspace is read-only: deleting a conversation starts no cost.*/export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {const auth = await resolveAgentAuth();diff --git a/web/src/app/api/keys/[id]/route.ts b/web/src/app/api/keys/[id]/route.tsindex cf0f53c0e..28634ce9d 100644--- a/web/src/app/api/keys/[id]/route.ts+++ b/web/src/app/api/keys/[id]/route.ts@@ -1,6 +1,7 @@import { NextResponse } from 'next/server';import { createClient } from '@/lib/supabase/server';+/** Open while the workspace is read-only: revoking a key takes back access. */export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {const { id } = await params;const supabase = await createClient();diff --git a/web/src/app/api/keys/route.ts b/web/src/app/api/keys/route.tsindex ceab193cd..5dac6ddd8 100644--- a/web/src/app/api/keys/route.ts+++ b/web/src/app/api/keys/route.ts@@ -24,6 +24,11 @@ export async function GET() {return NextResponse.json({ keys: data ?? [] });}+/**+ * Open while the workspace is read-only (2026-10-14 decision): a key costs+ * nothing, and on a read-only workspace it only reads — the MCP surface+ * answers subscription_inactive to everything but list_ and get_ tools.+ */export async function POST(req: Request) {const supabase = await createClient();const {diff --git a/web/src/app/api/settings/ai-providers/route.test.ts b/web/src/app/api/settings/ai-providers/route.test.tsindex 289e5ead5..4afa7dbaf 100644--- a/web/src/app/api/settings/ai-providers/route.test.ts+++ b/web/src/app/api/settings/ai-providers/route.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/*** /api/settings/ai-providers: an organization's own keys for Chat, one per@@ -7,12 +7,23 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';let user: { id: string } | null;let profile: { id: string; role: string; organization_id: string } | null;+/** The organization's plan, read on the cloud before a change. */+let org: { subscription_status: string; stripe_subscription_id: string };vi.mock('@/lib/supabase/server', () => ({createClient: async () => ({auth: { getUser: async () => ({ data: { user } }) },from: () => ({- select: () => ({ eq: () => ({ single: async () => ({ data: profile }) }) }),+ select: () => ({+ eq: () => ({+ single: async () => ({ data: profile }),+ // The plan check: the profile with its organization.+ maybeSingle: async () => ({+ data: profile && { ...profile, organizations: org },+ error: null,+ }),+ }),+ }),}),}),}));@@ -67,6 +78,7 @@ const send = (method: string, body?: unknown) =>beforeEach(() => {user = { id: 'u1' };profile = { id: 'u1', role: 'admin', organization_id: 'org1' };+ org = { subscription_status: 'active', stripe_subscription_id: 'sub_1' };queries.length = 0;results = [];rpc.mockReset().mockResolvedValue({ data: true, error: null });@@ -256,3 +268,44 @@ describe('DELETE', () => {expect((await remove('copilot')).status).toBe(400);});});++describe('a read-only workspace (cloud, plan not active)', () => {+ beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ org = { subscription_status: 'canceled', stripe_subscription_id: 'sub_1' };+ });+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('answers 402 subscription_inactive to saving or switching a key, and writes nothing', async () => {+ for (const res of [+ await PUT(send('PUT', { provider: 'openai', apiKey: KEY })),+ await PATCH(send('PATCH', { provider: 'google' })),+ ]) {+ expect(res.status).toBe(402);+ expect(await res.json()).toMatchObject({ code: 'subscription_inactive' });+ }+ expect(queries).toHaveLength(0);+ expect(rpc).not.toHaveBeenCalled();+ });++ it('still removes a key: that takes back access', async () => {+ const res = await DELETE(+ new Request('http://localhost/api/settings/ai-providers?provider=openai', {+ method: 'DELETE',+ }),+ );+ expect(res.status).toBe(200);+ expect(rpc).toHaveBeenCalledWith('remove_ai_provider_key', {+ p_organization_id: 'org1',+ p_provider: 'openai',+ });+ });++ it('saves once the plan is active', async () => {+ org = { subscription_status: 'trialing', stripe_subscription_id: 'sub_1' };+ results = [{ error: null }];+ expect((await PUT(send('PUT', { provider: 'openai', apiKey: KEY }))).status).toBe(200);+ });+});diff --git a/web/src/app/api/settings/ai-providers/route.ts b/web/src/app/api/settings/ai-providers/route.tsindex a78df7377..18573423e 100644--- a/web/src/app/api/settings/ai-providers/route.ts+++ b/web/src/app/api/settings/ai-providers/route.ts@@ -1,6 +1,7 @@import { NextResponse } from 'next/server';import { createClient } from '@/lib/supabase/server';import { supabaseAdmin } from '@/lib/supabase/admin';+import { writeRefusal } from '@/lib/subscription-guard';import { encryptApiKey, last4 } from '@/lib/agent/key-encryption';import { isAiProvider, parseProviderSettings, type AiProvider } from '@/lib/agent/providers';@@ -19,6 +20,9 @@ import { isAiProvider, parseProviderSettings, type AiProvider } from '@/lib/agen* - DELETE ?provider=: removes a key; when it was Chat's, the most recently* saved other one takes over.*+ * While the workspace is read-only (cloud, plan not active), PUT and PATCH+ * answer 402 subscription_inactive; DELETE stays open.+ ** Auth model:* - GET: any signed-in org member can see which keys are configured.* The chat endpoint already gates, so leaking "we have a key" is fine.@@ -139,6 +143,8 @@ export async function GET() {export async function PUT(req: Request) {const ctx = await getAdmin();if (ctx instanceof NextResponse) return ctx;+ const refused = await writeRefusal();+ if (refused) return refused;const body = (await req.json().catch(() => ({}))) as {provider?: unknown;@@ -213,6 +219,8 @@ export async function PUT(req: Request) {export async function PATCH(req: Request) {const ctx = await getAdmin();if (ctx instanceof NextResponse) return ctx;+ const refused = await writeRefusal();+ if (refused) return refused;const body = (await req.json().catch(() => ({}))) as { provider?: unknown };if (!isAiProvider(body.provider)) {@@ -228,6 +236,10 @@ export async function PATCH(req: Request) {return NextResponse.json({ ok: true });}+/**+ * Open while the workspace is read-only: removing a key takes back what the+ * org gave us, as disconnecting an integration does (lib/subscription-guard.ts).+ */export async function DELETE(req: Request) {const ctx = await getAdmin();if (ctx instanceof NextResponse) return ctx;diff --git a/web/src/app/api/settings/pulse/route.test.ts b/web/src/app/api/settings/pulse/route.test.tsindex 141ca1f7c..1a7811201 100644--- a/web/src/app/api/settings/pulse/route.test.ts+++ b/web/src/app/api/settings/pulse/route.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/*** /api/settings/pulse: the Daily Pulse's delivery per brand, and whether the@@ -8,6 +8,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const state = vi.hoisted(() => ({role: 'admin',+ // The organization's plan, read on the cloud before a change.+ subscriptionStatus: 'active',settings: [] as Record<string, unknown>[],upserts: [] as Record<string, unknown>[],}));@@ -21,6 +23,17 @@ vi.mock('@/lib/supabase/server', () => ({single: async () => ({data: { id: 'u1', role: state.role, organization_id: 'o1' },}),+ // The plan check: the profile with its organization.+ maybeSingle: async () => ({+ data: {+ organization_id: 'o1',+ organizations: {+ subscription_status: state.subscriptionStatus,+ stripe_subscription_id: 'sub_1',+ },+ },+ error: null,+ }),}),}),}),@@ -63,6 +76,7 @@ const put = (body: Record<string, unknown>) =>beforeEach(() => {state.role = 'admin';+ state.subscriptionStatus = 'active';state.settings = [];state.upserts = [];});@@ -111,3 +125,27 @@ describe('PUT /api/settings/pulse', () => {expect(state.upserts).toEqual([]);});});++describe('PUT /api/settings/pulse on a read-only workspace (cloud, plan not active)', () => {+ beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ state.subscriptionStatus = 'canceled';+ });+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('answers 402 subscription_inactive and saves nothing', async () => {+ const res = await put({ brandId: 'b1', frequency: 'weekly', recipients: [] });+ expect(res.status).toBe(402);+ expect(await res.json()).toMatchObject({ code: 'subscription_inactive' });+ expect(state.upserts).toEqual([]);+ });++ it('saves once the plan is active', async () => {+ state.subscriptionStatus = 'trialing';+ const res = await put({ brandId: 'b1', frequency: 'weekly', recipients: [] });+ expect(res.status).toBe(200);+ expect(state.upserts).toHaveLength(1);+ });+});diff --git a/web/src/app/api/settings/pulse/route.ts b/web/src/app/api/settings/pulse/route.tsindex b7f8796da..a95ced228 100644--- a/web/src/app/api/settings/pulse/route.ts+++ b/web/src/app/api/settings/pulse/route.ts@@ -1,6 +1,7 @@import { NextResponse } from 'next/server';import { createClient } from '@/lib/supabase/server';import { supabaseAdmin } from '@/lib/supabase/admin';+import { writeRefusal } from '@/lib/subscription-guard';import { parseRecipients } from '@/lib/pulse-recipients';/**@@ -93,6 +94,8 @@ export async function PUT(request: Request) {if (ctx.profile.role !== 'admin' && ctx.profile.role !== 'manager') {return NextResponse.json({ error: 'Forbidden' }, { status: 403 });}+ const refused = await writeRefusal();+ if (refused) return refused;let body: {brandId?: string;diff --git a/web/src/components/providers/upgrade-dialog-provider.test.tsx b/web/src/components/providers/upgrade-dialog-provider.test.tsxindex 43c3384eb..6c2d08bc4 100644--- a/web/src/components/providers/upgrade-dialog-provider.test.tsx+++ b/web/src/components/providers/upgrade-dialog-provider.test.tsx@@ -222,3 +222,30 @@ describe('useUpgradeGate', () => {expect(dialog()).toBeNull();});});++describe('a server action refused as read-only', () => {+ /** A rejection no caller caught, as the browser reports it. */+ async function reject(reason: unknown) {+ const event = Object.assign(new Event('unhandledrejection', { cancelable: true }), { reason });+ await act(async () => {+ window.dispatchEvent(event);+ });+ return event;+ }++ it('opens the upgrade dialog when no caller caught it, though the page still thought the plan active', async () => {+ await render({ active: true, status: 'active' });+ const event = await reject(+ Object.assign(new Error('masked in production'), { digest: 'subscription_inactive' }),+ );+ expect(event.defaultPrevented).toBe(true);+ expect(dialog()?.textContent).toContain('Choose a plan to keep going');+ });++ it('leaves any other rejection alone', async () => {+ await render({ active: false });+ const event = await reject(new Error('Failed to fetch'));+ expect(event.defaultPrevented).toBe(false);+ expect(dialog()).toBeNull();+ });+});diff --git a/web/src/components/providers/upgrade-dialog-provider.tsx b/web/src/components/providers/upgrade-dialog-provider.tsxindex 5fccf21e5..a31d4806d 100644--- a/web/src/components/providers/upgrade-dialog-provider.tsx+++ b/web/src/components/providers/upgrade-dialog-provider.tsx@@ -1,6 +1,6 @@'use client';-import { useCallback, useMemo, useState, type ReactNode } from 'react';+import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';import { Link } from '@/i18n/navigation';@@ -18,6 +18,7 @@ import {} from '@/components/ui/dialog';import { usePlanContext } from '@/components/providers/plan-provider';import { useUserRole } from '@/hooks/use-user-role';+import { isSubscriptionInactive } from '@/lib/api-failure';import { readOnlyReason, type ReadOnlyReason } from '@/lib/billing/subscription-access';import { openBillingPortal } from '@/lib/billing/portal-client';import { ChoosePlanDialog } from '@/components/billing/choose-plan-dialog';@@ -36,6 +37,10 @@ export { CHOOSE_PLAN_HREF, useUpgradeDialog, useUpgradeGate } from './upgrade-ga* Stripe's Checkout; other members are asked to turn to an admin. A payment* being retried asks for the payment method instead. Self-hosted is never* locked.+ *+ * A server action the server refused as read-only (assertWritable) that no+ * caller caught opens the dialog too: the plan can end while a page is open,+ * before its buttons know.*/export function UpgradeDialogProvider({adminName = null,@@ -56,6 +61,15 @@ export function UpgradeDialogProvider({setAction(typeof label === 'string' && label ? label : null);setOpen(true);}, []);+ useEffect(() => {+ const onRejection = (event: PromiseRejectionEvent) => {+ if (!isSubscriptionInactive(event.reason)) return;+ event.preventDefault();+ openUpgrade();+ };+ window.addEventListener('unhandledrejection', onRejection);+ return () => window.removeEventListener('unhandledrejection', onRejection);+ }, [openUpgrade]);const value = useMemo(() => ({isLocked: !subscriptionActive,diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex e023c0db7..30b6f076f 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -60,6 +60,7 @@ import {type TaskDetailsEdit,} from '@/lib/action-center/task-details';import type { PriorityLevel, PriorityReason } from '@/lib/action-center/priority';+import { assertWritable } from '@/lib/subscription-guard';export interface ActionAssignee {id: string;@@ -329,6 +330,7 @@ export async function updateActionStatus(status: ActionStatus,reason: ActionDismissReason | null = null,): Promise<void> {+ await assertWritable();const supabase = await createClient();const dismissReason =status === 'dismissed' && reason && ACTION_DISMISS_REASONS.includes(reason) ? reason : null;@@ -377,6 +379,7 @@ export async function assignAction(actionId: string,assigneeId: string | null,): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('actions')@@ -392,6 +395,7 @@ export async function setActionDueDate(actionId: string,dueDate: string | null,): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('actions')@@ -409,6 +413,7 @@ export async function updateTaskStatus(status: TaskStatus,skipReason?: string,): Promise<void> {+ await assertWritable();const supabase = await createClient();// A skip records why. "We decided not to" is only useful to the next reader@@ -450,6 +455,7 @@ function cleanTaskTitle(raw: string): string {* as many as someone types.*/export async function addTask(brandId: string, actionId: string, title: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const text = cleanTaskTitle(title);@@ -490,6 +496,7 @@ export async function updateTaskDetails(taskId: string,edit: TaskDetailsEdit & { title: string | null },): Promise<void> {+ await assertWritable();if (!isTaskDetailsEdit(edit) || (edit.title !== null && typeof edit.title !== 'string')) {throw new Error('Invalid task details');}@@ -539,6 +546,7 @@ export async function updateTaskDetails(* action makes that a non-issue.*/export async function deleteTask(brandId: string, actionId: string, taskId: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabasediff --git a/web/src/lib/actions/action-task-reviews.ts b/web/src/lib/actions/action-task-reviews.tsindex 0dafda9f3..92143f103 100644--- a/web/src/lib/actions/action-task-reviews.ts+++ b/web/src/lib/actions/action-task-reviews.ts@@ -8,6 +8,7 @@ import {type ActionTaskDetails,type TaskDetailsEdit,} from '@/lib/action-center/task-details';+import { assertWritable } from '@/lib/subscription-guard';/*** Tasks waiting for review (AC-010, 00293): ones an agent wrote without the@@ -91,6 +92,7 @@ export async function approveTaskReview(reviewId: string,edit: TaskDetailsEdit & { title: string },): Promise<ApproveTaskReviewResult> {+ await assertWritable();if (!isTaskDetailsEdit(edit) || typeof edit.title !== 'string') return { error: 'invalid' };const supabase = await createClient();const { data: row, error: readError } = await supabase@@ -123,6 +125,7 @@ export async function approveTaskReview(/** A task waiting for review dropped: it never reaches the action. */export async function dismissTaskReview(brandId: string, reviewId: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { data: row, error: readError } = await supabase.from('action_task_reviews')diff --git a/web/src/lib/actions/brand-domain.ts b/web/src/lib/actions/brand-domain.tsindex 9d5b14e40..51bc82a33 100644--- a/web/src/lib/actions/brand-domain.ts+++ b/web/src/lib/actions/brand-domain.ts@@ -5,6 +5,7 @@ import { revalidatePath } from 'next/cache';import { after } from 'next/server';import type { BrandDomain } from '@/types';import { API_BASE_URL } from '@/config/api';+import { assertWritable } from '@/lib/subscription-guard';/*** `prompt_results.citation_count` is computed at tracking time against the@@ -47,6 +48,7 @@ export async function addDomain(brandId: string,data: { domain: string; country?: string; isPrimary: boolean },): Promise<BrandDomain> {+ await assertWritable();const supabase = await createClient();const { data: domain, error } = await supabase@@ -71,6 +73,7 @@ export async function updateDomain(id: string,data: { domain?: string; country?: string | null; isPrimary?: boolean },): Promise<BrandDomain> {+ await assertWritable();const supabase = await createClient();const payload: Record<string, unknown> = {};@@ -96,6 +99,7 @@ export async function updateDomain(}export async function removeDomain(id: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { data: removed, error } = await supabase@@ -118,6 +122,7 @@ export async function syncDomains(brandId: string,domains: { domain: string; country?: string; isPrimary: boolean }[],): Promise<BrandDomain[]> {+ await assertWritable();const supabase = await createClient();await supabase.from('brand_domains').delete().eq('brand_id', brandId);diff --git a/web/src/lib/actions/brand-platform.ts b/web/src/lib/actions/brand-platform.tsindex 2eb94501c..38403e596 100644--- a/web/src/lib/actions/brand-platform.ts+++ b/web/src/lib/actions/brand-platform.ts@@ -4,6 +4,7 @@ import { createClient } from '@/lib/supabase/server';import { revalidatePath } from 'next/cache';import { enforceFeature, enforceLimit } from '@/lib/guards/plan-guard';import type { AIPlatform, BrandPlatform, CheckFrequency } from '@/types';+import { assertWritable } from '@/lib/subscription-guard';function mapRow(row: Record<string, unknown>): BrandPlatform {return {@@ -41,6 +42,7 @@ export async function syncBrandPlatforms(apiModel?: string;}[],): Promise<BrandPlatform[]> {+ await assertWritable();const supabase = await createClient();const { data: brand } = await supabase@@ -94,6 +96,7 @@ export async function updateBrandPlatform(id: string,updates: { isEnabled?: boolean; checkFrequency?: CheckFrequency; apiModel?: string },): Promise<BrandPlatform> {+ await assertWritable();const supabase = await createClient();const payload: Record<string, unknown> = {};diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.tsindex d33e7f215..495922e43 100644--- a/web/src/lib/actions/brand.ts+++ b/web/src/lib/actions/brand.ts@@ -10,6 +10,7 @@ import type { Brand, BrandDomain, Industry } from '@/types';import { MAX_PINNED_COMPETITORS } from '@/lib/insights-trend';import { isSiteType, type SiteType } from '@/lib/content/page-types';import { isConversionsConsent, type ConversionsConsent } from '@/lib/conversion-tracking';+import { assertWritable } from '@/lib/subscription-guard';function mapDomainRow(d: Record<string, unknown>): BrandDomain {return {@@ -98,6 +99,7 @@ export type CreateBrandResult = { brand: Brand } | { error: string; code: 'plan_* meaningless digest message (same as #427 for prompts).*/export async function createBrand(input: CreateBrandInput): Promise<CreateBrandResult> {+ await assertWritable({ onboarding: true });const supabase = await createClient();const { count } = await supabase@@ -175,6 +177,7 @@ interface UpdateBrandInput {}export async function updateBrand(id: string, updates: UpdateBrandInput): Promise<Brand> {+ await assertWritable();const supabase = await createClient();const payload: Record<string, unknown> = {};@@ -272,8 +275,19 @@ export async function setBrandShoppingMode(brandId: string,enabled: boolean,): Promise<{ promptsUpdated: number }> {- const supabase = await createClient();+ await assertWritable();+ return applyShoppingMode(await createClient(), brandId, enabled);+}+/**+ * setBrandShoppingMode's writes, without its plan check: markBrandAsEcommerce+ * runs them in setup, where an organization that never subscribed may write.+ */+async function applyShoppingMode(+ supabase: Awaited<ReturnType<typeof createClient>>,+ brandId: string,+ enabled: boolean,+): Promise<{ promptsUpdated: number }> {// RLS gates this — the calling user must already have write access to// the brand via their org membership. The updated row comes back, as in// setBrandActive, so a write RLS denied (an analyst) fails instead of@@ -348,6 +362,7 @@ export async function setBrandShoppingMode(export async function markBrandAsEcommerce(brandId: string,): Promise<{ industry: string | null; promptsUpdated: number }> {+ await assertWritable({ onboarding: true });const supabase = await createClient();const { data: brand, error } = await supabase.from('brands')@@ -372,7 +387,7 @@ export async function markBrandAsEcommerce(}industry = ecommerce;}- const { promptsUpdated } = await setBrandShoppingMode(brandId, true);+ const { promptsUpdated } = await applyShoppingMode(supabase, brandId, true);return { industry, promptsUpdated };}@@ -389,6 +404,7 @@ export async function markBrandAsEcommerce(* brand via their org membership.*/export async function setBrandActive(brandId: string, isActive: boolean): Promise<void> {+ await assertWritable();const supabase = await createClient();// Return the updated row so a no-op (invalid id, or RLS silently denying the@@ -419,6 +435,7 @@ export async function setPinnedCompetitors(brandId: string,competitorIds: string[],): Promise<string[]> {+ await assertWritable();if (!Array.isArray(competitorIds) || competitorIds.some((id) => typeof id !== 'string')) {throw new Error('Pinned competitors must be a list of competitor ids.');}diff --git a/web/src/lib/actions/catalog.ts b/web/src/lib/actions/catalog.tsindex 16ded2a36..edc930ded 100644--- a/web/src/lib/actions/catalog.ts+++ b/web/src/lib/actions/catalog.ts@@ -10,6 +10,7 @@ import {type CatalogSourceKind,type CatalogSyncStatus,} from '@/lib/catalog';+import { assertWritable } from '@/lib/subscription-guard';/*** A brand's catalog sources (#1263, 00279, 00282), read and changed through@@ -67,6 +68,7 @@ export async function addFeedSource(url: string,format: CatalogFormat = 'auto',): Promise<AddFeedResult> {+ await assertWritable();const address = typeof url === 'string' ? url.trim() : '';if (!z.guid().safeParse(brandId).success ||@@ -99,6 +101,7 @@ export async function addFeedSource(/** Removes a feed or an upload, and with it its products: admins and managers. A store goes through the API. */export async function removeCatalogSource(id: string): Promise<void> {+ await assertWritable();if (!z.guid().safeParse(id).success) throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabase.from('catalog_sources').delete().eq('id', id).select('id');diff --git a/web/src/lib/actions/competitor.ts b/web/src/lib/actions/competitor.tsindex 3517a945e..11f7eef31 100644--- a/web/src/lib/actions/competitor.ts+++ b/web/src/lib/actions/competitor.ts@@ -3,6 +3,7 @@import { createClient } from '@/lib/supabase/server';import { revalidatePath } from 'next/cache';import type { Competitor } from '@/types';+import { assertWritable } from '@/lib/subscription-guard';function mapRow(row: Record<string, unknown>): Competitor {return {@@ -30,6 +31,7 @@ export async function addCompetitor(brandId: string,input: { name: string; domain: string },): Promise<Competitor> {+ await assertWritable({ onboarding: true });const supabase = await createClient();const { data, error } = await supabase@@ -52,6 +54,7 @@ export async function addCompetitor(}export async function deleteCompetitor(id: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('competitors').delete().eq('id', id);diff --git a/web/src/lib/actions/content-authors.ts b/web/src/lib/actions/content-authors.tsindex 14856b24c..0807345a3 100644--- a/web/src/lib/actions/content-authors.ts+++ b/web/src/lib/actions/content-authors.ts@@ -3,6 +3,7 @@import { z } from 'zod';import { authorInput, type AuthorInput, type AuthorsRead } from '@/lib/content/authors';import { createClient } from '@/lib/supabase/server';+import { assertWritable } from '@/lib/subscription-guard';/*** Settings › Authors (Content Editor Quality spec §9, CE-037): the real@@ -99,6 +100,7 @@ export async function getContentAuthors(export async function saveContentAuthor(input: AuthorInput,): Promise<{ id: string } | { error: 'already_author' }> {+ await assertWritable();const parsed = authorInput.safeParse(input);if (!parsed.success) throw new Error('invalid');const { id, name, title, bio, photoUrl, sameAs, isMe } = parsed.data;@@ -161,6 +163,7 @@ export async function saveContentAuthor(/** Deletes an author the member may delete: one they added or are, or any as an admin. */export async function deleteContentAuthor(id: string): Promise<void> {+ await assertWritable();if (!z.guid().safeParse(id).success) throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabase.from('content_authors').delete().eq('id', id).select('id');@@ -175,6 +178,7 @@ export async function deleteContentAuthor(id: string): Promise<void> {* is refused.*/export async function setBrandByline(brandId: string, on: boolean): Promise<void> {+ await assertWritable();if (!z.guid().safeParse(brandId).success || typeof on !== 'boolean') throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabase@@ -188,6 +192,7 @@ export async function setBrandByline(brandId: string, on: boolean): Promise<void/** A brand's default author, or none (the organization byline): admins and managers. */export async function setDefaultAuthor(brandId: string, authorId: string | null): Promise<void> {+ await assertWritable();if (!z.guid().safeParse(brandId).success || (authorId && !z.guid().safeParse(authorId).success)) {throw new Error('invalid');}diff --git a/web/src/lib/actions/content-draft-inputs.ts b/web/src/lib/actions/content-draft-inputs.tsindex a9a0ca32a..666c0bafa 100644--- a/web/src/lib/actions/content-draft-inputs.ts+++ b/web/src/lib/actions/content-draft-inputs.ts@@ -8,6 +8,7 @@ import {type DraftInputs,} from '@/lib/content/draft-inputs';import { createClient } from '@/lib/supabase/server';+import { assertWritable } from '@/lib/subscription-guard';/*** Brief › Your input (Content Editor Quality spec §6, CE-048): the person's@@ -39,6 +40,7 @@ export async function getDraftInputs(id: string): Promise<DraftInputs> {/** Keeps the draft's input as given (all of it, as the editor holds it). */export async function saveDraftInputs(id: string, inputs: DraftInputs): Promise<DraftInputs> {+ await assertWritable();const parsed = draftInputsSchema.safeParse(inputs);if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');const supabase = await createClient();diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 4991e6f10..bc58190ff 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -115,6 +115,7 @@ import {type DraftSourceKind,type DraftSourcesData,} from '@/lib/content/sources';+import { assertWritable } from '@/lib/subscription-guard';/*** Content drafts (Content Editor, CE-002), read through the signed-in member's@@ -970,6 +971,7 @@ export async function startDraftFromAction(| { draftId: string; created: boolean; importFailed: boolean }| { error: 'invalid' | 'not_found' | 'failed' }> {+ await assertWritable();const parsed = actionStartInput.safeParse({ brandId, actionId, taskId, ...options });if (!parsed.success) return { error: 'invalid' };const { page } = parsed.data;@@ -1239,6 +1241,7 @@ export async function getContentOverlap(* stored as detected, so it follows the page (CE-023).*/export async function createContentDraft(brandId: string, start: DraftStart): Promise<string> {+ await assertWritable();const parsed = startInput.safeParse(start);if (!draftId.safeParse(brandId).success || !parsed.success) throw new Error('invalid');const { method, pageType, typePicked, source, bodyHtml, sourceUrl } = parsed.data;@@ -1327,6 +1330,7 @@ export async function saveContentDraft(base: { updatedAt: string; bodyHash: string; unconfirmedHash?: string };},): Promise<SaveDraftResult> {+ await assertWritable();if (typeof input?.bodyHtml === 'string' && input.bodyHtml.length > MAX_BODY_HTML_LENGTH) {return { ok: false, reason: 'too_large' };}@@ -1415,6 +1419,7 @@ const pageTypeInput = z.enum(PAGE_TYPES);* whatever the page says. Throws 'not_found' when no row changed.*/export async function setContentDraftPageType(id: string, pageType: PageType): Promise<void> {+ await assertWritable();if (!draftId.safeParse(id).success || !pageTypeInput.safeParse(pageType).success) {throw new Error('invalid');}@@ -1439,6 +1444,7 @@ const OTHER_ORGANIZATION = '23514';* is the same.*/export async function setContentDraftAuthor(id: string, authorId: string | null): Promise<void> {+ await assertWritable();if (!draftId.safeParse(id).success ||(authorId !== null && !z.guid().safeParse(authorId).success)@@ -1466,6 +1472,7 @@ export async function setContentDraftReviewer(id: string,reviewerId: string | null,): Promise<void> {+ await assertWritable();if (!draftId.safeParse(id).success ||(reviewerId !== null && !z.guid().safeParse(reviewerId).success)@@ -1494,6 +1501,7 @@ export async function confirmDraftAuthor(what: 'real' | 'profile',on: boolean,): Promise<void> {+ await assertWritable();if (!draftId.safeParse(id).success ||(what !== 'real' && what !== 'profile') ||@@ -1519,6 +1527,7 @@ export async function confirmDraftAuthor(* sources after; 'full' when the page keeps 50 already.*/export async function keepDraftSource(id: string, url: string): Promise<string[]> {+ await assertWritable();if (!draftId.safeParse(id).success || !keptSource.safeParse(url).success) {throw new Error('invalid');}@@ -1549,6 +1558,7 @@ export async function setContentDraftStatus(id: string,status: (typeof ROW_STATUSES)[number],): Promise<void> {+ await assertWritable();if (!draftId.safeParse(id).success || !(ROW_STATUSES as readonly string[]).includes(status)) {throw new Error('invalid');}@@ -1605,6 +1615,7 @@ async function unpublishOf(* managers; 00233's trigger refuses anyone else). It keeps its status.*/export async function archiveContentDraft(id: string, archived: boolean): Promise<void> {+ await assertWritable();if (!draftId.safeParse(id).success) throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabase@@ -1627,6 +1638,7 @@ export async function archiveContentDraft(id: string, archived: boolean): Promis* policy, 00233). Its versions, sources and suggestions go with it.*/export async function deleteContentDraft(id: string): Promise<void> {+ await assertWritable();if (!draftId.safeParse(id).success) throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabase.from('content_drafts').delete().eq('id', id).select('id');@@ -1658,6 +1670,7 @@ export async function markContentDraftReady(id: string,anyway?: { trust: number; reason: string | null; count: number | null },): Promise<{ status: DraftStatus; tasksDone: number }> {+ await assertWritable();if (!draftId.safeParse(id).success) throw new Error('invalid');const logged = anyway === undefined ? null : readyAnyway.safeParse(anyway);if (logged && !logged.success) throw new Error('invalid');@@ -1720,6 +1733,7 @@ export async function markContentDraftReady(export async function unmarkContentDraftReady(id: string,): Promise<{ status: DraftStatus; tasksReopened: number }> {+ await assertWritable();if (!draftId.safeParse(id).success) throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabase@@ -1883,6 +1897,7 @@ export async function getDraftHandoffs(id: string): Promise<DraftHandOff[]> {* another organization's.*/export async function restoreDraftVersion(id: string, versionId: string): Promise<RestoredDraft> {+ await assertWritable();if (!draftId.safeParse(id).success || !draftId.safeParse(versionId).success) {throw new Error('invalid');}@@ -1938,6 +1953,7 @@ export async function restoreDraftVersion(id: string, versionId: string): Promis* accepts. A failure is logged, not thrown: the suggestion can be undone.*/export async function keepAgentBeforeVersion(id: string): Promise<void> {+ await assertWritable();if (!draftId.safeParse(id).success) throw new Error('invalid');const supabase = await createClient();await keepVersion(supabase, id, 'agent_before');@@ -2053,6 +2069,7 @@ export async function decideDraftSuggestions(ids: string[],status: SuggestionStatus,): Promise<number> {+ await assertWritable();const parsed = decideInput.safeParse({ ids, status });if (!parsed.success) throw new Error('invalid');const supabase = await createClient();@@ -2132,6 +2149,7 @@ export async function setDraftSourceIncluded(id: string,choice: { kind: DraftSourceKind; ref: string; included: boolean },): Promise<void> {+ await assertWritable();const parsed = sourceChoice.safeParse(choice);if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');const supabase = await createClient();@@ -2175,6 +2193,7 @@ export type AddedDraftSource = z.infer<typeof addedSource>;* as added by hand. Throws 'not_found' when the draft isn't the member's.*/export async function addDraftSource(id: string, source: AddedDraftSource): Promise<void> {+ await assertWritable();const parsed = addedSource.safeParse(source);if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');const supabase = await createClient();@@ -2204,6 +2223,7 @@ const promptIdList = z.array(z.guid()).min(1).max(100);* 'not_found' when the draft isn't the member's.*/export async function addDraftPrompts(id: string, promptIds: string[]): Promise<void> {+ await assertWritable();const parsed = promptIdList.safeParse(promptIds);if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');const supabase = await createClient();@@ -2269,6 +2289,7 @@ export async function getDraftBrief(id: string): Promise<{ brief: DraftBrief | n/** Edit brief (CE-007): the brief as the person wrote it. Throws 'not_found' when no row changed. */export async function saveDraftBrief(id: string, brief: DraftBrief): Promise<DraftBrief> {+ await assertWritable();const parsed = draftBriefSchema.safeParse({ ...brief, origin: 'edit' });if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');// The column's 64 KB (00212): said, not a failed save.@@ -2585,6 +2606,7 @@ async function startAgentRun(* row changed.*/export async function saveDraftRules(id: string, rules: DraftRulesInput): Promise<void> {+ await assertWritable();const parsed = draftRulesSchema.safeParse(rules);if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');if (!draftRulesFit(parsed.data)) throw new Error('too_large');@@ -2645,6 +2667,7 @@ export async function saveMyRuleSet(pageType: PageType,set: SavedRuleSet,): Promise<void> {+ await assertWritable();const parsed = savedRuleSetSchema.safeParse(set);if (!draftId.safeParse(brandId).success ||@@ -2809,6 +2832,7 @@ export async function getOwnImages(id: string): Promise<string[]> {* is fine; 'full' when the draft keeps 50.*/export async function confirmOwnImage(id: string, src: string): Promise<'ok' | 'full'> {+ await assertWritable();if (!draftId.safeParse(id).success || !ownImageSrc.safeParse(src).success) {throw new Error('invalid');}@@ -2870,6 +2894,7 @@ export async function confirmDraftItem(kind: ConfirmationKind,key: string,): Promise<'ok' | 'full'> {+ await assertWritable();if (!draftId.safeParse(id).success ||!confirmationKind.safeParse(kind).success ||diff --git a/web/src/lib/actions/content-plan.ts b/web/src/lib/actions/content-plan.tsindex 837c8bcc2..489e2ff60 100644--- a/web/src/lib/actions/content-plan.ts+++ b/web/src/lib/actions/content-plan.ts@@ -20,6 +20,7 @@ import {type PlanTracking,} from '@/lib/content/plan';import { googleSourceStatus } from '@/lib/traffic-sources';+import { assertWritable } from '@/lib/subscription-guard';/*** What the Content plan (CE-014) is built from, read through the signed-in@@ -237,6 +238,7 @@ export async function setPlanRowPriority(rowKey: string,priority: boolean,): Promise<void> {+ await assertWritable();if (!markInput.safeParse({ brandId, rowKey }).success) throw new Error('invalid');const supabase = await createClient();const { data: user } = await supabase.auth.getUser();@@ -288,6 +290,7 @@ export async function getPlanPriorities(* agrees, and remembers the status it had for showing it again.*/export async function hidePlanRow(brandId: string, rowKey: string): Promise<void> {+ await assertWritable();if (!markInput.safeParse({ brandId, rowKey }).success) throw new Error('invalid');const opportunityId = checkedOpportunityId(rowKey);const supabase = await createClient();@@ -327,6 +330,7 @@ export async function hidePlanRow(brandId: string, rowKey: string): Promise<void* and only the mark goes.*/export async function showPlanRow(brandId: string, rowKey: string): Promise<void> {+ await assertWritable();if (!markInput.safeParse({ brandId, rowKey }).success) throw new Error('invalid');const opportunityId = checkedOpportunityId(rowKey);const supabase = await createClient();diff --git a/web/src/lib/actions/content-settings.ts b/web/src/lib/actions/content-settings.tsindex d91bdaa73..c482323e5 100644--- a/web/src/lib/actions/content-settings.ts+++ b/web/src/lib/actions/content-settings.ts@@ -2,6 +2,7 @@import { z } from 'zod';import { createClient } from '@/lib/supabase/server';+import { assertWritable } from '@/lib/subscription-guard';/** Settings › Content: a brand's Content Editor settings. */export interface ContentSettings {@@ -45,6 +46,7 @@ export async function getContentSettings(): Promise<ContentSettings | null> {* is refused.*/export async function setBrandQualityHandoff(brandId: string, on: boolean): Promise<void> {+ await assertWritable();if (!z.guid().safeParse(brandId).success || typeof on !== 'boolean') throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabasediff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.tsindex ab459a75c..55ff924ce 100644--- a/web/src/lib/actions/content.ts+++ b/web/src/lib/actions/content.ts@@ -5,6 +5,7 @@ import type { ContentBrief, ContentOpportunity, OpportunityBasket, WebhookConfigimport { API_BASE_URL } from '@/config/api';import { apiFailure, type ApiFailure } from '@/lib/api-failure';import type { ContentUsage } from '@/lib/content-usage';+import { assertWritable } from '@/lib/subscription-guard';const AEO_SERVER_URL = API_BASE_URL;@@ -632,6 +633,7 @@ export async function saveWebhookConfig(isActive?: boolean;},): Promise<WebhookConfig> {+ await assertWritable();const supabase = await createClient();const allowedEvents = ['opportunity.sent',diff --git a/web/src/lib/actions/getting-started.ts b/web/src/lib/actions/getting-started.tsindex 5a9bd60f5..5dcb74ce6 100644--- a/web/src/lib/actions/getting-started.ts+++ b/web/src/lib/actions/getting-started.ts@@ -15,6 +15,7 @@ import {parseGettingStartedFacts,type GettingStartedStatus,} from '@/lib/getting-started/steps';+import { assertWritable } from '@/lib/subscription-guard';/** The brand's steps, or null for a brand the caller can't see. */export async function getGettingStarted(brandId: string): Promise<GettingStartedStatus | null> {@@ -28,7 +29,8 @@ export async function getGettingStarted(brandId: string): Promise<GettingStarted/*** One of the explore pages was opened. Recorded once the brand's first* answers are in, so a page opened while it had nothing to show doesn't- * count. True when the step is recorded, now or before.+ * count. True when the step is recorded, now or before. Open while the+ * workspace is read-only: a trace of reading, which changes nothing.*/export async function markGettingStartedPageOpened(brandId: string,@@ -46,6 +48,7 @@ export async function markGettingStartedPageOpened(/** Skip an optional step (Search Console, Analytics). It counts as complete. */export async function skipGettingStartedStep(brandId: string, step: string): Promise<void> {+ await assertWritable();if (!GETTING_STARTED_STEPS.some((s) => s.key === step && s.optional)) {throw new Error('not an optional step');}@@ -66,6 +69,7 @@ export async function skipGettingStartedStep(brandId: string, step: string): Pro* steps finished meanwhile still count.*/export async function startGettingStarted(brandId: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('getting_started')@@ -81,6 +85,7 @@ export async function startGettingStarted(brandId: string): Promise<void> {* already done stay done, and Start brings it back.*/export async function skipGettingStarted(brandId: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { data, error } = await supabase.from('getting_started')diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.tsindex e1657b281..6ad2ce0ca 100644--- a/web/src/lib/actions/integrations.ts+++ b/web/src/lib/actions/integrations.ts@@ -2,6 +2,7 @@import { createClient } from '@/lib/supabase/server';import { API_BASE_URL } from '@/config/api';+import { assertWritable } from '@/lib/subscription-guard';/** Providers that expose the shared connect / status / disconnect flow. */export type IntegrationProvider =@@ -231,6 +232,7 @@ export async function getGscBrandMappings(): Promise<GscBrandMapping[]> {/** Persist a brand's property pick (null clears it). RLS: admin/manager. */export async function setBrandGscProperty(brandId: string, property: string | null): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('brands')@@ -289,6 +291,7 @@ export async function setBrandGaProperty(brandId: string,propertyId: string | null,): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('brands')diff --git a/web/src/lib/actions/kpis.ts b/web/src/lib/actions/kpis.tsindex 4cfa1c0c8..fca63c4dc 100644--- a/web/src/lib/actions/kpis.ts+++ b/web/src/lib/actions/kpis.ts@@ -37,6 +37,7 @@ import {import { presetKpiKeys, presetTarget } from '@/lib/kpis/presets';import { getInsightsSummary, getShareOfVoiceData, getVisibilityRateTrend } from './tracking';import { getTrafficSummary, getTrafficTrend } from './traffic';+import { assertWritable } from '@/lib/subscription-guard';const TREND_DAYS = 7;@@ -417,6 +418,7 @@ export async function saveKpiFramework(timeframe: KpiTimeframe,entries: KpiFrameworkEntry[],): Promise<void> {+ await assertWritable();if (entries.length === 0) throw new Error('empty framework');if (!(timeframe in TIMEFRAME_DAYS)) throw new Error('unknown timeframe');for (const entry of entries) {@@ -467,6 +469,7 @@ export async function saveKpiFramework(* would make a row vanish with no way back.*/export async function removeKpi(brandId: string, kpiKey: KpiKey): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('kpi_definitions')@@ -508,6 +511,7 @@ async function readPresets(brandId: string) {* without the function.*/export async function seedKpiPresets(brandId: string): Promise<boolean> {+ await assertWritable();const { entries } = await readPresets(brandId);const supabase = await createClient();const { data, error } = await supabase.rpc('seed_kpi_presets', {diff --git a/web/src/lib/actions/mentions.ts b/web/src/lib/actions/mentions.tsindex d5ab5e9be..c4d9f387c 100644--- a/web/src/lib/actions/mentions.ts+++ b/web/src/lib/actions/mentions.ts@@ -17,6 +17,7 @@ import {import { parseMentionsOverview, type MentionsOverview } from '@/lib/mentions-overview';import { parseMentionsPerception, type MentionsPerception } from '@/lib/mentions-perception';import type { Citation } from '@/types';+import { assertWritable } from '@/lib/subscription-guard';/*** The Mentions & Sentiment Overview's figures (MS-06) for a window and the@@ -215,6 +216,7 @@ export async function overrideMentionSentiment(| { changed: boolean; sentiment: MentionSentiment; override: SentimentOverride | null }| { error: 'forbidden' | 'invalid' | 'missing' | 'unknown'; message: string }> {+ await assertWritable();const supabase = await createClient();const { data, error } = await supabase.rpc('override_mention_sentiment', {p_result_id: resultId,diff --git a/web/src/lib/actions/menu-access.ts b/web/src/lib/actions/menu-access.tsindex a3d602f39..e7bf39749 100644--- a/web/src/lib/actions/menu-access.ts+++ b/web/src/lib/actions/menu-access.ts@@ -5,6 +5,7 @@ import { z } from 'zod';import { createClient } from '@/lib/supabase/server';import { supabaseAdmin } from '@/lib/supabase/admin';import { readMemberEmails } from '@/lib/member-emails';+import { assertWritable } from '@/lib/subscription-guard';import {WORK_AREA_IDS,canManageMenus,@@ -152,6 +153,7 @@ export async function getMenuAccessSettings(): Promise<MenuAccessSettings> {/** The sections a role doesn't see. */export async function setRoleMenu(role: MenuRole, hidden: string[]) {+ await assertWritable();const profile = await requireMenuManager();if (!MENU_ROLES.includes(role)) throw new Error('Nobody sets the admins’ menu');const parsed = sections.parse(hidden);@@ -174,6 +176,7 @@ export async function setRoleMenu(role: MenuRole, hidden: string[]) {* hides them, and hidden although it shows them. Empty both = the role's menu.*/export async function setMemberMenu(memberId: string, menu: { shown: string[]; hidden: string[] }) {+ await assertWritable();const profile = await requireMenuManager();const id = userId.parse(memberId);const shown = cleanMenuSections(sections.parse(menu.shown));@@ -201,6 +204,7 @@ export async function setMemberMenu(memberId: string, menu: { shown: string[]; h/** Lets a manager change menus, or takes it back. Admins only. */export async function setMenuManager(memberId: string, allowed: boolean) {+ await assertWritable();const profile = await currentProfile();if (profile.role !== 'admin') throw new Error('Only admins can choose who changes menus');const id = userId.parse(memberId);diff --git a/web/src/lib/actions/organization.ts b/web/src/lib/actions/organization.tsindex 5736dae87..60d3ea8b8 100644--- a/web/src/lib/actions/organization.ts+++ b/web/src/lib/actions/organization.ts@@ -4,6 +4,7 @@ import { createClient } from '@/lib/supabase/server';import { supabaseAdmin } from '@/lib/supabase/admin';import { revalidatePath } from 'next/cache';import { slugify } from '@/lib/slug';+import { assertWritable } from '@/lib/subscription-guard';// ---------------------------------------------------------------------------// Shared helpers (mirrors the pattern in team.ts)@@ -50,6 +51,7 @@ async function requireAdmin() {* any existing deep-links or external references that use the slug.*/export async function updateOrganizationName(name: string): Promise<void> {+ await assertWritable();const { profile } = await requireAdmin();const trimmed = name.trim();@@ -113,6 +115,8 @@ export async function getOrganization(): Promise<OrganizationInfo> {* 2. `auth.users.user_metadata.full_name` — so the Supabase JWT and* client-side `supabase.auth.getUser()` stay in sync without a* separate reload of the profile row.+ *+ * Open while the workspace is read-only: the person's own profile.*/export async function updateAccountName(name: string): Promise<void> {const supabase = await createClient();@@ -141,6 +145,7 @@ export async function updateAccountName(name: string): Promise<void> {}export async function createOrganization(name: string) {+ await assertWritable({ onboarding: true });const supabase = await createClient();const {diff --git a/web/src/lib/actions/prompt-suggestions.ts b/web/src/lib/actions/prompt-suggestions.tsindex 319bd4b17..128195315 100644--- a/web/src/lib/actions/prompt-suggestions.ts+++ b/web/src/lib/actions/prompt-suggestions.ts@@ -8,6 +8,7 @@ import { API_BASE_URL } from '@/config/api';// Types only — this file is `'use server'`, so the guards that go with them// live in a plain module (every runtime export here must be a server action).import type { PromptSuggestionSource, SuggestionSourceData } from '@/lib/prompt-suggestion-source';+import { assertWritable } from '@/lib/subscription-guard';const AEO_SERVER_URL = API_BASE_URL;@@ -312,6 +313,7 @@ export async function trackPagePrompts(pageUrl: string | null,prompts: { text: string; topic: string }[],): Promise<TrackPagePromptsResult> {+ await assertWritable();const wanted = (Array.isArray(prompts) ? prompts : []).filter((p) => typeof p?.text === 'string' && p.text.trim()).slice(0, MAX_PAGE_PROMPTS);diff --git a/web/src/lib/actions/prompt-workflow.ts b/web/src/lib/actions/prompt-workflow.tsindex 142ce07bf..efbfb11d5 100644--- a/web/src/lib/actions/prompt-workflow.ts+++ b/web/src/lib/actions/prompt-workflow.ts@@ -1,6 +1,7 @@'use server';import { createClient } from '@/lib/supabase/server';+import { assertWritable } from '@/lib/subscription-guard';/*** Prompt workflow (v1): per-prompt work status, a notes thread, and target@@ -97,6 +98,7 @@ export async function setPromptWorkStatus(promptId: string,status: PromptWorkStatus | null,): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('prompts')@@ -108,6 +110,7 @@ export async function setPromptWorkStatus(export type AddPromptNoteResult = { note: PromptNote } | { error: string };export async function addPromptNote(promptId: string, body: string): Promise<AddPromptNoteResult> {+ await assertWritable();const trimmed = body.trim();if (!trimmed) return { error: 'Note cannot be empty' };if (trimmed.length > 2000) return { error: 'Note is too long (max 2000 characters)' };@@ -138,6 +141,7 @@ export async function addPromptNote(promptId: string, body: string): Promise<Add}export async function deletePromptNote(noteId: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('prompt_notes').delete().eq('id', noteId);if (error) throw new Error(error.message);@@ -243,6 +247,7 @@ export async function addPromptTargetUrl(url: string,label?: string,): Promise<AddPromptTargetUrlResult> {+ await assertWritable();let normalized: string;try {normalized = normalizeTargetUrl(url);@@ -284,6 +289,7 @@ export async function addPromptTargetUrl(}export async function deletePromptTargetUrl(id: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('prompt_target_urls').delete().eq('id', id);if (error) throw new Error(error.message);diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 60f77a9fb..3fa730d05 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -28,6 +28,7 @@ import {type PlatformPositionRow,type PromptPositionCell,} from '@/lib/prompt-position-summary';+import { assertWritable } from '@/lib/subscription-guard';function filterByPlan(plan: Plan, platforms: string[], models: string[]) {const allowedScrapers = plan.limits.allowedScrapers@@ -198,6 +199,7 @@ export async function getPromptCapacity(* message (#427).*/export async function savePromptSet(input: SavePromptSetInput): Promise<SavePromptSetResult> {+ await assertWritable({ onboarding: true });const supabase = await createClient();const { organizationId: orgId, region: brandRegion } = await getBrandContext(@@ -312,6 +314,7 @@ export async function updatePrompt(models?: string[];},): Promise<Prompt> {+ await assertWritable();const supabase = await createClient();const payload: Record<string, unknown> = {};@@ -400,6 +403,7 @@ export async function updatePromptLocations(id: string,regionsInput: string[],): Promise<UpdatePromptLocationsResult> {+ await assertWritable();const supabase = await createClient();const regions = [...new Set(regionsInput.map((r) => r.trim().toUpperCase()))];@@ -493,6 +497,7 @@ export async function bulkUpdatePromptLocations(action: 'add' | 'remove',locationsInput: string[],): Promise<BulkUpdatePromptLocationsResult> {+ await assertWritable();const supabase = await createClient();const ids = [...new Set(promptIds)].filter(Boolean);@@ -606,6 +611,7 @@ export type AddPromptToSetResult = { prompt: Prompt } | { error: string; code?:* message (#427).*/export async function addPromptToSet(input: AddPromptInput): Promise<AddPromptToSetResult> {+ await assertWritable();const supabase = await createClient();const { data: ps } = await supabase@@ -689,6 +695,7 @@ export async function addPromptToBrand(brandId: string,input: { text: string; category?: string; platforms: string[]; models?: string[] },): Promise<AddPromptToBrandResult> {+ await assertWritable();const supabase = await createClient();const trimmed = input.text.trim();if (!trimmed) return { error: 'Prompt text is required.' };@@ -790,6 +797,7 @@ export async function setPromptActive(id: string,isActive: boolean,): Promise<SetPromptActiveResult> {+ await assertWritable();const supabase = await createClient();if (isActive) {@@ -840,6 +848,7 @@ export async function importPrompts(brandId: string,rows: ImportPromptRow[],): Promise<ImportPromptsResult> {+ await assertWritable();if (rows.length === 0) return { importedIdx: [], promptIds: [], analysisStarted: false };if (rows.length > 1000) return { error: 'Import at most 1,000 prompts at a time.' };const supabase = await createClient();@@ -939,6 +948,7 @@ export async function importPrompts(}export async function deletePrompt(id: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('prompts').delete().eq('id', id);@@ -958,6 +968,7 @@ export async function setPromptsActive(ids: string[],isActive: boolean,): Promise<SetPromptsActiveResult> {+ await assertWritable();if (ids.length === 0) return { updated: 0 };const supabase = await createClient();@@ -991,6 +1002,7 @@ export async function setPromptsActive(export async function deletePrompts(ids: string[],): Promise<{ deletedIds: string[] } | { error: string }> {+ await assertWritable();if (ids.length === 0) return { deletedIds: [] };if (ids.length > PROMPT_DELETE_BATCH) {return { error: `At most ${PROMPT_DELETE_BATCH} prompts per call.` };@@ -1003,6 +1015,7 @@ export async function deletePrompts(}export async function deletePromptSet(id: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('prompt_sets').delete().eq('id', id);diff --git a/web/src/lib/actions/read-only.test.ts b/web/src/lib/actions/read-only.test.tsnew file mode 100644index 000000000..b3e63cf8a--- /dev/null+++ b/web/src/lib/actions/read-only.test.ts@@ -0,0 +1,172 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Server actions on a read-only workspace (Ansvisor Cloud, plan not active):+ * one that writes refuses before it writes anything, and writes once the+ * plan is active; setup's writes stay open to an organization that never+ * subscribed; the person's own profile (their work areas too) and a+ * page-opened trace stay open.+ */++let org: { subscription_status: string | null; stripe_subscription_id: string | null };+let writes: string[];+/** What each update set, by table. */+let updates: { table: string; values: unknown }[];++/**+ * A query builder whose every call chains; records a write, resolves to+ * `row`, or to a list of it unless the query asked for one row.+ */+function query(table: string): unknown {+ const row =+ table === 'profiles'+ ? { organization_id: 'org-1', organizations: org }+ : table === 'brands'+ ? { id: 'brand-1', industry: null, shopping_mode_enabled: false }+ : table === 'prompts'+ ? { id: 'prompt-1', platforms: ['chatgpt'] }+ : { id: 'row-1', brand_id: 'brand-1', prompt_id: 'prompt-1', name: 'Acme', domain: '' };+ let one = false;+ const builder: unknown = new Proxy(+ {},+ {+ get: (_, prop) => {+ if (prop === 'then') {+ return (resolve: (value: unknown) => void) =>+ resolve({ data: one ? row : [row], error: null });+ }+ return (...args: unknown[]) => {+ if (prop === 'single' || prop === 'maybeSingle') one = true;+ if (['insert', 'update', 'upsert', 'delete'].includes(prop as string)) {+ writes.push(`${table}.${String(prop)}`);+ }+ if (prop === 'update') updates.push({ table, values: args[0] });+ return builder;+ };+ },+ },+ );+ return builder;+}++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ auth: {+ getUser: async () => ({ data: { user: { id: 'user-1' } } }),+ updateUser: async () => {+ writes.push('auth.updateUser');+ return { error: null };+ },+ },+ from: (table: string) => query(table),+ rpc: async (fn: string) => {+ writes.push(`rpc.${fn}`);+ return { data: true, error: null };+ },+ })),+}));+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));++const { SubscriptionInactiveError } = await import('@/lib/subscription-guard');+const { addCompetitor, deleteCompetitor } = await import('./competitor');+const { markBrandAsEcommerce, setBrandShoppingMode } = await import('./brand');+const { addPromptNote } = await import('./prompt-workflow');+const { markGettingStartedPageOpened } = await import('./getting-started');+const { updateAccountName } = await import('./organization');+const { setMemberMenu, setMenuManager, setMyWorkAreas, setRoleMenu } =+ await import('./menu-access');++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ org = { subscription_status: 'canceled', stripe_subscription_id: 'sub_1' };+ writes = [];+ updates = [];+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('server actions on a read-only workspace', () => {+ it('refuse before writing anything', async () => {+ await expect(addCompetitor('brand-1', { name: 'Acme', domain: 'acme.com' })).rejects.toThrow(+ SubscriptionInactiveError,+ );+ await expect(deleteCompetitor('row-1')).rejects.toThrow(SubscriptionInactiveError);+ await expect(addPromptNote('prompt-1', 'Check the answer')).rejects.toThrow(+ SubscriptionInactiveError,+ );+ expect(writes).toEqual([]);+ });++ it('write once the plan is active', async () => {+ org = { subscription_status: 'active', stripe_subscription_id: 'sub_1' };+ await addCompetitor('brand-1', { name: 'Acme', domain: 'acme.com' });+ await deleteCompetitor('row-1');+ await addPromptNote('prompt-1', 'Check the answer');+ expect(writes).toEqual(['competitors.insert', 'competitors.delete', 'prompt_notes.insert']);+ });++ it("let setup's writes through for an organization that never subscribed, and only those", async () => {+ org = { subscription_status: null, stripe_subscription_id: null };+ await addCompetitor('brand-1', { name: 'Acme', domain: 'acme.com' });+ await expect(deleteCompetitor('row-1')).rejects.toThrow(SubscriptionInactiveError);+ expect(writes).toEqual(['competitors.insert']);+ });++ it('let setup turn Shopping mode on for an organization that never subscribed', async () => {+ org = { subscription_status: null, stripe_subscription_id: null };+ await expect(markBrandAsEcommerce('brand-1')).resolves.toEqual({+ industry: 'E-commerce & Retail',+ promptsUpdated: 1,+ });+ expect(updates).toContainEqual({+ table: 'brands',+ values: { industry: 'E-commerce & Retail' },+ });+ expect(updates).toContainEqual({ table: 'brands', values: { shopping_mode_enabled: true } });+ expect(writes).toEqual([+ 'brands.update',+ 'brands.update',+ 'prompts.update',+ 'brand_platforms.upsert',+ ]);++ // Outside setup, the same change waits for a plan.+ writes = [];+ await expect(setBrandShoppingMode('brand-1', true)).rejects.toThrow(SubscriptionInactiveError);+ expect(writes).toEqual([]);+ });++ it("keep the person's own profile and a page-opened trace open", async () => {+ await updateAccountName('Ada');+ await markGettingStartedPageOpened('brand-1', 'visibility');+ expect(writes).toEqual([+ 'profiles.update',+ 'auth.updateUser',+ 'rpc.getting_started_page_opened',+ ]);+ });++ it('refuse a menu change, and keep answering "What do you work on?" open', async () => {+ await expect(setRoleMenu('analyst', ['content'])).rejects.toThrow(SubscriptionInactiveError);+ await expect(+ setMemberMenu('00000000-0000-4000-8000-000000000001', { shown: [], hidden: [] }),+ ).rejects.toThrow(SubscriptionInactiveError);+ await expect(setMenuManager('00000000-0000-4000-8000-000000000001', true)).rejects.toThrow(+ SubscriptionInactiveError,+ );+ expect(writes).toEqual([]);++ await setMyWorkAreas([]);+ expect(writes).toEqual(['profiles.update']);+ });++ it('never gate self-hosted', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ await addPromptNote('prompt-1', 'Check the answer');+ expect(writes).toEqual(['prompt_notes.insert']);+ });+});diff --git a/web/src/lib/actions/reports.ts b/web/src/lib/actions/reports.tsindex 6ee46a03a..df507650e 100644--- a/web/src/lib/actions/reports.ts+++ b/web/src/lib/actions/reports.ts@@ -29,6 +29,7 @@ import {type ReportSection,type ReportTemplateId,} from '@/lib/reports/templates';+import { assertWritable } from '@/lib/subscription-guard';/*** Simple Reports MVP — generate, list and delete immutable report snapshots.@@ -780,6 +781,7 @@ export async function createReport(sections?: ReportSection[];},): Promise<{ id: string }> {+ await assertWritable();const supabase = await createClient();const {data: { session },@@ -1024,6 +1026,7 @@ export async function getReport(id: string): Promise<Report | null> {}export async function deleteReport(id: string): Promise<void> {+ await assertWritable();const supabase = await createClient();const { error } = await supabase.from('reports').delete().eq('id', id);if (error) throw new Error(error.message);diff --git a/web/src/lib/actions/shopping-openai-index.ts b/web/src/lib/actions/shopping-openai-index.tsindex 03349b422..ab5132897 100644--- a/web/src/lib/actions/shopping-openai-index.ts+++ b/web/src/lib/actions/shopping-openai-index.ts@@ -4,6 +4,7 @@ import { z } from 'zod';import { createClient } from '@/lib/supabase/server';import type { OpenAiIndexRead } from '@/lib/shopping/openai-index';import { getShoppingMerchantSplit, type ShoppingDatePreset } from './shopping';+import { assertWritable } from '@/lib/subscription-guard';/*** What "Catalog in OpenAI's product index" reads (#1281): the brand's word@@ -40,6 +41,7 @@ export async function getOpenAiIndexRead(* change is refused.*/export async function setOpenAiProductFeed(brandId: string, on: boolean): Promise<void> {+ await assertWritable();if (!z.guid().safeParse(brandId).success || typeof on !== 'boolean') throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabasediff --git a/web/src/lib/actions/shopping-path.ts b/web/src/lib/actions/shopping-path.tsindex bba625c1f..cea9c0aa2 100644--- a/web/src/lib/actions/shopping-path.ts+++ b/web/src/lib/actions/shopping-path.ts@@ -14,6 +14,7 @@ import type {ShoppingProductCheck,} from '@/lib/content/shopping-check';import { readAllRpcRows } from '@/lib/supabase/rpc-pages';+import { assertWritable } from '@/lib/subscription-guard';import {NO_PATH_REASONS,bestInStock,@@ -81,6 +82,7 @@ export async function saveDraftShoppingPath(read: { builtAt: string; savedAt?: string | null },choices: ShoppingChoices,): Promise<{ path: ShoppingPath } | { error: 'changed' }> {+ await assertWritable();const at = readAt.safeParse(read);const chosen = shoppingChoicesSchema.safeParse(choices);if (!guid.safeParse(draftId).success || !at.success || !chosen.success) {diff --git a/web/src/lib/actions/signals.ts b/web/src/lib/actions/signals.tsindex 74cd45073..0f6b813cd 100644--- a/web/src/lib/actions/signals.ts+++ b/web/src/lib/actions/signals.ts@@ -24,6 +24,7 @@ import {import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';import { readPromptPlaces } from '@/lib/signals/prompt-places';import type { ActionStatus } from '@/lib/action-center/registry';+import { assertWritable } from '@/lib/subscription-guard';export type { Signal } from '@/lib/signals/map';@@ -203,6 +204,7 @@ export async function updateSignalStatus(signalIds: string[],status: SignalStatus,): Promise<void> {+ await assertWritable();if (signalIds.length === 0) return;const supabase = await createClient();const { data: before } = await supabasediff --git a/web/src/lib/actions/team.ts b/web/src/lib/actions/team.tsindex 0f7d71315..672cf6d18 100644--- a/web/src/lib/actions/team.ts+++ b/web/src/lib/actions/team.ts@@ -6,6 +6,7 @@ import { createClient } from '@/lib/supabase/server';import { supabaseAdmin } from '@/lib/supabase/admin';import { readMemberEmails } from '@/lib/member-emails';import { enforceLimit, getOrgPlan } from '@/lib/guards/plan-guard';+import { assertWritable } from '@/lib/subscription-guard';export type TeamRole = 'admin' | 'manager' | 'analyst' | 'agency_partner';@@ -163,6 +164,7 @@ export type InviteMemberResult = { inviteLink: string; emailSent: boolean } | {* meaningless digest string (#550).*/export async function inviteMember(email: string, role: TeamRole): Promise<InviteMemberResult> {+ await assertWritable();const { user, profile } = await requireAdmin();const normalizedEmail = email.trim().toLowerCase();@@ -273,6 +275,7 @@ export async function inviteMember(email: string, role: TeamRole): Promise<Invitreturn { inviteLink: shareLink, emailSent };}+/** Open while the workspace is read-only: it takes back access, never gives it. */export async function revokeInvitation(invitationId: string) {const { profile } = await requireAdmin();const supabase = await createClient();@@ -288,6 +291,7 @@ export async function revokeInvitation(invitationId: string) {}export async function resendInvitation(invitationId: string) {+ await assertWritable();const { profile } = await requireAdmin();const { data: invitation, error } = await supabaseAdmin@@ -325,6 +329,7 @@ export async function resendInvitation(invitationId: string) {}export async function updateMemberRole(userId: string, role: TeamRole) {+ await assertWritable();const { user, profile } = await requireAdmin();if (userId === user.id) {@@ -341,6 +346,7 @@ export async function updateMemberRole(userId: string, role: TeamRole) {revalidatePath('/dashboard/settings');}+/** Open while the workspace is read-only: it takes back access, never gives it. */export async function removeMember(userId: string) {const { user, profile } = await requireAdmin();@@ -378,6 +384,9 @@ export type AcceptInvitationResult = { organizationId: string; role: TeamRole }* server action, so the most actionable message in this flow — telling the* user which email to sign in with — would otherwise reach them as the* meaningless digest string (#550).+ *+ * Open while the workspace is read-only: the invited person's own account+ * joins, and finds the workspace read-only.*/export async function acceptInvitation(token: string): Promise<AcceptInvitationResult> {const supabase = await createClient();diff --git a/web/src/lib/actions/topic.ts b/web/src/lib/actions/topic.tsindex 35da038e4..c7202a0ab 100644--- a/web/src/lib/actions/topic.ts+++ b/web/src/lib/actions/topic.ts@@ -5,6 +5,7 @@ import { computeAiVisibilityScore } from '@/lib/visibility-score';import { API_BASE_URL } from '@/config/api';import type { Topic } from '@/types';import { DAY_MS, topicTrendDays, type TopicsWindow } from '@/lib/topic-trend';+import { assertWritable } from '@/lib/subscription-guard';import { TOPIC_NAME_CHARS, topicNameFits } from '@/lib/topic-names';export type { TopicsWindow } from '@/lib/topic-trend';@@ -27,6 +28,7 @@ function assertTopicNames(names: string[]) {}export async function createTopics(brandId: string, names: string[]): Promise<Topic[]> {+ await assertWritable({ onboarding: true });assertTopicNames(names);const supabase = await createClient();@@ -82,6 +84,7 @@ export async function getTopicById(brandId: string, topicId: string): Promise<To}export async function createTopic(brandId: string, name: string): Promise<Topic> {+ await assertWritable();assertTopicNames([name]);const supabase = await createClient();@@ -96,6 +99,7 @@ export async function createTopic(brandId: string, name: string): Promise<Topic>}export async function updateTopic(topicId: string, name: string): Promise<Topic> {+ await assertWritable();assertTopicNames([name]);const supabase = await createClient();@@ -438,6 +442,7 @@ export async function getTopicsOverview(}export async function deleteTopic(topicId: string): Promise<void> {+ await assertWritable();const supabase = await createClient();// Fetch topic to get name and brand_iddiff --git a/web/src/lib/api-failure.test.ts b/web/src/lib/api-failure.test.tsindex 8680ff2f1..62bddd766 100644--- a/web/src/lib/api-failure.test.ts+++ b/web/src/lib/api-failure.test.ts@@ -67,6 +67,15 @@ describe('isSubscriptionInactive', () => {expect(isSubscriptionInactive(new Error(JSON.stringify(body)).message)).toBe(true);});+ it("reads a server action's refusal by its digest, all production keeps of it", () => {+ const masked = 'An error occurred in the Server Components render.';+ const refusal = Object.assign(new Error(masked), { digest: 'subscription_inactive' });+ expect(isSubscriptionInactive(refusal)).toBe(true);+ expect(isSubscriptionInactive(Object.assign(new Error(masked), { digest: '1234' }))).toBe(+ false,+ );+ });+it('is false for anything else', () => {expect(isSubscriptionInactive({ error: 'plan_limit' })).toBe(false);expect(isSubscriptionInactive('Failed to fetch the chat response.')).toBe(false);diff --git a/web/src/lib/api-failure.ts b/web/src/lib/api-failure.tsindex 1ecef5535..5c95c9e81 100644--- a/web/src/lib/api-failure.ts+++ b/web/src/lib/api-failure.ts@@ -48,7 +48,9 @@ export function apiFailure(status: number, body: Record<string, unknown> = {}):/*** Whether a response body is the server's subscription_inactive (a read-only* workspace), also when it comes as text: the AI SDK's chat transport throws- * an error whose message is the response body.+ * an error whose message is the response body. A server action refused by+ * assertWritable (lib/subscription-guard.ts) throws an error whose digest is+ * the code, the one thing production keeps of it.*/export function isSubscriptionInactive(body: unknown): boolean {let value = body;@@ -59,9 +61,7 @@ export function isSubscriptionInactive(body: unknown): boolean {return false;}}- return (- typeof value === 'object' &&- value !== null &&- (value as { code?: unknown }).code === 'subscription_inactive'- );+ if (typeof value !== 'object' || value === null) return false;+ const { code, digest } = value as { code?: unknown; digest?: unknown };+ return code === 'subscription_inactive' || digest === 'subscription_inactive';}diff --git a/web/src/lib/mcp/subscription-gate.ts b/web/src/lib/mcp/subscription-gate.tsindex fa8994317..47a393ba9 100644--- a/web/src/lib/mcp/subscription-gate.ts+++ b/web/src/lib/mcp/subscription-gate.ts@@ -1,23 +1,27 @@import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';-import { NextResponse } from 'next/server';import { isCloud, isSubscriptionActive } from '@/config/plans';import { supabaseAdmin } from '@/lib/supabase/admin';+import {+ SUBSCRIPTION_INACTIVE,+ SubscriptionInactiveError,+ failedCallResponse,+ subscriptionInactiveResponse,+} from '@/lib/subscription-guard';/*** Ansvisor Cloud's read-only mode on the API key surface (MCP tools, the* /api/mcp REST routes): while a workspace's plan isn't active — its trial* ended, or it was canceled — reading stays open and anything that writes,* runs or spends answers with the server's 402 body, as the dashboard's- * upgrade dialog reads it. Self-hosted is never gated.+ * upgrade dialog reads it. Self-hosted is never gated. The refusal itself is+ * shared with the web app's own writes (lib/subscription-guard.ts).*/-export const SUBSCRIPTION_INACTIVE = {- error: 'plan_limit',- code: 'subscription_inactive',- message:- "This workspace's plan isn't active (its free trial ended or it was canceled), so it is " +- 'read-only: reading still works, but nothing can be changed, run or generated until an ' +- 'admin chooses a plan in Settings › Billing.',-} as const;+export {+ SUBSCRIPTION_INACTIVE,+ SubscriptionInactiveError,+ failedCallResponse,+ subscriptionInactiveResponse,+};/*** The tools that only read: open while read-only. Any other tool — a new one@@ -39,16 +43,6 @@ export async function subscriptionActiveFor(organizationId: string | null): Promreturn isSubscriptionActive(data?.subscription_status as string | null | undefined);}-/** A call that writes, runs or spends, refused while the workspace is read-only. */-export class SubscriptionInactiveError extends Error {- readonly code = SUBSCRIPTION_INACTIVE.code;-- constructor() {- super(SUBSCRIPTION_INACTIVE.message);- this.name = 'SubscriptionInactiveError';- }-}-/*** Refuse a costly call (the server's internal endpoints: a brief, a Site* Audit, an Improve action) while the workspace is read-only, whoever calls@@ -58,22 +52,6 @@ export async function assertSubscriptionActive(organizationId: string | null): Pif (!(await subscriptionActiveFor(organizationId))) throw new SubscriptionInactiveError();}-/** The REST routes' answer to a write while read-only. */-export function subscriptionInactiveResponse(): NextResponse {- return NextResponse.json(SUBSCRIPTION_INACTIVE, { status: 402 });-}--/**- * A REST route's answer to a call that threw: 402 subscription_inactive when- * a costly call was refused (assertSubscriptionActive), else 500 with the- * error's message.- */-export function failedCallResponse(err: unknown): NextResponse {- if (err instanceof SubscriptionInactiveError) return subscriptionInactiveResponse();- const message = err instanceof Error ? err.message : 'Failed';- return NextResponse.json({ error: message }, { status: 500 });-}-/** A tool's answer to a call while read-only: a tool error carrying the same body. */export function subscriptionInactiveToolResult() {return {diff --git a/web/src/lib/subscription-guard-coverage.test.ts b/web/src/lib/subscription-guard-coverage.test.tsnew file mode 100644index 000000000..bf0f5aa8e--- /dev/null+++ b/web/src/lib/subscription-guard-coverage.test.ts@@ -0,0 +1,417 @@+// @vitest-environment node+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import ts from 'typescript';+import { describe, expect, it } from 'vitest';++/**+ * Every write the web app makes straight to Supabase checks the plan first,+ * read from the code: each server action in lib/actions that writes —+ * itself or through a helper in its file — calls assertWritable, and each+ * POST, PUT, PATCH or DELETE route under app/api checks the plan, unless it+ * is named below with why it stays open while the workspace is read-only.+ * A new write is gated, or named here, before it ships.+ *+ * A write is .insert/.update/.upsert/.delete on a .from() query, a storage+ * change (a signed upload address too), an auth change, or an RPC whose+ * database function isn't declared STABLE or IMMUTABLE (supabase/schema.sql).+ * A query or bucket kept in a name first (`const images = ….storage.from(…)`)+ * is followed to it.+ *+ * The check comes first: it is the first thing a gated action awaits. And a+ * setup action (assertWritable({ onboarding: true })) never runs one in its+ * file that checks without it — that check would refuse the organization+ * setup lets through.+ */++const ACTIONS_DIR = join(__dirname, 'actions');+const API_DIR = join(__dirname, '../app/api');+const SCHEMA = join(__dirname, '../../../supabase/schema.sql');++/**+ * Server actions that write and stay open while read-only: file:function →+ * why. One that writes through the API (a fetch that posts, puts, patches or+ * deletes) is named here when the API keeps that route open too.+ */+const OPEN_ACTIONS: Record<string, string> = {+ 'organization.ts:updateAccountName': "the person's own profile",+ 'team.ts:acceptInvitation': "the invited person's own account joins",+ 'team.ts:revokeInvitation': 'takes back access, never gives it',+ 'team.ts:removeMember': 'takes back access, never gives it',+ 'getting-started.ts:markGettingStartedPageOpened': 'a trace of reading a page',+ 'content-images.ts:prepareImageUpload':+ 'checks the plan itself (isSubscriptionActive), to answer "plan" instead of throwing',+ 'brand.ts:deleteBrand':+ 'deleting a brand only removes what the person gave us (Ansvisor, 2026-10-27)',+ 'menu-access.ts:setMyWorkAreas':+ 'the person\'s own profile; it answers "What do you work on?", which /dashboard/welcome waits on',+};++/** Write routes that stay open while read-only: path:METHOD → why. */+const OPEN_ROUTES: Record<string, string> = {+ 'aeo/[...path]:POST': 'a proxy to the API, which answers 402 itself',+ 'aeo/[...path]:PUT': 'a proxy to the API, which answers 402 itself',+ 'aeo/[...path]:PATCH': 'a proxy to the API, which answers 402 itself',+ 'aeo/[...path]:DELETE': 'a proxy to the API, which answers 402 itself',+ 'agent/conversations/[id]:DELETE': 'deleting a conversation starts no cost',+ 'keys:POST': 'a key costs nothing and only reads while read-only (2026-10-14 decision)',+ 'keys/[id]:DELETE': 'revoking a key takes back access',+ 'mcp:POST': 'its tools are gated one by one (gateWriteTools)',+ 'mcp:DELETE': 'ends an MCP session',+ 'settings/ai-providers:DELETE': 'removing a key takes back access',+ 'stripe/checkout:POST': 'billing: choosing a plan',+ 'stripe/portal:POST': 'billing: the payment method',+ 'stripe/promo-code:POST': 'billing: checking a promo code',+ 'stripe/subscription:PATCH': 'billing: changing the plan',+ 'stripe/subscription:DELETE': 'billing: canceling the plan',+ 'stripe/webhook:POST': "Stripe's own calls",+ 'traffic/read:POST': 'reads only',+};++/** What checks a route's plan before it writes. */+const ROUTE_GATES = new Set([+ 'writeRefusal',+ 'assertWritable',+ 'subscriptionActiveFor',+ 'assertSubscriptionActive',+ 'authenticateMcpRequest',+]);++const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);+const DB_WRITES = new Set(['insert', 'update', 'upsert', 'delete']);+const STORAGE_WRITES = new Set([+ 'upload',+ 'update',+ 'remove',+ 'move',+ 'copy',+ 'createSignedUploadUrl',+]);++/** The database functions that only read: their last definition is STABLE or IMMUTABLE. */+function readOnlyFunctions(): Set<string> {+ const sql = readFileSync(SCHEMA, 'utf8');+ const volatility = new Map<string, boolean>();+ const create = /create\s+(?:or\s+replace\s+)?function\s+(?:"?public"?\.)?"?(\w+)"?\s*\(/gi;+ for (const match of sql.matchAll(create)) {+ const rest = sql.slice(match.index);+ const open = /\bas\s+(\$\w*\$)/i.exec(rest);+ if (!open) continue;+ const close = rest.indexOf(open[1], open.index + open[0].length);+ if (close < 0) continue;+ const end = rest.indexOf(';', close + open[1].length);+ const declared = rest.slice(0, open.index) + rest.slice(close, end < 0 ? undefined : end);+ volatility.set(match[1], /\b(stable|immutable)\b/i.test(declared));+ }+ return new Set([...volatility].filter(([, reads]) => reads).map(([name]) => name));+}++interface FunctionFacts {+ exported: boolean;+ writes: string[];+ /** Its fetches that change something through the API: `DELETE`, `POST`… */+ apiWrites: string[];+ gates: string[];+ /** It calls assertWritable() without `onboarding: true`. */+ strictGate: boolean;+ /** It calls assertWritable({ onboarding: true }). */+ onboardingGate: boolean;+ /** What it awaits first, outside the functions inside it: the callee's name, else the text. */+ firstAwait: string | null;+ callees: string[];+}++/** What a file names with `const`/`let`, by name: `images` → `supabase.storage.from(…)`. */+type Bindings = Map<string, ts.Expression>;++function readBindings(source: ts.SourceFile): Bindings {+ const bound: Bindings = new Map();+ const visit = (n: ts.Node) => {+ if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.initializer) {+ bound.set(n.name.text, n.initializer);+ }+ ts.forEachChild(n, visit);+ };+ visit(source);+ return bound;+}++/**+ * The chain a call hangs off: `supabase.from('x').select()` → true for+ * `.from`. A name is followed to what it was given, and a one-line arrow+ * to what it returns: `const uploads = () => admin.from('x')`.+ */+function chainCalls(node: ts.Expression, name: string, bound: Bindings): boolean {+ let current: ts.Expression = node;+ const followed = new Set<string>();+ for (;;) {+ if (ts.isCallExpression(current)) {+ const callee = current.expression;+ if (ts.isPropertyAccessExpression(callee) && callee.name.text === name) return true;+ current = callee;+ } else if (ts.isPropertyAccessExpression(current)) {+ if (current.name.text === name) return true;+ current = current.expression;+ } else if (ts.isAwaitExpression(current) || ts.isParenthesizedExpression(current)) {+ current = current.expression;+ } else if (ts.isArrowFunction(current) && !ts.isBlock(current.body)) {+ current = current.body;+ } else if (ts.isIdentifier(current) && bound.has(current.text) && !followed.has(current.text)) {+ followed.add(current.text);+ current = bound.get(current.text)!;+ } else {+ return false;+ }+ }+}++/** The first await in a function's own body, in source order: not in the functions inside it. */+function firstAwaitIn(root: ts.Node): string | null {+ let found: string | null = null;+ const visit = (n: ts.Node) => {+ if (found !== null) return;+ if (n !== root && ts.isFunctionLike(n)) return;+ if (ts.isAwaitExpression(n)) {+ const awaited = n.expression;+ found =+ ts.isCallExpression(awaited) && ts.isIdentifier(awaited.expression)+ ? awaited.expression.text+ : awaited.getText().slice(0, 60);+ return;+ }+ ts.forEachChild(n, visit);+ };+ visit(root);+ return found;+}++/** The top-level functions of a file: what each writes, which gates it calls, and its callees there. */+function readFunctions(+ file: string,+ readRpcs: Set<string>,+ gateNames: Set<string>,+): Map<string, FunctionFacts> {+ const source = ts.createSourceFile(+ file,+ readFileSync(file, 'utf8'),+ ts.ScriptTarget.Latest,+ true,+ );+ const bound = readBindings(source);+ const bodies = new Map<string, { node: ts.Node; exported: boolean }>();+ const isExported = (node: ts.Node) =>+ ts.canHaveModifiers(node) &&+ (ts.getModifiers(node) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword);+ for (const statement of source.statements) {+ if (ts.isFunctionDeclaration(statement) && statement.name && statement.body) {+ bodies.set(statement.name.text, { node: statement.body, exported: isExported(statement) });+ } else if (ts.isVariableStatement(statement)) {+ for (const declaration of statement.declarationList.declarations) {+ const init = declaration.initializer;+ if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {+ bodies.set(declaration.name.getText(source), {+ node: init,+ exported: isExported(statement),+ });+ }+ }+ }+ }++ const facts = new Map<string, FunctionFacts>();+ for (const [name, { node, exported }] of bodies) {+ const fact: FunctionFacts = {+ exported,+ writes: [],+ apiWrites: [],+ gates: [],+ strictGate: false,+ onboardingGate: false,+ firstAwait: firstAwaitIn(node),+ callees: [],+ };+ const visit = (n: ts.Node) => {+ if (ts.isCallExpression(n)) {+ const callee = n.expression;+ if (ts.isPropertyAccessExpression(callee)) {+ const method = callee.name.text;+ const target = callee.expression;+ if (chainCalls(target, 'storage', bound) && STORAGE_WRITES.has(method)) {+ fact.writes.push(`storage.${method}`);+ } else if (DB_WRITES.has(method) && chainCalls(target, 'from', bound)) {+ fact.writes.push(method);+ } else if (method === 'rpc') {+ const arg = n.arguments[0];+ const fn = arg && ts.isStringLiteralLike(arg) ? arg.text : '?';+ if (!readRpcs.has(fn)) fact.writes.push(`rpc ${fn}`);+ } else if (+ method === 'updateUser' ||+ (chainCalls(target, 'admin', bound) &&+ chainCalls(target, 'auth', bound) &&+ !['listUsers', 'getUserById'].includes(method))+ ) {+ fact.writes.push(`auth.${method}`);+ }+ } else if (ts.isIdentifier(callee)) {+ const called = callee.text;+ const opensMcpWrites = n.arguments.some((a) => /gateWrites:\s*false/.test(a.getText()));+ if (gateNames.has(called) && !opensMcpWrites) fact.gates.push(called);+ if (called === 'assertWritable') {+ const onboarding = n.arguments.some((a) => /onboarding:\s*true/.test(a.getText()));+ if (onboarding) fact.onboardingGate = true;+ else fact.strictGate = true;+ }+ if (bodies.has(called)) fact.callees.push(called);+ if (+ called === 'fetch' &&+ n.arguments[1] &&+ ts.isObjectLiteralExpression(n.arguments[1])+ ) {+ for (const prop of n.arguments[1].properties) {+ if (+ ts.isPropertyAssignment(prop) &&+ prop.name.getText() === 'method' &&+ ts.isStringLiteralLike(prop.initializer) &&+ WRITE_METHODS.has(prop.initializer.text)+ ) {+ fact.apiWrites.push(prop.initializer.text);+ }+ }+ }+ }+ }+ ts.forEachChild(n, visit);+ };+ visit(node);+ facts.set(name, fact);+ }+ return facts;+}++/** What a function writes and which gates it calls, through the helpers in its file. */+function reach(facts: Map<string, FunctionFacts>, name: string) {+ const writes = new Set<string>();+ const apiWrites = new Set<string>();+ const gates = new Set<string>();+ const seen = new Set<string>();+ const walk = (current: string) => {+ if (seen.has(current)) return;+ seen.add(current);+ const fact = facts.get(current)!;+ fact.writes.forEach((w) => writes.add(w));+ fact.apiWrites.forEach((w) => apiWrites.add(w));+ fact.gates.forEach((g) => gates.add(g));+ fact.callees.forEach(walk);+ };+ walk(name);+ return { writes: [...writes], apiWrites: [...apiWrites], gated: gates.size > 0 };+}++function routeFiles(dir: string): string[] {+ return readdirSync(dir).flatMap((entry) => {+ const path = join(dir, entry);+ if (statSync(path).isDirectory()) return routeFiles(path);+ return entry === 'route.ts' ? [path] : [];+ });+}++const readRpcs = readOnlyFunctions();++/** The server action files ('use server' in lib/actions), each with its functions. */+const actionFiles = readdirSync(ACTIONS_DIR)+ .filter((f) => f.endsWith('.ts') && !f.endsWith('.test.ts'))+ .filter((f) => /^['"]use server['"]/m.test(readFileSync(join(ACTIONS_DIR, f), 'utf8')))+ .map((file) => ({+ file,+ facts: readFunctions(join(ACTIONS_DIR, file), readRpcs, new Set(['assertWritable'])),+ }));++describe('read-only coverage', () => {+ it('reads which database functions only read', () => {+ // A sample each way, so a schema the parser can't read fails here.+ expect(readRpcs.has('mentions_list')).toBe(true);+ expect(readRpcs.has('insights_aggregates_daily')).toBe(true);+ expect(readRpcs.has('import_prompts')).toBe(false);+ expect(readRpcs.has('content_draft_snapshot')).toBe(false);+ });++ it('has every server action that writes call assertWritable, or name why it stays open', () => {+ const ungated: string[] = [];+ const writers = new Set<string>();+ const apiWriters = new Set<string>();+ const gatedOpen: string[] = [];+ for (const { file, facts } of actionFiles) {+ for (const [name, fact] of facts) {+ if (!fact.exported) continue;+ const { writes, apiWrites, gated } = reach(facts, name);+ const key = `${file}:${name}`;+ if (apiWrites.length) apiWriters.add(key);+ if (key in OPEN_ACTIONS && gated) gatedOpen.push(key);+ // A write through the API is the API's to refuse (requireActiveSubscription).+ if (!writes.length) continue;+ writers.add(key);+ if (!(key in OPEN_ACTIONS) && !gated) ungated.push(`${key} (${writes.join(', ')})`);+ }+ }+ expect(ungated).toEqual([]);+ // The open list stays true: each one writes, here or through the API, and doesn't check after all.+ expect(+ Object.keys(OPEN_ACTIONS).filter((key) => !writers.has(key) && !apiWriters.has(key)),+ ).toEqual([]);+ expect(gatedOpen).toEqual([]);+ // Sanity: the scan finds the writes it is meant to.+ expect(writers.size).toBeGreaterThan(90);+ });++ it('has every gated action check the plan before anything else it awaits', () => {+ const late: string[] = [];+ for (const { file, facts } of actionFiles) {+ for (const [name, fact] of facts) {+ const key = `${file}:${name}`;+ if (!fact.exported || key in OPEN_ACTIONS || !reach(facts, name).writes.length) continue;+ if (fact.firstAwait !== 'assertWritable') {+ late.push(`${key} (awaits ${fact.firstAwait ?? 'nothing'} first)`);+ }+ }+ }+ expect(late).toEqual([]);+ });++ it("has no setup action run a function in its file whose check refuses setup's organization", () => {+ // A setup action is open to an organization that never subscribed; a+ // plain assertWritable() it runs on the way would refuse that one.+ const refused: string[] = [];+ for (const { file, facts } of actionFiles) {+ for (const [name, fact] of facts) {+ if (!fact.onboardingGate) continue;+ const seen = new Set([name]);+ const walk = (callee: string) => {+ if (seen.has(callee)) return;+ seen.add(callee);+ const called = facts.get(callee)!;+ if (called.strictGate) refused.push(`${file}:${name} → ${callee}`);+ called.callees.forEach(walk);+ };+ fact.callees.forEach(walk);+ }+ }+ expect(refused).toEqual([]);+ });++ it('has every write route check the plan, or name why it stays open', () => {+ const ungated: string[] = [];+ const handlers = new Set<string>();+ for (const path of routeFiles(API_DIR)) {+ const route = relative(API_DIR, path).replace(/\/route\.ts$/, '');+ const facts = readFunctions(path, readRpcs, ROUTE_GATES);+ for (const [name, fact] of facts) {+ if (!fact.exported || !WRITE_METHODS.has(name)) continue;+ const key = `${route}:${name}`;+ handlers.add(key);+ if (!(key in OPEN_ROUTES) && !reach(facts, name).gated) ungated.push(key);+ }+ }+ expect(ungated).toEqual([]);+ expect(Object.keys(OPEN_ROUTES).filter((key) => !handlers.has(key))).toEqual([]);+ });+});diff --git a/web/src/lib/subscription-guard.test.ts b/web/src/lib/subscription-guard.test.tsnew file mode 100644index 000000000..ed9180474--- /dev/null+++ b/web/src/lib/subscription-guard.test.ts@@ -0,0 +1,150 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The web app's own writes on a read-only workspace (Ansvisor Cloud, plan not+ * active): assertWritable reads the signed-in person's organization, with+ * their profile in one query, and refuses unless its plan is active; setup's+ * writes stay open to an organization that never subscribed; a plan it can't+ * read refuses too. Self-hosted reads nothing.+ */++let user: { id: string } | null;+let profile: { organization_id: string | null } | null;+let profileError: { message: string } | null;+/** The profile's organization, as the embed reads it (null when RLS hides it). */+let org: { subscription_status: string | null; stripe_subscription_id: string | null } | null;+let reads: string[];++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ auth: { getUser: async () => ({ data: { user } }) },+ from: (table: string) => {+ const query = {+ select: (columns: string) => {+ reads.push(`${table}: ${columns}`);+ return query;+ },+ eq: () => query,+ maybeSingle: async () => ({+ data: profile && {+ ...profile,+ organizations: profile.organization_id ? org : null,+ },+ error: profileError,+ }),+ };+ return query;+ },+ })),+}));++const { assertWritable, SubscriptionInactiveError, writeRefusal } =+ await import('./subscription-guard');++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ user = { id: 'user-1' };+ profile = { organization_id: 'org-1' };+ profileError = null;+ org = { subscription_status: 'canceled', stripe_subscription_id: 'sub_1' };+ reads = [];+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('assertWritable', () => {+ it('lets an active or trialing plan write', async () => {+ for (const status of ['active', 'trialing']) {+ org = { subscription_status: status, stripe_subscription_id: 'sub_1' };+ await expect(assertWritable()).resolves.toBeUndefined();+ }+ });++ it('reads the organization with the profile, in one query', async () => {+ await assertWritable().catch(() => {});+ expect(reads).toEqual([+ 'profiles: organization_id, organizations(subscription_status, stripe_subscription_id)',+ ]);+ });++ it('refuses a plan that ended, a failed payment and an unfinished first payment', async () => {+ for (const status of ['canceled', 'past_due', 'unpaid', 'incomplete_expired', null]) {+ org = { subscription_status: status, stripe_subscription_id: 'sub_1' };+ await expect(assertWritable()).rejects.toBeInstanceOf(SubscriptionInactiveError);+ // An ended plan's setup writes are refused too.+ await expect(assertWritable({ onboarding: true })).rejects.toBeInstanceOf(+ SubscriptionInactiveError,+ );+ }+ });++ it("opens setup's writes to an organization that never subscribed, and only those", async () => {+ org = { subscription_status: null, stripe_subscription_id: null };+ await expect(assertWritable({ onboarding: true })).resolves.toBeUndefined();+ await expect(assertWritable()).rejects.toBeInstanceOf(SubscriptionInactiveError);+ });++ it('opens setup to a person with no organization yet', async () => {+ profile = { organization_id: null };+ await expect(assertWritable({ onboarding: true })).resolves.toBeUndefined();+ await expect(assertWritable()).rejects.toBeInstanceOf(SubscriptionInactiveError);+ });++ it("refuses when the plan can't be read, without calling it read-only", async () => {+ profileError = { message: 'connection reset' };+ for (const call of [() => assertWritable(), () => assertWritable({ onboarding: true })]) {+ const failure = await call().catch((err: unknown) => err);+ expect(failure).toBeInstanceOf(Error);+ expect(failure).not.toBeInstanceOf(SubscriptionInactiveError);+ expect((failure as Error).message).toContain('connection reset');+ }+ });++ it('refuses a missing profile or organization, and no one signed in', async () => {+ profile = null;+ await expect(assertWritable()).rejects.toBeInstanceOf(SubscriptionInactiveError);+ profile = { organization_id: 'org-1' };+ org = null;+ await expect(assertWritable()).rejects.toBeInstanceOf(SubscriptionInactiveError);+ user = null;+ await expect(assertWritable()).rejects.toThrow('Unauthorized');+ });++ it('never gates self-hosted, and reads nothing there', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ user = null;+ await expect(assertWritable()).resolves.toBeUndefined();+ expect(reads).toEqual([]);+ });++ it("carries the code as its digest, which production keeps of a server action's error", () => {+ const err = new SubscriptionInactiveError();+ expect(err.digest).toBe('subscription_inactive');+ expect(err.code).toBe('subscription_inactive');+ });+});++describe('writeRefusal', () => {+ it('lets an active plan through', async () => {+ org = { subscription_status: 'active', stripe_subscription_id: 'sub_1' };+ expect(await writeRefusal()).toBeNull();+ });++ it('answers 402 subscription_inactive while read-only', async () => {+ const res = await writeRefusal();+ expect(res?.status).toBe(402);+ expect(await res?.json()).toMatchObject({+ error: 'plan_limit',+ code: 'subscription_inactive',+ });+ });++ it("answers 500 when the plan can't be read", async () => {+ profileError = { message: 'timeout' };+ const res = await writeRefusal();+ expect(res?.status).toBe(500);+ });+});diff --git a/web/src/lib/subscription-guard.ts b/web/src/lib/subscription-guard.tsnew file mode 100644index 000000000..7d7d0d475--- /dev/null+++ b/web/src/lib/subscription-guard.ts@@ -0,0 +1,112 @@+import { NextResponse } from 'next/server';+import { isCloud, isSubscriptionActive } from '@/config/plans';+import { createClient } from '@/lib/supabase/server';++/**+ * Ansvisor Cloud's read-only mode for the web app's own writes: while a+ * workspace's plan isn't active — its trial ended, or it was canceled — the+ * server actions and Next routes that write straight to Supabase refuse, as+ * the API's requireActiveSubscription refuses its writes and the MCP surface+ * its tools (lib/mcp/subscription-gate.ts). The buttons are guarded already;+ * this keeps the rule when an action is called anyway. Self-hosted is never+ * gated.+ */+export const SUBSCRIPTION_INACTIVE = {+ error: 'plan_limit',+ code: 'subscription_inactive',+ message:+ "This workspace's plan isn't active (its free trial ended or it was canceled), so it is " ++ 'read-only: reading still works, but nothing can be changed, run or generated until an ' ++ 'admin chooses a plan in Settings › Billing.',+} as const;++/**+ * A call that writes, runs or spends, refused while the workspace is+ * read-only. Its digest is the code: production masks a server action's+ * error but keeps a digest it was thrown with, so the browser can still tell+ * this refusal (isSubscriptionInactive in lib/api-failure.ts) and open the+ * upgrade dialog.+ */+export class SubscriptionInactiveError extends Error {+ readonly code = SUBSCRIPTION_INACTIVE.code;+ readonly digest = SUBSCRIPTION_INACTIVE.code;++ constructor() {+ super(SUBSCRIPTION_INACTIVE.message);+ this.name = 'SubscriptionInactiveError';+ }+}++/** The REST routes' answer to a write while read-only. */+export function subscriptionInactiveResponse(): NextResponse {+ return NextResponse.json(SUBSCRIPTION_INACTIVE, { status: 402 });+}++/**+ * A REST route's answer to a call that threw: 402 subscription_inactive when+ * it was refused (assertWritable, assertSubscriptionActive), else 500 with+ * the error's message.+ */+export function failedCallResponse(err: unknown): NextResponse {+ if (err instanceof SubscriptionInactiveError) return subscriptionInactiveResponse();+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+}++/**+ * Refuse a write while the signed-in person's workspace is read-only, before+ * anything is written. On the cloud it reads their organization through+ * their session and throws SubscriptionInactiveError unless its subscription+ * is active or trialing. A plan that can't be read refuses too (an Error),+ * and so does a call with no one signed in.+ *+ * `onboarding`: setup's own writes (the organization, the brand, its topics,+ * prompts and competitors), open to an organization that never had a+ * subscription, so setup works before its plan step — as the API's+ * ONBOARDING_ROUTES. A plan that ended still refuses them.+ */+export async function assertWritable({+ onboarding = false,+}: { onboarding?: boolean } = {}): Promise<void> {+ if (!isCloud()) return;+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) throw new Error('Unauthorized');++ // The organization comes with the profile (profiles_organization_id_fkey): one round trip.+ const { data: profile, error } = await supabase+ .from('profiles')+ .select('organization_id, organizations(subscription_status, stripe_subscription_id)')+ .eq('id', user.id)+ .maybeSingle();+ if (error) throw new Error(`Could not read the workspace's plan: ${error.message}`);+ if (!profile) throw new SubscriptionInactiveError();+ // Setup creates the organization first: without one, nothing was ever subscribed.+ if (!profile.organization_id) {+ if (onboarding) return;+ throw new SubscriptionInactiveError();+ }++ const org = profile.organizations;+ if (!org) throw new SubscriptionInactiveError();+ if (isSubscriptionActive(org.subscription_status)) return;+ // Never subscribed: the Stripe subscription id, which only billing writes, stays once given.+ if (onboarding && !org.stripe_subscription_id) return;+ throw new SubscriptionInactiveError();+}++/**+ * A Next route's check before it writes: null when it may, else its answer —+ * 402 subscription_inactive while read-only, 500 when the plan can't be read.+ * Call it after the route's own sign-in check, so a missing session stays a 401.+ */+export async function writeRefusal(): Promise<NextResponse | null> {+ try {+ await assertWritable();+ return null;+ } catch (err) {+ return failedCallResponse(err);+ }+}