Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

chore: Decouple plans from the builder as much as possible (#5687)

Oleg Isonence3c82b5826f
diff --git a/apps/builder/app/env/env.server.ts b/apps/builder/app/env/env.server.ts
index f62ef5e8e1..834d7a2eef 100644
--- a/apps/builder/app/env/env.server.ts
+++ b/apps/builder/app/env/env.server.ts
@@ -1,81 +1,148 @@
-// @todo zod parse env, make explicit types i.e
-const env = {
+import { z } from "zod";
+
+const envSchema = z.object({
// Authentication
+ DEV_LOGIN: z.string().optional(),
+ GH_CLIENT_ID: z.string().optional(),
+ GH_CLIENT_SECRET: z.string().optional(),
+ GOOGLE_CLIENT_ID: z.string().optional(),
+ GOOGLE_CLIENT_SECRET: z.string().optional(),
+
+ // Secret session key, context encode
+ AUTH_SECRET: z.string().optional(),
+
+ // DEPLOYMENT_ENVIRONMENT development | preview | production
+ DEPLOYMENT_ENVIRONMENT: z
+ .enum(["development", "preview", "production"])
+ .optional(),
+ DEPLOYMENT_URL: z.string().url().optional(),
+
+ // Trpc on SaaS
+ TRPC_SERVER_URL: z.string().url().optional(),
+ TRPC_SERVER_API_TOKEN: z.string().optional(),
+
+ PORT: z
+ .string()
+ .optional()
+ .transform((val) => (val ? parseInt(val, 10) : undefined)),
+
+ // Assets
+ MAX_UPLOAD_SIZE: z.string().optional(),
+
+ // Remote assets
+ S3_ENDPOINT: z.string().optional(),
+ S3_REGION: z.string().optional(),
+ S3_ACCESS_KEY_ID: z.string().optional(),
+ S3_SECRET_ACCESS_KEY: z.string().optional(),
+ S3_BUCKET: z.string().optional(),
+ S3_ACL: z.string().optional(),
+
+ // Origin for /cdn-cgi/image/ cloudflare endpoint (without ending slash)
+ RESIZE_ORIGIN: z.string().url().optional(),
+
+ // Entri API credentials
+ ENTRI_APPLICATION_ID: z.string().default("webstudio"),
+ ENTRI_SECRET: z.string().optional(),
+
+ // Projects as templates in dashboard (comma-separated IDs)
+ PROJECT_TEMPLATES: z
+ .string()
+ .default("")
+ .transform((val) =>
+ val
+ .split(",")
+ .map((id) => id.trim())
+ .filter(Boolean)
+ ),
+
+ PUBLISHER_HOST: z.string().default("wstd.work"),
+
+ STAGING_USERNAME: z.string().default("admin"),
+ STAGING_PASSWORD: z.string().default("webstudio"),
+
+ FEATURE_FLAGS: z.string().default(""),
+
+ // Plan definitions for local dev/staging (JSON array of {name, features})
+ PLANS: z
+ .string()
+ .default("[]")
+ .refine((val) => {
+ try {
+ JSON.parse(val);
+ return true;
+ } catch {
+ return false;
+ }
+ }, "PLANS must be valid JSON"),
+
+ POSTGREST_URL: z.string().url().default("http://localhost:3000"),
+ POSTGREST_API_KEY: z.string().default(""),
+
+ // Payment worker configuration
+ PAYMENT_WORKER_URL: z.string().optional(),
+ PAYMENT_WORKER_TOKEN: z.string().optional(),
+
+ // Used for project oauth login flow
+ AUTH_WS_CLIENT_ID: z.string().default("12345"),
+ AUTH_WS_CLIENT_SECRET: z.string().default("12345678"),
+
+ // Vercel system variables
+ VERCEL: z.string().optional(),
+ VERCEL_ENV: z.enum(["development", "preview", "production"]).optional(),
+ VERCEL_URL: z.string().optional(),
+});
+
+const rawEnv = {
DEV_LOGIN: process.env.DEV_LOGIN,
GH_CLIENT_ID: process.env.GH_CLIENT_ID,
GH_CLIENT_SECRET: process.env.GH_CLIENT_SECRET,
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
-
- // Secret session key, context encode
AUTH_SECRET: process.env.AUTH_SECRET,
-
- // DEPLOYMENT_ENVIRONMENT development | preview | production
DEPLOYMENT_ENVIRONMENT: process.env.DEPLOYMENT_ENVIRONMENT,
DEPLOYMENT_URL: process.env.DEPLOYMENT_URL,
-
- // Trpc on SaaS
TRPC_SERVER_URL: process.env.TRPC_SERVER_URL,
TRPC_SERVER_API_TOKEN: process.env.TRPC_SERVER_API_TOKEN,
-
PORT: process.env.PORT,
-
- // Assets
MAX_UPLOAD_SIZE: process.env.MAX_UPLOAD_SIZE,
-
- // Remote assets
S3_ENDPOINT: process.env.S3_ENDPOINT,
S3_REGION: process.env.S3_REGION,
S3_ACCESS_KEY_ID: process.env.S3_ACCESS_KEY_ID,
S3_SECRET_ACCESS_KEY: process.env.S3_SECRET_ACCESS_KEY,
S3_BUCKET: process.env.S3_BUCKET,
S3_ACL: process.env.S3_ACL,
- /**
- * Origin of service implementing /cdn-cgi/image/ cloudflare endpoint
- * without ending slash
- */
RESIZE_ORIGIN: process.env.RESIZE_ORIGIN,
-
- /**
- * Entri API credentials
- */
- ENTRI_APPLICATION_ID: process.env.ENTRI_APPLICATION_ID ?? "webstudio",
+ ENTRI_APPLICATION_ID: process.env.ENTRI_APPLICATION_ID,
ENTRI_SECRET: process.env.ENTRI_SECRET,
+ PROJECT_TEMPLATES: process.env.PROJECT_TEMPLATES,
+ PUBLISHER_HOST: process.env.PUBLISHER_HOST,
+ STAGING_USERNAME: process.env.STAGING_USERNAME,
+ STAGING_PASSWORD: process.env.STAGING_PASSWORD,
+ FEATURE_FLAGS: process.env.FEATURE_FLAGS,
+ PLANS: process.env.PLANS,
+ POSTGREST_URL: process.env.POSTGREST_URL,
+ POSTGREST_API_KEY: process.env.POSTGREST_API_KEY,
+ PAYMENT_WORKER_URL: process.env.PAYMENT_WORKER_URL,
+ PAYMENT_WORKER_TOKEN: process.env.PAYMENT_WORKER_TOKEN,
+ AUTH_WS_CLIENT_ID: process.env.AUTH_WS_CLIENT_ID,
+ AUTH_WS_CLIENT_SECRET: process.env.AUTH_WS_CLIENT_SECRET,
+ VERCEL: process.env.VERCEL,
+ VERCEL_ENV: process.env.VERCEL_ENV,
+ VERCEL_URL: process.env.VERCEL_URL,
+};
- /**
- * Projects as templates in dashboard
- */
- PROJECT_TEMPLATES:
- process.env.PROJECT_TEMPLATES?.split(",").map((projectId) =>
- projectId.trim()
- ) ?? [],
-
- PUBLISHER_HOST: process.env.PUBLISHER_HOST || "wstd.work",
-
- STAGING_USERNAME: process.env.STAGING_USERNAME ?? "admin",
- STAGING_PASSWORD: process.env.STAGING_PASSWORD ?? "webstudio",
-
- FEATURE_FLAGS: process.env.FEATURE_FLAGS ?? "",
-
- // Plan definitions for local dev / staging.
- // JSON array of {name, features} objects; features are validated against PlanFeaturesSchema,
- // then all entries are merged together (booleans: any, numbers: max).
- // Example: PLANS='[{"name":"Pro","features":{"canDownloadAssets":true,"maxWorkspaces":5}}]'
- PLANS: process.env.PLANS ?? "[]",
-
- POSTGREST_URL: process.env.POSTGREST_URL ?? "http://localhost:3000",
- POSTGREST_API_KEY: process.env.POSTGREST_API_KEY ?? "",
+const parseResult = envSchema.safeParse(rawEnv);
- /** Payment worker base URL (e.g. https://apps.webstudio.is/builder-payments) */
- PAYMENT_WORKER_URL: process.env.PAYMENT_WORKER_URL ?? "",
- /** Shared secret token for authenticating requests to the payment worker */
- PAYMENT_WORKER_TOKEN: process.env.PAYMENT_WORKER_TOKEN ?? "",
+if (!parseResult.success) {
+ console.error("Invalid environment variables:", parseResult.error.format());
+ throw new Error(
+ `Environment validation failed: ${parseResult.error.message}`
+ );
+}
+const env = {
+ ...parseResult.data,
SECURE_COOKIE: true,
-
- // Used for project oauth login flow
- AUTH_WS_CLIENT_ID: process.env.AUTH_WS_CLIENT_ID ?? "12345",
- AUTH_WS_CLIENT_SECRET: process.env.AUTH_WS_CLIENT_SECRET ?? "12345678",
};
// Reject default OAuth secrets in production.
@@ -94,7 +161,11 @@ export type ServerEnv = typeof env;
// https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables
if (process.env.VERCEL !== undefined) {
if (env.DEPLOYMENT_ENVIRONMENT === undefined) {
- env.DEPLOYMENT_ENVIRONMENT = process.env.VERCEL_ENV;
+ env.DEPLOYMENT_ENVIRONMENT = process.env.VERCEL_ENV as
+ | "development"
+ | "preview"
+ | "production"
+ | undefined;
}
if (env.DEPLOYMENT_URL === undefined) {
env.DEPLOYMENT_URL = process.env.VERCEL_URL;
diff --git a/apps/builder/app/routes/_ui.(builder).tsx b/apps/builder/app/routes/_ui.(builder).tsx
index b595d28cd8..593d3d10a1 100644
--- a/apps/builder/app/routes/_ui.(builder).tsx
+++ b/apps/builder/app/routes/_ui.(builder).tsx
@@ -20,7 +20,8 @@ import {
authorizeProject,
} from "@webstudio-is/trpc-interface/index.server";
import { createContext } from "~/shared/context.server";
-import { getPlanInfo } from "~/shared/db/plan-features.server";
+import { getPlanInfo } from "@webstudio-is/trpc-interface/plan-client";
+import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";
import { dashboardPath, isBuilder, isDashboard } from "~/shared/router-utils";
import env from "~/env/env.server";
@@ -183,12 +184,13 @@ export const loader = async (loaderArgs: LoaderFunctionArgs) => {
throw workspace.error;
}
- const planResult = await getPlanInfo(
- workspace.data.userId,
- context.postgrest
- );
- context.planFeatures = planResult.planFeatures;
- context.purchases = planResult.purchases;
+ const planResult = await getPlanInfo([workspace.data.userId], context);
+ const ownerPlan = planResult.get(workspace.data.userId) ?? {
+ planFeatures: defaultPlanFeatures,
+ purchases: [],
+ };
+ context.planFeatures = ownerPlan.planFeatures;
+ context.purchases = ownerPlan.purchases;
// Determine the current user's relation to the workspace
if (
@@ -200,7 +202,7 @@ export const loader = async (loaderArgs: LoaderFunctionArgs) => {
// When the workspace owner has downgraded, members lose access.
// Data stays intact but permissions are suspended.
- if (planResult.planFeatures.maxWorkspaces <= 1) {
+ if (ownerPlan.planFeatures.maxWorkspaces <= 1) {
throw new AuthorizationError(
"The workspace owner's plan no longer supports workspace access"
);
diff --git a/apps/builder/app/routes/_ui.login._index.tsx b/apps/builder/app/routes/_ui.login._index.tsx
index 873cd52f30..63be3ec243 100644
--- a/apps/builder/app/routes/_ui.login._index.tsx
+++ b/apps/builder/app/routes/_ui.login._index.tsx
@@ -8,7 +8,7 @@ import { useLoaderData, type MetaFunction } from "@remix-run/react";
import { findAuthenticatedUser } from "~/services/auth.server";
import env from "~/env/env.server";
import type { LoginProps } from "~/auth/index.client";
-import { parsePlansEnv } from "~/shared/db/plan-features.server";
+import { parsePlansEnv } from "@webstudio-is/trpc-interface/plan-features";
import { useLoginErrorMessage } from "~/shared/session";
import {
comparePathnames,
diff --git a/apps/builder/app/routes/auth.dev.tsx b/apps/builder/app/routes/auth.dev.tsx
index f6cdd66f42..635ce5feee 100644
--- a/apps/builder/app/routes/auth.dev.tsx
+++ b/apps/builder/app/routes/auth.dev.tsx
@@ -5,91 +5,13 @@ import { AUTH_PROVIDERS } from "~/shared/session";
import { clearReturnToCookie, returnToPath } from "~/services/cookie.server";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
import { redirect, setNoStoreToRedirect } from "~/services/no-store-redirect";
+import { applyDevPlan } from "~/services/dev-plan.server";
import { createPostgrestContext } from "~/shared/context.server";
export default function Dev() {
return null;
}
-/**
- * Upsert or delete dev plan rows in the DB for the given user email.
- * This lets getPlanInfo work naturally (same as production) for all callers,
- * including getOwnerPlanFeatures for shared-workspace suspension checks.
- *
- * - Plan selected: upsert a Product row (id = "dev-product-{planName}") and a
- * TransactionLog row (eventId = "dev-{userId}") that satisfies the UserProduct view.
- * - No plan selected: delete the TransactionLog row so the user has no active purchase.
- */
-const applyDevPlan = async (email: string, planName: string | null) => {
- const postgrest = createPostgrestContext();
-
- // Resolve userId from email (user was already created by the authenticator).
- const userResult = await postgrest.client
- .from("User")
- .select("id")
- .eq("email", email)
- .single();
-
- if (userResult.error) {
- console.error("[applyDevPlan] Failed to find user:", userResult.error);
- return;
- }
-
- const userId = userResult.data?.id as string | undefined;
- if (!userId) {
- console.error("[applyDevPlan] No user found for email:", email);
- return;
- }
-
- if (planName !== null) {
- const productId = `dev-product-${planName}`;
-
- const productResult = await postgrest.client.from("Product").upsert({
- id: productId,
- name: planName,
- meta: {},
- features: [],
- images: [],
- });
- if (productResult.error) {
- console.error(
- "[applyDevPlan] Failed to upsert Product:",
- productResult.error
- );
- return;
- }
-
- const txResult = await postgrest.client.from("TransactionLog").upsert({
- eventId: `dev-${userId}`,
- userId,
- productId,
- eventData: {
- type: "checkout.session.completed",
- created: Math.floor(Date.now() / 1000),
- data: { object: { status: "complete" } },
- },
- });
- if (txResult.error) {
- console.error(
- "[applyDevPlan] Failed to upsert TransactionLog:",
- txResult.error
- );
- }
- } else {
- // Remove any existing dev plan row — the user becomes free tier.
- const deleteResult = await postgrest.client
- .from("TransactionLog")
- .delete()
- .eq("eventId", `dev-${userId}`);
- if (deleteResult.error) {
- console.error(
- "[applyDevPlan] Failed to delete TransactionLog:",
- deleteResult.error
- );
- }
- }
-};
-
export const action = async ({ request }: ActionFunctionArgs) => {
preventCrossOriginCookie(request);
@@ -123,7 +45,9 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const response = await clearReturnToCookie(request, error);
// Write the selected dev plan directly into the DB so that getPlanInfo
// reads it naturally for any user (including owner lookups from other sessions).
- await applyDevPlan(email, planName);
+ await applyDevPlan(email, planName, {
+ postgrest: createPostgrestContext(),
+ });
return setNoStoreToRedirect(response);
}
diff --git a/apps/builder/app/services/auth.server.ts b/apps/builder/app/services/auth.server.ts
index eca0ad29c9..5ae058fcdb 100644
--- a/apps/builder/app/services/auth.server.ts
+++ b/apps/builder/app/services/auth.server.ts
@@ -26,7 +26,7 @@ const transformRefToAlias = (input: string) => {
export const callbackOrigin =
env.DEPLOYMENT_ENVIRONMENT === "production"
? env.DEPLOYMENT_URL
- : env.DEPLOYMENT_ENVIRONMENT === "staging" ||
+ : env.DEPLOYMENT_ENVIRONMENT === "preview" ||
env.DEPLOYMENT_ENVIRONMENT === "development"
? `https://${transformRefToAlias(staticEnv.GITHUB_REF_NAME ?? "main")}.${env.DEPLOYMENT_ENVIRONMENT}.webstudio.is`
: `https://wstd.dev:${env.PORT || 5173}`;
diff --git a/apps/builder/app/services/dev-plan.server.test.ts b/apps/builder/app/services/dev-plan.server.test.ts
new file mode 100644
index 0000000000..86b3c2e73a
--- /dev/null
+++ b/apps/builder/app/services/dev-plan.server.test.ts
@@ -0,0 +1,84 @@
+import { describe, test, expect } from "vitest";
+import {
+ createTestServer,
+ db,
+ testContext,
+ json,
+ empty,
+} from "@webstudio-is/postgrest/testing";
+import { applyDevPlan } from "~/services/dev-plan.server";
+
+const server = createTestServer();
+
+// ─── applyDevPlan ─────────────────────────────────────────────
+
+describe("applyDevPlan (msw)", () => {
+ test("does nothing when user is not found", async () => {
+ server.use(
+ db.get("User", () =>
+ json(
+ { code: "PGRST116", message: "Row not found", details: "", hint: "" },
+ { status: 406 }
+ )
+ )
+ );
+
+ // Should resolve without throwing even when user is missing
+ await expect(
+ applyDevPlan("[email protected]", "Pro", testContext)
+ ).resolves.toBeUndefined();
+ });
+
+ test("upserts Product and TransactionLog when plan is set", async () => {
+ let productUpserted = false;
+ let txUpserted = false;
+
+ server.use(
+ db.get("User", () => json({ id: "user-1" })),
+ db.post("Product", () => {
+ productUpserted = true;
+ return empty({ status: 201 });
+ }),
+ db.post("TransactionLog", () => {
+ txUpserted = true;
+ return empty({ status: 201 });
+ })
+ );
+
+ await applyDevPlan("[email protected]", "Pro", testContext);
+ expect(productUpserted).toBe(true);
+ expect(txUpserted).toBe(true);
+ });
+
+ test("deletes TransactionLog when plan is null (free tier)", async () => {
+ let txDeleted = false;
+
+ server.use(
+ db.get("User", () => json({ id: "user-1" })),
+ db.delete("TransactionLog", () => {
+ txDeleted = true;
+ return empty({ status: 204 });
+ })
+ );
+
+ await applyDevPlan("[email protected]", null, testContext);
+ expect(txDeleted).toBe(true);
+ });
+
+ test("does nothing when Product upsert fails", async () => {
+ server.use(
+ db.get("User", () => json({ id: "user-1" })),
+ db.post("Product", () =>
+ json(
+ { code: "PGRST000", message: "DB error", details: "", hint: "" },
+ { status: 500 }
+ )
+ )
+ );
+
+ // Should resolve (logs error but doesn't throw)
+ await expect(
+ applyDevPlan("[email protected]", "Pro", testContext)
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/builder/app/services/dev-plan.server.ts b/apps/builder/app/services/dev-plan.server.ts
new file mode 100644
index 0000000000..64360e3b7f
--- /dev/null
+++ b/apps/builder/app/services/dev-plan.server.ts
@@ -0,0 +1,83 @@
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+
+/**
+ * Upsert or delete dev plan rows in the DB for the given user email.
+ * This lets getPlanInfo work naturally (same as production) for all callers,
+ * including getOwnerPlanFeatures for shared-workspace suspension checks.
+ *
+ * - Plan selected: upsert a Product row (id = "dev-product-{planName}") and a
+ * TransactionLog row (eventId = "dev-{userId}") that satisfies the UserProduct view.
+ * - No plan selected: delete the TransactionLog row so the user has no active purchase.
+ */
+export const applyDevPlan = async (
+ email: string,
+ planName: string | null,
+ context: Pick<AppContext, "postgrest">
+) => {
+ const { postgrest } = context;
+ // Resolve userId from email (user was already created by the authenticator).
+ const userResult = await postgrest.client
+ .from("User")
+ .select("id")
+ .eq("email", email)
+ .single();
+
+ if (userResult.error) {
+ console.error("[applyDevPlan] Failed to find user:", userResult.error);
+ return;
+ }
+
+ const userId = userResult.data?.id as string | undefined;
+ if (!userId) {
+ console.error("[applyDevPlan] No user found for email:", email);
+ return;
+ }
+
+ if (planName !== null) {
+ const productId = `dev-product-${planName}`;
+
+ const productResult = await postgrest.client.from("Product").upsert({
+ id: productId,
+ name: planName,
+ meta: {},
+ features: [],
+ images: [],
+ });
+ if (productResult.error) {
+ console.error(
+ "[applyDevPlan] Failed to upsert Product:",
+ productResult.error
+ );
+ return;
+ }
+
+ const txResult = await postgrest.client.from("TransactionLog").upsert({
+ eventId: `dev-${userId}`,
+ userId,
+ productId,
+ eventData: {
+ type: "checkout.session.completed",
+ created: Math.floor(Date.now() / 1000),
+ data: { object: { status: "complete" } },
+ },
+ });
+ if (txResult.error) {
+ console.error(
+ "[applyDevPlan] Failed to upsert TransactionLog:",
+ txResult.error
+ );
+ }
+ } else {
+ // Remove any existing dev plan row — the user becomes free tier.
+ const deleteResult = await postgrest.client
+ .from("TransactionLog")
+ .delete()
+ .eq("eventId", `dev-${userId}`);
+ if (deleteResult.error) {
+ console.error(
+ "[applyDevPlan] Failed to delete TransactionLog:",
+ deleteResult.error
+ );
+ }
+ }
+};
diff --git a/apps/builder/app/services/workspace-router.server.ts b/apps/builder/app/services/workspace-router.server.ts
index a4a40727f3..4c03ce4430 100644
--- a/apps/builder/app/services/workspace-router.server.ts
+++ b/apps/builder/app/services/workspace-router.server.ts
@@ -5,8 +5,9 @@ import {
createErrorResponse,
} from "@webstudio-is/trpc-interface/index.server";
import { workspace as workspaceApi } from "@webstudio-is/project/index.server";
-import { getPlanInfo } from "~/shared/db/plan-features.server";
import { roles } from "@webstudio-is/trpc-interface/authorize";
+import { getPlanInfo } from "@webstudio-is/trpc-interface/plan-client";
+import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";
import env from "~/env/env.server";
const Name = z.string().min(2).max(100);
@@ -63,10 +64,15 @@ const updateSeats = async ({
* Syncs the Stripe seat quantity for the owner of a given workspace.
* Called after adding or removing members.
* Throws on payment worker errors so the caller can decide whether to soft-fail.
+ *
+ * @param countDelta - adjustment to the current member count before syncing.
+ * Pass +1 when a member is about to be added (pre-charge) so that billing
+ * is checked before the DB change is committed.
*/
const syncOwnerSeats = async (
workspaceId: string,
- ctx: Parameters<typeof workspaceApi.countAllMembers>[1]
+ ctx: Parameters<typeof workspaceApi.countAllMembers>[1],
+ countDelta = 0
) => {
const workspaceResult = await ctx.postgrest.client
.from("Workspace")
@@ -80,8 +86,11 @@ const syncOwnerSeats = async (
}
const ownerId = workspaceResult.data.userId;
- const planInfo = await getPlanInfo(ownerId, ctx.postgrest);
- const { planFeatures, purchases } = planInfo;
+ const planResults = await getPlanInfo([ownerId], ctx);
+ const { planFeatures, purchases } = planResults.get(ownerId) ?? {
+ planFeatures: defaultPlanFeatures,
+ purchases: [],
+ };
const subscription = purchases.find((p) => p.subscriptionId !== undefined);
if (subscription?.subscriptionId === undefined) {
@@ -93,7 +102,7 @@ const syncOwnerSeats = async (
const result = await updateSeats({
userId: ownerId,
subscriptionId: subscription.subscriptionId,
- newQuantity: memberCount,
+ newQuantity: memberCount + countDelta,
minSeats: planFeatures.minSeats,
maxSeats: planFeatures.maxSeatsPerWorkspace,
});
@@ -178,6 +187,16 @@ export const workspaceRouter = router({
throw new Error("Upgrade your plan to invite members to workspaces.");
}
+ const isDevEnvironment = env.DEPLOYMENT_ENVIRONMENT === "development";
+ const hasPaymentWorker =
+ env.PAYMENT_WORKER_URL && env.PAYMENT_WORKER_TOKEN;
+
+ if (!hasPaymentWorker && !isDevEnvironment) {
+ throw new Error(
+ "Adding workspace members requires a configured payment provider."
+ );
+ }
+
const { maxSeatsPerWorkspace } = ctx.planFeatures;
if (maxSeatsPerWorkspace > 0) {
const [membersResult, pendingResult] = await Promise.all([
@@ -210,16 +229,21 @@ export const workspaceRouter = router({
}
}
- const { notificationId } = await workspaceApi.addMember(input, ctx);
-
- // Charge the seat at invite time (Figma model).
- // Soft-fail: the invite is already created, billing is best-effort.
- await syncOwnerSeats(input.workspaceId, ctx).catch((error) => {
- console.error(
- "[payment-worker] Failed to bill seat on invite:",
- error
+ // Pre-charge the seat before adding the member (Figma model).
+ // When the payment worker is configured, a billing failure aborts the
+ // invite so the member is never added. When the worker URL is not set
+ // (self-hosted / dev), syncOwnerSeats returns early and this is a no-op.
+ try {
+ await syncOwnerSeats(input.workspaceId, ctx, +1);
+ } catch (error) {
+ const technical =
+ error instanceof Error ? error.message : String(error);
+ throw new Error(
+ `Unable to update billing. Please try again or contact support. (${technical})`
);
- });
+ }
+
+ const { notificationId } = await workspaceApi.addMember(input, ctx);
return { success: true as const, notificationId };
} catch (error) {
diff --git a/apps/builder/app/shared/context.server.ts b/apps/builder/app/shared/context.server.ts
index 368d6a42ba..4fb1f61be4 100644
--- a/apps/builder/app/shared/context.server.ts
+++ b/apps/builder/app/shared/context.server.ts
@@ -5,7 +5,10 @@ import { trpcSharedClient } from "~/services/trpc.server";
import { entryApi } from "./entri/entri-api.server";
import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";
-import { getPlanInfo } from "./db/plan-features.server";
+import {
+ getPlanInfo,
+ getAuthorizationOwnerId,
+} from "@webstudio-is/trpc-interface/plan-client";
import { staticEnv } from "~/env/env.static.server";
import { createClient } from "@webstudio-is/postgrest/index.server";
import { builderAuthenticator } from "~/services/builder-auth.server";
@@ -151,27 +154,6 @@ const createEntriContext = () => {
};
};
-const createPlanContext = async (
- authorization: AppContext["authorization"],
- postgrest: AppContext["postgrest"]
-): Promise<{
- planFeatures: AppContext["planFeatures"];
- purchases: AppContext["purchases"];
-}> => {
- const ownerId =
- authorization.type === "token"
- ? authorization.ownerId
- : authorization.type === "user"
- ? authorization.userId
- : undefined;
-
- if (ownerId === undefined) {
- return { planFeatures: defaultPlanFeatures, purchases: [] };
- }
-
- return getPlanInfo(ownerId, postgrest);
-};
-
const createTrpcCache = () => {
const proceduresMaxAge = new Map<string, number>();
const setMaxAge = (path: string, value: number) => {
@@ -200,18 +182,31 @@ export const createContext = async (request: Request): Promise<AppContext> => {
const postgrest = createPostgrestContext();
const authorization = await createAuthorizationContext(request, postgrest);
+ const resolvePlanInfo = async (auth: AppContext["authorization"]) => {
+ const ownerId = getAuthorizationOwnerId(auth);
+ if (ownerId === undefined) {
+ return {
+ planFeatures: defaultPlanFeatures,
+ purchases: [] as AppContext["purchases"],
+ };
+ }
+ return (
+ (await getPlanInfo([ownerId], { postgrest })).get(ownerId) ?? {
+ planFeatures: defaultPlanFeatures,
+ purchases: [] as AppContext["purchases"],
+ }
+ );
+ };
+
const domain = createDomainContext();
const deployment = createDeploymentContext(getRequestOrigin(request.url));
const entri = createEntriContext();
- const { planFeatures, purchases } = await createPlanContext(
- authorization,
- postgrest
- );
+ const { planFeatures, purchases } = await resolvePlanInfo(authorization);
const trpcCache = createTrpcCache();
const getOwnerPlanFeatures = async (userId: string) => {
- const { planFeatures } = await getPlanInfo(userId, postgrest);
- return planFeatures;
+ const results = await getPlanInfo([userId], { postgrest });
+ return results.get(userId)?.planFeatures ?? defaultPlanFeatures;
};
const createTokenContext = async (authToken: string) => {
@@ -219,10 +214,8 @@ export const createContext = async (request: Request): Promise<AppContext> => {
authToken,
postgrest
);
- const { planFeatures, purchases } = await createPlanContext(
- authorization,
- postgrest
- );
+
+ const { planFeatures, purchases } = await resolvePlanInfo(authorization);
return {
authorization,
diff --git a/apps/builder/app/shared/db/plan-features.server.ts b/apps/builder/app/shared/db/plan-features.server.ts
deleted file mode 100644
index e8ff981888..0000000000
--- a/apps/builder/app/shared/db/plan-features.server.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
-import {
- type PlanFeatures,
- PlanFeaturesSchema,
- defaultPlanFeatures,
-} from "@webstudio-is/trpc-interface/plan-features";
-import env from "~/env/env.server";
-
-type PlanInfo = {
- planFeatures: PlanFeatures;
- purchases: AppContext["purchases"];
-};
-
-/**
- * Safely extract known plan-feature overrides from an untyped product.meta blob.
- * Unknown keys are stripped; invalid values fall back to the caller's defaults.
- */
-const parseProductMeta = (meta: unknown): Partial<PlanFeatures> => {
- const result = PlanFeaturesSchema.partial().safeParse(meta);
- return result.success ? result.data : {};
-};
-
-/**
- * Merge plan features from multiple products.
- * Booleans are merged with OR (any product enables it), numbers with max.
- */
-const mergeProductMetas = (productMetas: PlanFeatures[]): PlanFeatures => {
- if (productMetas.length === 0) {
- return defaultPlanFeatures;
- }
-
- return Object.fromEntries(
- (Object.keys(defaultPlanFeatures) as Array<keyof PlanFeatures>).map(
- (key) => {
- const vals = productMetas.map((item) => item[key]);
- const merged =
- typeof defaultPlanFeatures[key] === "boolean"
- ? (vals as boolean[]).some(Boolean)
- : Math.max(...(vals as number[]));
- return [key, merged];
- }
- )
- ) as PlanFeatures;
-};
-
-/**
- * Parse the PLANS env variable (JSON array of {name, extends?, features}).
- * - features is partial when extends is used; the parent plan fills in the rest.
- * - The final merged features are validated against the full PlanFeaturesSchema.
- * - Invalid entries are skipped with a console.error.
- * - An extends reference to an unknown plan name throws an error.
- * Returns a Map of plan name → resolved PlanFeatures.
- */
-export const parsePlansEnv = (raw: string): Map<string, PlanFeatures> => {
- try {
- const parsed = JSON.parse(raw);
- if (!Array.isArray(parsed)) {
- return new Map();
- }
-
- type PlanEntry = {
- name: string;
- extends?: string;
- features: Partial<PlanFeatures>;
- };
-
- // First pass: validate entry structure and collect partial features.
- const entries: PlanEntry[] = parsed.flatMap((item) => {
- if (
- typeof item !== "object" ||
- item === null ||
- typeof item.name !== "string"
- ) {
- console.error("Invalid PLANS entry (missing name):", item);
- return [];
- }
- if ("extends" in item && typeof item.extends !== "string") {
- console.error("Invalid PLANS entry (extends must be a string):", item);
- return [];
- }
- const result = PlanFeaturesSchema.partial().safeParse(
- "features" in item ? item.features : {}
- );
- if (!result.success) {
- console.error(
- `Invalid PLANS entry "${item.name}" features:`,
- result.error.flatten()
- );
- return [];
- }
- return [
- {
- name: item.name,
- extends: "extends" in item ? (item.extends as string) : undefined,
- features: result.data,
- } satisfies PlanEntry,
- ];
- });
-
- // Build name → partial features map for resolving extends.
- const byName = new Map<string, Partial<PlanFeatures>>(
- entries.map((e) => [e.name, e.features])
- );
-
- // Second pass: resolve extends and validate the full feature set.
- // Every entry implicitly extends defaultPlanFeatures; "extends" picks a named plan on top of that.
- const resolved = new Map<string, PlanFeatures>();
- for (const entry of entries) {
- if (entry.extends !== undefined && !byName.has(entry.extends)) {
- throw new Error(
- `PLANS entry "${entry.name}" extends unknown plan "${entry.extends}"`
- );
- }
- const parentFeatures: PlanFeatures =
- entry.extends === undefined
- ? defaultPlanFeatures
- : { ...defaultPlanFeatures, ...byName.get(entry.extends)! };
- const result = PlanFeaturesSchema.safeParse({
- ...parentFeatures,
- ...entry.features,
- });
- if (!result.success) {
- console.error(
- `Invalid PLANS entry "${entry.name}" features after resolving extends:`,
- result.error.flatten()
- );
- continue;
- }
- resolved.set(entry.name, result.data);
- }
- return resolved;
- } catch (error) {
- if (error instanceof Error && error.message.startsWith("PLANS entry")) {
- throw error;
- }
- return new Map();
- }
-};
-
-const buildPurchases = (
- userProducts: Array<{
- productId: string | null | undefined;
- subscriptionId: string | null | undefined;
- }>,
- productIdToName: Map<string, string>
-): PlanInfo["purchases"] => {
- const purchases: PlanInfo["purchases"] = [];
- for (const userProduct of userProducts) {
- if (userProduct.productId) {
- const planName = productIdToName.get(userProduct.productId) ?? "";
- purchases.push({
- planName,
- subscriptionId: userProduct.subscriptionId ?? undefined,
- });
- }
- }
- return purchases;
-};
-
-export const getPlanInfo = async (
- userId: string,
- postgrest: AppContext["postgrest"]
-): Promise<PlanInfo> => {
- const userProductsResult = await postgrest.client
- .from("UserProduct")
- .select("customerId, subscriptionId, productId")
- .eq("userId", userId);
-
- if (userProductsResult.error) {
- console.error(userProductsResult.error);
- throw new Error("Failed to fetch user products");
- }
-
- const userProducts = userProductsResult.data;
-
- // Filter out null/undefined productIds before querying
- const productIds = userProducts.flatMap(({ productId }) =>
- productId !== null && productId !== undefined ? [productId] : []
- );
-
- if (productIds.length > 0) {
- const productsResult = await postgrest.client
- .from("Product")
- .select("id, name, meta")
- .in("id", productIds);
-
- if (productsResult.error) {
- console.error(productsResult.error);
- throw new Error("Failed to fetch products");
- }
-
- const products = productsResult.data;
- const productIdToName = new Map(products.map((p) => [p.id, p.name]));
-
- // Look up each product's plan by name in PLANS env, falling back to defaultPlanFeatures.
- // Product meta is applied on top as per-product overrides.
- const plansByName = parsePlansEnv(env.PLANS);
- const productMetas = products.map((product) => ({
- ...(plansByName.get(product.name) ?? defaultPlanFeatures),
- ...parseProductMeta(product.meta),
- }));
-
- return {
- planFeatures: mergeProductMetas(productMetas),
- purchases: buildPurchases(userProducts, productIdToName),
- };
- }
-
- return {
- planFeatures: defaultPlanFeatures,
- purchases: [],
- };
-};
-
-export const __testing__ = {
- parseProductMeta,
- mergeProductMetas,
- parsePlansEnv,
-};
diff --git a/apps/builder/app/shared/db/user.server.test.ts b/apps/builder/app/shared/db/user.server.test.ts
new file mode 100644
index 0000000000..d98a28e386
--- /dev/null
+++ b/apps/builder/app/shared/db/user.server.test.ts
@@ -0,0 +1,193 @@
+import { describe, test, expect } from "vitest";
+import {
+ createTestServer,
+ db,
+ testContext,
+ json,
+} from "@webstudio-is/postgrest/testing";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import {
+ getUserById,
+ createOrLoginWithDev,
+ updateUserProjectsTags,
+} from "./user.server";
+
+const server = createTestServer();
+
+const createContext = (overrides: Partial<AppContext> = {}): AppContext =>
+ ({
+ ...testContext,
+ authorization: { type: "user", userId: "user-1" },
+ ...overrides,
+ }) as unknown as AppContext;
+
+const userRow = {
+ id: "user-1",
+ email: "[email protected]",
+ username: "tester",
+ image: "",
+ provider: "dev",
+ projectsTags: [],
+ createdAt: new Date().toISOString(),
+ team: null,
+};
+
+// ─── getUserById ───────────────────────────────────────────────
+
+describe("getUserById (msw)", () => {
+ test("returns user when found", async () => {
+ server.use(db.get("User", () => json(userRow)));
+
+ const result = await getUserById(createContext(), "user-1");
+ expect(result.id).toBe("user-1");
+ expect(result.email).toBe("[email protected]");
+ expect(result.projectsTags).toEqual([]);
+ });
+
+ test("throws when user not found", async () => {
+ server.use(
+ db.get("User", () =>
+ json(
+ { code: "PGRST116", message: "Row not found", details: "", hint: "" },
+ { status: 406 }
+ )
+ )
+ );
+
+ await expect(getUserById(createContext(), "missing")).rejects.toThrow(
+ "User not found"
+ );
+ });
+});
+
+// ─── createOrLoginWithDev ──────────────────────────────────────
+
+describe("createOrLoginWithDev (msw)", () => {
+ test("returns existing user when found", async () => {
+ let workspaceChecked = false;
+ server.use(
+ // User SELECT resolves successfully → existing user
+ db.get("User", () => json(userRow)),
+ // Workspace check — has default workspace
+ db.get("Workspace", () => {
+ workspaceChecked = true;
+ return json({ id: "ws-1" });
+ })
+ );
+
+ const result = await createOrLoginWithDev(
+ createContext(),
+ );
+ expect(result.id).toBe("user-1");
+ expect(workspaceChecked).toBe(true);
+ });
+
+ test("lazily creates workspace when existing user has none", async () => {
+ let workspaceCreated = false;
+ server.use(
+ db.get("User", () => json(userRow)),
+ // maybeSingle returns null when no row exists
+ db.get("Workspace", () => json(null)),
+ db.post("Workspace", () => {
+ workspaceCreated = true;
+ return json({ id: "ws-new" }, { status: 201 });
+ })
+ );
+
+ const result = await createOrLoginWithDev(
+ createContext(),
+ );
+ expect(result.id).toBe("user-1");
+ expect(workspaceCreated).toBe(true);
+ });
+
+ test("creates new user and workspace when email not found", async () => {
+ let userInserted = false;
+ let workspaceInserted = false;
+ server.use(
+ // User SELECT → PGRST116 (not found)
+ db.get("User", () =>
+ json(
+ { code: "PGRST116", message: "Row not found", details: "", hint: "" },
+ { status: 406 }
+ )
+ ),
+ db.post("User", () => {
+ userInserted = true;
+ return json({ ...userRow, id: "new-user" }, { status: 201 });
+ }),
+ db.post("Workspace", () => {
+ workspaceInserted = true;
+ return json({ id: "ws-new" }, { status: 201 });
+ })
+ );
+
+ const result = await createOrLoginWithDev(
+ createContext(),
+ );
+
+ expect(result.email).toBe("[email protected]"); // from userRow mock
+ expect(userInserted).toBe(true);
+ expect(workspaceInserted).toBe(true);
+ });
+
+ test("throws when User SELECT fails with unexpected error", async () => {
+ server.use(
+ db.get("User", () =>
+ json(
+ { code: "PGRST999", message: "DB error", details: "", hint: "" },
+ { status: 500 }
+ )
+ )
+ );
+
+ await expect(
+ createOrLoginWithDev(createContext(), "[email protected]")
+ ).rejects.toThrow("User not found");
+ });
+});
+
+// ─── updateUserProjectsTags ────────────────────────────────────
+
+describe("updateUserProjectsTags (msw)", () => {
+ const tags = [{ id: "tag-1", label: "Design" }];
+
+ test("returns updated tags", async () => {
+ server.use(
+ db.patch("User", () =>
+ json({ ...userRow, projectsTags: tags }, { status: 200 })
+ )
+ );
+
+ const result = await updateUserProjectsTags({ tags }, createContext());
+ expect(result).toEqual(tags);
+ });
+
+ test("throws AuthorizationError for non-user context", async () => {
+ await expect(
+ updateUserProjectsTags(
+ { tags },
+ createContext({ authorization: { type: "anonymous" } })
+ )
+ ).rejects.toThrow(AuthorizationError);
+ });
+
+ test("throws when DB update fails", async () => {
+ server.use(
+ db.patch("User", () =>
+ json(
+ { code: "PGRST123", message: "Update failed", details: "", hint: "" },
+ { status: 500 }
+ )
+ )
+ );
+
+ await expect(
+ updateUserProjectsTags({ tags }, createContext())
+ ).rejects.toBeTruthy();
+ });
+});
diff --git a/apps/builder/app/shared/marketplace/db.server.test.ts b/apps/builder/app/shared/marketplace/db.server.test.ts
new file mode 100644
index 0000000000..77d26d4703
--- /dev/null
+++ b/apps/builder/app/shared/marketplace/db.server.test.ts
@@ -0,0 +1,125 @@
+import { describe, test, expect } from "vitest";
+import {
+ createTestServer,
+ db,
+ testContext,
+ json,
+} from "@webstudio-is/postgrest/testing";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { getItems } from "./db.server";
+
+const server = createTestServer();
+
+const ctx = testContext as unknown as AppContext;
+
+const marketplaceProductJson = JSON.stringify({
+ category: "sectionTemplates",
+ name: "My Section",
+ thumbnailAssetId: "asset-thumb",
+ author: "Author Name",
+ email: "[email protected]",
+ website: "https://example.com",
+ issues: "",
+ description: "A nice section template for testing purposes.",
+});
+
+// ─── getItems ─────────────────────────────────────────────────
+
+describe("getItems (msw)", () => {
+ test("returns empty array when no marketplace products", async () => {
+ server.use(db.get("ApprovedMarketplaceProduct", () => json([])));
+
+ const result = await getItems(ctx);
+ expect(result).toEqual([]);
+ });
+
+ test("skips products with null marketplaceProduct or projectId", async () => {
+ server.use(
+ db.get("ApprovedMarketplaceProduct", () =>
+ json([
+ {
+ id: "1",
+ projectId: null,
+ marketplaceProduct: marketplaceProductJson,
+ authorizationToken: null,
+ },
+ {
+ id: "2",
+ projectId: "proj-1",
+ marketplaceProduct: null,
+ authorizationToken: null,
+ },
+ ])
+ )
+ );
+
+ const result = await getItems(ctx);
+ expect(result).toHaveLength(0);
+ });
+
+ test("skips products with invalid marketplaceProduct JSON", async () => {
+ server.use(
+ db.get("ApprovedMarketplaceProduct", () =>
+ json([
+ {
+ id: "1",
+ projectId: "proj-1",
+ // Category not in enum → parse fails
+ marketplaceProduct: JSON.stringify({
+ category: "invalid",
+ name: "x",
+ }),
+ authorizationToken: null,
+ },
+ ])
+ )
+ );
+
+ const result = await getItems(ctx);
+ expect(result).toHaveLength(0);
+ });
+
+ test("returns items with thumbnailAssetName when asset exists", async () => {
+ server.use(
+ db.get("ApprovedMarketplaceProduct", () =>
+ json([
+ {
+ id: "1",
+ projectId: "proj-1",
+ marketplaceProduct: marketplaceProductJson,
+ authorizationToken: "tok-abc",
+ },
+ ])
+ ),
+ db.get("Asset", () =>
+ json([{ id: "asset-thumb", name: "thumb.png", projectId: "proj-1" }])
+ )
+ );
+
+ const result = await getItems(ctx);
+ expect(result).toHaveLength(1);
+ expect(result[0].projectId).toBe("proj-1");
+ expect(result[0].authorizationToken).toBe("tok-abc");
+ expect(result[0].thumbnailAssetName).toBe("thumb.png");
+ });
+
+ test("returns items without thumbnailAssetName when asset missing", async () => {
+ server.use(
+ db.get("ApprovedMarketplaceProduct", () =>
+ json([
+ {
+ id: "1",
+ projectId: "proj-1",
+ marketplaceProduct: marketplaceProductJson,
+ authorizationToken: null,
+ },
+ ])
+ ),
+ db.get("Asset", () => json([]))
+ );
+
+ const result = await getItems(ctx);
+ expect(result).toHaveLength(1);
+ expect(result[0].thumbnailAssetName).toBeUndefined();
+ });
+});
diff --git a/apps/builder/app/shared/polly/topic-resolvers.server.test.ts b/apps/builder/app/shared/polly/topic-resolvers.server.test.ts
new file mode 100644
index 0000000000..f23a580e8f
--- /dev/null
+++ b/apps/builder/app/shared/polly/topic-resolvers.server.test.ts
@@ -0,0 +1,105 @@
+import { describe, test, expect, afterEach } from "vitest";
+import {
+ createTestServer,
+ db,
+ testContext,
+ json,
+} from "@webstudio-is/postgrest/testing";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { __testing__ } from "@webstudio-is/trpc-interface/plan-client";
+import { resolveTopics } from "./topic-resolvers.server";
+
+const server = createTestServer();
+
+afterEach(() => {
+ __testing__.resetProductCache();
+ delete process.env.PLANS;
+});
+
+const createContext = (userId = "user-1"): AppContext =>
+ ({
+ ...testContext,
+ authorization: { type: "user", userId },
+ }) as unknown as AppContext;
+
+// Helper: member row with workspace embedded
+const memberRow = (workspaceId: string, ownerId: string, name: string) => ({
+ workspaceId,
+ workspace: { userId: ownerId, name },
+});
+
+// ─── seatSuspended ─────────────────────────────────────────────
+
+describe("seatSuspended (msw)", () => {
+ test("returns false for non-user authorization", async () => {
+ const ctx = {
+ ...testContext,
+ authorization: { type: "anonymous" },
+ } as unknown as AppContext;
+
+ const result = await resolveTopics(["seatSuspended"], ctx);
+ expect(result.seatSuspended).toBe(false);
+ });
+
+ test("returns false when user has no workspace memberships", async () => {
+ server.use(db.get("WorkspaceMember", () => json([])));
+
+ const result = await resolveTopics(["seatSuspended"], createContext());
+ expect(result.seatSuspended).toBe(false);
+ });
+
+ test("returns false when all memberships are user's own workspaces", async () => {
+ server.use(
+ db.get("WorkspaceMember", () =>
+ // workspace.userId === userId → filtered out as own workspace
+ json([memberRow("ws-1", "user-1", "My Workspace")])
+ )
+ );
+
+ const result = await resolveTopics(
+ ["seatSuspended"],
+ createContext("user-1")
+ );
+ expect(result.seatSuspended).toBe(false);
+ });
+
+ test("returns workspace name when owner has default (free) plan", async () => {
+ server.use(
+ db.get("WorkspaceMember", () =>
+ json([memberRow("ws-owner", "owner-1", "Owner Workspace")])
+ ),
+ // getPlanInfo: no user products → defaultPlanFeatures (maxWorkspaces=1 → suspended)
+ db.get("UserProduct", () => json([]))
+ );
+
+ const result = await resolveTopics(
+ ["seatSuspended"],
+ createContext("user-1")
+ );
+ expect(result.seatSuspended).toBe("Owner Workspace");
+ });
+
+ test("returns false when owner has upgraded plan (maxWorkspaces > 1)", async () => {
+ process.env.PLANS = JSON.stringify([
+ { name: "Pro", features: { maxWorkspaces: 5 } },
+ ]);
+
+ server.use(
+ db.get("WorkspaceMember", () =>
+ json([memberRow("ws-owner", "owner-1", "Owner Workspace")])
+ ),
+ db.get("UserProduct", () =>
+ json([
+ { userId: "owner-1", productId: "prod-pro", subscriptionId: null },
+ ])
+ ),
+ db.get("Product", () => json([{ id: "prod-pro", name: "Pro", meta: {} }]))
+ );
+
+ const result = await resolveTopics(
+ ["seatSuspended"],
+ createContext("user-1")
+ );
+ expect(result.seatSuspended).toBe(false);
+ });
+});
diff --git a/apps/builder/app/shared/polly/topic-resolvers.server.ts b/apps/builder/app/shared/polly/topic-resolvers.server.ts
index e0d99741c6..3b79fdc26b 100644
--- a/apps/builder/app/shared/polly/topic-resolvers.server.ts
+++ b/apps/builder/app/shared/polly/topic-resolvers.server.ts
@@ -1,6 +1,7 @@
import { notification } from "@webstudio-is/project/index.server";
import { db as dashboardDb } from "@webstudio-is/dashboard/index.server";
-import { getPlanInfo } from "~/shared/db/plan-features.server";
+import { getPlanInfo } from "@webstudio-is/trpc-interface/plan-client";
+import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";
import { publicStaticEnv } from "~/env/env.static";
import type { TopicResolvers, TopicName, SubscriptionResponse } from "./types";
@@ -50,11 +51,16 @@ const resolvers: TopicResolvers = {
return false;
}
- // Check each workspace owner's plan — suspended if any owner can't cover seats.
+ // Check each workspace owner's plan — suspended if owner of any workspace can't cover seats.
+ const ownerIds = sharedWorkspaces.map(
+ (m) => (m.workspace as unknown as { userId: string }).userId
+ );
+ const planResults = await getPlanInfo(ownerIds, ctx);
+
for (const m of sharedWorkspaces) {
const ownerId = (m.workspace as unknown as { userId: string }).userId;
- const planResult = await getPlanInfo(ownerId, ctx.postgrest);
- const features = planResult.planFeatures;
+ const features =
+ planResults.get(ownerId)?.planFeatures ?? defaultPlanFeatures;
if (features.maxWorkspaces <= 1) {
return (m.workspace as unknown as { userId: string; name: string })
diff --git a/packages/asset-uploader/src/delete.test.ts b/packages/asset-uploader/src/delete.test.ts
new file mode 100644
index 0000000000..a73992fc12
--- /dev/null
+++ b/packages/asset-uploader/src/delete.test.ts
@@ -0,0 +1,130 @@
+import { describe, test, expect } from "vitest";
+import {
+ createTestServer,
+ db,
+ json,
+ empty,
+ testContext,
+} from "@webstudio-is/postgrest/testing";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import { deleteAssets } from "./delete";
+
+const server = createTestServer();
+
+const uid = () => `proj-${Math.random().toString(36).slice(2)}`;
+
+const createContext = (): AppContext =>
+ ({
+ ...testContext,
+ authorization: { type: "user", userId: "user-1" },
+ getOwnerPlanFeatures: async () => ({}),
+ }) as unknown as AppContext;
+
+/** hasProjectPermit: direct ownership check returns a row for a given projectId */
+const ownershipHandler = db.get("Project", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("userId")) {
+ return json({ id: url.searchParams.get("id")?.replace("eq.", "") });
+ }
+ return json(null);
+});
+
+describe("deleteAssets (msw)", () => {
+ test("throws AuthorizationError when caller lacks edit access", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json(null)),
+ db.get("WorkspaceProjectAuthorization", () => json([]))
+ );
+
+ await expect(
+ deleteAssets({ ids: ["asset-1"], projectId }, createContext())
+ ).rejects.toThrow(AuthorizationError);
+ });
+
+ test("throws when no assets found", async () => {
+ const projectId = uid();
+ server.use(
+ ownershipHandler,
+ db.get("Asset", () => json([]))
+ );
+
+ await expect(
+ deleteAssets({ ids: ["asset-1"], projectId }, createContext())
+ ).rejects.toThrow("Assets not found");
+ });
+
+ test("deletes assets and marks unused file as deleted", async () => {
+ const projectId = uid();
+ const assetRow = {
+ id: "asset-1",
+ projectId,
+ name: "photo.jpg",
+ file: { name: "photo.jpg" },
+ };
+ let patchedProject = false;
+ let deletedAsset = false;
+
+ server.use(
+ ownershipHandler,
+ db.get("Asset", ({ request }) => {
+ const url = new URL(request.url);
+ // usage check (in name filter) — no other assets use this file
+ if (url.searchParams.get("name")) {
+ return json([]);
+ }
+ return json([assetRow]);
+ }),
+ db.patch("Project", () => {
+ patchedProject = true;
+ return json({ id: projectId });
+ }),
+ db.delete("Asset", () => {
+ deletedAsset = true;
+ return empty({ status: 204 });
+ }),
+ db.patch("File", () => empty({ status: 204 }))
+ );
+
+ await deleteAssets({ ids: ["asset-1"], projectId }, createContext());
+
+ expect(patchedProject).toBe(true);
+ expect(deletedAsset).toBe(true);
+ });
+
+ test("does not mark file deleted when another asset still uses it", async () => {
+ const projectId = uid();
+ const assetRow = {
+ id: "asset-1",
+ projectId,
+ name: "photo.jpg",
+ file: { name: "photo.jpg" },
+ };
+ let markedFileDeleted = false;
+ let assetGetCount = 0;
+
+ server.use(
+ ownershipHandler,
+ db.get("Asset", () => {
+ assetGetCount += 1;
+ // First call: load the assets to delete. Second call: usage check.
+ if (assetGetCount === 1) {
+ return json([assetRow]);
+ }
+ // usage check — another asset still references the file
+ return json([{ name: "photo.jpg" }]);
+ }),
+ db.patch("Project", () => json({ id: projectId })),
+ db.delete("Asset", () => empty({ status: 204 })),
+ db.patch("File", () => {
+ markedFileDeleted = true;
+ return empty({ status: 204 });
+ })
+ );
+
+ await deleteAssets({ ids: ["asset-1"], projectId }, createContext());
+
+ expect(markedFileDeleted).toBe(false);
+ });
+});
diff --git a/packages/asset-uploader/src/delete.ts b/packages/asset-uploader/src/delete.ts
index 34eaefe86b..93412a04e1 100644
--- a/packages/asset-uploader/src/delete.ts
+++ b/packages/asset-uploader/src/delete.ts
@@ -63,8 +63,10 @@ export const deleteAssets = async (
}
// delete unused files
- await context.postgrest.client
- .from("File")
- .update({ isDeleted: true })
- .in("name", Array.from(unusedFileNames));
+ if (unusedFileNames.size > 0) {
+ await context.postgrest.client
+ .from("File")
+ .update({ isDeleted: true })
+ .in("name", Array.from(unusedFileNames));
+ }
};
diff --git a/packages/asset-uploader/src/patch.test.ts b/packages/asset-uploader/src/patch.test.ts
new file mode 100644
index 0000000000..67fdc256ac
--- /dev/null
+++ b/packages/asset-uploader/src/patch.test.ts
@@ -0,0 +1,151 @@
+import { describe, test, expect } from "vitest";
+import { enablePatches, enableMapSet } from "immer";
+import {
+ createTestServer,
+ db,
+ json,
+ empty,
+ testContext,
+} from "@webstudio-is/postgrest/testing";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { patchAssets } from "./patch";
+import type { Patch } from "immer";
+
+enablePatches();
+enableMapSet();
+
+const server = createTestServer();
+
+const uid = () => `proj-${Math.random().toString(36).slice(2)}`;
+
+const createContext = (): AppContext =>
+ ({
+ ...testContext,
+ authorization: { type: "user", userId: "user-1" },
+ getOwnerPlanFeatures: async () => ({}),
+ }) as unknown as AppContext;
+
+/** hasProjectPermit: direct ownership check — returns a row for any project */
+const ownershipHandler = db.get("Project", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("userId")) {
+ return json({ id: url.searchParams.get("id")?.replace("eq.", "") });
+ }
+ return json(null);
+});
+
+const assetRow = {
+ assetId: "asset-1",
+ projectId: "proj-1",
+ filename: "photo.jpg",
+ description: null,
+ file: {
+ name: "photo.jpg",
+ format: "jpg",
+ description: null,
+ size: 1000,
+ createdAt: "2024-01-01T00:00:00.000Z",
+ meta: JSON.stringify({ width: 100, height: 100 }),
+ status: "UPLOADED",
+ },
+};
+
+describe("patchAssets (msw)", () => {
+ test("throws when caller lacks edit access", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json(null)),
+ db.get("WorkspaceProjectAuthorization", () => json([]))
+ );
+
+ await expect(
+ patchAssets({ projectId }, [], createContext())
+ ).rejects.toThrow("You don't have edit access");
+ });
+
+ test("no-op when patches are empty and no assets exist", async () => {
+ const projectId = uid();
+ server.use(
+ ownershipHandler,
+ db.get("Asset", () => json([]))
+ );
+
+ // Should complete without throwing
+ await patchAssets({ projectId }, [], createContext());
+ });
+
+ test("updates asset description via patch", async () => {
+ const projectId = uid();
+ const localAssetRow = { ...assetRow, projectId };
+ let updatedDescription: string | undefined;
+
+ server.use(
+ ownershipHandler,
+ db.get("Asset", () => json([localAssetRow])),
+ db.patch("Asset", async ({ request }) => {
+ const body = (await request.json()) as { description?: string };
+ updatedDescription = body.description ?? undefined;
+ return json({ id: "asset-1" });
+ })
+ );
+
+ const patches: Patch[] = [
+ {
+ op: "replace",
+ path: ["asset-1", "description"],
+ value: "New description",
+ },
+ ];
+
+ await patchAssets({ projectId }, patches, createContext());
+ expect(updatedDescription).toBe("New description");
+ });
+
+ test("adds new asset when patch inserts an entry", async () => {
+ const projectId = uid();
+ let insertedAssets: unknown;
+
+ server.use(
+ ownershipHandler,
+ // loadAssetsByProject returns empty list — no existing assets
+ db.get("Asset", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.get("projectId")) {
+ return json([]);
+ }
+ return json([]);
+ }),
+ // File lookup for undo restore
+ db.get("File", () => json([{ name: "new.jpg" }])),
+ // restore isDeleted=false
+ db.patch("File", () => empty({ status: 204 })),
+ // asset insert
+ db.post("Asset", async ({ request }) => {
+ insertedAssets = await request.json();
+ return empty({ status: 201 });
+ })
+ );
+
+ const patches: Patch[] = [
+ {
+ op: "add",
+ path: ["asset-new"],
+ value: {
+ id: "asset-new",
+ name: "new.jpg",
+ type: "image",
+ projectId,
+ format: "jpg",
+ size: 500,
+ description: null,
+ createdAt: "2024-01-01T00:00:00.000Z",
+ path: "",
+ meta: { width: 50, height: 50 },
+ },
+ },
+ ];
+
+ await patchAssets({ projectId }, patches, createContext());
+ expect(insertedAssets).toBeDefined();
+ });
+});
diff --git a/packages/project-build/src/db/build.test.ts b/packages/project-build/src/db/build.test.ts
new file mode 100644
index 0000000000..fc4f907eea
--- /dev/null
+++ b/packages/project-build/src/db/build.test.ts
@@ -0,0 +1,241 @@
+import { describe, test, expect } from "vitest";
+import {
+ createTestServer,
+ db,
+ json,
+ empty,
+ testContext,
+} from "@webstudio-is/postgrest/testing";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import {
+ loadRawBuildById,
+ loadBuildById,
+ loadDevBuildByProjectId,
+ createBuild,
+ unpublishBuild,
+} from "./build";
+
+const server = createTestServer();
+
+const uid = () => `proj-${Math.random().toString(36).slice(2)}`;
+
+const createContext = (userId = "user-1"): AppContext =>
+ ({
+ ...testContext,
+ authorization: { type: "user", userId },
+ getOwnerPlanFeatures: async () => ({}),
+ }) as unknown as AppContext;
+
+/** hasProjectPermit: return the row when userId param is in the query */
+const ownershipHandler = db.get("Project", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("userId")) {
+ return json({ id: url.searchParams.get("id")?.replace("eq.", "") });
+ }
+ return json(null);
+});
+
+/** Minimal Build row that satisfies parseCompactBuild */
+const buildRow = {
+ id: "build-1",
+ projectId: "proj-1",
+ version: 0,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ pages: JSON.stringify({
+ meta: {},
+ homePage: {
+ id: "page-1",
+ name: "Home",
+ path: "/",
+ title: '"Home"',
+ meta: {},
+ rootInstanceId: "body-1",
+ systemDataSourceId: undefined,
+ },
+ pages: [],
+ }),
+ breakpoints: JSON.stringify([]),
+ styles: JSON.stringify([]),
+ styleSources: JSON.stringify([]),
+ styleSourceSelections: JSON.stringify([]),
+ props: JSON.stringify([]),
+ dataSources: JSON.stringify([]),
+ resources: JSON.stringify([]),
+ instances: JSON.stringify([
+ { id: "body-1", type: "instance", component: "Body", children: [] },
+ ]),
+ deployment: null,
+ marketplaceProduct: JSON.stringify({}),
+};
+
+// ---------------------------------------------------------------------------
+// loadRawBuildById
+// ---------------------------------------------------------------------------
+
+describe("loadRawBuildById (msw)", () => {
+ test("returns raw build row", async () => {
+ server.use(db.get("Build", () => json([buildRow])));
+ const result = await loadRawBuildById(createContext(), "build-1");
+ expect(result.id).toBe("build-1");
+ });
+
+ test("throws when build not found", async () => {
+ server.use(db.get("Build", () => json([])));
+ await expect(loadRawBuildById(createContext(), "missing")).rejects.toThrow(
+ "0 row(s)"
+ );
+ });
+
+ test("throws when multiple rows returned", async () => {
+ server.use(
+ db.get("Build", () => json([buildRow, { ...buildRow, id: "build-2" }]))
+ );
+ await expect(loadRawBuildById(createContext(), "build-1")).rejects.toThrow(
+ "2 row(s)"
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// loadBuildById (delegates to loadRawBuildById + parseCompactBuild)
+// ---------------------------------------------------------------------------
+
+describe("loadBuildById (msw)", () => {
+ test("returns parsed build with id and projectId", async () => {
+ server.use(db.get("Build", () => json([buildRow])));
+ const result = await loadBuildById(createContext(), "build-1");
+ expect(result.id).toBe("build-1");
+ expect(result.projectId).toBe("proj-1");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// loadDevBuildByProjectId
+// ---------------------------------------------------------------------------
+
+describe("loadDevBuildByProjectId (msw)", () => {
+ test("returns the dev build (no deployment)", async () => {
+ server.use(db.get("Build", () => json([buildRow])));
+ const result = await loadDevBuildByProjectId(createContext(), "proj-1");
+ expect(result.projectId).toBe("proj-1");
+ });
+
+ test("throws when no dev build found", async () => {
+ server.use(db.get("Build", () => json([])));
+ await expect(
+ loadDevBuildByProjectId(createContext(), "proj-1")
+ ).rejects.toThrow("No dev build found");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// createBuild
+// ---------------------------------------------------------------------------
+
+describe("createBuild (msw)", () => {
+ test("inserts a new build row", async () => {
+ let insertedRow: unknown;
+ server.use(
+ db.post("Build", async ({ request }) => {
+ insertedRow = await request.json();
+ return empty({ status: 201 });
+ })
+ );
+
+ await createBuild({ projectId: "proj-1" }, createContext());
+ expect(insertedRow).toMatchObject({ projectId: "proj-1" });
+ });
+
+ test("throws when insert fails", async () => {
+ server.use(
+ db.post("Build", () =>
+ json({ message: "constraint violation" }, { status: 409 })
+ )
+ );
+
+ await expect(
+ createBuild({ projectId: "proj-1" }, createContext())
+ ).rejects.toThrow();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// unpublishBuild
+// ---------------------------------------------------------------------------
+
+describe("unpublishBuild (msw)", () => {
+ test("throws AuthorizationError when caller lacks edit access", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json(null)),
+ db.get("WorkspaceProjectAuthorization", () => json([]))
+ );
+
+ await expect(
+ unpublishBuild({ projectId, domain: "example.com" }, createContext())
+ ).rejects.toThrow(AuthorizationError);
+ });
+
+ test("throws when domain is not published", async () => {
+ const projectId = uid();
+ server.use(
+ ownershipHandler,
+ // no builds with deployment containing example.com
+ db.get("Build", () => json([]))
+ );
+
+ await expect(
+ unpublishBuild({ projectId, domain: "example.com" }, createContext())
+ ).rejects.toThrow("is not published");
+ });
+
+ test("deletes build when it has only the one domain", async () => {
+ const projectId = uid();
+ let buildDeleted = false;
+ const deployment = JSON.stringify({
+ destination: "saas",
+ domains: ["example.com"],
+ });
+
+ server.use(
+ ownershipHandler,
+ db.get("Build", () => json([{ id: "build-prod", deployment }])),
+ db.delete("Build", () => {
+ buildDeleted = true;
+ return empty({ status: 204 });
+ })
+ );
+
+ await unpublishBuild({ projectId, domain: "example.com" }, createContext());
+ expect(buildDeleted).toBe(true);
+ });
+
+ test("updates build deployment when it has multiple domains", async () => {
+ const projectId = uid();
+ let updatedDeployment: unknown;
+ const deployment = JSON.stringify({
+ destination: "saas",
+ domains: ["example.com", "other.com"],
+ });
+
+ server.use(
+ ownershipHandler,
+ db.get("Build", () => json([{ id: "build-prod", deployment }])),
+ db.patch("Build", async ({ request }) => {
+ updatedDeployment = await request.json();
+ return json({ id: "build-prod" });
+ })
+ );
+
+ await unpublishBuild({ projectId, domain: "example.com" }, createContext());
+
+ expect(updatedDeployment).toMatchObject({
+ deployment: expect.stringContaining("other.com"),
+ });
+ expect(updatedDeployment).toMatchObject({
+ deployment: expect.not.stringContaining("example.com"),
+ });
+ });
+});
diff --git a/packages/project/src/db/workspace.test.ts b/packages/project/src/db/workspace.test.ts
new file mode 100644
index 0000000000..7979a667af
--- /dev/null
+++ b/packages/project/src/db/workspace.test.ts
@@ -0,0 +1,516 @@
+import { describe, test, expect } from "vitest";
+import {
+ createTestServer,
+ db,
+ json,
+ empty,
+ testContext,
+} from "@webstudio-is/postgrest/testing";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { AuthorizationError } from "@webstudio-is/trpc-interface/index.server";
+import { defaultPlanFeatures } from "@webstudio-is/trpc-interface/plan-features";
+import {
+ create,
+ rename,
+ remove,
+ findMany,
+ countAllMembers,
+ addMember,
+ updateRole,
+ removeMember,
+ moveProject,
+ transferProject,
+ findSharedWorkspacesByOwnerEmail,
+} from "./workspace";
+
+const server = createTestServer();
+
+const createContext = (userId = "user-1"): AppContext =>
+ ({
+ ...testContext,
+ authorization: { type: "user", userId },
+ getOwnerPlanFeatures: async () => defaultPlanFeatures,
+ }) as unknown as AppContext;
+
+const workspaceRow = {
+ id: "ws-1",
+ name: "My Workspace",
+ userId: "user-1",
+ isDefault: false,
+ isDeleted: false,
+ createdAt: "2024-01-01T00:00:00.000Z",
+};
+
+// ---------------------------------------------------------------------------
+// create
+// ---------------------------------------------------------------------------
+
+describe("create (msw)", () => {
+ test("throws for non-user auth (anonymous)", async () => {
+ const ctx = {
+ ...testContext,
+ authorization: { type: "anonymous" },
+ } as unknown as AppContext;
+ await expect(
+ create({ name: "Test", maxWorkspaces: 5 }, ctx)
+ ).rejects.toThrow(AuthorizationError);
+ });
+
+ test("throws when workspace name is too short", async () => {
+ await expect(
+ create({ name: "x", maxWorkspaces: 5 }, createContext())
+ ).rejects.toThrow("at least 2 characters");
+ });
+
+ test("throws when user is at the workspace limit", async () => {
+ server.use(
+ db.head("Workspace", () => empty({ headers: { "Content-Range": "*/5" } }))
+ );
+
+ await expect(
+ create({ name: "New WS", maxWorkspaces: 5 }, createContext())
+ ).rejects.toThrow("maximum number of workspaces");
+ });
+
+ test("creates workspace when under limit", async () => {
+ server.use(
+ db.head("Workspace", () =>
+ empty({ headers: { "Content-Range": "*/2" } })
+ ),
+ db.post("Workspace", () => json(workspaceRow, { status: 201 }))
+ );
+
+ const result = await create(
+ { name: "New WS", maxWorkspaces: 5 },
+ createContext()
+ );
+ expect(result.name).toBe("My Workspace");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// rename
+// ---------------------------------------------------------------------------
+
+describe("rename (msw)", () => {
+ test("throws for name too short", async () => {
+ await expect(
+ rename({ workspaceId: "ws-1", name: "x" }, createContext())
+ ).rejects.toThrow("at least 2 characters");
+ });
+
+ test("renames workspace and returns updated row", async () => {
+ server.use(
+ db.patch("Workspace", () => json({ ...workspaceRow, name: "Renamed" }))
+ );
+
+ const result = await rename(
+ { workspaceId: "ws-1", name: "Renamed" },
+ createContext()
+ );
+ expect(result.name).toBe("Renamed");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// remove
+// ---------------------------------------------------------------------------
+
+describe("remove (msw)", () => {
+ test("throws when workspace has projects and deleteProjects is not set", async () => {
+ server.use(
+ db.get("Workspace", () => json(workspaceRow)),
+ db.get("Project", () => json([{ id: "proj-1" }]))
+ );
+
+ await expect(
+ remove({ workspaceId: "ws-1" }, createContext())
+ ).rejects.toThrow("still contains projects");
+ });
+
+ test("throws when caller is not the owner", async () => {
+ server.use(
+ db.get("Workspace", () => json({ ...workspaceRow, userId: "other-user" }))
+ );
+
+ await expect(
+ remove({ workspaceId: "ws-1" }, createContext("user-1"))
+ ).rejects.toThrow(AuthorizationError);
+ });
+
+ test("throws when trying to delete the default workspace", async () => {
+ server.use(
+ db.get("Workspace", () => json({ ...workspaceRow, isDefault: true }))
+ );
+
+ await expect(
+ remove({ workspaceId: "ws-1" }, createContext())
+ ).rejects.toThrow("default workspace cannot be deleted");
+ });
+
+ test("soft-deletes workspace when empty", async () => {
+ let patched = false;
+ server.use(
+ db.get("Workspace", () => json(workspaceRow)),
+ db.get("Project", () => json([])),
+ db.patch("Workspace", () => {
+ patched = true;
+ return empty({ status: 204 });
+ })
+ );
+
+ await remove({ workspaceId: "ws-1" }, createContext());
+ expect(patched).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// findMany
+// ---------------------------------------------------------------------------
+
+describe("findMany (msw)", () => {
+ test("returns owned workspaces with role=own", async () => {
+ server.use(
+ db.get("Workspace", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.get("userId")) {
+ return json([workspaceRow]);
+ }
+ return json([]);
+ }),
+ db.get("WorkspaceMember", () => json([]))
+ );
+
+ const result = await findMany("user-1", createContext());
+ expect(result).toHaveLength(1);
+ expect(result[0].role).toBe("own");
+ expect(result[0].isDowngraded).toBe(false);
+ });
+
+ test("returns member workspaces with isDowngraded=true when owner plan maxWorkspaces<=1", async () => {
+ server.use(
+ // owned: none
+ db.get("Workspace", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("userId")) {
+ // first call: owned workspaces (eq userId)
+ if (url.searchParams.get("userId") === "eq.user-1") {
+ return json([]);
+ }
+ // third call: member workspace details
+ return json([{ ...workspaceRow, id: "ws-2", userId: "owner-2" }]);
+ }
+ // in workspaceIds
+ return json([{ ...workspaceRow, id: "ws-2", userId: "owner-2" }]);
+ }),
+ db.get("WorkspaceMember", () =>
+ json([{ workspaceId: "ws-2", relation: "editors" }])
+ )
+ );
+
+ const ctx = createContext();
+ ctx.getOwnerPlanFeatures = async () => ({
+ ...defaultPlanFeatures,
+ maxWorkspaces: 1,
+ });
+
+ const result = await findMany("user-1", ctx);
+ const member = result.find((w) => w.id === "ws-2");
+ expect(member?.isDowngraded).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// countAllMembers
+// ---------------------------------------------------------------------------
+
+describe("countAllMembers (msw)", () => {
+ test("returns 0 when user has no workspaces", async () => {
+ server.use(db.get("Workspace", () => json([])));
+
+ const count = await countAllMembers("user-1", createContext());
+ expect(count).toBe(0);
+ });
+
+ test("returns sum of active members + pending invites", async () => {
+ server.use(
+ db.get("Workspace", () => json([workspaceRow])),
+ db.head("WorkspaceMember", () =>
+ empty({ headers: { "Content-Range": "*/3" } })
+ ),
+ db.head("Notification", () =>
+ empty({ headers: { "Content-Range": "*/2" } })
+ )
+ );
+
+ const count = await countAllMembers("user-1", createContext());
+ expect(count).toBe(5);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// addMember
+// ---------------------------------------------------------------------------
+
+describe("addMember (msw)", () => {
+ const ownerWorkspace = { id: "ws-1", userId: "user-1" };
+
+ test("silently succeeds when invited email does not exist", async () => {
+ server.use(
+ db.get("Workspace", () => json(ownerWorkspace)),
+ db.get("User", () => json(null))
+ );
+
+ const result = await addMember(
+ { workspaceId: "ws-1", email: "[email protected]", relation: "editors" },
+ createContext()
+ );
+ expect(typeof result.notificationId).toBe("string");
+ });
+
+ test("throws when inviting yourself", async () => {
+ server.use(
+ db.get("Workspace", () => json(ownerWorkspace)),
+ db.get("User", () =>
+ json({ id: "user-1", email: "[email protected]", username: "me" })
+ )
+ );
+
+ await expect(
+ addMember(
+ { workspaceId: "ws-1", email: "[email protected]", relation: "editors" },
+ createContext()
+ )
+ ).rejects.toThrow("already the owner");
+ });
+
+ test("silently succeeds when invitee is already a member", async () => {
+ server.use(
+ db.get("Workspace", () => json(ownerWorkspace)),
+ db.get("User", () =>
+ json({ id: "user-2", email: "[email protected]", username: "other" })
+ ),
+ db.get("WorkspaceMember", () => json({ userId: "user-2" }))
+ );
+
+ const result = await addMember(
+ { workspaceId: "ws-1", email: "[email protected]", relation: "editors" },
+ createContext()
+ );
+ expect(typeof result.notificationId).toBe("string");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// updateRole
+// ---------------------------------------------------------------------------
+
+describe("updateRole (msw)", () => {
+ const ownerWorkspace = { id: "ws-1", userId: "user-1" };
+
+ test("throws when trying to change own role", async () => {
+ server.use(db.get("Workspace", () => json(ownerWorkspace)));
+ await expect(
+ updateRole(
+ { workspaceId: "ws-1", memberUserId: "user-1", relation: "editors" },
+ createContext()
+ )
+ ).rejects.toThrow("Cannot change the workspace owner's role");
+ });
+
+ test("throws when member not found", async () => {
+ server.use(
+ db.get("Workspace", () => json(ownerWorkspace)),
+ db.patch("WorkspaceMember", () => json(null))
+ );
+
+ await expect(
+ updateRole(
+ { workspaceId: "ws-1", memberUserId: "user-2", relation: "editors" },
+ createContext()
+ )
+ ).rejects.toThrow("Member not found");
+ });
+
+ test("updates member role successfully", async () => {
+ server.use(
+ db.get("Workspace", () => json(ownerWorkspace)),
+ db.patch("WorkspaceMember", () =>
+ json({ userId: "user-2", relation: "editors" })
+ )
+ );
+
+ await updateRole(
+ { workspaceId: "ws-1", memberUserId: "user-2", relation: "editors" },
+ createContext()
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// removeMember
+// ---------------------------------------------------------------------------
+
+describe("removeMember (msw)", () => {
+ test("throws when owner tries to remove themselves", async () => {
+ server.use(
+ db.get("Workspace", () => json({ id: "ws-1", userId: "user-1" }))
+ );
+
+ await expect(
+ removeMember(
+ { workspaceId: "ws-1", memberUserId: "user-1" },
+ createContext()
+ )
+ ).rejects.toThrow("owner cannot be removed");
+ });
+
+ test("throws when member not found", async () => {
+ server.use(
+ db.get("Workspace", () => json({ id: "ws-1", userId: "user-1" })),
+ db.patch("WorkspaceMember", () => json(null))
+ );
+
+ await expect(
+ removeMember(
+ { workspaceId: "ws-1", memberUserId: "user-2" },
+ createContext()
+ )
+ ).rejects.toThrow("Member not found");
+ });
+
+ test("removes member successfully", async () => {
+ server.use(
+ db.get("Workspace", () => json({ id: "ws-1", userId: "user-1" })),
+ db.patch("WorkspaceMember", () => json({ userId: "user-2" }))
+ );
+
+ await removeMember(
+ { workspaceId: "ws-1", memberUserId: "user-2" },
+ createContext()
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// moveProject
+// ---------------------------------------------------------------------------
+
+describe("moveProject (msw)", () => {
+ test("throws when project not found", async () => {
+ server.use(
+ db.get("Project", () => {
+ throw new Error("error");
+ })
+ );
+
+ await expect(
+ moveProject(
+ { projectId: "proj-1", targetWorkspaceId: "ws-2" },
+ createContext()
+ )
+ ).rejects.toThrow();
+ });
+
+ test("throws when cross-owner move attempted", async () => {
+ server.use(
+ db.get("Project", ({ request }) => {
+ const url = new URL(request.url);
+ // assertProjectPermission selects by id+isDeleted
+ if (url.searchParams.get("isDeleted")) {
+ return json({ id: "proj-1", userId: "user-1", workspaceId: null });
+ }
+ return json(null);
+ }),
+ db.get("Workspace", () => json({ id: "ws-2", userId: "user-2" }))
+ );
+
+ await expect(
+ moveProject(
+ { projectId: "proj-1", targetWorkspaceId: "ws-2" },
+ createContext()
+ )
+ ).rejects.toThrow(AuthorizationError);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// transferProject
+// ---------------------------------------------------------------------------
+
+describe("transferProject (msw)", () => {
+ test("silently succeeds when recipient email not found", async () => {
+ server.use(
+ db.get("Project", () =>
+ json({ id: "proj-1", userId: "user-1", workspaceId: null })
+ ),
+ db.get("User", () => json(null))
+ );
+
+ await transferProject(
+ { projectId: "proj-1", recipientEmail: "[email protected]" },
+ createContext()
+ );
+ });
+
+ test("throws when transferring to yourself", async () => {
+ server.use(
+ db.get("Project", () =>
+ json({ id: "proj-1", userId: "user-1", workspaceId: null })
+ ),
+ db.get("User", () => json({ id: "user-1" }))
+ );
+
+ await expect(
+ transferProject(
+ { projectId: "proj-1", recipientEmail: "[email protected]" },
+ createContext()
+ )
+ ).rejects.toThrow("cannot transfer a project to yourself");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// findSharedWorkspacesByOwnerEmail
+// ---------------------------------------------------------------------------
+
+describe("findSharedWorkspacesByOwnerEmail (msw)", () => {
+ test("returns empty array when target user not found", async () => {
+ server.use(db.get("User", () => json(null)));
+
+ const result = await findSharedWorkspacesByOwnerEmail(
+ { email: "[email protected]" },
+ createContext()
+ );
+ expect(result).toEqual([]);
+ });
+
+ test("returns workspaces where caller is a member", async () => {
+ server.use(
+ db.get("User", () => json({ id: "user-2" })),
+ db.get("Workspace", () => json([{ id: "ws-shared", name: "Shared WS" }])),
+ db.get("WorkspaceMember", () => json([{ workspaceId: "ws-shared" }]))
+ );
+
+ const result = await findSharedWorkspacesByOwnerEmail(
+ { email: "[email protected]" },
+ createContext()
+ );
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe("ws-shared");
+ });
+
+ test("returns empty when caller is not a member of any target workspace", async () => {
+ server.use(
+ db.get("User", () => json({ id: "user-2" })),
+ db.get("Workspace", () => json([{ id: "ws-other", name: "Other WS" }])),
+ db.get("WorkspaceMember", () => json([]))
+ );
+
+ const result = await findSharedWorkspacesByOwnerEmail(
+ { email: "[email protected]" },
+ createContext()
+ );
+ expect(result).toEqual([]);
+ });
+});
diff --git a/packages/trpc-interface/package.json b/packages/trpc-interface/package.json
index 5247613655..35721e0c06 100644
--- a/packages/trpc-interface/package.json
+++ b/packages/trpc-interface/package.json
@@ -29,6 +29,9 @@
"./plan-features": {
"webstudio": "./src/shared/plan-features.ts"
},
+ "./plan-client": {
+ "webstudio": "./src/shared/plan-client.server.ts"
+ },
"./authorize": {
"webstudio": "./src/authorize/role.ts"
}
diff --git a/packages/trpc-interface/src/authorize/project.server.test.ts b/packages/trpc-interface/src/authorize/project.server.test.ts
index 72ddeadc47..00700eb494 100644
--- a/packages/trpc-interface/src/authorize/project.server.test.ts
+++ b/packages/trpc-interface/src/authorize/project.server.test.ts
@@ -1,7 +1,20 @@
import { describe, test, expect } from "vitest";
-import { __testing__ } from "./project.server";
+import {
+ createTestServer,
+ db,
+ json,
+ testContext,
+} from "@webstudio-is/postgrest/testing";
+import type { AppContext } from "../context/context.server";
+import { defaultPlanFeatures } from "../shared/plan-features";
+import {
+ checkProjectPermit,
+ hasProjectPermit,
+ getProjectPermit,
+ __testing__,
+} from "./project.server";
-const { isRolePermitted } = __testing__;
+const { isRolePermitted, getWorkspaceOwnerIdForProject } = __testing__;
describe("isRolePermitted", () => {
describe("workspace owner (own relation)", () => {
@@ -141,3 +154,290 @@ describe("isRolePermitted", () => {
});
});
});
+
+// ---------------------------------------------------------------------------
+// MSW integration tests
+// ---------------------------------------------------------------------------
+
+const server = createTestServer();
+
+// Each test uses a unique projectId so the memoized `check()` doesn't
+// return a cached result from a previous test.
+const uid = () => `proj-${Math.random().toString(36).slice(2)}`;
+
+const makeUserCtx = (userId = "user-1", maxWorkspaces = 5): AppContext =>
+ ({
+ ...testContext,
+ authorization: { type: "user", userId },
+ getOwnerPlanFeatures: async () => ({
+ ...defaultPlanFeatures,
+ maxWorkspaces,
+ }),
+ }) as unknown as AppContext;
+
+// ---------------------------------------------------------------------------
+// getWorkspaceOwnerIdForProject
+// ---------------------------------------------------------------------------
+
+describe("getWorkspaceOwnerIdForProject (msw)", () => {
+ test("returns undefined when project has no workspace", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json({ id: projectId, workspaceId: null }))
+ );
+ const result = await getWorkspaceOwnerIdForProject(projectId, testContext);
+ expect(result).toBeUndefined();
+ });
+
+ test("returns workspace owner userId when workspace exists", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json({ id: projectId, workspaceId: "ws-1" })),
+ db.get("Workspace", () => json({ id: "ws-1", userId: "owner-99" }))
+ );
+ const result = await getWorkspaceOwnerIdForProject(projectId, testContext);
+ expect(result).toBe("owner-99");
+ });
+
+ test("returns undefined when workspace not found", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json({ id: projectId, workspaceId: "ws-gone" })),
+ db.get("Workspace", () => json(null))
+ );
+ const result = await getWorkspaceOwnerIdForProject(projectId, testContext);
+ expect(result).toBeUndefined();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// checkProjectPermit — user auth
+// ---------------------------------------------------------------------------
+
+describe("checkProjectPermit — user direct owner (msw)", () => {
+ test("allows edit when user directly owns the project", async () => {
+ const projectId = uid();
+ server.use(db.get("Project", () => json({ id: projectId })));
+ const allowed = await checkProjectPermit({
+ projectId,
+ permit: "edit",
+ authInfo: { type: "user", userId: "user-1" },
+ postgrestClient: testContext.postgrest.client,
+ });
+ expect(allowed).toBe(true);
+ });
+
+ test("allows via workspace member relation", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json(null)),
+ db.get("WorkspaceProjectAuthorization", () =>
+ json([{ relation: "builders" }])
+ )
+ );
+ const allowed = await checkProjectPermit({
+ projectId,
+ permit: "build",
+ authInfo: { type: "user", userId: "user-2" },
+ postgrestClient: testContext.postgrest.client,
+ });
+ expect(allowed).toBe(true);
+ });
+
+ test("denies when user has insufficient workspace relation", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json(null)),
+ db.get("WorkspaceProjectAuthorization", () =>
+ json([{ relation: "viewers" }])
+ )
+ );
+ const allowed = await checkProjectPermit({
+ projectId,
+ permit: "edit",
+ authInfo: { type: "user", userId: "user-3" },
+ postgrestClient: testContext.postgrest.client,
+ });
+ expect(allowed).toBe(false);
+ });
+
+ test("denies when user has no access at all", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json(null)),
+ db.get("WorkspaceProjectAuthorization", () => json([]))
+ );
+ const allowed = await checkProjectPermit({
+ projectId,
+ permit: "view",
+ authInfo: { type: "user", userId: "user-4" },
+ postgrestClient: testContext.postgrest.client,
+ });
+ expect(allowed).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// checkProjectPermit — token auth
+// ---------------------------------------------------------------------------
+
+describe("checkProjectPermit — token auth (msw)", () => {
+ test("allows when token exists with matching relation", async () => {
+ const projectId = uid();
+ server.use(db.get("AuthorizationToken", () => json({ token: "tok-1" })));
+ const allowed = await checkProjectPermit({
+ projectId,
+ permit: "view",
+ authInfo: { type: "token", authToken: "tok-1" },
+ postgrestClient: testContext.postgrest.client,
+ });
+ expect(allowed).toBe(true);
+ });
+
+ test("denies when token not found", async () => {
+ const projectId = uid();
+ server.use(db.get("AuthorizationToken", () => json(null)));
+ const allowed = await checkProjectPermit({
+ projectId,
+ permit: "view",
+ authInfo: { type: "token", authToken: "tok-missing" },
+ postgrestClient: testContext.postgrest.client,
+ });
+ expect(allowed).toBe(false);
+ });
+
+ test("denies 'own' permit for tokens regardless of DB", async () => {
+ const projectId = uid();
+ const allowed = await checkProjectPermit({
+ projectId,
+ permit: "own",
+ authInfo: { type: "token", authToken: "tok-any" },
+ postgrestClient: testContext.postgrest.client,
+ });
+ expect(allowed).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// checkProjectPermit — service auth
+// ---------------------------------------------------------------------------
+
+describe("checkProjectPermit — service auth", () => {
+ test("service auth allows view without DB", async () => {
+ const projectId = uid();
+ const allowed = await checkProjectPermit({
+ projectId,
+ permit: "view",
+ authInfo: { type: "service" },
+ postgrestClient: testContext.postgrest.client,
+ });
+ expect(allowed).toBe(true);
+ });
+
+ test("service auth denies edit", async () => {
+ const projectId = uid();
+ const allowed = await checkProjectPermit({
+ projectId,
+ permit: "edit",
+ authInfo: { type: "service" },
+ postgrestClient: testContext.postgrest.client,
+ });
+ expect(allowed).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// hasProjectPermit — workspace downgrade guard
+// ---------------------------------------------------------------------------
+
+describe("hasProjectPermit — workspace downgrade guard (msw)", () => {
+ test("denies workspace member when owner plan has maxWorkspaces <= 1", async () => {
+ const projectId = uid();
+ server.use(
+ // Per-call routing: ownership check uses userId param; workspaceId lookup does not
+ db.get("Project", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("userId")) {
+ return json(null);
+ }
+ return json({ id: projectId, workspaceId: "ws-1" });
+ }),
+ db.get("WorkspaceProjectAuthorization", () =>
+ json([{ relation: "editors" }])
+ ),
+ db.get("Workspace", () => json({ id: "ws-1", userId: "owner-1" }))
+ );
+ const ctx = makeUserCtx("user-2", 1);
+
+ const allowed = await hasProjectPermit({ projectId, permit: "edit" }, ctx);
+ expect(allowed).toBe(false);
+ });
+
+ test("allows workspace member when owner plan has maxWorkspaces > 1", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", ({ request }) => {
+ const url = new URL(request.url);
+ if (url.searchParams.has("userId")) {
+ return json(null);
+ }
+ return json({ id: projectId, workspaceId: "ws-1" });
+ }),
+ db.get("WorkspaceProjectAuthorization", () =>
+ json([{ relation: "editors" }])
+ ),
+ db.get("Workspace", () => json({ id: "ws-1", userId: "owner-1" }))
+ );
+ const ctx = makeUserCtx("user-2", 5);
+
+ const allowed = await hasProjectPermit({ projectId, permit: "edit" }, ctx);
+ expect(allowed).toBe(true);
+ });
+
+ test("anonymous auth always denied without hitting DB", async () => {
+ const projectId = uid();
+ const ctx = {
+ ...testContext,
+ authorization: { type: "anonymous" },
+ getOwnerPlanFeatures: async () => defaultPlanFeatures,
+ } as unknown as AppContext;
+ const allowed = await hasProjectPermit({ projectId, permit: "view" }, ctx);
+ expect(allowed).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getProjectPermit
+// ---------------------------------------------------------------------------
+
+describe("getProjectPermit (msw)", () => {
+ test("returns first matching permit from ordered list", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json({ id: projectId })),
+ db.get("WorkspaceProjectAuthorization", () => json([]))
+ );
+ const ctx = makeUserCtx("user-1");
+
+ const permit = await getProjectPermit(
+ { projectId, permits: ["own", "admin", "edit"] },
+ ctx
+ );
+ expect(permit).toBe("own");
+ });
+
+ test("returns undefined when no permit matches", async () => {
+ const projectId = uid();
+ server.use(
+ db.get("Project", () => json(null)),
+ db.get("WorkspaceProjectAuthorization", () => json([]))
+ );
+ const ctx = makeUserCtx("user-no-access");
+
+ const permit = await getProjectPermit(
+ { projectId, permits: ["edit", "view"] },
+ ctx
+ );
+ expect(permit).toBeUndefined();
+ });
+});
diff --git a/packages/trpc-interface/src/authorize/project.server.ts b/packages/trpc-interface/src/authorize/project.server.ts
index c807865448..b68bfa225c 100644
--- a/packages/trpc-interface/src/authorize/project.server.ts
+++ b/packages/trpc-interface/src/authorize/project.server.ts
@@ -234,9 +234,9 @@ export const checkProjectPermit = async ({
*/
const getWorkspaceOwnerIdForProject = async (
projectId: string,
- postgrestClient: AppContext["postgrest"]["client"]
+ context: Pick<AppContext, "postgrest">
): Promise<string | undefined> => {
- const project = await postgrestClient
+ const project = await context.postgrest.client
.from("Project")
.select("workspaceId")
.eq("id", projectId)
@@ -246,7 +246,7 @@ const getWorkspaceOwnerIdForProject = async (
return;
}
- const workspace = await postgrestClient
+ const workspace = await context.postgrest.client
.from("Workspace")
.select("userId")
.eq("id", project.data.workspaceId)
@@ -303,7 +303,7 @@ export const hasProjectPermit = async (
// User is a workspace member — verify the owner's plan
const workspaceOwnerId = await getWorkspaceOwnerIdForProject(
props.projectId,
- context.postgrest.client
+ context
);
if (workspaceOwnerId !== undefined) {
diff --git a/packages/trpc-interface/src/shared/plan-client.server.test.ts b/packages/trpc-interface/src/shared/plan-client.server.test.ts
new file mode 100644
index 0000000000..afac7097ea
--- /dev/null
+++ b/packages/trpc-interface/src/shared/plan-client.server.test.ts
@@ -0,0 +1,272 @@
+import { describe, test, expect, beforeEach, vi } from "vitest";
+import {
+ createTestServer,
+ db,
+ json,
+ testContext,
+} from "@webstudio-is/postgrest/testing";
+import { type PlanFeatures, defaultPlanFeatures } from "./plan-features";
+import { getPlanInfo, __testing__ } from "./plan-client.server";
+
+const { parseProductMeta, mergeProductMetas, resetProductCache } = __testing__;
+
+// ---------------------------------------------------------------------------
+// Unit tests for private helpers
+// ---------------------------------------------------------------------------
+
+const server = createTestServer();
+
+beforeEach(() => {
+ resetProductCache();
+ vi.unstubAllEnvs();
+});
+
+const proProduct = {
+ id: "prod-pro",
+ name: "Pro",
+ meta: { maxDomainsAllowedPerUser: 10 },
+};
+
+const proUserProduct = {
+ userId: "user-1",
+ productId: "prod-pro",
+ subscriptionId: "sub-abc",
+};
+
+describe("getPlanInfo (msw)", () => {
+ test("empty userIds returns empty map without hitting DB", async () => {
+ const result = await getPlanInfo([], testContext);
+ expect(result.size).toBe(0);
+ });
+
+ test("user with no products returns defaultPlanFeatures", async () => {
+ server.use(db.get("UserProduct", () => json([])));
+
+ const result = await getPlanInfo(["user-1"], testContext);
+ expect(result.get("user-1")).toEqual({
+ planFeatures: defaultPlanFeatures,
+ purchases: [],
+ });
+ });
+
+ test("user with one product resolves plan features from PLANS env + meta merge", async () => {
+ vi.stubEnv(
+ "PLANS",
+ JSON.stringify([{ name: "Pro", maxDomainsAllowedPerUser: 5 }])
+ );
+ server.use(
+ db.get("UserProduct", () => json([proUserProduct])),
+ db.get("Product", () => json([proProduct]))
+ );
+
+ const result = await getPlanInfo(["user-1"], testContext);
+ const info = result.get("user-1");
+ // meta overrides env plan: maxDomainsAllowedPerUser should be 10 (from meta)
+ expect(info?.planFeatures.maxDomainsAllowedPerUser).toBe(10);
+ expect(info?.purchases).toEqual([
+ { planName: "Pro", subscriptionId: "sub-abc" },
+ ]);
+ });
+
+ test("product not in PLANS falls back to defaultPlanFeatures for that product", async () => {
+ vi.stubEnv("PLANS", JSON.stringify([]));
+ server.use(
+ db.get("UserProduct", () => json([proUserProduct])),
+ db.get("Product", () => json([proProduct]))
+ );
+
+ const result = await getPlanInfo(["user-1"], testContext);
+ const info = result.get("user-1");
+ // meta provides maxDomainsAllowedPerUser: 10, rest from defaultPlanFeatures
+ expect(info?.planFeatures.maxDomainsAllowedPerUser).toBe(10);
+ expect(info?.planFeatures.canDownloadAssets).toBe(
+ defaultPlanFeatures.canDownloadAssets
+ );
+ });
+
+ test("multiple users batched in one UserProduct query", async () => {
+ vi.stubEnv("PLANS", JSON.stringify([]));
+ server.use(
+ db.get("UserProduct", ({ request }) => {
+ const url = new URL(request.url);
+ // PostgREST IN filter: userId=in.(user-1,user-2)
+ expect(url.searchParams.get("userId")).toMatch(/user-1/);
+ expect(url.searchParams.get("userId")).toMatch(/user-2/);
+ return json([
+ proUserProduct,
+ { userId: "user-2", productId: "prod-pro", subscriptionId: null },
+ ]);
+ }),
+ db.get("Product", () => json([proProduct]))
+ );
+
+ const result = await getPlanInfo(["user-1", "user-2"], testContext);
+ expect(result.size).toBe(2);
+ expect(result.get("user-1")?.purchases[0].planName).toBe("Pro");
+ expect(result.get("user-2")?.purchases[0].subscriptionId).toBeUndefined();
+ });
+
+ test("UserProduct DB error throws", async () => {
+ server.use(
+ db.get("UserProduct", () =>
+ json({ message: "db error" }, { status: 500 })
+ )
+ );
+
+ await expect(getPlanInfo(["user-1"], testContext)).rejects.toThrow(
+ "Failed to fetch user products"
+ );
+ });
+
+ test("Product DB error throws and cache is cleared for retry", async () => {
+ server.use(
+ db.get("UserProduct", () => json([proUserProduct])),
+ db.get("Product", () => json({ message: "db error" }, { status: 500 }))
+ );
+
+ await expect(getPlanInfo(["user-1"], testContext)).rejects.toThrow(
+ "Failed to fetch products"
+ );
+
+ // After error the cache is cleared — next call should hit DB again
+ server.use(
+ db.get("UserProduct", () => json([proUserProduct])),
+ db.get("Product", () => json([proProduct]))
+ );
+ vi.stubEnv("PLANS", JSON.stringify([]));
+ const result = await getPlanInfo(["user-1"], testContext);
+ expect(result.get("user-1")?.purchases[0].planName).toBe("Pro");
+ });
+
+ test("Product table is queried only once across two calls (cache hit)", async () => {
+ vi.stubEnv("PLANS", JSON.stringify([]));
+ let productFetchCount = 0;
+ server.use(
+ db.get("UserProduct", () => json([proUserProduct])),
+ db.get("Product", () => {
+ productFetchCount += 1;
+ return json([proProduct]);
+ })
+ );
+
+ await getPlanInfo(["user-1"], testContext);
+ await getPlanInfo(["user-1"], testContext);
+
+ expect(productFetchCount).toBe(1);
+ });
+});
+
+/** Full-featured plan for use in tests — all booleans true, numeric limits at max */
+const fullFeatures: PlanFeatures = {
+ ...defaultPlanFeatures,
+ canDownloadAssets: true,
+ canRestoreBackups: true,
+ allowAdditionalPermissions: true,
+ allowDynamicData: true,
+ allowContentMode: true,
+ allowStagingPublish: true,
+ maxContactEmailsPerProject: 5,
+ maxDomainsAllowedPerUser: 100,
+ maxDailyPublishesPerUser: 100,
+ maxWorkspaces: 1,
+ maxProjectsAllowedPerUser: 100,
+};
+
+describe("parseProductMeta", () => {
+ test("extracts known keys from a valid object", () => {
+ const result = parseProductMeta({
+ maxContactEmailsPerProject: 10,
+ canDownloadAssets: true,
+ });
+ expect(result).toEqual({
+ maxContactEmailsPerProject: 10,
+ canDownloadAssets: true,
+ });
+ });
+
+ test("strips unknown keys", () => {
+ const result = parseProductMeta({
+ admin: true,
+ maxContactEmailsPerProject: 3,
+ });
+ expect(result).toEqual({ maxContactEmailsPerProject: 3 });
+ });
+
+ test("returns empty object for non-object input", () => {
+ expect(parseProductMeta("not an object")).toEqual({});
+ expect(parseProductMeta(42)).toEqual({});
+ expect(parseProductMeta(undefined)).toEqual({});
+ });
+
+ test("returns empty object for null input", () => {
+ expect(parseProductMeta(null)).toEqual({});
+ });
+
+ test("rejects negative numbers", () => {
+ const result = parseProductMeta({ maxContactEmailsPerProject: -1 });
+ expect(result).toEqual({});
+ });
+
+ test("accepts zero for numeric fields", () => {
+ const result = parseProductMeta({ maxWorkspaces: 0 });
+ expect(result).toEqual({ maxWorkspaces: 0 });
+ });
+
+ test("rejects wrong types for fields", () => {
+ const result = parseProductMeta({
+ canDownloadAssets: "yes",
+ maxContactEmailsPerProject: "five",
+ });
+ expect(result).toEqual({});
+ });
+});
+
+describe("mergeProductMetas", () => {
+ test("booleans: true if ANY product grants the feature", () => {
+ const result = mergeProductMetas([
+ { ...fullFeatures, canDownloadAssets: false, canRestoreBackups: true },
+ { ...fullFeatures, canDownloadAssets: true, canRestoreBackups: false },
+ ]);
+ expect(result.canDownloadAssets).toBe(true);
+ expect(result.canRestoreBackups).toBe(true);
+ });
+
+ test("booleans: false when NO product grants the feature", () => {
+ const result = mergeProductMetas([
+ { ...fullFeatures, canDownloadAssets: false },
+ { ...fullFeatures, canDownloadAssets: false },
+ ]);
+ expect(result.canDownloadAssets).toBe(false);
+ });
+
+ test("numbers: takes the highest value across products", () => {
+ const result = mergeProductMetas([
+ { ...fullFeatures, maxContactEmailsPerProject: 3, maxWorkspaces: 2 },
+ { ...fullFeatures, maxContactEmailsPerProject: 10, maxWorkspaces: 5 },
+ ]);
+ expect(result.maxContactEmailsPerProject).toBe(10);
+ expect(result.maxWorkspaces).toBe(5);
+ });
+
+ test("single product returns its values unchanged", () => {
+ const plan = { ...fullFeatures, maxWorkspaces: 7 };
+ const result = mergeProductMetas([plan]);
+ expect(result).toEqual(plan);
+ });
+
+ test("empty array returns defaultPlanFeatures", () => {
+ const result = mergeProductMetas([]);
+ expect(result).toEqual(defaultPlanFeatures);
+ });
+});
+
+describe("workspaces plan", () => {
+ test("merging pro + workspaces product picks highest maxWorkspaces", () => {
+ const proProduct = { ...fullFeatures, maxWorkspaces: 1 };
+ const workspacesProduct = { ...defaultPlanFeatures, maxWorkspaces: 20 };
+
+ const result = mergeProductMetas([proProduct, workspacesProduct]);
+ expect(result.maxWorkspaces).toBe(20);
+ expect(result.canDownloadAssets).toBe(true);
+ });
+});
diff --git a/packages/trpc-interface/src/shared/plan-client.server.ts b/packages/trpc-interface/src/shared/plan-client.server.ts
new file mode 100644
index 0000000000..2c3f9affef
--- /dev/null
+++ b/packages/trpc-interface/src/shared/plan-client.server.ts
@@ -0,0 +1,208 @@
+import {
+ type PlanFeatures,
+ PlanFeaturesSchema,
+ defaultPlanFeatures,
+ parsePlansEnv,
+ type Purchase,
+} from "./plan-features";
+import type { AppContext } from "../context/context.server";
+
+export { parsePlansEnv } from "./plan-features";
+
+type PlanInfo = {
+ planFeatures: PlanFeatures;
+ purchases: Array<Purchase>;
+};
+
+const parseProductMeta = (meta: unknown): Partial<PlanFeatures> => {
+ const result = PlanFeaturesSchema.partial().safeParse(meta);
+ return result.success ? result.data : {};
+};
+
+const mergeProductMetas = (productMetas: Array<PlanFeatures>): PlanFeatures => {
+ if (productMetas.length === 0) {
+ return defaultPlanFeatures;
+ }
+
+ return Object.fromEntries(
+ (Object.keys(defaultPlanFeatures) as Array<keyof PlanFeatures>).map(
+ (key) => {
+ const vals = productMetas.map((item) => item[key]);
+ const merged =
+ typeof defaultPlanFeatures[key] === "boolean"
+ ? (vals as Array<boolean>).some(Boolean)
+ : Math.max(...(vals as Array<number>));
+ return [key, merged];
+ }
+ )
+ ) as PlanFeatures;
+};
+
+const buildPurchases = (
+ userProducts: Array<{
+ productId: string | null | undefined;
+ subscriptionId: string | null | undefined;
+ }>,
+ productIdToName: Map<string, string>
+): Array<Purchase> => {
+ const purchases: Array<Purchase> = [];
+ for (const userProduct of userProducts) {
+ if (userProduct.productId === null || userProduct.productId === undefined) {
+ continue;
+ }
+ purchases.push({
+ planName: productIdToName.get(userProduct.productId) ?? "",
+ subscriptionId: userProduct.subscriptionId ?? undefined,
+ });
+ }
+ return purchases;
+};
+
+type Product = { id: string; name: string; meta: unknown };
+
+// Products are admin-created and rarely change. Cache them for the lifetime of the
+// server instance to avoid a repeated DB round-trip on every request.
+// The promise itself is cached to deduplicate concurrent cold-start requests.
+let productCachePromise: Promise<Map<string, Product>> | undefined;
+
+const getProductCache = (
+ postgrest: AppContext["postgrest"]
+): Promise<Map<string, Product>> => {
+ if (productCachePromise !== undefined) {
+ return productCachePromise;
+ }
+ const promise: Promise<Map<string, Product>> = Promise.resolve(
+ postgrest.client.from("Product").select("id, name, meta")
+ ).then((result) => {
+ if (result.error) {
+ productCachePromise = undefined;
+ console.error(result.error);
+ throw new Error("Failed to fetch products");
+ }
+ return new Map(result.data.map((p) => [p.id, p as Product]));
+ });
+ productCachePromise = promise;
+ return promise;
+};
+
+export const getPlanInfo = async (
+ userIds: string[],
+ context: Pick<AppContext, "postgrest">
+): Promise<Map<string, PlanInfo>> => {
+ const { postgrest } = context;
+
+ if (userIds.length === 0) {
+ return new Map();
+ }
+
+ const userProductsResult = await postgrest.client
+ .from("UserProduct")
+ .select("userId, subscriptionId, productId")
+ .in("userId", userIds);
+
+ if (userProductsResult.error) {
+ console.error(userProductsResult.error);
+ throw new Error("Failed to fetch user products");
+ }
+
+ const userProductsByUserId = new Map<
+ string,
+ Array<{
+ productId: string | null;
+ subscriptionId: string | null;
+ }>
+ >();
+
+ for (const row of userProductsResult.data) {
+ if (row.userId === null) {
+ continue;
+ }
+ const rows = userProductsByUserId.get(row.userId) ?? [];
+ rows.push({
+ productId: row.productId,
+ subscriptionId: row.subscriptionId,
+ });
+ userProductsByUserId.set(row.userId, rows);
+ }
+
+ const productIds = [
+ ...new Set(
+ userProductsResult.data.flatMap(({ productId }) =>
+ productId === null || productId === undefined ? [] : [productId]
+ )
+ ),
+ ];
+
+ if (productIds.length === 0) {
+ return new Map(
+ userIds.map((userId) => [
+ userId,
+ { planFeatures: defaultPlanFeatures, purchases: [] },
+ ])
+ );
+ }
+
+ const allProducts = await getProductCache(postgrest);
+ const productById = new Map(
+ productIds.flatMap((id) => {
+ const product = allProducts.get(id);
+ return product !== undefined ? [[id, product] as const] : [];
+ })
+ );
+ const productIdToName = new Map(
+ [...productById.values()].map((product) => [product.id, product.name])
+ );
+ const plansByName = parsePlansEnv(process.env.PLANS ?? "[]");
+
+ return new Map(
+ userIds.map((userId) => {
+ const userProducts = userProductsByUserId.get(userId) ?? [];
+ const productMetas = userProducts.flatMap(({ productId }) => {
+ if (productId === null || productId === undefined) {
+ return [];
+ }
+ const product = productById.get(productId);
+ if (product === undefined) {
+ return [];
+ }
+ return [
+ {
+ ...(plansByName.get(product.name) ?? defaultPlanFeatures),
+ ...parseProductMeta(product.meta),
+ },
+ ];
+ });
+
+ return [
+ userId,
+ {
+ planFeatures: mergeProductMetas(productMetas),
+ purchases: buildPurchases(userProducts, productIdToName),
+ },
+ ];
+ })
+ );
+};
+
+/** Resets the module-level product cache. Only for use in tests. */
+const resetProductCache = () => {
+ productCachePromise = undefined;
+};
+
+export const __testing__ = {
+ parseProductMeta,
+ mergeProductMetas,
+ resetProductCache,
+};
+
+export const getAuthorizationOwnerId = (
+ authorization: AppContext["authorization"]
+): string | undefined => {
+ if (authorization.type === "token") {
+ return authorization.ownerId;
+ }
+ if (authorization.type === "user") {
+ return authorization.userId;
+ }
+ return undefined;
+};
diff --git a/apps/builder/app/shared/db/plan-features.server.test.ts b/packages/trpc-interface/src/shared/plan-features.test.ts
similarity index 52%
rename from apps/builder/app/shared/db/plan-features.server.test.ts
rename to packages/trpc-interface/src/shared/plan-features.test.ts
index 5fce74e9d7..fcd9947a1f 100644
--- a/apps/builder/app/shared/db/plan-features.server.test.ts
+++ b/packages/trpc-interface/src/shared/plan-features.test.ts
@@ -2,10 +2,8 @@ import { describe, test, expect } from "vitest";
import {
type PlanFeatures,
defaultPlanFeatures,
-} from "@webstudio-is/trpc-interface/plan-features";
-import { __testing__ } from "./plan-features.server";
-
-const { parseProductMeta, mergeProductMetas, parsePlansEnv } = __testing__;
+ parsePlansEnv,
+} from "./plan-features";
/** Full-featured plan for use in tests — all booleans true, numeric limits at max */
const fullFeatures: PlanFeatures = {
@@ -23,115 +21,6 @@ const fullFeatures: PlanFeatures = {
maxProjectsAllowedPerUser: 100,
};
-describe("parseProductMeta", () => {
- test("extracts known keys from a valid object", () => {
- const result = parseProductMeta({
- maxContactEmailsPerProject: 10,
- canDownloadAssets: true,
- });
- expect(result).toEqual({
- maxContactEmailsPerProject: 10,
- canDownloadAssets: true,
- });
- });
-
- test("strips unknown keys", () => {
- const result = parseProductMeta({
- admin: true,
- maxContactEmailsPerProject: 3,
- });
- expect(result).toEqual({ maxContactEmailsPerProject: 3 });
- });
-
- test("returns empty object for non-object input", () => {
- expect(parseProductMeta("not an object")).toEqual({});
- expect(parseProductMeta(42)).toEqual({});
- expect(parseProductMeta(undefined)).toEqual({});
- });
-
- test("returns empty object for null input", () => {
- expect(parseProductMeta(null)).toEqual({});
- });
-
- test("rejects negative numbers", () => {
- const result = parseProductMeta({ maxContactEmailsPerProject: -1 });
- expect(result).toEqual({});
- });
-
- test("accepts zero for numeric fields", () => {
- const result = parseProductMeta({ maxWorkspaces: 0 });
- expect(result).toEqual({ maxWorkspaces: 0 });
- });
-
- test("rejects wrong types for fields", () => {
- const result = parseProductMeta({
- canDownloadAssets: "yes",
- maxContactEmailsPerProject: "five",
- });
- expect(result).toEqual({});
- });
-});
-
-describe("mergeProductMetas", () => {
- test("booleans: true if ANY product grants the feature", () => {
- const result = mergeProductMetas([
- {
- ...fullFeatures,
- canDownloadAssets: false,
- canRestoreBackups: true,
- },
- {
- ...fullFeatures,
- canDownloadAssets: true,
- canRestoreBackups: false,
- },
- ]);
- expect(result.canDownloadAssets).toBe(true);
- expect(result.canRestoreBackups).toBe(true);
- });
-
- test("booleans: false when NO product grants the feature", () => {
- const result = mergeProductMetas([
- { ...fullFeatures, canDownloadAssets: false },
- { ...fullFeatures, canDownloadAssets: false },
- ]);
- expect(result.canDownloadAssets).toBe(false);
- });
-
- test("numbers: takes the highest value across products", () => {
- const result = mergeProductMetas([
- { ...fullFeatures, maxContactEmailsPerProject: 3, maxWorkspaces: 2 },
- { ...fullFeatures, maxContactEmailsPerProject: 10, maxWorkspaces: 5 },
- ]);
- expect(result.maxContactEmailsPerProject).toBe(10);
- expect(result.maxWorkspaces).toBe(5);
- });
-
- test("single product returns its values unchanged", () => {
- const plan = { ...fullFeatures, maxWorkspaces: 7 };
- const result = mergeProductMetas([plan]);
- expect(result).toEqual(plan);
- });
-
- test("empty array returns defaultPlanFeatures", () => {
- const result = mergeProductMetas([]);
- expect(result).toEqual(defaultPlanFeatures);
- });
-});
-
-describe("workspaces plan", () => {
- test("merging pro + workspaces product picks highest maxWorkspaces", () => {
- // Pro product grants all features with maxWorkspaces: 1
- const proProduct = { ...fullFeatures, maxWorkspaces: 1 };
- // Workspaces add-on only grants extra workspaces; all other fields default to false/0
- const workspacesProduct = { ...defaultPlanFeatures, maxWorkspaces: 20 };
-
- const result = mergeProductMetas([proProduct, workspacesProduct]);
- expect(result.maxWorkspaces).toBe(20);
- expect(result.canDownloadAssets).toBe(true);
- });
-});
-
describe("parsePlansEnv", () => {
const validEntry = JSON.stringify({ name: "Pro", features: fullFeatures });
const twoEntries = JSON.stringify([
@@ -176,11 +65,8 @@ describe("parsePlansEnv", () => {
])
);
expect(result.size).toBe(2);
- // Team inherits all of Pro's features
expect(result.get("Team")!.canDownloadAssets).toBe(true);
- // but overrides maxWorkspaces
expect(result.get("Team")!.maxWorkspaces).toBe(50);
- // Pro itself is unchanged
expect(result.get("Pro")!.maxWorkspaces).toBe(fullFeatures.maxWorkspaces);
});
diff --git a/packages/trpc-interface/src/shared/plan-features.ts b/packages/trpc-interface/src/shared/plan-features.ts
index 38e0538064..b56137a723 100644
--- a/packages/trpc-interface/src/shared/plan-features.ts
+++ b/packages/trpc-interface/src/shared/plan-features.ts
@@ -54,3 +54,97 @@ export type Purchase = {
planName: string;
subscriptionId?: string;
};
+
+/**
+ * Parse the PLANS env variable (JSON array of {name, extends?, features}).
+ * - features is partial when extends is used; the parent plan fills in the rest.
+ * - The final merged features are validated against the full PlanFeaturesSchema.
+ * - Invalid entries are skipped with a console.error.
+ * - An extends reference to an unknown plan name throws an error.
+ * Returns a Map of plan name → resolved PlanFeatures.
+ */
+export const parsePlansEnv = (raw: string): Map<string, PlanFeatures> => {
+ try {
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed)) {
+ return new Map();
+ }
+
+ type PlanEntry = {
+ name: string;
+ extends?: string;
+ features: Partial<PlanFeatures>;
+ };
+
+ // First pass: validate entry structure and collect partial features.
+ const entries: PlanEntry[] = parsed.flatMap((item) => {
+ if (
+ typeof item !== "object" ||
+ item === null ||
+ typeof item.name !== "string"
+ ) {
+ console.error("Invalid PLANS entry (missing name):", item);
+ return [];
+ }
+ if ("extends" in item && typeof item.extends !== "string") {
+ console.error("Invalid PLANS entry (extends must be a string):", item);
+ return [];
+ }
+ const result = PlanFeaturesSchema.partial().safeParse(
+ "features" in item ? item.features : {}
+ );
+ if (!result.success) {
+ console.error(
+ `Invalid PLANS entry "${item.name}" features:`,
+ result.error.flatten()
+ );
+ return [];
+ }
+ return [
+ {
+ name: item.name,
+ extends: "extends" in item ? (item.extends as string) : undefined,
+ features: result.data,
+ } satisfies PlanEntry,
+ ];
+ });
+
+ // Build name → partial features map for resolving extends.
+ const byName = new Map<string, Partial<PlanFeatures>>(
+ entries.map((e) => [e.name, e.features])
+ );
+
+ // Second pass: resolve extends and validate the full feature set.
+ // Every entry implicitly extends defaultPlanFeatures; "extends" picks a named plan on top of that.
+ const resolved = new Map<string, PlanFeatures>();
+ for (const entry of entries) {
+ if (entry.extends !== undefined && !byName.has(entry.extends)) {
+ throw new Error(
+ `PLANS entry "${entry.name}" extends unknown plan "${entry.extends}"`
+ );
+ }
+ const parentFeatures: PlanFeatures =
+ entry.extends === undefined
+ ? defaultPlanFeatures
+ : { ...defaultPlanFeatures, ...byName.get(entry.extends)! };
+ const result = PlanFeaturesSchema.safeParse({
+ ...parentFeatures,
+ ...entry.features,
+ });
+ if (!result.success) {
+ console.error(
+ `Invalid PLANS entry "${entry.name}" features after resolving extends:`,
+ result.error.flatten()
+ );
+ continue;
+ }
+ resolved.set(entry.name, result.data);
+ }
+ return resolved;
+ } catch (error) {
+ if (error instanceof Error && error.message.startsWith("PLANS entry")) {
+ throw error;
+ }
+ return new Map();
+ }
+};