(Billing for self hosts) Tie enterprise key to server (#22464)
# Enterprise key: bind to a server, free dev instances, self-serve transfer, shorter license ## Summary Enterprise keys were being reused across multiple instances (e.g. one prod + one dev, or several environments), which broke seat accounting and made licensing ambiguous. This PR ties each enterprise key to a **single server**, while giving customers a legitimate, self-serve way to run a **free development instance** and to **move their key** when they replace a server. ## Product behavior ### 1. Enterprise key is bound to one server - The first server to validate an enterprise key **claims** it (claim-on-first-use). From then on, that key is bound to that one server (until unbound - see 3.). - Any other instance that presents the **same key from a different server is hard-rejected**: it does not receive a license, so enterprise features stay off there. - Each instance has a stable server identifier. If one isn't set, the instance generates and persists one automatically on first validation (in keyValuePair table), so existing customers generally don't need to do anything (unless they have disabled config variables in db then they should add it to .env). ### 2. Free development instance - Every enterprise subscription gets **one free, non-billable development instance** in addition to its production instance. - An instance registers as development by declaring its instance type as `development` (done by default when validating the enterprise key, then can be toggled from UI or by updating value in keyValuePair table). - The free dev slot is only granted while there is an **active production instance** on the same subscription (so it's a perk for paying customers, not a way to run for free). - Only **one** dev instance can be active at a time per subscription, and it is **not counted as a billable seat**. ### 3. Self-serve unbind / rebind (transfer) - Admins can **release** the binding from the enterprise settings, which frees the key so it can be **claimed by a new server**. - This is the intended path when **sunsetting an instance and standing up a new one** (migration, re-hosting, disaster recovery): release on the old/dead box, then the new box claims it on its next validation. - To prevent abuse, releases are **rate-limited (10 per rolling 30 days)**; hitting the limit shows a clear message. ### 4. Automatic release of dead servers - If a bound server stops checking in for **14 days**, its binding is considered stale and is **auto-released**, so a replacement can claim the key without any manual step. This covers the case where the old server is already gone and can't release itself. ### 5. Shorter license validity (30 → 7 days) - The license (validity token) now expires after **7 days** instead of 30. The daily background refresh keeps healthy instances licensed transparently. - This limits the value of copying a license from one instance to another, since a copied license now stops working within a week. ### 6. License issuance is rate-limited - Issuing a new license is capped at **twice per 24h, independently for production and for development**. This tolerates the normal daily refresh (including small drift between runs) while blocking bursts of license minting for cloned instances. - Hitting this limit never revokes an existing, still-valid license — the current one keeps working until it expires; the manual "refresh" button just reports that the daily limit was reached. ## What changes for existing self-hosted customers **If you run a single production instance with one enterprise key:** nothing to do. On the next validation your instance reports its server identifier, claims the binding, and keeps working. **If you reuse one key across several instances (e.g. prod + dev, or multiple environments):** only the **first** instance to validate keeps its license. The others will **lose enterprise features**. To migrate: - Keep your production instance as-is (it claims the binding). - For a secondary/testing box, mark it as a **development instance** (set the instance type to `development`) to use the free dev slot — no extra cost. - If you genuinely need multiple production instances, you'll need **separate subscriptions/keys** for each. **If you're replacing a server (decommissioning + rebuilding):** - **Release** the binding from enterprise settings on the old instance, then start the new one — it will claim the key automatically. - If the old server is already gone, just wait for the **14-day auto-release**, or contact support. **Legacy instances that can't persist a server identifier automatically:** set the server identifier explicitly in your environment configuration (the instance logs a message telling you to do so). **Offline instances:** because licenses now last 7 days, an instance that can't reach our licensing endpoint for more than a week will lose enterprise features until it can check in again. > A migration email will be sent to affected customers separately. ## Technical implementation (brief) - Binding state lives in the **subscription's billing metadata** (bound server id + last-seen timestamps for prod and dev, release timestamps, and license-issuance timestamps). No new database is introduced on the licensing side; the billing provider's subscription metadata is the source of truth. <img width="976" height="413" alt="metadata_3" src="https://github.com/user-attachments/assets/ccc64822-e177-4223-a65a-4a4602aedf0e" /> - On each validation, a pure **binding resolver** takes the reported server id + instance type + current metadata and returns `allowed` (with the metadata to persist and whether the seat is billable) or `rejected`. It handles claim-on-first-use, staleness/auto-release, the dev-requires-active-prod rule, and the single-dev-slot rule. - **Rate limits** (release + license issuance) use a shared sliding-window helper stored as pruned timestamp lists in the same metadata, so the metadata self-cleans and never grows unbounded. License issuance uses **separate windows per instance type**. - The self-hosted instance **generates and persists a server identifier** if none is configured, and sends it (plus instance type) as instance metadata on validation. - A rejected binding returns a specific error code; the instance **revokes its stored license** on that code. A license-issuance rate-limit instead **throws a typed exception that surfaces to the manual refresh** while leaving the existing license untouched; the daily refresh job swallows it. - License lifetime is a configurable duration (defaulted from 30 to **7 days**), clamped to the subscription's cancellation date when sooner.
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
export const ENTERPRISE_INSTANCE_TYPE = {
|
||||
PRODUCTION: 'production',
|
||||
DEVELOPMENT: 'development',
|
||||
} as const;
|
||||
|
||||
export type EnterpriseInstanceType =
|
||||
(typeof ENTERPRISE_INSTANCE_TYPE)[keyof typeof ENTERPRISE_INSTANCE_TYPE];
|
||||
@@ -0,0 +1,6 @@
|
||||
// Machine codes returned to clients when a rate limit is hit, so the
|
||||
// self-hosted server and admin UI can surface the right message.
|
||||
export const ENTERPRISE_RATE_LIMIT_CODE = {
|
||||
RELEASE: 'ENTERPRISE_RELEASE_RATE_LIMITED',
|
||||
VALIDITY_TOKEN: 'ENTERPRISE_VALIDITY_TOKEN_RATE_LIMITED',
|
||||
} as const;
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
evaluateSlidingWindowRateLimit,
|
||||
type RateLimitDecision,
|
||||
} from './evaluate-sliding-window-rate-limit';
|
||||
import { getReleaseLimitPerWindow } from './get-release-limit-per-window';
|
||||
import { STRIPE_METADATA_KEY } from './stripe-metadata-key';
|
||||
import { type StripeMetadata } from './stripe-metadata';
|
||||
|
||||
export type ReleaseRateLimitDecision = RateLimitDecision;
|
||||
|
||||
const SECONDS_PER_DAY = 24 * 60 * 60;
|
||||
const RELEASE_RATE_WINDOW_DAYS = 30;
|
||||
|
||||
export function evaluateReleaseRateLimit({
|
||||
stripeMetadata,
|
||||
limit = getReleaseLimitPerWindow(),
|
||||
windowDays = RELEASE_RATE_WINDOW_DAYS,
|
||||
now = new Date(),
|
||||
}: {
|
||||
stripeMetadata: StripeMetadata;
|
||||
limit?: number;
|
||||
windowDays?: number;
|
||||
now?: Date;
|
||||
}): RateLimitDecision {
|
||||
return evaluateSlidingWindowRateLimit({
|
||||
raw: stripeMetadata?.[STRIPE_METADATA_KEY.RELEASE_TIMESTAMPS],
|
||||
metadataKey: STRIPE_METADATA_KEY.RELEASE_TIMESTAMPS,
|
||||
limit,
|
||||
windowMs: windowDays * SECONDS_PER_DAY * 1000,
|
||||
now,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
export type RateLimitDecision =
|
||||
| { allowed: true; metadataPatch: Record<string, string> }
|
||||
| { allowed: false; retryAfter: Date };
|
||||
|
||||
const parseRecentTimestamps = (
|
||||
raw: string | undefined,
|
||||
now: Date,
|
||||
windowMs: number,
|
||||
): number[] => {
|
||||
if (!isDefined(raw) || raw.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const nowMs = now.getTime();
|
||||
const cutoffMs = nowMs - windowMs;
|
||||
|
||||
return raw
|
||||
.split(',')
|
||||
.map((entry) => Number.parseInt(entry, 10))
|
||||
.filter(
|
||||
(timestampMs) =>
|
||||
!Number.isNaN(timestampMs) &&
|
||||
timestampMs > cutoffMs &&
|
||||
timestampMs <= nowMs,
|
||||
)
|
||||
.toSorted((a, b) => a - b);
|
||||
};
|
||||
|
||||
export const evaluateSlidingWindowRateLimit = ({
|
||||
raw,
|
||||
metadataKey,
|
||||
limit,
|
||||
windowMs,
|
||||
now,
|
||||
}: {
|
||||
raw: string | undefined;
|
||||
metadataKey: string;
|
||||
limit: number;
|
||||
windowMs: number;
|
||||
now: Date;
|
||||
}): RateLimitDecision => {
|
||||
const recentTimestamps = parseRecentTimestamps(raw, now, windowMs);
|
||||
|
||||
if (recentTimestamps.length >= limit) {
|
||||
const oldestTimestampMs = recentTimestamps[0];
|
||||
|
||||
return {
|
||||
allowed: false,
|
||||
retryAfter: new Date(oldestTimestampMs + windowMs),
|
||||
};
|
||||
}
|
||||
|
||||
const updatedTimestamps = [...recentTimestamps, now.getTime()];
|
||||
|
||||
return {
|
||||
allowed: true,
|
||||
metadataPatch: {
|
||||
[metadataKey]: updatedTimestamps.join(','),
|
||||
},
|
||||
};
|
||||
};
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { type EnterpriseInstanceType } from './enterprise-instance-type';
|
||||
import {
|
||||
evaluateSlidingWindowRateLimit,
|
||||
type RateLimitDecision,
|
||||
} from './evaluate-sliding-window-rate-limit';
|
||||
import { getValidityTokenEmissionLimitPerWindow } from './get-validity-token-emission-limit-per-window';
|
||||
import { type StripeMetadata } from './stripe-metadata';
|
||||
import { VALIDITY_TOKEN_EMISSIONS_KEY_BY_INSTANCE_TYPE } from './validity-token-emissions-key';
|
||||
|
||||
const VALIDITY_TOKEN_EMISSION_WINDOW_HOURS = 24;
|
||||
|
||||
export function evaluateValidityTokenEmissionRateLimit({
|
||||
stripeMetadata,
|
||||
instanceType,
|
||||
limit = getValidityTokenEmissionLimitPerWindow(),
|
||||
windowHours = VALIDITY_TOKEN_EMISSION_WINDOW_HOURS,
|
||||
now = new Date(),
|
||||
}: {
|
||||
stripeMetadata: StripeMetadata;
|
||||
instanceType: EnterpriseInstanceType;
|
||||
limit?: number;
|
||||
windowHours?: number;
|
||||
now?: Date;
|
||||
}): RateLimitDecision {
|
||||
const metadataKey =
|
||||
VALIDITY_TOKEN_EMISSIONS_KEY_BY_INSTANCE_TYPE[instanceType];
|
||||
|
||||
return evaluateSlidingWindowRateLimit({
|
||||
raw: stripeMetadata?.[metadataKey],
|
||||
metadataKey,
|
||||
limit,
|
||||
windowMs: windowHours * 60 * 60 * 1000,
|
||||
now,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
const DEFAULT_AUTO_RELEASE_DAYS = 14;
|
||||
|
||||
export function getAutoReleaseDays(): number {
|
||||
const value = process.env.ENTERPRISE_AUTO_RELEASE_DAYS;
|
||||
|
||||
if (value === undefined || value === '') {
|
||||
return DEFAULT_AUTO_RELEASE_DAYS;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
|
||||
if (Number.isNaN(parsed) || parsed < 1) {
|
||||
return DEFAULT_AUTO_RELEASE_DAYS;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
type EnterpriseConfigCheck = {
|
||||
route: string;
|
||||
feature: string;
|
||||
requiredEnvVars: string[];
|
||||
};
|
||||
|
||||
export function getEnterpriseConfigError({
|
||||
route,
|
||||
feature,
|
||||
requiredEnvVars,
|
||||
}: EnterpriseConfigCheck): NextResponse | null {
|
||||
const missingEnvVars = requiredEnvVars.filter(
|
||||
(envVarName) => !process.env[envVarName],
|
||||
);
|
||||
|
||||
if (missingEnvVars.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
console.error(
|
||||
`[${route}] 503 — ${missingEnvVars.join(', ')} ${
|
||||
missingEnvVars.length === 1 ? 'is' : 'are'
|
||||
} not configured`,
|
||||
);
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: `${feature} is not configured.` },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
const DEFAULT_RELEASE_LIMIT_PER_WINDOW = 10;
|
||||
|
||||
export function getReleaseLimitPerWindow(): number {
|
||||
const value = process.env.ENTERPRISE_RELEASE_LIMIT_PER_WINDOW;
|
||||
|
||||
if (value === undefined || value === '') {
|
||||
return DEFAULT_RELEASE_LIMIT_PER_WINDOW;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
|
||||
if (Number.isNaN(parsed) || parsed < 1) {
|
||||
return DEFAULT_RELEASE_LIMIT_PER_WINDOW;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
const DEFAULT_VALIDITY_TOKEN_EMISSIONS_PER_WINDOW = 2;
|
||||
|
||||
export function getValidityTokenEmissionLimitPerWindow(): number {
|
||||
const value = process.env.ENTERPRISE_VALIDITY_TOKEN_EMISSIONS_PER_DAY;
|
||||
|
||||
if (value === undefined || value === '') {
|
||||
return DEFAULT_VALIDITY_TOKEN_EMISSIONS_PER_WINDOW;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
|
||||
if (Number.isNaN(parsed) || parsed < 1) {
|
||||
return DEFAULT_VALIDITY_TOKEN_EMISSIONS_PER_WINDOW;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
@@ -1,7 +1,44 @@
|
||||
export { getEnterpriseConfigError } from './get-enterprise-config-error';
|
||||
export { getEnterprisePriceId } from './enterprise-price-id';
|
||||
export { getLicenseeFromStripeCustomer } from './get-licensee-from-stripe-customer';
|
||||
export { getStripeClient } from './stripe-client';
|
||||
export { getSubscriptionCurrentPeriodEnd } from './subscription-current-period-end';
|
||||
export {
|
||||
ENTERPRISE_INSTANCE_TYPE,
|
||||
type EnterpriseInstanceType,
|
||||
} from './enterprise-instance-type';
|
||||
export {
|
||||
SERVER_BINDING_OUTCOME,
|
||||
type ServerBindingOutcome,
|
||||
} from './server-binding-outcome';
|
||||
export {
|
||||
SERVER_BINDING_REJECTION_CODE,
|
||||
type ServerBindingRejectionCode,
|
||||
} from './server-binding-rejection-code';
|
||||
export { STRIPE_METADATA_KEY } from './stripe-metadata-key';
|
||||
export { VALIDITY_TOKEN_EMISSIONS_KEY_BY_INSTANCE_TYPE } from './validity-token-emissions-key';
|
||||
export { ENTERPRISE_RATE_LIMIT_CODE } from './enterprise-rate-limit-code';
|
||||
export { type StripeMetadata } from './stripe-metadata';
|
||||
export { getAutoReleaseDays } from './get-auto-release-days';
|
||||
export { getReleaseLimitPerWindow } from './get-release-limit-per-window';
|
||||
export { getValidityTokenEmissionLimitPerWindow } from './get-validity-token-emission-limit-per-window';
|
||||
export {
|
||||
evaluateSlidingWindowRateLimit,
|
||||
type RateLimitDecision,
|
||||
} from './evaluate-sliding-window-rate-limit';
|
||||
export {
|
||||
evaluateReleaseRateLimit,
|
||||
type ReleaseRateLimitDecision,
|
||||
} from './evaluate-release-rate-limit';
|
||||
export { evaluateValidityTokenEmissionRateLimit } from './evaluate-validity-token-emission-rate-limit';
|
||||
export { normalizeServerId } from './normalize-server-id';
|
||||
export { isBillableSeatReporter } from './is-billable-seat-reporter';
|
||||
export { parseInstanceType } from './parse-instance-type';
|
||||
export {
|
||||
resolveServerBinding,
|
||||
type ResolveServerBindingInput,
|
||||
type ServerBindingDecision,
|
||||
} from './resolve-server-binding';
|
||||
export { signEnterpriseKey } from './sign-enterprise-key';
|
||||
export { signValidityToken } from './sign-validity-token';
|
||||
export { verifyEnterpriseKey } from './verify-enterprise-key';
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import isEmpty from 'lodash.isempty';
|
||||
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import { normalizeServerId } from './normalize-server-id';
|
||||
import { STRIPE_METADATA_KEY } from './stripe-metadata-key';
|
||||
import { type StripeMetadata } from './stripe-metadata';
|
||||
|
||||
export function isBillableSeatReporter({
|
||||
stripeMetadata,
|
||||
serverId,
|
||||
}: {
|
||||
stripeMetadata: StripeMetadata;
|
||||
serverId?: string;
|
||||
}): boolean {
|
||||
const normalizedServerId = normalizeServerId(serverId);
|
||||
const boundServerId = stripeMetadata?.[STRIPE_METADATA_KEY.BOUND_SERVER_ID];
|
||||
|
||||
if (isEmpty(boundServerId)) {
|
||||
return !isDefined(normalizedServerId);
|
||||
}
|
||||
|
||||
return normalizedServerId === boundServerId;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// A server identifier only counts if it is a non-empty, non-whitespace string.
|
||||
// Clients can send '' or non-string runtime values, which must not be allowed
|
||||
// to claim or reuse a key (that would bypass single-server enforcement).
|
||||
export const normalizeServerId = (value: unknown): string | undefined => {
|
||||
if (typeof value !== 'string') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const trimmed = value.trim();
|
||||
|
||||
return trimmed.length === 0 ? undefined : trimmed;
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import {
|
||||
ENTERPRISE_INSTANCE_TYPE,
|
||||
type EnterpriseInstanceType,
|
||||
} from './enterprise-instance-type';
|
||||
|
||||
export function parseInstanceType(value?: string): EnterpriseInstanceType {
|
||||
return value === ENTERPRISE_INSTANCE_TYPE.DEVELOPMENT
|
||||
? ENTERPRISE_INSTANCE_TYPE.DEVELOPMENT
|
||||
: ENTERPRISE_INSTANCE_TYPE.PRODUCTION;
|
||||
}
|
||||
@@ -0,0 +1,569 @@
|
||||
import {
|
||||
evaluateReleaseRateLimit,
|
||||
evaluateValidityTokenEmissionRateLimit,
|
||||
isBillableSeatReporter,
|
||||
parseInstanceType,
|
||||
resolveServerBinding,
|
||||
STRIPE_METADATA_KEY,
|
||||
VALIDITY_TOKEN_EMISSIONS_KEY_BY_INSTANCE_TYPE,
|
||||
} from '.';
|
||||
|
||||
const NOW = new Date('2026-06-30T12:00:00.000Z');
|
||||
const AUTO_RELEASE_DAYS = 14;
|
||||
|
||||
const daysAgoIso = (days: number): string =>
|
||||
new Date(NOW.getTime() - days * 24 * 60 * 60 * 1000).toISOString();
|
||||
|
||||
describe('resolveServerBinding', () => {
|
||||
it('claims a free production slot and persists the binding in stripe', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {},
|
||||
serverId: 'server-a',
|
||||
instanceType: 'production',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision).toEqual({
|
||||
outcome: 'allowed',
|
||||
isBillable: true,
|
||||
metadataPatch: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: NOW.toISOString(),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('allows the already-bound production server (refreshes lastSeenAt)', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
},
|
||||
serverId: 'server-a',
|
||||
instanceType: 'production',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('allowed');
|
||||
if (decision.outcome === 'allowed') {
|
||||
expect(decision.isBillable).toBe(true);
|
||||
expect(
|
||||
decision.metadataPatch[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT],
|
||||
).toBe(NOW.toISOString());
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a foreign production server while the binding is fresh', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
},
|
||||
serverId: 'server-b',
|
||||
instanceType: 'production',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('rejected');
|
||||
if (decision.outcome === 'rejected') {
|
||||
expect(decision.code).toBe('ENTERPRISE_KEY_BOUND_TO_ANOTHER_SERVER');
|
||||
}
|
||||
});
|
||||
|
||||
it('auto-releases a stale binding to a new production server', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(
|
||||
AUTO_RELEASE_DAYS + 1,
|
||||
),
|
||||
},
|
||||
serverId: 'server-b',
|
||||
instanceType: 'production',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('allowed');
|
||||
if (decision.outcome === 'allowed') {
|
||||
expect(decision.metadataPatch[STRIPE_METADATA_KEY.BOUND_SERVER_ID]).toBe(
|
||||
'server-b',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('binds a development instance into the dev slot as non-billable', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
},
|
||||
serverId: 'server-dev',
|
||||
instanceType: 'development',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision).toEqual({
|
||||
outcome: 'allowed',
|
||||
isBillable: false,
|
||||
metadataPatch: {
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_ID]: 'server-dev',
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_LAST_SEEN_AT]: NOW.toISOString(),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a second development instance while the dev slot is fresh', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_ID]: 'server-dev',
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
},
|
||||
serverId: 'server-dev-2',
|
||||
instanceType: 'development',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('rejected');
|
||||
if (decision.outcome === 'rejected') {
|
||||
expect(decision.code).toBe('ENTERPRISE_DEV_SLOT_IN_USE');
|
||||
}
|
||||
});
|
||||
|
||||
it('auto-releases a stale dev slot to a new development server', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_ID]: 'server-dev',
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_LAST_SEEN_AT]: daysAgoIso(
|
||||
AUTO_RELEASE_DAYS + 1,
|
||||
),
|
||||
},
|
||||
serverId: 'server-dev-2',
|
||||
instanceType: 'development',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision).toEqual({
|
||||
outcome: 'allowed',
|
||||
isBillable: false,
|
||||
metadataPatch: {
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_ID]: 'server-dev-2',
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_LAST_SEEN_AT]: NOW.toISOString(),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a development instance that does not report a serverId', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
},
|
||||
serverId: null,
|
||||
instanceType: 'development',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('rejected');
|
||||
if (decision.outcome === 'rejected') {
|
||||
expect(decision.code).toBe('ENTERPRISE_MISSING_SERVER_ID');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a development instance when there is no production binding', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {},
|
||||
serverId: 'server-dev',
|
||||
instanceType: 'development',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('rejected');
|
||||
if (decision.outcome === 'rejected') {
|
||||
expect(decision.code).toBe('ENTERPRISE_DEV_REQUIRES_ACTIVE_PRODUCTION');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a development instance when the production binding is stale', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(
|
||||
AUTO_RELEASE_DAYS + 1,
|
||||
),
|
||||
},
|
||||
serverId: 'server-dev',
|
||||
instanceType: 'development',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('rejected');
|
||||
if (decision.outcome === 'rejected') {
|
||||
expect(decision.code).toBe('ENTERPRISE_DEV_REQUIRES_ACTIVE_PRODUCTION');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a production instance that lost its serverId while a binding exists', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
},
|
||||
serverId: null,
|
||||
instanceType: 'production',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('rejected');
|
||||
if (decision.outcome === 'rejected') {
|
||||
expect(decision.code).toBe('ENTERPRISE_MISSING_SERVER_ID');
|
||||
}
|
||||
});
|
||||
|
||||
it('allows legacy instances without a serverId without binding', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {},
|
||||
serverId: null,
|
||||
instanceType: 'production',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision).toEqual({
|
||||
outcome: 'allowed',
|
||||
isBillable: true,
|
||||
metadataPatch: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a production instance sending an empty serverId while a binding exists', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
},
|
||||
serverId: ' ',
|
||||
instanceType: 'production',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('rejected');
|
||||
if (decision.outcome === 'rejected') {
|
||||
expect(decision.code).toBe('ENTERPRISE_MISSING_SERVER_ID');
|
||||
}
|
||||
});
|
||||
|
||||
it('does not let an empty serverId claim a free key as the bound id', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {},
|
||||
serverId: '',
|
||||
instanceType: 'production',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision).toEqual({
|
||||
outcome: 'allowed',
|
||||
isBillable: true,
|
||||
metadataPatch: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a development instance sending a whitespace serverId', () => {
|
||||
const decision = resolveServerBinding({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a',
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: daysAgoIso(1),
|
||||
},
|
||||
serverId: ' ',
|
||||
instanceType: 'development',
|
||||
autoReleaseDays: AUTO_RELEASE_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.outcome).toBe('rejected');
|
||||
if (decision.outcome === 'rejected') {
|
||||
expect(decision.code).toBe('ENTERPRISE_MISSING_SERVER_ID');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('isBillableSeatReporter', () => {
|
||||
it('bills the bound production server', () => {
|
||||
expect(
|
||||
isBillableSeatReporter({
|
||||
stripeMetadata: { [STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a' },
|
||||
serverId: 'server-a',
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('does not bill a foreign server', () => {
|
||||
expect(
|
||||
isBillableSeatReporter({
|
||||
stripeMetadata: { [STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a' },
|
||||
serverId: 'server-b',
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('does not bill a development instance (no production binding)', () => {
|
||||
expect(
|
||||
isBillableSeatReporter({
|
||||
stripeMetadata: { [STRIPE_METADATA_KEY.DEV_SERVER_ID]: 'server-dev' },
|
||||
serverId: 'server-dev',
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('bills legacy instances with no serverId and no binding', () => {
|
||||
expect(
|
||||
isBillableSeatReporter({ stripeMetadata: {}, serverId: undefined }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('does not bill an empty serverId against a bound production server', () => {
|
||||
expect(
|
||||
isBillableSeatReporter({
|
||||
stripeMetadata: { [STRIPE_METADATA_KEY.BOUND_SERVER_ID]: 'server-a' },
|
||||
serverId: ' ',
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseInstanceType', () => {
|
||||
it('returns development only for the development literal', () => {
|
||||
expect(parseInstanceType('development')).toBe('development');
|
||||
expect(parseInstanceType('production')).toBe('production');
|
||||
expect(parseInstanceType(undefined)).toBe('production');
|
||||
expect(parseInstanceType('something-else')).toBe('production');
|
||||
});
|
||||
});
|
||||
|
||||
describe('evaluateReleaseRateLimit', () => {
|
||||
const RELEASE_WINDOW_DAYS = 30;
|
||||
const msDaysAgo = (days: number): number =>
|
||||
NOW.getTime() - days * 24 * 60 * 60 * 1000;
|
||||
|
||||
it('allows a release under the limit and records the new timestamp', () => {
|
||||
const decision = evaluateReleaseRateLimit({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.RELEASE_TIMESTAMPS]: [
|
||||
msDaysAgo(1),
|
||||
msDaysAgo(2),
|
||||
].join(','),
|
||||
},
|
||||
limit: 10,
|
||||
windowDays: RELEASE_WINDOW_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.allowed).toBe(true);
|
||||
if (decision.allowed) {
|
||||
const recorded = decision.metadataPatch[
|
||||
STRIPE_METADATA_KEY.RELEASE_TIMESTAMPS
|
||||
]
|
||||
.split(',')
|
||||
.map(Number);
|
||||
expect(recorded).toHaveLength(3);
|
||||
expect(recorded).toContain(NOW.getTime());
|
||||
}
|
||||
});
|
||||
|
||||
it('allows the first ever release (no prior timestamps)', () => {
|
||||
const decision = evaluateReleaseRateLimit({
|
||||
stripeMetadata: {},
|
||||
limit: 10,
|
||||
windowDays: RELEASE_WINDOW_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.allowed).toBe(true);
|
||||
if (decision.allowed) {
|
||||
expect(
|
||||
decision.metadataPatch[STRIPE_METADATA_KEY.RELEASE_TIMESTAMPS],
|
||||
).toBe(String(NOW.getTime()));
|
||||
}
|
||||
});
|
||||
|
||||
it('blocks a release when the limit is reached within the window', () => {
|
||||
const timestamps = Array.from({ length: 10 }, (_, index) =>
|
||||
msDaysAgo(index + 1),
|
||||
);
|
||||
|
||||
const decision = evaluateReleaseRateLimit({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.RELEASE_TIMESTAMPS]: timestamps.join(','),
|
||||
},
|
||||
limit: 10,
|
||||
windowDays: RELEASE_WINDOW_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.allowed).toBe(false);
|
||||
if (!decision.allowed) {
|
||||
const expectedRetry = new Date(
|
||||
msDaysAgo(10) + RELEASE_WINDOW_DAYS * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
expect(decision.retryAfter.toISOString()).toBe(
|
||||
expectedRetry.toISOString(),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('ignores releases older than the window (rolling)', () => {
|
||||
const timestamps = [
|
||||
...Array.from({ length: 9 }, (_, index) => msDaysAgo(index + 1)),
|
||||
msDaysAgo(40),
|
||||
msDaysAgo(45),
|
||||
];
|
||||
|
||||
const decision = evaluateReleaseRateLimit({
|
||||
stripeMetadata: {
|
||||
[STRIPE_METADATA_KEY.RELEASE_TIMESTAMPS]: timestamps.join(','),
|
||||
},
|
||||
limit: 10,
|
||||
windowDays: RELEASE_WINDOW_DAYS,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.allowed).toBe(true);
|
||||
if (decision.allowed) {
|
||||
const recorded = decision.metadataPatch[
|
||||
STRIPE_METADATA_KEY.RELEASE_TIMESTAMPS
|
||||
]
|
||||
.split(',')
|
||||
.map(Number);
|
||||
expect(recorded).toHaveLength(10);
|
||||
expect(recorded).not.toContain(msDaysAgo(40));
|
||||
expect(recorded).not.toContain(msDaysAgo(45));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('evaluateValidityTokenEmissionRateLimit', () => {
|
||||
const EMISSION_WINDOW_HOURS = 24;
|
||||
const PRODUCTION_KEY =
|
||||
VALIDITY_TOKEN_EMISSIONS_KEY_BY_INSTANCE_TYPE.production;
|
||||
const DEVELOPMENT_KEY =
|
||||
VALIDITY_TOKEN_EMISSIONS_KEY_BY_INSTANCE_TYPE.development;
|
||||
const msHoursAgo = (hours: number): number =>
|
||||
NOW.getTime() - hours * 60 * 60 * 1000;
|
||||
|
||||
it('allows the first ever emission (no prior timestamps)', () => {
|
||||
const decision = evaluateValidityTokenEmissionRateLimit({
|
||||
stripeMetadata: {},
|
||||
instanceType: 'production',
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.allowed).toBe(true);
|
||||
if (decision.allowed) {
|
||||
expect(decision.metadataPatch[PRODUCTION_KEY]).toBe(
|
||||
String(NOW.getTime()),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('allows a second emission within 24h and records it', () => {
|
||||
const decision = evaluateValidityTokenEmissionRateLimit({
|
||||
stripeMetadata: {
|
||||
[PRODUCTION_KEY]: String(msHoursAgo(3)),
|
||||
},
|
||||
instanceType: 'production',
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.allowed).toBe(true);
|
||||
if (decision.allowed) {
|
||||
const recorded = decision.metadataPatch[PRODUCTION_KEY]
|
||||
.split(',')
|
||||
.map(Number);
|
||||
expect(recorded).toHaveLength(2);
|
||||
expect(recorded).toContain(NOW.getTime());
|
||||
}
|
||||
});
|
||||
|
||||
it('blocks a third emission within the 24h window', () => {
|
||||
const decision = evaluateValidityTokenEmissionRateLimit({
|
||||
stripeMetadata: {
|
||||
[PRODUCTION_KEY]: [msHoursAgo(2), msHoursAgo(5)].join(','),
|
||||
},
|
||||
instanceType: 'production',
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.allowed).toBe(false);
|
||||
if (!decision.allowed) {
|
||||
const expectedRetry = new Date(
|
||||
msHoursAgo(5) + EMISSION_WINDOW_HOURS * 60 * 60 * 1000,
|
||||
);
|
||||
expect(decision.retryAfter.toISOString()).toBe(
|
||||
expectedRetry.toISOString(),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('prunes emissions older than the 24h window (rolling)', () => {
|
||||
const decision = evaluateValidityTokenEmissionRateLimit({
|
||||
stripeMetadata: {
|
||||
[PRODUCTION_KEY]: [msHoursAgo(25), msHoursAgo(48)].join(','),
|
||||
},
|
||||
instanceType: 'production',
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(decision.allowed).toBe(true);
|
||||
if (decision.allowed) {
|
||||
const recorded = decision.metadataPatch[PRODUCTION_KEY]
|
||||
.split(',')
|
||||
.map(Number);
|
||||
expect(recorded).toEqual([NOW.getTime()]);
|
||||
}
|
||||
});
|
||||
|
||||
it('tracks production and development budgets independently', () => {
|
||||
// Production is already at its limit within the window...
|
||||
const stripeMetadata = {
|
||||
[PRODUCTION_KEY]: [msHoursAgo(1), msHoursAgo(2)].join(','),
|
||||
};
|
||||
|
||||
const productionDecision = evaluateValidityTokenEmissionRateLimit({
|
||||
stripeMetadata,
|
||||
instanceType: 'production',
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
// ...but a development instance still has its full budget.
|
||||
const developmentDecision = evaluateValidityTokenEmissionRateLimit({
|
||||
stripeMetadata,
|
||||
instanceType: 'development',
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(productionDecision.allowed).toBe(false);
|
||||
expect(developmentDecision.allowed).toBe(true);
|
||||
if (developmentDecision.allowed) {
|
||||
expect(developmentDecision.metadataPatch[DEVELOPMENT_KEY]).toBe(
|
||||
String(NOW.getTime()),
|
||||
);
|
||||
expect(developmentDecision.metadataPatch[PRODUCTION_KEY]).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import isEmpty from 'lodash.isempty';
|
||||
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
|
||||
import {
|
||||
ENTERPRISE_INSTANCE_TYPE,
|
||||
type EnterpriseInstanceType,
|
||||
} from './enterprise-instance-type';
|
||||
import { normalizeServerId } from './normalize-server-id';
|
||||
import { SERVER_BINDING_OUTCOME } from './server-binding-outcome';
|
||||
import {
|
||||
SERVER_BINDING_REJECTION_CODE,
|
||||
type ServerBindingRejectionCode,
|
||||
} from './server-binding-rejection-code';
|
||||
import { STRIPE_METADATA_KEY } from './stripe-metadata-key';
|
||||
import { type StripeMetadata } from './stripe-metadata';
|
||||
|
||||
const SECONDS_PER_DAY = 24 * 60 * 60;
|
||||
|
||||
export type ResolveServerBindingInput = {
|
||||
stripeMetadata: StripeMetadata;
|
||||
serverId: string | null | undefined;
|
||||
instanceType: EnterpriseInstanceType;
|
||||
autoReleaseDays: number;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type ServerBindingDecision =
|
||||
| {
|
||||
outcome: typeof SERVER_BINDING_OUTCOME.ALLOWED;
|
||||
isBillable: boolean;
|
||||
metadataPatch: Record<string, string>;
|
||||
}
|
||||
| {
|
||||
outcome: typeof SERVER_BINDING_OUTCOME.REJECTED;
|
||||
code: ServerBindingRejectionCode;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
const isStale = (
|
||||
lastSeenAt: string | undefined,
|
||||
autoReleaseDays: number,
|
||||
now: Date,
|
||||
): boolean => {
|
||||
if (!isDefined(lastSeenAt) || isEmpty(lastSeenAt)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const lastSeenMs = Date.parse(lastSeenAt);
|
||||
|
||||
if (Number.isNaN(lastSeenMs)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ageSeconds = (now.getTime() - lastSeenMs) / 1000;
|
||||
|
||||
return ageSeconds > autoReleaseDays * SECONDS_PER_DAY;
|
||||
};
|
||||
|
||||
export function resolveServerBinding({
|
||||
stripeMetadata,
|
||||
serverId,
|
||||
instanceType,
|
||||
autoReleaseDays,
|
||||
now = new Date(),
|
||||
}: ResolveServerBindingInput): ServerBindingDecision {
|
||||
const normalizedServerId = normalizeServerId(serverId);
|
||||
|
||||
if (!isDefined(normalizedServerId)) {
|
||||
if (instanceType === ENTERPRISE_INSTANCE_TYPE.DEVELOPMENT) {
|
||||
return {
|
||||
outcome: SERVER_BINDING_OUTCOME.REJECTED,
|
||||
code: SERVER_BINDING_REJECTION_CODE.MISSING_SERVER_ID,
|
||||
reason:
|
||||
'A development instance must report a server identifier. Set SERVER_ID on this instance.',
|
||||
};
|
||||
}
|
||||
|
||||
const boundServerId = stripeMetadata?.[STRIPE_METADATA_KEY.BOUND_SERVER_ID];
|
||||
|
||||
if (isDefined(boundServerId)) {
|
||||
return {
|
||||
outcome: SERVER_BINDING_OUTCOME.REJECTED,
|
||||
code: SERVER_BINDING_REJECTION_CODE.MISSING_SERVER_ID,
|
||||
reason:
|
||||
'This enterprise key is bound to a server instance, but this instance did not report a server identifier. Set SERVER_ID on this instance or release the binding to rebind it.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
outcome: SERVER_BINDING_OUTCOME.ALLOWED,
|
||||
isBillable: true,
|
||||
metadataPatch: {},
|
||||
};
|
||||
}
|
||||
|
||||
const nowIso = now.toISOString();
|
||||
|
||||
if (instanceType === ENTERPRISE_INSTANCE_TYPE.DEVELOPMENT) {
|
||||
const productionServerId =
|
||||
stripeMetadata?.[STRIPE_METADATA_KEY.BOUND_SERVER_ID];
|
||||
const productionLastSeenAt =
|
||||
stripeMetadata?.[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT];
|
||||
|
||||
const hasActiveProductionBinding =
|
||||
!isEmpty(productionServerId) &&
|
||||
!isStale(productionLastSeenAt, autoReleaseDays, now);
|
||||
|
||||
if (!hasActiveProductionBinding) {
|
||||
return {
|
||||
outcome: SERVER_BINDING_OUTCOME.REJECTED,
|
||||
code: SERVER_BINDING_REJECTION_CODE.DEV_REQUIRES_ACTIVE_PRODUCTION,
|
||||
reason:
|
||||
'A free development instance requires an active production instance on this enterprise subscription.',
|
||||
};
|
||||
}
|
||||
|
||||
const expectedDevServerId = normalizeServerId(
|
||||
stripeMetadata?.[STRIPE_METADATA_KEY.DEV_SERVER_ID],
|
||||
);
|
||||
const devLastSeenAt =
|
||||
stripeMetadata?.[STRIPE_METADATA_KEY.DEV_SERVER_LAST_SEEN_AT];
|
||||
|
||||
if (
|
||||
isEmpty(expectedDevServerId) ||
|
||||
expectedDevServerId === normalizedServerId ||
|
||||
isStale(devLastSeenAt, autoReleaseDays, now)
|
||||
) {
|
||||
return {
|
||||
outcome: SERVER_BINDING_OUTCOME.ALLOWED,
|
||||
isBillable: false,
|
||||
metadataPatch: {
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_ID]: normalizedServerId,
|
||||
[STRIPE_METADATA_KEY.DEV_SERVER_LAST_SEEN_AT]: nowIso,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
outcome: SERVER_BINDING_OUTCOME.REJECTED,
|
||||
code: SERVER_BINDING_REJECTION_CODE.DEV_SLOT_IN_USE,
|
||||
reason:
|
||||
'The development instance slot for this enterprise key is already in use on another server.',
|
||||
};
|
||||
}
|
||||
|
||||
const boundServerId = normalizeServerId(
|
||||
stripeMetadata?.[STRIPE_METADATA_KEY.BOUND_SERVER_ID],
|
||||
);
|
||||
const boundLastSeenAt =
|
||||
stripeMetadata?.[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT];
|
||||
|
||||
if (
|
||||
isEmpty(boundServerId) ||
|
||||
boundServerId === normalizedServerId ||
|
||||
isStale(boundLastSeenAt, autoReleaseDays, now)
|
||||
) {
|
||||
return {
|
||||
outcome: SERVER_BINDING_OUTCOME.ALLOWED,
|
||||
isBillable: true,
|
||||
metadataPatch: {
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_ID]: normalizedServerId,
|
||||
[STRIPE_METADATA_KEY.BOUND_SERVER_LAST_SEEN_AT]: nowIso,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
outcome: SERVER_BINDING_OUTCOME.REJECTED,
|
||||
code: SERVER_BINDING_REJECTION_CODE.BOUND_TO_ANOTHER_SERVER,
|
||||
reason:
|
||||
'This enterprise key is already in use on another server instance. Release it from that server or transfer it to this one.',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export const SERVER_BINDING_OUTCOME = {
|
||||
ALLOWED: 'allowed',
|
||||
REJECTED: 'rejected',
|
||||
} as const;
|
||||
|
||||
export type ServerBindingOutcome =
|
||||
(typeof SERVER_BINDING_OUTCOME)[keyof typeof SERVER_BINDING_OUTCOME];
|
||||
@@ -0,0 +1,11 @@
|
||||
// Distinct machine codes per rejection reason so clients can react correctly
|
||||
// (only BOUND_TO_ANOTHER_SERVER means another server owns the key).
|
||||
export const SERVER_BINDING_REJECTION_CODE = {
|
||||
BOUND_TO_ANOTHER_SERVER: 'ENTERPRISE_KEY_BOUND_TO_ANOTHER_SERVER',
|
||||
MISSING_SERVER_ID: 'ENTERPRISE_MISSING_SERVER_ID',
|
||||
DEV_REQUIRES_ACTIVE_PRODUCTION: 'ENTERPRISE_DEV_REQUIRES_ACTIVE_PRODUCTION',
|
||||
DEV_SLOT_IN_USE: 'ENTERPRISE_DEV_SLOT_IN_USE',
|
||||
} as const;
|
||||
|
||||
export type ServerBindingRejectionCode =
|
||||
(typeof SERVER_BINDING_REJECTION_CODE)[keyof typeof SERVER_BINDING_REJECTION_CODE];
|
||||
@@ -4,7 +4,7 @@ import { signValidityToken } from './sign-validity-token';
|
||||
import { verifyJwt } from './verify-jwt';
|
||||
|
||||
const SECONDS_PER_DAY = 24 * 60 * 60;
|
||||
const DEFAULT_DURATION_DAYS = 30;
|
||||
const DEFAULT_DURATION_DAYS = 7;
|
||||
|
||||
type ValidityClaims = {
|
||||
exp: number;
|
||||
@@ -51,7 +51,7 @@ describe('signValidityToken', () => {
|
||||
});
|
||||
|
||||
it('clamps exp down to a cancellation inside the window', () => {
|
||||
const cancelAt = Math.floor(Date.now() / 1000) + 10 * SECONDS_PER_DAY;
|
||||
const cancelAt = Math.floor(Date.now() / 1000) + 3 * SECONDS_PER_DAY;
|
||||
const claims = verifiedClaims(
|
||||
signValidityToken('sub_clamped', { subscriptionCancelAt: cancelAt }),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { signJwt } from './sign-jwt';
|
||||
|
||||
const DEFAULT_VALIDITY_TOKEN_DURATION_DAYS = 30;
|
||||
const DEFAULT_VALIDITY_TOKEN_DURATION_DAYS = 7;
|
||||
const SECONDS_PER_DAY = 24 * 60 * 60;
|
||||
|
||||
type EnterpriseValidityPayload = {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
// Keys used to persist the enterprise binding state on the Stripe subscription
|
||||
// metadata (Stripe is the stateless store for twenty-website).
|
||||
export const STRIPE_METADATA_KEY = {
|
||||
BOUND_SERVER_ID: 'boundServerId',
|
||||
BOUND_SERVER_LAST_SEEN_AT: 'boundServerLastSeenAt',
|
||||
DEV_SERVER_ID: 'devServerId',
|
||||
DEV_SERVER_LAST_SEEN_AT: 'devServerLastSeenAt',
|
||||
RELEASE_TIMESTAMPS: 'releaseTimestamps',
|
||||
} as const;
|
||||
@@ -0,0 +1 @@
|
||||
export type StripeMetadata = Record<string, string> | null | undefined;
|
||||
@@ -0,0 +1,11 @@
|
||||
import {
|
||||
ENTERPRISE_INSTANCE_TYPE,
|
||||
type EnterpriseInstanceType,
|
||||
} from './enterprise-instance-type';
|
||||
|
||||
// Validity token emissions are rate-limited independently per instance type,
|
||||
// so each type gets its own timestamps bucket in the Stripe metadata.
|
||||
export const VALIDITY_TOKEN_EMISSIONS_KEY_BY_INSTANCE_TYPE = {
|
||||
[ENTERPRISE_INSTANCE_TYPE.PRODUCTION]: 'validityTokenEmissionsProduction',
|
||||
[ENTERPRISE_INSTANCE_TYPE.DEVELOPMENT]: 'validityTokenEmissionsDevelopment',
|
||||
} as const satisfies Record<EnterpriseInstanceType, string>;
|
||||
Reference in New Issue
Block a user