Skip to content

The open alternative to Salesforce, designed for AI.

feat(enterprise): withhold repeat trials by server id, flag repeat cards for review (#25620)

Marie13a73514e8bc
diff --git a/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx b/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx
index 6d03e73967c..ea32cd331ca 100644
--- a/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx
+++ b/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx
@@ -4,6 +4,7 @@ import { SubscriptionBenefit } from '@/settings/billing/components/SubscriptionB
import { ENTERPRISE_CHECKOUT_SESSION } from '@/settings/enterprise/graphql/queries/enterpriseCheckoutSession';
import { DialogInstance } from '@/ui/layout/dialog/components/DialogInstance';
import { useDialog } from '@/ui/layout/dialog/hooks/useDialog';
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
import { useApolloClient } from '@apollo/client/react';
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
@@ -13,6 +14,7 @@ import { Loader } from 'twenty-ui/primitives/feedback';
import { Radio, RadioGroup } from 'twenty-ui/primitives/input';
import { Dialog } from 'twenty-ui/primitives/surfaces';
import { themeCssVariables } from 'twenty-ui/theme';
+import { getErrorMessageFromApolloError } from '~/utils/get-error-message-from-apollo-error.util';
const StyledCheckoutButton = styled(MainButton)`
width: 200px;
@@ -136,8 +138,13 @@ export const EnterprisePlanModal = () => {
children: t`Could not open Stripe. Please contact support.`,
});
}
- } catch {
- enqueueToast({ variant: 'error', children: t`Error opening Stripe` });
+ } catch (error) {
+ enqueueToast({
+ variant: 'error',
+ children: CombinedGraphQLErrors.is(error)
+ ? getErrorMessageFromApolloError(error)
+ : t`Error opening Stripe`,
+ });
} finally {
setIsLoading(false);
}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts b/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
index 3b48e3af776..d001a025e8a 100644
--- a/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
@@ -615,12 +615,24 @@ export class EnterprisePlanService implements OnModuleInit {
}
const checkoutUrl = `${apiUrl}/checkout`;
+ const serverId = await this.getOrCreateServerId();
+
+ if (!isDefined(serverId)) {
+ throw new EnterpriseException(
+ 'Enterprise checkout requires a server id',
+ EnterpriseExceptionCode.ENTERPRISE_MISSING_SERVER_ID,
+ );
+ }
try {
const response = await fetch(checkoutUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ billingInterval, seatCount }),
+ body: JSON.stringify({
+ billingInterval,
+ seatCount,
+ instanceMetadata: { serverId },
+ }),
});
if (!response.ok) {
diff --git a/packages/twenty-website/.dev.vars.example b/packages/twenty-website/.dev.vars.example
index 9cd2773ff6c..4bc870e4817 100644
--- a/packages/twenty-website/.dev.vars.example
+++ b/packages/twenty-website/.dev.vars.example
@@ -2,6 +2,8 @@ NEXTJS_ENV=development
# Stripe — use a test-mode key locally
STRIPE_SECRET_KEY=
+# From `stripe listen --forward-to localhost:3000/api/enterprise/stripe-webhook`
+STRIPE_WEBHOOK_SECRET=
# Enterprise JWT — generate a test RSA keypair for local dev
ENTERPRISE_JWT_PRIVATE_KEY=
diff --git a/packages/twenty-website/.env.example b/packages/twenty-website/.env.example
index 114263f5366..96770c70008 100644
--- a/packages/twenty-website/.env.example
+++ b/packages/twenty-website/.env.example
@@ -27,6 +27,9 @@ TWENTY_MARKETPLACE_API_URL=
STRIPE_SECRET_KEY=
STRIPE_ENTERPRISE_MONTHLY_PRICE_ID=
STRIPE_ENTERPRISE_YEARLY_PRICE_ID=
+# Signing secret of the Stripe endpoint pointed at /api/enterprise/stripe-webhook.
+# Without it the webhook returns 503 and repeat trial cards go unrecorded.
+STRIPE_WEBHOOK_SECRET=
# RS256 key pair used to sign and verify enterprise license JWTs
# (use literal \n for newlines in the PEM values).
diff --git a/packages/twenty-website/src/app/api/enterprise/checkout/route.test.ts b/packages/twenty-website/src/app/api/enterprise/checkout/route.test.ts
new file mode 100644
index 00000000000..703668bb540
--- /dev/null
+++ b/packages/twenty-website/src/app/api/enterprise/checkout/route.test.ts
@@ -0,0 +1,130 @@
+// oxlint-disable-next-line unicorn/require-module-specifiers -- isolate from the other route.test globals
+export {};
+
+const ORIGINAL_ENV = { ...process.env };
+
+const SERVER_ID = 'server-1';
+
+const search = jest.fn();
+const createSession = jest.fn();
+
+jest.mock('@/platform/enterprise', () => ({
+ ...jest.requireActual('@/platform/enterprise'),
+ getStripeClient: () => ({
+ subscriptions: { search },
+ checkout: { sessions: { create: createSession } },
+ }),
+}));
+
+const buildRequest = (body: Record<string, unknown>) =>
+ new Request('https://example.com/api/enterprise/checkout', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+const loadRoute = async () => {
+ jest.resetModules();
+
+ return import('@/app/api/enterprise/checkout/route');
+};
+
+describe('POST /api/enterprise/checkout', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ process.env.STRIPE_SECRET_KEY = 'sk_test';
+ process.env.STRIPE_ENTERPRISE_MONTHLY_PRICE_ID = 'price_monthly';
+ process.env.STRIPE_ENTERPRISE_YEARLY_PRICE_ID = 'price_yearly';
+ process.env.NEXT_PUBLIC_WEBSITE_URL = 'https://example.com';
+ search.mockResolvedValue({ data: [] });
+ createSession.mockResolvedValue({ url: 'https://checkout.stripe.com/s' });
+ });
+
+ afterAll(() => {
+ process.env = ORIGINAL_ENV;
+ });
+
+ it('grants a trial to a server with no prior subscription and stamps it', async () => {
+ const { POST } = await loadRoute();
+
+ const response = await POST(
+ buildRequest({ instanceMetadata: { serverId: SERVER_ID } }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(search).toHaveBeenCalledTimes(1);
+ expect(createSession).toHaveBeenCalledTimes(1);
+ expect(createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ subscription_data: {
+ trial_period_days: 30,
+ metadata: {
+ source: 'enterprise-self-hosted',
+ trialServerId: SERVER_ID,
+ },
+ },
+ }),
+ );
+ });
+
+ it('withholds the trial from a server that already had one', async () => {
+ search.mockResolvedValue({ data: [{ id: 'sub_prior' }] });
+ const { POST } = await loadRoute();
+
+ const response = await POST(
+ buildRequest({ instanceMetadata: { serverId: SERVER_ID } }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(createSession).toHaveBeenCalledTimes(1);
+ expect(createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ subscription_data: {
+ metadata: { source: 'enterprise-self-hosted' },
+ },
+ }),
+ );
+ });
+
+ it.each([
+ ['no instanceMetadata', {}],
+ ['a null server id', { instanceMetadata: { serverId: null } }],
+ ['a blank server id', { instanceMetadata: { serverId: ' ' } }],
+ [
+ 'a server id Stripe search cannot take',
+ { instanceMetadata: { serverId: "x' OR status:'active" } },
+ ],
+ ])(
+ 'grants an unstamped trial to a checkout with %s',
+ async (_label, body) => {
+ const { POST } = await loadRoute();
+
+ const response = await POST(buildRequest(body));
+
+ expect(response.status).toBe(200);
+ expect(search).not.toHaveBeenCalled();
+ expect(createSession).toHaveBeenCalledTimes(1);
+ expect(createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ subscription_data: {
+ trial_period_days: 30,
+ metadata: { source: 'enterprise-self-hosted' },
+ },
+ }),
+ );
+ },
+ );
+
+ it('is unconfigured without a Stripe key', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ delete process.env.STRIPE_SECRET_KEY;
+ const { POST } = await loadRoute();
+
+ const response = await POST(
+ buildRequest({ instanceMetadata: { serverId: SERVER_ID } }),
+ );
+
+ expect(response.status).toBe(503);
+ expect(createSession).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-website/src/app/api/enterprise/checkout/route.ts b/packages/twenty-website/src/app/api/enterprise/checkout/route.ts
index 951bbb7516e..8b6b0e62f4c 100644
--- a/packages/twenty-website/src/app/api/enterprise/checkout/route.ts
+++ b/packages/twenty-website/src/app/api/enterprise/checkout/route.ts
@@ -1,6 +1,16 @@
import { NextResponse } from 'next/server';
-import { getEnterprisePriceId, getStripeClient } from '@/platform/enterprise';
+import {
+ getEnterprisePriceId,
+ getStripeClient,
+ hasPriorSubscriptionForServer,
+ isSearchableMetadataValue,
+ normalizeServerId,
+ resolveTrialPeriodDays,
+ STRIPE_METADATA_KEY,
+} from '@/platform/enterprise';
+
+const DEFAULT_TRIAL_PERIOD_DAYS = 30;
export const dynamic = 'force-dynamic';
@@ -21,6 +31,7 @@ export async function POST(request: Request) {
billingInterval?: unknown;
seatCount?: unknown;
successUrl?: unknown;
+ instanceMetadata?: { serverId?: unknown };
};
const billingInterval =
@@ -48,6 +59,21 @@ export async function POST(request: Request) {
? body.seatCount
: 1;
+ const serverId = normalizeServerId(body.instanceMetadata?.serverId);
+
+ const trialPeriodDays = resolveTrialPeriodDays({
+ defaultTrialPeriodDays: DEFAULT_TRIAL_PERIOD_DAYS,
+ hasPriorSubscription: await hasPriorSubscriptionForServer({
+ stripe,
+ serverId,
+ }),
+ });
+
+ const trialServerIdMetadata: Record<string, string> =
+ trialPeriodDays !== undefined && isSearchableMetadataValue(serverId)
+ ? { [STRIPE_METADATA_KEY.TRIAL_SERVER_ID]: serverId }
+ : {};
+
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
line_items: [
@@ -58,9 +84,12 @@ export async function POST(request: Request) {
],
success_url: successUrl,
subscription_data: {
- trial_period_days: 30,
+ ...(trialPeriodDays === undefined
+ ? {}
+ : { trial_period_days: trialPeriodDays }),
metadata: {
source: 'enterprise-self-hosted',
+ ...trialServerIdMetadata,
},
},
});
diff --git a/packages/twenty-website/src/app/api/enterprise/stripe-webhook/route.test.ts b/packages/twenty-website/src/app/api/enterprise/stripe-webhook/route.test.ts
new file mode 100644
index 00000000000..b481e836f69
--- /dev/null
+++ b/packages/twenty-website/src/app/api/enterprise/stripe-webhook/route.test.ts
@@ -0,0 +1,147 @@
+// oxlint-disable-next-line unicorn/require-module-specifiers -- isolate from the other route.test globals
+export {};
+
+const ORIGINAL_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
+const ORIGINAL_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET;
+
+const SUBSCRIPTION_ID = 'sub_new';
+
+const constructEventAsync = jest.fn();
+const recordTrialCard = jest.fn();
+
+jest.mock('@/platform/enterprise', () => ({
+ ...jest.requireActual('@/platform/enterprise'),
+ getStripeClient: () => ({ webhooks: { constructEventAsync } }),
+ recordTrialCard: (...args: unknown[]) => recordTrialCard(...args),
+}));
+
+const buildRequest = ({
+ signature = 't=1,v1=deadbeef',
+}: { signature?: string | null } = {}) => {
+ const headers = new Headers();
+
+ if (signature !== null) {
+ headers.set('stripe-signature', signature);
+ }
+
+ return new Request('https://example.com/api/enterprise/stripe-webhook', {
+ method: 'POST',
+ headers,
+ body: '{}',
+ });
+};
+
+const loadRoute = async () => {
+ jest.resetModules();
+
+ return import('@/app/api/enterprise/stripe-webhook/route');
+};
+
+const checkoutCompleted = (subscription: unknown) => ({
+ type: 'checkout.session.completed',
+ data: { object: { subscription } },
+});
+
+describe('POST /api/enterprise/stripe-webhook', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ jest.spyOn(console, 'info').mockImplementation(() => {});
+ process.env.STRIPE_SECRET_KEY = 'sk_test';
+ process.env.STRIPE_WEBHOOK_SECRET = 'whsec_test';
+ recordTrialCard.mockResolvedValue('first-trial-for-card');
+ });
+
+ afterAll(() => {
+ process.env.STRIPE_SECRET_KEY = ORIGINAL_SECRET_KEY;
+ process.env.STRIPE_WEBHOOK_SECRET = ORIGINAL_WEBHOOK_SECRET;
+ });
+
+ it('records the trial card on a signed checkout completion', async () => {
+ constructEventAsync.mockResolvedValue(checkoutCompleted(SUBSCRIPTION_ID));
+ const { POST } = await loadRoute();
+
+ const response = await POST(buildRequest());
+
+ expect(response.status).toBe(200);
+ expect(recordTrialCard).toHaveBeenCalledTimes(1);
+ expect(recordTrialCard).toHaveBeenCalledWith(
+ expect.objectContaining({ subscriptionId: SUBSCRIPTION_ID }),
+ );
+ });
+
+ it('reads the subscription id from an expanded subscription', async () => {
+ constructEventAsync.mockResolvedValue(
+ checkoutCompleted({ id: SUBSCRIPTION_ID }),
+ );
+ const { POST } = await loadRoute();
+
+ await POST(buildRequest());
+
+ expect(recordTrialCard).toHaveBeenCalledWith(
+ expect.objectContaining({ subscriptionId: SUBSCRIPTION_ID }),
+ );
+ });
+
+ it('rejects a request with no signature without calling Stripe', async () => {
+ const { POST } = await loadRoute();
+
+ const response = await POST(buildRequest({ signature: null }));
+
+ expect(response.status).toBe(400);
+ expect(constructEventAsync).not.toHaveBeenCalled();
+ expect(recordTrialCard).not.toHaveBeenCalled();
+ });
+
+ it('rejects a forged signature', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ constructEventAsync.mockRejectedValue(new Error('no signatures found'));
+ const { POST } = await loadRoute();
+
+ const response = await POST(buildRequest({ signature: 't=1,v1=forged' }));
+
+ expect(response.status).toBe(400);
+ expect(recordTrialCard).not.toHaveBeenCalled();
+ });
+
+ it('acknowledges an event it does not act on', async () => {
+ constructEventAsync.mockResolvedValue({ type: 'invoice.paid', data: {} });
+ const { POST } = await loadRoute();
+
+ const response = await POST(buildRequest());
+
+ expect(response.status).toBe(200);
+ expect(recordTrialCard).not.toHaveBeenCalled();
+ });
+
+ it('acknowledges a checkout that created no subscription', async () => {
+ constructEventAsync.mockResolvedValue(checkoutCompleted(null));
+ const { POST } = await loadRoute();
+
+ const response = await POST(buildRequest());
+
+ expect(response.status).toBe(200);
+ expect(recordTrialCard).not.toHaveBeenCalled();
+ });
+
+ it('asks Stripe to redeliver when recording fails', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ constructEventAsync.mockResolvedValue(checkoutCompleted(SUBSCRIPTION_ID));
+ recordTrialCard.mockRejectedValue(new Error('stripe is down'));
+ const { POST } = await loadRoute();
+
+ const response = await POST(buildRequest());
+
+ expect(response.status).toBe(500);
+ });
+
+ it('is unconfigured without a webhook secret', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ delete process.env.STRIPE_WEBHOOK_SECRET;
+ const { POST } = await loadRoute();
+
+ const response = await POST(buildRequest());
+
+ expect(response.status).toBe(503);
+ expect(constructEventAsync).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-website/src/app/api/enterprise/stripe-webhook/route.ts b/packages/twenty-website/src/app/api/enterprise/stripe-webhook/route.ts
new file mode 100644
index 00000000000..cac3bce62f4
--- /dev/null
+++ b/packages/twenty-website/src/app/api/enterprise/stripe-webhook/route.ts
@@ -0,0 +1,76 @@
+import { NextResponse } from 'next/server';
+
+import {
+ getEnterpriseConfigError,
+ getStripeClient,
+ recordTrialCard,
+} from '@/platform/enterprise';
+
+export const dynamic = 'force-dynamic';
+
+export async function POST(request: Request) {
+ const configError = getEnterpriseConfigError({
+ route: 'enterprise-stripe-webhook',
+ feature: 'Enterprise Stripe webhooks',
+ requiredEnvVars: ['STRIPE_SECRET_KEY', 'STRIPE_WEBHOOK_SECRET'],
+ });
+
+ if (configError) {
+ return configError;
+ }
+
+ const signature = request.headers.get('stripe-signature');
+
+ if (!signature) {
+ return NextResponse.json({ error: 'Missing signature' }, { status: 400 });
+ }
+
+ const stripe = getStripeClient();
+ const payload = await request.text();
+
+ let event;
+
+ try {
+ event = await stripe.webhooks.constructEventAsync(
+ payload,
+ signature,
+ process.env.STRIPE_WEBHOOK_SECRET as string,
+ );
+ } catch (error: unknown) {
+ console.error('[enterprise-stripe-webhook] signature check failed', error);
+
+ return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
+ }
+
+ if (event.type !== 'checkout.session.completed') {
+ return NextResponse.json({ received: true });
+ }
+
+ const subscription = event.data.object.subscription;
+ const subscriptionId =
+ typeof subscription === 'string' ? subscription : subscription?.id;
+
+ if (!subscriptionId) {
+ return NextResponse.json({ received: true });
+ }
+
+ try {
+ const outcome = await recordTrialCard({ stripe, subscriptionId });
+
+ console.info(
+ `[enterprise-stripe-webhook] ${subscriptionId} trial card: ${outcome}`,
+ );
+ } catch (error: unknown) {
+ console.error(
+ `[enterprise-stripe-webhook] trial card recording failed for ${subscriptionId}`,
+ error,
+ );
+
+ return NextResponse.json(
+ { error: 'Trial card recording failed' },
+ { status: 500 },
+ );
+ }
+
+ return NextResponse.json({ received: true });
+}
diff --git a/packages/twenty-website/src/platform/enterprise/extract-card-fingerprint.ts b/packages/twenty-website/src/platform/enterprise/extract-card-fingerprint.ts
new file mode 100644
index 00000000000..5776584ed26
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/extract-card-fingerprint.ts
@@ -0,0 +1,15 @@
+import type Stripe from 'stripe';
+
+import { isSearchableMetadataValue } from './is-searchable-metadata-value';
+
+export function extractCardFingerprint(
+ paymentMethod: string | Stripe.PaymentMethod | null | undefined,
+): string | undefined {
+ if (typeof paymentMethod !== 'object' || paymentMethod === null) {
+ return undefined;
+ }
+
+ const fingerprint = paymentMethod.card?.fingerprint;
+
+ return isSearchableMetadataValue(fingerprint) ? fingerprint : undefined;
+}
diff --git a/packages/twenty-website/src/platform/enterprise/find-prior-trial-for-card.ts b/packages/twenty-website/src/platform/enterprise/find-prior-trial-for-card.ts
new file mode 100644
index 00000000000..55f076bd919
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/find-prior-trial-for-card.ts
@@ -0,0 +1,31 @@
+import type Stripe from 'stripe';
+
+import { isSearchableMetadataValue } from './is-searchable-metadata-value';
+import { STRIPE_METADATA_KEY } from './stripe-metadata-key';
+
+type SubscriptionSearcher = {
+ subscriptions: Pick<Stripe['subscriptions'], 'search'>;
+};
+
+export async function findPriorTrialForCard({
+ stripe,
+ cardFingerprint,
+ excludedSubscriptionId,
+}: {
+ stripe: SubscriptionSearcher;
+ cardFingerprint: unknown;
+ excludedSubscriptionId: string;
+}): Promise<string | undefined> {
+ if (!isSearchableMetadataValue(cardFingerprint)) {
+ return undefined;
+ }
+
+ const result = await stripe.subscriptions.search({
+ query: `metadata['${STRIPE_METADATA_KEY.TRIAL_CARD_FINGERPRINT}']:'${cardFingerprint}'`,
+ limit: 2,
+ });
+
+ return result.data.find(
+ (subscription) => subscription.id !== excludedSubscriptionId,
+ )?.id;
+}
diff --git a/packages/twenty-website/src/platform/enterprise/has-prior-subscription-for-server.test.ts b/packages/twenty-website/src/platform/enterprise/has-prior-subscription-for-server.test.ts
new file mode 100644
index 00000000000..a1dd1b72920
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/has-prior-subscription-for-server.test.ts
@@ -0,0 +1,75 @@
+import { hasPriorSubscriptionForServer } from './has-prior-subscription-for-server';
+
+const SERVER_ID = 'cf9dbd56-fdd5-45d1-80c1-1b22bb1ad994';
+const EXPECTED_QUERY = `metadata['trialServerId']:'${SERVER_ID}' OR metadata['boundServerId']:'${SERVER_ID}'`;
+
+const stripeReturning = (data: unknown[]) => {
+ const search = jest.fn().mockResolvedValue({ data });
+
+ return { stripe: { subscriptions: { search } }, search };
+};
+
+describe('hasPriorSubscriptionForServer', () => {
+ it('reports a prior subscription bound to the same server', async () => {
+ const { stripe, search } = stripeReturning([{ id: 'sub_old' }]);
+
+ await expect(
+ hasPriorSubscriptionForServer({ stripe, serverId: SERVER_ID }),
+ ).resolves.toBe(true);
+
+ expect(search).toHaveBeenCalledTimes(1);
+ expect(search).toHaveBeenCalledWith({ query: EXPECTED_QUERY, limit: 1 });
+ });
+
+ it('matches a server that consumed a trial and then released its binding', async () => {
+ const { stripe, search } = stripeReturning([{ id: 'sub_released' }]);
+
+ await expect(
+ hasPriorSubscriptionForServer({ stripe, serverId: SERVER_ID }),
+ ).resolves.toBe(true);
+
+ expect(search.mock.calls[0][0].query).toContain(
+ `metadata['trialServerId']:'${SERVER_ID}'`,
+ );
+ });
+
+ it('reports no prior subscription for a first-time server', async () => {
+ const { stripe, search } = stripeReturning([]);
+
+ await expect(
+ hasPriorSubscriptionForServer({ stripe, serverId: SERVER_ID }),
+ ).resolves.toBe(false);
+
+ expect(search).toHaveBeenCalledTimes(1);
+ expect(search).toHaveBeenCalledWith({ query: EXPECTED_QUERY, limit: 1 });
+ });
+
+ it.each([
+ ["' OR metadata['boundServerId']:'*", 'quote injection'],
+ ['', 'empty'],
+ [' ', 'whitespace'],
+ [42, 'non-string'],
+ [undefined, 'absent'],
+ ])('never queries Stripe with %s (%s)', async (serverId, _label) => {
+ const { stripe, search } = stripeReturning([{ id: 'sub_old' }]);
+
+ await expect(
+ hasPriorSubscriptionForServer({ stripe, serverId }),
+ ).resolves.toBe(false);
+
+ expect(search).not.toHaveBeenCalled();
+ });
+
+ it('grants the benefit of the doubt when the Stripe search fails', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ const search = jest.fn().mockRejectedValue(new Error('stripe is down'));
+ const stripe = { subscriptions: { search } };
+
+ await expect(
+ hasPriorSubscriptionForServer({ stripe, serverId: SERVER_ID }),
+ ).resolves.toBe(false);
+
+ expect(search).toHaveBeenCalledTimes(1);
+ expect(search).toHaveBeenCalledWith({ query: EXPECTED_QUERY, limit: 1 });
+ });
+});
diff --git a/packages/twenty-website/src/platform/enterprise/has-prior-subscription-for-server.ts b/packages/twenty-website/src/platform/enterprise/has-prior-subscription-for-server.ts
new file mode 100644
index 00000000000..a6cd55cf9cf
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/has-prior-subscription-for-server.ts
@@ -0,0 +1,41 @@
+import type Stripe from 'stripe';
+
+import { isSearchableMetadataValue } from './is-searchable-metadata-value';
+import { normalizeServerId } from './normalize-server-id';
+import { STRIPE_METADATA_KEY } from './stripe-metadata-key';
+
+type SubscriptionSearcher = {
+ subscriptions: Pick<Stripe['subscriptions'], 'search'>;
+};
+
+export async function hasPriorSubscriptionForServer({
+ stripe,
+ serverId,
+}: {
+ stripe: SubscriptionSearcher;
+ serverId: unknown;
+}): Promise<boolean> {
+ const normalizedServerId = normalizeServerId(serverId);
+
+ if (!isSearchableMetadataValue(normalizedServerId)) {
+ return false;
+ }
+
+ const query = [
+ `metadata['${STRIPE_METADATA_KEY.TRIAL_SERVER_ID}']:'${normalizedServerId}'`,
+ `metadata['${STRIPE_METADATA_KEY.BOUND_SERVER_ID}']:'${normalizedServerId}'`,
+ ].join(' OR ');
+
+ try {
+ const result = await stripe.subscriptions.search({ query, limit: 1 });
+
+ return result.data.length > 0;
+ } catch (error: unknown) {
+ console.error(
+ '[enterprise-checkout] prior-subscription lookup failed, granting the trial',
+ error,
+ );
+
+ return false;
+ }
+}
diff --git a/packages/twenty-website/src/platform/enterprise/index.ts b/packages/twenty-website/src/platform/enterprise/index.ts
index cfdbafaf729..5594998883f 100644
--- a/packages/twenty-website/src/platform/enterprise/index.ts
+++ b/packages/twenty-website/src/platform/enterprise/index.ts
@@ -43,6 +43,19 @@ export {
} from './evaluate-release-rate-limit';
export { evaluateValidityTokenEmissionRateLimit } from './evaluate-validity-token-emission-rate-limit';
export { normalizeServerId } from './normalize-server-id';
+export { isSearchableMetadataValue } from './is-searchable-metadata-value';
+export { hasPriorSubscriptionForServer } from './has-prior-subscription-for-server';
+export { findPriorTrialForCard } from './find-prior-trial-for-card';
+export { extractCardFingerprint } from './extract-card-fingerprint';
+export { recordTrialCard } from './record-trial-card';
+export {
+ TRIAL_CARD_RECORD_OUTCOME,
+ type TrialCardRecordOutcome,
+} from './trial-card-record-outcome';
+export {
+ resolveTrialPeriodDays,
+ type ResolveTrialPeriodDaysInput,
+} from './resolve-trial-period-days';
export { isBillableSeatReporter } from './is-billable-seat-reporter';
export { parseInstanceType } from './parse-instance-type';
export {
diff --git a/packages/twenty-website/src/platform/enterprise/is-searchable-metadata-value.ts b/packages/twenty-website/src/platform/enterprise/is-searchable-metadata-value.ts
new file mode 100644
index 00000000000..36fa6aa864d
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/is-searchable-metadata-value.ts
@@ -0,0 +1,7 @@
+const SEARCHABLE_METADATA_VALUE_PATTERN = /^[A-Za-z0-9_.:-]{1,128}$/;
+
+export function isSearchableMetadataValue(value: unknown): value is string {
+ return (
+ typeof value === 'string' && SEARCHABLE_METADATA_VALUE_PATTERN.test(value)
+ );
+}
diff --git a/packages/twenty-website/src/platform/enterprise/record-trial-card.test.ts b/packages/twenty-website/src/platform/enterprise/record-trial-card.test.ts
new file mode 100644
index 00000000000..92dac2d2663
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/record-trial-card.test.ts
@@ -0,0 +1,166 @@
+import { recordTrialCard } from './record-trial-card';
+import { TRIAL_CARD_RECORD_OUTCOME } from './trial-card-record-outcome';
+
+const SUBSCRIPTION_ID = 'sub_new';
+const PRIOR_SUBSCRIPTION_ID = 'sub_previous';
+const FINGERPRINT = 'Xt5EWLLDS7FJjR1c';
+
+const stripeWith = ({
+ subscription,
+ searchResults = [],
+}: {
+ subscription: unknown;
+ searchResults?: unknown[];
+}) => {
+ const retrieve = jest.fn().mockResolvedValue(subscription);
+ const search = jest.fn().mockResolvedValue({ data: searchResults });
+ const update = jest.fn().mockResolvedValue({});
+
+ return {
+ stripe: { subscriptions: { retrieve, search, update } },
+ retrieve,
+ search,
+ update,
+ };
+};
+
+const trialingSubscription = (metadata: Record<string, string> = {}) => ({
+ id: SUBSCRIPTION_ID,
+ status: 'trialing',
+ metadata,
+ default_payment_method: { card: { fingerprint: FINGERPRINT } },
+});
+
+describe('recordTrialCard', () => {
+ it('flags a card that already trialed elsewhere, without touching the trial', async () => {
+ jest.spyOn(console, 'warn').mockImplementation(() => {});
+ const { stripe, update, search } = stripeWith({
+ subscription: trialingSubscription(),
+ searchResults: [{ id: PRIOR_SUBSCRIPTION_ID }],
+ });
+
+ await expect(
+ recordTrialCard({ stripe, subscriptionId: SUBSCRIPTION_ID }),
+ ).resolves.toBe(TRIAL_CARD_RECORD_OUTCOME.REPEAT_FLAGGED);
+
+ expect(search).toHaveBeenCalledTimes(1);
+ expect(search).toHaveBeenCalledWith({
+ query: `metadata['trialCardFingerprint']:'${FINGERPRINT}'`,
+ limit: 2,
+ });
+ expect(update).toHaveBeenCalledTimes(1);
+ expect(update).toHaveBeenCalledWith(SUBSCRIPTION_ID, {
+ metadata: {
+ trialCardFingerprint: FINGERPRINT,
+ priorTrialSubscriptionId: PRIOR_SUBSCRIPTION_ID,
+ },
+ });
+ });
+
+ it('never ends a trial the customer was shown', async () => {
+ jest.spyOn(console, 'warn').mockImplementation(() => {});
+ const { stripe, update } = stripeWith({
+ subscription: trialingSubscription(),
+ searchResults: [{ id: PRIOR_SUBSCRIPTION_ID }],
+ });
+
+ await recordTrialCard({ stripe, subscriptionId: SUBSCRIPTION_ID });
+
+ expect(update.mock.calls[0][1]).not.toHaveProperty('trial_end');
+ });
+
+ it('records a first-time card without flagging it', async () => {
+ const { stripe, update } = stripeWith({
+ subscription: trialingSubscription(),
+ });
+
+ await expect(
+ recordTrialCard({ stripe, subscriptionId: SUBSCRIPTION_ID }),
+ ).resolves.toBe(TRIAL_CARD_RECORD_OUTCOME.FIRST_TRIAL_FOR_CARD);
+
+ expect(update).toHaveBeenCalledTimes(1);
+ expect(update).toHaveBeenCalledWith(SUBSCRIPTION_ID, {
+ metadata: { trialCardFingerprint: FINGERPRINT },
+ });
+ });
+
+ it('does not flag itself when the search returns only this subscription', async () => {
+ const { stripe, update } = stripeWith({
+ subscription: trialingSubscription(),
+ searchResults: [{ id: SUBSCRIPTION_ID }],
+ });
+
+ await expect(
+ recordTrialCard({ stripe, subscriptionId: SUBSCRIPTION_ID }),
+ ).resolves.toBe(TRIAL_CARD_RECORD_OUTCOME.FIRST_TRIAL_FOR_CARD);
+
+ expect(update).toHaveBeenCalledWith(SUBSCRIPTION_ID, {
+ metadata: { trialCardFingerprint: FINGERPRINT },
+ });
+ });
+
+ it('is idempotent across webhook redeliveries', async () => {
+ const { stripe, search, update } = stripeWith({
+ subscription: trialingSubscription({
+ trialCardFingerprint: FINGERPRINT,
+ }),
+ searchResults: [{ id: PRIOR_SUBSCRIPTION_ID }],
+ });
+
+ await expect(
+ recordTrialCard({ stripe, subscriptionId: SUBSCRIPTION_ID }),
+ ).resolves.toBe(TRIAL_CARD_RECORD_OUTCOME.ALREADY_RECORDED);
+
+ expect(search).not.toHaveBeenCalled();
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it('leaves a subscription that is not trialing alone', async () => {
+ const { stripe, search, update } = stripeWith({
+ subscription: { ...trialingSubscription(), status: 'active' },
+ });
+
+ await expect(
+ recordTrialCard({ stripe, subscriptionId: SUBSCRIPTION_ID }),
+ ).resolves.toBe(TRIAL_CARD_RECORD_OUTCOME.NOT_TRIALING);
+
+ expect(search).not.toHaveBeenCalled();
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [null, 'no payment method'],
+ ['pm_123', 'an unexpanded payment method'],
+ [{ card: null }, 'a non-card payment method'],
+ [{ card: { fingerprint: null } }, 'a card without a fingerprint'],
+ [{ card: { fingerprint: "' OR 1:'1" } }, 'an unsearchable fingerprint'],
+ ])('records nothing for %s (%s)', async (defaultPaymentMethod, _label) => {
+ const { stripe, search, update } = stripeWith({
+ subscription: {
+ ...trialingSubscription(),
+ default_payment_method: defaultPaymentMethod,
+ },
+ });
+
+ await expect(
+ recordTrialCard({ stripe, subscriptionId: SUBSCRIPTION_ID }),
+ ).resolves.toBe(TRIAL_CARD_RECORD_OUTCOME.CARD_UNKNOWN);
+
+ expect(search).not.toHaveBeenCalled();
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it('records nothing when the prior-trial lookup fails, so a redelivery looks again', async () => {
+ const { stripe, search, update } = stripeWith({
+ subscription: trialingSubscription(),
+ });
+ search.mockRejectedValue(new Error('stripe is down'));
+
+ await expect(
+ recordTrialCard({ stripe, subscriptionId: SUBSCRIPTION_ID }),
+ ).rejects.toThrow('stripe is down');
+
+ expect(search).toHaveBeenCalledTimes(1);
+ expect(update).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-website/src/platform/enterprise/record-trial-card.ts b/packages/twenty-website/src/platform/enterprise/record-trial-card.ts
new file mode 100644
index 00000000000..b88fc78bb7d
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/record-trial-card.ts
@@ -0,0 +1,75 @@
+import type Stripe from 'stripe';
+
+import { extractCardFingerprint } from './extract-card-fingerprint';
+import { findPriorTrialForCard } from './find-prior-trial-for-card';
+import { STRIPE_METADATA_KEY } from './stripe-metadata-key';
+import {
+ TRIAL_CARD_RECORD_OUTCOME,
+ type TrialCardRecordOutcome,
+} from './trial-card-record-outcome';
+
+type SubscriptionRecorder = {
+ subscriptions: Pick<
+ Stripe['subscriptions'],
+ 'retrieve' | 'search' | 'update'
+ >;
+};
+
+export async function recordTrialCard({
+ stripe,
+ subscriptionId,
+}: {
+ stripe: SubscriptionRecorder;
+ subscriptionId: string;
+}): Promise<TrialCardRecordOutcome> {
+ const subscription = await stripe.subscriptions.retrieve(subscriptionId, {
+ expand: ['default_payment_method'],
+ });
+
+ if (subscription.status !== 'trialing') {
+ return TRIAL_CARD_RECORD_OUTCOME.NOT_TRIALING;
+ }
+
+ const cardFingerprint = extractCardFingerprint(
+ subscription.default_payment_method,
+ );
+
+ if (cardFingerprint === undefined) {
+ return TRIAL_CARD_RECORD_OUTCOME.CARD_UNKNOWN;
+ }
+
+ if (
+ subscription.metadata?.[STRIPE_METADATA_KEY.TRIAL_CARD_FINGERPRINT] ===
+ cardFingerprint
+ ) {
+ return TRIAL_CARD_RECORD_OUTCOME.ALREADY_RECORDED;
+ }
+
+ const priorTrialSubscriptionId = await findPriorTrialForCard({
+ stripe,
+ cardFingerprint,
+ excludedSubscriptionId: subscriptionId,
+ });
+
+ await stripe.subscriptions.update(subscriptionId, {
+ metadata: {
+ [STRIPE_METADATA_KEY.TRIAL_CARD_FINGERPRINT]: cardFingerprint,
+ ...(priorTrialSubscriptionId === undefined
+ ? {}
+ : {
+ [STRIPE_METADATA_KEY.PRIOR_TRIAL_SUBSCRIPTION_ID]:
+ priorTrialSubscriptionId,
+ }),
+ },
+ });
+
+ if (priorTrialSubscriptionId === undefined) {
+ return TRIAL_CARD_RECORD_OUTCOME.FIRST_TRIAL_FOR_CARD;
+ }
+
+ console.warn(
+ `[enterprise-stripe-webhook] ${subscriptionId} trials on a card that already trialed on ${priorTrialSubscriptionId}`,
+ );
+
+ return TRIAL_CARD_RECORD_OUTCOME.REPEAT_FLAGGED;
+}
diff --git a/packages/twenty-website/src/platform/enterprise/resolve-trial-period-days.test.ts b/packages/twenty-website/src/platform/enterprise/resolve-trial-period-days.test.ts
new file mode 100644
index 00000000000..7b41cfc49ce
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/resolve-trial-period-days.test.ts
@@ -0,0 +1,30 @@
+import { resolveTrialPeriodDays } from './resolve-trial-period-days';
+
+describe('resolveTrialPeriodDays', () => {
+ it('grants the full trial to a server with no prior subscription', () => {
+ expect(
+ resolveTrialPeriodDays({
+ defaultTrialPeriodDays: 30,
+ hasPriorSubscription: false,
+ }),
+ ).toBe(30);
+ });
+
+ it('grants no trial to a returning server', () => {
+ expect(
+ resolveTrialPeriodDays({
+ defaultTrialPeriodDays: 30,
+ hasPriorSubscription: true,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('grants no trial when the configured length is not positive', () => {
+ expect(
+ resolveTrialPeriodDays({
+ defaultTrialPeriodDays: 0,
+ hasPriorSubscription: false,
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-website/src/platform/enterprise/resolve-trial-period-days.ts b/packages/twenty-website/src/platform/enterprise/resolve-trial-period-days.ts
new file mode 100644
index 00000000000..13d1e20117d
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/resolve-trial-period-days.ts
@@ -0,0 +1,19 @@
+export type ResolveTrialPeriodDaysInput = {
+ defaultTrialPeriodDays: number;
+ hasPriorSubscription: boolean;
+};
+
+export function resolveTrialPeriodDays({
+ defaultTrialPeriodDays,
+ hasPriorSubscription,
+}: ResolveTrialPeriodDaysInput): number | undefined {
+ if (hasPriorSubscription) {
+ return undefined;
+ }
+
+ if (defaultTrialPeriodDays < 1) {
+ return undefined;
+ }
+
+ return defaultTrialPeriodDays;
+}
diff --git a/packages/twenty-website/src/platform/enterprise/stripe-metadata-key.ts b/packages/twenty-website/src/platform/enterprise/stripe-metadata-key.ts
index 78ca929587d..fec21955916 100644
--- a/packages/twenty-website/src/platform/enterprise/stripe-metadata-key.ts
+++ b/packages/twenty-website/src/platform/enterprise/stripe-metadata-key.ts
@@ -6,4 +6,7 @@ export const STRIPE_METADATA_KEY = {
DEV_SERVER_ID: 'devServerId',
DEV_SERVER_LAST_SEEN_AT: 'devServerLastSeenAt',
RELEASE_TIMESTAMPS: 'releaseTimestamps',
+ TRIAL_SERVER_ID: 'trialServerId',
+ TRIAL_CARD_FINGERPRINT: 'trialCardFingerprint',
+ PRIOR_TRIAL_SUBSCRIPTION_ID: 'priorTrialSubscriptionId',
} as const;
diff --git a/packages/twenty-website/src/platform/enterprise/trial-card-record-outcome.ts b/packages/twenty-website/src/platform/enterprise/trial-card-record-outcome.ts
new file mode 100644
index 00000000000..5be69a4c409
--- /dev/null
+++ b/packages/twenty-website/src/platform/enterprise/trial-card-record-outcome.ts
@@ -0,0 +1,10 @@
+export const TRIAL_CARD_RECORD_OUTCOME = {
+ NOT_TRIALING: 'not-trialing',
+ CARD_UNKNOWN: 'card-unknown',
+ ALREADY_RECORDED: 'already-recorded',
+ FIRST_TRIAL_FOR_CARD: 'first-trial-for-card',
+ REPEAT_FLAGGED: 'repeat-flagged',
+} as const;
+
+export type TrialCardRecordOutcome =
+ (typeof TRIAL_CARD_RECORD_OUTCOME)[keyof typeof TRIAL_CARD_RECORD_OUTCOME];