1454 lines
52 KiB
TypeScript
1454 lines
52 KiB
TypeScript
import { createHash, randomUUID } from "node:crypto";
|
|
|
|
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
|
import type { Prisma, Tenant, User } from "@hivegrid/db/prisma-browser";
|
|
import { findRegistrationBillingPreferenceCapability } from "@hivegrid/db/pretenant-security.server";
|
|
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { resolveUserEmailRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
|
|
import {
|
|
acceptWorkspaceInvite,
|
|
getWorkspaceInviteByToken,
|
|
hashWorkspaceInviteToken,
|
|
type WorkspaceInviteClient,
|
|
WorkspaceInviteError,
|
|
} from "@hivegrid/db/workspace-invites.server";
|
|
|
|
import { TenantUserJoined } from "~/application/enums/tenants/TenantUserJoined";
|
|
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
|
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
|
import {
|
|
prepareShkFormTemplates,
|
|
seedShkFormTemplatesWithTx,
|
|
type FormTemplateTranslationFn,
|
|
type PreparedShkFormTemplate,
|
|
} from "~/modules/forms/services/shkFormTemplates.server";
|
|
import { hashPassword, verifyPassword } from "~/utils/auth/passwordHasher.server";
|
|
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
|
import { db } from "~/utils/db.server";
|
|
import { publishTenantInvalidation } from "~/utils/db/tenant-cache.server";
|
|
import { createTenant, emitTenantCreatedHook } from "~/utils/db/tenants.db.server";
|
|
import { invalidateUserSnapshot } from "~/utils/db/user-snapshot-cache.server";
|
|
import { emitUserCreatedHook } from "~/utils/db/users.db.server";
|
|
import { seedShkCustomFieldTemplateWithTx } from "~/utils/integrations/crm/customFieldService.server";
|
|
import { ensureDefaultAcceptanceFormTemplateWithTx, ensureDefaultProjectTemplateWithTx } from "~/utils/integrations/projects/auftragService.server";
|
|
import { createScopedLogger } from "~/utils/logger.server";
|
|
import {
|
|
persistTenantRegistrationBillingPreferenceWithTx,
|
|
type RegistrationBillingPreference,
|
|
} from "~/services/billing/registration-billing-preference.server";
|
|
|
|
import { SHK_V2_TENANT_BOOTSTRAP_CONFIG, SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, type ShkV2TenantBootstrapConfig } from "./shk-v2.config";
|
|
import {
|
|
hasExactShkFirstSteps,
|
|
SHK_FIRST_STEPS,
|
|
SHK_FIRST_STEPS_CHECKLIST_CODE,
|
|
SHK_FIRST_STEPS_CHECKLIST_ID,
|
|
TENANT_PENDING_OWNER_REASON,
|
|
} from "./tenantBootstrap.constants";
|
|
import { isSignupCreationRequestKey } from "./signupCreationRequestKey.server";
|
|
import { issueReservedOwnerInvitationWithTx, type ReservedOwnerInvitationDraft } from "./ownerInvitationIssuance.server";
|
|
|
|
export const SHK_V2_BOOTSTRAP_SCOPE = "tenant-bootstrap";
|
|
|
|
const tenantBootstrapLogger = createScopedLogger("tenant-bootstrap");
|
|
|
|
type TenantCreationRequestMarker = {
|
|
key: string;
|
|
payloadHash: string;
|
|
tenantName: string;
|
|
tenantSlug: string;
|
|
signup?: {
|
|
normalizedEmail: string;
|
|
userId: string;
|
|
};
|
|
};
|
|
|
|
type BootstrapMarkerBody =
|
|
| {
|
|
state: "started";
|
|
attemptId: string;
|
|
templateKey: string;
|
|
schemaVersion: number;
|
|
creationRequest?: TenantCreationRequestMarker;
|
|
}
|
|
| {
|
|
state: "completed";
|
|
templateKey: string;
|
|
schemaVersion: number;
|
|
completedAt: string;
|
|
creationRequest?: TenantCreationRequestMarker;
|
|
};
|
|
|
|
export type TenantBootstrapUser = Pick<User, "id" | "email" | "firstName" | "lastName" | "locale" | "createdAt" | "defaultTenantId">;
|
|
|
|
export type TenantBootstrapResult = {
|
|
tenant: Tenant;
|
|
user: TenantBootstrapUser;
|
|
replayed: boolean;
|
|
};
|
|
|
|
export type SignupTenantBootstrapInput = {
|
|
email: string;
|
|
password: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
company: string;
|
|
avatarURL?: string;
|
|
locale?: string;
|
|
slug?: string;
|
|
creationRequestKey: string;
|
|
billingPreference?: RegistrationBillingPreference;
|
|
t: FormTemplateTranslationFn;
|
|
};
|
|
|
|
export type ExistingOwnerTenantBootstrapInput = {
|
|
user: TenantBootstrapUser;
|
|
name: string;
|
|
slug?: string;
|
|
creationRequestKey: string;
|
|
t: FormTemplateTranslationFn;
|
|
};
|
|
|
|
export type OwnedTenantCreationReplayInput = {
|
|
userId: string;
|
|
name: string;
|
|
slug?: string;
|
|
creationRequestKey: string;
|
|
};
|
|
|
|
export type ReservedTenantClaimInput = {
|
|
tenantId: string;
|
|
userId: string;
|
|
t: FormTemplateTranslationFn;
|
|
createUser?: {
|
|
id: string;
|
|
email: string;
|
|
passwordHash: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
locale?: string | null;
|
|
};
|
|
claim: {
|
|
kind: "workspace-invite";
|
|
inviteId: string;
|
|
token: string;
|
|
createdUserId?: string;
|
|
};
|
|
};
|
|
|
|
export type OwnerlessTenantReservationInput = {
|
|
name: string;
|
|
slug?: string;
|
|
operatorUserId: string;
|
|
reservationRequestKey: string;
|
|
ownerInvitation: ReservedOwnerInvitationDraft;
|
|
};
|
|
|
|
type BootstrapWithTxInput = {
|
|
tenantId: string;
|
|
tenantName: string;
|
|
tenantSlug: string;
|
|
userId: string;
|
|
attemptId: string;
|
|
t: FormTemplateTranslationFn;
|
|
now?: Date;
|
|
config?: ShkV2TenantBootstrapConfig;
|
|
configDigest: string;
|
|
preparedFormTemplates: ReadonlyArray<PreparedShkFormTemplate>;
|
|
creationRequest?: TenantCreationRequestMarker;
|
|
billingPreference?: RegistrationBillingPreference;
|
|
};
|
|
|
|
/**
|
|
* Creates a user and their first workspace in one transaction. CPU-heavy
|
|
* password hashing and immutable config preparation happen before the
|
|
* interactive database transaction starts.
|
|
*/
|
|
export async function createSignupTenantWithShkDefaults(input: SignupTenantBootstrapInput): Promise<TenantBootstrapResult> {
|
|
const normalizedEmail = normalizeEmail(input.email);
|
|
if (!isCreationRequestKey(input.creationRequestKey) || !normalizedEmail || !normalizedEmail.includes("@")) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "signup-creation-request" });
|
|
}
|
|
const userId = deriveSignupUserId(normalizedEmail, input.creationRequestKey);
|
|
const tenantId = deriveSignupTenantId(normalizedEmail, input.creationRequestKey);
|
|
const existingIdentity = await resolveUserEmailRlsIdentity(normalizedEmail);
|
|
if (existingIdentity && (existingIdentity.resourceId !== userId || existingIdentity.userId !== userId)) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: input.creationRequestKey,
|
|
});
|
|
}
|
|
const payloadHash = hashSignupCreationPayload(input, normalizedEmail);
|
|
const attemptId = randomUUID();
|
|
const preparedFormTemplates = prepareShkFormTemplates(input.t);
|
|
const verifiedReplayPasswordHash = existingIdentity
|
|
? await readAndVerifySignupReplayPasswordHash({
|
|
userId,
|
|
password: input.password,
|
|
creationRequestKey: input.creationRequestKey,
|
|
})
|
|
: null;
|
|
const passwordHash = existingIdentity ? null : await hashPassword(input.password);
|
|
let createdUser: User | undefined;
|
|
let replayed = false;
|
|
let validatedReplay = false;
|
|
|
|
let tenant: Tenant;
|
|
try {
|
|
tenant = await createTenant({
|
|
tenantId,
|
|
name: input.company,
|
|
slug: input.slug,
|
|
rejectSlugCollision: Boolean(input.slug?.trim()),
|
|
active: false,
|
|
deactivatedReason: TENANT_PENDING_OWNER_REASON,
|
|
rlsUserId: userId,
|
|
validateExistingReplay: async (existingTenant, tx) => {
|
|
if (!verifiedReplayPasswordHash) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: input.creationRequestKey,
|
|
});
|
|
}
|
|
createdUser = await validateSignupTenantCreationReplayWithTx(
|
|
tx,
|
|
existingTenant,
|
|
input,
|
|
normalizedEmail,
|
|
userId,
|
|
payloadHash,
|
|
verifiedReplayPasswordHash
|
|
);
|
|
replayed = true;
|
|
validatedReplay = true;
|
|
},
|
|
setup: async (createdTenant, tx) => {
|
|
if (validatedReplay) {
|
|
return createdTenant;
|
|
}
|
|
// A resolver-confirmed identity may only enter the authoritative
|
|
// existing-tenant replay path. Never create a user without a freshly
|
|
// prepared password hash if the tenant row unexpectedly does not exist.
|
|
if (passwordHash === null) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: input.creationRequestKey,
|
|
});
|
|
}
|
|
createdUser = await tx.user.create({
|
|
data: {
|
|
id: userId,
|
|
email: normalizedEmail,
|
|
passwordHash,
|
|
firstName: input.firstName,
|
|
lastName: input.lastName,
|
|
avatar: input.avatarURL ?? "",
|
|
phone: "",
|
|
locale: input.locale,
|
|
defaultTenantId: createdTenant.id,
|
|
active: true,
|
|
},
|
|
});
|
|
const result = await bootstrapShkV2TenantWithTx(tx, {
|
|
tenantId: createdTenant.id,
|
|
tenantName: createdTenant.name,
|
|
tenantSlug: createdTenant.slug,
|
|
userId,
|
|
attemptId,
|
|
t: input.t,
|
|
configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST,
|
|
preparedFormTemplates,
|
|
...(input.billingPreference ? { billingPreference: input.billingPreference } : {}),
|
|
creationRequest: {
|
|
key: input.creationRequestKey,
|
|
payloadHash,
|
|
tenantName: createdTenant.name,
|
|
tenantSlug: createdTenant.slug,
|
|
signup: { normalizedEmail, userId },
|
|
},
|
|
});
|
|
replayed = result.replayed;
|
|
return result.tenant;
|
|
},
|
|
emitCreatedHook: false,
|
|
});
|
|
} catch (error) {
|
|
if (isUniqueConstraintViolation(error)) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: input.creationRequestKey,
|
|
});
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
if (!createdUser) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "bootstrap-user" });
|
|
}
|
|
const postCommitContext = createdTenantContext(tenant.id, createdUser.id);
|
|
await Promise.all([
|
|
runPostCommitStep("tenant-cache.invalidate", postCommitContext, () => publishTenantInvalidation(tenant.id, tenant.slug)),
|
|
runPostCommitStep("user-cache.invalidate", postCommitContext, () => invalidateUserSnapshot(createdUser!.id)),
|
|
runPostCommitStep("tenant-hook.emit", postCommitContext, () => emitTenantCreatedHook(tenant, createdUser!.id)),
|
|
runPostCommitStep("user-hook.emit", postCommitContext, () => emitUserCreatedHook(createdUser!)),
|
|
]);
|
|
return { tenant, user: createdUser, replayed };
|
|
}
|
|
|
|
/** Creates a fully provisioned workspace for an already authenticated user. */
|
|
export async function createOwnedTenantWithShkDefaults(input: ExistingOwnerTenantBootstrapInput): Promise<TenantBootstrapResult> {
|
|
const current = getRlsExecutionContext();
|
|
if (current?.userId !== input.user.id || !isCreationRequestKey(input.creationRequestKey)) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-creation-request" });
|
|
}
|
|
const attemptId = randomUUID();
|
|
const preparedFormTemplates = prepareShkFormTemplates(input.t);
|
|
const tenantId = deriveTenantCreationId(input.user.id, input.creationRequestKey);
|
|
const creationReplayInput: OwnedTenantCreationReplayInput = {
|
|
userId: input.user.id,
|
|
name: input.name,
|
|
slug: input.slug,
|
|
creationRequestKey: input.creationRequestKey,
|
|
};
|
|
const payloadHash = hashTenantCreationPayload(creationReplayInput);
|
|
let replayed = false;
|
|
const tenant = await createTenant({
|
|
tenantId,
|
|
name: input.name,
|
|
slug: input.slug,
|
|
rejectSlugCollision: Boolean(input.slug?.trim()),
|
|
active: false,
|
|
deactivatedReason: TENANT_PENDING_OWNER_REASON,
|
|
rlsUserId: input.user.id,
|
|
validateExistingReplay: async (existingTenant, tx) => {
|
|
await validateOwnedTenantCreationReplayWithTx(tx, existingTenant, creationReplayInput, payloadHash);
|
|
},
|
|
setup: async (createdTenant, tx) => {
|
|
const result = await bootstrapShkV2TenantWithTx(tx, {
|
|
tenantId: createdTenant.id,
|
|
tenantName: createdTenant.name,
|
|
tenantSlug: createdTenant.slug,
|
|
userId: input.user.id,
|
|
attemptId,
|
|
t: input.t,
|
|
configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST,
|
|
preparedFormTemplates,
|
|
creationRequest: {
|
|
key: input.creationRequestKey,
|
|
payloadHash,
|
|
tenantName: createdTenant.name,
|
|
tenantSlug: createdTenant.slug,
|
|
},
|
|
});
|
|
replayed = result.replayed;
|
|
return result.tenant;
|
|
},
|
|
emitCreatedHook: false,
|
|
});
|
|
const postCommitContext = createdTenantContext(tenant.id, input.user.id);
|
|
await Promise.all([
|
|
runPostCommitStep("tenant-cache.invalidate", postCommitContext, () => publishTenantInvalidation(tenant.id, tenant.slug)),
|
|
runPostCommitStep("user-cache.invalidate", postCommitContext, () => invalidateUserSnapshot(input.user.id)),
|
|
runPostCommitStep("tenant-hook.emit", postCommitContext, () => emitTenantCreatedHook(tenant, input.user.id)),
|
|
]);
|
|
return { tenant, user: { ...input.user, defaultTenantId: tenant.id }, replayed };
|
|
}
|
|
|
|
/**
|
|
* Proves that a new-workspace POST is an exact replay before it enters the
|
|
* lower replay throttle. A deterministic tenant id or membership alone is not
|
|
* sufficient: the completed bootstrap marker and original payload must match.
|
|
*/
|
|
export async function isExactOwnedTenantCreationReplay(input: OwnedTenantCreationReplayInput): Promise<boolean> {
|
|
const current = getRlsExecutionContext();
|
|
if ((current && current.userId !== input.userId) || !isCreationRequestKey(input.creationRequestKey)) return false;
|
|
|
|
const tenantId = deriveTenantCreationId(input.userId, input.creationRequestKey);
|
|
const payloadHash = hashTenantCreationPayload(input);
|
|
const probe = () =>
|
|
runWithRlsContext({ tenantId, userId: input.userId }, () =>
|
|
db.$transaction(async (tx) => {
|
|
const tenant = await tx.tenant.findUnique({ where: { id: tenantId } });
|
|
if (!tenant) return false;
|
|
try {
|
|
await validateOwnedTenantCreationReplayWithTx(tx as unknown as TenantRlsClient, tenant, input, payloadHash);
|
|
return true;
|
|
} catch (error) {
|
|
if (error instanceof CatalogError) return false;
|
|
throw error;
|
|
}
|
|
})
|
|
);
|
|
|
|
if (current?.tenantId || current?.transaction || current?.publicKnowledgeBaseId) {
|
|
return await runWithIsolatedUserRlsContext(input.userId, probe);
|
|
}
|
|
return await probe();
|
|
}
|
|
|
|
/**
|
|
* Completes a previously ownerless reservation. The same marker and bootstrap
|
|
* body used by signup/new-workspace make retries safe.
|
|
*/
|
|
export async function claimReservedTenantWithShkDefaults(input: ReservedTenantClaimInput): Promise<TenantBootstrapResult> {
|
|
const current = getRlsExecutionContext();
|
|
if (!current?.userId || current.userId !== input.userId) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-reservation" });
|
|
}
|
|
const preparedFormTemplates = prepareShkFormTemplates(input.t);
|
|
const execute = () =>
|
|
runWithRlsContext({ tenantId: input.tenantId, userId: input.userId }, () =>
|
|
db.$transaction(async (tx) => {
|
|
const user = await authorizeReservationClaimWithTx(tx, input);
|
|
const reservedTenant = await tx.tenant.findUnique({ where: { id: input.tenantId } });
|
|
if (!reservedTenant) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-reservation" });
|
|
}
|
|
if (!reservedTenant.active && reservedTenant.deactivatedReason !== TENANT_PENDING_OWNER_REASON) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-reservation" });
|
|
}
|
|
const existingMemberships = await tx.tenantUser.findMany({
|
|
where: { tenantId: input.tenantId },
|
|
select: { userId: true, type: true, status: true },
|
|
take: 2,
|
|
});
|
|
if (
|
|
existingMemberships.length > 1 ||
|
|
(existingMemberships.length === 1 &&
|
|
(existingMemberships[0]?.userId !== input.userId ||
|
|
existingMemberships[0].type !== TenantUserType.OWNER ||
|
|
existingMemberships[0].status !== TenantUserStatus.ACTIVE))
|
|
) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-reservation" });
|
|
}
|
|
const result = await bootstrapShkV2TenantWithTx(tx, {
|
|
...input,
|
|
tenantName: reservedTenant.name,
|
|
tenantSlug: reservedTenant.slug,
|
|
attemptId: randomUUID(),
|
|
configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST,
|
|
preparedFormTemplates,
|
|
});
|
|
if (reservedTenant.active && !result.replayed) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey,
|
|
});
|
|
}
|
|
if (result.replayed) {
|
|
const owner = await tx.tenantUser.findFirst({
|
|
where: {
|
|
tenantId: input.tenantId,
|
|
userId: input.userId,
|
|
type: TenantUserType.OWNER,
|
|
status: TenantUserStatus.ACTIVE,
|
|
},
|
|
select: { id: true },
|
|
});
|
|
if (!owner) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-reservation" });
|
|
}
|
|
}
|
|
const finalTenant = result.tenant ?? (await tx.tenant.findUniqueOrThrow({ where: { id: input.tenantId } }));
|
|
return {
|
|
tenant: finalTenant,
|
|
user: { ...user, defaultTenantId: input.tenantId },
|
|
replayed: result.replayed,
|
|
};
|
|
})
|
|
);
|
|
|
|
const result = current.tenantId || current.transaction ? await runWithIsolatedUserRlsContext(input.userId, execute) : await execute();
|
|
const postCommitContext = createdTenantContext(result.tenant.id, input.userId);
|
|
await Promise.all([
|
|
runPostCommitStep("tenant-cache.invalidate", postCommitContext, () => publishTenantInvalidation(result.tenant.id, result.tenant.slug)),
|
|
runPostCommitStep("user-cache.invalidate", postCommitContext, () => invalidateUserSnapshot(input.userId)),
|
|
runPostCommitStep("tenant-hook.emit", postCommitContext, () => emitTenantCreatedHook(result.tenant, input.userId)),
|
|
]);
|
|
return result;
|
|
}
|
|
|
|
async function authorizeReservationClaimWithTx(tx: TenantRlsClient, input: ReservedTenantClaimInput): Promise<TenantBootstrapUser> {
|
|
const inviteClient = tx as unknown as WorkspaceInviteClient;
|
|
const invitation = await getWorkspaceInviteByToken({ token: input.claim.token }, inviteClient);
|
|
if (!invitation || invitation.id !== input.claim.inviteId || invitation.tenantId !== input.tenantId || invitation.type !== TenantUserType.OWNER) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
|
|
if (input.claim.createdUserId !== undefined && input.claim.createdUserId !== input.userId) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
|
|
const normalizedInvitationEmail = normalizeEmail(invitation.email);
|
|
if (input.createUser) {
|
|
const candidate = input.createUser;
|
|
if (
|
|
invitation.status !== "pending" ||
|
|
invitation.createdUserId !== null ||
|
|
input.claim.createdUserId !== input.userId ||
|
|
candidate.id !== input.userId ||
|
|
candidate.email !== normalizedInvitationEmail ||
|
|
candidate.firstName !== invitation.firstName ||
|
|
candidate.lastName !== invitation.lastName ||
|
|
!candidate.passwordHash.startsWith("$argon2id$")
|
|
) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
let existingIdentity: Awaited<ReturnType<typeof resolveUserEmailRlsIdentity>>;
|
|
try {
|
|
existingIdentity = await resolveUserEmailRlsIdentity(normalizedInvitationEmail, tx);
|
|
} catch {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
if (existingIdentity) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
let createdUser: User;
|
|
try {
|
|
createdUser = await tx.user.create({
|
|
data: {
|
|
id: candidate.id,
|
|
email: candidate.email,
|
|
passwordHash: candidate.passwordHash,
|
|
firstName: candidate.firstName,
|
|
lastName: candidate.lastName,
|
|
avatar: "",
|
|
phone: "",
|
|
active: true,
|
|
locale: candidate.locale ?? null,
|
|
defaultTenantId: null,
|
|
},
|
|
});
|
|
} catch (error) {
|
|
if (isUniqueConstraintViolation(error)) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
throw error;
|
|
}
|
|
const marker = await tx.tenantUserInvitation.updateMany({
|
|
where: {
|
|
id: invitation.id,
|
|
tenantId: input.tenantId,
|
|
email: normalizedInvitationEmail,
|
|
type: TenantUserType.OWNER,
|
|
pending: true,
|
|
status: "pending",
|
|
tokenHash: hashWorkspaceInviteToken(input.claim.token),
|
|
createdUserId: null,
|
|
acceptedAt: null,
|
|
revokedAt: null,
|
|
OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
|
|
},
|
|
data: { createdUserId: createdUser.id },
|
|
});
|
|
if (marker.count !== 1) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
try {
|
|
await acceptWorkspaceInvite(
|
|
{
|
|
tenantId: input.tenantId,
|
|
inviteId: input.claim.inviteId,
|
|
token: input.claim.token,
|
|
acceptedByUserId: input.userId,
|
|
createdUserId: input.userId,
|
|
},
|
|
inviteClient
|
|
);
|
|
} catch (error) {
|
|
if (error instanceof WorkspaceInviteError) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
throw error;
|
|
}
|
|
return createdUser;
|
|
}
|
|
|
|
let resolvedIdentity: Awaited<ReturnType<typeof resolveUserEmailRlsIdentity>>;
|
|
try {
|
|
resolvedIdentity = await resolveUserEmailRlsIdentity(normalizedInvitationEmail, tx);
|
|
} catch {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
if (!resolvedIdentity || resolvedIdentity.userId !== input.userId || resolvedIdentity.resourceId !== input.userId) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
const matchingUsers = await tx.user.findMany({
|
|
where: { email: { equals: normalizedInvitationEmail, mode: "insensitive" } },
|
|
select: { id: true },
|
|
orderBy: { id: "asc" },
|
|
take: 2,
|
|
});
|
|
if (matchingUsers.length !== 1 || matchingUsers[0]?.id !== input.userId) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
const lockedUsers = await tx.$queryRaw<User[]>`SELECT * FROM public."User" WHERE id = ${input.userId} FOR UPDATE`;
|
|
const user = lockedUsers.length === 1 ? lockedUsers[0] : null;
|
|
if (!user || !user.active || user.id !== input.userId || normalizeEmail(user.email) !== normalizedInvitationEmail) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
const invitationCreatedUserId = invitation.createdUserId ?? null;
|
|
if (invitation.status === "accepted" && invitation.acceptedByUserId === input.userId) {
|
|
if (invitationCreatedUserId !== (input.claim.createdUserId ?? null)) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
return user;
|
|
}
|
|
if (invitation.status !== "pending") {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
if (invitationCreatedUserId !== (input.claim.createdUserId ?? null)) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
try {
|
|
await acceptWorkspaceInvite(
|
|
{
|
|
tenantId: input.tenantId,
|
|
inviteId: input.claim.inviteId,
|
|
token: input.claim.token,
|
|
acceptedByUserId: input.userId,
|
|
...(input.claim.createdUserId ? { createdUserId: input.claim.createdUserId } : {}),
|
|
},
|
|
inviteClient
|
|
);
|
|
} catch (error) {
|
|
if (error instanceof WorkspaceInviteError) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-claim-capability" });
|
|
}
|
|
throw error;
|
|
}
|
|
return user;
|
|
}
|
|
|
|
/** Creates an ownerless reservation without defaults or lifecycle hooks. */
|
|
export async function reserveTenantWithoutOwner(input: OwnerlessTenantReservationInput): Promise<Tenant> {
|
|
const current = getRlsExecutionContext();
|
|
const name = input.name.trim();
|
|
const slug = input.slug?.trim() || undefined;
|
|
if (
|
|
!name ||
|
|
!input.operatorUserId ||
|
|
current?.userId !== input.operatorUserId ||
|
|
!isCreationRequestKey(input.reservationRequestKey) ||
|
|
!input.ownerInvitation ||
|
|
input.ownerInvitation.issuanceKey !== input.reservationRequestKey ||
|
|
input.ownerInvitation.fromUserId !== input.operatorUserId
|
|
) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "tenant-reservation-request" });
|
|
}
|
|
const tenantId = deriveTenantReservationId(input.operatorUserId, input.reservationRequestKey);
|
|
const requestHash = hashTenantReservationPayload({
|
|
operatorUserId: input.operatorUserId,
|
|
reservationRequestKey: input.reservationRequestKey,
|
|
name,
|
|
slug,
|
|
ownerInvitation: input.ownerInvitation,
|
|
});
|
|
return createTenant({
|
|
tenantId,
|
|
name,
|
|
slug,
|
|
active: false,
|
|
deactivatedReason: TENANT_PENDING_OWNER_REASON,
|
|
rlsUserId: input.operatorUserId,
|
|
emitCreatedHook: false,
|
|
validateExistingReplay: async (tenant, tx) => {
|
|
await validateTenantReservationReplayWithTx(tx as unknown as TenantRlsClient, tenant, input.reservationRequestKey, requestHash);
|
|
},
|
|
setup: async (tenant, tx) => {
|
|
await persistTenantReservationMarkerWithTx(tx as unknown as TenantRlsClient, tenant, input.reservationRequestKey, requestHash);
|
|
if (!tenant.active && tenant.deactivatedReason === TENANT_PENDING_OWNER_REASON) {
|
|
await issueReservedOwnerInvitationWithTx(tx, { tenantId: tenant.id, ...input.ownerInvitation });
|
|
}
|
|
return tenant;
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Applies every owner/default row through the transaction supplied by the
|
|
* tenant lifecycle. No mail, external billing, cache, event, or plugin side
|
|
* effect is allowed in this function.
|
|
*/
|
|
export async function bootstrapShkV2TenantWithTx(tx: TenantRlsClient, input: BootstrapWithTxInput): Promise<{ replayed: boolean; tenant?: Tenant }> {
|
|
const config = input.config ?? SHK_V2_TENANT_BOOTSTRAP_CONFIG;
|
|
const marker = await acquireBootstrapMarker(tx, input, config, input.configDigest);
|
|
if (marker.replayed) {
|
|
return marker;
|
|
}
|
|
|
|
await provisionOwnerWithTx(tx, input, config);
|
|
await provisionTenantRolesWithTx(tx, input, config);
|
|
await provisionSalesPipelinesWithTx(tx, input, config);
|
|
await seedShkCustomFieldTemplateWithTx(tx, { tenantId: input.tenantId });
|
|
await ensureDefaultAcceptanceFormTemplateWithTx(tx, input.tenantId);
|
|
await ensureDefaultProjectTemplateWithTx(tx, input.tenantId);
|
|
await seedShkFormTemplatesWithTx(tx, {
|
|
tenantId: input.tenantId,
|
|
userId: input.userId,
|
|
t: input.t,
|
|
preparedTemplates: input.preparedFormTemplates,
|
|
});
|
|
await provisionChecklistSessionWithTx(tx, input);
|
|
await provisionAutomationPlaceholdersWithTx(tx, input, config);
|
|
await provisionCustomerPortalScaffoldWithTx(tx, input);
|
|
if (input.billingPreference) {
|
|
await persistTenantRegistrationBillingPreferenceWithTx(tx, {
|
|
tenantId: input.tenantId,
|
|
...input.billingPreference,
|
|
});
|
|
}
|
|
|
|
const completedAt = input.now ?? new Date();
|
|
await tx.idempotencyKey.update({
|
|
where: markerWhere(input.tenantId, config.templateKey),
|
|
data: {
|
|
responseStatus: 201,
|
|
responseBody: {
|
|
state: "completed",
|
|
templateKey: config.templateKey,
|
|
schemaVersion: config.schemaVersion,
|
|
completedAt: completedAt.toISOString(),
|
|
...(input.creationRequest ? { creationRequest: input.creationRequest } : {}),
|
|
} satisfies BootstrapMarkerBody,
|
|
},
|
|
});
|
|
|
|
// This must remain the final write of the bootstrap transaction.
|
|
const tenant = await tx.tenant.update({
|
|
where: { id: input.tenantId },
|
|
data: { active: true, deactivatedReason: null },
|
|
});
|
|
return { replayed: false, tenant };
|
|
}
|
|
|
|
async function provisionCustomerPortalScaffoldWithTx(tx: TenantRlsClient, input: BootstrapWithTxInput): Promise<void> {
|
|
await tx.portal.upsert({
|
|
where: { tenantId: input.tenantId },
|
|
create: {
|
|
tenantId: input.tenantId,
|
|
createdByUserId: input.userId,
|
|
subdomain: input.tenantSlug,
|
|
title: input.tenantName,
|
|
isPublished: false,
|
|
metadata: { provisioningSource: "tenant_bootstrap_v1" },
|
|
},
|
|
update: {},
|
|
select: { id: true },
|
|
});
|
|
}
|
|
|
|
async function acquireBootstrapMarker(
|
|
tx: TenantRlsClient,
|
|
input: BootstrapWithTxInput,
|
|
config: ShkV2TenantBootstrapConfig,
|
|
requestHash: string
|
|
): Promise<{ replayed: boolean }> {
|
|
const responseBody = {
|
|
state: "started",
|
|
attemptId: input.attemptId,
|
|
templateKey: config.templateKey,
|
|
schemaVersion: config.schemaVersion,
|
|
...(input.creationRequest ? { creationRequest: input.creationRequest } : {}),
|
|
} satisfies BootstrapMarkerBody;
|
|
const marker = await tx.idempotencyKey.upsert({
|
|
where: markerWhere(input.tenantId, config.templateKey),
|
|
create: {
|
|
tenantId: input.tenantId,
|
|
partitionKey: markerPartition(input.tenantId),
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: config.templateKey,
|
|
requestHash,
|
|
responseStatus: 102,
|
|
responseBody,
|
|
},
|
|
update: {},
|
|
});
|
|
|
|
if (marker.requestHash !== requestHash) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: config.templateKey,
|
|
});
|
|
}
|
|
const storedBody = readMarkerBody(marker.responseBody);
|
|
if (input.creationRequest && !matchesCreationRequest(storedBody?.creationRequest, input.creationRequest)) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: config.templateKey,
|
|
});
|
|
}
|
|
if (marker.responseStatus === 201) {
|
|
return { replayed: true };
|
|
}
|
|
if (marker.responseStatus !== 102 || storedBody?.state !== "started" || storedBody.attemptId !== input.attemptId) {
|
|
throw new CatalogError(foundationErrors.idempotencyInProgress, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: config.templateKey,
|
|
});
|
|
}
|
|
return { replayed: false };
|
|
}
|
|
|
|
async function provisionOwnerWithTx(
|
|
tx: TenantRlsClient,
|
|
input: Pick<BootstrapWithTxInput, "tenantId" | "userId">,
|
|
config: ShkV2TenantBootstrapConfig
|
|
): Promise<void> {
|
|
const adminRoles = await tx.role.findMany({
|
|
where: {
|
|
tenantId: null,
|
|
name: config.ownerRole.name,
|
|
type: config.ownerRole.type,
|
|
},
|
|
select: { id: true },
|
|
orderBy: { id: "asc" },
|
|
take: 2,
|
|
});
|
|
if (adminRoles.length !== 1) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "global-admin-role" });
|
|
}
|
|
const adminRole = adminRoles[0]!;
|
|
|
|
await tx.tenantUser.upsert({
|
|
where: { tenantId_userId: { tenantId: input.tenantId, userId: input.userId } },
|
|
create: {
|
|
tenantId: input.tenantId,
|
|
userId: input.userId,
|
|
type: TenantUserType.OWNER,
|
|
joined: TenantUserJoined.CREATOR,
|
|
status: TenantUserStatus.ACTIVE,
|
|
},
|
|
update: {
|
|
type: TenantUserType.OWNER,
|
|
joined: TenantUserJoined.CREATOR,
|
|
status: TenantUserStatus.ACTIVE,
|
|
},
|
|
});
|
|
await tx.user.update({
|
|
where: { id: input.userId },
|
|
data: { defaultTenantId: input.tenantId },
|
|
});
|
|
await tx.userRole.deleteMany({
|
|
where: {
|
|
tenantId: input.tenantId,
|
|
userId: input.userId,
|
|
roleId: { not: adminRole.id },
|
|
},
|
|
});
|
|
await tx.userRole.createMany({
|
|
data: [{ tenantId: input.tenantId, userId: input.userId, roleId: adminRole.id }],
|
|
skipDuplicates: true,
|
|
});
|
|
}
|
|
|
|
async function provisionTenantRolesWithTx(
|
|
tx: TenantRlsClient,
|
|
input: Pick<BootstrapWithTxInput, "tenantId" | "t">,
|
|
config: ShkV2TenantBootstrapConfig
|
|
): Promise<void> {
|
|
const permissionKeys = [...new Set(config.tenantRoles.flatMap((role) => role.permissionKeys))];
|
|
const permissions = await tx.permission.findMany({
|
|
where: { name: { in: permissionKeys } },
|
|
select: { id: true, name: true },
|
|
});
|
|
if (permissions.length !== permissionKeys.length) {
|
|
const found = new Set(permissions.map(({ name }) => name));
|
|
throw new CatalogError(foundationErrors.notFound, {
|
|
resource: "bootstrap-permissions",
|
|
missing: permissionKeys.filter((key) => !found.has(key)).join(","),
|
|
});
|
|
}
|
|
|
|
const roles = await tx.role.createManyAndReturn({
|
|
data: config.tenantRoles.map((role) => ({
|
|
tenantId: input.tenantId,
|
|
name: role.name,
|
|
description: input.t(role.descriptionKey),
|
|
type: role.type,
|
|
assignToNewUsers: role.assignToNewUsers,
|
|
isDefault: role.isDefault,
|
|
order: role.order,
|
|
seatCategory: role.seatCategory,
|
|
isTemplateOrigin: role.isTemplateOrigin,
|
|
})),
|
|
skipDuplicates: true,
|
|
select: { id: true, name: true },
|
|
});
|
|
if (roles.length !== config.tenantRoles.length) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "bootstrap-tenant-roles" });
|
|
}
|
|
const roleIdByName = new Map(roles.map((role) => [role.name, role.id]));
|
|
const permissionIdByName = new Map(permissions.map((permission) => [permission.name, permission.id]));
|
|
await tx.rolePermission.createMany({
|
|
data: config.tenantRoles.flatMap((role) =>
|
|
role.permissionKeys.map((permissionKey) => ({
|
|
roleId: requireMapValue(roleIdByName, role.name, "bootstrap-tenant-role"),
|
|
permissionId: requireMapValue(permissionIdByName, permissionKey, "bootstrap-permission"),
|
|
}))
|
|
),
|
|
skipDuplicates: true,
|
|
});
|
|
}
|
|
|
|
async function provisionSalesPipelinesWithTx(
|
|
tx: TenantRlsClient,
|
|
input: Pick<BootstrapWithTxInput, "tenantId" | "userId">,
|
|
config: ShkV2TenantBootstrapConfig
|
|
): Promise<void> {
|
|
const pipelines = await tx.pipeline.createManyAndReturn({
|
|
data: config.salesPipelines.map((pipeline) => ({
|
|
tenantId: input.tenantId,
|
|
createdByUserId: input.userId,
|
|
name: pipeline.name,
|
|
typHint: pipeline.typHint,
|
|
position: pipeline.position,
|
|
isDefault: pipeline.isDefault,
|
|
isDemoData: pipeline.isDemoData,
|
|
})),
|
|
skipDuplicates: true,
|
|
select: { id: true, name: true },
|
|
});
|
|
if (pipelines.length !== config.salesPipelines.length) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "bootstrap-sales-pipelines" });
|
|
}
|
|
const pipelineIdByName = new Map(pipelines.map((pipeline) => [pipeline.name, pipeline.id]));
|
|
await tx.pipelineStage.createMany({
|
|
data: config.salesPipelines.flatMap((pipeline) =>
|
|
pipeline.stages.map((stage) => ({
|
|
tenantId: input.tenantId,
|
|
pipelineId: requireMapValue(pipelineIdByName, pipeline.name, "bootstrap-sales-pipeline"),
|
|
name: stage.name,
|
|
stageKind: stage.stageKind,
|
|
winProbability: stage.winProbability,
|
|
color: stage.color,
|
|
position: stage.position,
|
|
isDemoData: false,
|
|
}))
|
|
),
|
|
skipDuplicates: true,
|
|
});
|
|
await tx.lostReason.createMany({
|
|
data: config.salesLostReasons.map((name, index) => ({
|
|
tenantId: input.tenantId,
|
|
name,
|
|
position: (index + 1) * 10,
|
|
isDemoData: false,
|
|
})),
|
|
skipDuplicates: true,
|
|
});
|
|
}
|
|
|
|
async function provisionChecklistSessionWithTx(tx: TenantRlsClient, input: Pick<BootstrapWithTxInput, "tenantId" | "userId" | "now">): Promise<void> {
|
|
const onboarding = await tx.onboarding.findUnique({
|
|
where: { id: SHK_FIRST_STEPS_CHECKLIST_ID },
|
|
select: {
|
|
id: true,
|
|
title: true,
|
|
type: true,
|
|
realtime: true,
|
|
active: true,
|
|
canBeDismissed: true,
|
|
height: true,
|
|
steps: { select: { id: true, order: true, block: true } },
|
|
},
|
|
});
|
|
if (
|
|
!onboarding ||
|
|
onboarding.title !== SHK_FIRST_STEPS_CHECKLIST_CODE ||
|
|
onboarding.type !== "page" ||
|
|
onboarding.realtime !== false ||
|
|
!onboarding.active ||
|
|
onboarding.canBeDismissed !== true ||
|
|
onboarding.height !== null ||
|
|
!hasExactShkFirstSteps(onboarding.steps)
|
|
) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-catalog" });
|
|
}
|
|
const session = await tx.onboardingSession.upsert({
|
|
where: {
|
|
onboardingId_userId_tenantId: {
|
|
onboardingId: onboarding.id,
|
|
userId: input.userId,
|
|
tenantId: input.tenantId,
|
|
},
|
|
},
|
|
create: {
|
|
onboardingId: onboarding.id,
|
|
userId: input.userId,
|
|
tenantId: input.tenantId,
|
|
status: "active",
|
|
startedAt: input.now ?? new Date(),
|
|
},
|
|
update: {},
|
|
});
|
|
await tx.onboardingSessionStep.createMany({
|
|
data: SHK_FIRST_STEPS.map((step) => ({ onboardingSessionId: session.id, stepId: step.id })),
|
|
skipDuplicates: true,
|
|
});
|
|
}
|
|
|
|
async function provisionAutomationPlaceholdersWithTx(
|
|
tx: TenantRlsClient,
|
|
input: Pick<BootstrapWithTxInput, "tenantId" | "userId">,
|
|
config: ShkV2TenantBootstrapConfig
|
|
): Promise<void> {
|
|
await tx.automationTemplate.createMany({
|
|
data: config.automationPlaceholders.map((placeholder) => ({
|
|
tenantId: input.tenantId,
|
|
name: placeholder.templateKey,
|
|
description: null,
|
|
category: placeholder.category,
|
|
flowData: {
|
|
templateKey: placeholder.templateKey,
|
|
schemaVersion: config.schemaVersion,
|
|
isExecutable: placeholder.isExecutable,
|
|
nodes: placeholder.nodes,
|
|
activationGates: placeholder.activationGates,
|
|
} as Prisma.InputJsonValue,
|
|
isPublished: placeholder.isPublished,
|
|
createdByUserId: input.userId,
|
|
isDemoData: false,
|
|
})),
|
|
skipDuplicates: true,
|
|
});
|
|
}
|
|
|
|
const isCreationRequestKey = isSignupCreationRequestKey;
|
|
|
|
/**
|
|
* A creation key is never used as a database id directly. The authenticated
|
|
* owner id and a domain separator make chosen-key targeting across users
|
|
* computationally infeasible while keeping retries deterministic.
|
|
*/
|
|
export function deriveTenantCreationId(userId: string, creationRequestKey: string): string {
|
|
return deriveCreationUuid("tenant-creation:v1", userId, creationRequestKey);
|
|
}
|
|
|
|
export function deriveTenantReservationId(operatorUserId: string, reservationRequestKey: string): string {
|
|
return deriveCreationUuid("tenant-reservation:v1", operatorUserId, reservationRequestKey);
|
|
}
|
|
|
|
export function deriveSignupUserId(normalizedEmail: string, creationRequestKey: string): string {
|
|
return deriveCreationUuid("signup-user:v1", normalizeEmail(normalizedEmail), creationRequestKey);
|
|
}
|
|
|
|
export function deriveSignupTenantId(normalizedEmail: string, creationRequestKey: string): string {
|
|
return deriveCreationUuid("signup-tenant:v1", normalizeEmail(normalizedEmail), creationRequestKey);
|
|
}
|
|
|
|
function deriveCreationUuid(domain: string, identity: string, creationRequestKey: string): string {
|
|
const bytes = createHash("sha256").update(domain).update("\0").update(identity).update("\0").update(creationRequestKey).digest().subarray(0, 16);
|
|
bytes[6] = (bytes[6]! & 0x0f) | 0x50;
|
|
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
|
|
const hex = Buffer.from(bytes).toString("hex");
|
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
}
|
|
|
|
function hashSignupCreationPayload(input: SignupTenantBootstrapInput, normalizedEmail: string): string {
|
|
return createHash("sha256")
|
|
.update(
|
|
JSON.stringify({
|
|
contract: "signup-creation-request/v2",
|
|
key: input.creationRequestKey,
|
|
normalizedEmail,
|
|
company: input.company,
|
|
firstName: input.firstName,
|
|
lastName: input.lastName,
|
|
avatarURL: input.avatarURL ?? null,
|
|
locale: input.locale ?? null,
|
|
slug: input.slug ?? null,
|
|
billingPreference: input.billingPreference
|
|
? {
|
|
selectedSubscriptionPriceId: input.billingPreference.selectedSubscriptionPriceId,
|
|
selectedOfficeSeatQuantity: input.billingPreference.selectedOfficeSeatQuantity,
|
|
selectedFieldSeatQuantity: input.billingPreference.selectedFieldSeatQuantity,
|
|
}
|
|
: null,
|
|
})
|
|
)
|
|
.digest("hex");
|
|
}
|
|
|
|
function hashLegacySignupCreationPayload(input: SignupTenantBootstrapInput, normalizedEmail: string): string {
|
|
return createHash("sha256")
|
|
.update(
|
|
JSON.stringify({
|
|
contract: "signup-creation-request/v1",
|
|
key: input.creationRequestKey,
|
|
normalizedEmail,
|
|
company: input.company,
|
|
firstName: input.firstName,
|
|
lastName: input.lastName,
|
|
avatarURL: input.avatarURL ?? null,
|
|
locale: input.locale ?? null,
|
|
slug: input.slug ?? null,
|
|
})
|
|
)
|
|
.digest("hex");
|
|
}
|
|
|
|
function hashTenantCreationPayload(input: OwnedTenantCreationReplayInput): string {
|
|
return createHash("sha256")
|
|
.update(
|
|
JSON.stringify({
|
|
contract: "tenant-creation-request/v1",
|
|
userId: input.userId,
|
|
key: input.creationRequestKey,
|
|
name: input.name,
|
|
slug: input.slug ?? null,
|
|
})
|
|
)
|
|
.digest("hex");
|
|
}
|
|
|
|
function hashTenantReservationPayload(input: OwnerlessTenantReservationInput): string {
|
|
return createHash("sha256")
|
|
.update(
|
|
JSON.stringify({
|
|
contract: "tenant-reservation-request/v1",
|
|
operatorUserId: input.operatorUserId,
|
|
key: input.reservationRequestKey,
|
|
name: input.name,
|
|
slug: input.slug ?? null,
|
|
ownerInvitation: {
|
|
email: normalizeEmail(input.ownerInvitation.email),
|
|
firstName: input.ownerInvitation.firstName.trim(),
|
|
lastName: input.ownerInvitation.lastName.trim(),
|
|
fromUserId: input.ownerInvitation.fromUserId,
|
|
},
|
|
})
|
|
)
|
|
.digest("hex");
|
|
}
|
|
|
|
async function persistTenantReservationMarkerWithTx(tx: TenantRlsClient, tenant: Tenant, reservationRequestKey: string, requestHash: string): Promise<void> {
|
|
const marker = await tx.idempotencyKey.upsert({
|
|
where: reservationMarkerWhere(tenant.id, reservationRequestKey),
|
|
create: {
|
|
tenantId: tenant.id,
|
|
partitionKey: markerPartition(tenant.id),
|
|
scope: TENANT_RESERVATION_SCOPE,
|
|
key: reservationRequestKey,
|
|
requestHash,
|
|
responseStatus: 201,
|
|
responseBody: {
|
|
state: "reserved",
|
|
tenantName: tenant.name,
|
|
tenantSlug: tenant.slug,
|
|
},
|
|
},
|
|
update: {},
|
|
select: { requestHash: true, responseStatus: true, responseBody: true },
|
|
});
|
|
assertTenantReservationReplay(tenant, reservationRequestKey, requestHash, marker);
|
|
}
|
|
|
|
async function validateTenantReservationReplayWithTx(tx: TenantRlsClient, tenant: Tenant, reservationRequestKey: string, requestHash: string): Promise<void> {
|
|
const marker = await tx.idempotencyKey.findUnique({
|
|
where: reservationMarkerWhere(tenant.id, reservationRequestKey),
|
|
select: { requestHash: true, responseStatus: true, responseBody: true },
|
|
});
|
|
assertTenantReservationReplay(tenant, reservationRequestKey, requestHash, marker);
|
|
}
|
|
|
|
function assertTenantReservationReplay(
|
|
tenant: Tenant,
|
|
reservationRequestKey: string,
|
|
requestHash: string,
|
|
marker: { requestHash: string; responseStatus: number; responseBody: Prisma.JsonValue | null } | null
|
|
): void {
|
|
const body = marker?.responseBody;
|
|
const isBodyMatch =
|
|
body !== null &&
|
|
typeof body === "object" &&
|
|
!Array.isArray(body) &&
|
|
body.state === "reserved" &&
|
|
body.tenantName === tenant.name &&
|
|
body.tenantSlug === tenant.slug;
|
|
if (marker?.requestHash !== requestHash || marker?.responseStatus !== 201 || !isBodyMatch) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: TENANT_RESERVATION_SCOPE,
|
|
key: reservationRequestKey,
|
|
});
|
|
}
|
|
}
|
|
|
|
async function validateOwnedTenantCreationReplayWithTx(
|
|
tx: TenantRlsClient,
|
|
tenant: Tenant,
|
|
input: OwnedTenantCreationReplayInput,
|
|
payloadHash: string
|
|
): Promise<void> {
|
|
const owner = await tx.tenantUser.findFirst({
|
|
where: {
|
|
tenantId: tenant.id,
|
|
userId: input.userId,
|
|
type: TenantUserType.OWNER,
|
|
status: TenantUserStatus.ACTIVE,
|
|
},
|
|
select: { id: true },
|
|
});
|
|
const marker = await tx.idempotencyKey.findUnique({
|
|
where: markerWhere(tenant.id, SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey),
|
|
select: { requestHash: true, responseStatus: true, responseBody: true },
|
|
});
|
|
const markerBody = readMarkerBody(marker?.responseBody ?? null);
|
|
const expectedCreationRequest: TenantCreationRequestMarker = {
|
|
key: input.creationRequestKey,
|
|
payloadHash,
|
|
tenantName: tenant.name,
|
|
tenantSlug: tenant.slug,
|
|
};
|
|
const isCompletedOwnerReplay =
|
|
tenant.name === input.name &&
|
|
tenant.active &&
|
|
tenant.deactivatedReason === null &&
|
|
owner !== null &&
|
|
marker?.requestHash === SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST &&
|
|
marker.responseStatus === 201 &&
|
|
markerBody?.state === "completed" &&
|
|
matchesCreationRequest(markerBody.creationRequest, expectedCreationRequest);
|
|
if (!isCompletedOwnerReplay) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: input.creationRequestKey,
|
|
});
|
|
}
|
|
}
|
|
|
|
async function validateSignupTenantCreationReplayWithTx(
|
|
tx: TenantRlsClient,
|
|
tenant: Tenant,
|
|
input: SignupTenantBootstrapInput,
|
|
normalizedEmail: string,
|
|
userId: string,
|
|
payloadHash: string,
|
|
verifiedPasswordHash: string
|
|
): Promise<User> {
|
|
// Argon verification already completed outside the interactive transaction.
|
|
// Lock and compare the exact verified hash so a concurrent password change
|
|
// fails closed without holding a database connection during CPU-heavy work.
|
|
const lockedUsers = await tx.$queryRaw<User[]>`SELECT * FROM public."User" WHERE id = ${userId} FOR UPDATE`;
|
|
const user = lockedUsers.length === 1 ? lockedUsers[0] : null;
|
|
const owner = await tx.tenantUser.findFirst({
|
|
where: {
|
|
tenantId: tenant.id,
|
|
userId,
|
|
type: TenantUserType.OWNER,
|
|
status: TenantUserStatus.ACTIVE,
|
|
},
|
|
select: { id: true },
|
|
});
|
|
const marker = await tx.idempotencyKey.findUnique({
|
|
where: markerWhere(tenant.id, SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey),
|
|
select: { requestHash: true, responseStatus: true, responseBody: true },
|
|
});
|
|
const markerBody = readMarkerBody(marker?.responseBody ?? null);
|
|
const expectedCreationRequest: TenantCreationRequestMarker = {
|
|
key: input.creationRequestKey,
|
|
payloadHash,
|
|
tenantName: tenant.name,
|
|
tenantSlug: tenant.slug,
|
|
signup: { normalizedEmail, userId },
|
|
};
|
|
const expectedLegacyCreationRequest: TenantCreationRequestMarker = {
|
|
...expectedCreationRequest,
|
|
payloadHash: hashLegacySignupCreationPayload(input, normalizedEmail),
|
|
};
|
|
const hasV2CreationMarker = matchesCreationRequest(markerBody?.creationRequest, expectedCreationRequest);
|
|
const hasLegacyCreationMarker = matchesCreationRequest(markerBody?.creationRequest, expectedLegacyCreationRequest);
|
|
const billingPreferenceMatches = input.billingPreference
|
|
? hasV2CreationMarker || hasLegacyCreationMarker
|
|
? await signupReplayBillingPreferenceMatchesWithTx(tx, tenant.id, userId, input.billingPreference, hasLegacyCreationMarker)
|
|
: false
|
|
: true;
|
|
const replayShapeMatches =
|
|
tenant.id === deriveSignupTenantId(normalizedEmail, input.creationRequestKey) &&
|
|
tenant.name === input.company &&
|
|
tenant.active &&
|
|
tenant.deactivatedReason === null &&
|
|
user?.id === userId &&
|
|
normalizeEmail(user.email) === normalizedEmail &&
|
|
user.passwordHash === verifiedPasswordHash &&
|
|
user.defaultTenantId === tenant.id &&
|
|
user.active &&
|
|
owner !== null &&
|
|
marker?.requestHash === SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST &&
|
|
marker.responseStatus === 201 &&
|
|
markerBody?.state === "completed" &&
|
|
billingPreferenceMatches &&
|
|
(hasV2CreationMarker || hasLegacyCreationMarker);
|
|
if (!replayShapeMatches || !user) {
|
|
throw new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: input.creationRequestKey,
|
|
});
|
|
}
|
|
return user;
|
|
}
|
|
|
|
async function signupReplayBillingPreferenceMatchesWithTx(
|
|
tx: TenantRlsClient,
|
|
tenantId: string,
|
|
userId: string,
|
|
preference: RegistrationBillingPreference,
|
|
allowLegacyRegistrationFallback: boolean
|
|
): Promise<boolean> {
|
|
const tenantPreference = await tx.tenantProductConfiguration.findUnique({
|
|
where: { tenantId },
|
|
select: {
|
|
signupSubscriptionPriceId: true,
|
|
signupOfficeSeatQuantity: true,
|
|
signupFieldSeatQuantity: true,
|
|
},
|
|
});
|
|
if (tenantPreference) {
|
|
return (
|
|
tenantPreference.signupSubscriptionPriceId === preference.selectedSubscriptionPriceId &&
|
|
tenantPreference.signupOfficeSeatQuantity === preference.selectedOfficeSeatQuantity &&
|
|
tenantPreference.signupFieldSeatQuantity === preference.selectedFieldSeatQuantity
|
|
);
|
|
}
|
|
if (!allowLegacyRegistrationFallback) return false;
|
|
|
|
const registrationPreference = await findRegistrationBillingPreferenceCapability(tenantId, userId, tx);
|
|
return (
|
|
registrationPreference?.selectedSubscriptionPriceId === preference.selectedSubscriptionPriceId &&
|
|
registrationPreference.selectedOfficeSeatQuantity === preference.selectedOfficeSeatQuantity &&
|
|
registrationPreference.selectedFieldSeatQuantity === preference.selectedFieldSeatQuantity
|
|
);
|
|
}
|
|
|
|
async function readAndVerifySignupReplayPasswordHash({
|
|
userId,
|
|
password,
|
|
creationRequestKey,
|
|
}: {
|
|
userId: string;
|
|
password: string;
|
|
creationRequestKey: string;
|
|
}): Promise<string> {
|
|
const conflict = () =>
|
|
new CatalogError(foundationErrors.idempotencyConflict, {
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key: creationRequestKey,
|
|
});
|
|
const current = getRlsExecutionContext();
|
|
if (current && current.userId !== userId) {
|
|
throw conflict();
|
|
}
|
|
|
|
const readAndVerify = async () => {
|
|
const user = await db.user.findUnique({
|
|
where: { id: userId },
|
|
select: { passwordHash: true },
|
|
});
|
|
if (!user?.passwordHash) {
|
|
throw conflict();
|
|
}
|
|
const verification = await verifyPassword(password, user.passwordHash);
|
|
if (!verification.valid) {
|
|
throw conflict();
|
|
}
|
|
return user.passwordHash;
|
|
};
|
|
|
|
if (!current) {
|
|
return await runWithRlsContext({ userId }, readAndVerify);
|
|
}
|
|
if (current.tenantId || current.transaction || current.publicKnowledgeBaseId) {
|
|
return await runWithIsolatedUserRlsContext(userId, readAndVerify);
|
|
}
|
|
return await readAndVerify();
|
|
}
|
|
|
|
function matchesCreationRequest(actual: TenantCreationRequestMarker | undefined, expected: TenantCreationRequestMarker): boolean {
|
|
return (
|
|
actual?.key === expected.key &&
|
|
actual.payloadHash === expected.payloadHash &&
|
|
actual.tenantName === expected.tenantName &&
|
|
actual.tenantSlug === expected.tenantSlug &&
|
|
actual.signup?.normalizedEmail === expected.signup?.normalizedEmail &&
|
|
actual.signup?.userId === expected.signup?.userId
|
|
);
|
|
}
|
|
|
|
function normalizeEmail(value: string): string {
|
|
return value.trim().toLowerCase();
|
|
}
|
|
|
|
function isUniqueConstraintViolation(error: unknown): boolean {
|
|
return Boolean(error && typeof error === "object" && "code" in error && error.code === "P2002");
|
|
}
|
|
|
|
function markerPartition(tenantId: string): string {
|
|
return `tenant:${tenantId}`;
|
|
}
|
|
|
|
function markerWhere(tenantId: string, key: string) {
|
|
return {
|
|
idempotency_key_partition_scope_key: {
|
|
partitionKey: markerPartition(tenantId),
|
|
scope: SHK_V2_BOOTSTRAP_SCOPE,
|
|
key,
|
|
},
|
|
} as const;
|
|
}
|
|
|
|
const TENANT_RESERVATION_SCOPE = "tenant-reservation";
|
|
|
|
function reservationMarkerWhere(tenantId: string, key: string) {
|
|
return {
|
|
idempotency_key_partition_scope_key: {
|
|
partitionKey: markerPartition(tenantId),
|
|
scope: TENANT_RESERVATION_SCOPE,
|
|
key,
|
|
},
|
|
} as const;
|
|
}
|
|
|
|
function readMarkerBody(value: Prisma.JsonValue | null): BootstrapMarkerBody | null {
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
const state = value.state;
|
|
if (state === "started" && typeof value.attemptId === "string") {
|
|
return value as BootstrapMarkerBody;
|
|
}
|
|
if (state === "completed" && typeof value.completedAt === "string") {
|
|
return value as BootstrapMarkerBody;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function requireMapValue(map: Map<string, string>, key: string, resource: string): string {
|
|
const value = map.get(key);
|
|
if (!value) {
|
|
throw new CatalogError(foundationErrors.notFound, { resource, key });
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function createdTenantContext(tenantId: string, userId: string): Record<string, string> {
|
|
return { tenantId, userId };
|
|
}
|
|
|
|
/**
|
|
* A cache or hook outage after commit must not turn a successful creation into
|
|
* a retryable HTTP failure. New tenants cannot have a permissive stale cache;
|
|
* failures here are logged while the remaining post-commit work still runs.
|
|
*/
|
|
async function runPostCommitStep(operation: string, context: Record<string, string>, callback: () => Promise<void>): Promise<void> {
|
|
try {
|
|
await callback();
|
|
} catch (error) {
|
|
tenantBootstrapLogger.warn(
|
|
{
|
|
op: operation,
|
|
...context,
|
|
err: { name: error instanceof Error ? error.name : "Error" },
|
|
},
|
|
"Tenant bootstrap committed, but a post-commit step failed."
|
|
);
|
|
}
|
|
}
|