import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; import { getDbClient } from "./client.server.js"; import type { Prisma, TenantUserInvitation } from "./prisma-browser.js"; import { runWithRlsContext } from "./rls-context.server.js"; import { resolveWorkspaceInviteRlsIdentity } from "./rls-resolvers.server.js"; export const WORKSPACE_INVITE_STATUS_PENDING = "pending" as const; export const WORKSPACE_INVITE_STATUS_ACCEPTED = "accepted" as const; export const WORKSPACE_INVITE_STATUS_REVOKED = "revoked" as const; export const WORKSPACE_INVITE_STATUS_EXPIRED = "expired" as const; export const WORKSPACE_INVITE_STATUS_DELIVERY_FAILED = "delivery_failed" as const; export const WORKSPACE_INVITE_TOKEN_PREFIX_LENGTH = 12; export const WORKSPACE_INVITE_TOKEN_BYTE_LENGTH = 32; // R-P2b (User-Lifecycle) — Einladungen laufen nach 48h ab (DoD "Einladung 48h"). Single Source of // Truth: createWorkspaceInvite setzt diesen Default, wenn der Aufrufer kein expiresAt uebergibt. export const WORKSPACE_INVITE_TTL_MS = 48 * 60 * 60 * 1000; export type WorkspaceInviteStatus = | typeof WORKSPACE_INVITE_STATUS_PENDING | typeof WORKSPACE_INVITE_STATUS_ACCEPTED | typeof WORKSPACE_INVITE_STATUS_REVOKED | typeof WORKSPACE_INVITE_STATUS_EXPIRED | typeof WORKSPACE_INVITE_STATUS_DELIVERY_FAILED; export type WorkspaceInviteErrorCode = "duplicate_active_invite" | "invite_not_found" | "invite_expired" | "invite_already_finalized"; export class WorkspaceInviteError extends Error { readonly code: WorkspaceInviteErrorCode; constructor(code: WorkspaceInviteErrorCode) { super(code); this.name = "WorkspaceInviteError"; this.code = code; } } export type WorkspaceInviteDto = { id: string; tenantId: string; email: string; firstName: string; lastName: string; type: number; status: WorkspaceInviteStatus; pending: boolean; tokenPrefix: string | null; createdUserId: string | null; fromUserId: string | null; acceptedByUserId: string | null; revokedByUserId: string | null; expiresAt: Date | null; acceptedAt: Date | null; revokedAt: Date | null; }; export type WorkspaceInviteCreateResult = WorkspaceInviteDto & { token: string; }; export type WorkspaceInviteCreateInput = { tenantId: string; email: string; firstName: string; lastName: string; type: number; fromUserId?: string | null; createdUserId?: string | null; expiresAt?: Date | null; token?: string; now?: Date; }; export type WorkspaceInviteListInput = { tenantId: string; status?: WorkspaceInviteStatus; email?: string; now?: Date; }; export type WorkspaceInviteAcceptInput = { tenantId: string; inviteId: string; token: string; acceptedByUserId: string; /** Set only when accepting this invite created the accepting user account. */ createdUserId?: string; /** * Bind a previously unbound created-user marker as part of the caller's * existing user-creation transaction. This is deliberately rejected unless * an explicit transaction-compatible client is supplied. */ bindCreatedUserId?: boolean; now?: Date; }; export type WorkspaceInviteLookupInput = { token: string; now?: Date; }; export type WorkspaceInviteRevokeInput = { tenantId: string; inviteId: string; revokedByUserId: string; now?: Date; }; export type WorkspaceInviteClient = { tenantUserInvitation: { findFirst(args: { where: Prisma.TenantUserInvitationWhereInput; orderBy?: Prisma.TenantUserInvitationOrderByWithRelationInput | Prisma.TenantUserInvitationOrderByWithRelationInput[]; }): Promise; findMany(args: { where: Prisma.TenantUserInvitationWhereInput; orderBy: Prisma.TenantUserInvitationOrderByWithRelationInput | Prisma.TenantUserInvitationOrderByWithRelationInput[]; }): Promise; create(args: { data: Prisma.TenantUserInvitationUncheckedCreateInput }): Promise; update(args: { where: { id: string }; data: Prisma.TenantUserInvitationUncheckedUpdateInput }): Promise; updateMany(args: { where: Prisma.TenantUserInvitationWhereInput; data: Prisma.TenantUserInvitationUncheckedUpdateManyInput }): Promise<{ count: number }>; }; }; function normalizeEmail(email: string): string { return email.trim().toLowerCase(); } export function generateWorkspaceInviteToken(): string { return randomBytes(WORKSPACE_INVITE_TOKEN_BYTE_LENGTH).toString("base64url"); } export function hashWorkspaceInviteToken(token: string): string { return createHash("sha256").update(token).digest("hex"); } export function getWorkspaceInviteTokenPrefix(token: string): string { return token.slice(0, WORKSPACE_INVITE_TOKEN_PREFIX_LENGTH); } function tokenHashesMatch(actualHash: string | null, expectedHash: string): boolean { if (!actualHash) { return false; } const actual = Buffer.from(actualHash, "hex"); const expected = Buffer.from(expectedHash, "hex"); return actual.length === expected.length && timingSafeEqual(actual, expected); } function resolveInviteStatus(invite: Pick, now = new Date()): WorkspaceInviteStatus { if (invite.status === WORKSPACE_INVITE_STATUS_ACCEPTED || invite.acceptedAt) { return WORKSPACE_INVITE_STATUS_ACCEPTED; } if (invite.status === WORKSPACE_INVITE_STATUS_DELIVERY_FAILED) { return WORKSPACE_INVITE_STATUS_DELIVERY_FAILED; } if (invite.status === WORKSPACE_INVITE_STATUS_REVOKED || invite.revokedAt) { return WORKSPACE_INVITE_STATUS_REVOKED; } if (invite.status === WORKSPACE_INVITE_STATUS_EXPIRED || (invite.expiresAt && invite.expiresAt <= now)) { return WORKSPACE_INVITE_STATUS_EXPIRED; } return WORKSPACE_INVITE_STATUS_PENDING; } export function serializeWorkspaceInvite(invite: TenantUserInvitation, now = new Date()): WorkspaceInviteDto { const status = resolveInviteStatus(invite, now); return { id: invite.id, tenantId: invite.tenantId, email: invite.email, firstName: invite.firstName, lastName: invite.lastName, type: invite.type, status, pending: status === WORKSPACE_INVITE_STATUS_PENDING, tokenPrefix: invite.tokenPrefix, createdUserId: invite.createdUserId, fromUserId: invite.fromUserId, acceptedByUserId: invite.acceptedByUserId, revokedByUserId: invite.revokedByUserId, expiresAt: invite.expiresAt, acceptedAt: invite.acceptedAt, revokedAt: invite.revokedAt, }; } function getClient(client?: WorkspaceInviteClient): WorkspaceInviteClient { return client ?? getDbClient(); } export async function createWorkspaceInvite(input: WorkspaceInviteCreateInput, client?: WorkspaceInviteClient): Promise { const db = getClient(client); const now = input.now ?? new Date(); const email = normalizeEmail(input.email); await db.tenantUserInvitation.updateMany({ where: { tenantId: input.tenantId, email, pending: true, status: WORKSPACE_INVITE_STATUS_PENDING, expiresAt: { lte: now }, }, data: { pending: false, status: WORKSPACE_INVITE_STATUS_EXPIRED, }, }); const existing = await db.tenantUserInvitation.findFirst({ where: { tenantId: input.tenantId, email, status: WORKSPACE_INVITE_STATUS_PENDING, OR: [{ expiresAt: null }, { expiresAt: { gt: now } }], }, orderBy: { id: "asc" }, }); if (existing) { throw new WorkspaceInviteError("duplicate_active_invite"); } const token = input.token ?? generateWorkspaceInviteToken(); const tokenHash = hashWorkspaceInviteToken(token); let invite: TenantUserInvitation; try { invite = await db.tenantUserInvitation.create({ data: { tenantId: input.tenantId, email, firstName: input.firstName, lastName: input.lastName, type: input.type, pending: true, status: WORKSPACE_INVITE_STATUS_PENDING, tokenHash, tokenPrefix: getWorkspaceInviteTokenPrefix(token), // DoD "Einladung 48h": Default-Ablauf, wenn der Aufrufer nichts vorgibt (kein null mehr). expiresAt: input.expiresAt ?? new Date(now.getTime() + WORKSPACE_INVITE_TTL_MS), createdUserId: input.createdUserId ?? null, fromUserId: input.fromUserId ?? null, }, }); } catch (error) { if (isPrismaUniqueConstraintError(error)) { throw new WorkspaceInviteError("duplicate_active_invite"); } throw error; } return { ...serializeWorkspaceInvite(invite, now), token }; } function isPrismaUniqueConstraintError(error: unknown): boolean { return typeof error === "object" && error !== null && "code" in error && error.code === "P2002"; } export async function listWorkspaceInvites(input: WorkspaceInviteListInput, client?: WorkspaceInviteClient): Promise { const db = getClient(client); const invites = await db.tenantUserInvitation.findMany({ where: { tenantId: input.tenantId, ...(input.status ? { status: input.status } : {}), ...(input.email ? { email: normalizeEmail(input.email) } : {}), }, orderBy: [{ status: "asc" }, { expiresAt: "asc" }, { id: "asc" }], }); return invites.map((invite) => serializeWorkspaceInvite(invite, input.now)); } export async function getWorkspaceInviteByToken(input: WorkspaceInviteLookupInput, client?: WorkspaceInviteClient): Promise { if (!client) { const identity = await resolveWorkspaceInviteRlsIdentity(hashWorkspaceInviteToken(input.token)); if (!identity) return null; return runWithRlsContext({ tenantId: identity.tenantId }, () => getWorkspaceInviteByToken(input, getDbClient())); } const db = getClient(client); const tokenHash = hashWorkspaceInviteToken(input.token); const invite = await db.tenantUserInvitation.findFirst({ where: { tokenHash }, orderBy: { id: "asc" }, }); return invite && tokenHashesMatch(invite.tokenHash, tokenHash) ? serializeWorkspaceInvite(invite, input.now) : null; } export async function acceptWorkspaceInvite(input: WorkspaceInviteAcceptInput, client?: WorkspaceInviteClient): Promise { if (input.createdUserId !== undefined && input.createdUserId !== input.acceptedByUserId) { throw new WorkspaceInviteError("invite_not_found"); } if (input.bindCreatedUserId && (!client || input.createdUserId === undefined)) { throw new WorkspaceInviteError("invite_not_found"); } if (!client) { const identity = await resolveWorkspaceInviteRlsIdentity(hashWorkspaceInviteToken(input.token)); if (!identity || identity.tenantId !== input.tenantId || identity.resourceId !== input.inviteId) { throw new WorkspaceInviteError("invite_not_found"); } return runWithRlsContext({ tenantId: identity.tenantId, userId: input.acceptedByUserId }, () => acceptWorkspaceInvite(input, getDbClient())); } const db = getClient(client); const now = input.now ?? new Date(); const tokenHash = hashWorkspaceInviteToken(input.token); const candidate = await db.tenantUserInvitation.findFirst({ where: { id: input.inviteId, tenantId: input.tenantId, tokenHash, }, orderBy: { id: "asc" }, }); if (!candidate || !tokenHashesMatch(candidate.tokenHash, tokenHash)) { throw new WorkspaceInviteError("invite_not_found"); } const createdUserId = input.createdUserId ?? null; const expectedCreatedUserId = input.bindCreatedUserId ? null : createdUserId; if (candidate.createdUserId !== expectedCreatedUserId) { throw new WorkspaceInviteError("invite_not_found"); } const status = resolveInviteStatus(candidate, now); if (status === WORKSPACE_INVITE_STATUS_EXPIRED) { throw new WorkspaceInviteError("invite_expired"); } if (status !== WORKSPACE_INVITE_STATUS_PENDING) { throw new WorkspaceInviteError("invite_already_finalized"); } const transition = await db.tenantUserInvitation.updateMany({ where: { id: candidate.id, tenantId: input.tenantId, tokenHash, pending: true, status: WORKSPACE_INVITE_STATUS_PENDING, acceptedAt: null, revokedAt: null, acceptedByUserId: null, revokedByUserId: null, createdUserId: expectedCreatedUserId, OR: [{ expiresAt: null }, { expiresAt: { gt: now } }], }, data: { status: WORKSPACE_INVITE_STATUS_ACCEPTED, pending: false, acceptedAt: now, acceptedByUserId: input.acceptedByUserId, ...(input.createdUserId !== undefined ? { createdUserId: input.createdUserId } : {}), }, }); const invite = await db.tenantUserInvitation.findFirst({ where: { id: candidate.id, tenantId: input.tenantId, tokenHash }, orderBy: { id: "asc" }, }); if (transition.count !== 1) { if (!invite || !tokenHashesMatch(invite.tokenHash, tokenHash)) { throw new WorkspaceInviteError("invite_not_found"); } if (resolveInviteStatus(invite, now) === WORKSPACE_INVITE_STATUS_EXPIRED) { throw new WorkspaceInviteError("invite_expired"); } if (resolveInviteStatus(invite, now) !== WORKSPACE_INVITE_STATUS_PENDING) { throw new WorkspaceInviteError("invite_already_finalized"); } throw new WorkspaceInviteError("invite_not_found"); } if ( !invite || !tokenHashesMatch(invite.tokenHash, tokenHash) || resolveInviteStatus(invite, now) !== WORKSPACE_INVITE_STATUS_ACCEPTED || invite.acceptedByUserId !== input.acceptedByUserId || invite.createdUserId !== createdUserId ) { throw new WorkspaceInviteError("invite_not_found"); } return serializeWorkspaceInvite(invite, now); } export async function revokeWorkspaceInvite(input: WorkspaceInviteRevokeInput, client?: WorkspaceInviteClient): Promise { const db = getClient(client); const now = input.now ?? new Date(); const candidate = await db.tenantUserInvitation.findFirst({ where: { id: input.inviteId, tenantId: input.tenantId, }, orderBy: { id: "asc" }, }); if (!candidate) { throw new WorkspaceInviteError("invite_not_found"); } if (resolveInviteStatus(candidate, now) !== WORKSPACE_INVITE_STATUS_PENDING) { throw new WorkspaceInviteError("invite_already_finalized"); } const transition = await db.tenantUserInvitation.updateMany({ where: { id: candidate.id, tenantId: input.tenantId, pending: true, status: WORKSPACE_INVITE_STATUS_PENDING, acceptedAt: null, revokedAt: null, acceptedByUserId: null, revokedByUserId: null, OR: [{ expiresAt: null }, { expiresAt: { gt: now } }], }, data: { status: WORKSPACE_INVITE_STATUS_REVOKED, pending: false, revokedAt: now, revokedByUserId: input.revokedByUserId, }, }); const invite = await db.tenantUserInvitation.findFirst({ where: { id: candidate.id, tenantId: input.tenantId }, orderBy: { id: "asc" }, }); if (transition.count !== 1) { throw new WorkspaceInviteError("invite_already_finalized"); } if (!invite || resolveInviteStatus(invite, now) !== WORKSPACE_INVITE_STATUS_REVOKED || invite.revokedByUserId !== input.revokedByUserId) { throw new WorkspaceInviteError("invite_not_found"); } return serializeWorkspaceInvite(invite, now); }