Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,243 @@
import Constants from "~/application/Constants";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { EntitiesTemplateDto, TemplateEntityDto, TemplateEntityViewDto } from "~/modules/templates/EntityTemplateDto";
import getMaxEntityOrder, { createEntity, EntityWithDetails, findEntityByName, getEntityByName } from "../../db/entities/entities.db.server";
import { createEntityRelationship, EntityRelationshipWithDetails } from "../../db/entities/entityRelationships.db.server";
import { createEntityView, updateEntityViewProperties, updateEntityViewFilters, updateEntityViewSort } from "../../db/entities/entityViews.db.server";
import { createProperty, updatePropertyOptions, updatePropertyAttributes, getEntityPropertyByName } from "../../db/entities/properties.db.server";
import { createEntityPermissions } from "../../db/permissions/permissions.db.server";
import EntityViewHelper from "../../helpers/EntityViewHelper";
import OrderHelper from "../../helpers/OrderHelper";
import { mapToEntityTemplateType } from "../../helpers/PropertyHelper";
export async function validateEntitiesFromTemplate(template: EntitiesTemplateDto) {
if (template.entities.length === 0) {
throw Error("Invalid configuration");
}
await Promise.all(
template.entities.map(async (entity) => {
const existingEntity = await findEntityByName({ tenantId: null, name: entity.name });
if (existingEntity) {
throw Error("Entity already exists: " + entity.name);
}
if (!entity.properties || entity.properties.length === 0) {
throw Error("Entity has no properties: " + entity.name);
}
entity.properties.forEach((property) => {
if (property.name.includes(" ")) {
throw Error("Property names cannot contain spaces: " + property.name);
}
if (property.name.includes("-")) {
throw Error("Property names cannot contain '-': " + property.name);
}
});
})
);
}
export async function importEntitiesFromTemplate({ template, createdByUserId }: { template: EntitiesTemplateDto; createdByUserId: string }) {
const maxEntityOrder = await getMaxEntityOrder();
const createdEntities = await Promise.all(
template.entities.map(async (entity, idx) => {
const createdEntity = await createEntity(
{
name: entity.name,
slug: entity.slug,
prefix: entity.prefix,
title: entity.title,
titlePlural: entity.titlePlural,
isAutogenerated: entity.isAutogenerated ?? true,
hasApi: entity.hasApi ?? true,
icon: entity.icon ?? "",
active: entity.active ?? true,
type: entity.type ?? DefaultEntityTypes.All,
showInSidebar: entity.showInSidebar ?? true,
hasTags: entity.hasTags ?? true,
hasComments: entity.hasComments ?? true,
hasTasks: entity.hasTasks ?? false,
hasActivity: entity.hasActivity !== undefined ? entity.hasActivity : true,
hasBulkDelete: entity.hasBulkDelete !== undefined ? entity.hasBulkDelete : false,
hasViews: entity.hasViews !== undefined ? entity.hasViews : true,
defaultVisibility: entity.defaultVisibility ?? DefaultVisibility.Tenant,
onCreated: entity.onCreated ?? "redirectToOverview",
onEdit: entity.onEdit ?? "editRoute",
},
maxEntityOrder + idx + 1
);
// eslint-disable-next-line no-console
console.log("Entity created", createdEntity.name);
if (!createdEntity) {
throw new Error("Unable to create entity: " + JSON.stringify(entity));
}
await createEntityPermissions(createdEntity);
const newEntity = await getEntityByName({ tenantId: null, name: createdEntity.name });
const propertyOrder = OrderHelper.getNextOrder(newEntity.properties);
const properties = await Promise.all(
entity.properties.map(async (property, idxProperty) => {
let type: PropertyType | undefined = undefined;
if (property.type === "string") {
type = PropertyType.TEXT;
} else if (property.type === "number") {
type = PropertyType.NUMBER;
} else if (property.type === "boolean") {
type = PropertyType.BOOLEAN;
} else if (property.type === "date") {
type = PropertyType.DATE;
} else if (property.type === "media") {
type = PropertyType.MEDIA;
} else if (property.type === "select") {
type = PropertyType.SELECT;
} else if (property.type === "multiSelect") {
type = PropertyType.MULTI_SELECT;
} else if (property.type === "multiText") {
type = PropertyType.MULTI_TEXT;
} else if (property.type === "rangeNumber") {
type = PropertyType.RANGE_NUMBER;
} else if (property.type === "rangeDate") {
type = PropertyType.RANGE_DATE;
} else if (property.type === "formula") {
type = PropertyType.FORMULA;
} else {
throw new Error("Invalid property type: " + property.type);
}
const createdProperty = await createProperty({
entityId: createdEntity.id,
name: property.name,
title: property.title,
type,
subtype: property.subtype ?? null,
order: propertyOrder + idxProperty,
isDefault: false,
isRequired: property.isRequired ?? false,
isHidden: false,
isDisplay: property.isDisplay ?? false,
isReadOnly: property.isReadOnly ?? false,
canUpdate: property.canUpdate !== undefined ? property.canUpdate : true,
showInCreate: property.showInCreate ?? true,
formulaId: null,
tenantId: property.tenantId ?? null,
});
if (property.options) {
await updatePropertyOptions(
createdProperty.id,
property.options.map((item, idxOption) => {
return {
order: idxOption + 1,
value: item.value,
name: item.name,
color: item.color === undefined ? undefined : item.color,
};
})
);
}
if (property.attributes) {
await updatePropertyAttributes(
createdProperty.id,
property.attributes.map((item) => {
return {
value: item.value,
name: item.name,
};
})
);
}
return createdProperty;
})
);
// Views
if (entity.views) {
await Promise.all(
entity.views.map(async (view, idx) => {
const groupByProperty = properties.find((f) => f.name === view.groupByProperty);
if (view.tenantId) {
return;
}
const entityView = await createEntityView({
order: idx + 1,
entityId: createdEntity.id,
layout: view.layout,
name: view.name,
title: view.title,
isDefault: view.isDefault ?? false,
tenantId: null,
userId: view.userId ?? null,
createdByUserId,
isSystem: view.isSystem ?? false,
pageSize: view.pageSize ?? Constants.DEFAULT_PAGE_SIZE,
groupByPropertyId: groupByProperty?.id ?? null,
});
let viewProperties: { propertyId: string | null; order: number; name: string }[] = view.properties
? await Promise.all(
view.properties.map(async (prop, idxProp) => {
const property = await getEntityPropertyByName(createdEntity.id, prop);
return {
order: idxProp + 1,
propertyId: property?.id ?? null,
name: prop,
};
})
)
: [];
if (viewProperties.length === 0) {
viewProperties = newEntity.properties.map((item) => {
return {
propertyId: item.id,
order: item.order,
name: item.name,
};
});
}
const viewFilters: { name: string; condition: string; value: string; match: "and" | "or" }[] =
view.filters?.map((filter) => {
return {
match: filter.match ?? "and",
name: filter.name,
condition: filter.condition,
value: filter.value,
};
}) ?? [];
const viewSort: { name: string; asc: boolean; order: number }[] =
view.sort?.map((sort, idxSort) => {
return {
name: sort.name,
asc: sort.asc,
order: idxSort + 1,
};
}) ?? [];
await updateEntityViewProperties(entityView.id, viewProperties);
await updateEntityViewFilters(entityView.id, viewFilters);
await updateEntityViewSort(entityView.id, viewSort);
})
);
}
return createdEntity;
})
);
if (createdEntities.length > 0 && template.relationships) {
await Promise.all(
template.relationships.map(async (relationship) => {
const fromEntity = await getEntityByName({ tenantId: null, name: relationship.parent });
const toEntity = await getEntityByName({ tenantId: null, name: relationship.child });
return await createEntityRelationship({
parentId: fromEntity.id,
childId: toEntity.id,
order: relationship.order ?? 0,
title: relationship.title ?? null,
type: relationship.type ?? "one-to-many",
required: relationship.required ?? false,
cascade: false,
readOnly: relationship.readOnly ?? false,
hiddenIfEmpty: relationship.hiddenIfEmpty !== undefined ? relationship.hiddenIfEmpty : false,
childEntityViewId: null,
parentEntityViewId: null,
});
})
);
}
return createdEntities;
}
@@ -0,0 +1,87 @@
/**
* Feature-flags eval-cache (two-tier). Mirrors subscriptionCache pattern.
*
* L1 = in-process Map for sub-microsecond reads on the render hot-path.
* L2 = SharedStore (Redis or in-memory adapter) for cross-replica reuse.
* Pub/sub channel `shared-store:<ns>:ch:cache:feature-flags:invalidate`
* fans out flag-mutation events — every replica flushes its L1 on
* receipt so the next eval re-reads from DB.
*
* Bootstrap: call `subscribeFeatureFlagCache()` exactly once during web
* boot (idempotent). On flag mutation (admin save) the action handler
* calls `getFeatureFlagCache().invalidateFlag(flagName)` which publishes
* a sentinel — peer L1s flush wholesale (cheap, mutations are rare).
*/
import {
FEATURE_FLAGS_INVALIDATION_CHANNEL,
createFlagEvalCache,
type EvaluateFlagResult,
type FlagEvalCache,
} from "@toolctrl/feature-flags";
import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { createScopedLogger } from "~/utils/logger.server";
const log = createScopedLogger("feature-flags-cache");
const TTL_SECONDS_DEFAULT = 60; // spec: per-ctx eval result cached 60s.
let tierSingleton: TwoTierCache<EvaluateFlagResult> | null = null;
let cacheSingleton: FlagEvalCache | null = null;
let subscribeDisposer: (() => Promise<void>) | null = null;
function pubsubEnabledFromEnv(): boolean {
const raw = process.env.CACHE_INVALIDATION_ENABLED;
if (raw === undefined || raw === null || raw === "") return true;
return raw.toLowerCase() !== "false" && raw !== "0";
}
function ttlSecondsFromEnv(): number {
const raw = process.env.FEATURE_FLAGS_CACHE_TTL_SECONDS;
if (!raw) return TTL_SECONDS_DEFAULT;
const parsed = Number(raw);
if (!Number.isFinite(parsed) || parsed <= 0) return TTL_SECONDS_DEFAULT;
return Math.floor(parsed);
}
function getTier(): TwoTierCache<EvaluateFlagResult> {
if (tierSingleton) return tierSingleton;
tierSingleton = createTwoTierCache<EvaluateFlagResult>({
store: getSharedStore(),
namespace: "feature-flags",
ttlSeconds: ttlSecondsFromEnv(),
pubsubEnabled: pubsubEnabledFromEnv(),
logger: { warn: (obj, msg) => log.warn(obj, msg), error: (obj, msg) => log.error(obj, msg) },
});
return tierSingleton;
}
export function getFeatureFlagCache(): FlagEvalCache {
if (cacheSingleton) return cacheSingleton;
cacheSingleton = createFlagEvalCache(getTier());
return cacheSingleton;
}
/**
* Start the subscriber for this process. Idempotent. The handler
* flushes the entire L1 on any invalidation receipt, which is the
* correct trade-off because flag mutations are rare and L1 is small.
*/
export async function subscribeFeatureFlagCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
const tier = getTier();
subscribeDisposer = await tier.subscribe(() => {
// Any invalidation drops everything — see cache.ts comment.
tier.flushLocal();
});
log.info({ namespace: "feature-flags", channel: FEATURE_FLAGS_INVALIDATION_CHANNEL }, "feature-flag cache subscriber started");
return subscribeDisposer;
}
/** Test seam. */
export function __resetFeatureFlagCacheForTests(): void {
tierSingleton = null;
cacheSingleton = null;
subscribeDisposer = null;
}
@@ -0,0 +1,96 @@
/**
* Server-side evaluateFlag bridge.
*
* Wires the Prisma FeatureFlag table into the package-level
* `evaluateFlag` (`@toolctrl/feature-flags`). Caller passes a request
* + an EvaluationContext; we look up the row by name (caches L2-first
* via the feature-flag eval cache), run the pure evaluator and
* memo-cache the typed result for 60s.
*
* Multi-key lookup: the package-level loader is keyed by `name`, but
* dependency-resolution calls back with a parent-flag *id*. We
* therefore accept either via a single Prisma `OR` query so the
* second-level lookup keeps working.
*/
import {
evaluateFlag as evaluatePackage,
getFeatureFlagVariant as packageGetVariant,
type EvaluateFlagResult,
type FlagLoader,
type StoredFeatureFlag,
} from "@toolctrl/feature-flags";
import type { EvaluationContext } from "@toolctrl/feature-flags";
import type { FeatureFlag } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { getFeatureFlagCache } from "./featureFlagCache.server";
function toStored(row: FeatureFlag | null): StoredFeatureFlag | null {
if (!row) return null;
return {
id: row.id,
name: row.name,
enabled: row.enabled,
rules: row.rules ?? null,
variants: Array.isArray(row.variants) ? row.variants : [],
enabledFrom: row.enabledFrom ?? null,
enabledUntil: row.enabledUntil ?? null,
parentFlagId: row.parentFlagId ?? null,
};
}
const createLoader = (): FlagLoader => async (key: string) => {
// OR-lookup so dependency-resolution (which calls back with an id)
// works against the same loader.
const row = await db.featureFlag.findFirst({
where: { OR: [{ name: key }, { id: key }] },
});
return toStored(row);
};
/**
* Evaluate a single flag with full cache, dependency-resolution, and
* variant-selection. Returns the structured `{ enabled, variant?, reason }`.
*/
export async function evaluateFlagForContext(
name: string,
ctx: EvaluationContext,
): Promise<EvaluateFlagResult> {
const cache = getFeatureFlagCache();
const cached = await cache.get(name, ctx);
if (cached) return cached;
const result = await evaluatePackage(name, ctx, { load: createLoader() });
await cache.set(name, ctx, result);
return result;
}
/** Variant-only convenience wrapper. */
export async function getFeatureFlagVariantForContext(
name: string,
ctx: EvaluationContext,
) {
return packageGetVariant(name, ctx, { load: createLoader() });
}
/**
* Evaluate several flags in parallel. Used by root-loader SSR
* hydration so the React tree can read flags synchronously through
* a single context provider without re-fetching per call.
*/
export async function evaluateFlagsForContext(
names: readonly string[],
ctx: EvaluationContext,
): Promise<Record<string, EvaluateFlagResult>> {
const entries = await Promise.all(
names.map(async (n) => [n, await evaluateFlagForContext(n, ctx)] as const),
);
return Object.fromEntries(entries);
}
/**
* Drop every cached eval for a flag — call after admin mutations.
* Publishes on the feature-flags:invalidate channel.
*/
export async function invalidateFlagCache(flagName: string): Promise<void> {
await getFeatureFlagCache().invalidateFlag(flagName);
}
@@ -0,0 +1,85 @@
/**
* Request-bound bridge into the v2 evaluator.
*
* The legacy {@link FeatureFlagsService.hasFeatureFlag} accepts
* `(request, params, flagName)`. The v2 engine accepts an
* {@link EvaluationContext}. This helper assembles the context from
* the request (tenantId, userId) and delegates to
* `evaluateFlagForContext`, so existing call-sites can switch
* imports without changing their signatures.
*
* Returns `{ enabled, variant?, reason }` — call-sites that only
* care about the boolean use the convenience `isFeatureFlagEnabled`
* wrapper. Existing v1 routes that already build their own context
* via `FeatureFlagsService.hasFeatureFlag` keep working in parallel;
* v2 is opt-in.
*/
import { Params } from "react-router";
import type { EvaluateFlagResult } from "@toolctrl/feature-flags";
import { evaluateFlagForContext, evaluateFlagsForContext } from "./featureFlagEvaluator.server";
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
import { getUserInfo } from "~/utils/session.server";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
export interface RequestContextInput {
request: Request;
params: Params;
}
export async function evaluateFlagForRequest(
flagName: string,
{ request, params }: RequestContextInput,
): Promise<EvaluateFlagResult> {
const [tenantId, userInfo] = await Promise.all([
getTenantIdOrNull({ request, params }),
getUserInfo(request),
]);
return evaluateFlagForContext(flagName, {
flagName,
tenantId: tenantId ?? null,
userId: userInfo.userId || null,
});
}
/** Boolean shortcut for callers migrating from `hasFeatureFlag`. */
export async function isFeatureFlagEnabled(
flagName: string,
input: RequestContextInput,
): Promise<boolean> {
const result = await evaluateFlagForRequest(flagName, input);
return result.enabled;
}
/**
* SSR-hydration helper — return the names of every flag whose v2
* evaluation resolves `enabled` for the current request context.
*
* Replaces the v1 `FeatureFlagsService.getCurrentFeatureFlags` which
* was scoped + filtered through `FeatureFlagsFiltersService` (a
* separate filter engine that ran *outside* the v2 evaluator). The v2
* port skips the legacy filter table: callers are responsible for
* porting any per-flag filter rows into v2 rules in
* `FeatureFlag.rules` (see `docs/improvement-plan/...`). Until that
* data migration lands, results reflect the flag's bare
* `enabled=true` boolean modulo v2 rule evaluation.
*/
export async function getCurrentEnabledFlagNames(input: RequestContextInput): Promise<string[]> {
const [tenantId, userInfo, flags] = await Promise.all([
getTenantIdOrNull(input),
getUserInfo(input.request),
getAllFeatureFlags(),
]);
const names = flags
.map((f) => f.name ?? f.key ?? "")
.filter((n) => n.length > 0);
if (names.length === 0) return [];
const results = await evaluateFlagsForContext(names, {
flagName: "*",
tenantId: tenantId ?? null,
userId: userInfo.userId || null,
});
return Object.entries(results)
.filter(([, r]) => r.enabled)
.map(([n]) => n);
}
@@ -0,0 +1,652 @@
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
import { SubscriptionProductDto } from "../../../application/dtos/subscriptions/SubscriptionProductDto";
import {
createSubscriptionProduct,
createSubscriptionPrice,
createSubscriptionFeature,
updateSubscriptionProductStripeId,
updateSubscriptionPriceStripeId,
deleteSubscriptionPrice,
deleteSubscriptionProduct,
updateSubscriptionProduct,
deleteSubscriptionFeatures,
deleteSubscriptionUsageBasedTier,
deleteSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedTier,
getSubscriptionPriceByStripeId,
getSubscriptionUsageBasedPriceByStripeId,
getSubscriptionProduct,
getAllSubscriptionProducts,
} from "../../db/subscriptionProducts.db.server";
import {
createStripeProduct,
createStripePrice,
archiveStripePrice,
deleteStripeProduct,
updateStripeProduct,
createStripeUsageBasedPrice,
archiveStripeProduct,
getStripeSession,
createStripeCustomer,
createStripeSubscription,
} from "../../stripe.server";
import { CheckoutSessionStatus, SubscriptionPrice, SubscriptionUsageBasedPrice } from "@toolctrl/db/prisma-browser";
import Stripe from "stripe";
import { getOrPersistTenantSubscription, updateTenantSubscriptionCustomerId } from "../../db/tenantSubscriptions.db.server";
import { getTenant } from "../../db/tenants.db.server";
import { getCheckoutSessionStatus, updateCheckoutSessionStatus } from "../../db/stripe/checkoutSessions.db.server";
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
import { TFunction } from "i18next";
import { TenantTypesApi } from "../../api/.server/TenantTypesApi";
import { addTenantSubscriptionProduct } from "../../db/subscriptions/tenantSubscriptionProducts.db.server";
import EventsService from "../../../modules/events/services/.server/EventsService";
import { SubscriptionSubscribedDto } from "~/modules/events/dtos/SubscriptionSubscribedDto";
import { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto";
import { getUser } from "../../db/users.db.server";
import { cancelTenantSubscription, clearAllSubscriptionsCache, clearTenantSubscriptionCache, getActiveTenantSubscriptions } from "./subscriptionService";
import currencies from "~/application/pricing/currencies";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { createScopedLogger } from "~/utils/logger.server";
const pricingLogger = createScopedLogger("pricing");
export async function createPlans(plans: SubscriptionProductDto[]) {
for (const plan of plans.sort((a, b) => a.order - b.order)) {
await createPlan(
plan,
plan.prices.map((price) => {
return {
billingPeriod: price.billingPeriod,
currency: price.currency,
price: Number(price.price),
};
}),
plan.features,
plan.usageBasedPrices
);
}
}
export async function createPlan(
plan: SubscriptionProductDto,
prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[],
features: SubscriptionFeatureDto[],
usageBasedPrices?: SubscriptionUsageBasedPriceDto[],
t?: TFunction
) {
// Create stripe product
const stripeProduct = await createStripeProduct({ title: plan.translatedTitle ?? plan.title });
// Save to db
const product = await createSubscriptionProduct({
stripeId: stripeProduct?.id ?? "",
order: plan.order,
title: plan.title,
model: plan.model,
description: plan.description ?? null,
badge: plan.badge ?? null,
groupTitle: plan.groupTitle ?? null,
groupDescription: plan.groupDescription ?? null,
active: plan.active,
public: plan.public,
billingAddressCollection: plan.billingAddressCollection ?? "auto",
hasQuantity: plan.hasQuantity ?? false,
canBuyAgain: plan.canBuyAgain ?? false,
});
if (!product) {
throw new Error("Could not create subscription product");
}
await Promise.all(
prices.map(async (price) => {
// Create stripe price
const stripePrice = await createStripePrice(stripeProduct?.id ?? "", price);
// Save to db
return await createSubscriptionPrice({
...price,
subscriptionProductId: product.id,
stripeId: stripePrice?.id ?? "",
type: SubscriptionPriceType.RECURRING,
billingPeriod: price.billingPeriod,
price: price.price,
currency: price.currency,
trialDays: price.trialDays ?? 0,
active: true,
});
})
);
await Promise.all(
features
.sort((a, b) => a.order - b.order)
.map(async (feature) => {
// Save to db
return await createSubscriptionFeature(product.id, feature);
})
);
if (usageBasedPrices) {
await Promise.all(
usageBasedPrices.map(async (usageBasedPrice) => {
pricingLogger.info(
{ op: "createUsageBasedPrice", productId: product.id, billingPeriod: usageBasedPrice.billingPeriod, unit: usageBasedPrice.unit },
"Creating usage-based price",
);
const stripePrice = await createStripeUsageBasedPrice(stripeProduct?.id ?? "", {
...usageBasedPrice,
unitTitle: t ? t(usageBasedPrice.unitTitle) : usageBasedPrice.unitTitle,
});
const createdPrice = await createSubscriptionUsageBasedPrice({
subscriptionProductId: product.id,
stripeId: stripePrice?.id ?? "",
billingPeriod: usageBasedPrice.billingPeriod,
currency: usageBasedPrice.currency,
unit: usageBasedPrice.unit,
unitTitle: usageBasedPrice.unitTitle,
unitTitlePlural: usageBasedPrice.unitTitlePlural,
usageType: usageBasedPrice.usageType,
aggregateUsage: usageBasedPrice.aggregateUsage,
tiersMode: usageBasedPrice.tiersMode,
billingScheme: usageBasedPrice.billingScheme,
});
await Promise.all(
usageBasedPrice.tiers.map(async (tierPrice) => {
await createSubscriptionUsageBasedTier({
subscriptionUsageBasedPriceId: createdPrice.id,
from: tierPrice.from,
to: tierPrice.to !== null && tierPrice.to !== undefined ? Number(tierPrice.to) : null,
perUnitPrice: tierPrice.perUnitPrice !== null && tierPrice.perUnitPrice !== undefined ? Number(tierPrice.perUnitPrice) : null,
flatFeePrice: tierPrice.flatFeePrice !== null && tierPrice.flatFeePrice !== undefined ? Number(tierPrice.flatFeePrice) : null,
});
})
);
})
);
}
}
export async function syncPlan(
plan: SubscriptionProductDto,
prices: { id?: string; billingPeriod: SubscriptionBillingPeriod; price: number; currency: string }[]
) {
if (!plan.id) {
throw new Error(`Plan ${plan.title} not found on database`);
}
const stripeProduct = await createStripeProduct({ title: plan.translatedTitle ?? plan.title });
if (!stripeProduct) {
throw new Error("Could not create product");
}
await updateSubscriptionProductStripeId(plan.id, {
stripeId: stripeProduct.id,
});
prices.map(async (price) => {
// Create stripe price
const stripePrice = await createStripePrice(stripeProduct?.id ?? "", price);
if (!stripePrice) {
throw new Error(`Could not create price ${plan.title} - ${price.price}`);
}
// Save to db
await updateSubscriptionPriceStripeId(price.id ?? "", {
stripeId: stripePrice?.id ?? "",
});
});
}
export async function updatePlan(plan: SubscriptionProductDto, features: SubscriptionFeatureDto[]) {
if (!plan.id) {
throw new Error(`Plan ${plan.title} not found on database`);
}
await updateStripeProduct(plan.stripeId, { title: plan.translatedTitle ?? plan.title });
await updateSubscriptionProduct(plan.id, {
order: plan.order,
title: plan.title,
model: plan.model,
description: plan.description ?? null,
badge: plan.badge ?? null,
groupTitle: plan.groupTitle ?? null,
groupDescription: plan.groupDescription ?? null,
public: plan.public,
billingAddressCollection: plan.billingAddressCollection ?? "auto",
hasQuantity: plan.hasQuantity === undefined ? undefined : plan.hasQuantity,
canBuyAgain: plan.canBuyAgain === undefined ? undefined : plan.canBuyAgain,
});
await deleteSubscriptionFeatures(plan.id ?? "");
await clearAllSubscriptionsCache();
return await Promise.all(
features
.sort((a, b) => a.order - b.order)
.map(async (feature) => {
return await createSubscriptionFeature(plan.id ?? "", feature);
})
);
}
export async function deletePlan(plan: SubscriptionProductDto) {
await clearAllSubscriptionsCache();
pricingLogger.info({ op: "deletePlan.flatPrices", planId: plan.id, count: plan.prices?.length ?? 0 }, "Deleting flat-rate prices");
await Promise.all(
plan.prices
.filter((f) => f.stripeId)
.map(async (price) => {
await archiveStripePrice(price.stripeId);
if (price.id) {
await deleteSubscriptionPrice(price.id);
}
return null;
})
);
pricingLogger.info(
{ op: "deletePlan.usageBasedPrices", planId: plan.id, count: plan.usageBasedPrices?.length ?? 0 },
"Deleting usage-based prices",
);
if (plan.usageBasedPrices) {
await Promise.all(
plan.usageBasedPrices?.map(async (price) => {
await archiveStripePrice(price.stripeId);
await Promise.all(
price.tiers.map(async (tier) => {
return deleteSubscriptionUsageBasedTier(tier.id);
})
);
await deleteSubscriptionUsageBasedPrice(price.id);
return null;
})
);
}
pricingLogger.info({ op: "deletePlan.product", planId: plan.id, stripeId: plan.stripeId }, "Deleting Stripe product");
if (plan.stripeId) {
try {
await deleteStripeProduct(plan.stripeId);
} catch (e: any) {
pricingLogger.warn(
{ err: e, op: "deletePlan.product.archive", planId: plan.id, stripeId: plan.stripeId },
"Could not delete Stripe product; archiving instead",
);
await archiveStripeProduct(plan.stripeId);
}
}
if (plan.id) {
await deleteSubscriptionProduct(plan.id);
}
}
export type CheckoutSessionResponse = {
id: string;
customer: {
id: string;
email: string;
name: string;
};
products: {
id: string;
title: string;
quantity: number;
subscription: string | undefined;
prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[];
}[];
status: CheckoutSessionStatus | null;
};
export async function getAcquiredItemsFromCheckoutSession(session_id: string | null): Promise<CheckoutSessionResponse | null> {
const session = await getStripeSession(session_id ?? "");
if (!session || session.status !== "complete") {
return null;
}
const prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[] = [];
try {
let line_items: { price: Stripe.Price; quantity: number | undefined }[] = [];
if (session.line_items) {
session.line_items.data.forEach((item) => {
if (item.price) {
line_items.push({
price: item.price,
quantity: item.quantity ?? undefined,
});
}
});
}
await Promise.all(
line_items.map(async (line_item) => {
const flatPrice = await getSubscriptionPriceByStripeId(line_item.price.id);
const usageBasedPrice = await getSubscriptionUsageBasedPriceByStripeId(line_item.price.id);
const quantity = line_item.quantity ?? undefined;
if (!flatPrice && !usageBasedPrice) {
throw new Error("Price not found: " + line_item.price.id);
}
prices.push({
flatPrice: flatPrice ?? undefined,
usageBasedPrice: usageBasedPrice ?? undefined,
quantity,
});
})
);
} catch (e: any) {
pricingLogger.error({ err: e, op: "getAcquiredItemsFromCheckoutSession" }, "Failed to load acquired items from checkout session");
}
const products: {
id: string;
title: string;
quantity: number;
subscription: string | undefined;
prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[];
}[] = [];
prices.forEach((item) => {
const productId = item.flatPrice?.subscriptionProductId ?? item.usageBasedPrice?.subscriptionProductId ?? "";
if (!productId) {
return;
}
const product = products.find((p) => p.id === productId);
if (!product) {
products.push({
id: productId,
title: "",
quantity: item.quantity ?? 1,
prices: [item],
subscription: session.subscription?.toString(),
});
} else {
product?.prices.push(item);
}
});
await Promise.all(
products.map(async (product) => {
const subscriptionProduct = await getSubscriptionProduct(product.id);
product.title = subscriptionProduct?.title ?? "";
})
);
const status = await getCheckoutSessionStatus(session.id);
return {
id: session.id,
customer: {
id: session.customer?.toString() ?? "",
name: session.customer_details?.name ?? "",
email: session.customer_details?.email ?? "",
},
products,
status,
};
}
export async function addTenantProductsFromCheckoutSession({
request,
tenantId,
user,
checkoutSession,
createdUserId,
createdTenantId,
t,
}: {
request: Request;
tenantId: string;
user: { id: string; email: string };
checkoutSession: CheckoutSessionResponse;
createdUserId?: string | null;
createdTenantId?: string | null;
t: TFunction;
}) {
clearTenantSubscriptionCache(tenantId);
const appConfiguration = await getAppConfiguration({ request });
const tenant = await getTenant(tenantId);
if (!tenant) {
throw new Error("Tenant not found");
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
if (!tenantSubscription.stripeCustomerId) {
const customer = await createStripeCustomer(user.email, tenant.name);
if (customer) {
tenantSubscription.stripeCustomerId = customer.id;
await updateTenantSubscriptionCustomerId(tenant.id, {
stripeCustomerId: customer.id,
});
}
}
const existingSessionStatus = await getCheckoutSessionStatus(checkoutSession.id);
if (!checkoutSession) {
throw new Error(t("settings.subscription.checkout.invalid"));
} else if (checkoutSession.customer.id !== tenantSubscription.stripeCustomerId) {
throw new Error(t("settings.subscription.checkout.invalidCustomer"));
} else if (!existingSessionStatus) {
throw new Error(t("settings.subscription.checkout.invalid"));
} else if (!existingSessionStatus.pending) {
throw new Error(t("settings.subscription.checkout.alreadyProcessed"));
} else {
await updateCheckoutSessionStatus(checkoutSession.id, {
pending: false,
createdUserId,
createdTenantId,
});
if (!appConfiguration.subscription.multiple) {
const hasSubscribed = checkoutSession.products.some((product) => product.subscription);
const activeSubscriptions = await getActiveTenantSubscriptions(tenant.id);
const recurringSubscriptions = activeSubscriptions?.products.filter((f) => f.stripeSubscriptionId) || [];
pricingLogger.info(
{
op: "cancelExistingSubscriptions",
tenantId: tenant.id,
hasSubscribed,
recurringCount: recurringSubscriptions.length,
},
"Cancelling existing subscriptions before new subscribe",
);
if (hasSubscribed && recurringSubscriptions.length > 0) {
await Promise.all(
recurringSubscriptions.map(async (recurringSubscription) => {
pricingLogger.info(
{
op: "cancelSubscription",
tenantId: tenant.id,
subscriptionId: recurringSubscription.id,
productId: recurringSubscription.subscriptionProductId,
},
"Cancelling tenant subscription",
);
return await cancelTenantSubscription(recurringSubscription.id, { tenantId, userId: user.id, t });
})
);
}
}
await Promise.all(
checkoutSession.products.map(async (product) => {
// const existingProduct = await getTenantSubscriptionProduct(tenant.id, product.id);
// if (!existingProduct) {
await addTenantSubscriptionProduct({
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: product.id ?? "",
quantity: product.quantity,
stripeSubscriptionId: product.subscription ?? "",
fromCheckoutSessionId: checkoutSession.id,
prices: product.prices.map((price) => {
return {
subscriptionPriceId: price.flatPrice?.id,
subscriptionUsageBasedPriceId: price.usageBasedPrice?.id,
};
}),
});
// } else {
// // is active
// if (!existingProduct.endsAt) {
// await updateTenantSubscriptionProduct(existingProduct.id, {
// quantity: (existingProduct.quantity ?? 1) + 1,
// });
// } else {
// await updateTenantSubscriptionProduct(existingProduct.id, {
// quantity: product.quantity,
// endsAt: null,
// cancelledAt: null,
// });
// }
// }
const subscriptionProduct = await getSubscriptionProduct(product.id);
if (subscriptionProduct) {
function checkUpgradeDowngrade(plan: SubscriptionProductDto) {
const existing = tenantSubscription?.products.find((f) => f)?.subscriptionProduct;
if (existing) {
if (plan.order > existing.order) {
return { upgrade: true };
} else {
return { downgrade: true };
}
}
}
let event: "subscription.subscribed" | "subscription.upgraded" | "subscription.downgraded" = "subscription.subscribed";
if (tenantSubscription.products.length > 0) {
const upgradeDowngrade = checkUpgradeDowngrade(subscriptionProduct);
if (upgradeDowngrade?.upgrade) {
event = "subscription.upgraded";
} else if (upgradeDowngrade?.downgrade) {
event = "subscription.downgraded";
}
}
await EventsService.create({
request,
event,
tenantId: tenant.id,
userId: user.id,
data: {
user: { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: { id: product.id, title: t(subscriptionProduct.title) || subscriptionProduct.title },
session: checkoutSession.id,
},
} satisfies SubscriptionSubscribedDto,
});
await TenantTypesApi.setTenantTypes({ tenantId, subscriptionProduct });
}
})
);
}
}
export async function autosubscribeToTrialOrFreePlan({
request,
t,
tenantId,
userId,
}: {
request: Request;
t: TFunction;
tenantId: string;
userId: string | null;
}) {
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Starting auto-subscribe to trial/free plan");
const tenant = await getTenant(tenantId);
if (!tenant) {
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant not found; skipping");
return;
}
if (!tenant.subscription?.stripeCustomerId) {
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant has no Stripe customer id; skipping");
return;
}
const defaultCurrency = currencies.find((f) => f.default)?.value;
if (!defaultCurrency) {
return;
}
const allProducts = await getAllSubscriptionProducts(true);
const productsFree: SubscriptionPriceDto[] = [];
const productsWithTrialDays: SubscriptionPriceDto[] = [];
pricingLogger.debug(
{ op: "autosubscribeToTrialOrFreePlan.products", tenantId, count: allProducts.length },
"Auto-subscribe candidate products loaded",
);
allProducts.forEach((product) => {
if (product.prices.length === 0) {
return;
}
const allPricesAreZero = product.prices.every((price) => price.currency === defaultCurrency && (price.price === undefined || Number(price.price) === 0));
if (allPricesAreZero) {
productsFree.push(product.prices[0]);
}
const firstPriceWithTrialDays = product.prices.find(
(price) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0)
);
if (firstPriceWithTrialDays) {
productsWithTrialDays.push(firstPriceWithTrialDays);
}
});
try {
if (productsWithTrialDays.length > 0) {
pricingLogger.info(
{
op: "autosubscribeToTrialOrFreePlan",
tenantId: tenant.id,
productCount: productsWithTrialDays.length,
productIds: productsWithTrialDays.map((p) => p.subscriptionProductId),
},
"Autosubscribing tenant to trial/free plan",
);
const price = productsWithTrialDays[0];
const trial_end = Math.floor(Date.now() / 1000) + (price.trialDays || 30) * 24 * 60 * 60;
const stripeSubscription = await createStripeSubscription(tenant.subscription.stripeCustomerId, price.stripeId, trial_end);
await addTenantSubscriptionProduct({
tenantSubscriptionId: tenant.subscription.id,
subscriptionProductId: price.subscriptionProductId,
quantity: 1,
stripeSubscriptionId: stripeSubscription.id,
fromCheckoutSessionId: null,
prices: [
{
subscriptionPriceId: price.id,
},
],
});
const user = userId ? await getUser(userId) : null;
await EventsService.create({
request,
event: "subscription.subscribed",
tenantId: tenant.id,
userId: user?.id ?? null,
data: {
user: !user ? null : { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: {
id: price.subscriptionProductId,
title: t(price.subscriptionProduct?.title ?? "") || price.subscriptionProduct?.title || "",
},
},
} satisfies SubscriptionSubscribedDto,
});
} else if (productsFree.length > 0) {
// TODO: IMPLEMENT
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.free", tenantId, count: productsFree.length },
"Free products available but auto-subscribe-free path not implemented yet",
);
} else {
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.none", tenantId },
"No auto-subscription products/plans found",
);
}
} catch (e: any) {
pricingLogger.error({ err: e, op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed");
}
}
@@ -0,0 +1,99 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MemoryAdapter, createSharedStore } from "@toolctrl/shared-store";
vi.mock("~/utils/cache.server", () => {
const map = new Map<string, unknown>();
return {
cache: map,
cachified: vi.fn(),
clearCacheKey: vi.fn((key: string) => map.delete(key)),
clearCacheKeyPrefix: vi.fn((prefix: string) => {
for (const k of map.keys()) if (k.startsWith(prefix)) map.delete(k);
}),
__test_map: map,
};
});
vi.mock("~/shared-store.server", async () => {
const { MemoryAdapter, createSharedStore } = await import("@toolctrl/shared-store");
const adapter = new MemoryAdapter();
const store = createSharedStore({ namespace: "web-test", adapter });
return {
getSharedStore: () => store,
__setSharedStoreFactoryForTests: vi.fn(),
__resetSharedStoreForTests: vi.fn(),
};
});
import {
getSubscriptionCache,
subscribeSubscriptionCache,
__resetSubscriptionCacheForTests,
} from "./subscriptionCache.server";
import * as cacheServer from "~/utils/cache.server";
beforeEach(() => {
__resetSubscriptionCacheForTests();
// clear shared cache.server map between tests
(cacheServer as unknown as { __test_map: Map<string, unknown> }).__test_map.clear();
vi.mocked(cacheServer.clearCacheKey).mockClear();
vi.mocked(cacheServer.clearCacheKeyPrefix).mockClear();
delete process.env.CACHE_INVALIDATION_ENABLED;
delete process.env.CACHE_L1_TTL_SECONDS;
});
afterEach(() => {
__resetSubscriptionCacheForTests();
});
describe("subscription cache (two-tier)", () => {
it("invalidate(tenantId) publishes + clears L2 and triggers local clearCacheKey via subscriber", async () => {
const cache = getSubscriptionCache();
await subscribeSubscriptionCache();
await cache.invalidate("tenant-1");
// Give the in-process pubsub event loop a tick to flush.
await new Promise((r) => setTimeout(r, 10));
expect(vi.mocked(cacheServer.clearCacheKey)).toHaveBeenCalledWith("tenantSubscription:tenant-1");
});
it("wildcard invalidate clears the cachified prefix", async () => {
const cache = getSubscriptionCache();
await subscribeSubscriptionCache();
await cache.invalidate();
await new Promise((r) => setTimeout(r, 10));
expect(vi.mocked(cacheServer.clearCacheKeyPrefix)).toHaveBeenCalledWith("tenantSubscription:");
});
it("respects CACHE_INVALIDATION_ENABLED=false (subscribe is no-op, no publish)", async () => {
process.env.CACHE_INVALIDATION_ENABLED = "false";
__resetSubscriptionCacheForTests();
const cache = getSubscriptionCache();
const dispose = await subscribeSubscriptionCache();
await cache.invalidate("tenant-2");
await new Promise((r) => setTimeout(r, 10));
// subscriber never wired because pubsub disabled → no clearCacheKey from remote path
expect(vi.mocked(cacheServer.clearCacheKey)).not.toHaveBeenCalled();
await dispose();
});
it("subscribeSubscriptionCache is idempotent (returns same disposer)", async () => {
const a = await subscribeSubscriptionCache();
const b = await subscribeSubscriptionCache();
expect(a).toBe(b);
});
it("uses CACHE_L1_TTL_SECONDS override when present", async () => {
process.env.CACHE_L1_TTL_SECONDS = "120";
__resetSubscriptionCacheForTests();
const cache = getSubscriptionCache();
// Smoke: a set/get round-trip works with overridden TTL.
await cache.set("t1", null);
expect(await cache.get("t1")).toBeNull();
});
});
// Silence the unused createSharedStore import — used only to load the package
// (and force its types) for the mock factory above. vitest's mock factory is
// hoisted so the dynamic import shape is the standard pattern here.
void MemoryAdapter;
void createSharedStore;
@@ -0,0 +1,74 @@
import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store";
import type { TenantSubscriptionWithDetails } from "@toolctrl/db/subscriptions.server";
import { getSharedStore } from "~/shared-store.server";
import { clearCacheKey, clearCacheKeyPrefix } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
/**
* Subscription cache (two-tier). L1 = in-process Map, L2 = SharedStore;
* cross-replica purges via pub/sub on channel
* `shared-store:web:ch:cache:subscription:invalidate`.
*
* Bootstrap (idempotent): call `subscribeSubscriptionCache()` once during
* web boot so this replica listens for invalidation messages emitted by
* the API stripe webhook handler.
*/
const log = createScopedLogger("subscription-cache");
const TTL_SECONDS_DEFAULT = 5 * 60; // 5 minutes — L1 safety-net so a missed pub/sub event self-heals quickly.
let cacheSingleton: TwoTierCache<TenantSubscriptionWithDetails | null> | null = null;
let subscribeDisposer: (() => Promise<void>) | null = null;
function pubsubEnabledFromEnv(): boolean {
const raw = process.env.CACHE_INVALIDATION_ENABLED;
if (raw === undefined || raw === null || raw === "") return true;
return raw.toLowerCase() !== "false" && raw !== "0";
}
function ttlSecondsFromEnv(): number {
const raw = process.env.CACHE_L1_TTL_SECONDS;
if (!raw) return TTL_SECONDS_DEFAULT;
const parsed = Number(raw);
if (!Number.isFinite(parsed) || parsed <= 0) return TTL_SECONDS_DEFAULT;
return Math.floor(parsed);
}
export function getSubscriptionCache(): TwoTierCache<TenantSubscriptionWithDetails | null> {
if (cacheSingleton) return cacheSingleton;
cacheSingleton = createTwoTierCache<TenantSubscriptionWithDetails | null>({
store: getSharedStore(),
namespace: "subscription",
ttlSeconds: ttlSecondsFromEnv(),
pubsubEnabled: pubsubEnabledFromEnv(),
logger: { warn: (obj, msg) => log.warn(obj, msg), error: (obj, msg) => log.error(obj, msg) },
});
return cacheSingleton;
}
/**
* Start the subscriber for this process. Safe to call repeatedly (idempotent).
* Returns the disposer for tests / graceful shutdown.
*/
export async function subscribeSubscriptionCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
const cache = getSubscriptionCache();
// Bridge: on remote invalidation, also purge the in-process cachified
// LRU keyed `tenantSubscription:<tenantId>` so getActiveTenantSubscriptions
// refetches on the next call.
subscribeDisposer = await cache.subscribe((key) => {
if (!key || key === "*") {
clearCacheKeyPrefix("tenantSubscription:");
} else {
clearCacheKey(`tenantSubscription:${key}`);
}
});
log.info({ namespace: "subscription" }, "subscription cache subscriber started");
return subscribeDisposer;
}
/** Test seam: drop the singleton + disposer so each test gets a fresh cache. */
export function __resetSubscriptionCacheForTests(): void {
cacheSingleton = null;
subscribeDisposer = null;
}
@@ -0,0 +1,136 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("../../db.server", () => ({ db: {} }));
vi.mock("../../db/entities/entities.db.server", () => ({ findSimpleEntityByName: vi.fn() }));
vi.mock("../../db/stripe/checkoutSessions.db.server", () => ({ createCheckoutSessionStatus: vi.fn(), getCheckoutSessionStatus: vi.fn() }));
vi.mock("../../db/subscriptionProducts.db.server", () => ({ getAllSubscriptionFeatures: vi.fn() }));
vi.mock("@toolctrl/db/subscriptions.server", () => ({
createTenantSubscriptionUsageRecord: vi.fn(),
listTenantSubscriptionIds: vi.fn(),
updateTenantSubscriptionProduct: vi.fn(),
}));
vi.mock("../../db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: vi.fn(), getTenantSubscriptions: vi.fn() }));
vi.mock("~/modules/emails/services/EmailService", () => ({ sendEmail: vi.fn() }));
vi.mock("../../helpers/ApiKeyHelper", () => ({ apiKeyCreditableStatusCodes: [], apiKeyIgnoreEndpoints: [] }));
vi.mock("../../stripe.server", () => ({
cancelStripeSubscription: vi.fn(),
createUsageRecord: vi.fn(),
getStripeSession: vi.fn(),
getStripeSubscription: vi.fn(),
}));
vi.mock("../../url.server", () => ({ getBaseURL: vi.fn() }));
vi.mock("./pricingService", () => ({ getAcquiredItemsFromCheckoutSession: vi.fn() }));
vi.mock("../../cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn(), clearCacheKeyPrefix: vi.fn() }));
// Stable invalidate spy so tests can assert the cross-replica publish path.
const subscriptionCacheInvalidateMock = vi.fn().mockResolvedValue(undefined);
vi.mock("./subscriptionCache.server", () => ({
getSubscriptionCache: () => ({
invalidate: subscriptionCacheInvalidateMock,
get: vi.fn(),
set: vi.fn(),
subscribe: vi.fn(),
flushLocal: vi.fn(),
deleteLocal: vi.fn(),
}),
}));
vi.mock("~/utils/db/subscriptions/tenantSubscriptionProducts.db.server", () => ({
cancelTenantSubscriptionProduct: vi.fn(),
getTenantSubscriptionProductById: vi.fn(),
}));
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: vi.fn() }));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({ default: {} }));
vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn() }));
import {
cancelTenantSubscription,
clearAllSubscriptionsCache,
clearTenantSubscriptionCache,
} from "./subscriptionService";
import { cancelStripeSubscription } from "../../stripe.server";
import { getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { clearCacheKey } from "../../cache.server";
import { listTenantSubscriptionIds } from "@toolctrl/db/subscriptions.server";
describe("cancelTenantSubscription", () => {
it("returns without logging or calling Stripe when the product is not subscribed", async () => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce({
id: "tenant-sub-product-id",
stripeSubscriptionId: null,
} as Awaited<ReturnType<typeof getTenantSubscriptionProductById>>);
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
await cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" });
expect(consoleLog).not.toHaveBeenCalled();
expect(cancelStripeSubscription).not.toHaveBeenCalled();
consoleLog.mockRestore();
});
});
describe("subscription cache invalidation", () => {
it("clearTenantSubscriptionCache only invalidates the affected tenant key", () => {
const clearCacheKeyMock = vi.mocked(clearCacheKey);
clearCacheKeyMock.mockClear();
clearTenantSubscriptionCache("tenant-a");
expect(clearCacheKeyMock).toHaveBeenCalledTimes(1);
expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-a");
});
it("clearTenantSubscriptionCache does not enumerate other tenants (no global thrash)", () => {
const clearCacheKeyMock = vi.mocked(clearCacheKey);
const listMock = vi.mocked(listTenantSubscriptionIds);
clearCacheKeyMock.mockClear();
listMock.mockClear();
clearTenantSubscriptionCache("tenant-x");
expect(listMock).not.toHaveBeenCalled();
});
it("clearTenantSubscriptionCache publishes a cross-replica invalidation for the tenant", () => {
subscriptionCacheInvalidateMock.mockClear();
clearTenantSubscriptionCache("tenant-b");
// Peer web replicas must drop their L1 too — not just this process.
expect(subscriptionCacheInvalidateMock).toHaveBeenCalledTimes(1);
expect(subscriptionCacheInvalidateMock).toHaveBeenCalledWith("tenant-b");
});
it("clearAllSubscriptionsCache broadcasts a wildcard cross-replica invalidation", async () => {
subscriptionCacheInvalidateMock.mockClear();
vi.mocked(listTenantSubscriptionIds).mockResolvedValueOnce(
[] as Awaited<ReturnType<typeof listTenantSubscriptionIds>>,
);
await clearAllSubscriptionsCache();
// No key argument == wildcard flush across every replica's L1.
expect(subscriptionCacheInvalidateMock).toHaveBeenCalledTimes(1);
expect(subscriptionCacheInvalidateMock).toHaveBeenCalledWith();
});
it("clearAllSubscriptionsCache invalidates every cached tenant subscription", async () => {
const clearCacheKeyMock = vi.mocked(clearCacheKey);
const listMock = vi.mocked(listTenantSubscriptionIds);
clearCacheKeyMock.mockClear();
listMock.mockReset();
listMock.mockResolvedValueOnce([
{ id: "sub-1", tenantId: "tenant-1" },
{ id: "sub-2", tenantId: "tenant-2" },
{ id: "sub-3", tenantId: "tenant-3" },
] as Awaited<ReturnType<typeof listTenantSubscriptionIds>>);
await clearAllSubscriptionsCache();
expect(clearCacheKeyMock).toHaveBeenCalledTimes(3);
expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-1");
expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-2");
expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-3");
});
});
@@ -0,0 +1,618 @@
import { Prisma, SubscriptionPrice } from "@toolctrl/db/prisma-browser";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import currencies from "~/application/pricing/currencies";
import { db } from "../../db.server";
import { findSimpleEntityByName } from "../../db/entities/entities.db.server";
import { createCheckoutSessionStatus, getCheckoutSessionStatus } from "../../db/stripe/checkoutSessions.db.server";
import { getAllSubscriptionFeatures } from "../../db/subscriptionProducts.db.server";
import {
createTenantSubscriptionUsageRecord,
listTenantSubscriptionIds,
updateTenantSubscriptionProduct,
type TenantSubscriptionWithDetails,
} from "@toolctrl/db/subscriptions.server";
import { getTenantSubscription, getTenantSubscriptions } from "../../db/tenantSubscriptions.db.server";
import { sendEmail } from "~/modules/emails/services/EmailService";
import { apiKeyCreditableStatusCodes, apiKeyIgnoreEndpoints } from "../../helpers/ApiKeyHelper";
import { cancelStripeSubscription, getStripeSession, getStripeSubscription } from "../../stripe.server";
import { getBaseURL } from "../../url.server";
import { getAcquiredItemsFromCheckoutSession } from "./pricingService";
import { cachified, clearCacheKey } from "../../cache.server";
import { getSubscriptionCache } from "./subscriptionCache.server";
import DateUtils from "~/utils/shared/DateUtils";
import { TFunction } from "i18next";
import { cancelTenantSubscriptionProduct, getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { SubscriptionCancelledDto } from "~/modules/events/dtos/SubscriptionCancelledDto";
import EventsService from "~/modules/events/services/.server/EventsService";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?: TenantSubscriptionWithDetails | null): Promise<PlanFeatureUsageDto[]> {
let subscription: TenantSubscriptionWithDetails | null = null;
if (tenantSubscription === undefined) {
subscription = await getActiveTenantSubscriptions(tenantId);
} else {
subscription = tenantSubscription;
}
const myUsage: PlanFeatureUsageDto[] = [];
let allFeatures: SubscriptionFeatureDto[] = [];
const features: { name: string; order: number; title: string; type: SubscriptionFeatureLimitType; value: number; accumulate: boolean }[] =
await getAllSubscriptionFeatures();
features
.filter((f) => f.name)
.forEach((feature) => {
const existing = allFeatures.find((f) => f.name === feature.name);
if (!existing) {
allFeatures.push({
order: feature.order,
name: feature.name,
title: feature.title,
type: feature.type,
value: feature.value,
accumulate: feature.accumulate,
});
}
});
allFeatures = allFeatures.sort((a, b) => a.order - b.order);
await Promise.all(
allFeatures.map(async (item) => {
let myFeatures: SubscriptionFeatureDto[] = [];
subscription?.products.forEach((product) => {
const feature = product.subscriptionProduct.features.find((f) => f.name === item.name);
if (feature) {
if (!product.quantity) {
myFeatures.push(feature);
} else {
// per-seat or one-time multiplication
for (let idx = 0; idx < product.quantity; idx++) {
myFeatures.push(feature);
}
}
}
});
const existingSubscriptionFeature = mergeFeatures(myFeatures);
const feature = existingSubscriptionFeature ?? item;
const entity = await findSimpleEntityByName(item.name);
const usage: PlanFeatureUsageDto = {
entity: entity ?? undefined,
order: feature.order,
title: feature.title,
name: feature.name,
type: feature.type,
value: feature.value,
used: 0,
remaining: 0,
enabled: feature.type !== SubscriptionFeatureLimitType.NOT_INCLUDED,
message: "",
};
if (!existingSubscriptionFeature) {
usage.type = SubscriptionFeatureLimitType.NOT_INCLUDED;
usage.enabled = false;
if (subscription?.products && subscription.products.length > 0) {
usage.message = "featureLimits.upgradeSubscription";
} else {
usage.message = "featureLimits.noSubscription";
}
} else {
if (feature.type === SubscriptionFeatureLimitType.NOT_INCLUDED) {
usage.enabled = false;
usage.message = "featureLimits.notIncluded";
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
usage.used = await getUsed(tenantId, feature, subscription);
usage.remaining = usage.value - usage.used;
if (usage.remaining <= 0) {
usage.message = `You've reached the limit (${usage.used}/${usage.value}) for ${entity?.titlePlural ?? feature.name}`;
usage.enabled = false;
}
} else if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
usage.used = await getUsed(tenantId, feature, subscription);
usage.remaining = usage.value - usage.used;
usage.period = getUsedPeriod(subscription);
if (usage.remaining <= 0) {
// var now = new Date();
// const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
usage.message = `You've reached the limit this month (${usage.used}/${usage.value}) for ${entity?.titlePlural ?? feature.name}`;
usage.enabled = false;
}
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
usage.remaining = "unlimited";
}
}
myUsage.push(usage);
})
);
return myUsage.sort((a, b) => a.order - b.order);
}
function mergeFeatures(features: SubscriptionFeatureDto[]) {
if (features.length === 0) {
return undefined;
}
const mergedFeature: SubscriptionFeatureDto = {
order: features[0].order,
title: features[0].title,
name: features[0].name,
type: SubscriptionFeatureLimitType.NOT_INCLUDED,
value: 0,
accumulate: features[0].accumulate,
};
let firstFeature = true;
features.forEach((feature) => {
if (mergedFeature.type < feature.type) {
mergedFeature.type = feature.type;
}
// console.log({ mergedFeature });
if (mergedFeature.accumulate || firstFeature) {
mergedFeature.value += feature.value;
}
firstFeature = false;
});
return mergedFeature;
}
export async function getPlanFeatureUsage(
tenantId: string,
featureName: string,
tenantSubscription?: TenantSubscriptionWithDetails | null
): Promise<PlanFeatureUsageDto | undefined> {
const usage = await getPlanFeaturesUsage(tenantId, tenantSubscription);
return usage.find((f) => f.name === featureName);
}
function getUsedPeriod(subscription: TenantSubscriptionWithDetails | null) {
const date = new Date(),
y = date.getFullYear(),
m = date.getMonth();
let firstDay = new Date(y, m, 1, 0, 0, 1);
let lastDay = new Date(y, m + 1, 0, 23, 59, 59);
// if it's december, last day is january 0
if (m === 11) {
lastDay = new Date(y + 1, 0, 0, 23, 59, 59);
}
subscription?.products.forEach((product) => {
if (product.currentPeriodStart && product.currentPeriodEnd) {
firstDay = product.currentPeriodStart;
lastDay = product.currentPeriodEnd;
}
});
return {
firstDay,
lastDay,
};
}
async function getUsed(tenantId: string, feature: SubscriptionFeatureDto, subscription: TenantSubscriptionWithDetails | null): Promise<number> {
const { firstDay, lastDay } = await getUsedPeriod(subscription);
if (feature.name === DefaultFeatures.Users) {
if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
return await db.tenantUser.count({
where: {
tenantId,
createdAt: {
gte: firstDay,
lt: lastDay,
},
},
});
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
return await db.tenantUser.count({
where: {
tenantId,
},
});
}
} else if (feature.name === DefaultFeatures.API) {
if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
return await db.apiKeyLog.count({
where: {
tenantId,
status: { in: apiKeyCreditableStatusCodes },
endpoint: { notIn: apiKeyIgnoreEndpoints },
createdAt: {
gte: firstDay,
lt: lastDay,
},
},
});
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
return await db.apiKeyLog.count({
where: {
tenantId,
status: { in: apiKeyCreditableStatusCodes },
endpoint: { notIn: apiKeyIgnoreEndpoints },
},
});
}
} else if (feature.name === DefaultFeatures.Credits) {
if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
return await getSpentCredits({
tenantId,
createdAt: {
gte: firstDay,
lt: lastDay,
},
});
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
return await getSpentCredits({ tenantId });
}
} else {
const entity = await findSimpleEntityByName(feature.name);
// if (!entity) {
// // throw new Error("Entity does not exist with plural title: " + feature.name);
// }
if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
const where: Prisma.RowWhereInput = {
tenantId,
entityId: entity?.id ?? "",
createdAt: {
gte: firstDay,
lt: lastDay,
},
};
return db.row.count({
where,
});
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
const count = await db.row.count({
where: {
tenantId,
entityId: entity?.id ?? "",
},
});
return count;
}
}
return 0;
}
async function getSpentCredits(where: Prisma.CreditWhereInput): Promise<number> {
const spent = await db.credit.aggregate({
where: {
...where,
amount: { lt: 0 },
},
_sum: {
amount: true,
},
});
return Math.abs(spent._sum.amount ?? 0);
}
// export async function getPlanFeatureUsage(tenantId: string, featureName: string): Promise<PlanFeatureUsageDto> {
// const myUsage: PlanFeatureUsageDto[] = [];
// let allFeatures: SubscriptionFeatureDto[] = [];
// const features = await getAllSubscriptionFeatures();
// features.forEach((feature) => {
// const existing = allFeatures.find((f) => f.name === feature.name);
// if (!existing) {
// allFeatures.push({
// order: feature.order,
// name: feature.name,
// title: feature.title,
// type: feature.type,
// value: feature.value,
// });
// }
// });
// allFeatures = allFeatures.sort((a, b) => a.order - b.order);
// allFeatures.forEach((feature) => {
// const featureUsage: PlanFeatureUsageDto = {
// order: feature.order,
// title: feature.title,
// name: feature.name,
// type: feature.type,
// value: feature.value,
// used: 0,
// remaining: 0,
// };
// if (feature.type === SubscriptionFeatureLimitType.MAX) {
// featureUsage.used = 2;
// featureUsage.remaining = featureUsage.value - featureUsage.used;
// } else if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
// featureUsage.used = 3;
// featureUsage.remaining = featureUsage.value - featureUsage.used;
// }
// myUsage.push(featureUsage);
// });
// return myUsage;
// }
export async function getActiveTenantSubscriptions(tenantId: string) {
const mySubscription = await cachified({
key: `tenantSubscription:${tenantId}`,
ttl: 1000 * 60 * 60, // 1 hour
getFreshValue: () => getTenantSubscription(tenantId),
});
if (mySubscription) {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.stripeSubscriptionId) {
let currentPeriod =
item.currentPeriodStart && item.currentPeriodEnd
? {
start: DateUtils.getDateStartOfDay(item.currentPeriodStart),
end: DateUtils.getDateEndOfDay(item.currentPeriodEnd),
}
: undefined;
const today = new Date();
let todayIsInCurrentPeriod = false;
if (currentPeriod) {
todayIsInCurrentPeriod = today >= item.currentPeriodStart! && today <= item.currentPeriodEnd!;
}
if (currentPeriod && todayIsInCurrentPeriod) {
item.currentPeriodStart = currentPeriod.start;
item.currentPeriodEnd = currentPeriod.end;
} else {
const stripeSubscription = await getStripeSubscription(item.stripeSubscriptionId);
if (stripeSubscription) {
let startOfDay = new Date((stripeSubscription.items.data[0]?.current_period_start ?? 0) * 1000);
let endOfDay = new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000);
item.currentPeriodStart = DateUtils.getDateStartOfDay(startOfDay);
item.currentPeriodEnd = DateUtils.getDateEndOfDay(endOfDay);
}
const updatedItem = await updateTenantSubscriptionProduct({ id: item.id, tenantId: mySubscription.tenantId }, {
currentPeriodStart: item.currentPeriodStart,
currentPeriodEnd: item.currentPeriodEnd,
});
// Cross-replica purge: the Stripe billing-period sync mutates the
// subscription, so peer web replicas must drop their L1 too —
// a bare clearCacheKey would only purge this process.
clearTenantSubscriptionCache(updatedItem.tenantSubscription.tenantId);
}
}
})
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
mySubscription.products = mySubscription.products.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
}
return mySubscription;
}
export async function getActiveTenantsSubscriptions() {
const subscriptions = await getTenantSubscriptions();
return await Promise.all(
subscriptions.map(async (mySubscription) => {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.stripeSubscriptionId) {
const stripeSubscription = await getStripeSubscription(item.stripeSubscriptionId);
if (stripeSubscription) {
item.currentPeriodStart = new Date((stripeSubscription.items.data[0]?.current_period_start ?? 0) * 1000);
item.currentPeriodEnd = new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000);
}
}
})
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
return mySubscription;
})
);
}
export async function reportUsage(tenantId: string, unit: string) {
const tenantSubscription = await getActiveTenantSubscriptions(tenantId);
if (!tenantSubscription) {
return;
}
await Promise.all(
tenantSubscription.products.map(async (product) => {
return await Promise.all(
product.prices.map(async (price) => {
if (!product.stripeSubscriptionId) {
return;
}
if (price.subscriptionUsageBasedPrice?.unit === unit) {
const stripeSubscription = await getStripeSubscription(product.stripeSubscriptionId);
const subscriptionItem = stripeSubscription?.items.data.find((f) => f.price.id === price.subscriptionUsageBasedPrice?.stripeId);
if (subscriptionItem) {
// Stripe submission is handled by the meter-based reporter in
// `apps/worker/src/jobs/ai-cost-stripe-report.ts`; this path only
// keeps local bookkeeping for tenant-facing usage history.
await createTenantSubscriptionUsageRecord({
tenantSubscriptionProductPriceId: price.id,
timestamp: Math.floor(Date.now() / 1000),
quantity: 1,
stripeSubscriptionItemId: subscriptionItem.id,
});
}
}
})
);
})
);
}
export async function persistCheckoutSessionStatus({
request,
id,
fromUrl,
fromUserId,
fromTenantId,
}: {
request: Request;
id: string;
fromUrl: string;
fromUserId?: string | null;
fromTenantId?: string | null;
}) {
const existingCheckoutSession = await getCheckoutSessionStatus(id);
if (!existingCheckoutSession) {
const stripeCheckoutSession = await getStripeSession(id);
if (stripeCheckoutSession) {
const session = await createCheckoutSessionStatus({
id: stripeCheckoutSession.id,
email: stripeCheckoutSession.customer_details?.email ?? "",
fromUrl,
fromUserId,
fromTenantId,
});
if (!session.fromUserId && !session.fromTenantId) {
const sessionResponse = await getAcquiredItemsFromCheckoutSession(session.id);
if (sessionResponse && sessionResponse.products.length > 0) {
const mailTranslator = await getMailTranslatorFromRequest(request);
await sendEmail({
request,
to: session.email,
alias: "account-setup",
...EmailTemplates.ACCOUNT_SETUP_EMAIL.parse({
appConfiguration: await getAppConfiguration({ request }),
data: {
email: session.email,
plan: sessionResponse.products[0].title,
action_url: `${getBaseURL(request)}/pricing/${session.id}/success`,
},
t: mailTranslator.t,
locale: mailTranslator.locale,
}),
});
}
}
}
}
}
export async function getMrr(currency: string) {
const activeSubscriptions = await getActiveTenantsSubscriptions();
let summary: { total: number; count: number } = {
total: 0,
count: 0,
};
activeSubscriptions.forEach((s) => {
s.products.forEach((p) => {
summary.count++;
p.prices.forEach((f) => {
summary.total += getPriceInCurrency(f.subscriptionPrice, currency);
});
});
});
return summary;
}
function getPriceInCurrency(subscriptionPrice: SubscriptionPrice | null, currency: string) {
if (!subscriptionPrice) {
return 0;
}
let total = 0;
if (subscriptionPrice.billingPeriod === SubscriptionBillingPeriod.MONTHLY) {
total = Number(subscriptionPrice.price);
} else if (subscriptionPrice.billingPeriod === SubscriptionBillingPeriod.YEARLY) {
total = Number(subscriptionPrice.price) / 12;
} else if (subscriptionPrice.billingPeriod === SubscriptionBillingPeriod.WEEKLY) {
total = Number(subscriptionPrice.price) * 4;
} else if (subscriptionPrice.billingPeriod === SubscriptionBillingPeriod.DAILY) {
total = Number(subscriptionPrice.price) * 30;
}
if (currency !== subscriptionPrice.currency) {
total = convertToCurrency({ from: subscriptionPrice.currency, to: currency, price: total });
}
return total;
}
export function convertToCurrency({ from, price, to }: { from: string; price: number; to: string }): number {
const fromCurrency = currencies.find((f) => f.value === from);
const toCurrency = currencies.find((f) => f.value === to);
if (!fromCurrency || !toCurrency) {
return 0;
}
const fromParity = fromCurrency.parities?.find((f) => f.from === to);
const toParity = toCurrency.parities?.find((f) => f.from === from);
if (fromParity && fromParity.parity !== 0) {
return price / fromParity.parity;
} else if (toParity && toParity.parity !== 0) {
return price / toParity.parity;
}
return 0;
}
/**
* Invalidate the cached subscription for a single tenant. Prefer this over
* `clearAllSubscriptionsCache` whenever the change is tenant-scoped (e.g.
* Stripe webhooks) so we don't thrash every other tenant's cache entry.
*
* Publishes a cross-replica invalidation on the `cache:subscription:invalidate`
* channel via the two-tier cache so peer web replicas drop their L1 too.
* The publish is fire-and-forget — failures are logged but never thrown.
*/
export function clearTenantSubscriptionCache(tenantId: string) {
clearCacheKey(`tenantSubscription:${tenantId}`);
// Best-effort fan-out to peer replicas; never blocks the caller.
void getSubscriptionCache()
.invalidate(tenantId)
.catch(() => {
/* errors are logged inside the helper via its logger */
});
}
/**
* Invalidate every cached tenant subscription. Use only for global changes
* (plan/feature CRUD, bulk migrations). Also broadcasts a wildcard
* invalidation on the subscription pub/sub channel so peer replicas flush
* their L1 in one shot rather than per-tenant.
*/
export async function clearAllSubscriptionsCache() {
const tenantSubs = await listTenantSubscriptionIds();
tenantSubs.forEach((tenantSub) => {
clearCacheKey(`tenantSubscription:${tenantSub.tenantId}`);
});
// Wildcard fan-out — peer replicas flush their L1 entirely.
await getSubscriptionCache().invalidate().catch(() => {
/* logged inside helper */
});
}
export async function cancelTenantSubscription(
tenantSubscriptionProductId: string,
{ tenantId, userId, t }: { tenantId: string; userId: string; t?: TFunction }
) {
const tenantSubscriptionProduct = await getTenantSubscriptionProductById({ id: tenantSubscriptionProductId, tenantId });
if (!tenantSubscriptionProduct) {
throw new Error("Subscription product not found");
}
if (!tenantSubscriptionProduct.stripeSubscriptionId) {
return;
}
const user = userId ? await getUser(userId) : null;
const tenant = await getTenant(tenantId);
if (user && tenant) {
await EventsService.create({
event: "subscription.cancelled",
tenantId: tenant.id,
userId: user.id,
data: {
user: { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name },
subscription: {
product: {
id: tenantSubscriptionProduct.subscriptionProductId,
title: t ? t(tenantSubscriptionProduct.subscriptionProduct.title) : tenantSubscriptionProduct.subscriptionProduct.title,
},
},
} satisfies SubscriptionCancelledDto,
});
}
await cancelStripeSubscription(tenantSubscriptionProduct?.stripeSubscriptionId);
const stripeSubscription = await getStripeSubscription(tenantSubscriptionProduct.stripeSubscriptionId);
await cancelTenantSubscriptionProduct(tenantSubscriptionProduct.id, tenantId, {
cancelledAt: new Date(),
endsAt: stripeSubscription?.items.data[0]?.current_period_end ? new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000) : new Date(),
});
}
@@ -0,0 +1,93 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
vi.mock("@toolctrl/db/subscriptions.server", () => ({
getTenantSubscription: vi.fn(),
}));
vi.mock("@toolctrl/queue", () => ({
setTenantPlanLookup: vi.fn(),
}));
vi.mock("./subscriptionCache.server", () => ({
getSubscriptionCache: vi.fn(),
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
}),
}));
import { getTenantSubscription } from "@toolctrl/db/subscriptions.server";
import { setTenantPlanLookup } from "@toolctrl/queue";
import { getSubscriptionCache } from "./subscriptionCache.server";
import {
__resetTenantPlanLookupForTests,
getCachedTenantPlan,
setSubscriptionToPlanTier,
wireTenantPlanLookup,
} from "./tenantPlanLookup.server";
const getTenantSubscriptionMock = vi.mocked(getTenantSubscription);
const setTenantPlanLookupMock = vi.mocked(setTenantPlanLookup);
const getSubscriptionCacheMock = vi.mocked(getSubscriptionCache);
const cacheGet = vi.fn<[string], Promise<unknown>>();
const cacheSet = vi.fn<[string, unknown], Promise<void>>();
describe("tenant plan lookup", () => {
beforeEach(() => {
getTenantSubscriptionMock.mockReset();
cacheGet.mockReset();
cacheSet.mockReset().mockResolvedValue(undefined);
setTenantPlanLookupMock.mockReset();
getSubscriptionCacheMock.mockReset().mockReturnValue({ get: cacheGet, set: cacheSet } as any);
__resetTenantPlanLookupForTests();
});
afterEach(() => {
__resetTenantPlanLookupForTests();
});
test("returns null when no classifier is registered", async () => {
cacheGet.mockResolvedValue({ id: "sub_1" });
await expect(getCachedTenantPlan("tenant_1")).resolves.toBeNull();
// Cache hit — DB never queried
expect(getTenantSubscriptionMock).not.toHaveBeenCalled();
});
test("fetches subscription from DB on cache miss and primes L2", async () => {
cacheGet.mockResolvedValue(null);
getTenantSubscriptionMock.mockResolvedValue({ id: "sub_1" });
setSubscriptionToPlanTier((sub) => (sub ? "pro" : null));
await expect(getCachedTenantPlan("tenant_1")).resolves.toBe("pro");
expect(getTenantSubscriptionMock).toHaveBeenCalledWith("tenant_1");
expect(cacheSet).toHaveBeenCalledWith("tenant_1", { id: "sub_1" });
});
test("returns null and logs when DB fetch fails", async () => {
cacheGet.mockResolvedValue(null);
getTenantSubscriptionMock.mockRejectedValue(new Error("db down"));
setSubscriptionToPlanTier(() => "enterprise");
await expect(getCachedTenantPlan("tenant_2")).resolves.toBeNull();
});
test("classifier maps subscription to a plan tier", async () => {
cacheGet.mockResolvedValue({ tier: "enterprise" });
setSubscriptionToPlanTier((sub) => {
const tier = (sub as { tier?: string } | null)?.tier;
return tier === "enterprise" ? "enterprise" : tier === "pro" ? "pro" : "free";
});
await expect(getCachedTenantPlan("tenant_ent")).resolves.toBe("enterprise");
});
test("wireTenantPlanLookup registers exactly once", () => {
setTenantPlanLookupMock.mockClear();
wireTenantPlanLookup();
wireTenantPlanLookup();
expect(setTenantPlanLookupMock).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,87 @@
/**
* Tenant plan lookup wiring for BullMQ priority resolution.
*
* The queue package's `resolveJobPriorityForTenant` accepts a pluggable
* `TenantPlanLookup`. This module registers one that reads from the
* subscription cache (two-tier, L1 in-process + L2 SharedStore) so each
* enqueue is a cheap synchronous-ish lookup instead of a DB hit.
*
* Plan-tier mapping is intentionally pluggable: the boilerplate has no
* hard-coded `enterprise|pro|free` field on tenants. Operators wire their
* own classifier via `setSubscriptionToPlanTier`. Until that is set, this
* lookup returns `null` for every tenant, which the resolver then maps to
* NORMAL. Internal jobs (`tenantId: null`) still get CRITICAL.
*
* Bootstrap:
* ```ts
* import { wireTenantPlanLookup } from "~/utils/services/.server/tenantPlanLookup.server";
* wireTenantPlanLookup();
* ```
* Call once during web boot — idempotent.
*/
import type { TenantPlanIdentifier } from "@toolctrl/queue";
import { setTenantPlanLookup } from "@toolctrl/queue";
import type { TenantSubscriptionWithDetails } from "@toolctrl/db/subscriptions.server";
import { getTenantSubscription } from "@toolctrl/db/subscriptions.server";
import { getSubscriptionCache } from "./subscriptionCache.server";
import { createScopedLogger } from "~/utils/logger.server";
const log = createScopedLogger("tenant-plan-lookup");
export type SubscriptionPlanClassifier = (
subscription: TenantSubscriptionWithDetails | null,
) => TenantPlanIdentifier | null;
let classifier: SubscriptionPlanClassifier = () => null;
let wired = false;
/**
* Replace the active classifier. Operators wire their own mapping
* (e.g. by stripe product id → "enterprise"|"pro"|"free"). Passing the
* default no-op classifier disables plan-based priority and falls back
* to NORMAL for all tenants.
*/
export function setSubscriptionToPlanTier(next: SubscriptionPlanClassifier): void {
classifier = next;
}
/**
* Cached lookup used by both the queue resolver and any caller that wants
* a cheap plan tier for the given tenant.
*/
export async function getCachedTenantPlan(tenantId: string): Promise<TenantPlanIdentifier | null> {
const cache = getSubscriptionCache();
let cached = await cache.get(tenantId);
if (cached === null) {
try {
const fresh = await getTenantSubscription(tenantId);
await cache.set(tenantId, fresh ?? null);
cached = fresh ?? null;
} catch (error) {
log.warn(
{ tenantId, error: error instanceof Error ? error.message : String(error) },
"getCachedTenantPlan: subscription fetch failed; returning null",
);
return null;
}
}
return classifier(cached);
}
/**
* Register the lookup on the queue package. Idempotent — calling twice is
* a no-op so per-request bootstraps don't churn the registration.
*/
export function wireTenantPlanLookup(): void {
if (wired) return;
wired = true;
setTenantPlanLookup((tenantId) => getCachedTenantPlan(tenantId));
log.info({}, "tenant plan lookup wired into queue priority resolver");
}
/** Test seam — drop the wiring + classifier. */
export function __resetTenantPlanLookupForTests(): void {
classifier = () => null;
wired = false;
setTenantPlanLookup(null);
}
@@ -0,0 +1,188 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Params } from "react-router";
vi.mock("../../db.server", () => ({
db: {
tenant: {
findFirst: vi.fn(),
},
},
}));
vi.mock("../../cache.server", () => ({
cachified: vi.fn(),
clearCacheKey: vi.fn(),
}));
import { cachified } from "../../cache.server";
import { db } from "../../db.server";
import { getTenantIdFromUrl, getTenantIdOrNull, resolveTenantLookupSource } from "./urlService";
const env = {
APP_BASE_DOMAIN: "localhost:3000",
WEB_APP_HOST: "app.localhost:3000",
ADMIN_APP_HOST: "admin.localhost:3000",
API_HOST: "api.localhost:3000",
APP_PROTOCOL: "http",
};
function makeRequest(host: string, pathname = "/app/acme") {
return new Request(`http://localhost:3000${pathname}`, {
headers: {
host,
},
});
}
async function expectRedirectToApp(promise: Promise<unknown>) {
try {
await promise;
throw new Error("Expected redirect to /app");
} catch (error) {
expect(error).toBeInstanceOf(Response);
expect((error as Response).status).toBe(302);
expect((error as Response).headers.get("Location")).toBe("http://app.localhost:3000/");
}
}
describe("resolveTenantLookupSource", () => {
beforeEach(() => {
vi.stubEnv("APP_BASE_DOMAIN", env.APP_BASE_DOMAIN);
vi.stubEnv("WEB_APP_HOST", env.WEB_APP_HOST);
vi.stubEnv("ADMIN_APP_HOST", env.ADMIN_APP_HOST);
vi.stubEnv("API_HOST", env.API_HOST);
vi.stubEnv("APP_PROTOCOL", env.APP_PROTOCOL);
});
it("uses explicit params when no request exists to keep route-loader behavior stable", () => {
expect(resolveTenantLookupSource({ params: { tenant: "acme" } })).toEqual({ source: "app-route-param", tenant: "acme" });
expect(resolveTenantLookupSource({ params: {} })).toEqual({ source: "none", tenant: null });
});
it("allows tenant lookup only for app-host requests with params or legacy app paths", () => {
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/acme/dashboard"), params: { tenant: "acme" } })).toEqual({
source: "app-route-param",
tenant: "acme",
});
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/app/acme/dashboard"), params: {} })).toEqual({
source: "app-route-param",
tenant: "acme",
});
});
it.each([
["admin", env.ADMIN_APP_HOST],
["api", env.API_HOST],
["root", env.APP_BASE_DOMAIN],
["unknown", "unknown.localhost:3000"],
])("does not infer tenant context for %s-host /app paths", (_label, host) => {
expect(resolveTenantLookupSource({ request: makeRequest(host, "/app/acme/dashboard"), params: { tenant: "acme" } })).toEqual({
source: "none",
tenant: null,
});
});
it("keeps public app-host routes out of tenant resolution", () => {
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/app"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/login"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/reset?token=abc"), params: {} })).toEqual({ source: "none", tenant: null });
});
it("does not self-redirect when the app host is also the base domain", () => {
vi.stubEnv("APP_BASE_DOMAIN", "boiler.saas-ctrl.com");
vi.stubEnv("WEB_APP_HOST", "boiler.saas-ctrl.com");
vi.stubEnv("ADMIN_APP_HOST", "admin.boiler.saas-ctrl.com");
vi.stubEnv("API_HOST", "api.boiler.saas-ctrl.com");
vi.stubEnv("APP_PROTOCOL", "https");
expect(resolveTenantLookupSource({ request: makeRequest("boiler.saas-ctrl.com", "/"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest("boiler.saas-ctrl.com", "/app"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest("boiler.saas-ctrl.com", "/login"), params: {} })).toEqual({ source: "none", tenant: null });
});
});
describe("getTenantIdOrNull", () => {
beforeEach(() => {
vi.stubEnv("APP_BASE_DOMAIN", env.APP_BASE_DOMAIN);
vi.stubEnv("WEB_APP_HOST", env.WEB_APP_HOST);
vi.stubEnv("ADMIN_APP_HOST", env.ADMIN_APP_HOST);
vi.stubEnv("API_HOST", env.API_HOST);
vi.stubEnv("APP_PROTOCOL", env.APP_PROTOCOL);
vi.clearAllMocks();
});
it.each([
["admin", env.ADMIN_APP_HOST],
["api", env.API_HOST],
["root", env.APP_BASE_DOMAIN],
["unknown", "unknown.localhost:3000"],
])("returns null without DB lookup for %s-host /app paths", async (_label, host) => {
await expect(getTenantIdOrNull({ request: makeRequest(host, "/app/acme/dashboard"), params: { tenant: "acme" } })).resolves.toBeNull();
expect(db.tenant.findFirst).not.toHaveBeenCalled();
});
it("allows admin-host routes to opt into tenant scope through tenantId query parameters", async () => {
vi.mocked(db.tenant.findFirst).mockResolvedValueOnce({ id: "tenant_1" });
await expect(getTenantIdOrNull({ request: makeRequest(env.ADMIN_APP_HOST, "/forms?tenantId=acme"), params: {} })).resolves.toBe("tenant_1");
expect(db.tenant.findFirst).toHaveBeenCalledWith({
where: { OR: [{ slug: "acme" }, { id: "acme" }] },
select: { id: true },
});
});
it("keeps admin-host routes global when tenantId query parameters are absent", async () => {
await expect(getTenantIdOrNull({ request: makeRequest(env.ADMIN_APP_HOST, "/forms"), params: {} })).resolves.toBeNull();
expect(db.tenant.findFirst).not.toHaveBeenCalled();
});
it("looks up exactly one tenant-bearing app-host request and returns its id", async () => {
vi.mocked(db.tenant.findFirst).mockResolvedValueOnce({ id: "tenant_1" });
await expect(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/acme/dashboard"), params: { tenant: "acme" } })).resolves.toBe("tenant_1");
expect(db.tenant.findFirst).toHaveBeenCalledTimes(1);
expect(db.tenant.findFirst).toHaveBeenCalledWith({
where: { OR: [{ slug: "acme" }, { id: "acme" }] },
select: { id: true },
});
});
it("returns null for public app-host routes without DB lookup", async () => {
await expect(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/"), params: {} })).resolves.toBeNull();
await expect(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/app"), params: {} })).resolves.toBeNull();
await expect(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/login"), params: {} })).resolves.toBeNull();
expect(db.tenant.findFirst).not.toHaveBeenCalled();
});
it("redirects app-host requests with unknown tenants to /app", async () => {
vi.mocked(db.tenant.findFirst).mockResolvedValueOnce(null);
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
await expectRedirectToApp(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/acme/dashboard"), params: { tenant: "acme" } }));
expect(db.tenant.findFirst).toHaveBeenCalledTimes(1);
consoleLog.mockRestore();
});
});
describe("getTenantIdFromUrl", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(cachified).mockImplementation((async ({ getFreshValue }: { getFreshValue: (context?: unknown) => unknown }) => getFreshValue()) as typeof cachified);
});
it("keeps explicit tenant param lookup behavior stable", async () => {
vi.mocked(db.tenant.findFirst).mockResolvedValueOnce({ id: "tenant_1" });
await expect(getTenantIdFromUrl({ tenant: "acme" } as Params)).resolves.toBe("tenant_1");
expect(db.tenant.findFirst).toHaveBeenCalledWith({
where: { OR: [{ slug: "acme" }, { id: "acme" }] },
select: { id: true },
});
});
});
@@ -0,0 +1,133 @@
import { redirect } from "react-router";
import { db } from "../../db.server";
import { Params } from "react-router";
import UrlUtils from "../../app/UrlUtils";
import { getHostRoutingContextFromRequest } from "../../app/HostRouting.server";
import { isWebRoutePath } from "../../app/PublicRouteSegments";
import { cachified, clearCacheKey } from "../../cache.server";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
export type TenantResolverSource = "app-route-param" | "admin-query-param" | "none" | "invalid-app-route";
export type TenantResolverResult =
| { source: "app-route-param"; tenant: string }
| { source: "admin-query-param"; tenant: string }
| { source: "none"; tenant: null }
| { source: "invalid-app-route"; tenant: null };
export function resolveTenantLookupSource({ request, params }: { request?: Request; params: Params }): TenantResolverResult {
if (!request) {
return getTenantResolverResultFromParams(params);
}
const context = getHostRoutingContextFromRequest(request);
if (context === "admin") {
const tenant = normalizeTenantParam(new URL(request.url).searchParams.get("tenantId"));
return tenant ? { source: "admin-query-param", tenant } : { source: "none", tenant: null };
}
if (context !== "app") {
return { source: "none", tenant: null };
}
return getTenantResolverResultForAppRequest(request, params);
}
export async function getTenantIdFromUrl(params: Params) {
const { tenant } = params;
const normalizedTenant = typeof tenant === "string" ? tenant.trim() : "";
if (!normalizedTenant) {
// eslint-disable-next-line no-console
console.log("[urlService] getTenantIdFromUrl(): Redirecting to app root");
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
let tenantFromParams = await cachified({
key: `tenantIdOrSlug:${normalizedTenant}`,
ttl: 1000 * 60 * 60 * 24,
getFreshValue: () => getTenantByIdOrSlug(normalizedTenant),
});
if (!tenantFromParams) {
tenantFromParams = await getTenantByIdOrSlug(normalizedTenant);
if (tenantFromParams) {
clearCacheKey(`tenant:${normalizedTenant}`);
clearCacheKey(`tenant:${tenantFromParams}`);
clearCacheKey(`tenantIdOrSlug:${normalizedTenant}`);
clearCacheKey(`tenantIdOrSlug:${tenantFromParams}`);
clearCacheKey(`tenantSimple:${tenantFromParams}`);
}
}
if (!tenantFromParams) {
// eslint-disable-next-line no-console
console.log("[urlService] getTenantIdFromUrl(): Redirecting to app root");
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
return tenantFromParams;
}
export async function getTenantIdOrNull({ request, params }: { request: Request; params: Params }) {
const resolverResult = resolveTenantLookupSource({ request, params });
if (resolverResult.source === "none") {
return null;
}
if (resolverResult.source === "invalid-app-route") {
// eslint-disable-next-line no-console
console.log("[urlService] getTenantIdOrNull(): Redirecting to app root");
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
const tenantFromParams = await getTenantByIdOrSlug(resolverResult.tenant);
if (!tenantFromParams) {
// eslint-disable-next-line no-console
console.log("[urlService] getTenantIdOrNull(): Redirecting to app root");
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
return tenantFromParams;
}
export async function getTenantByIdOrSlug(tenant: string | undefined) {
return (
(
await db.tenant.findFirst({
where: { OR: [{ slug: tenant }, { id: tenant }] },
select: { id: true },
})
)?.id ?? ""
);
}
function getTenantResolverResultFromParams(params: Params): TenantResolverResult {
const tenant = normalizeTenantParam(params.tenant);
return tenant ? { source: "app-route-param", tenant } : { source: "none", tenant: null };
}
function getTenantResolverResultForAppRequest(request: Request, params: Params): TenantResolverResult {
const pathname = new URL(request.url).pathname;
if (pathname === "/" || pathname === "/app" || isWebRoutePath(pathname)) {
return { source: "none", tenant: null };
}
const tenant = normalizeTenantParam(params.tenant) ?? getLegacyAppTenantFromPathname(pathname);
if (tenant) {
return { source: "app-route-param", tenant };
}
return { source: "invalid-app-route", tenant: null };
}
function getLegacyAppTenantFromPathname(pathname: string) {
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
const strippedPathname = UrlUtils.stripTrailingSlash(normalizedPathname);
if (strippedPathname === "/app") {
return null;
}
return normalizedPathname.match(/^\/app\/([^/]+)/)?.[1] ?? null;
}
function normalizeTenantParam(tenant: Params["tenant"] | null) {
return typeof tenant === "string" && tenant.trim() ? tenant : null;
}
@@ -0,0 +1,109 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getAdminActiveUserKpiCounts, getAdminTenantKpiCounts } from "@toolctrl/db/kpi.server";
import { StatChange } from "~/application/dtos/stats/StatChange";
import { getAdminDashboardStats } from "./adminDashboardService";
import { getMrr } from "./.server/subscriptionService";
vi.mock("@toolctrl/db/kpi.server", () => ({
getAdminActiveUserKpiCounts: vi.fn(),
getAdminTenantKpiCounts: vi.fn(),
}));
vi.mock("./.server/subscriptionService", () => ({
getMrr: vi.fn(),
}));
const translations: Record<string, string> = {
"admin.kpi.accounts.name": "Translated accounts",
"admin.kpi.accounts.hint": "Translated total accounts",
"admin.kpi.mrr.name": "Translated MRR",
"admin.kpi.mrr.hint": "Translated monthly revenue",
"admin.kpi.mrr.previousStat": "{{0}} translated accounts",
"admin.kpi.activeUsers.name": "Translated MAU",
"admin.kpi.activeUsers.hint": "Translated monthly active users",
};
function t(key: string) {
return translations[key] ?? key;
}
describe("getAdminDashboardStats", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getMrr).mockResolvedValue({ total: 1234.5, count: 7 });
});
it("builds translated KPI stats from package counts and forwards the selected period", async () => {
const gte = new Date("2026-01-01T00:00:00.000Z");
vi.mocked(getAdminTenantKpiCounts).mockResolvedValue({ added: 3, total: 10 });
vi.mocked(getAdminActiveUserKpiCounts).mockResolvedValue({ added: 2, total: 8 });
const stats = await getAdminDashboardStats({ t, gte });
expect(getAdminTenantKpiCounts).toHaveBeenCalledTimes(1);
expect(getAdminTenantKpiCounts).toHaveBeenCalledWith({ gte });
expect(getAdminActiveUserKpiCounts).toHaveBeenCalledTimes(1);
expect(getAdminActiveUserKpiCounts).toHaveBeenCalledWith({ gte });
expect(getMrr).toHaveBeenCalledTimes(1);
expect(getMrr).toHaveBeenCalledWith("usd");
expect(stats).toEqual([
{
name: "Translated accounts",
hint: "Translated total accounts",
stat: "10",
previousStat: "7",
change: "+3",
changeType: StatChange.Increase,
path: "/accounts",
},
{
name: "Translated MRR",
hint: "Translated monthly revenue",
stat: "$1,234.50",
previousStat: "7 translated accounts",
},
{
name: "Translated MAU",
hint: "Translated monthly active users",
stat: "8",
previousStat: "6",
change: "+2",
changeType: StatChange.Increase,
},
]);
});
it("keeps zero additions visible with equal change type and missing translations as key text", async () => {
vi.mocked(getAdminTenantKpiCounts).mockResolvedValue({ added: 0, total: 5 });
vi.mocked(getAdminActiveUserKpiCounts).mockResolvedValue({ added: 0, total: 0 });
vi.mocked(getMrr).mockResolvedValue({ total: 0, count: 0 });
const stats = await getAdminDashboardStats({ t: (key) => key });
expect(getAdminTenantKpiCounts).toHaveBeenCalledWith({ gte: undefined });
expect(getAdminActiveUserKpiCounts).toHaveBeenCalledWith({ gte: undefined });
expect(stats[0]).toMatchObject({
name: "admin.kpi.accounts.name",
hint: "admin.kpi.accounts.hint",
stat: "5",
previousStat: "5",
change: "+0",
changeType: StatChange.Equal,
path: "/accounts",
});
expect(stats[1]).toMatchObject({
name: "admin.kpi.mrr.name",
hint: "admin.kpi.mrr.hint",
stat: "$0.00",
previousStat: "admin.kpi.mrr.previousStat",
});
expect(stats[2]).toMatchObject({
name: "admin.kpi.activeUsers.name",
hint: "admin.kpi.activeUsers.hint",
stat: "0",
previousStat: "0",
change: "+0",
changeType: StatChange.Increase,
});
});
});
@@ -0,0 +1,62 @@
import { getAdminActiveUserKpiCounts, getAdminTenantKpiCounts } from "@toolctrl/db/kpi.server";
import { Stat } from "~/application/dtos/stats/Stat";
import currencies from "~/application/pricing/currencies";
import { getStatChangeType } from "../app/DashboardUtils";
import NumberUtils from "../shared/NumberUtils";
import { getMrr } from "./.server/subscriptionService";
import { promiseHash } from "../promises/promiseHash";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
type AdminDashboardStatsOptions = {
t: (key: string) => string;
gte?: Date;
};
export async function getAdminDashboardStats({ t, gte }: AdminDashboardStatsOptions): Promise<Stat[]> {
const { tenantStat, mrrStat, activeUsersStat } = await promiseHash({
tenantStat: getTenantStat({ t, gte }),
mrrStat: getMMRStat(t),
activeUsersStat: getActiveUsersStat({ t, gte }),
});
return [tenantStat, mrrStat, activeUsersStat];
}
async function getTenantStat({ t, gte }: AdminDashboardStatsOptions) {
const { added, total } = await getAdminTenantKpiCounts({ gte });
const tenantStat: Stat = {
name: t("admin.kpi.accounts.name"),
hint: t("admin.kpi.accounts.hint"),
stat: total.toString(),
previousStat: (total - added).toString(),
change: "+" + added.toString(),
changeType: getStatChangeType(added, total),
path: adminPath("accounts", { mode: "host-aware" }),
};
return tenantStat;
}
async function getMMRStat(t: AdminDashboardStatsOptions["t"]) {
const defaultCurrency = currencies.find((f) => f.default);
const currency = defaultCurrency ?? { value: "usd", symbol: "$" };
const mrr = await getMrr(currency.value);
const tenantStat: Stat = {
name: t("admin.kpi.mrr.name"),
hint: t("admin.kpi.mrr.hint"),
stat: currency.symbol + NumberUtils.decimalFormat(mrr.total),
previousStat: t("admin.kpi.mrr.previousStat").replace("{{0}}", NumberUtils.intFormat(mrr.count)),
};
return tenantStat;
}
async function getActiveUsersStat({ t, gte }: AdminDashboardStatsOptions) {
const { added, total } = await getAdminActiveUserKpiCounts({ gte });
const activeUsersStat: Stat = {
name: t("admin.kpi.activeUsers.name"),
hint: t("admin.kpi.activeUsers.hint"),
stat: total.toString(),
previousStat: (total - added).toString(),
change: "+" + added.toString(),
changeType: getStatChangeType(added, total),
};
return activeUsersStat;
}
@@ -0,0 +1,51 @@
import { Entity } from "@toolctrl/db/prisma-browser";
import { Stat } from "~/application/dtos/stats/Stat";
import { getStatChangeType } from "../app/DashboardUtils";
import { db } from "../db.server";
import { getAllEntities } from "../db/entities/entities.db.server";
import DateUtils from "../shared/DateUtils";
export async function getCustomEntitiesDashboardStats(lastDays: number): Promise<Stat[]> {
const entities = await getAllEntities({ tenantId: null });
const stats = entities.map(async (entity) => {
return await getEntityStat(entity, lastDays);
});
return await Promise.all(stats);
}
async function getEntityStat(entity: Entity, lastDays: number) {
const { added, total } = await getEntityCreatedSince(entity.id, lastDays);
const tenantStat: Stat = {
name: entity.titlePlural,
hint: "",
stat: added.toString(),
previousStat: (total - added).toString(),
change: "+" + added.toString(),
changeType: getStatChangeType(added, total),
};
return tenantStat;
}
async function getEntityCreatedSince(entityId: string, lastDays: number) {
const from = DateUtils.daysFromDate(new Date(), lastDays * -1);
const [added, total] = await Promise.all([
db.row.count({
where: {
entityId,
createdAt: {
gte: from,
},
},
}),
db.row.count({
where: {
entityId,
},
}),
]);
return {
added,
total,
};
}
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import { parseAdminSettingsForm, redactSettingsAuditDetails } from "./adminSettingsValidation.server";
const sensitiveHeadScript = `<script>window.token="secret-token";fetch("https://tracker.example/pixel?apiKey=raw-key")</script>`;
function createForm(values: Record<string, string | boolean | undefined>) {
const form = new FormData();
Object.entries(values).forEach(([key, value]) => {
if (value !== undefined) {
form.set(key, typeof value === "boolean" ? String(value) : value);
}
});
return form;
}
describe("adminSettingsValidation.server", () => {
it("normalizes valid general settings and rejects missing required names", () => {
const valid = parseAdminSettingsForm(
"general",
createForm({ action: "update", name: " Acme Portal ", theme: "zinc", headScripts: sensitiveHeadScript, bodyScripts: "" })
);
expect(valid).toMatchObject({ ok: true, section: "general" });
expect(valid.ok && valid.data).toMatchObject({ name: "Acme Portal", theme: "zinc", headScripts: sensitiveHeadScript, bodyScripts: "" });
const invalid = parseAdminSettingsForm("general", createForm({ action: "update", name: " " }));
expect(invalid).toEqual({ ok: false, status: 400, errors: { name: ["This field is required."] } });
});
it("normalizes authentication booleans", () => {
const result = parseAdminSettingsForm(
"authentication",
createForm({ action: "update", requireEmailVerification: "on", requireOrganization: "true" })
);
expect(result).toMatchObject({
ok: true,
section: "authentication",
data: {
authRequireEmailVerification: true,
authRequireOrganization: true,
authRequireName: false,
},
});
});
it("normalizes analytics settings (EU-sterilisiert, ohne Google Analytics)", () => {
const valid = parseAdminSettingsForm("analytics", createForm({ action: "update", enabled: "true", simpleAnalytics: "on" }));
expect(valid).toMatchObject({
ok: true,
section: "analytics",
data: {
analyticsEnabled: true,
analyticsSimpleAnalytics: true,
analyticsPlausibleAnalytics: false,
},
});
// EU-Sterilisation (R-P1a): ein mitgesendetes googleAnalyticsTrackingId wird ignoriert, nicht persistiert.
const ignored = parseAdminSettingsForm("analytics", createForm({ action: "update", googleAnalyticsTrackingId: "G-ABC12345" }));
expect(ignored.ok).toBe(true);
expect(JSON.stringify(ignored)).not.toContain("G-ABC12345");
});
it("normalizes cookie settings and rejects malformed actions or booleans", () => {
const valid = parseAdminSettingsForm("cookies", createForm({ action: "update", enabled: "true" }));
expect(valid).toEqual({ ok: true, section: "cookies", data: { cookiesEnabled: true } });
const invalid = parseAdminSettingsForm("cookies", createForm({ action: "delete", enabled: "true" }));
expect(invalid).toEqual({ ok: false, status: 400, errors: { action: ["Invalid action."] } });
const tampered = parseAdminSettingsForm("cookies", createForm({ action: "update", enabled: "definitely" }));
expect(tampered).toEqual({ ok: false, status: 400, errors: { enabled: ["Boolean value is invalid."] } });
});
it("redacts scripts, tokens and query strings from audit details", () => {
const audit = redactSettingsAuditDetails("general", {
headScripts: sensitiveHeadScript,
bodyScripts: `<script src="https://cdn.example/app.js?token=raw-token"></script>`,
brandingLogo: "https://assets.example/logo.png?token=raw-token",
cookiesEnabled: true,
});
expect(audit).toContain("headScripts");
expect(audit).toContain("cookiesEnabled");
expect(audit).toContain("true");
expect(audit).not.toContain(sensitiveHeadScript);
expect(audit).not.toContain("raw-token");
expect(audit).not.toContain("?token=");
});
});
@@ -0,0 +1,217 @@
import { Prisma } from "@toolctrl/db/prisma-browser";
export type AdminSettingsSection = "general" | "authentication" | "analytics" | "cookies";
export type AdminSettingsValidationErrors = Record<string, string[]>;
export type AdminSettingsValidationResult =
| { ok: true; section: AdminSettingsSection; data: Prisma.AppConfigurationUpdateInput }
| { ok: false; status: 400; errors: AdminSettingsValidationErrors };
const MAX_SHORT_TEXT_LENGTH = 255;
const MAX_SCRIPT_LENGTH = 20_000;
const MAX_BRANDING_VALUE_LENGTH = 10_000;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// EU-Sterilisation (R-P1a): googleAnalyticsTrackingId aus den Admin-Analytics-Settings entfernt.
const SECRET_FIELD_NAMES = new Set(["headScripts", "bodyScripts"]);
export function parseAdminSettingsForm(section: AdminSettingsSection, form: FormData): AdminSettingsValidationResult {
const errors: AdminSettingsValidationErrors = {};
const action = getString(form, "action");
if (action !== "update") {
addError(errors, "action", "Invalid action.");
return invalid(errors);
}
switch (section) {
case "general":
return parseGeneralSettings(form, errors);
case "authentication":
return parseAuthenticationSettings(form, errors);
case "analytics":
return parseAnalyticsSettings(form, errors);
case "cookies":
return parseCookiesSettings(form, errors);
default:
addError(errors, "section", "Invalid settings section.");
return invalid(errors);
}
}
export function redactSettingsAuditDetails(section: AdminSettingsSection, input: Prisma.AppConfigurationUpdateInput): string {
const details = {
section,
changedFields: Object.keys(input).sort(),
values: Object.fromEntries(
Object.entries(input)
.sort(([left], [right]) => left.localeCompare(right))
.map(([field, value]) => [field, redactFieldValue(field, value)])
),
};
return JSON.stringify(details).slice(0, 4_000);
}
function parseGeneralSettings(form: FormData, errors: AdminSettingsValidationErrors): AdminSettingsValidationResult {
const name = requireString(form, "name", errors);
const theme = optionalString(form, "theme", errors);
const logo = optionalString(form, "logo", errors, MAX_BRANDING_VALUE_LENGTH);
const logoDarkMode = optionalString(form, "logoDarkMode", errors, MAX_BRANDING_VALUE_LENGTH);
const icon = optionalString(form, "icon", errors, MAX_BRANDING_VALUE_LENGTH);
const iconDarkMode = optionalString(form, "iconDarkMode", errors, MAX_BRANDING_VALUE_LENGTH);
const favicon = optionalString(form, "favicon", errors, MAX_BRANDING_VALUE_LENGTH);
const headScripts = optionalString(form, "headScripts", errors, MAX_SCRIPT_LENGTH);
const bodyScripts = optionalString(form, "bodyScripts", errors, MAX_SCRIPT_LENGTH);
if (Object.keys(errors).length > 0) {
return invalid(errors);
}
return valid("general", {
name,
brandingLogo: logo,
brandingLogoDarkMode: logoDarkMode,
brandingIcon: icon,
brandingIconDarkMode: iconDarkMode,
brandingFavicon: favicon,
theme,
headScripts,
bodyScripts,
});
}
function parseAuthenticationSettings(form: FormData, errors: AdminSettingsValidationErrors): AdminSettingsValidationResult {
if (Object.keys(errors).length > 0) {
return invalid(errors);
}
return valid("authentication", {
authRequireEmailVerification: getBoolean(form, "requireEmailVerification"),
authRequireOrganization: getBoolean(form, "requireOrganization"),
authRequireName: getBoolean(form, "requireName"),
subscriptionRequired: getBoolean(form, "required"),
subscriptionAllowSubscribeBeforeSignUp: getBoolean(form, "allowSubscribeBeforeSignUp"),
subscriptionAllowSignUpBeforeSubscribe: getBoolean(form, "allowSignUpBeforeSubscribe"),
});
}
function parseAnalyticsSettings(form: FormData, errors: AdminSettingsValidationErrors): AdminSettingsValidationResult {
if (Object.keys(errors).length > 0) {
return invalid(errors);
}
return valid("analytics", {
analyticsEnabled: getBoolean(form, "enabled"),
analyticsSimpleAnalytics: getBoolean(form, "simpleAnalytics"),
analyticsPlausibleAnalytics: getBoolean(form, "plausibleAnalytics"),
});
}
function parseCookiesSettings(form: FormData, errors: AdminSettingsValidationErrors): AdminSettingsValidationResult {
const enabled = getOptionalBoolean(form, "enabled", errors);
if (Object.keys(errors).length > 0) {
return invalid(errors);
}
return valid("cookies", {
cookiesEnabled: enabled,
});
}
function requireString(form: FormData, field: string, errors: AdminSettingsValidationErrors, maxLength = MAX_SHORT_TEXT_LENGTH) {
const value = optionalString(form, field, errors, maxLength);
if (!value) {
addError(errors, field, "This field is required.");
}
return value;
}
function optionalString(form: FormData, field: string, errors: AdminSettingsValidationErrors, maxLength = MAX_SHORT_TEXT_LENGTH) {
const value = getString(form, field).trim();
if (value.length > maxLength) {
addError(errors, field, `Must be ${maxLength} characters or fewer.`);
}
if (field.toLowerCase().includes("email") && value && !EMAIL_PATTERN.test(value)) {
addError(errors, field, "Email address is invalid.");
}
return value;
}
function getString(form: FormData, field: string) {
const value = form.get(field);
return typeof value === "string" ? value : "";
}
function getBoolean(form: FormData, field: string) {
const value = form.get(field);
return value === "on" || value === "true" || value === "1";
}
function getOptionalBoolean(form: FormData, field: string, errors: AdminSettingsValidationErrors) {
const value = form.get(field);
if (value === null) {
return false;
}
if (value === "on" || value === "true" || value === "1") {
return true;
}
if (value === "off" || value === "false" || value === "0") {
return false;
}
addError(errors, field, "Boolean value is invalid.");
return false;
}
function addError(errors: AdminSettingsValidationErrors, field: string, message: string) {
errors[field] = [...(errors[field] ?? []), message];
}
function invalid(errors: AdminSettingsValidationErrors): AdminSettingsValidationResult {
return { ok: false, status: 400, errors };
}
function valid(section: AdminSettingsSection, data: Prisma.AppConfigurationUpdateInput): AdminSettingsValidationResult {
return { ok: true, section, data };
}
function redactFieldValue(field: string, value: unknown) {
if (typeof value === "boolean") {
return value;
}
if (typeof value === "string") {
if (SECRET_FIELD_NAMES.has(field) || isSensitiveFieldName(field)) {
return { redacted: true, length: value.length, source: value ? "provided" : "empty" };
}
if (looksLikeUrl(value)) {
return { redacted: true, source: "url", origin: safeUrlOrigin(value), hasQuery: hasUrlQuery(value) };
}
return { redacted: true, length: value.length, source: value ? "provided" : "empty" };
}
if (value === null || value === undefined) {
return { source: "empty" };
}
return { redacted: true, source: "complex" };
}
function isSensitiveFieldName(field: string) {
return /token|password|secret|key|script|tracking|url/i.test(field);
}
function looksLikeUrl(value: string) {
return /^https?:\/\//i.test(value);
}
function safeUrlOrigin(value: string) {
try {
return new URL(value).origin;
} catch {
return "invalid-url";
}
}
function hasUrlQuery(value: string) {
try {
return new URL(value).search.length > 0;
} catch {
return false;
}
}
@@ -0,0 +1,179 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@toolctrl/db/accounts.server", () => ({
createUniqueLegacyTenantIpAddress: vi.fn(),
findLegacyTenantByIdOrSlug: vi.fn(),
getLegacyTenantMembershipsForUser: vi.fn(),
}));
vi.mock("@toolctrl/db/api-keys.server", () => ({
createLegacyApiKeyLog: vi.fn(),
findLegacyApiKeyByKey: vi.fn(),
setLegacyApiKeyLogStatus: vi.fn(),
}));
vi.mock("@toolctrl/db/users.server", () => ({ findLegacyUserWithoutPasswordById: vi.fn() }));
vi.mock("./.server/subscriptionService", () => ({
getActiveTenantSubscriptions: vi.fn(),
getPlanFeatureUsage: vi.fn(),
}));
vi.mock("../server/IpUtils", () => ({ getClientIPAddress: vi.fn(() => "127.0.0.1") }));
vi.mock("jsonwebtoken", () => ({ default: { verify: vi.fn() } }));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: { sendToRoles: vi.fn() },
}));
vi.mock("../stripe.server", () => ({ getOpenInvoices: vi.fn() }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
vi.mock("./rateLimitService", () => ({ rateLimitByKey: vi.fn() }));
vi.mock("../cache.server", () => ({ cachified: vi.fn() }));
vi.mock("../app/CrossHostUrls", () => ({ absoluteAppPath: vi.fn(() => "https://app.example.com/acme/settings/api/keys") }));
vi.mock("@toolctrl/config", () => ({
loadApiConfig: vi.fn(() => ({
ok: true,
config: {
apiKeys: { allowLegacyPlaintextFallback: false },
jwtSecret: "web-hash-secret",
routing: {},
},
diagnostics: [],
})),
loadRequiredWebConfig: vi.fn(() => ({ apiAccessToken: "service-secret", jwtSecret: "web-jwt-secret", routing: {} })),
}));
import { findLegacyTenantByIdOrSlug } from "@toolctrl/db/accounts.server";
import { createLegacyApiKeyLog, findLegacyApiKeyByKey, setLegacyApiKeyLogStatus } from "@toolctrl/db/api-keys.server";
import { loadApiConfig } from "@toolctrl/config";
import { cachified } from "../cache.server";
import { getTranslations } from "~/locale/i18next.server";
import { rateLimitByKey } from "./rateLimitService";
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
import { getServiceAccessTokenFromRequest, hasValidServiceAccessToken, validateApiKey, validateTenantApiKey } from "./apiService";
describe("service API access token helpers", () => {
beforeEach(() => {
vi.mocked(findLegacyTenantByIdOrSlug).mockResolvedValue({ id: "tenant_1" } as never);
vi.mocked(createLegacyApiKeyLog).mockResolvedValue({ id: "log_1" } as never);
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
});
afterEach(() => {
vi.clearAllMocks();
});
it("accepts service tokens from bearer auth and x-api-key headers", () => {
const bearerRequest = new Request("https://example.com/v1/accounts", { headers: { Authorization: "Bearer service-secret" } });
const apiKeyRequest = new Request("https://example.com/v1/accounts", { headers: { "X-Api-Key": "service-secret" } });
expect(getServiceAccessTokenFromRequest(bearerRequest)).toBe("service-secret");
expect(hasValidServiceAccessToken(bearerRequest)).toBe(true);
expect(hasValidServiceAccessToken(apiKeyRequest)).toBe(true);
});
it("rejects missing or mismatched service tokens", () => {
expect(hasValidServiceAccessToken(new Request("https://example.com/v1/accounts"))).toBe(false);
expect(hasValidServiceAccessToken(new Request("https://example.com/v1/accounts", { headers: { Authorization: "Bearer wrong" } }))).toBe(false);
expect(hasValidServiceAccessToken(new Request("https://example.com/v1/accounts", { headers: { Authorization: "Bearer service-secret-extra" } }))).toBe(false);
});
it("redacts sensitive API log query params before persistence", () => {
const request = new Request(
"https://example.com/v1/entities/contact/rows?entity=contact&id=row_1&page=2&token=raw-token&email=person@example.test&next=/dashboard&apiKey=sk_live_secret"
);
expect(serializeApiLogSearchParams(request)).toBe(
JSON.stringify({
page: "2",
token: "[REDACTED]",
email: "[REDACTED]",
next: "/dashboard",
apiKey: "[REDACTED]",
})
);
});
it("uses hashed cache keys for stored API-key lookups", async () => {
vi.mocked(findLegacyApiKeyByKey).mockResolvedValue(null);
await expect(validateApiKey(new Request("https://example.com/v1/widgets", { headers: { "X-Api-Key": "stored-key" } }), {})).rejects.toThrow(
"Invalid API Key"
);
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: getApiKeyLookupCacheKey("stored-key") }));
expect(cachified).not.toHaveBeenCalledWith(expect.objectContaining({ key: "apiKey:stored-key" }));
});
it("resolves service-token tenant scope from query or headers", async () => {
const queryRequest = new Request("https://example.com/internal/api/workflows/run/workflow_1?tenantId=tenant_1", { headers: { "X-Api-Key": "service-secret" } });
const tenantHeaderRequest = new Request("https://example.com/internal/api/workflows/run/workflow_1", { headers: { "X-Api-Key": "service-secret", "X-Tenant-Id": "tenant_1" } });
const accountHeaderRequest = new Request("https://example.com/internal/api/workflows/run/workflow_1", { headers: { "X-Api-Key": "service-secret", "X-Account-Id": "tenant_1" } });
await expect(validateApiKey(queryRequest, {})).resolves.toEqual({ tenant: { id: "tenant_1" } });
await expect(validateApiKey(tenantHeaderRequest, {})).resolves.toEqual({ tenant: { id: "tenant_1" } });
await expect(validateApiKey(accountHeaderRequest, {})).resolves.toEqual({ tenant: { id: "tenant_1" } });
expect(findLegacyTenantByIdOrSlug).toHaveBeenCalledTimes(3);
expect(findLegacyTenantByIdOrSlug).toHaveBeenCalledWith("tenant_1");
});
it("rejects conflicting service-token tenant scopes", async () => {
const request = new Request("https://example.com/internal/api/workflows/run/workflow_1?tenantId=tenant_1", {
headers: { "X-Api-Key": "service-secret", "X-Tenant-Id": "tenant_2" },
});
await expect(validateApiKey(request, {})).rejects.toThrow("Conflicting tenant scope values");
expect(findLegacyTenantByIdOrSlug).not.toHaveBeenCalled();
});
it("rejects stored API keys that include tenant-scope query or headers", async () => {
const queryRequest = new Request("https://example.com/v1/widgets?tenantId=tenant_1", { headers: { "X-Api-Key": "stored-key" } });
const tenantHeaderRequest = new Request("https://example.com/v1/widgets", { headers: { "X-Api-Key": "stored-key", "X-Tenant-Id": "tenant_1" } });
const accountHeaderRequest = new Request("https://example.com/v1/widgets", { headers: { "X-Api-Key": "stored-key", "X-Account-Id": "tenant_1" } });
await expect(validateApiKey(queryRequest, {})).rejects.toThrow("You cannot use tenantId, X-Tenant-Id, or X-Account-Id with a stored API key");
await expect(validateApiKey(tenantHeaderRequest, {})).rejects.toThrow("You cannot use tenantId, X-Tenant-Id, or X-Account-Id with a stored API key");
await expect(validateApiKey(accountHeaderRequest, {})).rejects.toThrow("You cannot use tenantId, X-Tenant-Id, or X-Account-Id with a stored API key");
expect(findLegacyApiKeyByKey).not.toHaveBeenCalled();
});
it("threads API-key hash secret and plaintext-fallback cutover into stored-key lookup", async () => {
vi.mocked(loadApiConfig).mockReturnValue({
ok: true,
config: {
apiKeys: { allowLegacyPlaintextFallback: false },
jwtSecret: "cutover-hash-secret",
routing: {},
},
diagnostics: [],
} as never);
vi.mocked(findLegacyApiKeyByKey).mockResolvedValue(null);
const request = new Request("https://example.com/v1/widgets", { headers: { "X-Api-Key": "stored-key" } });
await expect(validateApiKey(request, {})).rejects.toThrow("Invalid API Key");
expect(findLegacyApiKeyByKey).toHaveBeenCalledWith("stored-key", undefined, "cutover-hash-secret", {
allowPlaintextFallback: false,
});
});
it("updates stored API-key error logs with tenant scope", async () => {
vi.mocked(findLegacyApiKeyByKey).mockResolvedValue({
id: "api_key_1",
tenantId: "tenant_1",
active: true,
expires: null,
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
} as never);
vi.mocked(createLegacyApiKeyLog).mockResolvedValue({ id: "log_1", tenantId: "tenant_1" } as never);
vi.mocked(rateLimitByKey).mockResolvedValue({ error: "tenant quota exceeded" } as never);
const request = new Request("https://example.com/v1/widgets", { headers: { "X-Api-Key": "stored-key" } });
await expect(validateTenantApiKey(request, {})).rejects.toMatchObject({
message: "Rate limit exceeded: tenant quota exceeded",
status: 429,
apiKeyLog: { id: "log_1", tenantId: "tenant_1" },
});
expect(setLegacyApiKeyLogStatus).toHaveBeenCalledWith(
{ id: "log_1", tenantId: "tenant_1" },
expect.objectContaining({ error: "Rate limit exceeded: tenant quota exceeded", status: 429 })
);
});
});
@@ -0,0 +1,328 @@
import { timingSafeEqual } from "node:crypto";
import {
createUniqueLegacyTenantIpAddress,
findLegacyTenantByIdOrSlug,
getLegacyTenantMembershipsForUser,
} from "@toolctrl/db/accounts.server";
import {
createLegacyApiKeyLog,
findLegacyApiKeyByKey,
setLegacyApiKeyLogStatus as setApiKeyLogStatus,
type LegacyApiKeySimple,
} from "@toolctrl/db/api-keys.server";
import type { ApiKeyLog } from "@toolctrl/db/prisma-browser";
import { findLegacyUserWithoutPasswordById } from "@toolctrl/db/users.server";
import { Params } from "react-router";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { getActiveTenantSubscriptions, getPlanFeatureUsage } from "./.server/subscriptionService";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { getClientIPAddress } from "../server/IpUtils";
import jwt from "jsonwebtoken";
import NotificationService from "~/modules/notifications/services/.server/NotificationService";
import { getOpenInvoices } from "../stripe.server";
import { getTranslations } from "~/locale/i18next.server";
import { rateLimitByKey } from "./rateLimitService";
import { cachified } from "../cache.server";
import { loadApiConfig, loadRequiredWebConfig } from "@toolctrl/config";
import { absoluteAppPath } from "../app/CrossHostUrls";
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
type ApiKeyLogScope = { id: string; tenantId: string };
async function setApiError(request: Request, params: Params, error: string, status: number, apiKeyLogScope?: ApiKeyLogScope) {
if (apiKeyLogScope) {
await setApiKeyLogStatus(apiKeyLogScope, {
error,
status,
startTime: null,
});
} else {
await createApiKeyLog(request, {
apiKeyId: null,
tenantId: null,
endpoint: new URL(request.url).pathname,
error,
status,
});
}
throw Object.assign(new Error(error), {
status,
apiKeyLog: apiKeyLogScope,
});
}
function getRequiredJwtSecret() {
const jwtSecret = loadRequiredWebConfig().jwtSecret;
if (!jwtSecret) {
throw new Error("JWT_SECRET is required for API authorization.");
}
return jwtSecret;
}
async function createApiKeyLog(
request: Request,
data: {
tenantId: string | null;
apiKeyId: string | null;
endpoint: string;
error?: string;
status?: number;
alias?: string;
tenantName?: string;
},
) {
return createLegacyApiKeyLog({
tenantId: data.tenantId,
apiKeyId: data.apiKeyId,
endpoint: data.endpoint,
error: data.error,
status: data.status,
alias: data.alias,
tenantName: data.tenantName,
ip: getClientIPAddress(request) ?? "",
method: request.method,
params: serializeApiLogSearchParams(request),
});
}
async function getApiKeyFromHeader(key: string) {
return cachified({
key: getApiKeyLookupCacheKey(key),
ttl: 1000 * 60 * 60,
getFreshValue: () => {
const { config } = loadApiConfig();
return findLegacyApiKeyByKey(key, undefined, config.jwtSecret, {
allowPlaintextFallback: config.apiKeys.allowLegacyPlaintextFallback,
});
},
});
}
export function getServiceAccessTokenFromRequest(request: Request) {
const authorization = request.headers.get("Authorization")?.trim() ?? "";
if (/^Bearer\s+/i.test(authorization)) {
return authorization.replace(/^Bearer\s+/i, "").trim();
}
return request.headers.get("X-Api-Key")?.trim() ?? "";
}
export function hasValidServiceAccessToken(request: Request) {
const apiAccessToken = loadRequiredWebConfig().apiAccessToken;
return typeof apiAccessToken === "string" && apiAccessToken.length > 0 && timingSafeStringEqual(getServiceAccessTokenFromRequest(request), apiAccessToken);
}
function timingSafeStringEqual(left: string, right: string) {
const leftBuffer = Buffer.from(left);
const rightBuffer = Buffer.from(right);
if (leftBuffer.byteLength !== rightBuffer.byteLength) {
return false;
}
return timingSafeEqual(leftBuffer, rightBuffer);
}
function getServiceTenantScopeFromRequest(request: Request) {
const scopes = getTenantScopeOverridesFromRequest(request);
const distinctValues = new Set(scopes);
if (distinctValues.size > 1) {
throw Error("Conflicting tenant scope values");
}
return scopes[0] ?? null;
}
function getTenantScopeOverridesFromRequest(request: Request) {
const searchParams = new URL(request.url).searchParams;
return [
searchParams.get("tenantId"),
request.headers.get("X-Tenant-Id"),
request.headers.get("X-Account-Id"),
]
.map((value) => value?.trim() ?? "")
.filter((value) => value.length > 0);
}
export type ApiAccessValidation = {
userId?: string;
tenant: {
id: string;
name: string;
slug: string;
deactivatedReason: string | null;
} | null;
tenantApiKey?: {
apiKey: LegacyApiKeySimple;
apiKeyLog: ApiKeyLog;
usage: PlanFeatureUsageDto | undefined;
};
};
export async function validateApiKey(request: Request, params: Params): Promise<ApiAccessValidation> {
const authorization = request.headers.get("Authorization");
if (authorization && authorization.startsWith("Bearer ")) {
const token = authorization.split(" ")[1];
let userId = "";
try {
const decoded: any = jwt.verify(token, getRequiredJwtSecret());
userId = decoded.userId;
} catch (e: any) {
throw Error("Invalid authorization token: " + e.message);
}
const user = await findLegacyUserWithoutPasswordById(userId);
if (!user) {
throw Error("Unauthorized");
}
let tenantId = request.headers.get("X-Account-Id") ?? request.headers.get("X-Tenant-Id");
if (!tenantId) {
if (!user.admin) {
throw Error("No X-Account-Id provided");
} else {
tenantId = null;
}
}
if (tenantId !== null) {
const userTenants = await getLegacyTenantMembershipsForUser(user.id);
if (!userTenants.find((t) => t.id === tenantId || t.slug === tenantId)) {
throw Error("Unauthorized");
}
}
const tenant = await findLegacyTenantByIdOrSlug(tenantId ?? "");
return {
userId,
tenant: tenantId === null ? null : tenant,
};
}
const apiKeyFromHeaders = request.headers.get("X-Api-Key") ?? "";
if (!apiKeyFromHeaders) {
throw Error("No X-API-Key header or Authorization token provided");
}
const apiAccessToken = loadRequiredWebConfig().apiAccessToken;
if (apiAccessToken && apiKeyFromHeaders === apiAccessToken) {
const tenantId = getServiceTenantScopeFromRequest(request);
if (!tenantId) {
return { tenant: null };
}
const tenant = await findLegacyTenantByIdOrSlug(tenantId);
if (!tenant) {
throw Error("Account not found: " + tenantId);
}
return { tenant };
}
if (getTenantScopeOverridesFromRequest(request).length > 0) {
throw Error("You cannot use tenantId, X-Tenant-Id, or X-Account-Id with a stored API key");
}
return validateTenantApiKey(request, params);
}
export async function validateTenantApiKey(request: Request, params: Params): Promise<ApiAccessValidation> {
const { t } = await getTranslations(request);
const apiKeyFromHeaders = request.headers.get("X-Api-Key") ?? "";
const apiKey = await getApiKeyFromHeader(apiKeyFromHeaders);
if (!apiKey) {
throw await setApiError(request, params, "Invalid API Key", 401);
}
const tenantSubscription = await getActiveTenantSubscriptions(apiKey.tenantId);
const rateLimitResult = await rateLimitByKey({
apiKey: apiKey.id,
tenantId: apiKey.tenantId,
tenantSubscription,
});
const apiKeyLog = await createApiKeyLog(request, {
apiKeyId: apiKey.id,
tenantId: apiKey.tenantId,
endpoint: new URL(request.url).pathname,
});
if (rateLimitResult.error) {
throw await setApiError(request, params, "Rate limit exceeded: " + rateLimitResult.error, 429, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
createUniqueLegacyTenantIpAddress({
ip: getClientIPAddress(request) ?? "Unknown",
fromUrl: new URL(request.url).pathname,
tenantId: apiKey.tenantId,
apiKeyId: apiKey.id,
});
if (apiKey.tenant.deactivatedReason) {
throw await setApiError(request, params, "Account deactivated: " + apiKey.tenant.deactivatedReason, 403, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
if (!apiKey.active) {
throw await setApiError(request, params, "Inactive API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
if (apiKey.expires && apiKey?.expires < new Date()) {
throw await setApiError(request, params, "Expired API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
const usage = await getPlanFeatureUsage(apiKey.tenantId, DefaultFeatures.API, tenantSubscription);
if (usage && !usage.enabled) {
await NotificationService.sendToRoles({
channel: "admin-users",
tenantId: null,
notification: {
message: `${apiKey.tenant.name} (${apiKey.tenant.slug}) API error. ${t(usage.message)}`,
action: {
url: absoluteAppPath(loadRequiredWebConfig().routing, apiKey.tenant.slug, "settings/api/keys"),
},
},
});
throw await setApiError(request, params, t(usage.message), 402, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
if (tenantSubscription && tenantSubscription.stripeCustomerId) {
const openInvoices = await getOpenInvoices(tenantSubscription.stripeCustomerId);
if (openInvoices.data.length > 0) {
const invoicesDescription = openInvoices.data.map((invoice) => `Invoice #${invoice.number} - ${invoice.total} ${invoice.currency}`).join("\n");
await NotificationService.sendToRoles({
channel: "admin-users",
tenantId: null,
notification: {
message: `${apiKey.tenant.name} (${apiKey.tenant.slug}) API error. You have open invoices: ${invoicesDescription}`,
action: {
url: absoluteAppPath(loadRequiredWebConfig().routing, apiKey.tenant.slug, "settings/api/keys"),
},
},
});
throw await setApiError(request, params, "You have open invoices: " + invoicesDescription, 402, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
}
return {
tenant: apiKey.tenant,
tenantApiKey: {
apiKey,
apiKeyLog,
usage,
},
};
}
export type WorkflowApiAccessValidation = {
tenant: ApiAccessValidation["tenant"];
userId?: string;
apiKeyLog?: ApiKeyLog | ApiKeyLogScope;
usage?: PlanFeatureUsageDto;
};
export async function getWorkflowApiKeyFromRequest(request: Request, params: Params): Promise<WorkflowApiAccessValidation> {
const apiAccessValidation = await validateApiKey(request, params);
return {
tenant: apiAccessValidation.tenant,
userId: apiAccessValidation.userId,
apiKeyLog: apiAccessValidation.tenantApiKey?.apiKeyLog,
usage: apiAccessValidation.tenantApiKey?.usage,
};
}
export async function setWorkflowApiKeyLogStatus(
apiAccessValidation: WorkflowApiAccessValidation | undefined,
data: { error?: string; status: number; startTime: number },
) {
if (!apiAccessValidation?.apiKeyLog) {
return;
}
const tenantId = apiAccessValidation.apiKeyLog.tenantId ?? apiAccessValidation.tenant?.id;
if (!tenantId) {
throw new Error(`API key log ${apiAccessValidation.apiKeyLog.id} cannot be updated without tenant scope`);
}
await setApiKeyLogStatus({ id: apiAccessValidation.apiKeyLog.id, tenantId }, data);
}
@@ -0,0 +1,104 @@
import { TFunction } from "i18next";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import { Stat } from "~/application/dtos/stats/Stat";
import { getStatChangePercentage, getStatChangeType } from "../app/DashboardUtils";
import { db } from "../db.server";
import { EntitySimple, getAllEntities } from "../db/entities/entities.db.server";
import { TenantSimple } from "../db/tenants.db.server";
import { RowsApi } from "../api/.server/RowsApi";
export async function getAppDashboardStats({
tenant,
gte,
entities,
}: {
t: TFunction;
tenant: TenantSimple | null;
gte: Date | undefined | undefined;
entities?: EntitySimple[];
}): Promise<Stat[]> {
if (!tenant) {
return [];
}
if (!entities) {
entities = await getAllEntities({ tenantId: tenant.id, active: true, types: [DefaultEntityTypes.All, DefaultEntityTypes.AppOnly] });
}
const promises = entities.map((entity) => getEntityStat(entity, tenant.id, gte));
const stats = await Promise.all(promises);
return stats;
}
export async function getEntityStat(entity: EntitySimple, tenantId: string, gte: Date | undefined) {
const { total, added } = await getRowsCreatedSince(entity.id, tenantId, gte);
const stat: Stat = {
name: entity.titlePlural,
hint: "",
stat: added.toString(),
previousStat: (total - added).toString(),
change: getStatChangePercentage(added, total) + "%",
changeType: getStatChangeType(added, total),
entity: {
slug: entity.slug,
},
};
return stat;
}
async function getRowsCreatedSince(entityId: string, tenantId: string, gte: Date | undefined) {
const [added, total] = await Promise.all([
db.row.count({
where: {
entityId,
tenantId,
createdAt: {
gte,
},
},
}),
db.row.count({
where: {
entityId,
tenantId,
},
}),
]);
return {
added,
total,
};
}
export type EntitySummaryDto = {
order: number;
rowsData: RowsApi.GetRowsData;
};
export async function getEntitySummaries({
entities,
tenantId,
}: {
entities: { name: string; pageSize?: number }[];
tenantId: string | null;
}): Promise<EntitySummaryDto[]> {
const entitySummaries: EntitySummaryDto[] = [];
await Promise.all(
entities.map(async ({ name, pageSize }, idx) => {
const entitySummary = {
order: idx,
rowsData: await RowsApi.getAll({
entity: { name },
tenantId,
pageSize: pageSize || 3,
urlSearchParams: new URLSearchParams({
view: "null",
}),
}),
};
entitySummaries.push(entitySummary);
})
);
return entitySummaries;
}
@@ -0,0 +1,360 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createRegistrationForm, createUserAndTenant, getRegistrationFormData } from "./authService";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { createRegistration, getRegistrationByEmail, updateRegistration } from "~/utils/db/registration.db.server";
import { createTenant, createTenantUser } from "~/utils/db/tenants.db.server";
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
import { register } from "~/utils/db/users.db.server";
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { TenantTypesApi } from "~/utils/api/.server/TenantTypesApi";
import EventsService from "~/modules/events/services/.server/EventsService";
import { sendEmail } from "~/modules/emails/services/EmailService";
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
getAppConfiguration: vi.fn(),
}));
vi.mock("~/utils/db/registration.db.server", () => ({
createRegistration: vi.fn(),
getRegistrationByEmail: vi.fn(),
updateRegistration: vi.fn(),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
createTenant: vi.fn(),
createTenantUser: vi.fn(),
getTenantBySlug: vi.fn(),
}));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({
getAllRoles: vi.fn(),
}));
vi.mock("~/utils/db/users.db.server", () => ({
getUserByEmail: vi.fn(),
register: vi.fn(),
}));
vi.mock("~/modules/emails/services/TransactionalEmailQueue.server", () => ({
queueTransactionalEmail: vi.fn(),
}));
vi.mock("~/modules/emails/services/EmailService", () => ({
sendEmail: vi.fn(),
}));
vi.mock("~/utils/url.server", () => ({
getAbsoluteUrl: vi.fn((_request: Request, path: string) => `https://example.com${path}`),
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(async () => ({ lng: "en" })),
}));
vi.mock("crypto", () => ({
default: {
randomBytes: vi.fn(() => ({ toString: vi.fn(() => "registration-token") })),
},
}));
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({
default: {
VERIFICATION_EMAIL: {
parse: vi.fn(({ data }) => ({
subject: "Verify your email",
body: `<p>Verify at ${data.action_url} for ${data.name}</p>`,
})),
},
WELCOME_EMAIL: {
parse: vi.fn(({ data }) => ({
subject: "Welcome",
body: `<p>Welcome at ${data.action_url} for ${data.name}</p>`,
})),
},
},
}));
vi.mock("~/utils/api/.server/TenantTypesApi", () => ({
TenantTypesApi: {
setTenantTypes: vi.fn(),
},
}));
vi.mock("~/modules/events/services/.server/EventsService", () => ({
default: {
create: vi.fn(),
},
}));
vi.mock("~/utils/stripe.server", () => ({
createStripeCustomer: vi.fn(),
isStripeConfigured: vi.fn(() => false),
}));
vi.mock("~/modules/ipAddress/services/IpAddressService.server", () => ({
default: {
log: vi.fn(async () => undefined),
},
}));
vi.mock("~/utils/db.server", () => ({
db: {},
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
remixI18Next: {
getFixedT: vi.fn(async () => (key: string) => key),
getLocale: vi.fn(async () => "de"),
},
}));
vi.mock("~/locale/mail-translator.server", () => ({
getMailTranslator: vi.fn(async () => ({ t: (key: string) => key, locale: "de" })),
getMailTranslatorFromRequest: vi.fn(async () => ({ t: (key: string) => key, locale: "de" })),
resolveMailLocale: vi.fn((locale: string | null | undefined) => locale ?? "de"),
}));
const getAppConfigurationMock = vi.mocked(getAppConfiguration);
const getRegistrationByEmailMock = vi.mocked(getRegistrationByEmail);
const updateRegistrationMock = vi.mocked(updateRegistration);
const createRegistrationMock = vi.mocked(createRegistration);
const queueTransactionalEmailMock = vi.mocked(queueTransactionalEmail);
const verificationParseMock = vi.mocked(EmailTemplates.VERIFICATION_EMAIL.parse);
const welcomeParseMock = vi.mocked(EmailTemplates.WELCOME_EMAIL.parse);
const createTenantMock = vi.mocked(createTenant);
const registerMock = vi.mocked(register);
const getAllRolesMock = vi.mocked(getAllRoles);
const createTenantUserMock = vi.mocked(createTenantUser);
const setTenantTypesMock = vi.mocked(TenantTypesApi.setTenantTypes);
const eventsCreateMock = vi.mocked(EventsService.create);
const sendEmailMock = vi.mocked(sendEmail);
const request = new Request("https://example.com/register");
const appConfiguration = {
app: { name: "Example" },
email: { fromName: "Support", supportEmail: "support@example.com" },
} as Awaited<ReturnType<typeof getAppConfiguration>>;
describe("auth service transactional registration emails", () => {
beforeEach(() => {
vi.clearAllMocks();
getAppConfigurationMock.mockResolvedValue(appConfiguration);
queueTransactionalEmailMock.mockResolvedValue({ enqueued: true, jobId: "job_1" });
});
it("recreates pending registration tokens and enqueues verification email", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
updateRegistrationMock.mockResolvedValue({ id: "registration_1" } as Awaited<ReturnType<typeof updateRegistration>>);
await createRegistrationForm({ request, email: "ada@example.com", ipAddress: "127.0.0.1", firstName: "Ada", company: "Ada Co", recreateToken: true });
expect(updateRegistrationMock).toHaveBeenCalledWith("registration_1", {
firstName: "Ada",
lastName: undefined,
company: "Ada Co",
token: "registration-token",
leadConversionLeadId: null,
leadConversionToken: null,
leadConversionPlanId: null,
});
expect(verificationParseMock).toHaveBeenCalledWith(
expect.objectContaining({
appConfiguration,
data: {
action_url: "https://example.com/verify/registration-token",
name: "Ada",
},
t: expect.any(Function),
locale: expect.any(String),
})
);
expect(queueTransactionalEmailMock).toHaveBeenCalledWith({
to: "ada@example.com",
alias: "email-verification",
subject: "Verify your email",
body: "<p>Verify at https://example.com/verify/registration-token for Ada</p>",
data: {
action_url: "https://example.com/verify/registration-token",
name: "Ada",
},
priorityOverride: "critical",
});
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(updateRegistrationMock.mock.invocationCallOrder[0]);
expect(sendEmailMock).not.toHaveBeenCalled();
});
it("refreshes persisted lead conversion context when recreating pending registration tokens", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
updateRegistrationMock.mockResolvedValue({ id: "registration_1" } as Awaited<ReturnType<typeof updateRegistration>>);
await createRegistrationForm({
request,
email: "lead@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
lastName: "Lovelace",
company: "Ada Co",
recreateToken: true,
leadId: "lead_2",
leadToken: "signed-token-2",
leadPlanId: "plan_scale",
});
expect(updateRegistrationMock).toHaveBeenCalledWith("registration_1", {
firstName: "Ada",
lastName: "Lovelace",
company: "Ada Co",
token: "registration-token",
leadConversionLeadId: "lead_2",
leadConversionToken: "signed-token-2",
leadConversionPlanId: "plan_scale",
});
expect(queueTransactionalEmailMock).toHaveBeenCalledWith(
expect.objectContaining({
to: "lead@example.com",
alias: "email-verification",
priorityOverride: "critical",
})
);
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(updateRegistrationMock.mock.invocationCallOrder[0]);
expect(sendEmailMock).not.toHaveBeenCalled();
});
it("creates new registration records and enqueues verification email", async () => {
getRegistrationByEmailMock.mockResolvedValue(null);
createRegistrationMock.mockResolvedValue({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
await createRegistrationForm({ request, email: "ada@example.com", ipAddress: "127.0.0.1", firstName: "Ada", lastName: "Lovelace", company: "Ada Co", slug: "ada-co" });
expect(createRegistrationMock).toHaveBeenCalledWith({
email: "ada@example.com",
firstName: "Ada",
lastName: "Lovelace",
company: "Ada Co",
token: "registration-token",
selectedSubscriptionPriceId: null,
leadConversionLeadId: null,
leadConversionToken: null,
leadConversionPlanId: null,
ipAddress: "127.0.0.1",
slug: "ada-co",
});
expect(queueTransactionalEmailMock).toHaveBeenCalledWith({
to: "ada@example.com",
alias: "email-verification",
subject: "Verify your email",
body: "<p>Verify at https://example.com/verify/registration-token for Ada</p>",
data: {
action_url: "https://example.com/verify/registration-token",
name: "Ada",
},
priorityOverride: "critical",
});
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(createRegistrationMock.mock.invocationCallOrder[0]);
expect(sendEmailMock).not.toHaveBeenCalled();
});
it("persists signed lead conversion context for email verification registrations", async () => {
getRegistrationByEmailMock.mockResolvedValue(null);
createRegistrationMock.mockResolvedValue({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
await createRegistrationForm({
request,
email: "lead@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
leadId: "lead_1",
leadToken: "signed-token",
leadPlanId: "plan_pro",
});
expect(createRegistrationMock).toHaveBeenCalledWith(
expect.objectContaining({
email: "lead@example.com",
leadConversionLeadId: "lead_1",
leadConversionToken: "signed-token",
leadConversionPlanId: "plan_pro",
})
);
});
it("parses signed lead conversion fields from registration posts", async () => {
const form = new URLSearchParams({
email: "Lead@Example.com ",
password: "Password123!",
company: "Ada Co",
leadId: "lead_1",
leadToken: "signed-token",
leadPlanId: "plan_pro",
});
await expect(
getRegistrationFormData(
new Request("https://example.com/register", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: form,
})
)
).resolves.toMatchObject({
email: "lead@example.com",
company: "Ada Co",
leadId: "lead_1",
leadToken: "signed-token",
leadPlanId: "plan_pro",
});
});
it("creates new accounts before enqueueing welcome email with account metadata", async () => {
createTenantMock.mockResolvedValue({ id: "tenant_1", name: "Ada Co", slug: "ada-co" } as Awaited<ReturnType<typeof createTenant>>);
registerMock.mockResolvedValue({ id: "user_1", email: "ada@example.com" } as Awaited<ReturnType<typeof register>>);
getAllRolesMock.mockResolvedValue([{ id: "role_1" }] as Awaited<ReturnType<typeof getAllRoles>>);
createTenantUserMock.mockResolvedValue({ id: "tenant_user_1" } as Awaited<ReturnType<typeof createTenantUser>>);
setTenantTypesMock.mockResolvedValue(undefined);
eventsCreateMock.mockResolvedValue({} as Awaited<ReturnType<typeof EventsService.create>>);
const result = await createUserAndTenant({ request, email: "ada@example.com", password: "password", company: "Ada Co", firstName: "Ada", lastName: "Lovelace", locale: "en", slug: "ada-co" });
expect(result).toEqual({ user: { id: "user_1", email: "ada@example.com" }, tenant: { id: "tenant_1", name: "Ada Co", slug: "ada-co" } });
expect(queueTransactionalEmailMock).toHaveBeenCalledWith({
to: "ada@example.com",
alias: "welcome",
tenantId: "tenant_1",
userId: "user_1",
subject: "Welcome",
body: "<p>Welcome at https://example.com/login for Ada</p>",
data: {
action_url: "https://example.com/login",
name: "Ada",
},
});
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(createTenantUserMock.mock.invocationCallOrder[0]);
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(setTenantTypesMock.mock.invocationCallOrder[0]);
expect(welcomeParseMock).toHaveBeenCalledWith(
expect.objectContaining({
appConfiguration,
data: {
action_url: "https://example.com/login",
name: "Ada",
},
t: expect.any(Function),
locale: expect.any(String),
})
);
expect(sendEmailMock).not.toHaveBeenCalled();
});
it("throws for already-created registrations without enqueueing", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: "tenant_1" } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
await expect(createRegistrationForm({ request, email: "ada@example.com", ipAddress: "127.0.0.1", recreateToken: true })).rejects.toThrow("api.errors.userAlreadyRegistered");
expect(updateRegistrationMock).not.toHaveBeenCalled();
expect(createRegistrationMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
expect(sendEmailMock).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,440 @@
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { getTranslations } from "~/locale/i18next.server";
import UserValidationUtils from "../app/UserValidationUtils";
import { getAppConfiguration } from "../db/appConfiguration.db.server";
import { getAllRoles } from "../db/permissions/roles.db.server";
import { createTenant, createTenantUser, getTenantBySlug } from "../db/tenants.db.server";
import { getUserByEmail, register } from "../db/users.db.server";
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
import { createStripeCustomer, isStripeConfigured } from "../stripe.server";
import crypto from "crypto";
import { createRegistration, getRegistrationByEmail, updateRegistration } from "../db/registration.db.server";
import { db } from "~/utils/db.server";
import { getClientIPAddress } from "~/utils/server/IpUtils";
import { addBlacklistAttempt, findInBlacklist } from "../db/blacklist.db.server";
import { getAbsoluteUrl } from "../url.server";
import { getUserInfo } from "../session.server";
import { TenantTypesApi } from "../api/.server/TenantTypesApi";
import EventsService from "../../modules/events/services/.server/EventsService";
import { AccountCreatedDto } from "~/modules/events/dtos/AccountCreatedDto";
import { autosubscribeToTrialOrFreePlan } from "./.server/pricingService";
import IpAddressServiceServer from "~/modules/ipAddress/services/IpAddressService.server";
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { getMailTranslator, getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
import { verifyLeadToken } from "~/utils/leads/leadToken.server";
import { recordExistingTenantLeadConversion } from "~/utils/leads/convertLead.server";
import { createScopedLogger } from "~/utils/logger.server";
import { resolveCaptchaConfig, verifyCaptchaToken, getSitekey, isCaptchaConfigured } from "@toolctrl/captcha";
import { validateDesiredTenantSlug } from "./tenantService";
import { seedShkRolesForTenant } from "./shkRoles.server";
const authServiceLogger = createScopedLogger("auth-service");
function translateIpAddressError(t: (key: string) => string, error: string): string {
if (error === "blacklisted") {
return t("admin.accounts.ipAddresses.errors.blacklisted");
}
if (error === "unauthorized") {
return t("admin.accounts.ipAddresses.errors.unauthorized");
}
return error;
}
export type RegistrationData = {
email?: string;
password?: string;
company?: string;
firstName?: string;
lastName?: string;
avatarURL?: string;
slug?: string;
leadId?: string;
leadToken?: string;
leadPlanId?: string;
/** mCaptcha proof-of-work token from the client widget (hidden `mcaptcha__token` field). */
captchaToken?: string;
};
export async function getRegistrationFormData(request: Request): Promise<RegistrationData> {
const formData = await request.formData();
const email = formData.get("email")?.toString().toLowerCase().trim();
const password = formData.get("password")?.toString();
const company = formData.get("company")?.toString();
const firstName = formData.get("first-name")?.toString();
const lastName = formData.get("last-name")?.toString();
const slug = formData.get("slug")?.toString();
const leadId = formData.get("leadId")?.toString().trim() || undefined;
const leadToken = formData.get("leadToken")?.toString().trim() || undefined;
const leadPlanId = formData.get("leadPlanId")?.toString().trim() || undefined;
const captchaToken = formData.get("mcaptcha__token")?.toString().trim() || undefined;
const ipError = await IpAddressServiceServer.log(request, {
action: "register",
description: email ? "registration-attempt" : "{empty email}",
metadata: { emailDomain: email?.includes("@") ? email.substring(email.lastIndexOf("@") + 1) : undefined, slug },
}).catch((e) => e.message);
if (ipError) {
const { t } = await getTranslations(request);
throw Error(translateIpAddressError(t, ipError));
}
return { email, password, company, firstName, lastName, slug, leadId, leadToken, leadPlanId, captchaToken };
}
async function resolveLeadConversionContext(registrationData: RegistrationData, invalidMessage: string): Promise<{ leadId: string; planId: string | null } | null> {
const hasAnyLeadField = Boolean(registrationData.leadId || registrationData.leadToken || registrationData.leadPlanId);
if (!hasAnyLeadField) return null;
if (process.env.LEAD_CONVERSION_ENABLED === "false") return null;
if (!registrationData.email || !registrationData.leadId || !registrationData.leadToken) {
throw Error(invalidMessage);
}
const payload = verifyLeadToken(registrationData.leadToken);
if (!payload || payload.leadId !== registrationData.leadId) {
throw Error(invalidMessage);
}
const lead = await db.lead.findUnique({
where: { id: registrationData.leadId },
select: { email: true, convertedToTenantId: true },
});
if (!lead || lead.convertedToTenantId || lead.email.toLowerCase().trim() !== registrationData.email.toLowerCase().trim()) {
throw Error(invalidMessage);
}
return {
leadId: registrationData.leadId,
planId: payload.planId ?? registrationData.leadPlanId ?? null,
};
}
export async function validateRegistration({
request,
registrationData,
addToTrialOrFreePlan,
checkEmailVerification = true,
stripeCustomerId,
}: {
request: Request;
registrationData: RegistrationData;
addToTrialOrFreePlan: boolean;
checkEmailVerification?: boolean;
stripeCustomerId?: string;
}) {
const { t } = await getTranslations(request);
const userInfo = await getUserInfo(request);
const appConfiguration = await getAppConfiguration({ request });
const { email, password, company, firstName, lastName, avatarURL, slug } = registrationData;
if (!email || !UserValidationUtils.validateEmail(email)) {
throw Error(t("account.register.errors.invalidEmail"));
}
// Anti-spam: verify the mCaptcha PoW token for human signups (email/password is
// the only signup path after EU-Sterilisation removed social OAuth). No-op when
// captcha is unconfigured; verification fails open if the instance is unreachable
// (CAPTCHA_FAIL_OPEN).
const captcha = resolveCaptchaConfig(process.env);
if (isCaptchaConfigured(captcha)) {
const captchaOk = await verifyCaptchaToken({
token: registrationData.captchaToken,
sitekey: getSitekey(captcha, "login"),
secret: captcha.accountSecret,
instanceUrl: captcha.instanceUrl,
failOpen: captcha.failOpen,
logger: authServiceLogger,
});
if (!captchaOk) {
throw Error(t("account.register.errors.captchaFailed"));
}
}
const leadConversionContext = await resolveLeadConversionContext(registrationData, t("account.register.errors.invalidLeadConversion"));
if (!appConfiguration.auth.requireEmailVerification && (typeof password !== "string" || password.length === 0)) {
throw Error(t("account.register.errors.passwordRequired"));
} else if (!appConfiguration.auth.requireEmailVerification && password) {
const policyResult = await validatePolicyPassword(password, { email });
if (!policyResult.valid) {
const firstError = policyResult.errors[0];
throw Error(firstError ? t(firstError.code, firstError.args ?? {}) : t("auth:errors.invalidPassword"));
}
} else if (appConfiguration.auth.requireOrganization && typeof company !== "string") {
throw Error(t("account.register.errors.organizationRequired"));
} else if (appConfiguration.auth.requireName && (typeof firstName !== "string" || typeof lastName !== "string")) {
throw Error(t("account.register.errors.nameRequired"));
}
if (company && company.length > 100) {
throw Error(t("account.register.errors.companyMaxLength"));
} else if (firstName && firstName.length > 50) {
throw Error(t("account.register.errors.firstNameMaxLength"));
} else if (lastName && lastName.length > 50) {
throw Error(t("account.register.errors.lastNameMaxLength"));
}
const ipAddress = getClientIPAddress(request.headers)?.toString() ?? "";
const blacklistedEmail = await findInBlacklist("email", email);
if (blacklistedEmail) {
await addBlacklistAttempt(blacklistedEmail);
throw Error(t("account.register.errors.blacklist.email"));
}
const blacklistedDomain = await findInBlacklist("domain", email.substring(email.lastIndexOf("@") + 1));
if (blacklistedDomain) {
await addBlacklistAttempt(blacklistedDomain);
throw Error(t("account.register.errors.blacklist.domain"));
}
const blacklistedIp = await findInBlacklist("ip", ipAddress);
if (blacklistedIp) {
await addBlacklistAttempt(blacklistedIp);
throw Error(t("account.register.errors.blacklist.ip"));
}
const existingUser = await getUserByEmail(email);
if (existingUser) {
throw Error(t("api.errors.userAlreadyRegistered"));
}
// Vom Nutzer GEWAEHLTER Slug: reservierte/zu-kurze Werte mit Klartext ablehnen, statt sie
// spaeter in createUserAndTenant/getAvailableTenantSlug still umzuschreiben (S1/R-P2a). Greift
// unabhaengig von auth.slug.require, sobald ein Slug uebermittelt wurde.
if (typeof slug === "string" && slug.trim().length > 0) {
const slugCheck = validateDesiredTenantSlug(slug);
if (!slugCheck.ok && slugCheck.reason !== "empty") {
throw Error(t(slugCheck.reason === "reserved" ? "account.register.errors.slugReserved" : "account.register.errors.slugTooShort"));
}
}
if (appConfiguration.auth.slug?.require) {
if (!slug) {
throw Error(t(appConfiguration.auth.slug.type === "tenant" ? "account.register.errors.slugRequired" : "account.register.errors.usernameRequired"));
}
const existingTenant = await getTenantBySlug(slug);
if (existingTenant) {
throw Error(t(appConfiguration.auth.slug.type === "tenant" ? "account.register.errors.slugTaken" : "account.register.errors.usernameTaken"));
}
}
if (checkEmailVerification && appConfiguration.auth.requireEmailVerification) {
return { email, ipAddress, verificationRequired: true };
}
const locale = userInfo.lng;
const registered = await createUserAndTenant({
request,
email,
password,
company,
firstName,
lastName,
stripeCustomerId,
avatarURL,
locale,
slug,
});
if (addToTrialOrFreePlan) {
await autosubscribeToTrialOrFreePlan({ request, t, tenantId: registered.tenant.id, userId: registered.user.id });
}
if (leadConversionContext) {
try {
await recordExistingTenantLeadConversion({
leadId: leadConversionContext.leadId,
tenantId: registered.tenant.id,
planId: leadConversionContext.planId,
conversionPath: "self-service",
});
} catch (error) {
authServiceLogger.warn(
{
op: "lead.selfServiceConversion.record_failed",
leadId: leadConversionContext.leadId,
tenantId: registered.tenant.id,
err: { name: error instanceof Error ? error.name : "Error" },
},
"Registration succeeded but lead conversion attribution could not be recorded."
);
}
}
return { email, ipAddress, verificationRequired: false, registered };
}
interface CreateRegistrationFormDto {
request: Request;
email: string;
ipAddress: string;
company?: string;
firstName?: string;
lastName?: string;
recreateToken?: boolean;
slug?: string;
leadId?: string;
leadToken?: string;
leadPlanId?: string | null;
}
export async function createRegistrationForm({ request, email, company, firstName, lastName, ipAddress, recreateToken, slug, leadId, leadToken, leadPlanId }: CreateRegistrationFormDto) {
const registration = await getRegistrationByEmail(email);
if (registration) {
if (registration.createdTenantId) {
throw Error("api.errors.userAlreadyRegistered");
} else {
if (recreateToken) {
const newToken = crypto.randomBytes(20).toString("hex");
await updateRegistration(registration.id, {
firstName,
lastName,
company,
token: newToken,
leadConversionLeadId: leadId ?? null,
leadConversionToken: leadToken ?? null,
leadConversionPlanId: leadPlanId ?? null,
});
const emailData = {
action_url: getAbsoluteUrl(request, `/verify/${newToken}`),
name: firstName ?? "",
};
const mailTranslator = await getMailTranslatorFromRequest(request);
await queueTransactionalEmail({
to: email,
alias: "email-verification",
...EmailTemplates.VERIFICATION_EMAIL.parse({
appConfiguration: await getAppConfiguration({ request }),
data: emailData,
t: mailTranslator.t,
locale: mailTranslator.locale,
}),
data: emailData,
priorityOverride: "critical",
});
}
}
} else {
var token = crypto.randomBytes(20).toString("hex");
await createRegistration({
email,
firstName: firstName ?? "",
lastName: lastName ?? "",
company: company ?? "",
token,
selectedSubscriptionPriceId: null,
leadConversionLeadId: leadId ?? null,
leadConversionToken: leadToken ?? null,
leadConversionPlanId: leadPlanId ?? null,
ipAddress,
slug: slug ?? null,
});
const emailData = {
action_url: getAbsoluteUrl(request, `/verify/${token}`),
name: firstName ?? "",
};
const mailTranslator = await getMailTranslatorFromRequest(request);
await queueTransactionalEmail({
to: email,
alias: "email-verification",
...EmailTemplates.VERIFICATION_EMAIL.parse({
appConfiguration: await getAppConfiguration({ request }),
data: emailData,
t: mailTranslator.t,
locale: mailTranslator.locale,
}),
data: emailData,
priorityOverride: "critical",
});
}
}
interface CreateUserAndTenantDto {
request: Request;
email: string;
password?: string;
company?: string;
firstName?: string;
lastName?: string;
stripeCustomerId?: string;
avatarURL?: string;
locale?: string;
slug?: string;
}
export async function createUserAndTenant({
request,
email,
password,
company,
firstName,
lastName,
stripeCustomerId,
avatarURL,
locale,
slug,
}: CreateUserAndTenantDto) {
let tenantName = company ?? email.split("@")[0];
if (!stripeCustomerId && isStripeConfigured()) {
const stripeCustomer = await createStripeCustomer(email, tenantName);
if (!stripeCustomer) {
throw Error("Could not create Stripe customer");
}
stripeCustomerId = stripeCustomer.id;
}
const tenant = await createTenant({ name: tenantName, subscriptionCustomerId: stripeCustomerId, slug });
if (!tenant) {
throw Error("Could not create tenant");
}
const user = await register({
email: email,
password: password ?? "",
firstName: firstName ?? "",
lastName: lastName ?? "",
avatarURL,
locale,
defaultTenantId: tenant.id,
request,
});
if (!user) {
throw Error("Could not create user");
}
const roles = await getAllRoles("app");
await createTenantUser(
{
tenantId: tenant.id,
userId: user.id,
type: TenantUserType.OWNER,
},
roles
);
await TenantTypesApi.setTenantTypes({ tenantId: tenant.id });
// R-P2b — neuen (SHK-)Tenant mit den SHK-Standard-Rollen-Templates bestuecken. Best-effort:
// ein Seed-Fehler darf die Registrierung nicht blockieren (Rollen sind anpassbar/nachseedbar).
await seedShkRolesForTenant(tenant.id).catch((error: unknown) => {
authServiceLogger.warn(
{ op: "register.seedShkRoles.failed", tenantId: tenant.id, err: { name: error instanceof Error ? error.name : "Error" } },
"Tenant created but SHK standard roles could not be seeded; they can be re-seeded later."
);
});
const emailData = {
action_url: getAbsoluteUrl(request, "/login"),
name: firstName,
};
const welcomeMailTranslator = await getMailTranslator(user.locale ?? locale);
await queueTransactionalEmail({
to: email,
alias: "welcome",
tenantId: tenant.id,
userId: user.id,
...EmailTemplates.WELCOME_EMAIL.parse({
appConfiguration: await getAppConfiguration({ request }),
data: emailData,
t: welcomeMailTranslator.t,
locale: welcomeMailTranslator.locale,
}),
data: emailData,
});
await EventsService.create({
request,
event: "account.created",
tenantId: tenant.id,
userId: user.id,
data: {
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
user: { id: user.id, email: user.email },
} satisfies AccountCreatedDto,
});
return { user, tenant };
}
@@ -0,0 +1,220 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
findInBlacklist: vi.fn(),
getAppConfiguration: vi.fn(),
getTenantBySlug: vi.fn(),
getUserByEmail: vi.fn(),
register: vi.fn(),
createTenant: vi.fn(),
createTenantUser: vi.fn(),
getAllRoles: vi.fn(),
verifyLeadToken: vi.fn(),
recordExistingTenantLeadConversion: vi.fn(),
leadFindUnique: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(async () => ({ lng: "en" })),
}));
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
getAppConfiguration: (...args: unknown[]) => mocks.getAppConfiguration(...args),
}));
vi.mock("~/utils/app/UserValidationUtils", () => ({
default: {
validateEmail: vi.fn(() => true),
validatePassword: vi.fn(() => true),
},
}));
vi.mock("~/services/auth/password-policy.server", () => ({
validatePassword: vi.fn(async () => ({ valid: true, errors: [] })),
}));
vi.mock("~/utils/db/blacklist.db.server", () => ({
addBlacklistAttempt: vi.fn(),
findInBlacklist: (...args: unknown[]) => mocks.findInBlacklist(...args),
}));
vi.mock("~/utils/db/users.db.server", () => ({
getUserByEmail: (...args: unknown[]) => mocks.getUserByEmail(...args),
register: (...args: unknown[]) => mocks.register(...args),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
createTenant: (...args: unknown[]) => mocks.createTenant(...args),
createTenantUser: (...args: unknown[]) => mocks.createTenantUser(...args),
getTenantBySlug: (...args: unknown[]) => mocks.getTenantBySlug(...args),
}));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRoles: (...args: unknown[]) => mocks.getAllRoles(...args) }));
vi.mock("~/utils/db/registration.db.server", () => ({
createRegistration: vi.fn(),
getRegistrationByEmail: vi.fn(),
updateRegistration: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({ db: { lead: { findUnique: (...args: unknown[]) => mocks.leadFindUnique(...args) } } }));
vi.mock("~/utils/stripe.server", () => ({ createStripeCustomer: vi.fn(), isStripeConfigured: vi.fn(() => false) }));
vi.mock("~/utils/url.server", () => ({ getAbsoluteUrl: vi.fn(() => "https://example.test") }));
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
vi.mock("~/modules/emails/services/TransactionalEmailQueue.server", () => ({ queueTransactionalEmail: vi.fn() }));
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({ default: { WELCOME_EMAIL: { parse: vi.fn(() => ({ subject: "Welcome", body: "Welcome" })) } } }));
vi.mock("~/locale/mail-translator.server", () => ({
getMailTranslator: vi.fn(async () => ({ t: (key: string) => key, locale: "en" })),
getMailTranslatorFromRequest: vi.fn(),
}));
vi.mock("~/modules/ipAddress/services/IpAddressService.server", () => ({ default: { log: vi.fn() } }));
vi.mock("~/utils/api/.server/TenantTypesApi", () => ({ TenantTypesApi: { setTenantTypes: vi.fn() } }));
vi.mock("~/utils/leads/leadToken.server", () => ({ verifyLeadToken: (...args: unknown[]) => mocks.verifyLeadToken(...args) }));
vi.mock("~/utils/leads/convertLead.server", () => ({ recordExistingTenantLeadConversion: (...args: unknown[]) => mocks.recordExistingTenantLeadConversion(...args) }));
import { validateRegistration } from "./authService";
const request = new Request("https://example.test/register");
function appConfiguration(slug: { require: boolean; type: "tenant" | "user" } = { require: false, type: "tenant" }) {
return {
auth: {
requireEmailVerification: false,
requireOrganization: false,
requireName: false,
slug,
},
};
}
describe("validateRegistration i18n errors", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getAppConfiguration.mockResolvedValue(appConfiguration());
mocks.findInBlacklist.mockResolvedValue(null);
mocks.getUserByEmail.mockResolvedValue(null);
mocks.getTenantBySlug.mockResolvedValue(null);
mocks.createTenant.mockResolvedValue({ id: "tenant_1", name: "Ada", slug: "ada" });
mocks.register.mockResolvedValue({ id: "user_1", email: "ada@example.test", locale: "en" });
mocks.createTenantUser.mockResolvedValue({});
mocks.getAllRoles.mockResolvedValue([]);
mocks.verifyLeadToken.mockReturnValue(null);
mocks.recordExistingTenantLeadConversion.mockResolvedValue({});
mocks.leadFindUnique.mockResolvedValue(null);
delete process.env.LEAD_CONVERSION_ENABLED;
});
it.each([
["companyMaxLength", { company: "a".repeat(101) }],
["firstNameMaxLength", { firstName: "a".repeat(51) }],
["lastNameMaxLength", { lastName: "a".repeat(51) }],
])("uses a translation key for %s", async (errorKey, registrationData) => {
await expect(
validateRegistration({
request,
registrationData: { email: "ada@example.test", password: "Password123!", ...registrationData },
addToTrialOrFreePlan: false,
})
).rejects.toThrow(`account.register.errors.${errorKey}`);
});
it.each([
["tenant", "slugRequired"],
["user", "usernameRequired"],
] as const)("uses a translation key when the %s slug is required", async (slugType, errorKey) => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: true, type: slugType }));
await expect(
validateRegistration({
request,
registrationData: { email: "ada@example.test", password: "Password123!" },
addToTrialOrFreePlan: false,
})
).rejects.toThrow(`account.register.errors.${errorKey}`);
});
it.each([
["tenant", "slugTaken"],
["user", "usernameTaken"],
] as const)("uses a translation key when the %s slug is already taken", async (slugType, errorKey) => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: true, type: slugType }));
mocks.getTenantBySlug.mockResolvedValueOnce({ id: "tenant_1" });
await expect(
validateRegistration({
request,
registrationData: { email: "ada@example.test", password: "Password123!", slug: "ada" },
addToTrialOrFreePlan: false,
})
).rejects.toThrow(`account.register.errors.${errorKey}`);
});
it.each([
["reserved", "slugReserved", "admin"],
["too short", "slugTooShort", "x"],
] as const)("rejects a user-provided slug that is %s, independent of auth.slug.require", async (_label, errorKey, slug) => {
await expect(
validateRegistration({
request,
registrationData: { email: "ada@example.test", password: "Password123!", slug },
addToTrialOrFreePlan: false,
})
).rejects.toThrow(`account.register.errors.${errorKey}`);
});
it.each([
["only plan id", { email: "ada@example.test", password: "Password123!", leadPlanId: "plan_pro" }],
["missing token", { email: "ada@example.test", password: "Password123!", leadId: "lead_1" }],
["token for a different lead", { email: "ada@example.test", password: "Password123!", leadId: "lead_1", leadToken: "signed" }],
["converted lead", { email: "ada@example.test", password: "Password123!", leadId: "lead_1", leadToken: "signed" }],
["email mismatch", { email: "ada@example.test", password: "Password123!", leadId: "lead_1", leadToken: "signed" }],
])("rejects invalid lead conversion context: %s", async (name, registrationData) => {
if (name === "token for a different lead") {
mocks.verifyLeadToken.mockReturnValueOnce({ leadId: "other_lead", planId: "plan_token" });
} else if (name === "converted lead") {
mocks.verifyLeadToken.mockReturnValueOnce({ leadId: "lead_1", planId: "plan_token" });
mocks.leadFindUnique.mockResolvedValueOnce({ email: "ada@example.test", convertedToTenantId: "tenant_existing" });
} else if (name === "email mismatch") {
mocks.verifyLeadToken.mockReturnValueOnce({ leadId: "lead_1", planId: "plan_token" });
mocks.leadFindUnique.mockResolvedValueOnce({ email: "grace@example.test", convertedToTenantId: null });
}
await expect(
validateRegistration({
request,
registrationData,
addToTrialOrFreePlan: false,
})
).rejects.toThrow("account.register.errors.invalidLeadConversion");
expect(mocks.recordExistingTenantLeadConversion).not.toHaveBeenCalled();
});
it("records valid self-service lead conversion with token plan precedence", async () => {
mocks.verifyLeadToken.mockReturnValueOnce({ leadId: "lead_1", planId: "plan_from_token" });
mocks.leadFindUnique.mockResolvedValueOnce({ email: "ada@example.test", convertedToTenantId: null });
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
leadId: "lead_1",
leadToken: "signed",
leadPlanId: "plan_from_form",
},
addToTrialOrFreePlan: false,
})
).resolves.toMatchObject({ verificationRequired: false, registered: { tenant: { id: "tenant_1" }, user: { id: "user_1" } } });
expect(mocks.recordExistingTenantLeadConversion).toHaveBeenCalledWith({
leadId: "lead_1",
tenantId: "tenant_1",
planId: "plan_from_token",
conversionPath: "self-service",
});
});
});
@@ -0,0 +1,31 @@
import { DocsSidebar } from "~/application/sidebar/DocsSidebar";
import { SideBarItem } from "~/application/sidebar/SidebarItem";
import type { CommandAction } from "~/services/command-registry/commandRegistry";
export function getDocCommands(): CommandAction[] {
const commands: CommandAction[] = [];
DocsSidebar().forEach((item) => {
commands.push(...getCommandsFromItem(item, [], []));
});
return commands;
}
function getCommandsFromItem(item: SideBarItem, commands: CommandAction[], parent: string[]) {
if (item.path && item.title) {
let description = item.description ?? "";
if (parent.length > 0) {
description = parent.join(" / ");
}
commands.push({
id: item.path,
name: item.title,
shortcut: [],
subtitle: description,
});
}
item.items?.forEach((subItem) => {
return getCommandsFromItem(subItem, commands, [...parent, item.title]);
});
return commands;
}
@@ -0,0 +1,33 @@
import { db } from "../db.server";
import { getTenant } from "../db/tenants.db.server";
import { getAvailableTenantSlug } from "./tenantService";
export async function getAvailableTenantInboundAddress(name: string) {
const slug = await getAvailableTenantSlug({ name });
const slugWithDots = slug.split("-").join(".");
let address = slugWithDots;
let tries = 1;
do {
const existingAddress = await db.tenantInboundAddress.findUnique({
where: {
address,
},
});
if (existingAddress !== null) {
address = slugWithDots + tries.toString();
tries++;
} else {
break;
}
} while (true);
return address;
}
export async function getTenantDefaultInboundAddress(tenantId: string) {
const tenant = await getTenant(tenantId);
let address: string | null = null;
if (tenant?.inboundAddresses && tenant?.inboundAddresses.length > 0) {
address = tenant.inboundAddresses[0].address;
}
return address;
}
@@ -0,0 +1,78 @@
import { getPlanFeatureUsage } from "./.server/subscriptionService";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import { cache } from "../cache.server";
import { TenantSubscriptionWithDetails } from "../db/tenantSubscriptions.db.server";
const DEFAULT_RATE_LIMIT_PER_MINUTE = 60;
const DEFAULT_RATE_LIMIT_PER_SECOND = 5;
function getCacheKey(apiKey: string, period: string, timestamp: number): string {
return `rateLimit:${apiKey}:${period}:${timestamp}`;
}
export async function rateLimitByKey({
apiKey,
tenantSubscription,
tenantId,
limitByMinute,
limitBySecond,
}: {
apiKey: string;
tenantSubscription: TenantSubscriptionWithDetails | null;
tenantId: string;
limitByMinute?: number;
limitBySecond?: number;
}): Promise<{
success: boolean;
error: string | null;
}> {
const currentTimestamp = Math.floor(Date.now() / 1000);
const minuteTimestamp = Math.floor(currentTimestamp / 60);
const secondTimestamp = currentTimestamp;
const minuteKey = getCacheKey(apiKey, "minute", minuteTimestamp);
const secondKey = getCacheKey(apiKey, "second", secondTimestamp);
let minuteCount = (cache.get(minuteKey)?.value as number) || 0;
let secondCount = (cache.get(secondKey)?.value as number) || 0;
if (limitByMinute === undefined) {
const feature = await getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerMinute, tenantSubscription);
if (!feature) {
limitByMinute = DEFAULT_RATE_LIMIT_PER_MINUTE;
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
limitByMinute = 0;
} else {
limitByMinute = feature.value;
}
}
if (limitBySecond === undefined) {
const feature = await getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerSecond, tenantSubscription);
if (!feature) {
limitBySecond = DEFAULT_RATE_LIMIT_PER_SECOND;
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
limitBySecond = 0;
} else {
limitBySecond = feature.value;
}
}
minuteCount += 1;
secondCount += 1;
if (limitByMinute !== 0 && minuteCount > limitByMinute) {
let tryAgainIn = 60 - (currentTimestamp % 60);
return { success: false, error: `You've exceeded the ${limitByMinute} request/min rate limit, try again in ${tryAgainIn} seconds` };
}
if (limitBySecond !== 0 && secondCount > limitBySecond) {
return { success: false, error: `You've exceeded the ${limitBySecond} request/sec rate limit` };
}
cache.set(minuteKey, { value: minuteCount, metadata: { createdTime: Date.now() } }, { ttl: 60 * 1000 });
cache.set(secondKey, { value: secondCount, metadata: { createdTime: Date.now() } }, { ttl: 1000 });
return { success: true, error: null };
}
@@ -0,0 +1,126 @@
import { describe, expect, test, vi } from "vitest";
vi.mock("~/utils/db/entities/entities.db.server", () => ({ getAllEntities: vi.fn() }));
vi.mock("~/utils/db/permissions/permissions.db.server", () => ({ createPermissions: vi.fn(), getAllPermissions: vi.fn() }));
vi.mock("~/utils/db/permissions/rolePermissions.db.server", () => ({ createRolePermission: vi.fn() }));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ createRole: vi.fn(), getAllRoles: vi.fn(), getRoleByName: vi.fn() }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({ createUserRole: vi.fn() }));
vi.mock("~/utils/db/tenants.db.server", () => ({ adminGetAllTenants: vi.fn() }));
vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsers: vi.fn() }));
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getEntityPermissions: vi.fn() }));
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
import { DefaultPermission, DefaultPermissions } from "~/application/dtos/shared/DefaultPermissions";
import { defaultAdminRoles, defaultAppRoles, defaultPermissions } from "./rolesAndPermissionsService";
function duplicates(values: string[]) {
const seen = new Set<string>();
const duplicateValues = new Set<string>();
values.forEach((value) => {
if (seen.has(value)) {
duplicateValues.add(value);
}
seen.add(value);
});
return Array.from(duplicateValues).sort();
}
describe("default roles matrix", () => {
test("seeded admin roles are unique, typed as admin, and are not assigned to new users", () => {
const adminRoleNames = defaultAdminRoles.map((role) => role.name);
expect(duplicates(adminRoleNames), "duplicate default admin role names").toEqual([]);
expect(adminRoleNames.sort(), "seeded admin roles must match DefaultAdminRoles").toEqual(Object.values(DefaultAdminRoles).sort());
expect(
defaultAdminRoles.filter((role) => role.type !== "admin").map((role) => `${role.name}:${role.type}`),
"admin roles with unexpected type"
).toEqual([]);
expect(
defaultAdminRoles.filter((role) => role.assignToNewUsers).map((role) => role.name),
"operator admin roles must be assigned intentionally"
).toEqual([]);
});
test("seeded app roles are unique, typed as app, and only User is assigned to new users", () => {
const appRoleNames = defaultAppRoles.map((role) => role.name);
expect(duplicates(appRoleNames), "duplicate default app role names").toEqual([]);
expect(appRoleNames.sort(), "seeded app roles must match DefaultAppRoles").toEqual(Object.values(DefaultAppRoles).sort());
expect(
defaultAppRoles.filter((role) => role.type !== "app").map((role) => `${role.name}:${role.type}`),
"app roles with unexpected type"
).toEqual([]);
expect(
defaultAppRoles.filter((role) => role.assignToNewUsers).map((role) => role.name),
"only User should be assigned to new app users"
).toEqual([DefaultAppRoles.User]);
});
});
describe("default permissions matrix", () => {
const defaultRoleNames = new Set([...defaultAdminRoles.map((role) => role.name), ...defaultAppRoles.map((role) => role.name)]);
function seedDefinitionsFor(permissionName: DefaultPermission) {
return defaultPermissions.filter((permission) => permission.name === permissionName);
}
test("permission names are unique and every inRoles target exists in default roles", () => {
const permissionNames = defaultPermissions.map((permission) => permission.name);
const orphanRoleTargets = defaultPermissions.flatMap((permission) =>
permission.inRoles.filter((roleName) => !defaultRoleNames.has(roleName)).map((roleName) => `${permission.name} -> ${roleName}`)
);
expect(duplicates(permissionNames), "duplicate default permission names").toEqual([]);
expect(orphanRoleTargets, "permissions targeting missing default roles").toEqual([]);
});
test("every DefaultPermissions entry has exactly one seed definition", () => {
const seedCounts = new Map(defaultPermissions.map((permission) => [permission.name, 0]));
defaultPermissions.forEach((permission) => {
seedCounts.set(permission.name, (seedCounts.get(permission.name) ?? 0) + 1);
});
const missingSeedDefinitions = DefaultPermissions.filter((permissionName) => !seedCounts.has(permissionName));
const duplicateSeedDefinitions = Array.from(seedCounts.entries())
.filter(([, count]) => count !== 1)
.map(([permissionName, count]) => `${permissionName}:${count}`);
const nonEnumSeedDefinitions = defaultPermissions
.map((permission) => permission.name)
.filter((permissionName) => !DefaultPermissions.includes(permissionName));
expect(missingSeedDefinitions, "DefaultPermissions entries missing from defaultPermissions seeds").toEqual([]);
expect(duplicateSeedDefinitions, "DefaultPermissions entries with duplicate seed definitions").toEqual([]);
expect(nonEnumSeedDefinitions, "defaultPermissions seed definitions missing from DefaultPermissions").toEqual([]);
});
test("audit permissions are seeded once and assigned only to intended default roles", () => {
const adminAuditPermissionName = "admin.auditTrails.view";
const appAuditPermissionName = "app.settings.auditTrails.view";
const expectedAdminAuditRoles = [DefaultAdminRoles.SuperAdmin];
const expectedAppAuditRoles = [DefaultAppRoles.SuperUser, DefaultAppRoles.Admin];
const adminAuditSeedDefinitions = seedDefinitionsFor(adminAuditPermissionName);
const appAuditSeedDefinitions = seedDefinitionsFor(appAuditPermissionName);
const adminAuditEnumEntries = DefaultPermissions.filter((permissionName) => permissionName === adminAuditPermissionName);
const appAuditEnumEntries = DefaultPermissions.filter((permissionName) => permissionName === appAuditPermissionName);
expect(adminAuditSeedDefinitions, `${adminAuditPermissionName} must have exactly one defaultPermissions seed definition`).toHaveLength(1);
expect(adminAuditEnumEntries, `${adminAuditPermissionName} must exist exactly once in DefaultPermissions`).toHaveLength(1);
expect(
[...(adminAuditSeedDefinitions[0]?.inRoles ?? [])].sort(),
`${adminAuditPermissionName} must target SuperAdmin only`
).toEqual([...expectedAdminAuditRoles].sort());
expect(appAuditSeedDefinitions, `${appAuditPermissionName} must have exactly one defaultPermissions seed definition`).toHaveLength(1);
expect(appAuditEnumEntries, `${appAuditPermissionName} must exist exactly once in DefaultPermissions`).toHaveLength(1);
expect([...(appAuditSeedDefinitions[0]?.inRoles ?? [])].sort(), `${appAuditPermissionName} must target SuperUser and Admin only`).toEqual(
[...expectedAppAuditRoles].sort()
);
expect(appAuditSeedDefinitions[0]?.inRoles, `${appAuditPermissionName} must not target User`).not.toContain(DefaultAppRoles.User);
expect(appAuditSeedDefinitions[0]?.inRoles, `${appAuditPermissionName} must not target Billing Admin`).not.toContain(DefaultAppRoles.BillingAdmin);
});
});
@@ -0,0 +1,252 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
vi.mock("~/utils/db/entities/entities.db.server", () => ({ getAllEntities: vi.fn() }));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ createRole: vi.fn(), getAllRoles: vi.fn() }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({ createUserRoleAssignments: vi.fn() }));
vi.mock("~/utils/db/tenants.db.server", () => ({ adminGetAllTenants: vi.fn() }));
vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsers: vi.fn() }));
vi.mock("~/utils/db.server", () => ({
db: {
role: {
findMany: vi.fn(),
},
permission: {
createMany: vi.fn(),
findMany: vi.fn(),
},
rolePermission: {
createMany: vi.fn(),
},
},
}));
vi.mock("~/utils/cache.server", () => ({ clearCacheKey: vi.fn() }));
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getEntityPermissions: vi.fn() }));
vi.mock("@toolctrl/db/permissions-seed.server", async () => {
const actual = await vi.importActual<typeof import("@toolctrl/db/permissions-seed.server")>("@toolctrl/db/permissions-seed.server");
return {
...actual,
syncDefaultRolesAndPermissions: vi.fn(async () => ({
roleCount: actual.defaultAdminRoleSeeds.length + actual.defaultAppRoleSeeds.length,
permissionCount: actual.defaultPermissionSeeds.length,
createdPermissions: 0,
createdRolePermissions: 0,
})),
};
});
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
import { createUserRoleAssignments } from "~/utils/db/permissions/userRoles.db.server";
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
import { adminGetAllUsers } from "~/utils/db/users.db.server";
import { db } from "~/utils/db.server";
import { clearCacheKey } from "~/utils/cache.server";
import { getEntityPermissions } from "~/utils/helpers/PermissionsHelper";
import { syncDefaultRolesAndPermissions } from "@toolctrl/db/permissions-seed.server";
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
import { defaultAdminRoles, defaultAppRoles, defaultPermissions, seedRolesAndPermissions, type RolesAndPermissionsSeedDiagnosticEvent } from "./rolesAndPermissionsService";
const getAllEntitiesMock = vi.mocked(getAllEntities);
const getAllRolesMock = vi.mocked(getAllRoles);
const createUserRoleAssignmentsMock = vi.mocked(createUserRoleAssignments);
const adminGetAllTenantsMock = vi.mocked(adminGetAllTenants);
const adminGetAllUsersMock = vi.mocked(adminGetAllUsers);
const dbMock = vi.mocked(db);
const clearCacheKeyMock = vi.mocked(clearCacheKey);
const getEntityPermissionsMock = vi.mocked(getEntityPermissions);
const syncDefaultRolesAndPermissionsMock = vi.mocked(syncDefaultRolesAndPermissions);
type RoleRow = Awaited<ReturnType<typeof getAllRoles>>[number];
const roleBase = {
type: "admin",
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
description: "Test role",
order: 0,
isDefault: true,
assignToNewUsers: false,
permissions: [],
};
const adminRoleRows = defaultAdminRoles.map((role, index) => ({ ...roleBase, id: `admin-role-${index}`, name: role.name, type: role.type }) as RoleRow);
const appRoleRows = defaultAppRoles.map((role, index) => ({ ...roleBase, id: `app-role-${index}`, name: role.name, type: role.type }) as RoleRow);
const allRoleRows = [...adminRoleRows, ...appRoleRows];
function serializedDiagnostics(events: RolesAndPermissionsSeedDiagnosticEvent[]) {
return JSON.stringify(events);
}
describe("seedRolesAndPermissions diagnostics", () => {
beforeEach(() => {
vi.clearAllMocks();
getAllRolesMock.mockImplementation(async (type?: string) => {
if (type === "admin") return adminRoleRows;
if (type === "app") return appRoleRows;
return allRoleRows;
});
dbMock.permission.createMany.mockResolvedValue({ count: 3 } as never);
dbMock.permission.findMany.mockResolvedValue([
{ id: "permission-widget-view", name: "app.widget.view" },
{ id: "permission-report-view", name: "app.report.view" },
{ id: "permission-report-read", name: "app.report.read" },
] as never);
dbMock.role.findMany.mockResolvedValue(
[
{ id: "admin-role-super-admin", name: DefaultAdminRoles.SuperAdmin },
{ id: "app-role-super-user", name: DefaultAppRoles.SuperUser },
{ id: "app-role-admin", name: DefaultAppRoles.Admin },
{ id: "app-role-user", name: DefaultAppRoles.User },
] as never
);
dbMock.rolePermission.createMany.mockResolvedValue({ count: 12 } as never);
getAllEntitiesMock.mockResolvedValue([
{ id: "entity-1", type: "widget" } as Awaited<ReturnType<typeof getAllEntities>>[number],
{ id: "entity-2", type: "report" } as Awaited<ReturnType<typeof getAllEntities>>[number],
]);
getEntityPermissionsMock
.mockResolvedValueOnce([{ name: "app.widget.view", description: "View widgets" }])
.mockResolvedValueOnce([
{ name: "app.report.view", description: "View reports" },
{ name: "app.report.read", description: "Read reports" },
]);
adminGetAllUsersMock.mockResolvedValue({
items: [
{ id: "admin-user-id", email: "admin@email.com", admin: { userId: "admin-user-id" }, passwordHash: "hashed-password" },
{ id: "other-admin-id", email: "other@example.com", admin: { userId: "other-admin-id" }, token: "sk_live_secret" },
{ id: "app-user-id", email: "app@example.com", admin: null },
] as Awaited<ReturnType<typeof adminGetAllUsers>>["items"],
pagination: {} as Awaited<ReturnType<typeof adminGetAllUsers>>["pagination"],
});
adminGetAllTenantsMock.mockResolvedValue([
{
id: "tenant-1",
users: [
{ userId: "admin-user-id" } as Awaited<ReturnType<typeof adminGetAllTenants>>[number]["users"][number],
{ userId: "app-user-id" } as Awaited<ReturnType<typeof adminGetAllTenants>>[number]["users"][number],
],
} as Awaited<ReturnType<typeof adminGetAllTenants>>[number],
]);
createUserRoleAssignmentsMock.mockResolvedValue({ count: adminRoleRows.length + 2 * appRoleRows.length } as never);
syncDefaultRolesAndPermissionsMock.mockResolvedValue({
roleCount: defaultAdminRoles.length + defaultAppRoles.length,
permissionCount: defaultPermissions.length,
createdPermissions: 0,
createdRolePermissions: 0,
} as Awaited<ReturnType<typeof syncDefaultRolesAndPermissions>>);
});
test("emits bounded start and success counts without credential fields or raw user records", async () => {
const diagnostics = vi.fn();
await seedRolesAndPermissions({ adminEmail: "admin@email.com", diagnostics });
expect(syncDefaultRolesAndPermissionsMock).toHaveBeenCalledOnce();
const events = diagnostics.mock.calls.map(([event]) => event as RolesAndPermissionsSeedDiagnosticEvent);
expect(events).toEqual([
{
phase: "start",
adminRoleCount: defaultAdminRoles.length,
appRoleCount: defaultAppRoles.length,
defaultPermissionCount: defaultPermissions.length,
dynamicEntityPermissionCount: 0,
adminUserAssignmentCount: 0,
tenantUserAssignmentCount: 0,
},
{
phase: "success",
adminRoleCount: adminRoleRows.length,
appRoleCount: appRoleRows.length,
defaultPermissionCount: defaultPermissions.length,
dynamicEntityPermissionCount: 3,
adminUserAssignmentCount: adminRoleRows.length,
tenantUserAssignmentCount: 2 * appRoleRows.length,
},
]);
expect(serializedDiagnostics(events)).not.toContain("password");
expect(serializedDiagnostics(events)).not.toContain("token");
expect(serializedDiagnostics(events)).not.toContain("hashed-password");
expect(serializedDiagnostics(events)).not.toContain("sk_live_secret");
expect(serializedDiagnostics(events)).not.toContain("admin-user-id");
const defaultAppPermissionCount = defaultPermissions.filter((permission) => permission.type === "app").length;
expect(dbMock.permission.createMany).toHaveBeenCalledWith({
data: [
{
order: defaultAppPermissionCount + 3,
name: "app.widget.view",
description: "View widgets",
type: "widget",
isDefault: true,
entityId: null,
},
{
order: defaultAppPermissionCount + 4,
name: "app.report.view",
description: "View reports",
type: "report",
isDefault: true,
entityId: null,
},
{
order: defaultAppPermissionCount + 5,
name: "app.report.read",
description: "Read reports",
type: "report",
isDefault: true,
entityId: null,
},
],
skipDuplicates: true,
});
expect(dbMock.rolePermission.createMany).toHaveBeenCalledWith({
data: expect.arrayContaining([
{ permissionId: "permission-widget-view", roleId: "admin-role-super-admin" },
{ permissionId: "permission-widget-view", roleId: "app-role-super-user" },
{ permissionId: "permission-widget-view", roleId: "app-role-admin" },
{ permissionId: "permission-widget-view", roleId: "app-role-user" },
]),
skipDuplicates: true,
});
expect(clearCacheKeyMock).toHaveBeenCalledWith("permission:app.widget.view");
expect(createUserRoleAssignmentsMock).toHaveBeenCalledWith(
expect.arrayContaining([
{ userId: "admin-user-id", roleId: adminRoleRows[0]?.id, tenantId: null },
{ userId: "admin-user-id", roleId: appRoleRows[0]?.id, tenantId: "tenant-1" },
{ userId: "app-user-id", roleId: appRoleRows[0]?.id, tenantId: "tenant-1" },
])
);
});
test("preserves the legacy adminEmail argument while assigning the seeded admin user", async () => {
await seedRolesAndPermissions("admin@email.com");
expect(createUserRoleAssignmentsMock).toHaveBeenCalledWith(
expect.arrayContaining([{ userId: "admin-user-id", roleId: adminRoleRows[0]?.id, tenantId: null }])
);
});
test("emits failure diagnostics and rethrows the original seed error", async () => {
const diagnostics = vi.fn();
const originalError = new Error("seed failed without password token literals");
getAllEntitiesMock.mockRejectedValueOnce(originalError);
await expect(seedRolesAndPermissions({ adminEmail: "admin@email.com", diagnostics })).rejects.toBe(originalError);
const events = diagnostics.mock.calls.map(([event]) => event as RolesAndPermissionsSeedDiagnosticEvent);
expect(events).toHaveLength(2);
expect(events[1]).toMatchObject({
phase: "failure",
adminRoleCount: adminRoleRows.length,
appRoleCount: appRoleRows.length,
defaultPermissionCount: defaultPermissions.length,
dynamicEntityPermissionCount: 0,
adminUserAssignmentCount: 0,
tenantUserAssignmentCount: 0,
error: originalError,
});
expect(serializedDiagnostics(events)).not.toContain("password");
expect(serializedDiagnostics(events)).not.toContain("token");
expect(serializedDiagnostics(events)).not.toContain("hashed-password");
expect(serializedDiagnostics(events)).not.toContain("sk_live_secret");
});
});
@@ -0,0 +1,207 @@
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import {
defaultAdminRoleSeeds,
defaultAppRoleSeeds,
defaultPermissionSeedDescriptors,
syncDefaultRolesAndPermissions,
type DefaultPermissionSeed,
type DefaultRoleSeed,
} from "@toolctrl/db/permissions-seed.server";
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
import { createUserRoleAssignments, type UserRoleAssignment } from "~/utils/db/permissions/userRoles.db.server";
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
import { adminGetAllUsers } from "~/utils/db/users.db.server";
import { db } from "~/utils/db.server";
import { clearCacheKey } from "~/utils/cache.server";
import { getEntityPermissions } from "~/utils/helpers/PermissionsHelper";
export type CreateRoleDto = DefaultRoleSeed;
export const defaultAdminRoles: CreateRoleDto[] = [...defaultAdminRoleSeeds];
export const defaultAppRoles: CreateRoleDto[] = [...defaultAppRoleSeeds];
export type CreatePermissionDto = Omit<DefaultPermissionSeed, "name" | "type"> & {
name: DefaultPermission;
type: string;
};
export const defaultPermissions: CreatePermissionDto[] = defaultPermissionSeedDescriptors.map((permission) => ({
...permission,
name: permission.name as DefaultPermission,
}));
export type RolesAndPermissionsSeedDiagnosticPhase = "start" | "success" | "failure";
export type RolesAndPermissionsSeedDiagnosticEvent = {
phase: RolesAndPermissionsSeedDiagnosticPhase;
adminRoleCount?: number;
appRoleCount?: number;
defaultPermissionCount?: number;
dynamicEntityPermissionCount?: number;
adminUserAssignmentCount?: number;
tenantUserAssignmentCount?: number;
error?: unknown;
};
export type RolesAndPermissionsSeedDiagnostics = (event: RolesAndPermissionsSeedDiagnosticEvent) => void | Promise<void>;
export type SeedRolesAndPermissionsOptions = {
adminEmail?: string;
diagnostics?: RolesAndPermissionsSeedDiagnostics;
};
function toSeedRolesAndPermissionsOptions(adminEmailOrOptions?: string | SeedRolesAndPermissionsOptions): SeedRolesAndPermissionsOptions {
if (typeof adminEmailOrOptions === "string") {
return { adminEmail: adminEmailOrOptions };
}
return adminEmailOrOptions ?? {};
}
async function emitRolesAndPermissionsSeedDiagnostic(
diagnostics: RolesAndPermissionsSeedDiagnostics | undefined,
event: RolesAndPermissionsSeedDiagnosticEvent
): Promise<void> {
await diagnostics?.(event);
}
async function createDynamicEntityPermissions(permissions: { inRoles: string[]; name: string; description: string; type: string; order: number }[]): Promise<void> {
if (permissions.length === 0) {
return;
}
const permissionNames = [...new Set(permissions.map((permission) => permission.name))];
await db.permission.createMany({
data: permissions.map((permission) => ({
order: permission.order,
name: permission.name,
description: permission.description,
type: permission.type,
isDefault: true,
entityId: null,
})),
skipDuplicates: true,
});
permissionNames.forEach((permissionName) => {
clearCacheKey(`permission:${permissionName}`);
});
const createdOrExistingPermissions = await db.permission.findMany({
where: {
name: {
in: permissionNames,
},
},
select: {
id: true,
name: true,
},
});
const permissionByName = new Map(createdOrExistingPermissions.map((permission) => [permission.name, permission]));
const roleNames = [...new Set(permissions.flatMap((permission) => permission.inRoles))];
const roles = await db.role.findMany({
where: {
name: {
in: roleNames,
},
tenantId: null,
},
select: {
id: true,
name: true,
},
});
const roleByName = new Map(roles.map((role) => [role.name, role]));
const rolePermissionData = permissions.flatMap((permission) => {
const createdOrExistingPermission = permissionByName.get(permission.name);
if (!createdOrExistingPermission) {
return [];
}
return permission.inRoles.map((roleName) => {
const role = roleByName.get(roleName);
if (!role) {
throw new Error("Role required: " + roleName);
}
return {
permissionId: createdOrExistingPermission.id,
roleId: role.id,
};
});
});
if (rolePermissionData.length > 0) {
await db.rolePermission.createMany({
data: rolePermissionData,
skipDuplicates: true,
});
}
}
export async function seedRolesAndPermissions(adminEmailOrOptions?: string | SeedRolesAndPermissionsOptions): Promise<void> {
const { adminEmail, diagnostics } = toSeedRolesAndPermissionsOptions(adminEmailOrOptions);
const counts = {
adminRoleCount: defaultAdminRoles.length,
appRoleCount: defaultAppRoles.length,
defaultPermissionCount: defaultPermissions.length,
dynamicEntityPermissionCount: 0,
adminUserAssignmentCount: 0,
tenantUserAssignmentCount: 0,
};
await emitRolesAndPermissionsSeedDiagnostic(diagnostics, { phase: "start", ...counts });
try {
await syncDefaultRolesAndPermissions({ client: db });
const adminRoles = await getAllRoles("admin");
counts.adminRoleCount = adminRoles.length;
const appRoles = await getAllRoles("app");
counts.appRoleCount = appRoles.length;
const entities = await getAllEntities({ tenantId: null, active: true });
const entityPermissionGroups = await Promise.all(
entities.map(async (entity) =>
(await getEntityPermissions(entity)).map((permission) => ({
inRoles: [DefaultAdminRoles.SuperAdmin, DefaultAppRoles.SuperUser, DefaultAppRoles.Admin, DefaultAppRoles.User].map((f) => f.toString()),
name: permission.name as DefaultPermission,
description: permission.description,
type: entity.type,
}))
)
);
const appPermissionCount = defaultPermissions.filter((f) => f.type === "app").length;
const dynamicEntityPermissions = entityPermissionGroups.flat().map((permission, index) => ({
...permission,
order: appPermissionCount + index + 3,
}));
counts.dynamicEntityPermissionCount = dynamicEntityPermissions.length;
await createDynamicEntityPermissions(dynamicEntityPermissions);
const users = (await adminGetAllUsers()).items;
const userRoleAssignments: UserRoleAssignment[] = [];
users
.filter((f) => f.admin && adminEmail && f.email === adminEmail)
.forEach((user) => {
adminRoles.forEach((adminRole) => {
counts.adminUserAssignmentCount += 1;
userRoleAssignments.push({ userId: user.id, roleId: adminRole.id, tenantId: null });
});
});
const tenants = await adminGetAllTenants();
tenants.forEach((tenant) => {
tenant.users.forEach((tenantUser) => {
appRoles.forEach((appRole) => {
counts.tenantUserAssignmentCount += 1;
userRoleAssignments.push({ userId: tenantUser.userId, roleId: appRole.id, tenantId: tenant.id });
});
});
});
await createUserRoleAssignments(userRoleAssignments);
await emitRolesAndPermissionsSeedDiagnostic(diagnostics, { phase: "success", ...counts });
} catch (error) {
await emitRolesAndPermissionsSeedDiagnostic(diagnostics, { phase: "failure", ...counts, error });
throw error;
}
}
@@ -0,0 +1,76 @@
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
import { db } from "../db.server";
import { EntityWithDetails } from "../db/entities/entities.db.server";
import { createRow, getMaxRowFolio, getRow } from "../db/entities/rows.db.server";
import { createManualRowLog, createRowLog } from "../db/logs.db.server";
export async function getCreateNewRow({ entityName, createdByUserId, tenantId }: { entityName: string; createdByUserId: string; tenantId?: string | null }) {
const entity = await db.entity.findUnique({ where: { name: entityName } });
if (!entity) {
throw new Error("Entity required: " + entityName);
}
let folio = 1;
const maxFolio = await getMaxRowFolio({ tenantId: tenantId ?? null, entityId: entity.id });
if (maxFolio && maxFolio._max.folio !== null) {
folio = maxFolio._max.folio + 1;
}
return {
row: {
create: {
entityId: entity.id,
createdByUserId,
tenantId: tenantId ?? null,
folio,
},
},
};
}
export async function createNewRowWithEntity({
entity,
createdByUserId,
tenantId,
request,
nextFolio,
}: {
entity: EntityWithDetails;
createdByUserId: string | null;
tenantId?: string | null;
request?: Request;
nextFolio?: number;
}) {
const row = await createRow({
entity,
data: {
createdByUserId,
tenantId: tenantId ?? null,
properties: {},
dynamicProperties: [],
},
nextFolio,
});
const item = await getRow({ entityId: entity.id, id: row!.id, tenantId: tenantId ?? null });
if (row) {
if (request) {
await createRowLog(request, {
tenantId: tenantId ?? null,
createdByUserId,
action: DefaultLogActions.Created,
entity,
item,
});
} else {
await createManualRowLog(
{
tenantId: tenantId ?? null,
createdByUserId,
action: DefaultLogActions.Created + " " + entity.title,
entity,
item,
},
request
);
}
}
return row;
}
@@ -0,0 +1,18 @@
import { SetupItem } from "~/application/dtos/setup/SetupItem";
import { getAllSubscriptionProducts } from "../db/subscriptionProducts.db.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { t as i18nT } from "i18next";
export async function getSetupSteps(): Promise<SetupItem[]> {
return [await getPricingStep()];
}
async function getPricingStep(): Promise<SetupItem> {
let items = await getAllSubscriptionProducts();
return Promise.resolve({
title: i18nT("setup.pricing.title"),
description: i18nT("setup.pricing.description"),
completed: items.length > 0,
path: adminPath("settings/pricing", { mode: "host-aware" }),
});
}
@@ -0,0 +1,57 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const dbMock = vi.hoisted(() => ({
permission: { findMany: vi.fn() },
role: { findFirst: vi.fn(), create: vi.fn() },
rolePermission: { findFirst: vi.fn(), create: vi.fn() },
}));
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
import { SHK_ROLE_NAMES, SHK_ROLE_SEEDS, seedShkRolesForTenant } from "./shkRoles.server";
beforeEach(() => {
vi.clearAllMocks();
});
describe("SHK role definitions", () => {
it("defines the six partner-named roles with Geschaeftsfuehrer as admin tier", () => {
expect(SHK_ROLE_NAMES).toEqual(["Geschäftsführer", "Projektleiter", "Verwaltung", "Vertriebler", "Kundensupporter", "Monteur"]);
expect(SHK_ROLE_SEEDS.find((role) => role.name === "Geschäftsführer")?.tier).toBe("admin");
});
it("gives every role at least dashboard access as the P2 baseline", () => {
for (const role of SHK_ROLE_SEEDS) {
expect(role.permissionKeys).toContain("app.dashboard.view");
}
});
});
describe("seedShkRolesForTenant", () => {
it("creates the missing roles as tenant-scoped app roles and links resolvable permissions", async () => {
dbMock.permission.findMany.mockResolvedValue([{ id: "perm_dash", name: "app.dashboard.view" }]);
dbMock.role.findFirst.mockResolvedValue(null);
dbMock.role.create.mockImplementation(async ({ data }: { data: { name: string } }) => ({ id: `role_${data.name}` }));
dbMock.rolePermission.findFirst.mockResolvedValue(null);
dbMock.rolePermission.create.mockResolvedValue({});
const result = await seedShkRolesForTenant("t1");
expect(result.createdRoles).toBe(6);
expect(dbMock.role.create).toHaveBeenCalledTimes(6);
expect(dbMock.role.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ tenantId: "t1", name: "Geschäftsführer", type: "app", assignToNewUsers: false }) })
);
// Nur die aufloesbare Permission (dashboard) wird verknuepft.
expect(dbMock.rolePermission.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ permissionId: "perm_dash" }) }));
});
it("is idempotent: existing roles are not recreated", async () => {
dbMock.permission.findMany.mockResolvedValue([]);
dbMock.role.findFirst.mockResolvedValue({ id: "existing" });
const result = await seedShkRolesForTenant("t1");
expect(result.createdRoles).toBe(0);
expect(dbMock.role.create).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,110 @@
import { db } from "~/utils/db.server";
// R-P2b — SHK-Standard-Rollen (vom Partner genannt). PROVISORISCH/ANPASSBAR: datengetrieben, per
// Tenant als Template geseedet (upsert, idempotent). Die fachspezifischen Rechte (CRM/Leads/Projekte/
// Auftraege) haengen sich PRO PHASE an, sobald die Entitaeten existieren; bei P2 differenzieren nur die
// bereits vorhandenen App-/Settings-Rechte. Anpassbar ueber den Rollen-Editor (D-P2) oder durch Aendern
// dieser Definition + Re-Seed. Bulk-entfernbar ueber SHK_ROLE_NAMES (is_demo_data-Konvention, bis das
// Entity-Model TenantRole.is_template_origin angeglichen ist).
export type ShkRoleTier = "admin" | "elevated" | "standard";
export interface ShkRoleSeed {
readonly name: string;
// i18n-Key im Namespace-Format `settings:<key>` (Doppelpunkt!), gespeichert in Role.description;
// der Rollen-Editor löst ihn via t() auf (roleDisplayDescription). i18next adressiert ausgelagerte
// Namespaces mit ":" -- ein Punkt-Präfix landet im defaultNS und erschiene als nackter Key. Kein
// Klartext im Seed -> erfüllt die Hardcoded-String-Disziplin; Text liegt in settings.json.
readonly descriptionKey: string;
readonly tier: ShkRoleTier;
readonly permissionKeys: readonly string[];
}
const DASHBOARD = "app.dashboard.view";
export const SHK_ROLE_SEEDS: readonly ShkRoleSeed[] = [
{
name: "Geschäftsführer",
descriptionKey: "settings:shkRoles.geschaeftsfuehrer.description",
tier: "admin",
permissionKeys: [
DASHBOARD,
"app.settings.members.view",
"app.settings.members.create",
"app.settings.members.update",
"app.settings.members.delete",
"app.settings.roles.view",
"app.settings.roles.set",
"app.settings.groups.full",
"app.settings.account.view",
"app.settings.account.update",
"app.settings.subscription.view",
"app.settings.subscription.update",
"app.settings.subscription.invoices.view",
"app.settings.auditTrails.view",
],
},
{
name: "Projektleiter",
descriptionKey: "settings:shkRoles.projektleiter.description",
tier: "elevated",
permissionKeys: [DASHBOARD, "app.settings.members.view", "app.settings.groups.full", "app.settings.auditTrails.view"],
},
{
name: "Verwaltung",
descriptionKey: "settings:shkRoles.verwaltung.description",
tier: "elevated",
permissionKeys: [DASHBOARD, "app.settings.members.view", "app.settings.account.view", "app.settings.subscription.invoices.view"],
},
{
name: "Vertriebler",
descriptionKey: "settings:shkRoles.vertriebler.description",
tier: "standard",
permissionKeys: [DASHBOARD],
},
{
name: "Kundensupporter",
descriptionKey: "settings:shkRoles.kundensupporter.description",
tier: "standard",
permissionKeys: [DASHBOARD],
},
{
name: "Monteur",
descriptionKey: "settings:shkRoles.monteur.description",
tier: "standard",
permissionKeys: [DASHBOARD],
},
];
export const SHK_ROLE_NAMES: readonly string[] = SHK_ROLE_SEEDS.map((role) => role.name);
// Seedt die SHK-Rollen als App-Rollen eines Tenants (idempotent). Setzt fehlende Rollen + ihre
// vorhandenen Permission-Verknuepfungen auf; bestehende bleiben unberuehrt (anpassbar im Editor).
export async function seedShkRolesForTenant(tenantId: string): Promise<{ createdRoles: number }> {
const wantedKeys = [...new Set(SHK_ROLE_SEEDS.flatMap((role) => role.permissionKeys))];
const permissions = await db.permission.findMany({ where: { name: { in: wantedKeys } }, select: { id: true, name: true } });
const permissionIdByName = new Map(permissions.map((permission) => [permission.name, permission.id]));
let createdRoles = 0;
for (const [index, seed] of SHK_ROLE_SEEDS.entries()) {
let role = await db.role.findFirst({ where: { tenantId, name: seed.name, type: "app" }, select: { id: true } });
if (!role) {
role = await db.role.create({
data: { tenantId, name: seed.name, description: seed.descriptionKey, type: "app", assignToNewUsers: false, isDefault: false, order: 100 + index },
select: { id: true },
});
createdRoles++;
}
for (const key of seed.permissionKeys) {
const permissionId = permissionIdByName.get(key);
if (!permissionId) {
continue;
}
const existing = await db.rolePermission.findFirst({ where: { roleId: role.id, permissionId } });
if (!existing) {
await db.rolePermission.create({ data: { roleId: role.id, permissionId } });
}
}
}
return { createdRoles };
}
@@ -0,0 +1,81 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
getAvailableTenantSlug,
isReservedTenantChildRouteSlug,
isReservedTenantSlug,
normalizeTenantSlug,
validateDesiredTenantSlug,
} from "./tenantService";
import { db } from "../db.server";
vi.mock("../db.server", () => ({ db: { tenant: { count: vi.fn() } } }));
const countMock = vi.mocked(db.tenant.count);
vi.mock("../stripe.server", () => ({ deleteStripeCustomer: vi.fn() }));
vi.mock("../db/tenants.db.server", () => ({ deleteTenant: vi.fn() }));
vi.mock("../db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: vi.fn() }));
vi.mock("./.server/subscriptionService", () => ({ cancelTenantSubscription: vi.fn() }));
describe("tenant route slug reservations", () => {
it("normalizes slugs before checking top-level route reservations", () => {
expect(normalizeTenantSlug(" Settings ")).toBe("settings");
expect(isReservedTenantSlug("Admin")).toBe(true);
expect(isReservedTenantSlug("Acme")).toBe(false);
});
it("reserves tenant child routes used by canonical workspace pages", () => {
expect(isReservedTenantChildRouteSlug("settings")).toBe(true);
expect(isReservedTenantChildRouteSlug("CRM")).toBe(true);
expect(isReservedTenantChildRouteSlug("g")).toBe(true);
expect(isReservedTenantChildRouteSlug("customers")).toBe(false);
});
});
describe("validateDesiredTenantSlug", () => {
it("accepts a normal workspace name and returns the normalized slug", () => {
expect(validateDesiredTenantSlug("Acme Corp")).toEqual({ ok: true, slug: "acme-corp" });
expect(validateDesiredTenantSlug(" Beta Works ")).toEqual({ ok: true, slug: "beta-works" });
});
it("rejects reserved slugs with a typed reason", () => {
expect(validateDesiredTenantSlug("admin")).toEqual({ ok: false, reason: "reserved" });
expect(validateDesiredTenantSlug("API")).toEqual({ ok: false, reason: "reserved" });
expect(validateDesiredTenantSlug("settings")).toEqual({ ok: false, reason: "reserved" });
});
it("rejects empty and symbol-only input", () => {
expect(validateDesiredTenantSlug("")).toEqual({ ok: false, reason: "empty" });
expect(validateDesiredTenantSlug("!!!")).toEqual({ ok: false, reason: "empty" });
});
it("rejects single-character slugs as too short", () => {
expect(validateDesiredTenantSlug("x")).toEqual({ ok: false, reason: "too-short" });
});
});
describe("getAvailableTenantSlug", () => {
beforeEach(() => {
countMock.mockReset();
});
it("returns the name-derived slug when free", async () => {
countMock.mockResolvedValue(0);
await expect(getAvailableTenantSlug({ name: "Acme" })).resolves.toBe("acme");
});
it("appends a counter when the slug is already taken", async () => {
countMock.mockResolvedValueOnce(1).mockResolvedValueOnce(0);
await expect(getAvailableTenantSlug({ name: "Acme" })).resolves.toBe("acme1");
});
it("skips reserved desired slugs without a DB lookup and falls back to the name base", async () => {
countMock.mockResolvedValue(0);
// "admin" ist reserviert -> getExistingSlug kurzschliesst (kein count) -> Namens-Basis + Zaehler.
await expect(getAvailableTenantSlug({ name: "Acme", slug: "admin" })).resolves.toBe("acme1");
});
it("never returns an empty or numeric slug for symbol-only names", async () => {
countMock.mockResolvedValue(0);
await expect(getAvailableTenantSlug({ name: "!!!" })).resolves.toBe("workspace");
});
});
@@ -0,0 +1,111 @@
import UrlUtils from "../app/UrlUtils";
import { reservedTenantChildRouteSlugs, reservedTenantRouteSlugs } from "../app/PublicRouteSegments";
import { db } from "../db.server";
import { deleteTenant } from "../db/tenants.db.server";
import { getTenantSubscription } from "../db/tenantSubscriptions.db.server";
import { deleteStripeCustomer } from "../stripe.server";
import { TFunction } from "i18next";
import { cancelTenantSubscription } from "./.server/subscriptionService";
export function normalizeTenantSlug(slug: string) {
return UrlUtils.slugify(slug).toLowerCase();
}
export const reservedTenantSlugs = new Set(reservedTenantRouteSlugs.map((slug) => normalizeTenantSlug(slug)));
export const reservedTenantChildSlugs = new Set(reservedTenantChildRouteSlugs.map((slug) => normalizeTenantSlug(slug)));
export function isReservedTenantSlug(slug: string) {
return reservedTenantSlugs.has(normalizeTenantSlug(slug));
}
export function isReservedTenantChildRouteSlug(slug: string) {
return reservedTenantChildSlugs.has(normalizeTenantSlug(slug));
}
// Mindestlaenge eines Tenant-Slugs. Ein-Zeichen-Slugs kollidieren mit reservierten
// Kind-Routen (z.B. "/g") und sind als Workspace-URL ohnehin ungeeignet.
export const MIN_TENANT_SLUG_LENGTH = 2;
// Fallback-Basis, falls ein Firmenname keinen verwertbaren Slug ergibt (reine
// Sonderzeichen -> slugify liefert ""). Verhindert leere/numerische Slugs ("", "1").
const FALLBACK_TENANT_SLUG_BASE = "workspace";
function tenantSlugBaseFromName(name: string) {
const base = normalizeTenantSlug(name ?? "");
return base.length > 0 ? base : FALLBACK_TENANT_SLUG_BASE;
}
export type TenantSlugValidation = { ok: true; slug: string } | { ok: false; reason: "empty" | "too-short" | "reserved" };
// Synchrone Validierung eines vom Nutzer GEWAEHLTEN Slugs (Signup-Formular): liefert
// einen typisierten Grund fuer Klartext-Fehlermeldungen, statt den Wunsch still
// umzuschreiben. Die DB-Eindeutigkeitspruefung bleibt in getAvailableTenantSlug.
export function validateDesiredTenantSlug(input: string): TenantSlugValidation {
const slug = normalizeTenantSlug(input ?? "");
if (slug.length === 0) {
return { ok: false, reason: "empty" };
}
if (slug.length < MIN_TENANT_SLUG_LENGTH) {
return { ok: false, reason: "too-short" };
}
if (isReservedTenantSlug(slug)) {
return { ok: false, reason: "reserved" };
}
return { ok: true, slug };
}
export async function deleteAndCancelTenant({ tenantId, userId, t }: { tenantId: string; userId: string; t?: TFunction }) {
const tenantSubscription = await getTenantSubscription(tenantId);
await cancelAllTenantPlans({ t, tenantId, userId });
if (tenantSubscription?.stripeCustomerId) {
await deleteStripeCustomer(tenantSubscription?.stripeCustomerId);
}
return await deleteTenant(tenantId);
}
export async function cancelAllTenantPlans({ tenantId, userId, t }: { tenantId: string; userId: string; t?: TFunction }) {
const tenantSubscription = await getTenantSubscription(tenantId);
if (tenantSubscription?.products) {
await Promise.all(
tenantSubscription.products.map(async (tenantSubscriptionProduct) => {
await cancelTenantSubscription(tenantSubscriptionProduct.id, {
tenantId,
userId,
t,
});
})
);
}
}
export async function getAvailableTenantSlug({ name, slug }: { name: string; slug?: string }) {
const base = tenantSlugBaseFromName(name);
slug = slug === undefined ? base : normalizeTenantSlug(slug);
// Degenerierter Wunsch-Slug (leer nach Normalisierung) faellt auf die Namens-Basis zurueck.
if (slug.length === 0) {
slug = base;
}
let tries = 1;
do {
const existingSlug = await getExistingSlug(slug);
if (existingSlug) {
slug = base + tries.toString();
tries++;
} else {
break;
}
} while (true);
return slug;
}
export async function getExistingSlug(slug: string) {
if (isReservedTenantSlug(slug)) {
return true;
}
const existing = await db.tenant.count({
where: {
slug,
},
});
return existing > 0;
}
@@ -0,0 +1,78 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
const dbMock = vi.hoisted(() => ({
tenantUser: { findFirst: vi.fn(), update: vi.fn(), count: vi.fn() },
group: { updateMany: vi.fn() },
}));
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
import { deactivateTenantUser, reactivateTenantUser } from "./tenantUserLifecycle.server";
beforeEach(() => {
vi.clearAllMocks();
dbMock.tenantUser.update.mockResolvedValue({});
dbMock.group.updateMany.mockResolvedValue({ count: 0 });
});
describe("deactivateTenantUser", () => {
it("returns not-found when the member does not exist in the tenant", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue(null);
expect(await deactivateTenantUser({ tenantId: "t1", targetUserId: "u1" })).toEqual({ ok: false, reason: "not-found" });
expect(dbMock.tenantUser.update).not.toHaveBeenCalled();
});
it("is idempotent for an already inactive member", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", type: TenantUserType.MEMBER, status: TenantUserStatus.INACTIVE });
expect(await deactivateTenantUser({ tenantId: "t1", targetUserId: "u1" })).toEqual({ ok: false, reason: "already-inactive" });
expect(dbMock.tenantUser.update).not.toHaveBeenCalled();
});
it("blocks deactivating the last active admin/owner", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", type: TenantUserType.ADMIN, status: TenantUserStatus.ACTIVE });
dbMock.tenantUser.count.mockResolvedValue(0); // no other active privileged member
expect(await deactivateTenantUser({ tenantId: "t1", targetUserId: "u1" })).toEqual({ ok: false, reason: "last-admin" });
expect(dbMock.tenantUser.update).not.toHaveBeenCalled();
});
it("deactivates an admin when another active admin remains", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", type: TenantUserType.OWNER, status: TenantUserStatus.ACTIVE });
dbMock.tenantUser.count.mockResolvedValue(1);
expect(await deactivateTenantUser({ tenantId: "t1", targetUserId: "u1" })).toEqual({ ok: true });
expect(dbMock.tenantUser.update).toHaveBeenCalledWith({ where: { id: "m1" }, data: { status: TenantUserStatus.INACTIVE } });
});
it("deactivates a plain member without an admin-count check", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", type: TenantUserType.MEMBER, status: TenantUserStatus.ACTIVE });
expect(await deactivateTenantUser({ tenantId: "t1", targetUserId: "u1" })).toEqual({ ok: true });
expect(dbMock.tenantUser.count).not.toHaveBeenCalled();
});
it("reassigns owned groups to the successor before deactivating", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", type: TenantUserType.MEMBER, status: TenantUserStatus.ACTIVE });
dbMock.group.updateMany.mockResolvedValue({ count: 2 });
await deactivateTenantUser({ tenantId: "t1", targetUserId: "u1", reassignToUserId: "u2" });
expect(dbMock.group.updateMany).toHaveBeenCalledWith({ where: { tenantId: "t1", createdByUserId: "u1" }, data: { createdByUserId: "u2" } });
});
it("does not reassign to the same user", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", type: TenantUserType.MEMBER, status: TenantUserStatus.ACTIVE });
await deactivateTenantUser({ tenantId: "t1", targetUserId: "u1", reassignToUserId: "u1" });
expect(dbMock.group.updateMany).not.toHaveBeenCalled();
});
});
describe("reactivateTenantUser", () => {
it("reactivates an inactive member", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", status: TenantUserStatus.INACTIVE });
expect(await reactivateTenantUser({ tenantId: "t1", targetUserId: "u1" })).toEqual({ ok: true });
expect(dbMock.tenantUser.update).toHaveBeenCalledWith({ where: { id: "m1" }, data: { status: TenantUserStatus.ACTIVE } });
});
it("is idempotent for an already active member", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", status: TenantUserStatus.ACTIVE });
expect(await reactivateTenantUser({ tenantId: "t1", targetUserId: "u1" })).toEqual({ ok: false, reason: "already-active" });
});
});
@@ -0,0 +1,96 @@
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { db } from "~/utils/db.server";
// R-P2b — User-Lifecycle: Soft-Deaktivierung mit Last-Admin-Guard + optionalem Ownership-Reassign.
// Ein Tenant muss IMMER mindestens einen aktiven Owner/Admin behalten, sonst waere er handlungsunfaehig.
const PRIVILEGED_TYPES = [TenantUserType.OWNER, TenantUserType.ADMIN];
export type DeactivateTenantUserResult =
| { ok: true }
| { ok: false; reason: "not-found" | "already-inactive" | "last-admin" };
// Zaehlt aktive Owner/Admins eines Tenants (optional einen User ausschliessend).
export async function countActivePrivilegedMembers(tenantId: string, excludeUserId?: string): Promise<number> {
return db.tenantUser.count({
where: {
tenantId,
status: TenantUserStatus.ACTIVE,
type: { in: PRIVILEGED_TYPES },
...(excludeUserId ? { userId: { not: excludeUserId } } : {}),
},
});
}
// Reassign des tenant-eigenen Besitzes eines deaktivierten Users an einen Nachfolger. Bei P2 ist das
// die Gruppen-Ownership; Fach-Module (CRM/Projekte ab P6) haengen ihren Reassign hier an, wenn sie
// existieren. Gibt die Anzahl umgehaengter Datensaetze zurueck.
export async function reassignTenantUserOwnership({
tenantId,
fromUserId,
toUserId,
}: {
tenantId: string;
fromUserId: string;
toUserId: string;
}): Promise<number> {
const groups = await db.group.updateMany({
where: { tenantId, createdByUserId: fromUserId },
data: { createdByUserId: toUserId },
});
return groups.count;
}
export async function deactivateTenantUser({
tenantId,
targetUserId,
reassignToUserId,
}: {
tenantId: string;
targetUserId: string;
reassignToUserId?: string;
}): Promise<DeactivateTenantUserResult> {
const member = await db.tenantUser.findFirst({
where: { tenantId, userId: targetUserId },
select: { id: true, type: true, status: true },
});
if (!member) {
return { ok: false, reason: "not-found" };
}
if (member.status === TenantUserStatus.INACTIVE) {
return { ok: false, reason: "already-inactive" };
}
if (PRIVILEGED_TYPES.includes(member.type)) {
const otherActiveAdmins = await countActivePrivilegedMembers(tenantId, targetUserId);
if (otherActiveAdmins === 0) {
return { ok: false, reason: "last-admin" };
}
}
if (reassignToUserId && reassignToUserId !== targetUserId) {
await reassignTenantUserOwnership({ tenantId, fromUserId: targetUserId, toUserId: reassignToUserId });
}
await db.tenantUser.update({ where: { id: member.id }, data: { status: TenantUserStatus.INACTIVE } });
return { ok: true };
}
export async function reactivateTenantUser({
tenantId,
targetUserId,
}: {
tenantId: string;
targetUserId: string;
}): Promise<{ ok: true } | { ok: false; reason: "not-found" | "already-active" }> {
const member = await db.tenantUser.findFirst({
where: { tenantId, userId: targetUserId },
select: { id: true, status: true },
});
if (!member) {
return { ok: false, reason: "not-found" };
}
if (member.status === TenantUserStatus.ACTIVE) {
return { ok: false, reason: "already-active" };
}
await db.tenantUser.update({ where: { id: member.id }, data: { status: TenantUserStatus.ACTIVE } });
return { ok: true };
}
@@ -0,0 +1,53 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { deleteUserWithItsTenants } from "./userService";
import { getMyTenants, getTenantWithUsers } from "../db/tenants.db.server";
import { deleteUser } from "../db/users.db.server";
import { deleteAndCancelTenant } from "./tenantService";
vi.mock("../db.server", () => ({ db: {} }));
vi.mock("../cache.server", () => ({ clearCacheKey: vi.fn() }));
vi.mock("../db/permissions/userRoles.db.server", () => ({ createUserRoles: vi.fn(), deleteAllUserRoles: vi.fn() }));
vi.mock("../db/tenants.db.server", () => ({ getMyTenants: vi.fn(), getTenantWithUsers: vi.fn() }));
vi.mock("../db/users.db.server", () => ({ deleteUser: vi.fn() }));
vi.mock("./tenantService", () => ({ deleteAndCancelTenant: vi.fn() }));
const soloTenant = { id: "tenant_solo", name: "Solo" };
const sharedTenant = { id: "tenant_shared", name: "Shared" };
describe("deleteUserWithItsTenants", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getMyTenants).mockResolvedValue([soloTenant, sharedTenant] as never);
vi.mocked(getTenantWithUsers).mockImplementation(async (tenantId) => {
if (tenantId === soloTenant.id) {
return { users: [{ userId: "user_1" }] } as never;
}
return { users: [{ userId: "user_1" }, { userId: "user_2" }] } as never;
});
vi.mocked(deleteAndCancelTenant).mockResolvedValue(soloTenant as never);
vi.mocked(deleteUser).mockResolvedValue({ id: "user_1" } as never);
});
it("cancels and deletes only tenants where the deleted user is the sole tenant user", async () => {
const result = await deleteUserWithItsTenants("user_1");
expect(deleteAndCancelTenant).toHaveBeenCalledTimes(1);
expect(deleteAndCancelTenant).toHaveBeenCalledWith({ tenantId: soloTenant.id, userId: "user_1" });
expect(deleteUser).toHaveBeenCalledWith("user_1");
expect(result.deletedTenants).toEqual([soloTenant]);
});
it("does not delete shared tenants when another tenant user remains", async () => {
await deleteUserWithItsTenants("user_1");
expect(deleteAndCancelTenant).not.toHaveBeenCalledWith({ tenantId: sharedTenant.id, userId: "user_1" });
});
it("does not delete the user if tenant cancellation fails", async () => {
vi.mocked(deleteAndCancelTenant).mockRejectedValueOnce(new Error("stripe unavailable") as never);
await expect(deleteUserWithItsTenants("user_1")).rejects.toThrow("stripe unavailable");
expect(deleteUser).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,63 @@
import { Tenant, Role } from "@toolctrl/db/prisma-browser";
import { getMyTenants, getTenantWithUsers } from "../db/tenants.db.server";
import { UserWithoutPassword, deleteUser } from "../db/users.db.server";
import { deleteAndCancelTenant } from "./tenantService";
import { db } from "../db.server";
import { createUserRoles, deleteAllUserRoles } from "../db/permissions/userRoles.db.server";
import { clearCacheKey } from "../cache.server";
export async function deleteUserWithItsTenants(id: string) {
const userTenants = await getMyTenants(id);
const deletedAccounts = await Promise.all(
userTenants.map(async (tenant) => {
const tenantUsers = await getTenantWithUsers(tenant.id);
if (tenantUsers?.users.length === 1 && tenantUsers.users[0].userId === id) {
return await deleteAndCancelTenant({
tenantId: tenant.id,
userId: id,
});
}
})
);
const deletedTenants: Tenant[] = [];
deletedAccounts.forEach((deletedAccount) => {
if (deletedAccount) {
deletedTenants.push(deletedAccount);
}
});
return {
deletedUser: await deleteUser(id),
deletedTenants,
};
}
export async function setUserRoles({
user,
roles,
isAdmin,
type,
}: {
user: UserWithoutPassword;
roles: { role: Role; tenantId: string | null }[];
isAdmin: boolean;
type: "admin" | "app";
}) {
if (user.admin && !isAdmin) {
await db.adminUser.delete({ where: { userId: user.id } });
} else if (!user.admin && isAdmin) {
await db.adminUser.create({ data: { userId: user.id } });
}
await deleteAllUserRoles(user.id, type);
return await createUserRoles(
user.id,
roles.map(({ role, tenantId }) => ({
id: role.id,
tenantId,
}))
).then((item) => {
clearCacheKey(`user:${user.id}`);
clearCacheKey(`userRoles:${user.id}:${null}`);
return item;
});
}
@@ -0,0 +1,179 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/utils/services/.server/featureFlagsRequest.server", () => ({
isFeatureFlagEnabled: vi.fn(),
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({
t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${JSON.stringify(values)}` : key),
})),
}));
vi.mock("~/utils/db/permissions/permissions.db.server", () => ({
getAllPermissions: vi.fn(),
}));
vi.mock("~/utils/db/permissions/rolePermissions.db.server", () => ({
setRolePermissions: vi.fn(),
}));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({
createRole: vi.fn(),
deleteRole: vi.fn(),
getNextRolesOrder: vi.fn(),
getRole: vi.fn(),
getTenantAppRoleByName: vi.fn(),
updateRole: vi.fn(),
}));
vi.mock("~/utils/db/logs.db.server", () => ({
createAdminLog: vi.fn(),
}));
import { createAdminLog } from "~/utils/db/logs.db.server";
import { getAllPermissions } from "~/utils/db/permissions/permissions.db.server";
import { setRolePermissions } from "~/utils/db/permissions/rolePermissions.db.server";
import { createRole, deleteRole, getNextRolesOrder, getRole, getTenantAppRoleByName, updateRole } from "~/utils/db/permissions/roles.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { createWorkspaceRole, deleteWorkspaceRole, requireWorkspaceRolesBuilderAccess, updateWorkspaceRole } from "./workspaceRoles.server";
const request = new Request("https://example.com/acme/settings/roles?token=secret&password=hunter2");
const params = { tenant: "acme" };
const tenantId = "tenant_1";
async function expectResponseRejection(promise: Promise<unknown>, status: number, text: string) {
await expect(promise).rejects.toMatchObject({ status });
await promise.catch(async (error) => {
expect(error).toBeInstanceOf(Response);
await expect((error as Response).text()).resolves.toContain(text);
});
}
function expectNoRoleMutations() {
expect(createRole).not.toHaveBeenCalled();
expect(updateRole).not.toHaveBeenCalled();
expect(deleteRole).not.toHaveBeenCalled();
expect(setRolePermissions).not.toHaveBeenCalled();
expect(createAdminLog).not.toHaveBeenCalled();
}
describe("workspace role builder policy", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(verifyUserHasPermission).mockResolvedValue(true);
vi.mocked(getNextRolesOrder).mockResolvedValue(7);
vi.mocked(getTenantAppRoleByName).mockResolvedValue(null);
vi.mocked(getAllPermissions).mockResolvedValue([{ name: "app.settings.members.view", type: "app" }] as never);
});
it("requires the role-setting permission (no feature-flag gate)", async () => {
await expect(requireWorkspaceRolesBuilderAccess({ request, params, tenantId })).resolves.toEqual({ tenantId });
expect(verifyUserHasPermission).toHaveBeenCalledWith(request, "app.settings.roles.set", tenantId);
});
it("creates tenant-owned workspace roles with app permissions", async () => {
vi.mocked(createRole).mockResolvedValue({ id: "role_1", name: "Workspace editor", type: "app" } as never);
await expect(
createWorkspaceRole({
request,
tenantId,
data: { name: " Workspace editor ", description: "Can edit workspace data", type: "app", permissionNames: ["app.settings.members.view"] },
})
).resolves.toMatchObject({ id: "role_1" });
expect(createRole).toHaveBeenCalledWith({
order: 7,
name: "Workspace editor",
description: "Can edit workspace data",
assignToNewUsers: false,
type: "app",
isDefault: false,
tenantId,
});
expect(setRolePermissions).toHaveBeenCalledWith("role_1", ["app.settings.members.view"]);
});
it("still rejects admin role type tampering before storage checks", async () => {
await expectResponseRejection(
createWorkspaceRole({
request,
tenantId,
data: { name: "Admin", description: "", type: "admin", permissionNames: ["app.settings.members.view"] },
}),
400,
"settings.rolesAndPermissions.errors.appRolesOnly",
);
expectNoRoleMutations();
});
it("updates and deletes only tenant-owned non-default app roles", async () => {
vi.mocked(getRole).mockResolvedValue({ id: "role_1", name: "Workspace editor", type: "app", isDefault: false, tenantId, permissions: [] } as never);
vi.mocked(updateRole).mockResolvedValue({ id: "role_1", name: "Workspace editor", type: "app" } as never);
vi.mocked(deleteRole).mockResolvedValue({ id: "role_1", name: "Workspace editor", type: "app" } as never);
await updateWorkspaceRole({
request,
tenantId,
roleId: "role_1",
data: { name: "Workspace editor", description: "Updated", type: "app", permissionNames: ["app.settings.members.view"] },
});
await deleteWorkspaceRole({ request, tenantId, roleId: "role_1" });
expect(updateRole).toHaveBeenCalledWith("role_1", {
name: "Workspace editor",
description: "Updated",
assignToNewUsers: false,
type: "app",
});
expect(deleteRole).toHaveBeenCalledWith("role_1");
});
it("blocks role updates outside the current tenant", async () => {
vi.mocked(getRole).mockResolvedValue({ id: "role_1", name: "Other tenant", type: "app", isDefault: false, tenantId: "tenant_2", permissions: [] } as never);
await expectResponseRejection(
updateWorkspaceRole({
request,
tenantId,
roleId: "role_1",
data: { name: "Workspace editor", description: "Updated", type: "app", permissionNames: ["app.settings.members.view"] },
}),
404,
"settings.rolesAndPermissions.errors.roleNotFound"
);
expect(updateRole).not.toHaveBeenCalled();
});
it("rejects duplicate role names with localized interpolation before storage mutation", async () => {
vi.mocked(getTenantAppRoleByName).mockResolvedValueOnce({ id: "role_existing", name: "Workspace editor", type: "app" } as never);
await expectResponseRejection(
createWorkspaceRole({
request,
tenantId,
data: { name: "Workspace editor", description: "", type: "app", permissionNames: ["app.settings.members.view"] },
}),
400,
'settings.rolesAndPermissions.errors.existingRole:{"name":"Workspace editor"}',
);
expectNoRoleMutations();
});
it("rejects non-app permission names with localized interpolation before storage mutation", async () => {
await expectResponseRejection(
createWorkspaceRole({
request,
tenantId,
data: { name: "Workspace editor", description: "", type: "app", permissionNames: ["admin.roles.delete"] },
}),
400,
'settings.rolesAndPermissions.errors.invalidAppPermissions:{"permissions":"admin.roles.delete"}',
);
expectNoRoleMutations();
});
});
@@ -0,0 +1,144 @@
import type { TFunction } from "i18next";
import { Params } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { createAdminLog } from "~/utils/db/logs.db.server";
import { getAllPermissions } from "~/utils/db/permissions/permissions.db.server";
import { setRolePermissions } from "~/utils/db/permissions/rolePermissions.db.server";
import { createRole, deleteRole, getNextRolesOrder, getRole, getTenantAppRoleByName, updateRole } from "~/utils/db/permissions/roles.db.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
export type WorkspaceRoleMutationInput = {
name: string;
description: string;
assignToNewUsers?: boolean;
type?: "admin" | "app";
permissionNames: string[];
};
export type WorkspaceRoleAccessArgs = {
request: Request;
params: Params;
tenantId: string;
};
const WORKSPACE_ROLES_PERMISSION = "app.settings.roles.set";
// Flag-Gate (workspace-roles) ENTFERNT 2026-06-22: Tenant-eigene Rollen sind P2-Kernfunktion fuer ALLE
// Tenants -> nur noch die Permission `app.settings.roles.set` entscheidet (kein Feature-Flag-Kill-Switch
// mehr). Hintergrund: der eigentliche Mehrwert (Fach-Rechte zum Zuweisen) waechst erst mit den Modulen ab
// P6-P9; der Builder selbst soll aber jedem Tenant offenstehen.
export async function requireWorkspaceRolesBuilderAccess({ request, tenantId }: WorkspaceRoleAccessArgs) {
await verifyUserHasPermission(request, WORKSPACE_ROLES_PERMISSION, tenantId);
return { tenantId };
}
export async function createWorkspaceRole({ request, tenantId, data }: { request: Request; tenantId: string; data: WorkspaceRoleMutationInput }) {
const { t } = await getTranslations(request);
assertAppRoleInput(data.type, t);
const name = normalizeRoleName(data.name, t);
await assertUniqueRoleName({ name, tenantId, t });
await assertAppPermissionNames(data.permissionNames, t);
const role = await createRole({
order: await getNextRolesOrder("app", tenantId),
name,
description: data.description,
assignToNewUsers: data.assignToNewUsers ?? false,
type: "app",
isDefault: false,
tenantId,
});
await setRolePermissions(role.id, data.permissionNames);
await logWorkspaceRoleMutation(request, "Workspace Role Created", tenantId, role.id, role.name, data.permissionNames.length);
return role;
}
export async function updateWorkspaceRole({ request, tenantId, roleId, data }: { request: Request; tenantId: string; roleId: string; data: WorkspaceRoleMutationInput }) {
const { t } = await getTranslations(request);
assertAppRoleInput(data.type, t);
const existing = await getExistingMutableAppRole(roleId, tenantId, t);
const name = normalizeRoleName(data.name, t);
await assertUniqueRoleName({ name, tenantId, currentRoleId: roleId, t });
await assertAppPermissionNames(data.permissionNames, t);
const role = await updateRole(roleId, {
name,
description: data.description,
assignToNewUsers: data.assignToNewUsers ?? false,
type: "app",
});
await setRolePermissions(existing.id, data.permissionNames);
await logWorkspaceRoleMutation(request, "Workspace Role Updated", tenantId, role.id, role.name, data.permissionNames.length);
return role;
}
export async function deleteWorkspaceRole({ request, tenantId, roleId }: { request: Request; tenantId: string; roleId: string }) {
const { t } = await getTranslations(request);
const existing = await getExistingMutableAppRole(roleId, tenantId, t);
const role = await deleteRole(existing.id);
await logWorkspaceRoleMutation(request, "Workspace Role Deleted", tenantId, role.id, role.name, existing.permissions.length);
return role;
}
function assertAppRoleInput(type: "admin" | "app" | undefined, t: TFunction) {
if (type === "admin") {
throw new Response(t("settings.rolesAndPermissions.errors.appRolesOnly"), { status: 400 });
}
}
function normalizeRoleName(name: string, t: TFunction) {
const normalized = name.trim();
if (!normalized) {
throw new Response(t("settings.rolesAndPermissions.errors.roleNameRequired"), { status: 400 });
}
return normalized;
}
async function assertUniqueRoleName({ name, tenantId, currentRoleId, t }: { name: string; tenantId: string; currentRoleId?: string; t: TFunction }) {
const existing = await getTenantAppRoleByName(name, tenantId);
if (existing && existing.id !== currentRoleId) {
throw new Response(t("settings.rolesAndPermissions.errors.existingRole", { name }), { status: 400 });
}
}
async function assertAppPermissionNames(permissionNames: string[], t: TFunction) {
const appPermissions = await getAllPermissions("app");
const allowedNames = new Set(appPermissions.map((permission) => permission.name));
const invalid = permissionNames.filter((name) => !allowedNames.has(name));
if (invalid.length > 0) {
throw new Response(t("settings.rolesAndPermissions.errors.invalidAppPermissions", { permissions: invalid.join(", ") }), { status: 400 });
}
}
async function getExistingMutableAppRole(roleId: string, tenantId: string, t: TFunction) {
const existing = await getRole(roleId);
if (!existing) {
throw new Response(t("settings.rolesAndPermissions.errors.roleNotFound"), { status: 404 });
}
if (existing.type !== "app") {
throw new Response(t("settings.rolesAndPermissions.errors.appRolesOnly"), { status: 400 });
}
if (existing.isDefault) {
throw new Response(t("settings.rolesAndPermissions.errors.defaultRoleImmutable"), { status: 400 });
}
if (existing.tenantId !== tenantId) {
throw new Response(t("settings.rolesAndPermissions.errors.roleNotFound"), { status: 404 });
}
return existing;
}
async function logWorkspaceRoleMutation(request: Request, action: string, tenantId: string, roleId: string, roleName: string, permissionCount: number) {
await createAdminLog(
request,
action,
JSON.stringify({
tenantId,
roleId,
roleName,
permissionCount,
})
);
}