Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(settings): keep the server Supabase client out of Roles & access, so the web build passes (#1796)
Cihan9e0e67b259cb
diff --git a/web/src/lib/chat/plan-facts.ts b/web/src/lib/chat/plan-facts.tsindex 9aead6a6f..fa2e4991a 100644--- a/web/src/lib/chat/plan-facts.ts+++ b/web/src/lib/chat/plan-facts.ts@@ -9,7 +9,7 @@ import {type PlanId,type PlanLimits,} from '@/config/plans';-import { planFromOrgRow } from '@/lib/guards/plan-guard';+import { planFromOrgRow } from '@/lib/guards/plan-row';import type { PlanGate } from './registry/define-tool';/**@@ -54,7 +54,7 @@ export interface PlanFacts {nextPlan: NextPlan | null;}-/** The organization columns the facts read (plan-guard's ORG_PLAN_COLUMNS). */+/** The organization columns the facts read (plan-row's ORG_PLAN_COLUMNS). */export type OrgPlanRow = {plan?: unknown;subscription_status?: unknown;@@ -88,7 +88,7 @@ function nextPlanOf(id: PlanId, isTrial: boolean): NextPlan | null {};}-/** The facts for an organization row with its plan columns (plan-guard's ORG_PLAN_COLUMNS). */+/** The facts for an organization row with its plan columns (plan-row's ORG_PLAN_COLUMNS). */export function planFactsFromOrgRow(row: OrgPlanRow): PlanFacts {if (!isCloud()) {const plan = PLANS.self_hosted;diff --git a/web/src/lib/guards/plan-guard.ts b/web/src/lib/guards/plan-guard.tsindex 1dd6203f3..1e168ea89 100644--- a/web/src/lib/guards/plan-guard.ts+++ b/web/src/lib/guards/plan-guard.ts@@ -6,9 +6,13 @@ import {getPlan,hasFeature,isCloud,- isSubscriptionActive,isWithinLimit,} from '@/config/plans';+import { planFromOrgRow } from './plan-row';++// The row-to-plan reads moved to plan-row.ts, which client components can+// import; kept here for the server callers that already read them from here.+export { ORG_PLAN_COLUMNS, planFromOrgRow, usagePlanFromOrgRow } from './plan-row';export async function getOrgPlan(organizationId: string): Promise<Plan> {if (!isCloud()) return getPlan('self_hosted');@@ -23,60 +27,6 @@ export async function getOrgPlan(organizationId: string): Promise<Plan> {return planFromOrgRow(data);}-/** The organization columns {@link planFromOrgRow} reads. */-export const ORG_PLAN_COLUMNS = 'plan, subscription_status, plan_overrides';--/**- * The plan an organization row is entitled to, for callers that read the row- * themselves (the MCP server has no user session, so it reads with the- * service role).- */-export function planFromOrgRow(- data: { plan?: unknown; subscription_status?: unknown; plan_overrides?: unknown } | null,-): Plan {- if (!isCloud()) return getPlan('self_hosted');-- // `trialing` is a paid plan in its trial window — treat it as active so- // trial customers get their actual plan's limits (seats, brands, prompts…)- // instead of being silently dropped to starter.- if (!isSubscriptionActive(data?.subscription_status as string | null | undefined)) {- return getPlan('starter');- }-- return ownPlan(data);-}--/** The plan the organization's row names, Enterprise's overrides merged. */-function ownPlan(data: { plan?: unknown; plan_overrides?: unknown } | null): Plan {- const plan = getPlan(data?.plan as string | null | undefined);-- // Enterprise orgs can have custom limit overrides- if (data?.plan === 'enterprise' && data.plan_overrides) {- const overrides = data.plan_overrides as Record<string, unknown>;- return {- ...plan,- limits: { ...plan.limits, ...overrides } as typeof plan.limits,- };- }-- return plan;-}--/**- * The plan to show an organization's usage against: while its subscription- * is active, the one it's entitled to; once it has ended (read-only, the- * Choose a plan step), the plan it was on, marked ended, not Starter's,- * which it never chose. What choosing a plan again gives it back.- */-export function usagePlanFromOrgRow(- data: { plan?: unknown; subscription_status?: unknown; plan_overrides?: unknown } | null,-): { plan: Plan; ended: boolean } {- if (isCloud() && !isSubscriptionActive(data?.subscription_status as string | null | undefined)) {- return { plan: ownPlan(data), ended: true };- }- return { plan: planFromOrgRow(data), ended: false };-}-export class PlanLimitError extends Error {public readonly requiredPlan: string;diff --git a/web/src/lib/guards/plan-row.test.ts b/web/src/lib/guards/plan-row.test.tsnew file mode 100644index 000000000..983118e84--- /dev/null+++ b/web/src/lib/guards/plan-row.test.ts@@ -0,0 +1,91 @@+// @vitest-environment node+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++/**+ * A client component must not reach the server's Supabase client+ * (lib/supabase/server.ts, which imports next/headers): the production build+ * fails on it, as it did when Settings › Roles & access reached plan-guard.ts+ * through lib/chat/plan-facts.ts. This walks the imports from every+ * 'use client' file, stopping at 'use server' modules (they are called, not+ * bundled) and skipping type-only imports.+ */++const SRC = resolve(__dirname, '../..');+const SERVER_ONLY = [join(SRC, 'lib/supabase/server.ts')];++function files(dir: string): string[] {+ return readdirSync(dir).flatMap((name) => {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) return files(path);+ return /\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name) ? [path] : [];+ });+}++function resolveImport(from: string, spec: string): string | null {+ let base: string;+ if (spec.startsWith('@/')) base = join(SRC, spec.slice(2));+ else if (spec.startsWith('.')) base = resolve(dirname(from), spec);+ else return null;+ for (const candidate of [`${base}.ts`, `${base}.tsx`, join(base, 'index.ts'), base]) {+ if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;+ }+ return null;+}++const IMPORT = /^\s*(import|export)\s+(type\s+)?([^'"]*?)\s*from\s*['"]([^'"]+)['"]/gm;++function runtimeImports(path: string): string[] {+ const source = readFileSync(path, 'utf8');+ const out: string[] = [];+ for (const match of source.matchAll(IMPORT)) {+ const [, , typeOnly, clause, spec] = match;+ if (typeOnly) continue;+ // `import { type A, type B } from …` is elided like `import type`.+ const named = clause.match(/^\{([^}]*)\}$/);+ if (+ named &&+ named[1]+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)+ .every((s) => s.startsWith('type '))+ )+ continue;+ const target = resolveImport(path, spec);+ if (target) out.push(target);+ }+ return out;+}++const isDirective = (path: string, directive: string) =>+ new RegExp(`^\\s*['"]${directive}['"]`).test(readFileSync(path, 'utf8'));++function serverOnlyPath(start: string): string[] | null {+ const seen = new Set<string>([start]);+ const queue: string[][] = [[start]];+ while (queue.length) {+ const chain = queue.shift()!;+ const current = chain[chain.length - 1];+ if (SERVER_ONLY.includes(current)) return chain;+ if (current !== start && isDirective(current, 'use server')) continue;+ for (const next of runtimeImports(current)) {+ if (seen.has(next)) continue;+ seen.add(next);+ queue.push([...chain, next]);+ }+ }+ return null;+}++describe('client components and the server Supabase client', () => {+ it('never reach lib/supabase/server.ts', () => {+ const reached = files(SRC)+ .filter((path) => isDirective(path, 'use client'))+ .map(serverOnlyPath)+ .filter((chain): chain is string[] => chain !== null)+ .map((chain) => chain.map((p) => p.slice(SRC.length + 1)).join(' → '));+ expect(reached).toEqual([]);+ });+});diff --git a/web/src/lib/guards/plan-row.ts b/web/src/lib/guards/plan-row.tsnew file mode 100644index 000000000..97f968d64--- /dev/null+++ b/web/src/lib/guards/plan-row.ts@@ -0,0 +1,62 @@+import { type Plan, getPlan, isCloud, isSubscriptionActive } from '@/config/plans';++/**+ * Reading an organization row's plan, with no database client: plan-guard.ts+ * imports the server's Supabase client (next/headers), so client components+ * that need a row's plan (Settings › Roles & access through lib/chat) read it+ * from here.+ */++/** The organization columns {@link planFromOrgRow} reads. */+export const ORG_PLAN_COLUMNS = 'plan, subscription_status, plan_overrides';++/**+ * The plan an organization row is entitled to, for callers that read the row+ * themselves (the MCP server has no user session, so it reads with the+ * service role).+ */+export function planFromOrgRow(+ data: { plan?: unknown; subscription_status?: unknown; plan_overrides?: unknown } | null,+): Plan {+ if (!isCloud()) return getPlan('self_hosted');++ // `trialing` is a paid plan in its trial window — treat it as active so+ // trial customers get their actual plan's limits (seats, brands, prompts…)+ // instead of being silently dropped to starter.+ if (!isSubscriptionActive(data?.subscription_status as string | null | undefined)) {+ return getPlan('starter');+ }++ return ownPlan(data);+}++/** The plan the organization's row names, Enterprise's overrides merged. */+function ownPlan(data: { plan?: unknown; plan_overrides?: unknown } | null): Plan {+ const plan = getPlan(data?.plan as string | null | undefined);++ // Enterprise orgs can have custom limit overrides+ if (data?.plan === 'enterprise' && data.plan_overrides) {+ const overrides = data.plan_overrides as Record<string, unknown>;+ return {+ ...plan,+ limits: { ...plan.limits, ...overrides } as typeof plan.limits,+ };+ }++ return plan;+}++/**+ * The plan to show an organization's usage against: while its subscription+ * is active, the one it's entitled to; once it has ended (read-only, the+ * Choose a plan step), the plan it was on, marked ended, not Starter's,+ * which it never chose. What choosing a plan again gives it back.+ */+export function usagePlanFromOrgRow(+ data: { plan?: unknown; subscription_status?: unknown; plan_overrides?: unknown } | null,+): { plan: Plan; ended: boolean } {+ if (isCloud() && !isSubscriptionActive(data?.subscription_status as string | null | undefined)) {+ return { plan: ownPlan(data), ended: true };+ }+ return { plan: planFromOrgRow(data), ended: false };+}