1046 lines
33 KiB
TypeScript
1046 lines
33 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
|
|
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { Prisma, Role, Tenant, TenantInboundAddress, TenantUser } from "@hivegrid/db/prisma-browser";
|
|
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
|
|
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
|
import { TenantUserJoined } from "~/application/enums/tenants/TenantUserJoined";
|
|
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
|
import { db, dbRead } from "~/utils/db.server";
|
|
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
|
import RowFiltersHelper from "../helpers/RowFiltersHelper";
|
|
import { createUserRole } from "./permissions/userRoles.db.server";
|
|
import { invalidateUserPermissionCache } from "./permissions/permission-cache.server";
|
|
import { TenantSubscriptionWithDetails, createTenantSubscription } from "./tenantSubscriptions.db.server";
|
|
import { UserSimple, UserWithRoles } from "./users.db.server";
|
|
import { isReservedTenantSlug, normalizeTenantSlug } from "../services/tenantService";
|
|
import TenantModelHelper from "../helpers/models/TenantModelHelper";
|
|
import { cachified } from "../cache.server";
|
|
import { emitPluginHookFireAndForget } from "~/modules/plugins/services/.server/pluginHookPublisher";
|
|
import { PLUGIN_HOOK_TENANT_CREATED } from "@hivegrid/plugin-runtime";
|
|
import { publishTenantInvalidation, TENANT_SNAPSHOT_SAFETY_TTL_SECONDS } from "./tenant-cache.server";
|
|
|
|
const TENANT_SNAPSHOT_SAFETY_TTL_MS = TENANT_SNAPSHOT_SAFETY_TTL_SECONDS * 1_000;
|
|
const TENANT_IDENTIFIER_CREATE_ATTEMPTS = 100;
|
|
const ADMIN_TENANT_HYDRATION_BATCH_SIZE = 10;
|
|
const FALLBACK_TENANT_SLUG_BASE = "workspace";
|
|
|
|
class TenantIdentifierCollisionError extends Error {
|
|
constructor(cause: unknown) {
|
|
super("Tenant identifier already exists", { cause });
|
|
this.name = "TenantIdentifierCollisionError";
|
|
}
|
|
}
|
|
|
|
export class TenantSlugCollisionError extends Error {
|
|
constructor() {
|
|
super("Tenant slug already exists");
|
|
this.name = "TenantSlugCollisionError";
|
|
}
|
|
}
|
|
|
|
export type TenantSimple = {
|
|
id: string;
|
|
name: string;
|
|
slug: string;
|
|
icon: string | null;
|
|
logo: string | null;
|
|
deactivatedReason: string | null;
|
|
active: boolean;
|
|
theme: string | null;
|
|
themeConfig: string | null;
|
|
};
|
|
|
|
export type TenantWithProfile = Tenant;
|
|
|
|
export type TenantWithDetails = Tenant & {
|
|
inboundAddresses: TenantInboundAddress[];
|
|
users: (TenantUser & {
|
|
user: UserSimple;
|
|
})[];
|
|
subscription: TenantSubscriptionWithDetails | null;
|
|
};
|
|
|
|
const adminTenantUsageSelect = {
|
|
...TenantModelHelper.selectSimpleTenantProperties,
|
|
createdAt: true,
|
|
users: {
|
|
select: {
|
|
user: { select: { email: true } },
|
|
},
|
|
},
|
|
subscription: {
|
|
select: {
|
|
products: {
|
|
select: {
|
|
id: true,
|
|
endsAt: true,
|
|
subscriptionProduct: { select: { title: true } },
|
|
prices: {
|
|
select: {
|
|
subscriptionPrice: {
|
|
select: { price: true, currency: true, billingPeriod: true },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
_count: { select: { events: true } },
|
|
} satisfies Prisma.TenantSelect;
|
|
|
|
export type TenantWithUsage = Prisma.TenantGetPayload<{ select: typeof adminTenantUsageSelect }>;
|
|
|
|
export type TenantSessionIdentity = Pick<Tenant, "id" | "name" | "slug" | "active" | "deactivatedReason">;
|
|
|
|
export type TenantUserWithUser = TenantUser & {
|
|
user: UserWithRoles;
|
|
};
|
|
|
|
export type TenantUserWithDetails = TenantUser & {
|
|
tenant: Tenant;
|
|
user: UserSimple;
|
|
};
|
|
|
|
export async function getTenantsInIds(ids: string[]): Promise<TenantWithDetails[]> {
|
|
return await db.tenant.findMany({
|
|
where: { id: { in: ids } },
|
|
include: {
|
|
...TenantModelHelper.includeTenantWithDetails,
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function adminGetAllTenants(): Promise<TenantWithDetails[]> {
|
|
const roots = await db.tenant.findMany({
|
|
select: { id: true },
|
|
orderBy: { createdAt: "desc" },
|
|
});
|
|
return hydrateAdminTenantDetails(roots.map((tenant) => tenant.id));
|
|
}
|
|
|
|
export async function adminGetAllTenantsIdsAndNames(): Promise<{ id: string; name: string; slug: string }[]> {
|
|
// Admin-only enumeration used for picklists and audit views — replica-safe.
|
|
// Called AFTER auth has already resolved the admin user via the write client,
|
|
// so the replica-lag read-after-write hazard does not apply here.
|
|
return await dbRead.tenant.findMany({
|
|
select: { id: true, name: true, slug: true },
|
|
});
|
|
}
|
|
|
|
export async function adminGetAllActiveTenantSimple(): Promise<TenantSimple[]> {
|
|
// Admin tenant-switcher listing used post-auth — replica-safe.
|
|
// The admin user identity itself was loaded on the write client in the
|
|
// session-resolution path; this enumeration is purely informational.
|
|
return await dbRead.tenant.findMany({
|
|
where: { active: true },
|
|
select: TenantModelHelper.selectSimpleTenantProperties,
|
|
orderBy: { name: "asc" },
|
|
});
|
|
}
|
|
|
|
export async function adminGetAllTenantsWithUsage(
|
|
filters?: FiltersDto,
|
|
pagination?: { page: number; pageSize: number }
|
|
): Promise<{ items: TenantWithUsage[]; pagination: PaginationDto }> {
|
|
const rootWhere: Prisma.TenantWhereInput = RowFiltersHelper.getFiltersCondition(filters) ?? {};
|
|
const hasRootFilter = Object.keys(rootWhere).length > 0;
|
|
const userId = filters?.properties.find((f) => f.name === "userId")?.value ?? filters?.query ?? "";
|
|
const hasRelationFilter = Boolean(userId);
|
|
const page = pagination?.page ?? 1;
|
|
const pageSize = pagination?.pageSize ?? 10;
|
|
let items: TenantWithUsage[];
|
|
let totalItems: number;
|
|
|
|
if (!hasRelationFilter) {
|
|
const [roots, count] = await Promise.all([
|
|
db.tenant.findMany({
|
|
skip: pagination ? pageSize * (page - 1) : undefined,
|
|
take: pagination ? pageSize : undefined,
|
|
where: rootWhere,
|
|
select: { id: true },
|
|
orderBy: { createdAt: "desc" },
|
|
}),
|
|
db.tenant.count({ where: rootWhere }),
|
|
]);
|
|
items = await hydrateAdminTenantUsage(roots.map((tenant) => tenant.id));
|
|
totalItems = count;
|
|
} else {
|
|
const [roots, rootMatches] = await Promise.all([
|
|
db.tenant.findMany({ select: { id: true }, orderBy: { createdAt: "desc" } }),
|
|
hasRootFilter ? db.tenant.findMany({ where: rootWhere, select: { id: true } }) : Promise.resolve([]),
|
|
]);
|
|
const rootMatchIds = new Set(rootMatches.map((tenant) => tenant.id));
|
|
const matchingIds = await filterAdminTenantIdsByRelation({
|
|
tenantIds: roots.map((tenant) => tenant.id),
|
|
rootMatchIds,
|
|
hasRootFilter,
|
|
userId,
|
|
});
|
|
totalItems = matchingIds.length;
|
|
const pageIds = pagination ? matchingIds.slice(pageSize * (page - 1), pageSize * page) : matchingIds;
|
|
items = await hydrateAdminTenantUsage(pageIds);
|
|
}
|
|
|
|
return {
|
|
items,
|
|
pagination: {
|
|
page,
|
|
pageSize,
|
|
totalItems,
|
|
totalPages: Math.ceil(totalItems / pageSize),
|
|
},
|
|
};
|
|
}
|
|
|
|
async function filterAdminTenantIdsByRelation({
|
|
tenantIds,
|
|
rootMatchIds,
|
|
hasRootFilter,
|
|
userId,
|
|
}: {
|
|
tenantIds: string[];
|
|
rootMatchIds: ReadonlySet<string>;
|
|
hasRootFilter: boolean;
|
|
userId: string;
|
|
}): Promise<string[]> {
|
|
const matchingIds: string[] = [];
|
|
const relationConditions: Prisma.TenantWhereInput[] = [];
|
|
if (userId) relationConditions.push({ users: { some: { userId } } });
|
|
|
|
for (let index = 0; index < tenantIds.length; index += ADMIN_TENANT_HYDRATION_BATCH_SIZE) {
|
|
const batch = tenantIds.slice(index, index + ADMIN_TENANT_HYDRATION_BATCH_SIZE);
|
|
const matches = await Promise.all(
|
|
batch.map(async (tenantId) => {
|
|
if (hasRootFilter && rootMatchIds.has(tenantId)) return true;
|
|
if (relationConditions.length === 0) return false;
|
|
return runWithRlsContext({ tenantId }, async () => {
|
|
const match = await db.tenant.findFirst({
|
|
where: { id: tenantId, OR: relationConditions },
|
|
select: { id: true },
|
|
});
|
|
return match !== null;
|
|
});
|
|
})
|
|
);
|
|
for (const [offset, matchesFilter] of matches.entries()) {
|
|
if (matchesFilter) matchingIds.push(batch[offset]!);
|
|
}
|
|
}
|
|
|
|
return matchingIds;
|
|
}
|
|
|
|
async function hydrateAdminTenantUsage(tenantIds: string[]): Promise<TenantWithUsage[]> {
|
|
const tenants: TenantWithUsage[] = [];
|
|
for (let index = 0; index < tenantIds.length; index += ADMIN_TENANT_HYDRATION_BATCH_SIZE) {
|
|
const batch = tenantIds.slice(index, index + ADMIN_TENANT_HYDRATION_BATCH_SIZE);
|
|
const hydrated = await Promise.all(
|
|
batch.map((tenantId) =>
|
|
runWithRlsContext({ tenantId }, () =>
|
|
db.tenant.findUnique({
|
|
where: { id: tenantId },
|
|
select: adminTenantUsageSelect,
|
|
})
|
|
)
|
|
)
|
|
);
|
|
for (const tenant of hydrated) {
|
|
if (tenant) tenants.push(tenant);
|
|
}
|
|
}
|
|
return tenants;
|
|
}
|
|
|
|
async function hydrateAdminTenantDetails(tenantIds: string[]): Promise<TenantWithDetails[]> {
|
|
const tenants: TenantWithDetails[] = [];
|
|
for (let index = 0; index < tenantIds.length; index += ADMIN_TENANT_HYDRATION_BATCH_SIZE) {
|
|
const batch = tenantIds.slice(index, index + ADMIN_TENANT_HYDRATION_BATCH_SIZE);
|
|
const hydrated = await Promise.all(
|
|
batch.map((tenantId) =>
|
|
runWithRlsContext({ tenantId }, () =>
|
|
db.tenant.findUnique({
|
|
where: { id: tenantId },
|
|
include: TenantModelHelper.includeTenantWithDetails,
|
|
})
|
|
)
|
|
)
|
|
);
|
|
for (const tenant of hydrated) {
|
|
if (tenant) tenants.push(tenant);
|
|
}
|
|
}
|
|
return tenants;
|
|
}
|
|
|
|
export async function getTenant(id: string): Promise<TenantWithDetails | null> {
|
|
return await cachified({
|
|
key: `tenant:${id}`,
|
|
ttl: TENANT_SNAPSHOT_SAFETY_TTL_MS,
|
|
getFreshValue: () =>
|
|
db.tenant.findUnique({
|
|
where: {
|
|
id,
|
|
},
|
|
include: {
|
|
...TenantModelHelper.includeTenantWithDetails,
|
|
},
|
|
}),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Resolves a tenant only through an active membership owned by the authenticated
|
|
* user. This intentionally bypasses the shared tenant snapshot cache: login and
|
|
* route authorization must never depend on whether another request warmed a
|
|
* process-wide cache entry.
|
|
*/
|
|
export async function getTenantSessionIdentityForUser({
|
|
userId,
|
|
tenant,
|
|
allowInactiveTenant = false,
|
|
}: {
|
|
userId: string;
|
|
tenant?: string | null;
|
|
allowInactiveTenant?: boolean;
|
|
}): Promise<TenantSessionIdentity | null> {
|
|
const normalizedUserId = userId.trim();
|
|
const normalizedTenant = tenant?.trim();
|
|
if (!normalizedUserId || (tenant !== undefined && !normalizedTenant)) {
|
|
return null;
|
|
}
|
|
|
|
const resolveMembership = async () => {
|
|
const membership = await db.tenantUser.findFirst({
|
|
where: {
|
|
userId: normalizedUserId,
|
|
status: TenantUserStatus.ACTIVE,
|
|
tenant: {
|
|
...(normalizedTenant ? { OR: [{ id: normalizedTenant }, { slug: normalizedTenant }] } : {}),
|
|
...(allowInactiveTenant ? {} : { active: true }),
|
|
},
|
|
},
|
|
select: {
|
|
tenant: {
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
slug: true,
|
|
active: true,
|
|
deactivatedReason: true,
|
|
},
|
|
},
|
|
},
|
|
orderBy: { tenant: { name: "asc" } },
|
|
});
|
|
return membership?.tenant ?? null;
|
|
};
|
|
|
|
// Request middleware normally supplies the user identity. Authentication
|
|
// completion runs before that middleware can observe the new session, so it
|
|
// binds the identity proven by the password/MFA/registration flow here.
|
|
if (getRlsExecutionContext()?.userId) {
|
|
return resolveMembership();
|
|
}
|
|
return runWithRlsContext({ userId: normalizedUserId }, resolveMembership);
|
|
}
|
|
|
|
type InvitationTenantIdentity = Pick<Tenant, "id" | "name" | "slug" | "active" | "deactivatedReason">;
|
|
|
|
/** Safe invitation projection. The verified invite capability must bind the tenant first. */
|
|
export async function getInvitationTenantIdentity(
|
|
tenantId: string,
|
|
options: { allowedInactiveReason?: "pending_owner" } = {}
|
|
): Promise<InvitationTenantIdentity | null> {
|
|
const normalizedTenantId = tenantId.trim();
|
|
if (!normalizedTenantId || getRlsExecutionContext()?.tenantId !== normalizedTenantId) {
|
|
return null;
|
|
}
|
|
const allowPendingOwnerReservation = options.allowedInactiveReason === "pending_owner";
|
|
return db.tenant.findFirst({
|
|
where: {
|
|
id: normalizedTenantId,
|
|
...(allowPendingOwnerReservation ? { OR: [{ active: true }, { active: false, deactivatedReason: "pending_owner" }] } : { active: true }),
|
|
},
|
|
select: { id: true, name: true, slug: true, active: true, deactivatedReason: true },
|
|
});
|
|
}
|
|
|
|
export async function requireTenant(id: string): Promise<TenantWithDetails> {
|
|
const tenant = await getTenant(id);
|
|
if (!tenant) {
|
|
throw new Error("Tenant not found: " + id);
|
|
}
|
|
return tenant;
|
|
}
|
|
|
|
export async function getTenantSimple(id: string): Promise<TenantSimple | null> {
|
|
return await cachified({
|
|
key: `tenantSimple:${id}`,
|
|
ttl: TENANT_SNAPSHOT_SAFETY_TTL_MS,
|
|
getFreshValue: () =>
|
|
db.tenant.findUnique({
|
|
where: { id },
|
|
select: TenantModelHelper.selectSimpleTenantProperties,
|
|
}),
|
|
});
|
|
}
|
|
|
|
export async function getTenantByIdOrSlug(id: string) {
|
|
return await cachified({
|
|
key: `tenantIdOrSlug:${id}`,
|
|
ttl: TENANT_SNAPSHOT_SAFETY_TTL_MS,
|
|
getFreshValue: () =>
|
|
db.tenant.findFirst({
|
|
where: {
|
|
OR: [{ id }, { slug: id }],
|
|
},
|
|
include: {
|
|
subscription: true,
|
|
},
|
|
}),
|
|
});
|
|
}
|
|
|
|
export async function getTenantBySlug(slug: string) {
|
|
return await db.tenant.findUnique({
|
|
where: {
|
|
slug,
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function getTenantWithProfile(id: string): Promise<TenantWithProfile | null> {
|
|
return await db.tenant.findUnique({
|
|
where: { id },
|
|
});
|
|
}
|
|
|
|
export async function getTenantWithUsers(id?: string) {
|
|
if (!id) {
|
|
return null;
|
|
}
|
|
return await db.tenant.findUnique({
|
|
where: {
|
|
id,
|
|
},
|
|
include: {
|
|
users: true,
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function getMyTenants(userId: string): Promise<TenantSimple[]> {
|
|
const tenantsAsMember = await db.tenant.findMany({
|
|
where: { active: true, users: { some: { userId, status: TenantUserStatus.ACTIVE } } },
|
|
select: TenantModelHelper.selectSimpleTenantProperties,
|
|
orderBy: { name: "asc" },
|
|
});
|
|
|
|
// await Promise.all(tenantsAsMember.map(async(tenant) => {
|
|
// const relatedTenants = await db.tenantRelationship.findFirst({
|
|
// where: { fromTenantId: tenant.id },
|
|
// include: { toTenant: true },
|
|
// });
|
|
// }));
|
|
|
|
return [...tenantsAsMember];
|
|
}
|
|
|
|
export async function getTenantUsersCount(tenantId: string) {
|
|
return await db.tenantUser.count({
|
|
where: { tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
|
});
|
|
}
|
|
|
|
export async function getTenantUsers(tenantId?: string | null, options: { includeInactive?: boolean } = {}): Promise<TenantUserWithUser[]> {
|
|
if (!tenantId) {
|
|
return [];
|
|
}
|
|
return await db.tenantUser.findMany({
|
|
where: {
|
|
tenantId,
|
|
...(options.includeInactive ? {} : { status: TenantUserStatus.ACTIVE, user: { active: true } }),
|
|
},
|
|
include: {
|
|
user: {
|
|
include: {
|
|
roles: { where: { tenantId }, include: { role: true } },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function getTenantUsersInTenantIds(tenantIds: string[]): Promise<TenantUserWithDetails[]> {
|
|
return await db.tenantUser.findMany({
|
|
where: {
|
|
tenantId: { in: tenantIds },
|
|
},
|
|
include: {
|
|
tenant: true,
|
|
user: { select: UserModelHelper.selectSimpleUserProperties },
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function getAllTenantUsers(): Promise<TenantUserWithUser[]> {
|
|
return await db.tenantUser.findMany({
|
|
include: {
|
|
user: {
|
|
include: {
|
|
roles: { include: { role: true } },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function getTenantUser(id?: string, tenantId?: string) {
|
|
if (!id) {
|
|
return null;
|
|
}
|
|
return await db.tenantUser.findFirst({
|
|
where: {
|
|
id,
|
|
...(tenantId ? { tenantId } : {}),
|
|
},
|
|
include: {
|
|
tenant: true,
|
|
user: true,
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function getTenantUserByIds(tenantId: string, userId: string) {
|
|
return await db.tenantUser.findFirst({
|
|
where: {
|
|
tenantId,
|
|
userId,
|
|
},
|
|
include: {
|
|
tenant: true,
|
|
user: true,
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function getTenantUserSimple({ tenantId, userId }: { tenantId: string; userId: string }) {
|
|
return await cachified({
|
|
key: `tenantUserSimple:${tenantId}:${userId}`,
|
|
ttl: TENANT_SNAPSHOT_SAFETY_TTL_MS,
|
|
getFreshValue: () =>
|
|
db.tenantUser
|
|
.findFirstOrThrow({
|
|
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, tenant: { active: true } },
|
|
select: { id: true, type: true },
|
|
})
|
|
.catch(() => null),
|
|
});
|
|
}
|
|
|
|
export async function getTenantMember(userId?: string, tenantId?: string) {
|
|
return await db.tenantUser.findFirst({
|
|
where: {
|
|
userId,
|
|
tenantId,
|
|
status: TenantUserStatus.ACTIVE,
|
|
tenant: { active: true },
|
|
},
|
|
include: {
|
|
tenant: true,
|
|
user: true,
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function getTenantUserType(userId: string, tenantId: string) {
|
|
return await db.tenantUser.findFirst({
|
|
where: {
|
|
userId,
|
|
tenantId,
|
|
status: TenantUserStatus.ACTIVE,
|
|
tenant: {
|
|
active: true,
|
|
},
|
|
},
|
|
select: { status: true, type: true },
|
|
});
|
|
}
|
|
|
|
export async function updateTenant(before: Tenant, data: { name?: string; icon?: string; slug?: string }) {
|
|
const update: Prisma.TenantUncheckedUpdateInput = {
|
|
name: data.name,
|
|
icon: data.icon,
|
|
slug: data.slug,
|
|
};
|
|
return await db.tenant
|
|
.update({
|
|
where: {
|
|
id: before.id,
|
|
},
|
|
data: update,
|
|
})
|
|
.then(async (item) => {
|
|
await publishTenantInvalidation(before.id, before.slug, item.slug);
|
|
return item;
|
|
});
|
|
}
|
|
|
|
export async function updateTenantAnrede(id: string, anrede: string) {
|
|
return await db.tenant
|
|
.update({
|
|
where: { id },
|
|
data: { anrede },
|
|
})
|
|
.then(async (item) => {
|
|
await publishTenantInvalidation(item.id, item.slug);
|
|
return item;
|
|
});
|
|
}
|
|
|
|
export async function createTenant({
|
|
name,
|
|
icon,
|
|
subscriptionCustomerId,
|
|
active,
|
|
deactivatedReason,
|
|
slug,
|
|
setup,
|
|
rlsUserId,
|
|
emitCreatedHook = true,
|
|
tenantId: preallocatedTenantId,
|
|
validateExistingReplay,
|
|
rejectSlugCollision = false,
|
|
}: {
|
|
name: string;
|
|
icon?: string;
|
|
subscriptionCustomerId?: string | undefined;
|
|
active?: boolean;
|
|
deactivatedReason?: string | null;
|
|
slug?: string;
|
|
setup?: (tenant: Tenant, tx: Prisma.TransactionClient) => Promise<Tenant | void>;
|
|
rlsUserId?: string;
|
|
emitCreatedHook?: boolean;
|
|
tenantId?: string;
|
|
validateExistingReplay?: (tenant: Tenant, tx: Prisma.TransactionClient) => Promise<void>;
|
|
rejectSlugCollision?: boolean;
|
|
}) {
|
|
// Under FORCE RLS, a tenant-scoped runtime user cannot enumerate other
|
|
// tenants to preflight globally unique identifiers. Generate candidates
|
|
// locally and let the database constraints arbitrate the race.
|
|
const availableSlug = initialTenantSlug({ name, slug });
|
|
const availableInboundAddress = initialTenantInboundAddress(name);
|
|
let tenant: Tenant | undefined;
|
|
let createdNewTenant = false;
|
|
let slugAttempt = 0;
|
|
let inboundAddressAttempt = 0;
|
|
|
|
for (let attempt = 0; attempt < TENANT_IDENTIFIER_CREATE_ATTEMPTS; attempt += 1) {
|
|
const tenantId = preallocatedTenantId ?? randomUUID();
|
|
const candidateSlug = rejectSlugCollision ? availableSlug : appendIdentifierSuffix(availableSlug, slugAttempt);
|
|
const candidateInboundAddress = appendIdentifierSuffix(availableInboundAddress, inboundAddressAttempt);
|
|
let createdRowInAttempt = false;
|
|
|
|
try {
|
|
tenant = await runWithTargetTenantRlsContext(tenantId, rlsUserId, () =>
|
|
db.$transaction(async (tx) => {
|
|
const created = await tx.tenant
|
|
.create({
|
|
data: {
|
|
id: tenantId,
|
|
name,
|
|
slug: candidateSlug,
|
|
icon,
|
|
active: active ?? true,
|
|
...(deactivatedReason !== undefined ? { deactivatedReason } : {}),
|
|
inboundAddresses: {
|
|
create: [{ address: candidateInboundAddress }],
|
|
},
|
|
},
|
|
})
|
|
.catch((error) => {
|
|
if (isUniqueConstraintViolation(error)) {
|
|
throw new TenantIdentifierCollisionError(error);
|
|
}
|
|
throw error;
|
|
});
|
|
createdRowInAttempt = true;
|
|
|
|
if (subscriptionCustomerId) {
|
|
await createTenantSubscription(created.id, subscriptionCustomerId);
|
|
}
|
|
|
|
if (!setup) {
|
|
return created;
|
|
}
|
|
|
|
const setupTenant = await setup(created, tx);
|
|
if (setupTenant) {
|
|
return setupTenant;
|
|
}
|
|
|
|
// Setup may deliberately activate the tenant as its final atomic
|
|
// provisioning step. Return the committed shape, not the stale row
|
|
// produced by the initial inactive insert.
|
|
return await tx.tenant.findUniqueOrThrow({ where: { id: created.id } });
|
|
})
|
|
);
|
|
createdNewTenant = true;
|
|
break;
|
|
} catch (error) {
|
|
// A setup callback may have populated request-local tenant snapshots
|
|
// before a later provisioning step rolled the transaction back. A
|
|
// create-time P2002 never exposed this candidate and must not evict a
|
|
// potentially unrelated tenant that owns the colliding slug.
|
|
if (createdRowInAttempt) {
|
|
await publishTenantInvalidation(tenantId, candidateSlug).catch(() => undefined);
|
|
}
|
|
if (!(error instanceof TenantIdentifierCollisionError)) {
|
|
throw error;
|
|
}
|
|
|
|
if (preallocatedTenantId) {
|
|
const replayedTenant = await replayExistingTenantSetup({
|
|
tenantId: preallocatedTenantId,
|
|
rlsUserId,
|
|
setup,
|
|
validateExistingReplay,
|
|
});
|
|
if (replayedTenant) {
|
|
tenant = replayedTenant;
|
|
break;
|
|
}
|
|
}
|
|
|
|
const collision = classifyTenantIdentifierCollision(error);
|
|
if (collision === "slug") {
|
|
if (rejectSlugCollision) {
|
|
throw new TenantSlugCollisionError();
|
|
}
|
|
slugAttempt += 1;
|
|
} else if (collision === "inbound-address") {
|
|
inboundAddressAttempt += 1;
|
|
} else if (collision !== "id") {
|
|
// Never guess which identifier lost a race. Guessing can silently
|
|
// rewrite a user-selected slug and can mask new unique constraints.
|
|
throw error;
|
|
}
|
|
|
|
if (attempt === TENANT_IDENTIFIER_CREATE_ATTEMPTS - 1) {
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!tenant) {
|
|
throw new Error("Could not allocate unique tenant identifiers");
|
|
}
|
|
|
|
if (emitCreatedHook && createdNewTenant) {
|
|
await emitTenantCreatedHook(tenant, rlsUserId);
|
|
}
|
|
|
|
return tenant;
|
|
}
|
|
|
|
export async function emitTenantCreatedHook(tenant: Tenant, rlsUserId?: string): Promise<void> {
|
|
// Phase 06 #22 — emit plugin hook `tenant.created` so installed
|
|
// plugins subscribed to the tenant lifecycle can react. Fire-and-
|
|
// forget: hook delivery failures never propagate into tenant create.
|
|
await runWithTargetTenantRlsContext(tenant.id, rlsUserId, () =>
|
|
emitPluginHookFireAndForget(
|
|
PLUGIN_HOOK_TENANT_CREATED,
|
|
{
|
|
tenantId: tenant.id,
|
|
slug: tenant.slug,
|
|
ownerEmail: null,
|
|
plan: null,
|
|
createdAt: tenant.createdAt.toISOString(),
|
|
},
|
|
{ tenantId: tenant.id, dispatchKey: `tenant:${tenant.id}:created` }
|
|
)
|
|
);
|
|
}
|
|
|
|
export async function createTenantUser(data: { tenantId: string; userId: string; type: number }, roles: Role[]) {
|
|
return runWithRlsContext({ tenantId: data.tenantId }, () =>
|
|
db.$transaction(async (tx) => {
|
|
const tenantUser = await tx.tenantUser.create({
|
|
data: {
|
|
...data,
|
|
joined: TenantUserJoined.JOINED_BY_INVITATION,
|
|
status: TenantUserStatus.ACTIVE,
|
|
},
|
|
});
|
|
|
|
await Promise.all(
|
|
roles.map(async (role) => {
|
|
return await createUserRole(tenantUser.userId, role.id, tenantUser.tenantId);
|
|
})
|
|
);
|
|
|
|
return tenantUser;
|
|
})
|
|
);
|
|
}
|
|
|
|
function appendIdentifierSuffix(value: string, attempt: number): string {
|
|
if (attempt === 0) return value;
|
|
const separator = value.indexOf("@");
|
|
return separator < 0 ? `${value}${attempt}` : `${value.slice(0, separator)}${attempt}${value.slice(separator)}`;
|
|
}
|
|
|
|
function initialTenantSlug({ name, slug }: { name: string; slug?: string }): string {
|
|
const nameBase = normalizeTenantSlug(name) || FALLBACK_TENANT_SLUG_BASE;
|
|
const desired = slug === undefined ? nameBase : normalizeTenantSlug(slug) || nameBase;
|
|
return isReservedTenantSlug(desired) ? `${nameBase}1` : desired;
|
|
}
|
|
|
|
function initialTenantInboundAddress(name: string): string {
|
|
return initialTenantSlug({ name }).replaceAll("-", ".");
|
|
}
|
|
|
|
async function replayExistingTenantSetup({
|
|
tenantId,
|
|
rlsUserId,
|
|
setup,
|
|
validateExistingReplay,
|
|
}: {
|
|
tenantId: string;
|
|
rlsUserId?: string;
|
|
setup?: (tenant: Tenant, tx: Prisma.TransactionClient) => Promise<Tenant | void>;
|
|
validateExistingReplay?: (tenant: Tenant, tx: Prisma.TransactionClient) => Promise<void>;
|
|
}): Promise<Tenant | undefined> {
|
|
return runWithTargetTenantRlsContext(tenantId, rlsUserId, () =>
|
|
db.$transaction(async (tx) => {
|
|
const existing = await tx.tenant.findUnique({ where: { id: tenantId } });
|
|
if (!existing) {
|
|
return undefined;
|
|
}
|
|
if (!validateExistingReplay) {
|
|
throw new Error("Preallocated tenant replay requires explicit validation");
|
|
}
|
|
await validateExistingReplay(existing, tx);
|
|
if (!setup) {
|
|
return existing;
|
|
}
|
|
const setupTenant = await setup(existing, tx);
|
|
return setupTenant ?? (await tx.tenant.findUniqueOrThrow({ where: { id: tenantId } }));
|
|
})
|
|
);
|
|
}
|
|
|
|
function runWithTargetTenantRlsContext<T>(tenantId: string, rlsUserId: string | undefined, callback: () => T): T {
|
|
const current = getRlsExecutionContext();
|
|
if (rlsUserId && current?.userId === rlsUserId && (current.transaction !== undefined || (current.tenantId !== undefined && current.tenantId !== tenantId))) {
|
|
return runWithIsolatedUserRlsContext(rlsUserId, () => runWithRlsContext({ tenantId, userId: rlsUserId }, callback));
|
|
}
|
|
return runWithRlsContext({ tenantId, userId: rlsUserId }, callback);
|
|
}
|
|
|
|
function isUniqueConstraintViolation(error: unknown): boolean {
|
|
return Boolean(error && typeof error === "object" && "code" in error && error.code === "P2002");
|
|
}
|
|
|
|
type TenantIdentifierCollisionKind = "slug" | "inbound-address" | "id";
|
|
|
|
const TENANT_IDENTIFIER_FIELDS = new Map<string, TenantIdentifierCollisionKind>([
|
|
["slug", "slug"],
|
|
["address", "inbound-address"],
|
|
["id", "id"],
|
|
]);
|
|
|
|
const TENANT_IDENTIFIER_CONSTRAINTS = new Map<string, TenantIdentifierCollisionKind>([
|
|
["tenant_slug_key", "slug"],
|
|
["tenantinboundaddress_address_key", "inbound-address"],
|
|
["tenant_pkey", "id"],
|
|
]);
|
|
|
|
function classifyTenantIdentifierCollision(error: TenantIdentifierCollisionError): TenantIdentifierCollisionKind | null {
|
|
const cause = asRecord(error.cause);
|
|
const meta = asRecord(cause?.meta);
|
|
if (!meta) return null;
|
|
|
|
// Prisma 7 with adapter-pg keeps the mapped database constraint inside the
|
|
// driver adapter error. When that shape is present it is authoritative: do
|
|
// not fall back to legacy metadata and accidentally rewrite an identifier.
|
|
if (Object.prototype.hasOwnProperty.call(meta, "driverAdapterError")) {
|
|
const driverAdapterError = asRecord(meta.driverAdapterError);
|
|
const driverCause = asRecord(driverAdapterError?.cause);
|
|
if (driverCause?.kind !== "UniqueConstraintViolation") return null;
|
|
const constraint = classifyDriverConstraint(driverCause.constraint);
|
|
if (constraint || driverCause.constraint !== undefined) return constraint;
|
|
return classifyOriginalUniqueConstraintMessage(driverCause.originalCode, driverCause.originalMessage);
|
|
}
|
|
|
|
return classifyLegacyConstraintTarget(meta.target);
|
|
}
|
|
|
|
function classifyOriginalUniqueConstraintMessage(code: unknown, message: unknown): TenantIdentifierCollisionKind | null {
|
|
if (code !== "23505" || typeof message !== "string") return null;
|
|
const match = /^duplicate key value violates unique constraint "([^"]+)"$/u.exec(message);
|
|
return match?.[1] ? classifyConstraintName(match[1]) : null;
|
|
}
|
|
|
|
function classifyDriverConstraint(constraint: unknown): TenantIdentifierCollisionKind | null {
|
|
if (typeof constraint === "string") {
|
|
return classifyConstraintName(constraint);
|
|
}
|
|
|
|
const record = asRecord(constraint);
|
|
if (!record) return null;
|
|
const classifications: TenantIdentifierCollisionKind[] = [];
|
|
|
|
for (const property of ["fields", "name", "index"] as const) {
|
|
if (!Object.prototype.hasOwnProperty.call(record, property)) continue;
|
|
const classification = property === "fields" ? classifyConstraintFields(record[property]) : classifyConstraintName(record[property]);
|
|
if (!classification) return null;
|
|
classifications.push(classification);
|
|
}
|
|
|
|
if (classifications.length === 0 || classifications.some((classification) => classification !== classifications[0])) {
|
|
return null;
|
|
}
|
|
return classifications[0] ?? null;
|
|
}
|
|
|
|
function classifyLegacyConstraintTarget(target: unknown): TenantIdentifierCollisionKind | null {
|
|
if (typeof target === "string") {
|
|
return classifyConstraintField(target) ?? classifyConstraintName(target);
|
|
}
|
|
if (!Array.isArray(target) || target.length !== 1 || typeof target[0] !== "string") {
|
|
return null;
|
|
}
|
|
return classifyConstraintField(target[0]) ?? classifyConstraintName(target[0]);
|
|
}
|
|
|
|
function classifyConstraintFields(fields: unknown): TenantIdentifierCollisionKind | null {
|
|
if (!Array.isArray(fields) || fields.length !== 1 || typeof fields[0] !== "string") {
|
|
return null;
|
|
}
|
|
return classifyConstraintField(fields[0]);
|
|
}
|
|
|
|
function classifyConstraintField(field: string): TenantIdentifierCollisionKind | null {
|
|
return TENANT_IDENTIFIER_FIELDS.get(normalizeDatabaseIdentifier(field)) ?? null;
|
|
}
|
|
|
|
function classifyConstraintName(name: unknown): TenantIdentifierCollisionKind | null {
|
|
if (typeof name !== "string") return null;
|
|
return TENANT_IDENTIFIER_CONSTRAINTS.get(normalizeDatabaseIdentifier(name)) ?? null;
|
|
}
|
|
|
|
function normalizeDatabaseIdentifier(identifier: string): string {
|
|
const unquoted = identifier.trim().replaceAll('"', "");
|
|
return (unquoted.split(".").at(-1) ?? "").toLowerCase();
|
|
}
|
|
|
|
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
|
|
}
|
|
|
|
export async function deleteTenantUser(id: string, tenantId?: string) {
|
|
if (tenantId) {
|
|
const tenantUser = await db.tenantUser.findFirst({
|
|
where: {
|
|
id,
|
|
tenantId,
|
|
},
|
|
select: {
|
|
tenantId: true,
|
|
userId: true,
|
|
},
|
|
});
|
|
|
|
if (!tenantUser) {
|
|
return { count: 0 };
|
|
}
|
|
|
|
const deleted = await db.$transaction(async (tx) => {
|
|
const result = await tx.tenantUser.deleteMany({
|
|
where: {
|
|
id,
|
|
tenantId,
|
|
},
|
|
});
|
|
await tx.userRole.deleteMany({
|
|
where: {
|
|
tenantId: tenantUser.tenantId,
|
|
userId: tenantUser.userId,
|
|
},
|
|
});
|
|
await tx.groupUser.deleteMany({
|
|
where: {
|
|
userId: tenantUser.userId,
|
|
group: {
|
|
tenantId: tenantUser.tenantId,
|
|
},
|
|
},
|
|
});
|
|
return result;
|
|
});
|
|
await invalidateUserPermissionCache(tenantUser.userId, tenantUser.tenantId);
|
|
return deleted;
|
|
}
|
|
|
|
const deleted = await db.tenantUser.delete({
|
|
where: {
|
|
id,
|
|
},
|
|
});
|
|
if (deleted.tenantId) {
|
|
await db.$transaction(async (tx) => {
|
|
await tx.userRole.deleteMany({
|
|
where: {
|
|
tenantId: deleted.tenantId,
|
|
userId: deleted.userId,
|
|
},
|
|
});
|
|
await tx.groupUser.deleteMany({
|
|
where: {
|
|
userId: deleted.userId,
|
|
group: {
|
|
tenantId: deleted.tenantId,
|
|
},
|
|
},
|
|
});
|
|
});
|
|
await invalidateUserPermissionCache(deleted.userId, deleted.tenantId);
|
|
}
|
|
return deleted;
|
|
}
|
|
|
|
export async function deleteTenant(id: string) {
|
|
const item = await db.tenant.delete({
|
|
where: {
|
|
id,
|
|
},
|
|
include: {
|
|
subscription: true,
|
|
users: true,
|
|
invitations: true,
|
|
logs: true,
|
|
apiKeys: true,
|
|
userRoles: true,
|
|
},
|
|
});
|
|
await publishTenantInvalidation(item.id, item.slug);
|
|
return item;
|
|
}
|
|
|
|
export async function updateTenantDeactivated(id: string, data: { active: boolean; deactivatedReason: string | null }) {
|
|
return await db.tenant
|
|
.update({
|
|
where: {
|
|
id,
|
|
},
|
|
data,
|
|
})
|
|
.then(async (item) => {
|
|
await publishTenantInvalidation(item.id, item.slug);
|
|
return item;
|
|
});
|
|
}
|