Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -0,0 +1,896 @@
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
|
||||
import type { OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
|
||||
import { CatalogError, foundationErrors, withTenantScope } from "@hivegrid/foundation";
|
||||
import { CHAT_EVENT_NAMES, isPersistentChatEvent, validateChatServerEvent, type ChatRealtimeMessage } from "@hivegrid/realtime";
|
||||
|
||||
import { toPersistedChatEventType } from "./event-type-mapping.js";
|
||||
import { chatErrors } from "./errors.js";
|
||||
import { CHAT_PERMISSIONS } from "./permissions.js";
|
||||
import { publishChatPersistentRealtimeWakeup } from "./realtime-wakeup.server.js";
|
||||
import { encodeChatMessageCursor, parseChatMessageCursor, runChatRepositoryTransaction } from "./repository.server.js";
|
||||
import type { ChatAttachmentRecord, ChatMemberChannelDetail, ChatParticipantProfileRecord, ChatRouteRepositoryContext } from "./types.js";
|
||||
|
||||
const ACTIVE_TENANT_USER_STATUS = 2;
|
||||
const AUDIT_MESSAGE_LIMIT = 100;
|
||||
|
||||
const AUDIT_MESSAGE_SELECT = {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
tenantId: true,
|
||||
chatId: true,
|
||||
authorUserId: true,
|
||||
clientMessageId: true,
|
||||
body: true,
|
||||
bodyFormat: true,
|
||||
parentMessageId: true,
|
||||
mentions: true,
|
||||
linkPreviews: true,
|
||||
editedAt: true,
|
||||
deletedAt: true,
|
||||
systemEventKind: true,
|
||||
systemEventMetadata: true,
|
||||
} as const satisfies Prisma.TeamChatMessageSelect;
|
||||
|
||||
type AuditMessageRow = Prisma.TeamChatMessageGetPayload<{ select: typeof AUDIT_MESSAGE_SELECT }>;
|
||||
|
||||
export type ChatAuditSessionContext = Readonly<{
|
||||
sessionId: string;
|
||||
reason: string;
|
||||
expiresAtIso: string;
|
||||
}>;
|
||||
|
||||
export type ChatAuditAttachmentVariant = "original" | "preview" | "thumb";
|
||||
|
||||
export type ChatAuditAttachmentDownload = Readonly<{
|
||||
fileId: string;
|
||||
messageId: string;
|
||||
displayName: string;
|
||||
storageKey: string;
|
||||
}>;
|
||||
|
||||
export type ChatAuditChannelSummary = Readonly<{
|
||||
id: string;
|
||||
kind: "project" | "group" | "dm";
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
projectId: string | null;
|
||||
isPrivate: boolean;
|
||||
archivedAtIso: string | null;
|
||||
lastMessageAtIso: string | null;
|
||||
memberCount: number;
|
||||
participants: readonly ChatParticipantProfileRecord[];
|
||||
}>;
|
||||
|
||||
export type ChatAuditAdministrationRecord = Readonly<{
|
||||
channel: Readonly<{
|
||||
id: string;
|
||||
kind: "project" | "group" | "dm";
|
||||
archivedAtIso: string | null;
|
||||
}>;
|
||||
canAdminister: boolean;
|
||||
members: readonly Readonly<{
|
||||
userId: string;
|
||||
displayName: string;
|
||||
avatarUrl: string | null;
|
||||
roleInChat: "admin" | "member";
|
||||
}>[];
|
||||
}>;
|
||||
|
||||
export type ChatAuditAdminMutationResult = Readonly<{
|
||||
chatId: string;
|
||||
changed: boolean;
|
||||
}>;
|
||||
|
||||
export async function listChatAuditChannels(
|
||||
input: ChatRouteRepositoryContext & {
|
||||
readonly requestId: string;
|
||||
readonly auditSession: ChatAuditSessionContext;
|
||||
}
|
||||
): Promise<readonly ChatAuditChannelSummary[]> {
|
||||
const requestId = normalizeIdentifier(input.requestId, "requestId");
|
||||
const auditSession = normalizeAuditSession(input.auditSession);
|
||||
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readAllChannels, async (tx) => {
|
||||
const channels = await tx.teamChat.findMany({
|
||||
where: withTenantScope(input.tenantId, {}),
|
||||
orderBy: [{ lastMessageAt: "desc" }, { createdAt: "desc" }, { id: "desc" }],
|
||||
select: {
|
||||
id: true,
|
||||
kind: true,
|
||||
name: true,
|
||||
description: true,
|
||||
projektId: true,
|
||||
isPrivate: true,
|
||||
archivedAt: true,
|
||||
lastMessageAt: true,
|
||||
_count: { select: { members: { where: withTenantScope(input.tenantId, { leftAt: null }) } } },
|
||||
},
|
||||
});
|
||||
const participants = await listParticipantProfiles(
|
||||
tx,
|
||||
input.tenantId,
|
||||
channels.map((channel) => channel.id)
|
||||
);
|
||||
const profilesByChat = groupParticipantProfiles(participants);
|
||||
|
||||
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.userId,
|
||||
actorType: "user",
|
||||
action: "chat.audit.channel_listed",
|
||||
targetType: "Tenant",
|
||||
targetId: input.tenantId,
|
||||
requestId,
|
||||
sourceModule: "chat",
|
||||
outcome: "success",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["gdpr"],
|
||||
metadata: {
|
||||
auditSessionId: auditSession.sessionId,
|
||||
reason: auditSession.reason,
|
||||
expiresAtIso: auditSession.expiresAtIso,
|
||||
readOnly: true,
|
||||
channelCount: channels.length,
|
||||
},
|
||||
summaryText: "Die tenantweite Chat-Übersicht wurde im schreibgeschützten Admin-Auditmodus gelesen.",
|
||||
});
|
||||
|
||||
return channels.map((channel) => ({
|
||||
id: channel.id,
|
||||
kind: channel.kind,
|
||||
name: normalizeOptionalText(channel.name),
|
||||
description: normalizeOptionalText(channel.description),
|
||||
projectId: channel.projektId,
|
||||
isPrivate: channel.isPrivate,
|
||||
archivedAtIso: channel.archivedAt?.toISOString() ?? null,
|
||||
lastMessageAtIso: channel.lastMessageAt?.toISOString() ?? null,
|
||||
memberCount: channel._count.members,
|
||||
participants: profilesByChat.get(channel.id) ?? [],
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
export async function getChatAuditChannelDetail(
|
||||
input: ChatRouteRepositoryContext & {
|
||||
readonly chatId: string;
|
||||
readonly requestId: string;
|
||||
readonly auditSession: ChatAuditSessionContext;
|
||||
readonly beforeMessageCursor?: string;
|
||||
}
|
||||
): Promise<ChatMemberChannelDetail> {
|
||||
const chatId = normalizeIdentifier(input.chatId, "chatId");
|
||||
const requestId = normalizeIdentifier(input.requestId, "requestId");
|
||||
const auditSession = normalizeAuditSession(input.auditSession);
|
||||
const beforeMessageCursor = normalizeAuditMessageCursor(input.beforeMessageCursor, chatId);
|
||||
|
||||
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readAllChannels, async (tx) => {
|
||||
const channel = await tx.teamChat.findFirst({
|
||||
where: withTenantScope(input.tenantId, { id: chatId }),
|
||||
select: {
|
||||
id: true,
|
||||
kind: true,
|
||||
name: true,
|
||||
description: true,
|
||||
projektId: true,
|
||||
isPrivate: true,
|
||||
archivedAt: true,
|
||||
lastMessageAt: true,
|
||||
eventStreamId: true,
|
||||
_count: { select: { members: { where: withTenantScope(input.tenantId, { leftAt: null }) } } },
|
||||
},
|
||||
});
|
||||
if (!channel) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
|
||||
|
||||
const [participants, latestEvent, messageRows] = await Promise.all([
|
||||
listParticipantProfiles(tx, input.tenantId, [chatId]),
|
||||
tx.teamChatEvent.findFirst({
|
||||
where: withTenantScope(input.tenantId, { chatId }),
|
||||
orderBy: { sequence: "desc" },
|
||||
select: { sequence: true },
|
||||
}),
|
||||
tx.teamChatMessage.findMany({
|
||||
where: withTenantScope(input.tenantId, {
|
||||
chatId,
|
||||
parentMessageId: null,
|
||||
...(beforeMessageCursor
|
||||
? {
|
||||
OR: [{ createdAt: { lt: beforeMessageCursor.createdAt } }, { createdAt: beforeMessageCursor.createdAt, id: { lt: beforeMessageCursor.id } }],
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
||||
take: AUDIT_MESSAGE_LIMIT + 1,
|
||||
select: AUDIT_MESSAGE_SELECT,
|
||||
}),
|
||||
]);
|
||||
const hasOlderMessages = messageRows.length > AUDIT_MESSAGE_LIMIT;
|
||||
const visibleMessages = messageRows.slice(0, AUDIT_MESSAGE_LIMIT).reverse();
|
||||
const attachments = await listAuditAttachments(
|
||||
tx,
|
||||
input.tenantId,
|
||||
visibleMessages.map((message) => message.id)
|
||||
);
|
||||
const attachmentIdsByMessageId = groupAttachmentIds(attachments);
|
||||
|
||||
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.userId,
|
||||
actorType: "user",
|
||||
action: "chat.audit.channel_opened",
|
||||
targetType: "TeamChat",
|
||||
targetId: channel.id,
|
||||
requestId,
|
||||
sourceModule: "chat",
|
||||
outcome: "success",
|
||||
dataSensitivity: channel.kind === "dm" ? "confidential" : "internal",
|
||||
regulatoryScope: ["gdpr"],
|
||||
metadata: {
|
||||
auditSessionId: auditSession.sessionId,
|
||||
reason: auditSession.reason,
|
||||
channelKind: channel.kind,
|
||||
expiresAtIso: auditSession.expiresAtIso,
|
||||
readOnly: true,
|
||||
pageCursor: input.beforeMessageCursor ?? null,
|
||||
},
|
||||
summaryText: "Ein Chat-Kanal wurde im schreibgeschützten Admin-Auditmodus geöffnet.",
|
||||
});
|
||||
|
||||
return {
|
||||
channel: {
|
||||
id: channel.id,
|
||||
kind: channel.kind,
|
||||
name: normalizeOptionalText(channel.name),
|
||||
description: normalizeOptionalText(channel.description),
|
||||
projektId: channel.projektId,
|
||||
isPrivate: channel.isPrivate,
|
||||
archivedAtIso: channel.archivedAt?.toISOString() ?? null,
|
||||
lastMessageAtIso: channel.lastMessageAt?.toISOString() ?? null,
|
||||
eventStreamId: channel.eventStreamId,
|
||||
eventCursor: latestEvent ? `${channel.eventStreamId}:${latestEvent.sequence.toString()}` : "0",
|
||||
member: {
|
||||
roleInChat: "member",
|
||||
notificationPreference: "muted",
|
||||
lastReadMessageId: null,
|
||||
lastReadAtIso: null,
|
||||
isPinned: false,
|
||||
canWrite: false,
|
||||
},
|
||||
memberCount: channel._count.members,
|
||||
participants,
|
||||
unreadCount: 0,
|
||||
hasUnreadMention: false,
|
||||
lastMessage: visibleMessages.at(-1)
|
||||
? mapMessage(visibleMessages.at(-1)!, channel.eventStreamId, attachmentIdsByMessageId.get(visibleMessages.at(-1)!.id) ?? [])
|
||||
: null,
|
||||
},
|
||||
messages: visibleMessages.map((message) => mapMessage(message, channel.eventStreamId, attachmentIdsByMessageId.get(message.id) ?? [])),
|
||||
readReceipts: [],
|
||||
messageFeatures: [],
|
||||
attachments,
|
||||
hasOlderMessages,
|
||||
olderMessageCursor: hasOlderMessages && visibleMessages[0] ? encodeChatMessageCursor(chatId, visibleMessages[0]) : null,
|
||||
eventCursor: latestEvent ? `${channel.eventStreamId}:${latestEvent.sequence.toString()}` : "0",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one attachment inside the reason-bound audit transaction. Generic
|
||||
* Files visibility intentionally cannot use chat.read_all_channels, otherwise
|
||||
* an administrator could bypass the audit session and its immutable read log.
|
||||
*/
|
||||
export async function getChatAuditAttachmentDownload(
|
||||
input: ChatRouteRepositoryContext & {
|
||||
readonly chatId: string;
|
||||
readonly fileId: string;
|
||||
readonly variant: ChatAuditAttachmentVariant;
|
||||
readonly requestId: string;
|
||||
readonly auditSession: ChatAuditSessionContext;
|
||||
}
|
||||
): Promise<ChatAuditAttachmentDownload> {
|
||||
const chatId = normalizeIdentifier(input.chatId, "chatId");
|
||||
const fileId = normalizeIdentifier(input.fileId, "fileId");
|
||||
const requestId = normalizeIdentifier(input.requestId, "requestId");
|
||||
const auditSession = normalizeAuditSession(input.auditSession);
|
||||
const variant = normalizeAuditAttachmentVariant(input.variant);
|
||||
|
||||
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readAllChannels, async (tx) => {
|
||||
const links = await tx.fileEntityLink.findMany({
|
||||
where: withTenantScope(input.tenantId, { fileId, entityType: "chat_message" as const }),
|
||||
select: { entityId: true, fileId: true },
|
||||
});
|
||||
if (links.length === 0) throw new CatalogError(foundationErrors.notFound, { attachment: "not-visible" });
|
||||
|
||||
const linkedMessages = await tx.teamChatMessage.findMany({
|
||||
where: withTenantScope(input.tenantId, {
|
||||
id: { in: links.map((link) => link.entityId) },
|
||||
chatId,
|
||||
}),
|
||||
select: { id: true },
|
||||
take: 1,
|
||||
});
|
||||
const message = linkedMessages[0];
|
||||
if (!message) throw new CatalogError(foundationErrors.notFound, { attachment: "not-visible" });
|
||||
|
||||
const files = await tx.file.findMany({
|
||||
where: withTenantScope(input.tenantId, { id: fileId, archivedAt: null, scanStatus: "clean" as const }),
|
||||
select: {
|
||||
id: true,
|
||||
displayName: true,
|
||||
storageKey: true,
|
||||
previewStorageKey: true,
|
||||
thumbnailStorageKey: true,
|
||||
},
|
||||
take: 1,
|
||||
});
|
||||
const file = files[0];
|
||||
if (!file) throw new CatalogError(foundationErrors.notFound, { attachment: "not-deliverable" });
|
||||
const storageKey = variant === "preview" ? file.previewStorageKey : variant === "thumb" ? file.thumbnailStorageKey : file.storageKey;
|
||||
if (!storageKey) throw new CatalogError(foundationErrors.notFound, { attachment: "variant-not-deliverable" });
|
||||
|
||||
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.userId,
|
||||
actorType: "user",
|
||||
action: "chat.audit.attachment_opened",
|
||||
targetType: "File",
|
||||
targetId: file.id,
|
||||
requestId,
|
||||
sourceModule: "chat",
|
||||
outcome: "success",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["gdpr"],
|
||||
metadata: {
|
||||
auditSessionId: auditSession.sessionId,
|
||||
reason: auditSession.reason,
|
||||
expiresAtIso: auditSession.expiresAtIso,
|
||||
chatId,
|
||||
messageId: message.id,
|
||||
variant,
|
||||
readOnly: true,
|
||||
},
|
||||
summaryText: "Ein Chat-Anhang wurde im schreibgeschützten Admin-Auditmodus geöffnet.",
|
||||
});
|
||||
|
||||
return {
|
||||
fileId: file.id,
|
||||
messageId: message.id,
|
||||
displayName: file.displayName,
|
||||
storageKey,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function getChatAuditAdministration(input: ChatRouteRepositoryContext & { readonly chatId: string }): Promise<ChatAuditAdministrationRecord> {
|
||||
const chatId = normalizeIdentifier(input.chatId, "chatId");
|
||||
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readAllChannels, async (tx, currentPermissions) => {
|
||||
const channel = await tx.teamChat.findFirst({
|
||||
where: withTenantScope(input.tenantId, { id: chatId }),
|
||||
select: {
|
||||
id: true,
|
||||
kind: true,
|
||||
archivedAt: true,
|
||||
members: {
|
||||
where: withTenantScope(input.tenantId, { leftAt: null }),
|
||||
orderBy: [{ roleInChat: "asc" }, { userId: "asc" }],
|
||||
select: { userId: true, roleInChat: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!channel) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
|
||||
const participants = await listParticipantProfiles(tx, input.tenantId, [chatId]);
|
||||
const profiles = new Map(participants.map((participant) => [participant.userId, participant]));
|
||||
return {
|
||||
channel: {
|
||||
id: channel.id,
|
||||
kind: channel.kind,
|
||||
archivedAtIso: channel.archivedAt?.toISOString() ?? null,
|
||||
},
|
||||
canAdminister: currentPermissions.includes(CHAT_PERMISSIONS.admin),
|
||||
members: channel.members.flatMap((member) => {
|
||||
const profile = profiles.get(member.userId);
|
||||
return profile ? [{ userId: member.userId, displayName: profile.displayName, avatarUrl: profile.avatarUrl, roleInChat: member.roleInChat }] : [];
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function forceSetChatAuditMemberRole(
|
||||
input: ChatRouteRepositoryContext & {
|
||||
readonly chatId: string;
|
||||
readonly memberUserId: string;
|
||||
readonly roleInChat: "admin" | "member";
|
||||
readonly requestId: string;
|
||||
readonly auditSession: ChatAuditSessionContext;
|
||||
}
|
||||
): Promise<ChatAuditAdminMutationResult> {
|
||||
const normalized = {
|
||||
...normalizeAuditAdminMutation(input),
|
||||
memberUserId: normalizeIdentifier(input.memberUserId, "memberUserId"),
|
||||
};
|
||||
const roleInChat = normalizeMemberRole(input.roleInChat);
|
||||
return runChatAuditAdminTransaction(input, async (tx) => {
|
||||
const channel = await requireAuditChannel(tx, input.tenantId, normalized.chatId);
|
||||
const member = await tx.teamChatMember.findFirst({
|
||||
where: withTenantScope(input.tenantId, {
|
||||
chatId: channel.id,
|
||||
userId: normalized.memberUserId,
|
||||
leftAt: null,
|
||||
}),
|
||||
select: { id: true, roleInChat: true, joinedAt: true, manualRoleInChat: true, isManualMember: true },
|
||||
});
|
||||
if (!member) throw new CatalogError(foundationErrors.notFound, { member: "not-visible" });
|
||||
const changed = member.roleInChat !== roleInChat || !member.isManualMember || member.manualRoleInChat !== roleInChat;
|
||||
if (changed) {
|
||||
const updated = await tx.teamChatMember.updateMany({
|
||||
where: withTenantScope(input.tenantId, { id: member.id, chatId: channel.id, leftAt: null }),
|
||||
data: {
|
||||
roleInChat,
|
||||
isManualMember: true,
|
||||
manualRoleInChat: roleInChat,
|
||||
writeRevokedAt: null,
|
||||
},
|
||||
});
|
||||
if (updated.count !== 1) throw new CatalogError(chatErrors.integrityFailure);
|
||||
await publishAuditRealtimeEvent(tx, {
|
||||
tenantId: input.tenantId,
|
||||
chatId: channel.id,
|
||||
eventStreamId: channel.eventStreamId,
|
||||
actorUserId: input.userId,
|
||||
requestId: normalized.requestId,
|
||||
event: CHAT_EVENT_NAMES.memberAdded,
|
||||
data: { userId: normalized.memberUserId, roleInChat, joinedAt: member.joinedAt.toISOString() },
|
||||
});
|
||||
}
|
||||
await publishAuditAdminMutation(tx, input, normalized, channel, {
|
||||
action: "chat.audit.member_role_forced",
|
||||
targetType: "TeamChatMember",
|
||||
targetId: member.id,
|
||||
metadata: { memberUserId: normalized.memberUserId, previousRoleInChat: member.roleInChat, roleInChat, changed },
|
||||
summaryText: "Eine Chat-Mitgliedsrolle wurde im begründeten Admin-Auditmodus erzwungen.",
|
||||
});
|
||||
return { chatId: channel.id, changed };
|
||||
});
|
||||
}
|
||||
|
||||
export async function forceRemoveChatAuditMember(
|
||||
input: ChatRouteRepositoryContext & {
|
||||
readonly chatId: string;
|
||||
readonly memberUserId: string;
|
||||
readonly requestId: string;
|
||||
readonly auditSession: ChatAuditSessionContext;
|
||||
}
|
||||
): Promise<ChatAuditAdminMutationResult> {
|
||||
const normalized = {
|
||||
...normalizeAuditAdminMutation(input),
|
||||
memberUserId: normalizeIdentifier(input.memberUserId, "memberUserId"),
|
||||
};
|
||||
return runChatAuditAdminTransaction(input, async (tx) => {
|
||||
const channel = await requireAuditChannel(tx, input.tenantId, normalized.chatId);
|
||||
const member = await tx.teamChatMember.findFirst({
|
||||
where: withTenantScope(input.tenantId, {
|
||||
chatId: channel.id,
|
||||
userId: normalized.memberUserId,
|
||||
leftAt: null,
|
||||
}),
|
||||
select: { id: true, roleInChat: true },
|
||||
});
|
||||
if (!member) throw new CatalogError(foundationErrors.notFound, { member: "not-visible" });
|
||||
const leftAt = new Date();
|
||||
const updated = await tx.teamChatMember.updateMany({
|
||||
where: withTenantScope(input.tenantId, { id: member.id, chatId: channel.id, leftAt: null }),
|
||||
data: {
|
||||
roleInChat: "member",
|
||||
isManualMember: false,
|
||||
manualRoleInChat: null,
|
||||
isProjectManaged: false,
|
||||
projectRoleInChat: null,
|
||||
isGroupManaged: false,
|
||||
writeRevokedAt: leftAt,
|
||||
leftAt,
|
||||
},
|
||||
});
|
||||
if (updated.count !== 1) throw new CatalogError(chatErrors.integrityFailure);
|
||||
await publishAuditRealtimeEvent(tx, {
|
||||
tenantId: input.tenantId,
|
||||
chatId: channel.id,
|
||||
eventStreamId: channel.eventStreamId,
|
||||
actorUserId: input.userId,
|
||||
requestId: normalized.requestId,
|
||||
event: CHAT_EVENT_NAMES.memberRemoved,
|
||||
data: { userId: normalized.memberUserId, leftAt: leftAt.toISOString() },
|
||||
});
|
||||
await publishAuditAdminMutation(tx, input, normalized, channel, {
|
||||
action: "chat.audit.member_removed",
|
||||
targetType: "TeamChatMember",
|
||||
targetId: member.id,
|
||||
metadata: { memberUserId: normalized.memberUserId, previousRoleInChat: member.roleInChat, leftAtIso: leftAt.toISOString() },
|
||||
summaryText: "Ein Chat-Mitglied wurde im begründeten Admin-Auditmodus entfernt.",
|
||||
});
|
||||
return { chatId: channel.id, changed: true };
|
||||
});
|
||||
}
|
||||
|
||||
export async function forceArchiveChatAuditChannel(
|
||||
input: ChatRouteRepositoryContext & {
|
||||
readonly chatId: string;
|
||||
readonly requestId: string;
|
||||
readonly auditSession: ChatAuditSessionContext;
|
||||
}
|
||||
): Promise<ChatAuditAdminMutationResult> {
|
||||
const normalized = normalizeAuditAdminMutation(input);
|
||||
return runChatAuditAdminTransaction(input, async (tx) => {
|
||||
const channel = await requireAuditChannel(tx, input.tenantId, normalized.chatId);
|
||||
const changed = channel.archivedAt === null;
|
||||
if (changed) {
|
||||
const archivedAt = new Date();
|
||||
const updated = await tx.teamChat.updateMany({
|
||||
where: withTenantScope(input.tenantId, { id: channel.id, archivedAt: null }),
|
||||
data: { archivedAt, archivedReason: "manual" },
|
||||
});
|
||||
if (updated.count !== 1) throw new CatalogError(chatErrors.integrityFailure);
|
||||
await publishAuditRealtimeEvent(tx, {
|
||||
tenantId: input.tenantId,
|
||||
chatId: channel.id,
|
||||
eventStreamId: channel.eventStreamId,
|
||||
actorUserId: input.userId,
|
||||
requestId: normalized.requestId,
|
||||
event: CHAT_EVENT_NAMES.channelArchived,
|
||||
data: { archivedAt: archivedAt.toISOString(), reason: "manual" },
|
||||
});
|
||||
}
|
||||
await publishAuditAdminMutation(tx, input, normalized, channel, {
|
||||
action: "chat.audit.channel_archived",
|
||||
targetType: "TeamChat",
|
||||
targetId: channel.id,
|
||||
metadata: { previousArchivedAtIso: channel.archivedAt?.toISOString() ?? null, changed },
|
||||
summaryText: "Ein Chat-Kanal wurde im begründeten Admin-Auditmodus archiviert.",
|
||||
});
|
||||
return { chatId: channel.id, changed };
|
||||
});
|
||||
}
|
||||
|
||||
type AuditChannelMutationRow = Readonly<{
|
||||
id: string;
|
||||
kind: "project" | "group" | "dm";
|
||||
eventStreamId: string;
|
||||
archivedAt: Date | null;
|
||||
}>;
|
||||
|
||||
type NormalizedAuditAdminMutation = Readonly<{
|
||||
chatId: string;
|
||||
requestId: string;
|
||||
auditSession: ChatAuditSessionContext;
|
||||
}>;
|
||||
|
||||
type ChatAuditActivityAction =
|
||||
| "chat.audit.member_role_forced"
|
||||
| "chat.audit.member_removed"
|
||||
| "chat.audit.channel_archived";
|
||||
|
||||
function chatAuditActivitySummaryKey(action: ChatAuditActivityAction): string {
|
||||
const summaryKeys: Readonly<Record<ChatAuditActivityAction, string>> = {
|
||||
"chat.audit.member_role_forced": "activity.runtime.chat.auditMemberRoleChanged",
|
||||
"chat.audit.member_removed": "activity.runtime.chat.auditMemberRemoved",
|
||||
"chat.audit.channel_archived": "activity.runtime.chat.auditChannelArchived",
|
||||
};
|
||||
return summaryKeys[action];
|
||||
}
|
||||
|
||||
function runChatAuditAdminTransaction<TResult>(input: ChatRouteRepositoryContext, operation: (tx: DbTransactionClient) => Promise<TResult>): Promise<TResult> {
|
||||
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.admin, async (tx, currentPermissions) => {
|
||||
if (!currentPermissions.includes(CHAT_PERMISSIONS.readAllChannels)) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
return operation(tx);
|
||||
});
|
||||
}
|
||||
|
||||
async function requireAuditChannel(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<AuditChannelMutationRow> {
|
||||
const channel = await tx.teamChat.findFirst({
|
||||
where: withTenantScope(tenantId, { id: chatId }),
|
||||
select: { id: true, kind: true, eventStreamId: true, archivedAt: true },
|
||||
});
|
||||
if (!channel) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
|
||||
return channel;
|
||||
}
|
||||
|
||||
function normalizeAuditAdminMutation(input: {
|
||||
readonly chatId: string;
|
||||
readonly requestId: string;
|
||||
readonly auditSession: ChatAuditSessionContext;
|
||||
}): NormalizedAuditAdminMutation {
|
||||
return {
|
||||
chatId: normalizeIdentifier(input.chatId, "chatId"),
|
||||
requestId: normalizeIdentifier(input.requestId, "requestId"),
|
||||
auditSession: normalizeAuditSession(input.auditSession),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeMemberRole(value: string): "admin" | "member" {
|
||||
if (value === "admin" || value === "member") return value;
|
||||
throw new Error("roleInChat is invalid");
|
||||
}
|
||||
|
||||
async function publishAuditAdminMutation(
|
||||
tx: DbTransactionClient,
|
||||
input: Pick<ChatRouteRepositoryContext, "tenantId" | "userId">,
|
||||
normalized: NormalizedAuditAdminMutation,
|
||||
channel: AuditChannelMutationRow,
|
||||
event: Readonly<{
|
||||
action: ChatAuditActivityAction;
|
||||
targetType: string;
|
||||
targetId: string;
|
||||
metadata: Record<string, Prisma.InputJsonValue | null>;
|
||||
summaryText: string;
|
||||
}>
|
||||
): Promise<void> {
|
||||
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.userId,
|
||||
actorType: "user",
|
||||
action: event.action,
|
||||
targetType: event.targetType,
|
||||
targetId: event.targetId,
|
||||
requestId: normalized.requestId,
|
||||
sourceModule: "chat",
|
||||
outcome: "success",
|
||||
dataSensitivity: channel.kind === "dm" ? "confidential" : "internal",
|
||||
regulatoryScope: ["gdpr"],
|
||||
metadata: {
|
||||
auditSessionId: normalized.auditSession.sessionId,
|
||||
reason: normalized.auditSession.reason,
|
||||
expiresAtIso: normalized.auditSession.expiresAtIso,
|
||||
channelId: channel.id,
|
||||
channelKind: channel.kind,
|
||||
...event.metadata,
|
||||
} as Prisma.InputJsonObject,
|
||||
summaryText: event.summaryText,
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
actorKind: "user",
|
||||
activityType: "audit_event",
|
||||
subjectType: "tenant",
|
||||
subjectId: input.tenantId,
|
||||
summaryText: chatAuditActivitySummaryKey(event.action),
|
||||
metadata: {
|
||||
sourceModule: "chat",
|
||||
chatAction: event.action,
|
||||
channelId: channel.id,
|
||||
targetType: event.targetType,
|
||||
targetId: event.targetId,
|
||||
},
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
}
|
||||
|
||||
type ChatAuditRealtimeMutation =
|
||||
| Readonly<{
|
||||
event: typeof CHAT_EVENT_NAMES.memberAdded;
|
||||
data: { userId: string; roleInChat: "admin" | "member"; joinedAt: string };
|
||||
}>
|
||||
| Readonly<{
|
||||
event: typeof CHAT_EVENT_NAMES.memberRemoved;
|
||||
data: { userId: string; leftAt: string };
|
||||
}>
|
||||
| Readonly<{
|
||||
event: typeof CHAT_EVENT_NAMES.channelArchived;
|
||||
data: { archivedAt: string; reason: "manual" };
|
||||
}>;
|
||||
|
||||
async function publishAuditRealtimeEvent(
|
||||
tx: DbTransactionClient,
|
||||
input: Readonly<{
|
||||
tenantId: string;
|
||||
chatId: string;
|
||||
eventStreamId: string;
|
||||
actorUserId: string;
|
||||
requestId: string;
|
||||
}> &
|
||||
ChatAuditRealtimeMutation
|
||||
): Promise<void> {
|
||||
const persisted = await tx.teamChatEvent.create({
|
||||
data: withTenantScope(input.tenantId, {
|
||||
chatId: input.chatId,
|
||||
type: toPersistedChatEventType(input.event),
|
||||
actorUserId: input.actorUserId,
|
||||
entityId: input.event === CHAT_EVENT_NAMES.channelArchived ? input.chatId : input.data.userId,
|
||||
requestId: input.requestId,
|
||||
data: input.data as Prisma.InputJsonObject,
|
||||
}),
|
||||
select: { sequence: true, occurredAt: true },
|
||||
});
|
||||
const event = validateChatServerEvent({
|
||||
event: input.event,
|
||||
cursor: `${input.eventStreamId}:${persisted.sequence.toString()}`,
|
||||
requestId: input.requestId,
|
||||
tenantId: input.tenantId,
|
||||
chatId: input.chatId,
|
||||
occurredAt: persisted.occurredAt.toISOString(),
|
||||
data: input.data,
|
||||
});
|
||||
if (!isPersistentChatEvent(event)) throw new CatalogError(chatErrors.integrityFailure);
|
||||
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event });
|
||||
}
|
||||
|
||||
async function listAuditAttachments(tx: DbTransactionClient, tenantId: string, messageIds: readonly string[]): Promise<ChatAttachmentRecord[]> {
|
||||
if (messageIds.length === 0) return [];
|
||||
const links = await tx.fileEntityLink.findMany({
|
||||
where: withTenantScope(tenantId, { entityType: "chat_message" as const, entityId: { in: [...messageIds] } }),
|
||||
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
||||
select: { entityId: true, fileId: true, linkRole: true },
|
||||
});
|
||||
const files = await tx.file.findMany({
|
||||
where: withTenantScope(tenantId, { id: { in: links.map((link) => link.fileId) }, archivedAt: null }),
|
||||
select: { id: true, displayName: true, mimeType: true, sizeBytes: true, previewStatus: true, scanStatus: true },
|
||||
});
|
||||
const byId = new Map(files.map((file) => [file.id, file]));
|
||||
return links.flatMap((link) => {
|
||||
const file = byId.get(link.fileId);
|
||||
return file
|
||||
? [
|
||||
{
|
||||
messageId: link.entityId,
|
||||
fileId: file.id,
|
||||
displayName: file.displayName,
|
||||
mimeType: file.mimeType,
|
||||
sizeBytes: file.sizeBytes,
|
||||
linkRole: link.linkRole,
|
||||
previewStatus: file.previewStatus,
|
||||
scanStatus: file.scanStatus,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
function groupAttachmentIds(rows: readonly ChatAttachmentRecord[]): Map<string, string[]> {
|
||||
const grouped = new Map<string, string[]>();
|
||||
for (const row of rows) grouped.set(row.messageId, [...(grouped.get(row.messageId) ?? []), row.fileId]);
|
||||
return grouped;
|
||||
}
|
||||
|
||||
export async function recordChatAuditSessionStarted(
|
||||
input: ChatRouteRepositoryContext & {
|
||||
readonly requestId: string;
|
||||
readonly auditSession: ChatAuditSessionContext;
|
||||
}
|
||||
): Promise<void> {
|
||||
const requestId = normalizeIdentifier(input.requestId, "requestId");
|
||||
const auditSession = normalizeAuditSession(input.auditSession);
|
||||
await runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readAllChannels, async (tx) => {
|
||||
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.userId,
|
||||
actorType: "user",
|
||||
action: "chat.audit.session_started",
|
||||
targetType: "Tenant",
|
||||
targetId: input.tenantId,
|
||||
requestId,
|
||||
sourceModule: "chat",
|
||||
outcome: "success",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["gdpr"],
|
||||
metadata: {
|
||||
auditSessionId: auditSession.sessionId,
|
||||
reason: auditSession.reason,
|
||||
expiresAtIso: auditSession.expiresAtIso,
|
||||
readOnly: true,
|
||||
},
|
||||
summaryText: "Eine zeitlich begrenzte Chat-Admin-Auditsitzung wurde gestartet.",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
type ParticipantProjection = ChatParticipantProfileRecord & { readonly chatId: string };
|
||||
|
||||
async function listParticipantProfiles(tx: DbTransactionClient, tenantId: string, chatIds: readonly string[]): Promise<ParticipantProjection[]> {
|
||||
if (chatIds.length === 0) return [];
|
||||
return tx.$queryRaw<ParticipantProjection[]>`
|
||||
SELECT participant."chatId" AS "chatId",
|
||||
participant."userId" AS "userId",
|
||||
COALESCE(
|
||||
NULLIF(TRIM(CONCAT_WS(' ', participant_user."firstName", participant_user."lastName")), ''),
|
||||
participant_user."email"
|
||||
) AS "displayName",
|
||||
participant_user."avatar" AS "avatarUrl"
|
||||
FROM "TeamChatMember" AS participant
|
||||
INNER JOIN "TenantUser" AS participant_tenant_user
|
||||
ON participant_tenant_user."tenantId" = participant."tenantId"
|
||||
AND participant_tenant_user."userId" = participant."userId"
|
||||
AND participant_tenant_user."status" = ${ACTIVE_TENANT_USER_STATUS}
|
||||
INNER JOIN "User" AS participant_user
|
||||
ON participant_user."id" = participant."userId"
|
||||
AND participant_user."active" = TRUE
|
||||
AND participant_user."pendingDeletion" = FALSE
|
||||
AND participant_user."pseudonymized" = FALSE
|
||||
WHERE participant."tenantId" = ${tenantId}
|
||||
AND participant."chatId" = ANY(${chatIds}::text[])
|
||||
AND participant."leftAt" IS NULL
|
||||
ORDER BY participant."chatId" ASC, "displayName" ASC, participant."userId" ASC
|
||||
`;
|
||||
}
|
||||
|
||||
function groupParticipantProfiles(rows: readonly ParticipantProjection[]): Map<string, ChatParticipantProfileRecord[]> {
|
||||
const result = new Map<string, ChatParticipantProfileRecord[]>();
|
||||
for (const row of rows) {
|
||||
const current = result.get(row.chatId) ?? [];
|
||||
current.push({ userId: row.userId, displayName: row.displayName, avatarUrl: row.avatarUrl });
|
||||
result.set(row.chatId, current);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function mapMessage(row: AuditMessageRow, eventStreamId: string, attachmentIds: readonly string[]): ChatRealtimeMessage {
|
||||
const event = validateChatServerEvent({
|
||||
event: CHAT_EVENT_NAMES.messageCreated,
|
||||
cursor: `${eventStreamId}:1`,
|
||||
requestId: `audit-message-${row.id}`,
|
||||
tenantId: row.tenantId,
|
||||
chatId: row.chatId,
|
||||
occurredAt: row.createdAt.toISOString(),
|
||||
data: {
|
||||
message: {
|
||||
id: row.id,
|
||||
clientMessageId: row.clientMessageId,
|
||||
authorUserId: row.authorUserId,
|
||||
body: row.body,
|
||||
bodyFormat: row.bodyFormat,
|
||||
parentMessageId: row.parentMessageId,
|
||||
mentions: row.mentions,
|
||||
attachmentIds: [...attachmentIds],
|
||||
linkPreviews: row.linkPreviews,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
editedAt: row.editedAt?.toISOString() ?? null,
|
||||
deletedAt: row.deletedAt?.toISOString() ?? null,
|
||||
...(row.bodyFormat === "system" ? { systemEvent: { kind: row.systemEventKind, metadata: row.systemEventMetadata } } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
if (event.event !== CHAT_EVENT_NAMES.messageCreated) throw new Error("Stored audit chat message is invalid");
|
||||
return event.data.message;
|
||||
}
|
||||
|
||||
function normalizeAuditSession(session: ChatAuditSessionContext): ChatAuditSessionContext {
|
||||
const sessionId = normalizeIdentifier(session.sessionId, "audit session id");
|
||||
const reason = session.reason.trim().replace(/\s+/g, " ");
|
||||
const expiresAt = new Date(session.expiresAtIso);
|
||||
if (!reason || reason.length > 500 || reason.includes("\0") || Number.isNaN(expiresAt.getTime())) {
|
||||
throw new Error("audit session is invalid");
|
||||
}
|
||||
return { sessionId, reason, expiresAtIso: expiresAt.toISOString() };
|
||||
}
|
||||
|
||||
function normalizeAuditAttachmentVariant(value: string): ChatAuditAttachmentVariant {
|
||||
if (value !== "original" && value !== "preview" && value !== "thumb") {
|
||||
throw new CatalogError(foundationErrors.notFound, { attachment: "invalid-variant" });
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function normalizeAuditMessageCursor(value: string | undefined, chatId: string): { createdAt: Date; id: string } | null {
|
||||
try {
|
||||
return parseChatMessageCursor(value, chatId);
|
||||
} catch {
|
||||
throw new CatalogError(chatErrors.invalidInput, { field: "beforeMessageCursor" });
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeIdentifier(value: string, label: string): string {
|
||||
const normalized = value.trim();
|
||||
if (!normalized || normalized.length > 500 || normalized.includes("\0")) throw new Error(`${label} is invalid`);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function normalizeOptionalText(value: string | null): string | null {
|
||||
const normalized = value?.trim() ?? "";
|
||||
return normalized || null;
|
||||
}
|
||||
Reference in new issue
Block a user