340 lines
13 KiB
TypeScript
340 lines
13 KiB
TypeScript
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
|
import type { Prisma, TenantUserInvitation } from "@hivegrid/db/prisma-browser";
|
|
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import {
|
|
WORKSPACE_INVITE_STATUS_ACCEPTED,
|
|
WORKSPACE_INVITE_STATUS_DELIVERY_FAILED,
|
|
WORKSPACE_INVITE_STATUS_EXPIRED,
|
|
WORKSPACE_INVITE_STATUS_PENDING,
|
|
WORKSPACE_INVITE_STATUS_REVOKED,
|
|
} from "@hivegrid/db/workspace-invites.server";
|
|
|
|
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
|
import { db } from "~/utils/db.server";
|
|
|
|
import { TENANT_PENDING_OWNER_REASON } from "./tenantBootstrap.constants";
|
|
import {
|
|
isExactReservedOwnerInvitationMailReplay,
|
|
issueReservedOwnerInvitationWithTx,
|
|
type ReservedOwnerInvitationDraft,
|
|
} from "./ownerInvitationIssuance.server";
|
|
|
|
const OWNER_INVITATION_REISSUE_SCOPE = "tenant-owner-invitation-reissue";
|
|
|
|
type OwnerIdentity = {
|
|
email: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
};
|
|
|
|
export type ReservedOwnerInvitationReissueTarget = OwnerIdentity & {
|
|
invitationId: string;
|
|
tenantName: string;
|
|
};
|
|
|
|
export type ReservedOwnerInvitationReissueInput = {
|
|
tenantId: string;
|
|
operatorUserId: string;
|
|
sourceInvitationId: string;
|
|
ownerInvitation: ReservedOwnerInvitationDraft;
|
|
};
|
|
|
|
/**
|
|
* Resolves the only safe OWNER identity that may be rotated. Mail rendering is
|
|
* deliberately performed by the caller after this transaction has completed.
|
|
*/
|
|
export async function getReservedOwnerInvitationReissueTarget(input: {
|
|
tenantId: string;
|
|
operatorUserId: string;
|
|
}): Promise<ReservedOwnerInvitationReissueTarget> {
|
|
assertAuthenticatedOperator(input.operatorUserId);
|
|
assertIdentifier(input.tenantId);
|
|
|
|
return runInReservationTenantContext(input.tenantId, input.operatorUserId, () =>
|
|
db.$transaction(async (tx) => {
|
|
const { tenant, invitations } = await loadReservationState(tx, input.tenantId);
|
|
assertOwnerlessReservation(tenant);
|
|
const invitationSet = assertUnambiguousOwnerInvitationSet(invitations, input.tenantId, new Date());
|
|
|
|
return {
|
|
invitationId: invitationSet.latest.id,
|
|
tenantName: tenant.name,
|
|
...invitationSet.identity,
|
|
};
|
|
})
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Atomically terminalizes the expected OWNER capability and issues its
|
|
* replacement. The stable issuance key makes a parallel or response-loss
|
|
* retry replay the already-created replacement instead of rotating it again.
|
|
*/
|
|
export async function reissueReservedOwnerInvitation(input: ReservedOwnerInvitationReissueInput): Promise<{ invitationId: string; replayed: boolean }> {
|
|
assertAuthenticatedOperator(input.operatorUserId);
|
|
assertIdentifier(input.tenantId);
|
|
assertIdentifier(input.sourceInvitationId);
|
|
if (input.ownerInvitation.fromUserId !== input.operatorUserId) {
|
|
throw reissueNotFound();
|
|
}
|
|
|
|
const requestedIdentity = normalizeOwnerIdentity(input.ownerInvitation);
|
|
if (!isValidOwnerIdentity(requestedIdentity) || !input.ownerInvitation.issuanceKey.trim()) {
|
|
throw reissueConflict(input.ownerInvitation.issuanceKey);
|
|
}
|
|
|
|
return runInReservationTenantContext(input.tenantId, input.operatorUserId, () =>
|
|
db.$transaction(async (tx) => {
|
|
await acquireOwnerInvitationLock(tx, input.tenantId);
|
|
const now = new Date();
|
|
const { tenant, invitations } = await loadReservationState(tx, input.tenantId);
|
|
assertOwnerlessReservation(tenant);
|
|
|
|
const invitationSet = assertUnambiguousOwnerInvitationSet(invitations, input.tenantId, now);
|
|
if (!ownerIdentitiesEqual(invitationSet.identity, requestedIdentity)) {
|
|
throw reissueConflict(input.ownerInvitation.issuanceKey);
|
|
}
|
|
|
|
const source = invitations.find((invitation) => invitation.id === input.sourceInvitationId);
|
|
if (!source || !isEligibleOwnerInvitation(source, input.tenantId, invitationSet.identity, now)) {
|
|
throw reissueConflict(input.ownerInvitation.issuanceKey);
|
|
}
|
|
|
|
const activeInvitations = invitations.filter((invitation) => isActiveOwnerInvitation(invitation, now));
|
|
if (activeInvitations.length > 1) {
|
|
throw reissueConflict(input.ownerInvitation.issuanceKey);
|
|
}
|
|
|
|
const activeInvitation = activeInvitations[0];
|
|
if (
|
|
activeInvitation?.fromUserId === input.operatorUserId &&
|
|
(await hasMatchingInvitationReplay(tx, activeInvitation, input.ownerInvitation))
|
|
) {
|
|
// A response-loss retry renders a fresh raw token before entering this
|
|
// transaction. The mail contract normalizes that token against the
|
|
// already persisted invitation hash, so the same logical issuance key
|
|
// replays the committed capability without another rotation.
|
|
return { invitationId: activeInvitation.id, replayed: true };
|
|
}
|
|
|
|
if (invitationSet.latest.id !== source.id || (activeInvitation && activeInvitation.id !== source.id)) {
|
|
throw reissueConflict(input.ownerInvitation.issuanceKey);
|
|
}
|
|
|
|
if (isPendingInvitation(source)) {
|
|
const transition = await tx.tenantUserInvitation.updateMany({
|
|
where: {
|
|
id: source.id,
|
|
tenantId: input.tenantId,
|
|
type: TenantUserType.OWNER,
|
|
email: source.email,
|
|
firstName: source.firstName,
|
|
lastName: source.lastName,
|
|
pending: true,
|
|
status: WORKSPACE_INVITE_STATUS_PENDING,
|
|
createdUserId: null,
|
|
acceptedAt: null,
|
|
revokedAt: null,
|
|
acceptedByUserId: null,
|
|
revokedByUserId: null,
|
|
},
|
|
data: {
|
|
pending: false,
|
|
status: WORKSPACE_INVITE_STATUS_REVOKED,
|
|
revokedAt: now,
|
|
revokedByUserId: input.operatorUserId,
|
|
},
|
|
});
|
|
if (transition.count !== 1) {
|
|
throw reissueConflict(input.ownerInvitation.issuanceKey);
|
|
}
|
|
}
|
|
|
|
return issueReservedOwnerInvitationWithTx(tx, { tenantId: input.tenantId, ...input.ownerInvitation });
|
|
})
|
|
);
|
|
}
|
|
|
|
type ReservationState = {
|
|
tenant: {
|
|
id: string;
|
|
name: string;
|
|
active: boolean;
|
|
deactivatedReason: string | null;
|
|
_count: { users: number };
|
|
} | null;
|
|
invitations: TenantUserInvitation[];
|
|
};
|
|
|
|
async function loadReservationState(tx: Prisma.TransactionClient, tenantId: string): Promise<ReservationState> {
|
|
const tenant = await tx.tenant.findUnique({
|
|
where: { id: tenantId },
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
active: true,
|
|
deactivatedReason: true,
|
|
_count: { select: { users: true } },
|
|
},
|
|
});
|
|
const invitations = await tx.tenantUserInvitation.findMany({
|
|
where: { tenantId, type: TenantUserType.OWNER },
|
|
orderBy: { id: "desc" },
|
|
// The UI submits the latest capability; an exact response-loss replay can
|
|
// reference only its immediate predecessor. Older history is never a valid
|
|
// rotation source and must not make request latency grow without bound.
|
|
take: 3,
|
|
});
|
|
return { tenant, invitations };
|
|
}
|
|
|
|
function assertOwnerlessReservation(tenant: ReservationState["tenant"]): asserts tenant is NonNullable<ReservationState["tenant"]> {
|
|
if (!tenant || tenant.active || tenant.deactivatedReason !== TENANT_PENDING_OWNER_REASON || tenant._count.users !== 0) {
|
|
throw reissueNotFound();
|
|
}
|
|
}
|
|
|
|
function assertUnambiguousOwnerInvitationSet(
|
|
invitations: TenantUserInvitation[],
|
|
tenantId: string,
|
|
now: Date
|
|
): { latest: TenantUserInvitation; identity: OwnerIdentity } {
|
|
const latest = invitations[0];
|
|
if (!latest) {
|
|
throw reissueNotFound();
|
|
}
|
|
|
|
const identity = normalizeOwnerIdentity(latest);
|
|
if (!isValidOwnerIdentity(identity)) {
|
|
throw reissueNotFound();
|
|
}
|
|
|
|
for (const invitation of invitations) {
|
|
if (!isEligibleOwnerInvitation(invitation, tenantId, identity, now)) {
|
|
throw reissueNotFound();
|
|
}
|
|
}
|
|
|
|
const activeInvitations = invitations.filter((invitation) => isActiveOwnerInvitation(invitation, now));
|
|
if (activeInvitations.length > 1 || (activeInvitations[0] && activeInvitations[0].id !== latest.id)) {
|
|
throw reissueNotFound();
|
|
}
|
|
return { latest, identity };
|
|
}
|
|
|
|
function isEligibleOwnerInvitation(invitation: TenantUserInvitation, tenantId: string, identity: OwnerIdentity, now: Date): boolean {
|
|
if (
|
|
invitation.tenantId !== tenantId ||
|
|
invitation.type !== TenantUserType.OWNER ||
|
|
invitation.status === WORKSPACE_INVITE_STATUS_ACCEPTED ||
|
|
invitation.createdUserId !== null ||
|
|
invitation.acceptedAt !== null ||
|
|
invitation.acceptedByUserId !== null ||
|
|
!ownerIdentitiesEqual(normalizeOwnerIdentity(invitation), identity) ||
|
|
!invitation.tokenHash ||
|
|
!/^[a-f0-9]{64}$/u.test(invitation.tokenHash)
|
|
) {
|
|
return false;
|
|
}
|
|
|
|
if (isPendingInvitation(invitation)) {
|
|
return invitation.revokedAt === null && invitation.revokedByUserId === null;
|
|
}
|
|
if (invitation.status === WORKSPACE_INVITE_STATUS_REVOKED) {
|
|
return !invitation.pending && invitation.revokedAt !== null && invitation.revokedByUserId !== null;
|
|
}
|
|
if (invitation.status === WORKSPACE_INVITE_STATUS_DELIVERY_FAILED) {
|
|
return !invitation.pending && invitation.revokedAt !== null && invitation.revokedByUserId === null;
|
|
}
|
|
if (invitation.status === WORKSPACE_INVITE_STATUS_EXPIRED) {
|
|
return (
|
|
!invitation.pending &&
|
|
invitation.revokedAt === null &&
|
|
invitation.revokedByUserId === null &&
|
|
invitation.expiresAt !== null &&
|
|
invitation.expiresAt <= now
|
|
);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function isPendingInvitation(invitation: TenantUserInvitation): boolean {
|
|
return invitation.status === WORKSPACE_INVITE_STATUS_PENDING && invitation.pending;
|
|
}
|
|
|
|
function isActiveOwnerInvitation(invitation: TenantUserInvitation, now: Date): boolean {
|
|
return isPendingInvitation(invitation) && invitation.revokedAt === null && (invitation.expiresAt === null || invitation.expiresAt > now);
|
|
}
|
|
|
|
async function hasMatchingInvitationReplay(
|
|
tx: Prisma.TransactionClient,
|
|
invitation: TenantUserInvitation,
|
|
ownerInvitation: ReservedOwnerInvitationDraft
|
|
): Promise<boolean> {
|
|
const outbox = await tx.outboxEvent.findUnique({
|
|
where: { dispatchKey: ownerInvitationDispatchKey(invitation.id) },
|
|
select: { tenantId: true, eventType: true, payload: true, status: true },
|
|
});
|
|
if (!outbox || !invitation.tokenHash) {
|
|
return false;
|
|
}
|
|
return isExactReservedOwnerInvitationMailReplay(outbox, { tenantId: invitation.tenantId, ...ownerInvitation }, invitation.id, invitation.tokenHash);
|
|
}
|
|
|
|
function acquireOwnerInvitationLock(tx: Prisma.TransactionClient, tenantId: string): Promise<unknown> {
|
|
return tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`tenant-owner-invitation:${tenantId}`}, 0))`;
|
|
}
|
|
|
|
function runInReservationTenantContext<T>(tenantId: string, operatorUserId: string, callback: () => T): T {
|
|
const current = getRlsExecutionContext();
|
|
if (!current || current.userId !== operatorUserId) {
|
|
throw reissueNotFound();
|
|
}
|
|
|
|
const run = () => runWithRlsContext({ tenantId, userId: operatorUserId }, callback);
|
|
if (current.tenantId !== undefined || current.transaction !== undefined || current.publicKnowledgeBaseId !== undefined) {
|
|
return runWithIsolatedUserRlsContext(operatorUserId, run);
|
|
}
|
|
return run();
|
|
}
|
|
|
|
function normalizeOwnerIdentity(input: Pick<TenantUserInvitation, "email" | "firstName" | "lastName"> | ReservedOwnerInvitationDraft): OwnerIdentity {
|
|
return {
|
|
email: input.email.trim().toLowerCase(),
|
|
firstName: input.firstName.trim(),
|
|
lastName: input.lastName.trim(),
|
|
};
|
|
}
|
|
|
|
function isValidOwnerIdentity(identity: OwnerIdentity): boolean {
|
|
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/u.test(identity.email) && Boolean(identity.firstName && identity.lastName);
|
|
}
|
|
|
|
function ownerIdentitiesEqual(left: OwnerIdentity, right: OwnerIdentity): boolean {
|
|
return left.email === right.email && left.firstName === right.firstName && left.lastName === right.lastName;
|
|
}
|
|
|
|
function ownerInvitationDispatchKey(invitationId: string): string {
|
|
return `mail:workspace-owner-invite:${invitationId}`;
|
|
}
|
|
|
|
function assertAuthenticatedOperator(operatorUserId: string): void {
|
|
if (!operatorUserId.trim() || getRlsExecutionContext()?.userId !== operatorUserId) {
|
|
throw reissueNotFound();
|
|
}
|
|
}
|
|
|
|
function assertIdentifier(value: string): void {
|
|
if (!value.trim() || value !== value.trim() || value.length > 191 || value.includes("\u0000")) {
|
|
throw reissueNotFound();
|
|
}
|
|
}
|
|
|
|
function reissueNotFound(): CatalogError {
|
|
return new CatalogError(foundationErrors.notFound, { resource: OWNER_INVITATION_REISSUE_SCOPE });
|
|
}
|
|
|
|
function reissueConflict(key: string): CatalogError {
|
|
return new CatalogError(foundationErrors.idempotencyConflict, { scope: OWNER_INVITATION_REISSUE_SCOPE, key });
|
|
}
|