Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,50 @@
{
"name": "@hivegrid/chat",
"version": "0.0.0",
"private": true,
"type": "module",
"sideEffects": false,
"exports": {
".": "./src/index.ts",
"./audit.server": "./src/audit.server.ts",
"./channel-settings.server": "./src/channel-settings.server.ts",
"./deep-links": "./src/deep-links.ts",
"./discovery.server": "./src/discovery.server.ts",
"./gateway-auth.server": "./src/gateway-auth.server.ts",
"./group-sync.server": "./src/group-sync.server.ts",
"./lifecycle.server": "./src/lifecycle.server.ts",
"./link-preview.server": "./src/link-preview.server.ts",
"./message-discovery.server": "./src/message-discovery.server.ts",
"./message-effects.server": "./src/message-effects.server.ts",
"./message-features.server": "./src/message-features.server.ts",
"./message-mutations.server": "./src/message-mutations.server.ts",
"./member-preferences.server": "./src/member-preferences.server.ts",
"./mentions.server": "./src/mentions.server.ts",
"./module-access.server": "./src/module-access.server.ts",
"./project-link.server": "./src/project-link.server.ts",
"./project-sync.server": "./src/project-sync.server.ts",
"./realtime-wakeup.server": "./src/realtime-wakeup.server.ts",
"./repository.server": "./src/repository.server.ts",
"./system-message.server": "./src/system-message.server.ts",
"./sync-locks.server": "./src/sync-locks.server.ts"
},
"scripts": {
"build": "pnpm run typecheck",
"test": "vitest run src",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@hivegrid/activity": "workspace:*",
"@hivegrid/db": "workspace:*",
"@hivegrid/entitlements": "workspace:*",
"@hivegrid/foundation": "workspace:*",
"@hivegrid/realtime": "workspace:*",
"jsonwebtoken": "^9.0.0"
},
"devDependencies": {
"@types/jsonwebtoken": "^9.0.6",
"@types/node": "^25.0.0",
"typescript": "^5.3.2",
"vitest": "^3.2.4"
}
}
@@ -0,0 +1,67 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
function source(fileName: string): string {
return readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), fileName), "utf8");
}
describe("chat activity summary i18n contract", () => {
it("persists semantic keys for every generic Activity write", () => {
const expectedKeysByFile: Readonly<Record<string, readonly string[]>> = {
"mentions.server.ts": [
"activity.runtime.chat.messageCreated",
"activity.runtime.chat.threadReplyCreated",
"activity.runtime.chat.messageEdited",
"activity.runtime.chat.entityMentioned",
],
"message-mutations.server.ts": ["activity.runtime.chat.projectMessageDeleted"],
"message-features.server.ts": [
"activity.runtime.chat.messagePinned",
"activity.runtime.chat.messageUnpinned",
],
"group-sync.server.ts": ["activity.runtime.chat.permissionGroupSynced"],
"project-sync.server.ts": [
"activity.runtime.chat.projectChatArchived",
"activity.runtime.chat.projectChatCreated",
"activity.runtime.chat.projectMembersSynced",
],
"lifecycle.server.ts": [
"activity.runtime.chat.groupCreated",
"activity.runtime.chat.groupJoined",
"activity.runtime.chat.groupMemberChanged",
"activity.runtime.chat.groupMemberRemoved",
"activity.runtime.chat.groupLeft",
"activity.runtime.chat.groupPrivacyChanged",
"activity.runtime.chat.groupArchived",
"activity.runtime.chat.projectChatArchived",
"activity.runtime.chat.projectMemberRemoved",
"activity.runtime.chat.projectMemberChanged",
],
"audit.server.ts": [
"activity.runtime.chat.auditMemberRoleChanged",
"activity.runtime.chat.auditMemberRemoved",
"activity.runtime.chat.auditChannelArchived",
],
};
for (const [fileName, expectedKeys] of Object.entries(expectedKeysByFile)) {
const fileSource = source(fileName);
for (const key of expectedKeys) expect(fileSource, `${fileName} should persist ${key}`).toContain(`"${key}"`);
}
});
it("does not persist message bodies or channel names as translated summaries", () => {
const mentionsSource = source("mentions.server.ts");
expect(mentionsSource).not.toMatch(/summaryText:\s*`/u);
expect(mentionsSource).not.toContain("mentionAwareSnippet");
});
it("keeps audit prose separate from the generic Activity summary key", () => {
const auditSource = source("audit.server.ts");
expect(auditSource).toContain("summaryText: event.summaryText");
expect(auditSource).toContain("summaryText: chatAuditActivitySummaryKey(event.action)");
});
});
@@ -0,0 +1,447 @@
// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
forceArchiveChatAuditChannel,
forceRemoveChatAuditMember,
forceSetChatAuditMemberRole,
getChatAuditChannelDetail,
listChatAuditChannels,
recordChatAuditSessionStarted,
} from "./audit.server.js";
import { CHAT_PERMISSIONS } from "./permissions.js";
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_A = "chat_audit_rls_tenant_a";
const TENANT_B = "chat_audit_rls_tenant_b";
const AUDITOR_A = "chat_audit_rls_auditor_a";
const MEMBER_A = "chat_audit_rls_member_a";
const MEMBER_B = "chat_audit_rls_member_b";
const CHAT_A = "chat_audit_rls_channel_a";
const CHAT_B = "chat_audit_rls_channel_b";
const MESSAGE_A = "chat_audit_rls_message_a";
const MESSAGE_B = "chat_audit_rls_message_b";
const ROLE_ID = "chat_audit_rls_role";
const READ_OWN_PERMISSION_ID = "chat_audit_rls_read_own_permission";
const READ_ALL_PERMISSION_ID = "chat_audit_rls_read_all_permission";
const ADMIN_PERMISSION_ID = "chat_audit_rls_admin_permission";
const READ_OWN_ROLE_PERMISSION_ID = "chat_audit_rls_role_read_own";
const READ_ALL_ROLE_PERMISSION_ID = "chat_audit_rls_role_read_all";
const ADMIN_ROLE_PERMISSION_ID = "chat_audit_rls_role_admin";
const USER_ROLE_ID = "chat_audit_rls_user_role";
const SESSION_ID = "chat_audit_rls_session";
const LIST_REQUEST_ID = "chat_audit_rls_list_request";
const SESSION_REQUEST_ID = "chat_audit_rls_session_request";
const OPEN_REQUEST_ID = "chat_audit_rls_open_request";
const ROLE_REQUEST_ID = "chat_audit_rls_role_request";
const REMOVE_REQUEST_ID = "chat_audit_rls_remove_request";
const ARCHIVE_REQUEST_ID = "chat_audit_rls_archive_request";
const AUDIT_REASON = "Kundensupport-Fall 4711 pruefen";
const STALE_ROUTE_PERMISSIONS = [CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.readAllChannels, CHAT_PERMISSIONS.admin] as const;
describeIfDatabase("chat admin audit with restricted FORCE RLS", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
let createdReadOwnPermission = false;
let createdReadAllPermission = false;
let createdAdminPermission = false;
beforeAll(async () => {
await cleanup(admin);
await admin.user.createMany({
data: [
{
id: AUDITOR_A,
email: "chat-audit-auditor-a@example.test",
firstName: "Audit",
lastName: "Admin",
active: true,
},
{
id: MEMBER_A,
email: "chat-audit-member-a@example.test",
firstName: "Member",
lastName: "A",
active: true,
},
{
id: MEMBER_B,
email: "chat-audit-member-b@example.test",
firstName: "Member",
lastName: "B",
active: true,
},
],
});
await admin.tenant.createMany({
data: [
{ id: TENANT_A, slug: TENANT_A, name: "Chat audit RLS tenant A", active: true },
{ id: TENANT_B, slug: TENANT_B, name: "Chat audit RLS tenant B", active: true },
],
});
await admin.tenantUser.createMany({
data: [
{ id: "chat_audit_rls_tu_auditor_a", tenantId: TENANT_A, userId: AUDITOR_A, type: 0, joined: 1, status: 2 },
{ id: "chat_audit_rls_tu_member_a", tenantId: TENANT_A, userId: MEMBER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_audit_rls_tu_member_b", tenantId: TENANT_B, userId: MEMBER_B, type: 0, joined: 1, status: 2 },
],
});
await admin.teamChat.createMany({
data: [
{
id: CHAT_A,
tenantId: TENANT_A,
createdByUserId: MEMBER_A,
kind: "dm",
name: null,
isPrivate: true,
eventStreamId: "chat_audit_rls_stream_a",
dmPairKey: "chat_audit_rls_pair_a",
lastMessageAt: new Date("2026-07-16T10:00:00.000Z"),
},
{
id: CHAT_B,
tenantId: TENANT_B,
createdByUserId: MEMBER_B,
kind: "group",
name: "Foreign tenant channel",
isPrivate: true,
eventStreamId: "chat_audit_rls_stream_b",
lastMessageAt: new Date("2026-07-16T11:00:00.000Z"),
},
],
});
await admin.teamChatMember.createMany({
data: [
{
id: "chat_audit_rls_member_row_a",
tenantId: TENANT_A,
chatId: CHAT_A,
userId: MEMBER_A,
notificationPref: "all_messages",
},
{
id: "chat_audit_rls_member_row_b",
tenantId: TENANT_B,
chatId: CHAT_B,
userId: MEMBER_B,
notificationPref: "all_messages",
},
],
});
await admin.teamChatMessage.createMany({
data: [
{
id: MESSAGE_A,
tenantId: TENANT_A,
chatId: CHAT_A,
authorUserId: MEMBER_A,
clientMessageId: `${MESSAGE_A}_client`,
body: "Tenant A confidential audit message",
mentions: [],
linkPreviews: [],
},
{
id: MESSAGE_B,
tenantId: TENANT_B,
chatId: CHAT_B,
authorUserId: MEMBER_B,
clientMessageId: `${MESSAGE_B}_client`,
body: "Tenant B must stay invisible",
mentions: [],
linkPreviews: [],
},
],
});
const readOwnPermission = await ensurePermission(admin, CHAT_PERMISSIONS.readOwnChannels, READ_OWN_PERMISSION_ID, 99_970);
createdReadOwnPermission = readOwnPermission.created;
const readAllPermission = await ensurePermission(admin, CHAT_PERMISSIONS.readAllChannels, READ_ALL_PERMISSION_ID, 99_971);
createdReadAllPermission = readAllPermission.created;
const adminPermission = await ensurePermission(admin, CHAT_PERMISSIONS.admin, ADMIN_PERMISSION_ID, 99_972);
createdAdminPermission = adminPermission.created;
await admin.role.create({
data: {
id: ROLE_ID,
tenantId: null,
name: "Chat audit RLS role",
description: "Restricted-role proof for chat admin audit",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 99_970,
},
});
await admin.rolePermission.createMany({
data: [
{ id: READ_OWN_ROLE_PERMISSION_ID, roleId: ROLE_ID, permissionId: readOwnPermission.id },
{ id: READ_ALL_ROLE_PERMISSION_ID, roleId: ROLE_ID, permissionId: readAllPermission.id },
{ id: ADMIN_ROLE_PERMISSION_ID, roleId: ROLE_ID, permissionId: adminPermission.id },
],
});
await admin.userRole.create({
data: { id: USER_ROLE_ID, tenantId: TENANT_A, userId: AUDITOR_A, roleId: ROLE_ID },
});
});
afterAll(async () => {
await cleanup(admin);
if (createdReadOwnPermission) {
await admin.permission.deleteMany({
where: { id: READ_OWN_PERMISSION_ID, name: CHAT_PERMISSIONS.readOwnChannels },
});
}
if (createdReadAllPermission) {
await admin.permission.deleteMany({
where: { id: READ_ALL_PERMISSION_ID, name: CHAT_PERMISSIONS.readAllChannels },
});
}
if (createdAdminPermission) {
await admin.permission.deleteMany({
where: { id: ADMIN_PERMISSION_ID, name: CHAT_PERMISSIONS.admin },
});
}
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("reads every channel in its own tenant, records every audit access, and rechecks revoked permission", async () => {
const role = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(role).toEqual([{ currentUser: "hivegrid_app" }]);
const rlsState = await app.$queryRaw<Array<{ tableName: string; enabled: boolean; forced: boolean }>>`
SELECT relname AS "tableName", relrowsecurity AS enabled, relforcerowsecurity AS forced
FROM pg_catalog.pg_class
WHERE relnamespace = 'public'::regnamespace
AND relname IN ('TeamChat', 'TeamChatMember', 'TeamChatMessage', 'OutboxEvent')
ORDER BY relname ASC
`;
expect(rlsState).toHaveLength(4);
expect(rlsState.every((table) => table.enabled && table.forced)).toBe(true);
await expect(app.teamChat.findMany({ select: { id: true } })).resolves.toEqual([]);
await expect(app.teamChatMessage.findMany({ select: { id: true } })).resolves.toEqual([]);
const context = {
tenantId: TENANT_A,
userId: AUDITOR_A,
permissions: STALE_ROUTE_PERMISSIONS,
} as const;
const auditSession = {
sessionId: SESSION_ID,
reason: AUDIT_REASON,
expiresAtIso: "2026-07-16T10:15:00.000Z",
} as const;
const channels = await listChatAuditChannels({
...context,
requestId: LIST_REQUEST_ID,
auditSession,
});
expect(channels.map(({ id }) => id)).toEqual([CHAT_A]);
expect(channels[0]).toMatchObject({
kind: "dm",
memberCount: 1,
participants: [{ userId: MEMBER_A, displayName: "Member A", avatarUrl: null }],
});
await recordChatAuditSessionStarted({
...context,
requestId: SESSION_REQUEST_ID,
auditSession,
});
await expect(
getChatAuditChannelDetail({
...context,
chatId: CHAT_B,
requestId: "chat_audit_rls_foreign_open_request",
auditSession,
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
forceArchiveChatAuditChannel({
...context,
chatId: CHAT_B,
requestId: "chat_audit_rls_foreign_archive_request",
auditSession,
})
).rejects.toMatchObject({ code: "foundation.not_found" });
const detail = await getChatAuditChannelDetail({
...context,
chatId: CHAT_A,
requestId: OPEN_REQUEST_ID,
auditSession,
});
expect(detail).toMatchObject({
channel: {
id: CHAT_A,
kind: "dm",
member: { canWrite: false, notificationPreference: "muted" },
},
messages: [{ id: MESSAGE_A, body: "Tenant A confidential audit message" }],
readReceipts: [],
messageFeatures: [],
});
await forceSetChatAuditMemberRole({
...context,
chatId: CHAT_A,
memberUserId: MEMBER_A,
roleInChat: "admin",
requestId: ROLE_REQUEST_ID,
auditSession,
});
await forceRemoveChatAuditMember({
...context,
chatId: CHAT_A,
memberUserId: MEMBER_A,
requestId: REMOVE_REQUEST_ID,
auditSession,
});
await forceArchiveChatAuditChannel({
...context,
chatId: CHAT_A,
requestId: ARCHIVE_REQUEST_ID,
auditSession,
});
await expect(
admin.teamChatMember.findUnique({
where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } },
select: { leftAt: true, writeRevokedAt: true, isManualMember: true, isProjectManaged: true, isGroupManaged: true },
})
).resolves.toMatchObject({
leftAt: expect.any(Date),
writeRevokedAt: expect.any(Date),
isManualMember: false,
isProjectManaged: false,
isGroupManaged: false,
});
await expect(admin.teamChat.findUnique({ where: { id: CHAT_A }, select: { archivedAt: true, archivedReason: true } })).resolves.toMatchObject({
archivedAt: expect.any(Date),
archivedReason: "manual",
});
const outboxRows = await admin.outboxEvent.findMany({
where: {
tenantId: TENANT_A,
eventType: "audit.event.create",
OR: [
{ payload: { path: ["requestId"], equals: SESSION_REQUEST_ID } },
{ payload: { path: ["requestId"], equals: LIST_REQUEST_ID } },
{ payload: { path: ["requestId"], equals: OPEN_REQUEST_ID } },
{ payload: { path: ["requestId"], equals: ROLE_REQUEST_ID } },
{ payload: { path: ["requestId"], equals: REMOVE_REQUEST_ID } },
{ payload: { path: ["requestId"], equals: ARCHIVE_REQUEST_ID } },
],
},
orderBy: { createdAt: "asc" },
select: { payload: true },
});
expect(outboxRows).toHaveLength(6);
expect(outboxRows.map(({ payload }) => payload)).toEqual([
expect.objectContaining({
action: "chat.audit.channel_listed",
requestId: LIST_REQUEST_ID,
metadata: expect.objectContaining({ auditSessionId: SESSION_ID, reason: AUDIT_REASON, readOnly: true }),
}),
expect.objectContaining({
action: "chat.audit.session_started",
requestId: SESSION_REQUEST_ID,
metadata: expect.objectContaining({ auditSessionId: SESSION_ID, reason: AUDIT_REASON, readOnly: true }),
}),
expect.objectContaining({
action: "chat.audit.channel_opened",
requestId: OPEN_REQUEST_ID,
targetId: CHAT_A,
dataSensitivity: "confidential",
metadata: expect.objectContaining({ auditSessionId: SESSION_ID, reason: AUDIT_REASON, readOnly: true }),
}),
expect.objectContaining({
action: "chat.audit.member_role_forced",
requestId: ROLE_REQUEST_ID,
metadata: expect.objectContaining({ auditSessionId: SESSION_ID, reason: AUDIT_REASON, memberUserId: MEMBER_A, roleInChat: "admin" }),
}),
expect.objectContaining({
action: "chat.audit.member_removed",
requestId: REMOVE_REQUEST_ID,
metadata: expect.objectContaining({ auditSessionId: SESSION_ID, reason: AUDIT_REASON, memberUserId: MEMBER_A }),
}),
expect.objectContaining({
action: "chat.audit.channel_archived",
requestId: ARCHIVE_REQUEST_ID,
metadata: expect.objectContaining({ auditSessionId: SESSION_ID, reason: AUDIT_REASON, channelId: CHAT_A }),
}),
]);
await expect(
admin.outboxEvent.count({
where: {
tenantId: TENANT_B,
eventType: "audit.event.create",
payload: { path: ["requestId"], equals: OPEN_REQUEST_ID },
},
})
).resolves.toBe(0);
await admin.rolePermission.delete({ where: { id: ADMIN_ROLE_PERMISSION_ID } });
await expect(
forceArchiveChatAuditChannel({
...context,
chatId: CHAT_A,
requestId: "chat_audit_rls_revoked_admin_request",
auditSession,
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await admin.rolePermission.delete({ where: { id: READ_ALL_ROLE_PERMISSION_ID } });
await expect(
listChatAuditChannels({
...context,
requestId: "chat_audit_rls_revoked_list_request",
auditSession,
})
).rejects.toMatchObject({ code: "foundation.not_found" });
});
});
async function ensurePermission(
admin: ReturnType<typeof createDbClient>,
name: string,
fixtureId: string,
order: number
): Promise<{ id: string; created: boolean }> {
const existing = await admin.permission.findUnique({ where: { name }, select: { id: true } });
if (existing) return { id: existing.id, created: false };
const created = await admin.permission.create({
data: {
id: fixtureId,
name,
description: "Chat admin audit RLS fixture",
type: "app",
isDefault: false,
order,
},
select: { id: true },
});
return { id: created.id, created: true };
}
async function cleanup(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.outboxEvent.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.userRole.deleteMany({ where: { id: USER_ROLE_ID } });
await admin.rolePermission.deleteMany({
where: { id: { in: [READ_OWN_ROLE_PERMISSION_ID, READ_ALL_ROLE_PERMISSION_ID, ADMIN_ROLE_PERMISSION_ID] } },
});
await admin.role.deleteMany({ where: { id: ROLE_ID } });
await admin.teamChatMessage.deleteMany({ where: { id: { in: [MESSAGE_A, MESSAGE_B] } } });
await admin.teamChatEvent.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.teamChatMember.deleteMany({ where: { id: { in: ["chat_audit_rls_member_row_a", "chat_audit_rls_member_row_b"] } } });
await admin.teamChat.deleteMany({ where: { id: { in: [CHAT_A, CHAT_B] } } });
await admin.tenantUser.deleteMany({
where: { id: { in: ["chat_audit_rls_tu_auditor_a", "chat_audit_rls_tu_member_a", "chat_audit_rls_tu_member_b"] } },
});
await admin.tenant.deleteMany({ where: { id: { in: [TENANT_A, TENANT_B] } } });
await admin.user.deleteMany({ where: { id: { in: [AUDITOR_A, MEMBER_A, MEMBER_B] } } });
}
@@ -0,0 +1,397 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "./permissions.js";
const mocks = vi.hoisted(() => ({
runTransaction: vi.fn(),
publishAudit: vi.fn(),
publishWakeup: vi.fn(),
logActivity: vi.fn(),
tx: {
teamChat: { findMany: vi.fn(), findFirst: vi.fn(), updateMany: vi.fn() },
teamChatEvent: { findFirst: vi.fn(), create: vi.fn() },
teamChatMember: { findFirst: vi.fn(), updateMany: vi.fn() },
teamChatMessage: { findMany: vi.fn() },
fileEntityLink: { findMany: vi.fn() },
file: { findMany: vi.fn() },
$queryRaw: vi.fn(),
},
}));
vi.mock("./repository.server.js", () => ({
runChatRepositoryTransaction: (...args: unknown[]) => mocks.runTransaction(...args),
parseChatMessageCursor: (value: string | undefined) =>
value
? {
createdAt: new Date("2026-07-16T08:30:00.000Z"),
id: "message-cursor",
}
: null,
encodeChatMessageCursor: (_chatId: string, row: { id: string }) => `cursor-${row.id}`,
}));
vi.mock("@hivegrid/db/audit-events.server", () => ({
publishAuditEventViaOutbox: (...args: unknown[]) => mocks.publishAudit(...args),
}));
vi.mock("./realtime-wakeup.server.js", () => ({
publishChatPersistentRealtimeWakeup: (...args: unknown[]) => mocks.publishWakeup(...args),
}));
vi.mock("@hivegrid/activity", () => ({
logActivity: (...args: unknown[]) => mocks.logActivity(...args),
}));
import {
forceArchiveChatAuditChannel,
forceRemoveChatAuditMember,
forceSetChatAuditMemberRole,
getChatAuditAdministration,
getChatAuditAttachmentDownload,
getChatAuditChannelDetail,
listChatAuditChannels,
recordChatAuditSessionStarted,
} from "./audit.server.js";
const context = {
tenantId: "tenant-a",
userId: "admin-a",
permissions: [CHAT_PERMISSIONS.readAllChannels],
} as const;
const auditSession = {
sessionId: "audit-session-1",
reason: "Kundenreklamation prüfen",
expiresAtIso: "2026-07-16T10:15:00.000Z",
};
describe("AK-P15b chat admin audit repository", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.runTransaction.mockImplementation(
async (_context: unknown, _permission: string, operation: (tx: typeof mocks.tx, permissions: readonly string[]) => Promise<unknown>) =>
operation(mocks.tx, [CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.readAllChannels, CHAT_PERMISSIONS.admin])
);
mocks.tx.teamChat.findMany.mockResolvedValue([]);
mocks.tx.teamChat.findFirst.mockResolvedValue(channel());
mocks.tx.teamChatEvent.findFirst.mockResolvedValue({ sequence: 4n });
mocks.tx.teamChatMessage.findMany.mockResolvedValue([message()]);
mocks.tx.teamChat.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.teamChatMember.findFirst.mockResolvedValue({
id: "membership-a",
roleInChat: "member",
joinedAt: new Date("2026-07-16T08:00:00.000Z"),
manualRoleInChat: "member",
isManualMember: true,
});
mocks.tx.teamChatMember.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.teamChatEvent.create.mockResolvedValue({ sequence: 5n, occurredAt: new Date("2026-07-16T09:05:00.000Z") });
mocks.tx.fileEntityLink.findMany.mockResolvedValue([]);
mocks.tx.file.findMany.mockResolvedValue([]);
mocks.tx.$queryRaw.mockResolvedValue([
{ chatId: "chat-a", userId: "member-a", displayName: "Anna Adler", avatarUrl: null },
{ chatId: "chat-a", userId: "member-b", displayName: "Ben Bauer", avatarUrl: null },
]);
});
it("lists all channels only through the fresh read-all gate and explicit tenant scope", async () => {
mocks.tx.teamChat.findMany.mockResolvedValue([channel()]);
const result = await listChatAuditChannels({
...context,
requestId: "list-request-1",
auditSession,
});
expect(mocks.runTransaction).toHaveBeenCalledWith(expect.objectContaining(context), CHAT_PERMISSIONS.readAllChannels, expect.any(Function));
expect(mocks.tx.teamChat.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId: "tenant-a" },
select: expect.objectContaining({
_count: { select: { members: { where: { tenantId: "tenant-a", leftAt: null } } } },
}),
})
);
expect(result).toEqual([
expect.objectContaining({
id: "chat-a",
memberCount: 2,
participants: [
{ userId: "member-a", displayName: "Anna Adler", avatarUrl: null },
{ userId: "member-b", displayName: "Ben Bauer", avatarUrl: null },
],
}),
]);
expect(mocks.publishAudit).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({
action: "chat.audit.channel_listed",
requestId: "list-request-1",
metadata: expect.objectContaining({
auditSessionId: "audit-session-1",
reason: "Kundenreklamation prüfen",
channelCount: 1,
}),
})
);
});
it("writes an immutable audit event for every read-only channel opening", async () => {
const detail = await getChatAuditChannelDetail({
...context,
chatId: "chat-a",
requestId: "open-request-1",
auditSession,
});
expect(mocks.tx.teamChat.findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: "tenant-a", id: "chat-a" } }));
expect(detail.channel.member.canWrite).toBe(false);
expect(detail.messages).toHaveLength(1);
expect(mocks.publishAudit).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({
tenantId: "tenant-a",
actorId: "admin-a",
action: "chat.audit.channel_opened",
targetId: "chat-a",
requestId: "open-request-1",
dataSensitivity: "confidential",
metadata: expect.objectContaining({
auditSessionId: "audit-session-1",
reason: "Kundenreklamation prüfen",
readOnly: true,
}),
})
);
});
it("resolves every attachment download through the reason-bound audit gate and logs the read", async () => {
mocks.tx.fileEntityLink.findMany.mockResolvedValue([{ entityId: "message-a", fileId: "file-a" }]);
mocks.tx.teamChatMessage.findMany.mockResolvedValue([{ id: "message-a" }]);
mocks.tx.file.findMany.mockResolvedValue([
{
id: "file-a",
displayName: "rechnung.pdf",
storageKey: "tenants/tenant-a/files/file-a",
previewStorageKey: null,
thumbnailStorageKey: null,
},
]);
const result = await getChatAuditAttachmentDownload({
...context,
chatId: "chat-a",
fileId: "file-a",
variant: "original",
requestId: "attachment-request-1",
auditSession,
});
expect(mocks.runTransaction).toHaveBeenCalledWith(expect.anything(), CHAT_PERMISSIONS.readAllChannels, expect.any(Function));
expect(mocks.tx.teamChatMessage.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId: "tenant-a", id: { in: ["message-a"] }, chatId: "chat-a" },
})
);
expect(mocks.tx.file.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId: "tenant-a", id: "file-a", archivedAt: null, scanStatus: "clean" },
})
);
expect(mocks.publishAudit).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({
action: "chat.audit.attachment_opened",
targetType: "File",
targetId: "file-a",
requestId: "attachment-request-1",
metadata: expect.objectContaining({
auditSessionId: "audit-session-1",
reason: auditSession.reason,
chatId: "chat-a",
messageId: "message-a",
variant: "original",
}),
})
);
expect(result.storageKey).toBe("tenants/tenant-a/files/file-a");
});
it("rejects a missing attachment variant before recording a successful audit read", async () => {
mocks.tx.fileEntityLink.findMany.mockResolvedValue([{ entityId: "message-a", fileId: "file-a" }]);
mocks.tx.teamChatMessage.findMany.mockResolvedValue([{ id: "message-a" }]);
mocks.tx.file.findMany.mockResolvedValue([
{
id: "file-a",
displayName: "rechnung.pdf",
storageKey: "tenants/tenant-a/files/file-a",
previewStorageKey: null,
thumbnailStorageKey: null,
},
]);
await expect(
getChatAuditAttachmentDownload({
...context,
chatId: "chat-a",
fileId: "file-a",
variant: "preview",
requestId: "attachment-request-missing-preview",
auditSession,
})
).rejects.toMatchObject({ status: 404 });
expect(mocks.publishAudit).not.toHaveBeenCalled();
});
it("does not audit or expose an attachment that is not linked to the requested channel", async () => {
mocks.tx.fileEntityLink.findMany.mockResolvedValue([{ entityId: "other-message", fileId: "file-a" }]);
mocks.tx.teamChatMessage.findMany.mockResolvedValue([]);
await expect(
getChatAuditAttachmentDownload({
...context,
chatId: "chat-a",
fileId: "file-a",
variant: "original",
requestId: "attachment-request-2",
auditSession,
})
).rejects.toMatchObject({ status: 404 });
expect(mocks.tx.file.findMany).not.toHaveBeenCalled();
expect(mocks.publishAudit).not.toHaveBeenCalled();
});
it("logs each justified audit session before any channel is exposed", async () => {
await recordChatAuditSessionStarted({ ...context, requestId: "session-request-1", auditSession });
expect(mocks.publishAudit).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({
action: "chat.audit.session_started",
targetType: "Tenant",
targetId: "tenant-a",
metadata: expect.objectContaining({ auditSessionId: "audit-session-1", reason: "Kundenreklamation prüfen" }),
})
);
});
it("loads force-admin capabilities through the read-all boundary", async () => {
const result = await getChatAuditAdministration({ ...context, chatId: "chat-a" });
expect(mocks.runTransaction).toHaveBeenCalledWith(expect.anything(), CHAT_PERMISSIONS.readAllChannels, expect.any(Function));
expect(result).toMatchObject({
channel: { id: "chat-a", kind: "dm" },
canAdminister: true,
members: [
{ userId: "member-a", displayName: "Anna Adler", roleInChat: "admin" },
{ userId: "member-b", displayName: "Ben Bauer", roleInChat: "member" },
],
});
});
it("force-updates a member role only through both fresh admin permissions and logs the reason", async () => {
await forceSetChatAuditMemberRole({
...context,
permissions: [CHAT_PERMISSIONS.readAllChannels, CHAT_PERMISSIONS.admin],
chatId: "chat-a",
memberUserId: "member-a",
roleInChat: "admin",
requestId: "role-request-1",
auditSession,
});
expect(mocks.runTransaction).toHaveBeenCalledWith(expect.anything(), CHAT_PERMISSIONS.admin, expect.any(Function));
expect(mocks.tx.teamChatMember.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ tenantId: "tenant-a", chatId: "chat-a", id: "membership-a" }),
data: expect.objectContaining({ roleInChat: "admin", isManualMember: true, manualRoleInChat: "admin" }),
})
);
expect(mocks.publishAudit).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({
action: "chat.audit.member_role_forced",
requestId: "role-request-1",
metadata: expect.objectContaining({ reason: auditSession.reason, memberUserId: "member-a", roleInChat: "admin" }),
})
);
expect(mocks.publishWakeup).toHaveBeenCalledOnce();
expect(mocks.logActivity).toHaveBeenCalledOnce();
});
it("force-removes a member and audits the destructive action", async () => {
await forceRemoveChatAuditMember({
...context,
permissions: [CHAT_PERMISSIONS.readAllChannels, CHAT_PERMISSIONS.admin],
chatId: "chat-a",
memberUserId: "member-a",
requestId: "remove-request-1",
auditSession,
});
expect(mocks.tx.teamChatMember.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ leftAt: expect.any(Date), isManualMember: false, isProjectManaged: false, isGroupManaged: false }),
})
);
expect(mocks.publishAudit).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({ action: "chat.audit.member_removed", metadata: expect.objectContaining({ reason: auditSession.reason }) })
);
});
it("archives any tenant channel as an audited cleanup action", async () => {
await forceArchiveChatAuditChannel({
...context,
permissions: [CHAT_PERMISSIONS.readAllChannels, CHAT_PERMISSIONS.admin],
chatId: "chat-a",
requestId: "archive-request-1",
auditSession,
});
expect(mocks.tx.teamChat.updateMany).toHaveBeenCalledWith(
expect.objectContaining({ where: { tenantId: "tenant-a", id: "chat-a", archivedAt: null }, data: expect.objectContaining({ archivedReason: "manual" }) })
);
expect(mocks.publishAudit).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({ action: "chat.audit.channel_archived", metadata: expect.objectContaining({ reason: auditSession.reason }) })
);
});
});
function channel() {
return {
id: "chat-a",
kind: "dm",
name: null,
description: null,
projektId: null,
isPrivate: true,
archivedAt: null,
lastMessageAt: new Date("2026-07-16T09:00:00.000Z"),
eventStreamId: "stream-a",
members: [
{ userId: "member-a", roleInChat: "admin" },
{ userId: "member-b", roleInChat: "member" },
],
_count: { members: 2 },
};
}
function message() {
const timestamp = new Date("2026-07-16T09:00:00.000Z");
return {
id: "message-a",
createdAt: timestamp,
updatedAt: timestamp,
tenantId: "tenant-a",
chatId: "chat-a",
authorUserId: "member-a",
clientMessageId: "client-a",
body: "Vertrauliche Nachricht",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [],
linkPreviews: [],
editedAt: null,
deletedAt: null,
systemEventKind: null,
systemEventMetadata: null,
};
}
@@ -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;
}
@@ -0,0 +1,252 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "./permissions.js";
const mocks = vi.hoisted(() => ({
currentPermissions: [] as string[],
runChatRepositoryTransaction: vi.fn(),
tx: {
teamChat: { findFirst: vi.fn() },
tenantUser: { findMany: vi.fn() },
},
}));
vi.mock("./repository.server.js", () => ({
runChatRepositoryTransaction: (...args: unknown[]) => mocks.runChatRepositoryTransaction(...args),
}));
import { loadChatChannelSettings } from "./channel-settings.server.js";
const NOW = new Date("2026-07-16T10:00:00.000Z");
const context = {
tenantId: "tenant_1",
userId: "user_viewer",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
} as const;
function channel(kind: "group" | "dm" | "project", overrides: Record<string, unknown> = {}) {
return {
id: "chat_1",
kind,
name: kind === "dm" ? null : " Montage ",
description: " Einsatzteam ",
projektId: kind === "project" ? "project_1" : null,
isPrivate: kind !== "group",
archivedAt: null,
members: [member("user_viewer", "admin"), member("user_member", "member")],
...overrides,
};
}
function member(userId: string, roleInChat: "admin" | "member", overrides: Record<string, unknown> = {}) {
return {
userId,
joinedAt: NOW,
joinedViaUserId: "user_viewer",
roleInChat,
isManualMember: true,
manualRoleInChat: roleInChat,
isProjectManaged: false,
projectRoleInChat: null,
isGroupManaged: false,
writeRevokedAt: null,
...overrides,
};
}
function tenantUser(userId: string, firstName: string, lastName: string, overrides: Record<string, unknown> = {}) {
return {
userId,
user: {
firstName,
lastName,
email: `${userId}@example.test`,
avatar: null,
...overrides,
},
};
}
describe("chat channel settings repository", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.currentPermissions.splice(0, mocks.currentPermissions.length, CHAT_PERMISSIONS.readOwnChannels);
mocks.runChatRepositoryTransaction.mockImplementation(
async (_context: unknown, _permission: string, callback: (tx: typeof mocks.tx, permissions: readonly string[]) => Promise<unknown>) =>
callback(mocks.tx, mocks.currentPermissions)
);
mocks.tx.teamChat.findFirst.mockResolvedValue(channel("group"));
mocks.tx.tenantUser.findMany.mockResolvedValue([
tenantUser("user_viewer", "Raffael", "Sheikh", { avatar: " /avatars/viewer " }),
tenantUser("user_member", "Ada", "Lovelace"),
tenantUser("user_candidate", "Grace", "Hopper"),
]);
});
it("loads a tenant-scoped group for its active channel admin with profiles, provenance, candidates, and capabilities", async () => {
mocks.tx.teamChat.findFirst.mockResolvedValue(
channel("group", {
members: [
member("user_viewer", "admin", { isManualMember: true, isGroupManaged: true }),
member("user_member", "member", {
isManualMember: false,
manualRoleInChat: null,
isGroupManaged: true,
writeRevokedAt: new Date("2026-07-16T09:00:00.000Z"),
}),
],
})
);
const result = await loadChatChannelSettings({ ...context, chatId: " chat_1 " });
expect(mocks.runChatRepositoryTransaction).toHaveBeenCalledWith(
{ ...context, chatId: " chat_1 " },
CHAT_PERMISSIONS.readOwnChannels,
expect.any(Function)
);
expect(mocks.tx.teamChat.findFirst).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
id: "chat_1",
members: { some: { tenantId: "tenant_1", userId: "user_viewer", leftAt: null } },
},
select: expect.objectContaining({
members: expect.objectContaining({ where: { tenantId: "tenant_1", leftAt: null } }),
}),
});
expect(mocks.tx.tenantUser.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: {
tenantId: "tenant_1",
status: 2,
user: { active: true, pendingDeletion: false, pseudonymized: false },
},
})
);
expect(result.channel).toEqual({
id: "chat_1",
kind: "group",
name: "Montage",
description: "Einsatzteam",
privacy: "public",
archivedAtIso: null,
projectId: null,
});
expect(result.members).toEqual([
expect.objectContaining({
userId: "user_viewer",
displayName: "Raffael Sheikh",
avatarUrl: "/avatars/viewer",
roleInChat: "admin",
provenance: expect.objectContaining({ isManualMember: true, isGroupManaged: true }),
}),
expect.objectContaining({
userId: "user_member",
displayName: "Ada Lovelace",
writeRevokedAtIso: "2026-07-16T09:00:00.000Z",
provenance: expect.objectContaining({ isManualMember: false, isGroupManaged: true }),
}),
]);
expect(result.candidateUsers).toEqual([expect.objectContaining({ userId: "user_candidate", displayName: "Grace Hopper" })]);
expect(result.capabilities).toEqual({
canManageMembers: true,
canManageAdmins: true,
canChangePrivacy: true,
canManageManualGuests: false,
canArchive: true,
canLeave: false,
isReadOnly: false,
});
});
it("uses the fresh chat.admin grant instead of the stale route snapshot", async () => {
mocks.currentPermissions.push(CHAT_PERMISSIONS.admin);
mocks.tx.teamChat.findFirst.mockResolvedValue(channel("group", { members: [member("user_viewer", "member"), member("user_member", "member")] }));
const result = await loadChatChannelSettings({ ...context, permissions: [CHAT_PERMISSIONS.readOwnChannels], chatId: "chat_1" });
expect(result.capabilities.canManageMembers).toBe(true);
expect(result.candidateUsers.map(({ userId }) => userId)).toEqual(["user_candidate"]);
});
it("does not trust a stale route chat.admin grant after it was revoked", async () => {
mocks.tx.teamChat.findFirst.mockResolvedValue(channel("group", { members: [member("user_viewer", "member"), member("user_member", "member")] }));
const result = await loadChatChannelSettings({
...context,
permissions: [CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.admin],
chatId: "chat_1",
});
expect(result.capabilities).toEqual({
canManageMembers: false,
canManageAdmins: false,
canChangePrivacy: false,
canManageManualGuests: false,
canArchive: false,
canLeave: true,
isReadOnly: false,
});
expect(result.candidateUsers).toEqual([]);
});
it("keeps DM settings read-only", async () => {
mocks.currentPermissions.push(CHAT_PERMISSIONS.admin);
mocks.tx.teamChat.findFirst.mockResolvedValue(
channel("dm", { members: [member("user_viewer", "member"), member("user_member", "member")] })
);
const result = await loadChatChannelSettings({ ...context, chatId: "chat_1" });
expect(result.channel).toMatchObject({ kind: "dm", privacy: null, projectId: null });
expect(result.capabilities).toEqual({
canManageMembers: false,
canManageAdmins: false,
canChangePrivacy: false,
canManageManualGuests: false,
canArchive: false,
canLeave: false,
isReadOnly: true,
});
expect(result.candidateUsers).toEqual([]);
});
it("lets an active project member with fresh chat.admin manage manual guests and archive", async () => {
mocks.currentPermissions.push(CHAT_PERMISSIONS.admin);
mocks.tx.teamChat.findFirst.mockResolvedValue(
channel("project", {
members: [
member("user_viewer", "member", { isManualMember: false, manualRoleInChat: null, isProjectManaged: true, projectRoleInChat: "member" }),
member("user_member", "member", { isManualMember: false, manualRoleInChat: null, isProjectManaged: true, projectRoleInChat: "member" }),
],
})
);
const result = await loadChatChannelSettings({ ...context, chatId: "chat_1" });
expect(result.capabilities).toEqual({
canManageMembers: false,
canManageAdmins: false,
canChangePrivacy: false,
canManageManualGuests: true,
canArchive: true,
canLeave: false,
isReadOnly: false,
});
expect(result.candidateUsers.map(({ userId }) => userId)).toEqual(["user_candidate"]);
});
it("fails closed before profiles when the viewer is not an active channel member", async () => {
mocks.tx.teamChat.findFirst.mockResolvedValue(null);
await expect(loadChatChannelSettings({ ...context, chatId: "chat_hidden" })).rejects.toMatchObject({ code: "foundation.not_found" });
expect(mocks.tx.tenantUser.findMany).not.toHaveBeenCalled();
});
it("rejects an invalid channel id before opening the repository transaction", async () => {
await expect(loadChatChannelSettings({ ...context, chatId: " " })).rejects.toThrow("chatId is invalid");
expect(mocks.runChatRepositoryTransaction).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,228 @@
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_PERMISSIONS } from "./permissions.js";
import { runChatRepositoryTransaction } from "./repository.server.js";
import type { ChatChannelKind, ChatMemberRole, ChatRouteRepositoryContext } from "./types.js";
const ACTIVE_TENANT_USER_STATUS = 2;
const CHANNEL_SETTINGS_SELECT = {
id: true,
kind: true,
name: true,
description: true,
projektId: true,
isPrivate: true,
archivedAt: true,
members: {
where: { leftAt: null },
orderBy: { userId: "asc" },
select: {
userId: true,
joinedAt: true,
joinedViaUserId: true,
roleInChat: true,
isManualMember: true,
manualRoleInChat: true,
isProjectManaged: true,
projectRoleInChat: true,
isGroupManaged: true,
writeRevokedAt: true,
},
},
} as const satisfies Prisma.TeamChatSelect;
type ChannelSettingsRow = Prisma.TeamChatGetPayload<{ select: typeof CHANNEL_SETTINGS_SELECT }>;
export type LoadChatChannelSettingsInput = ChatRouteRepositoryContext & {
readonly chatId: string;
};
export type ChatChannelSettingsProfile = Readonly<{
userId: string;
displayName: string;
email: string;
avatarUrl: string | null;
}>;
export type ChatChannelSettingsMember = ChatChannelSettingsProfile &
Readonly<{
roleInChat: ChatMemberRole;
joinedAtIso: string;
joinedViaUserId: string | null;
writeRevokedAtIso: string | null;
provenance: Readonly<{
isManualMember: boolean;
manualRoleInChat: ChatMemberRole | null;
isProjectManaged: boolean;
projectRoleInChat: ChatMemberRole | null;
isGroupManaged: boolean;
}>;
}>;
export type ChatChannelSettingsCapabilities = Readonly<{
canManageMembers: boolean;
canManageAdmins: boolean;
canChangePrivacy: boolean;
canManageManualGuests: boolean;
canArchive: boolean;
canLeave: boolean;
isReadOnly: boolean;
}>;
export type ChatChannelSettingsRecord = Readonly<{
channel: Readonly<{
id: string;
kind: ChatChannelKind;
name: string | null;
description: string | null;
privacy: "public" | "private" | null;
archivedAtIso: string | null;
projectId: string | null;
}>;
members: readonly ChatChannelSettingsMember[];
candidateUsers: readonly ChatChannelSettingsProfile[];
capabilities: ChatChannelSettingsCapabilities;
}>;
export async function loadChatChannelSettings(input: LoadChatChannelSettingsInput): Promise<ChatChannelSettingsRecord> {
const chatId = normalizeIdentifier(input.chatId);
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx, currentPermissions) => {
const channel = await loadActiveMemberChannel(tx, input, chatId);
if (!channel) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
const profiles = await loadActiveTenantProfiles(tx, input.tenantId);
const profilesByUserId = new Map(profiles.map((profile) => [profile.userId, profile]));
const members = channel.members.flatMap<ChatChannelSettingsMember>((member) => {
const profile = profilesByUserId.get(member.userId);
if (!profile) return [];
return [
{
...profile,
roleInChat: member.roleInChat,
joinedAtIso: member.joinedAt.toISOString(),
joinedViaUserId: member.joinedViaUserId,
writeRevokedAtIso: member.writeRevokedAt?.toISOString() ?? null,
provenance: {
isManualMember: member.isManualMember,
manualRoleInChat: member.manualRoleInChat,
isProjectManaged: member.isProjectManaged,
projectRoleInChat: member.projectRoleInChat,
isGroupManaged: member.isGroupManaged,
},
},
];
});
const viewer = members.find((member) => member.userId === input.userId);
if (!viewer) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
const capabilities = buildCapabilities(channel, viewer, members, currentPermissions);
const memberIds = new Set(members.map((member) => member.userId));
const candidateUsers = capabilities.canManageMembers || capabilities.canManageManualGuests
? profiles.filter((profile) => !memberIds.has(profile.userId))
: [];
return {
channel: {
id: channel.id,
kind: channel.kind,
name: normalizeOptionalText(channel.name),
description: normalizeOptionalText(channel.description),
privacy: channel.kind === "group" ? (channel.isPrivate ? "private" : "public") : null,
archivedAtIso: channel.archivedAt?.toISOString() ?? null,
projectId: channel.kind === "project" ? channel.projektId : null,
},
members,
candidateUsers,
capabilities,
};
});
}
async function loadActiveMemberChannel(
tx: DbTransactionClient,
context: Pick<LoadChatChannelSettingsInput, "tenantId" | "userId">,
chatId: string
): Promise<ChannelSettingsRow | null> {
const memberScope = withTenantScope(context.tenantId, { userId: context.userId, leftAt: null });
return tx.teamChat.findFirst({
where: withTenantScope(context.tenantId, {
id: chatId,
members: { some: memberScope },
}),
select: {
...CHANNEL_SETTINGS_SELECT,
members: {
...CHANNEL_SETTINGS_SELECT.members,
where: withTenantScope(context.tenantId, { leftAt: null }),
},
},
});
}
async function loadActiveTenantProfiles(tx: DbTransactionClient, tenantId: string): Promise<ChatChannelSettingsProfile[]> {
const memberships = await tx.tenantUser.findMany({
where: withTenantScope(tenantId, {
status: ACTIVE_TENANT_USER_STATUS,
user: { active: true, pendingDeletion: false, pseudonymized: false },
}),
select: {
userId: true,
user: { select: { firstName: true, lastName: true, email: true, avatar: true } },
},
orderBy: [{ user: { firstName: "asc" } }, { user: { lastName: "asc" } }, { user: { email: "asc" } }, { userId: "asc" }],
});
return memberships.map(({ userId, user }) => ({
userId,
displayName: displayName(user.firstName, user.lastName, user.email),
email: user.email,
avatarUrl: normalizeOptionalText(user.avatar),
}));
}
function buildCapabilities(
channel: ChannelSettingsRow,
viewer: ChatChannelSettingsMember,
members: readonly ChatChannelSettingsMember[],
currentPermissions: readonly string[]
): ChatChannelSettingsCapabilities {
const isGroup = channel.kind === "group";
const isProject = channel.kind === "project";
const isArchived = channel.archivedAt !== null;
const hasActiveSource =
viewer.provenance.isManualMember || viewer.provenance.isProjectManaged || viewer.provenance.isGroupManaged;
const isManager =
(isGroup || isProject) &&
viewer.writeRevokedAtIso === null &&
hasActiveSource &&
(viewer.roleInChat === "admin" || currentPermissions.includes(CHAT_PERMISSIONS.admin));
const canManage = isManager && !isArchived;
const viewerIsOnlyAdmin = viewer.roleInChat === "admin" && members.filter((member) => member.roleInChat === "admin").length === 1;
return {
canManageMembers: isGroup && canManage,
canManageAdmins: isGroup && canManage,
canChangePrivacy: isGroup && canManage,
canManageManualGuests: isProject && canManage,
canArchive: canManage,
canLeave: isGroup && !isArchived && !viewerIsOnlyAdmin,
isReadOnly: channel.kind === "dm" || isArchived || (isProject && !canManage),
};
}
function displayName(firstName: string, lastName: string, email: string): string {
return [firstName.trim(), lastName.trim()].filter(Boolean).join(" ") || email.trim();
}
function normalizeOptionalText(value: string | null): string | null {
const normalized = value?.trim() ?? "";
return normalized || null;
}
function normalizeIdentifier(value: string): string {
if (typeof value !== "string") throw new Error("chatId must be a string");
const normalized = value.trim();
if (!normalized || normalized.length > 500 || normalized.includes("\0")) throw new Error("chatId is invalid");
return normalized;
}
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { buildChatMessageDeepLink } from "./deep-links.js";
describe("chat message deep links", () => {
it("hydrates and focuses a top-level message", () => {
expect(buildChatMessageDeepLink({ tenantSlug: "demo", chatId: "chat 1", messageId: "message/1" })).toBe(
"/demo/chat/chat%201?message=message%2F1#message-message%2F1"
);
});
it("keeps exact thread replies addressable", () => {
expect(buildChatMessageDeepLink({ tenantSlug: "demo", chatId: "chat_1", parentMessageId: "parent_1", messageId: "reply_1" })).toBe(
"/demo/chat/chat_1/thread/parent_1?message=reply_1#message-reply_1"
);
});
});
@@ -0,0 +1,28 @@
export type ChatMessageDeepLinkInput = Readonly<{
tenantSlug: string;
chatId: string;
messageId: string;
parentMessageId?: string | null;
}>;
/** Canonical exact-message target used by notifications, pins, and search. */
export function buildChatMessageDeepLink(input: ChatMessageDeepLinkInput): string {
const tenantSlug = encodeURIComponent(requiredSegment(input.tenantSlug, "tenantSlug"));
const chatId = encodeURIComponent(requiredSegment(input.chatId, "chatId"));
const messageId = encodeURIComponent(requiredSegment(input.messageId, "messageId"));
const parentMessageId = optionalSegment(input.parentMessageId);
const threadPath = parentMessageId ? `/thread/${encodeURIComponent(parentMessageId)}` : "";
return `/${tenantSlug}/chat/${chatId}${threadPath}?message=${messageId}#message-${messageId}`;
}
function requiredSegment(value: string, name: string): string {
const normalized = value.trim();
if (!normalized) throw new Error(`chat deep-link ${name} is required`);
return normalized;
}
function optionalSegment(value: string | null | undefined): string | null {
if (value === null || value === undefined) return null;
return requiredSegment(value, "parentMessageId");
}
@@ -0,0 +1,103 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "./permissions.js";
const mocks = vi.hoisted(() => ({
runTransaction: vi.fn(),
tx: {
teamChat: { findMany: vi.fn() },
},
}));
vi.mock("./repository.server.js", () => ({
runChatRepositoryTransaction: (...args: unknown[]) => mocks.runTransaction(...args),
}));
import { listDiscoverablePublicGroupChats } from "./discovery.server.js";
const context = {
tenantId: "tenant_1",
userId: "user_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
} as const;
describe("public group discovery", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.runTransaction.mockImplementation((_context, _permission, operation: (tx: typeof mocks.tx) => unknown) => operation(mocks.tx));
mocks.tx.teamChat.findMany.mockResolvedValue([]);
});
it("lists only active public groups outside the viewer's active memberships", async () => {
mocks.tx.teamChat.findMany.mockResolvedValue([
{
id: "chat_public",
name: " Montage Nord ",
description: " Öffentlicher Austausch ",
_count: { members: 4 },
},
]);
const result = await listDiscoverablePublicGroupChats({ ...context, query: " Montage ", limit: 12 });
expect(mocks.runTransaction).toHaveBeenCalledWith(contextWithInput(" Montage ", 12), CHAT_PERMISSIONS.readOwnChannels, expect.any(Function));
expect(mocks.tx.teamChat.findMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
kind: "group",
isPrivate: false,
archivedAt: null,
name: { not: null },
members: { none: { tenantId: "tenant_1", userId: "user_1", leftAt: null } },
OR: [
{ name: { contains: "Montage", mode: "insensitive" } },
{ description: { contains: "Montage", mode: "insensitive" } },
],
},
select: {
id: true,
name: true,
description: true,
_count: { select: { members: { where: { tenantId: "tenant_1", leftAt: null } } } },
},
orderBy: [{ name: "asc" }, { id: "asc" }],
take: 12,
});
expect(result).toEqual({
channels: [{ id: "chat_public", name: "Montage Nord", description: "Öffentlicher Austausch", memberCount: 4 }],
});
});
it("keeps DM, project, private, archived, foreign-tenant, and joined channels outside the query contract", async () => {
await listDiscoverablePublicGroupChats(context);
const where = mocks.tx.teamChat.findMany.mock.calls[0]?.[0]?.where;
expect(where).toMatchObject({
tenantId: "tenant_1",
kind: "group",
isPrivate: false,
archivedAt: null,
members: { none: { tenantId: "tenant_1", userId: "user_1", leftAt: null } },
});
expect(where).not.toHaveProperty("projektId");
});
it("rejects malformed public input before opening the RLS transaction", async () => {
await expect(listDiscoverablePublicGroupChats({ ...context, query: "x".repeat(201) })).rejects.toMatchObject({ code: "chat.invalid_input" });
await expect(listDiscoverablePublicGroupChats({ ...context, limit: 0 })).rejects.toMatchObject({ code: "chat.invalid_input" });
await expect(listDiscoverablePublicGroupChats({ ...context, limit: 51 })).rejects.toMatchObject({ code: "chat.invalid_input" });
expect(mocks.runTransaction).not.toHaveBeenCalled();
expect(mocks.tx.teamChat.findMany).not.toHaveBeenCalled();
});
it("fails closed instead of rendering a malformed group row", async () => {
mocks.tx.teamChat.findMany.mockResolvedValue([{ id: "chat_bad", name: " ", description: null, _count: { members: 0 } }]);
await expect(listDiscoverablePublicGroupChats(context)).rejects.toMatchObject({ code: "chat.integrity_failure" });
});
});
function contextWithInput(query: string, limit: number) {
return { ...context, query, limit };
}
@@ -0,0 +1,98 @@
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { CatalogError, withTenantScope } from "@hivegrid/foundation";
import { chatErrors } from "./errors.js";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { runChatRepositoryTransaction } from "./repository.server.js";
import type { ChatRouteRepositoryContext } from "./types.js";
const DEFAULT_DISCOVER_LIMIT = 25;
const MAX_DISCOVER_LIMIT = 50;
const MAX_DISCOVER_QUERY_LENGTH = 200;
export type DiscoverPublicGroupChatsInput = ChatRouteRepositoryContext & {
readonly query?: string;
readonly limit?: number;
};
export type DiscoverablePublicGroupChat = {
readonly id: string;
readonly name: string;
readonly description: string | null;
readonly memberCount: number;
};
export type DiscoverPublicGroupChatsResult = {
readonly channels: readonly DiscoverablePublicGroupChat[];
};
/**
* Lists active public group channels that the current tenant user has not yet
* joined. The shared transaction boundary binds RLS and re-checks tenant,
* module, and permission access in the same transaction as this read.
*/
export async function listDiscoverablePublicGroupChats(
input: DiscoverPublicGroupChatsInput
): Promise<DiscoverPublicGroupChatsResult> {
const normalized = normalizeInput(input);
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
const activeViewerMembership = withTenantScope(input.tenantId, {
userId: input.userId,
leftAt: null,
});
const activeMember = withTenantScope(input.tenantId, { leftAt: null });
const textFilter: Prisma.TeamChatWhereInput = normalized.query
? {
OR: [
{ name: { contains: normalized.query, mode: "insensitive" } },
{ description: { contains: normalized.query, mode: "insensitive" } },
],
}
: {};
const rows = await tx.teamChat.findMany({
where: withTenantScope(input.tenantId, {
kind: "group" as const,
isPrivate: false,
archivedAt: null,
name: { not: null },
members: { none: activeViewerMembership },
...textFilter,
}),
select: {
id: true,
name: true,
description: true,
_count: { select: { members: { where: activeMember } } },
},
orderBy: [{ name: "asc" }, { id: "asc" }],
take: normalized.limit,
});
return {
channels: rows.map((row) => {
const name = row.name?.trim();
if (!name) throw new CatalogError(chatErrors.integrityFailure);
return {
id: row.id,
name,
description: row.description?.trim() || null,
memberCount: Math.max(0, row._count.members),
};
}),
};
});
}
function normalizeInput(input: Pick<DiscoverPublicGroupChatsInput, "query" | "limit">): {
readonly query: string;
readonly limit: number;
} {
const query = input.query?.trim() ?? "";
if (query.length > MAX_DISCOVER_QUERY_LENGTH) throw new CatalogError(chatErrors.invalidInput);
const limit = input.limit ?? DEFAULT_DISCOVER_LIMIT;
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_DISCOVER_LIMIT) {
throw new CatalogError(chatErrors.invalidInput);
}
return { query, limit };
}
@@ -0,0 +1,49 @@
import type { CatalogErrorDefinition } from "@hivegrid/foundation";
export const chatErrors = {
invalidInput: {
code: "chat.invalid_input",
status: 400,
i18nKey: "chat.errors.invalidInput",
},
integrityFailure: {
code: "chat.integrity_failure",
status: 500,
i18nKey: "chat.errors.integrityFailure",
},
realtimeUnavailable: {
code: "chat.realtime_unavailable",
status: 503,
i18nKey: "chat.errors.realtimeUnavailable",
},
realtimeRateLimited: {
code: "chat.realtime_rate_limited",
status: 429,
i18nKey: "chat.errors.realtimeRateLimited",
},
pinsNotAllowedInDirectMessages: {
code: "chat.pins_not_allowed_in_direct_messages",
status: 400,
i18nKey: "chat.errors.pinsNotAllowedInDirectMessages",
},
pinLimitReached: {
code: "chat.pin_limit_reached",
status: 409,
i18nKey: "chat.errors.pinLimitReached",
},
reactionLimitReached: {
code: "chat.reaction_limit_reached",
status: 409,
i18nKey: "chat.errors.reactionLimitReached",
},
messageEditWindowExpired: {
code: "chat.message_edit_window_expired",
status: 409,
i18nKey: "chat.errors.messageEditWindowExpired",
},
messageDeleteWindowExpired: {
code: "chat.message_delete_window_expired",
status: 409,
i18nKey: "chat.errors.messageDeleteWindowExpired",
},
} as const satisfies Record<string, CatalogErrorDefinition>;
@@ -0,0 +1,40 @@
import { TeamChatEventType } from "@hivegrid/db/prisma-browser";
import { CHAT_EVENT_NAMES, type ChatPersistentEvent } from "@hivegrid/realtime";
import { describe, expect, it } from "vitest";
import { toChatPersistentEventName, toPersistedChatEventType } from "./event-type-mapping.js";
const persistentNames: Array<ChatPersistentEvent["event"]> = [
CHAT_EVENT_NAMES.messageCreated,
CHAT_EVENT_NAMES.messageUpdated,
CHAT_EVENT_NAMES.messageDeleted,
CHAT_EVENT_NAMES.reactionAdded,
CHAT_EVENT_NAMES.reactionRemoved,
CHAT_EVENT_NAMES.threadReply,
CHAT_EVENT_NAMES.readReceipt,
CHAT_EVENT_NAMES.memberAdded,
CHAT_EVENT_NAMES.memberRemoved,
CHAT_EVENT_NAMES.channelArchived,
CHAT_EVENT_NAMES.pinChanged,
CHAT_EVENT_NAMES.linkPreviewReady,
];
describe("chat event persistence mapping", () => {
it("round-trips every generated Prisma enum value to its wire name", () => {
const persistedTypes = Object.values(TeamChatEventType);
expect(persistedTypes).toHaveLength(persistentNames.length);
for (const persistedType of persistedTypes) {
const wireName = toChatPersistentEventName(persistedType);
expect(toPersistedChatEventType(wireName)).toBe(persistedType);
}
});
it("round-trips every persistent wire event without including ephemeral events", () => {
for (const wireName of persistentNames) {
expect(toChatPersistentEventName(toPersistedChatEventType(wireName))).toBe(wireName);
}
expect(persistentNames).not.toContain(CHAT_EVENT_NAMES.typingStarted);
expect(persistentNames).not.toContain(CHAT_EVENT_NAMES.presenceOnline);
});
});
@@ -0,0 +1,42 @@
import { TeamChatEventType, type TeamChatEventType as PersistedChatEventType } from "@hivegrid/db/prisma-browser";
import { CHAT_EVENT_NAMES, type ChatPersistentEvent } from "@hivegrid/realtime";
export type ChatPersistentEventName = ChatPersistentEvent["event"];
const PERSISTED_TO_WIRE = {
[TeamChatEventType.message_created]: CHAT_EVENT_NAMES.messageCreated,
[TeamChatEventType.message_updated]: CHAT_EVENT_NAMES.messageUpdated,
[TeamChatEventType.message_deleted]: CHAT_EVENT_NAMES.messageDeleted,
[TeamChatEventType.reaction_added]: CHAT_EVENT_NAMES.reactionAdded,
[TeamChatEventType.reaction_removed]: CHAT_EVENT_NAMES.reactionRemoved,
[TeamChatEventType.thread_reply]: CHAT_EVENT_NAMES.threadReply,
[TeamChatEventType.read_updated]: CHAT_EVENT_NAMES.readReceipt,
[TeamChatEventType.member_added]: CHAT_EVENT_NAMES.memberAdded,
[TeamChatEventType.member_removed]: CHAT_EVENT_NAMES.memberRemoved,
[TeamChatEventType.channel_archived]: CHAT_EVENT_NAMES.channelArchived,
[TeamChatEventType.message_pin_changed]: CHAT_EVENT_NAMES.pinChanged,
[TeamChatEventType.link_preview_ready]: CHAT_EVENT_NAMES.linkPreviewReady,
} as const satisfies Readonly<Record<PersistedChatEventType, ChatPersistentEventName>>;
const WIRE_TO_PERSISTED = {
[CHAT_EVENT_NAMES.messageCreated]: TeamChatEventType.message_created,
[CHAT_EVENT_NAMES.messageUpdated]: TeamChatEventType.message_updated,
[CHAT_EVENT_NAMES.messageDeleted]: TeamChatEventType.message_deleted,
[CHAT_EVENT_NAMES.reactionAdded]: TeamChatEventType.reaction_added,
[CHAT_EVENT_NAMES.reactionRemoved]: TeamChatEventType.reaction_removed,
[CHAT_EVENT_NAMES.threadReply]: TeamChatEventType.thread_reply,
[CHAT_EVENT_NAMES.readReceipt]: TeamChatEventType.read_updated,
[CHAT_EVENT_NAMES.memberAdded]: TeamChatEventType.member_added,
[CHAT_EVENT_NAMES.memberRemoved]: TeamChatEventType.member_removed,
[CHAT_EVENT_NAMES.channelArchived]: TeamChatEventType.channel_archived,
[CHAT_EVENT_NAMES.pinChanged]: TeamChatEventType.message_pin_changed,
[CHAT_EVENT_NAMES.linkPreviewReady]: TeamChatEventType.link_preview_ready,
} as const satisfies Readonly<Record<ChatPersistentEventName, PersistedChatEventType>>;
export function toChatPersistentEventName(type: PersistedChatEventType): ChatPersistentEventName {
return PERSISTED_TO_WIRE[type];
}
export function toPersistedChatEventType(event: ChatPersistentEventName): PersistedChatEventType {
return WIRE_TO_PERSISTED[event];
}
@@ -0,0 +1,151 @@
import jwt, { type Algorithm, type JwtPayload } from "jsonwebtoken";
import { describe, expect, it } from "vitest";
import {
CHAT_GATEWAY_TOKEN_AUDIENCE,
CHAT_GATEWAY_TOKEN_ISSUER,
CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS,
CHAT_GATEWAY_TOKEN_PURPOSE,
issueChatGatewayToken,
verifyChatGatewayToken,
} from "./gateway-auth.server.js";
const SECRET = "chat-gateway-secret-at-least-32-bytes-long";
const OTHER_SECRET = "other-chat-secret-at-least-32-bytes-long";
const NOW = new Date("2026-07-15T12:00:00.000Z");
const NOW_SECONDS = Math.floor(NOW.getTime() / 1_000);
const TOKEN_ID = "123e4567-e89b-42d3-a456-426614174000";
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
const identity = {
userId: "user_1",
tenantId: "tenant_1",
sessionId: "session_1",
} as const;
function issue(overrides: Partial<Parameters<typeof issueChatGatewayToken>[0]> = {}): string {
return issueChatGatewayToken({ ...identity, secret: SECRET, now: NOW, ...overrides });
}
function signClaims(
claims: Record<string, unknown> = {},
options: {
algorithm?: Algorithm;
audience?: string | string[];
expiresIn?: number;
issuer?: string;
secret?: string;
} = {}
): string {
return jwt.sign(
{
tenantId: identity.tenantId,
sid: identity.sessionId,
purpose: CHAT_GATEWAY_TOKEN_PURPOSE,
iat: NOW_SECONDS,
...claims,
},
options.secret ?? SECRET,
{
algorithm: options.algorithm ?? "HS256",
audience: options.audience ?? CHAT_GATEWAY_TOKEN_AUDIENCE,
expiresIn: options.expiresIn ?? CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS,
issuer: options.issuer ?? CHAT_GATEWAY_TOKEN_ISSUER,
jwtid: TOKEN_ID,
subject: identity.userId,
}
);
}
describe("chat gateway JWT contract", () => {
it("issues a strict HS256 identity token and verifies it without authorization snapshots", () => {
const token = issue();
const decoded = jwt.decode(token) as JwtPayload;
const tokenId = decoded.jti as string;
expect(Object.keys(decoded).sort()).toEqual(["aud", "exp", "iat", "iss", "jti", "purpose", "sid", "sub", "tenantId"]);
expect(decoded).toMatchObject({
iss: CHAT_GATEWAY_TOKEN_ISSUER,
aud: CHAT_GATEWAY_TOKEN_AUDIENCE,
sub: identity.userId,
tenantId: identity.tenantId,
sid: identity.sessionId,
purpose: CHAT_GATEWAY_TOKEN_PURPOSE,
iat: NOW_SECONDS,
exp: NOW_SECONDS + CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS,
});
expect(tokenId).toMatch(UUID_PATTERN);
expect(decoded).not.toHaveProperty("permissions");
expect(decoded).not.toHaveProperty("channelIds");
expect(verifyChatGatewayToken(token, { secret: SECRET, now: NOW })).toEqual({
userId: identity.userId,
tenantId: identity.tenantId,
sessionId: identity.sessionId,
tokenId,
issuedAt: NOW_SECONDS,
expiresAt: NOW_SECONDS + CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS,
});
});
it("allows a shorter lifetime but refuses issuance beyond 900 seconds", () => {
const shortToken = issue({ ttlSeconds: 60 });
expect((jwt.decode(shortToken) as JwtPayload).exp).toBe(NOW_SECONDS + 60);
expect(() => issue({ ttlSeconds: CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS + 1 })).toThrow("TTL is invalid");
expect(() => issue({ ttlSeconds: 0 })).toThrow("TTL is invalid");
});
it("refuses issuance with weak configuration or malformed identity claims", () => {
expect(() => issue({ secret: "too-short" })).toThrow("auth secret is unavailable");
expect(() => issue({ secret: ` ${SECRET}` })).toThrow("auth secret is unavailable");
expect(() => issue({ userId: " " })).toThrow("userId is invalid");
expect(() => issue({ tenantId: "tenant\u0000evil" })).toThrow("tenantId is invalid");
expect(() => issue({ sessionId: "" })).toThrow("sessionId is invalid");
expect(() => issue({ now: new Date(Number.NaN) })).toThrow("clock is invalid");
});
it("pins the signature algorithm, dedicated secret, issuer and audience", () => {
expect(verifyChatGatewayToken(signClaims({}, { algorithm: "HS384" }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(issue(), { secret: OTHER_SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({}, { issuer: "other-service" }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({}, { audience: "other-gateway" }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({}, { audience: [CHAT_GATEWAY_TOKEN_AUDIENCE] }), { secret: SECRET, now: NOW })).toBeNull();
});
it("rejects wrong purpose, extra authorization claims and lifetimes beyond the contract", () => {
expect(verifyChatGatewayToken(signClaims({ purpose: "hocuspocus" }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({ permissions: ["chat.admin"] }), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(signClaims({ channelIds: ["chat_1"] }), { secret: SECRET, now: NOW })).toBeNull();
expect(
verifyChatGatewayToken(signClaims({}, { expiresIn: CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS + 1 }), {
secret: SECRET,
now: NOW,
})
).toBeNull();
});
it("requires every identity and temporal claim", () => {
const validClaims = jwt.decode(issue()) as JwtPayload;
for (const key of ["sub", "tenantId", "sid", "purpose", "jti", "iat", "exp"] as const) {
const claims = { ...validClaims };
delete claims[key];
const token = jwt.sign(claims, SECRET, { algorithm: "HS256", noTimestamp: true });
expect(verifyChatGatewayToken(token, { secret: SECRET, now: NOW }), key).toBeNull();
}
});
it("honors only a bounded clock tolerance and rejects expired or future-issued tokens", () => {
const token = issue({ ttlSeconds: 60 });
expect(verifyChatGatewayToken(token, { secret: SECRET, now: new Date(NOW.getTime() + 60_000), clockToleranceSeconds: 0 })).toBeNull();
expect(verifyChatGatewayToken(token, { secret: SECRET, now: new Date(NOW.getTime() + 60_000), clockToleranceSeconds: 1 })).not.toBeNull();
expect(verifyChatGatewayToken(token, { secret: SECRET, now: new Date(NOW.getTime() - 31_000), clockToleranceSeconds: 30 })).toBeNull();
expect(verifyChatGatewayToken(token, { secret: SECRET, now: NOW, clockToleranceSeconds: 31 })).toBeNull();
expect(verifyChatGatewayToken(token, { secret: SECRET, now: NOW, clockToleranceSeconds: -1 })).toBeNull();
});
it("fails closed for malformed tokens, weak verification secrets and invalid verifier clocks", () => {
expect(verifyChatGatewayToken("not-a-jwt", { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken("x".repeat(4_097), { secret: SECRET, now: NOW })).toBeNull();
expect(verifyChatGatewayToken(issue(), { secret: "too-short", now: NOW })).toBeNull();
expect(verifyChatGatewayToken(issue(), { secret: SECRET, now: new Date(Number.NaN) })).toBeNull();
});
});
@@ -0,0 +1,178 @@
import { randomUUID } from "node:crypto";
import jwt, { type JwtPayload } from "jsonwebtoken";
export const CHAT_GATEWAY_TOKEN_ISSUER = "web-app";
export const CHAT_GATEWAY_TOKEN_AUDIENCE = "team-chat-gateway";
export const CHAT_GATEWAY_TOKEN_PURPOSE = "team-chat";
export const CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS = 15 * 60;
export const CHAT_GATEWAY_TOKEN_DEFAULT_TTL_SECONDS = CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS;
export const CHAT_GATEWAY_TOKEN_MAX_CLOCK_TOLERANCE_SECONDS = 30;
export const CHAT_GATEWAY_TOKEN_DEFAULT_CLOCK_TOLERANCE_SECONDS = 15;
export const CHAT_GATEWAY_MIN_SECRET_BYTES = 32;
const MAX_TOKEN_LENGTH = 4_096;
const MAX_ID_LENGTH = 191;
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
const REQUIRED_CLAIMS = ["aud", "exp", "iat", "iss", "jti", "purpose", "sid", "sub", "tenantId"] as const;
const ALLOWED_CLAIMS = new Set<string>(REQUIRED_CLAIMS);
export type ChatGatewayTokenIdentity = {
readonly userId: string;
readonly tenantId: string;
readonly sessionId: string;
readonly tokenId: string;
readonly issuedAt: number;
readonly expiresAt: number;
};
export type IssueChatGatewayTokenInput = {
readonly userId: string;
readonly tenantId: string;
readonly sessionId: string;
/** Dedicated gateway secret. It must not be shared with Hocuspocus or another audience. */
readonly secret: string;
readonly ttlSeconds?: number;
readonly now?: Date;
};
export type VerifyChatGatewayTokenOptions = {
/** Dedicated gateway secret. It must not be shared with Hocuspocus or another audience. */
readonly secret: string;
readonly clockToleranceSeconds?: number;
readonly now?: Date;
};
/**
* Issues the short-lived identity capability used only by the standalone team-chat gateway.
* Authorization stays server-side: permissions and channel memberships are deliberately absent.
*/
export function issueChatGatewayToken(input: IssueChatGatewayTokenInput): string {
const secret = requireStrongSecret(input.secret);
const userId = requireIdentifier(input.userId, "userId");
const tenantId = requireIdentifier(input.tenantId, "tenantId");
const sessionId = requireIdentifier(input.sessionId, "sessionId");
const ttlSeconds = input.ttlSeconds ?? CHAT_GATEWAY_TOKEN_DEFAULT_TTL_SECONDS;
if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS) {
throw new Error("Chat gateway token TTL is invalid");
}
const nowSeconds = requireClockTimestamp(input.now);
const tokenId = randomUUID();
return jwt.sign(
{
tenantId,
sid: sessionId,
purpose: CHAT_GATEWAY_TOKEN_PURPOSE,
iat: nowSeconds,
},
secret,
{
algorithm: "HS256",
audience: CHAT_GATEWAY_TOKEN_AUDIENCE,
expiresIn: ttlSeconds,
issuer: CHAT_GATEWAY_TOKEN_ISSUER,
jwtid: tokenId,
subject: userId,
}
);
}
/**
* Verifies signature, audience, issuer, lifetime and the exact claim allow-list.
* Any malformed token or unsafe verifier configuration fails closed with `null`.
*/
export function verifyChatGatewayToken(token: string, options: VerifyChatGatewayTokenOptions): ChatGatewayTokenIdentity | null {
const secret = normalizeStrongSecret(options.secret);
if (!secret || typeof token !== "string" || token.length === 0 || token.length > MAX_TOKEN_LENGTH) return null;
const clockToleranceSeconds = options.clockToleranceSeconds ?? CHAT_GATEWAY_TOKEN_DEFAULT_CLOCK_TOLERANCE_SECONDS;
if (!Number.isInteger(clockToleranceSeconds) || clockToleranceSeconds < 0 || clockToleranceSeconds > CHAT_GATEWAY_TOKEN_MAX_CLOCK_TOLERANCE_SECONDS) {
return null;
}
let nowSeconds: number;
try {
nowSeconds = requireClockTimestamp(options.now);
} catch {
return null;
}
let claims: JwtPayload | string;
try {
claims = jwt.verify(token, secret, {
algorithms: ["HS256"],
audience: CHAT_GATEWAY_TOKEN_AUDIENCE,
clockTimestamp: nowSeconds,
clockTolerance: clockToleranceSeconds,
issuer: CHAT_GATEWAY_TOKEN_ISSUER,
maxAge: `${CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS}s`,
});
} catch {
return null;
}
if (typeof claims === "string" || !hasExactClaims(claims)) return null;
if (claims.iss !== CHAT_GATEWAY_TOKEN_ISSUER || claims.aud !== CHAT_GATEWAY_TOKEN_AUDIENCE) return null;
if (claims.purpose !== CHAT_GATEWAY_TOKEN_PURPOSE) return null;
if (!isIdentifier(claims.sub) || !isIdentifier(claims.tenantId) || !isIdentifier(claims.sid)) return null;
if (typeof claims.jti !== "string" || !UUID_PATTERN.test(claims.jti)) return null;
if (!Number.isInteger(claims.iat) || !Number.isInteger(claims.exp)) return null;
const issuedAt = claims.iat as number;
const expiresAt = claims.exp as number;
if (expiresAt <= issuedAt || expiresAt - issuedAt > CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS) return null;
if (issuedAt > nowSeconds + clockToleranceSeconds || expiresAt <= nowSeconds - clockToleranceSeconds) return null;
return {
userId: claims.sub,
tenantId: claims.tenantId,
sessionId: claims.sid,
tokenId: claims.jti,
issuedAt,
expiresAt,
};
}
function hasExactClaims(claims: JwtPayload): claims is JwtPayload & {
aud: string;
exp: number;
iat: number;
iss: string;
jti: string;
purpose: string;
sid: string;
sub: string;
tenantId: string;
} {
const keys = Object.keys(claims);
return keys.length === REQUIRED_CLAIMS.length && REQUIRED_CLAIMS.every((claim) => claim in claims) && keys.every((claim) => ALLOWED_CLAIMS.has(claim));
}
function requireStrongSecret(secret: string): string {
const normalized = normalizeStrongSecret(secret);
if (!normalized) throw new Error("Chat gateway auth secret is unavailable");
return normalized;
}
function normalizeStrongSecret(secret: unknown): string | null {
if (typeof secret !== "string" || secret !== secret.trim()) return null;
if (Buffer.byteLength(secret, "utf8") < CHAT_GATEWAY_MIN_SECRET_BYTES) return null;
return secret;
}
function requireIdentifier(value: string, name: "userId" | "tenantId" | "sessionId"): string {
if (!isIdentifier(value)) throw new Error(`Chat gateway ${name} is invalid`);
return value;
}
function isIdentifier(value: unknown): value is string {
return typeof value === "string" && value.length > 0 && value.length <= MAX_ID_LENGTH && value === value.trim() && !value.includes("\u0000");
}
function requireClockTimestamp(now: Date | undefined): number {
const timestamp = now?.getTime() ?? Date.now();
if (!Number.isFinite(timestamp)) throw new Error("Chat gateway token clock is invalid");
return Math.floor(timestamp / 1_000);
}
@@ -0,0 +1,346 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
tenantHasChatModuleForSystemTx: vi.fn(),
publishAuditEventViaOutbox: vi.fn(),
publishChatPersistentRealtimeWakeup: vi.fn(),
writeChatSystemMessageWithTx: vi.fn(),
logActivity: vi.fn(),
nextEventSequence: 1n,
tx: {
$executeRaw: vi.fn(),
group: { findMany: vi.fn() },
tenantUser: { findMany: vi.fn() },
teamChat: { findFirst: vi.fn() },
teamChatGroupSource: { findMany: vi.fn() },
teamChatMember: { create: vi.fn(), updateMany: vi.fn() },
teamChatEvent: { create: vi.fn() },
},
}));
vi.mock("./module-access.server.js", () => ({
tenantHasChatModuleForSystemTx: (...args: unknown[]) => mocks.tenantHasChatModuleForSystemTx(...args),
}));
vi.mock("@hivegrid/db/audit-events.server", () => ({
publishAuditEventViaOutbox: (...args: unknown[]) => mocks.publishAuditEventViaOutbox(...args),
}));
vi.mock("@hivegrid/activity", () => ({
logActivity: (...args: unknown[]) => mocks.logActivity(...args),
}));
vi.mock("./realtime-wakeup.server.js", () => ({
publishChatPersistentRealtimeWakeup: (...args: unknown[]) => mocks.publishChatPersistentRealtimeWakeup(...args),
}));
vi.mock("./system-message.server.js", () => ({
writeChatSystemMessageWithTx: (...args: unknown[]) => mocks.writeChatSystemMessageWithTx(...args),
}));
import { resolvePermissionGroupMembersWithTx, syncPermissionGroupChatsIfEnabledWithTx } from "./group-sync.server.js";
const INPUT = {
tenantId: "tenant_1",
groupId: "group_1",
actorUserId: "user_actor",
requestId: "request_1",
} as const;
function channel() {
return {
id: "chat_1",
eventStreamId: "stream_1",
isPrivate: true,
notificationDefault: "mentions_only",
groupSources: [{ groupId: "group_1" }, { groupId: "group_2" }],
members: [
{
id: "member_admin",
userId: "user_actor",
roleInChat: "admin",
isProjectManaged: false,
isManualMember: true,
isGroupManaged: false,
manualRoleInChat: "admin",
projectRoleInChat: null,
groupSyncOptOutAt: null,
writeRevokedAt: null,
leftAt: null,
},
{
id: "member_overlap",
userId: "user_overlap",
roleInChat: "member",
isProjectManaged: false,
isManualMember: true,
isGroupManaged: true,
manualRoleInChat: "member",
projectRoleInChat: null,
groupSyncOptOutAt: null,
writeRevokedAt: null,
leftAt: null,
},
{
id: "member_removed",
userId: "user_removed",
roleInChat: "member",
isProjectManaged: false,
isManualMember: false,
isGroupManaged: true,
manualRoleInChat: null,
projectRoleInChat: null,
groupSyncOptOutAt: null,
writeRevokedAt: null,
leftAt: null,
},
{
id: "member_existing",
userId: "user_existing",
roleInChat: "member",
isProjectManaged: false,
isManualMember: true,
isGroupManaged: false,
manualRoleInChat: "member",
projectRoleInChat: null,
groupSyncOptOutAt: null,
writeRevokedAt: null,
leftAt: null,
},
],
};
}
describe("permission-group chat sync", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.nextEventSequence = 1n;
mocks.tenantHasChatModuleForSystemTx.mockResolvedValue(true);
mocks.tx.$executeRaw.mockResolvedValue(1);
mocks.tx.teamChatGroupSource.findMany.mockResolvedValue([{ chatId: "chat_1" }]);
mocks.tx.teamChat.findFirst.mockResolvedValue(channel());
mocks.tx.group.findMany.mockResolvedValue([
{ id: "group_1", users: [{ userId: "user_new" }, { userId: "user_existing" }] },
{ id: "group_2", users: [{ userId: "user_new" }] },
]);
mocks.tx.tenantUser.findMany.mockImplementation(async ({ where }: { where: { userId?: { in?: string[] } } }) =>
(where.userId?.in ?? []).map((userId) => ({
userId,
user: { firstName: userId, lastName: null, email: `${userId}@example.test` },
}))
);
mocks.tx.teamChatMember.create.mockResolvedValue({ id: "member_new" });
mocks.tx.teamChatMember.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.teamChatEvent.create.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({
sequence: mocks.nextEventSequence++,
occurredAt: new Date("2026-07-16T08:00:00.000Z"),
tenantId: data.tenantId,
chatId: data.chatId,
type: data.type,
actorUserId: data.actorUserId,
entityId: data.entityId,
requestId: data.requestId,
data: data.data,
}));
mocks.publishChatPersistentRealtimeWakeup.mockResolvedValue({ id: "outbox_1" });
mocks.writeChatSystemMessageWithTx.mockImplementation(async (_tx: unknown, input: Record<string, unknown>) => ({
replayed: false,
event: { event: "chat.message.created", cursor: "stream_1:99", ...input },
}));
mocks.publishAuditEventViaOutbox.mockResolvedValue(undefined);
mocks.logActivity.mockResolvedValue({ id: "activity_1" });
});
it("resolves the deduplicated active-user union only from tenant-owned groups", async () => {
await expect(resolvePermissionGroupMembersWithTx(mocks.tx as never, "tenant_1", ["group_2", "group_1", "group_1"])).resolves.toEqual({
groupIds: ["group_1", "group_2"],
userIds: ["user_existing", "user_new"],
});
expect(mocks.tx.group.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", id: { in: ["group_1", "group_2"] } },
select: {
id: true,
users: {
where: {
user: {
active: true,
pendingDeletion: false,
pseudonymized: false,
tenants: { some: { tenantId: "tenant_1", status: 2 } },
},
},
select: { userId: true },
},
},
orderBy: { id: "asc" },
});
});
it("fails closed when any selected permission group is outside the tenant", async () => {
mocks.tx.group.findMany.mockResolvedValueOnce([{ id: "group_1", users: [] }]);
await expect(resolvePermissionGroupMembersWithTx(mocks.tx as never, "tenant_1", ["group_1", "foreign_group"])).rejects.toThrow(
"outside the tenant"
);
});
it("does not inspect chat sources when the tenant chat module is disabled", async () => {
mocks.tenantHasChatModuleForSystemTx.mockResolvedValueOnce(false);
await expect(syncPermissionGroupChatsIfEnabledWithTx(mocks.tx as never, INPUT)).resolves.toEqual({
changedChatIds: [],
addedUserIds: [],
removedUserIds: [],
});
expect(mocks.tx.teamChatGroupSource.findMany).not.toHaveBeenCalled();
});
it("reconciles all sync groups while preserving direct membership provenance", async () => {
const result = await syncPermissionGroupChatsIfEnabledWithTx(mocks.tx as never, INPUT);
expect(result).toEqual({
changedChatIds: ["chat_1"],
addedUserIds: ["user_new"],
removedUserIds: ["user_removed"],
});
expect(mocks.tx.teamChatMember.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: "tenant_1",
chatId: "chat_1",
userId: "user_new",
isManualMember: false,
isProjectManaged: false,
isGroupManaged: true,
manualRoleInChat: null,
projectRoleInChat: null,
notificationPref: "mentions_only",
}),
select: { id: true },
});
expect(mocks.tx.teamChatMember.updateMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", id: "member_existing", chatId: "chat_1", userId: "user_existing" },
data: { isGroupManaged: true, roleInChat: "member", writeRevokedAt: null, leftAt: null },
});
expect(mocks.tx.teamChatMember.updateMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", id: "member_overlap", chatId: "chat_1", userId: "user_overlap" },
data: { isGroupManaged: false, roleInChat: "member", writeRevokedAt: null, leftAt: null },
});
expect(mocks.tx.teamChatMember.updateMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", id: "member_removed", chatId: "chat_1", userId: "user_removed" },
data: { isGroupManaged: false, roleInChat: "member", leftAt: expect.any(Date) },
});
expect(mocks.tx.teamChatEvent.create).toHaveBeenCalledTimes(2);
expect(mocks.writeChatSystemMessageWithTx).toHaveBeenCalledTimes(2);
expect(mocks.writeChatSystemMessageWithTx).toHaveBeenNthCalledWith(
1,
mocks.tx,
expect.objectContaining({
kind: "member_added",
systemEventKey: expect.stringMatching(/^group-sync:[a-f0-9]{24}:member:[a-f0-9]{24}:added:[a-f0-9]{24}$/),
metadata: expect.objectContaining({ memberUserId: "user_new", memberName: "user_new" }),
})
);
expect(mocks.writeChatSystemMessageWithTx).toHaveBeenNthCalledWith(
2,
mocks.tx,
expect.objectContaining({
kind: "member_removed",
systemEventKey: expect.stringMatching(/^group-sync:[a-f0-9]{24}:member:[a-f0-9]{24}:removed:[a-f0-9]{24}$/),
metadata: expect.objectContaining({ memberUserId: "user_removed", memberName: "user_removed" }),
})
);
expect(mocks.publishChatPersistentRealtimeWakeup).toHaveBeenCalledTimes(4);
expect(mocks.publishAuditEventViaOutbox).toHaveBeenCalledOnce();
expect(mocks.logActivity).toHaveBeenCalledOnce();
expect(mocks.tx.$executeRaw.mock.calls[0]?.[1]).toBe("chat-membership:tenant_1:chat_1");
});
it("reactivates a previously inactive group-derived member without an explicit opt-out", async () => {
const existing = channel().members[3];
mocks.tx.teamChat.findFirst.mockResolvedValueOnce({
...channel(),
groupSources: [{ groupId: "group_1" }],
members: [
{
...existing,
roleInChat: "admin",
isManualMember: true,
manualRoleInChat: "admin",
leftAt: new Date("2026-07-15T12:00:00.000Z"),
},
],
});
mocks.tx.group.findMany.mockResolvedValueOnce([{ id: "group_1", users: [{ userId: "user_existing" }] }]);
await expect(syncPermissionGroupChatsIfEnabledWithTx(mocks.tx as never, INPUT)).resolves.toMatchObject({
addedUserIds: ["user_existing"],
});
expect(mocks.tx.teamChatMember.updateMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", id: "member_existing", chatId: "chat_1", userId: "user_existing" },
data: {
isGroupManaged: true,
roleInChat: "admin",
writeRevokedAt: null,
leftAt: null,
joinedAt: expect.any(Date),
joinedViaUserId: "user_actor",
},
});
});
it("keeps a group-managed member inactive after an explicit channel leave", async () => {
const optedOutAt = new Date("2026-07-15T12:00:00.000Z");
const existing = channel().members[3];
mocks.tx.teamChat.findFirst.mockResolvedValueOnce({
...channel(),
groupSources: [{ groupId: "group_1" }],
members: [
{
...existing,
isManualMember: false,
isGroupManaged: true,
manualRoleInChat: null,
groupSyncOptOutAt: optedOutAt,
leftAt: optedOutAt,
},
],
});
mocks.tx.group.findMany.mockResolvedValueOnce([{ id: "group_1", users: [{ userId: "user_existing" }] }]);
await expect(syncPermissionGroupChatsIfEnabledWithTx(mocks.tx as never, INPUT)).resolves.toEqual({
changedChatIds: [],
addedUserIds: [],
removedUserIds: [],
});
expect(mocks.tx.teamChatMember.updateMany).not.toHaveBeenCalled();
expect(mocks.tx.teamChatEvent.create).not.toHaveBeenCalled();
});
it("adds group provenance without overwriting a manual admin role", async () => {
const manualAdmin = {
...channel().members[3],
roleInChat: "admin" as const,
manualRoleInChat: "admin" as const,
};
mocks.tx.teamChat.findFirst.mockResolvedValueOnce({
...channel(),
groupSources: [{ groupId: "group_1" }],
members: [manualAdmin],
});
mocks.tx.group.findMany.mockResolvedValueOnce([{ id: "group_1", users: [{ userId: "user_existing" }] }]);
await syncPermissionGroupChatsIfEnabledWithTx(mocks.tx as never, INPUT);
expect(mocks.tx.teamChatMember.updateMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", id: "member_existing", chatId: "chat_1", userId: "user_existing" },
data: {
isGroupManaged: true,
roleInChat: "admin",
writeRevokedAt: null,
leftAt: null,
},
});
expect(mocks.tx.teamChatMember.updateMany.mock.calls[0]?.[0].data).not.toHaveProperty("manualRoleInChat");
});
});
@@ -0,0 +1,479 @@
import { createHash } from "node:crypto";
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 { withTenantScope } from "@hivegrid/foundation";
import { CHAT_EVENT_NAMES, isPersistentChatEvent, validateChatServerEvent } from "@hivegrid/realtime";
import { toChatPersistentEventName, toPersistedChatEventType } from "./event-type-mapping.js";
import { hasActiveChatMembershipSource, resolveEffectiveChatMemberRole } from "./member-role.js";
import { tenantHasChatModuleForSystemTx } from "./module-access.server.js";
import { publishChatPersistentRealtimeWakeup } from "./realtime-wakeup.server.js";
import { lockChatMembershipWithTx } from "./sync-locks.server.js";
import { writeChatSystemMessageWithTx } from "./system-message.server.js";
const ACTIVE_TENANT_USER_STATUS = 2;
const CHAT_EVENT_LOCK_SALT = 15_015;
const PERSISTED_EVENT_SELECT = {
sequence: true,
occurredAt: true,
tenantId: true,
chatId: true,
type: true,
actorUserId: true,
entityId: true,
requestId: true,
data: true,
} as const satisfies Prisma.TeamChatEventSelect;
type PersistedGroupSyncEvent = Prisma.TeamChatEventGetPayload<{ select: typeof PERSISTED_EVENT_SELECT }>;
export type PermissionGroupMembers = Readonly<{
groupIds: readonly string[];
userIds: readonly string[];
}>;
export type PermissionGroupChatSyncInput = Readonly<{
tenantId: string;
groupId: string;
actorUserId: string;
requestId: string;
}>;
export type PermissionGroupChatSyncResult = Readonly<{
changedChatIds: readonly string[];
addedUserIds: readonly string[];
removedUserIds: readonly string[];
}>;
type GroupManagedChannel = Readonly<{
id: string;
eventStreamId: string;
isPrivate: boolean;
notificationDefault: "all_messages" | "mentions_only" | "muted";
groupSources: readonly Readonly<{ groupId: string }>[];
members: readonly GroupManagedMember[];
}>;
type GroupManagedMember = Readonly<{
id: string;
userId: string;
roleInChat: "admin" | "member";
isProjectManaged: boolean;
isManualMember: boolean;
isGroupManaged: boolean;
manualRoleInChat: "admin" | "member" | null;
projectRoleInChat: "admin" | "member" | null;
groupSyncOptOutAt: Date | null;
writeRevokedAt: Date | null;
leftAt: Date | null;
}>;
/** Resolve selected tenant permission groups to the union of active tenant users. */
export async function resolvePermissionGroupMembersWithTx(
tx: DbTransactionClient,
tenantId: string,
requestedGroupIds: readonly string[]
): Promise<PermissionGroupMembers> {
const groupIds = normalizeIdentifiers(requestedGroupIds, "groupId");
if (groupIds.length === 0) return { groupIds: [], userIds: [] };
const groups = await tx.group.findMany({
where: withTenantScope(tenantId, { id: { in: groupIds } }),
select: {
id: true,
users: {
where: {
user: {
active: true,
pendingDeletion: false,
pseudonymized: false,
tenants: { some: withTenantScope(tenantId, { status: ACTIVE_TENANT_USER_STATUS }) },
},
},
select: { userId: true },
},
},
orderBy: { id: "asc" },
});
if (groups.length !== groupIds.length || groups.some((group, index) => group.id !== groupIds[index])) {
throw new Error("Permission-group selection contains a group outside the tenant");
}
return {
groupIds,
userIds: normalizeIdentifiers(
groups.flatMap((group) => group.users.map((membership) => membership.userId)),
"groupUserId"
),
};
}
/**
* Reconcile every active group chat that auto-syncs the changed permission
* group. The caller keeps the GroupUser mutation and this reconciliation in
* one tenant/RLS transaction.
*/
export async function syncPermissionGroupChatsIfEnabledWithTx(
tx: DbTransactionClient,
input: PermissionGroupChatSyncInput
): Promise<PermissionGroupChatSyncResult> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const groupId = normalizeIdentifier(input.groupId, "groupId");
const actorUserId = normalizeIdentifier(input.actorUserId, "actorUserId");
const requestId = normalizeIdentifier(input.requestId, "requestId");
if (!(await tenantHasChatModuleForSystemTx(tx, tenantId))) {
return { changedChatIds: [], addedUserIds: [], removedUserIds: [] };
}
const sources = await tx.teamChatGroupSource.findMany({
where: withTenantScope(tenantId, {
groupId,
syncEnabled: true,
chat: { kind: "group" as const, archivedAt: null },
}),
select: { chatId: true },
orderBy: { chatId: "asc" },
});
const chatIds = normalizeIdentifiers(
sources.map((source) => source.chatId),
"chatId"
);
const changedChatIds: string[] = [];
const addedUserIds = new Set<string>();
const removedUserIds = new Set<string>();
for (const chatId of chatIds) {
const result = await syncPermissionGroupChatWithTx(tx, { tenantId, chatId, actorUserId, requestId });
if (!result.changed) continue;
changedChatIds.push(chatId);
result.addedUserIds.forEach((userId) => addedUserIds.add(userId));
result.removedUserIds.forEach((userId) => removedUserIds.add(userId));
}
return {
changedChatIds,
addedUserIds: [...addedUserIds].sort(),
removedUserIds: [...removedUserIds].sort(),
};
}
async function syncPermissionGroupChatWithTx(
tx: DbTransactionClient,
input: Readonly<{ tenantId: string; chatId: string; actorUserId: string; requestId: string }>
): Promise<Readonly<{ changed: boolean; addedUserIds: readonly string[]; removedUserIds: readonly string[] }>> {
await lockChatMembershipWithTx(tx, input.tenantId, input.chatId);
const channel = await loadGroupManagedChannel(tx, input.tenantId, input.chatId);
if (!channel) return { changed: false, addedUserIds: [], removedUserIds: [] };
const groupMembers = await resolvePermissionGroupMembersWithTx(
tx,
input.tenantId,
channel.groupSources.map((source) => source.groupId)
);
const desiredUserIds = new Set(groupMembers.userIds);
const membersByUserId = new Map(channel.members.map((member) => [member.userId, member]));
const changedAt = new Date();
const addedUserIds: string[] = [];
const removedUserIds: string[] = [];
let sourceOnlyChange = false;
for (const userId of groupMembers.userIds) {
const member = membersByUserId.get(userId);
if (!member) {
await tx.teamChatMember.create({
data: withTenantScope(input.tenantId, {
chatId: channel.id,
userId,
joinedAt: changedAt,
joinedViaUserId: input.actorUserId,
roleInChat: "member",
notificationPref: channel.notificationDefault,
isProjectManaged: false,
isManualMember: false,
isGroupManaged: true,
manualRoleInChat: null,
projectRoleInChat: null,
writeRevokedAt: null,
leftAt: null,
}),
select: { id: true },
});
addedUserIds.push(userId);
continue;
}
if (member.groupSyncOptOutAt !== null) {
if (!member.isGroupManaged) {
const updated = await tx.teamChatMember.updateMany({
where: withTenantScope(input.tenantId, { id: member.id, chatId: channel.id, userId }),
data: { isGroupManaged: true },
});
if (updated.count !== 1) throw new Error("Group-managed chat membership changed concurrently");
sourceOnlyChange = true;
}
continue;
}
const becomesActive = member.leftAt !== null;
const desiredRole = resolveEffectiveChatMemberRole({
...member,
isGroupManaged: true,
});
if (member.isGroupManaged && !becomesActive && member.writeRevokedAt === null && member.roleInChat === desiredRole) continue;
const updated = await tx.teamChatMember.updateMany({
where: withTenantScope(input.tenantId, { id: member.id, chatId: channel.id, userId }),
data: {
isGroupManaged: true,
roleInChat: desiredRole,
writeRevokedAt: null,
leftAt: null,
...(becomesActive ? { joinedAt: changedAt, joinedViaUserId: input.actorUserId } : {}),
},
});
if (updated.count !== 1) throw new Error("Group-managed chat membership changed concurrently");
if (becomesActive) addedUserIds.push(userId);
else sourceOnlyChange = true;
}
for (const member of channel.members) {
if (!member.isGroupManaged || desiredUserIds.has(member.userId)) continue;
const remainingSources = {
...member,
isGroupManaged: false,
};
const remainsActive = hasActiveChatMembershipSource(remainingSources);
const desiredRole = resolveEffectiveChatMemberRole(remainingSources);
const updated = await tx.teamChatMember.updateMany({
where: withTenantScope(input.tenantId, { id: member.id, chatId: channel.id, userId: member.userId }),
data: {
isGroupManaged: false,
roleInChat: desiredRole,
...(remainsActive ? { writeRevokedAt: null, leftAt: null } : { leftAt: changedAt }),
},
});
if (updated.count !== 1) throw new Error("Group-managed chat membership changed concurrently");
if (remainsActive || member.leftAt !== null) sourceOnlyChange = true;
else removedUserIds.push(member.userId);
}
if (addedUserIds.length > 0 || removedUserIds.length > 0) {
await lockChatEventStream(tx, input.tenantId, channel.id);
const labels = await loadTenantUserLabels(tx, input.tenantId, [...addedUserIds, ...removedUserIds]);
for (const userId of addedUserIds.sort()) {
await appendGroupSyncEvent(tx, input, channel, userId, "added", changedAt);
await writeGroupSyncMemberSystemMessage(tx, input, channel.id, userId, labels.get(userId), "added");
}
for (const userId of removedUserIds.sort()) {
await appendGroupSyncEvent(tx, input, channel, userId, "removed", changedAt);
await writeGroupSyncMemberSystemMessage(tx, input, channel.id, userId, labels.get(userId), "removed");
}
}
const changed = sourceOnlyChange || addedUserIds.length > 0 || removedUserIds.length > 0;
if (changed) {
await recordGroupSync(tx, input, channel, groupMembers.groupIds, addedUserIds, removedUserIds);
}
return { changed, addedUserIds, removedUserIds };
}
async function loadGroupManagedChannel(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<GroupManagedChannel | null> {
return tx.teamChat.findFirst({
where: withTenantScope(tenantId, { id: chatId, kind: "group" as const, archivedAt: null }),
select: {
id: true,
eventStreamId: true,
isPrivate: true,
notificationDefault: true,
groupSources: {
where: withTenantScope(tenantId, { syncEnabled: true }),
select: { groupId: true },
orderBy: { groupId: "asc" },
},
members: {
where: withTenantScope(tenantId, {}),
select: {
id: true,
userId: true,
roleInChat: true,
isProjectManaged: true,
isManualMember: true,
isGroupManaged: true,
manualRoleInChat: true,
projectRoleInChat: true,
groupSyncOptOutAt: true,
writeRevokedAt: true,
leftAt: true,
},
orderBy: { userId: "asc" },
},
},
});
}
async function appendGroupSyncEvent(
tx: DbTransactionClient,
input: Readonly<{ tenantId: string; actorUserId: string; requestId: string }>,
channel: Pick<GroupManagedChannel, "id" | "eventStreamId">,
userId: string,
operation: "added" | "removed",
changedAt: Date
): Promise<void> {
const event = await tx.teamChatEvent.create({
data: withTenantScope(input.tenantId, {
chatId: channel.id,
type: toPersistedChatEventType(operation === "added" ? CHAT_EVENT_NAMES.memberAdded : CHAT_EVENT_NAMES.memberRemoved),
actorUserId: input.actorUserId,
entityId: userId,
requestId: groupSyncMemberRequestId(input.requestId, userId, operation),
data: (operation === "added"
? { userId, roleInChat: "member", joinedAt: changedAt.toISOString() }
: { userId, leftAt: changedAt.toISOString() }) as Prisma.InputJsonValue,
}),
select: PERSISTED_EVENT_SELECT,
});
await publishPersistedGroupSyncEventWakeup(tx, channel.eventStreamId, event);
}
async function loadTenantUserLabels(
tx: DbTransactionClient,
tenantId: string,
userIds: readonly string[]
): Promise<ReadonlyMap<string, string>> {
const normalizedUserIds = normalizeIdentifiers(userIds, "userId");
const memberships = await tx.tenantUser.findMany({
where: withTenantScope(tenantId, { userId: { in: normalizedUserIds } }),
select: {
userId: true,
user: { select: { firstName: true, lastName: true, email: true } },
},
});
return new Map(
memberships.map((membership) => [membership.userId, chatUserDisplayName(membership.user)] as const)
);
}
function chatUserDisplayName(user: { firstName: string | null; lastName: string | null; email: string }): string {
return (
[user.firstName, user.lastName]
.map((part) => part?.trim())
.filter((part): part is string => Boolean(part))
.join(" ") || user.email
);
}
async function writeGroupSyncMemberSystemMessage(
tx: DbTransactionClient,
input: Readonly<{ tenantId: string; actorUserId: string; requestId: string }>,
chatId: string,
userId: string,
memberName: string | undefined,
operation: "added" | "removed"
): Promise<void> {
const chatKey = stableEventKeyPart(chatId);
const userKey = stableEventKeyPart(userId);
const transitionKey = stableEventKeyPart(input.requestId);
const result = await writeChatSystemMessageWithTx(tx, {
tenantId: input.tenantId,
chatId,
systemEventKey: `group-sync:${chatKey}:member:${userKey}:${operation}:${transitionKey}`,
requestId: `chat-group-sync:${chatKey}:member-${operation}:${userKey}:${transitionKey}`,
kind: operation === "added" ? "member_added" : "member_removed",
metadata: {
memberUserId: userId,
...(memberName ? { memberName } : {}),
source: "permission_group_sync",
},
actorUserId: input.actorUserId,
});
if (!result.replayed) {
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event: result.event });
}
}
async function publishPersistedGroupSyncEventWakeup(
tx: DbTransactionClient,
eventStreamId: string,
row: PersistedGroupSyncEvent
): Promise<void> {
const event = validateChatServerEvent({
event: toChatPersistentEventName(row.type),
cursor: `${eventStreamId}:${row.sequence.toString()}`,
requestId: row.requestId,
tenantId: row.tenantId,
chatId: row.chatId,
occurredAt: row.occurredAt.toISOString(),
data: row.data,
});
if (!isPersistentChatEvent(event)) throw new Error("Permission-group sync produced an ephemeral durable event");
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event });
}
function groupSyncMemberRequestId(requestId: string, userId: string, operation: "added" | "removed"): string {
return `${requestId.slice(0, 430)}:${operation}:${stableEventKeyPart(userId)}`;
}
function stableEventKeyPart(value: string): string {
return createHash("sha256").update(value).digest("hex").slice(0, 24);
}
async function recordGroupSync(
tx: DbTransactionClient,
input: Readonly<{ tenantId: string; actorUserId: string; requestId: string }>,
channel: GroupManagedChannel,
groupIds: readonly string[],
addedUserIds: readonly string[],
removedUserIds: readonly string[]
): Promise<void> {
const metadata: Prisma.InputJsonObject = {
groupIds: [...groupIds],
addedUserIds: [...addedUserIds],
removedUserIds: [...removedUserIds],
};
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId: input.tenantId,
actorId: input.actorUserId,
actorType: "user",
action: "chat.group.permission_source_synced",
targetType: "TeamChat",
targetId: channel.id,
requestId: input.requestId,
sourceModule: "chat",
dataSensitivity: "internal",
metadata,
summaryText: "Eine Berechtigungsgruppe wurde mit einem Team-Chat synchronisiert.",
});
await logActivity(
{
tenantId: input.tenantId,
actorUserId: input.actorUserId,
actorKind: "user",
activityType: "audit_event",
subjectType: "tenant",
subjectId: input.tenantId,
summaryText: "activity.runtime.chat.permissionGroupSynced",
metadata: { sourceModule: "chat", lifecycleAction: "permission_group_synced", visibility: channel.isPrivate ? "private" : "public" },
},
{ client: tx }
);
}
async function lockChatEventStream(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<void> {
const lockKey = `chat-event:${tenantId}:${chatId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${CHAT_EVENT_LOCK_SALT}))`;
}
function normalizeIdentifiers(values: readonly string[], label: string): string[] {
return [...new Set(values.map((value) => normalizeIdentifier(value, label)))].sort();
}
function normalizeIdentifier(value: string, label: string): string {
if (typeof value !== "string") throw new Error(`${label} must be a string`);
const normalized = value.trim();
if (!normalized || normalized.length > 500 || normalized.includes("\0")) throw new Error(`${label} is invalid`);
return normalized;
}
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import * as chat from "./index.js";
describe("chat browser boundary", () => {
it("exposes contracts without leaking the server repository", () => {
expect(chat.CHAT_PERMISSIONS.write).toBe("chat.write");
expect(chat.chatErrors.invalidInput).toMatchObject({ status: 400, i18nKey: "chat.errors.invalidInput" });
expect(chat.chatErrors.integrityFailure).toMatchObject({ status: 500, i18nKey: "chat.errors.integrityFailure" });
expect(chat.toPersistedChatEventType).toBeTypeOf("function");
expect(chat).not.toHaveProperty("issueChatGatewayToken");
expect(chat).not.toHaveProperty("verifyChatGatewayToken");
expect(chat).not.toHaveProperty("sendTopLevelChatMessage");
expect(chat).not.toHaveProperty("getWriteDbClient");
});
});
@@ -0,0 +1,6 @@
// Browser-safe chat contracts. Server consumers must import the explicit
// `@hivegrid/chat/repository.server` boundary for persistence operations.
export * from "./event-type-mapping.js";
export * from "./errors.js";
export * from "./permissions.js";
export type * from "./types.js";
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,143 @@
// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
createPrismaChatLinkPreviewStore,
extractChatLinkPreviewPlaceholders,
hashChatLinkPreviewBody,
type ChatLinkPreviewJob,
} from "./link-preview.server.js";
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_A = "chat_preview_rls_tenant_a";
const TENANT_B = "chat_preview_rls_tenant_b";
const USER_A = "chat_preview_rls_user_a";
const USER_B = "chat_preview_rls_user_b";
const CHAT_A = "chat_preview_rls_chat_a";
const CHAT_B = "chat_preview_rls_chat_b";
const MESSAGE_A = "chat_preview_rls_message_a";
const MESSAGE_B = "chat_preview_rls_message_b";
const BODY_A = "A https://docs.example.test/a";
const BODY_B = "B https://docs.example.test/b";
describeIfDatabase("chat link previews with the restricted app role", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
const store = createPrismaChatLinkPreviewStore();
beforeAll(async () => {
await cleanup(admin);
await admin.user.createMany({
data: [
{ id: USER_A, email: "chat-preview-rls-a@example.test", firstName: "Preview", lastName: "A", active: true },
{ id: USER_B, email: "chat-preview-rls-b@example.test", firstName: "Preview", lastName: "B", active: true },
],
});
await admin.tenant.createMany({
data: [
{ id: TENANT_A, slug: TENANT_A, name: "Chat preview A", active: true },
{ id: TENANT_B, slug: TENANT_B, name: "Chat preview B", active: true },
],
});
await admin.tenantUser.createMany({
data: [
{ id: "chat_preview_rls_membership_a", tenantId: TENANT_A, userId: USER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_preview_rls_membership_b", tenantId: TENANT_B, userId: USER_B, type: 0, joined: 1, status: 2 },
],
});
await admin.teamChat.createMany({
data: [
{ id: CHAT_A, tenantId: TENANT_A, createdByUserId: USER_A, kind: "group", name: "A", eventStreamId: "chat_preview_rls_stream_a" },
{ id: CHAT_B, tenantId: TENANT_B, createdByUserId: USER_B, kind: "group", name: "B", eventStreamId: "chat_preview_rls_stream_b" },
],
});
await admin.teamChatMessage.createMany({
data: [
{
id: MESSAGE_A,
tenantId: TENANT_A,
chatId: CHAT_A,
authorUserId: USER_A,
clientMessageId: "chat-preview-rls-client-a",
body: BODY_A,
linkPreviews: extractChatLinkPreviewPlaceholders(BODY_A),
},
{
id: MESSAGE_B,
tenantId: TENANT_B,
chatId: CHAT_B,
authorUserId: USER_B,
clientMessageId: "chat-preview-rls-client-b",
body: BODY_B,
linkPreviews: extractChatLinkPreviewPlaceholders(BODY_B),
},
],
});
});
afterAll(async () => {
await cleanup(admin);
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("loads and enriches only the message inside the bound tenant", async () => {
const sameTenantJob = job(TENANT_A, CHAT_A, MESSAGE_A, BODY_A, "outbox_preview_rls_a");
const crossTenantJob = job(TENANT_A, CHAT_B, MESSAGE_B, BODY_B, "outbox_preview_rls_cross");
await expect(store.loadSource(sameTenantJob)).resolves.toEqual({ body: BODY_A });
await expect(store.loadSource(crossTenantJob)).resolves.toBeNull();
const enriched = [
{
url: "https://docs.example.test/a",
title: "Tenant A docs",
description: "Visible only in A",
imageUrl: null,
siteName: "Example Docs",
},
];
await expect(store.persist({ ...sameTenantJob, updates: [{ urlIndex: 0, preview: enriched[0]! }], retries: [] })).resolves.toBe("updated");
await expect(
store.persist({
...crossTenantJob,
updates: [{ urlIndex: 0, preview: extractChatLinkPreviewPlaceholders(BODY_B)[0]! }],
retries: [],
})
).resolves.toBe("skipped");
await expect(admin.teamChatMessage.findUnique({ where: { id: MESSAGE_A }, select: { linkPreviews: true } })).resolves.toEqual({ linkPreviews: enriched });
await expect(admin.teamChatMessage.findUnique({ where: { id: MESSAGE_B }, select: { linkPreviews: true } })).resolves.toEqual({
linkPreviews: extractChatLinkPreviewPlaceholders(BODY_B),
});
await expect(admin.teamChatEvent.count({ where: { tenantId: TENANT_A, chatId: CHAT_A, entityId: MESSAGE_A, type: "link_preview_ready" } })).resolves.toBe(
1
);
await expect(admin.teamChatEvent.count({ where: { tenantId: TENANT_B, chatId: CHAT_B, entityId: MESSAGE_B } })).resolves.toBe(0);
await admin.teamChat.update({ where: { id: CHAT_A }, data: { archivedAt: new Date("2026-07-16T12:00:00.000Z") } });
await expect(store.loadSource(sameTenantJob)).resolves.toBeNull();
await expect(store.persist({ ...sameTenantJob, updates: [{ urlIndex: 0, preview: enriched[0]! }], retries: [] })).resolves.toBe("skipped");
});
});
function job(tenantId: string, chatId: string, messageId: string, body: string, outboxEventId: string): ChatLinkPreviewJob {
return {
outboxEventId,
tenantId,
eventType: "chat.linkpreview.requested",
payload: { chatId, messageId, bodyHash: hashChatLinkPreviewBody(body) },
};
}
async function cleanup(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.outboxEvent.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.teamChatEvent.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.teamChatMessage.deleteMany({ where: { id: { in: [MESSAGE_A, MESSAGE_B] } } });
await admin.teamChat.deleteMany({ where: { id: { in: [CHAT_A, CHAT_B] } } });
await admin.tenantUser.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.tenant.deleteMany({ where: { id: { in: [TENANT_A, TENANT_B] } } });
await admin.user.deleteMany({ where: { id: { in: [USER_A, USER_B] } } });
}
@@ -0,0 +1,551 @@
import { CHAT_EVENT_NAMES } from "@hivegrid/realtime";
import { fetchOutboundHttpWithRedirects } from "@hivegrid/foundation/outbound-http";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
client: { $transaction: vi.fn() },
tx: {
$executeRaw: vi.fn(),
$queryRaw: vi.fn(),
tenant: { findFirst: vi.fn() },
teamChatMessage: { findFirst: vi.fn(), update: vi.fn() },
teamChatEvent: { create: vi.fn() },
outboxEvent: { create: vi.fn(), findUnique: vi.fn() },
},
runWithRlsContext: vi.fn(),
moduleEnabled: vi.fn(),
publishWakeup: vi.fn(),
}));
vi.mock("@hivegrid/db/client.server", () => ({ getWriteDbClient: () => mocks.client }));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: (context: unknown, operation: () => unknown) => mocks.runWithRlsContext(context, operation),
}));
vi.mock("./module-access.server.js", () => ({
tenantHasChatModuleForSystemTx: (...args: unknown[]) => mocks.moduleEnabled(...args),
}));
vi.mock("./realtime-wakeup.server.js", () => ({
publishChatPersistentRealtimeWakeup: (...args: unknown[]) => mocks.publishWakeup(...args),
}));
import {
CHAT_LINK_PREVIEW_HTML_LIMIT_BYTES,
CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE,
CHAT_LINK_PREVIEW_USER_AGENT,
createPrismaChatLinkPreviewStore,
extractChatLinkPreviewPlaceholders,
fetchChatLinkPreview,
hashChatLinkPreviewBody,
parseChatLinkPreviewJob,
publishChatLinkPreviewRequest,
runChatLinkPreviewJob,
type ChatLinkPreviewJob,
} from "./link-preview.server.js";
const BODY = "Siehe https://docs.example.test/article";
const NOW = new Date("2026-07-16T10:00:00.000Z");
beforeEach(() => {
vi.clearAllMocks();
});
function job(overrides: Partial<ChatLinkPreviewJob> = {}): ChatLinkPreviewJob {
return {
outboxEventId: "outbox_1",
tenantId: "tenant_1",
eventType: CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE,
payload: { chatId: "chat_1", messageId: "message_1", bodyHash: hashChatLinkPreviewBody(BODY) },
...overrides,
};
}
describe("chat link preview URL intake", () => {
it("extracts at most three stable public cards and removes punctuation", () => {
expect(
extractChatLinkPreviewPlaceholders("https://one.example/a, https://two.example/b https://one.example/a https://three.example/c https://four.example/d")
).toEqual([
{ url: "https://one.example/a", title: null, description: null, imageUrl: null, siteName: "one.example" },
{ url: "https://two.example/b", title: null, description: null, imageUrl: null, siteName: "two.example" },
{ url: "https://three.example/c", title: null, description: null, imageUrl: null, siteName: "three.example" },
]);
});
it.each([
"http://localhost/admin",
"http://127.0.0.1/metadata",
"http://10.0.0.1/internal",
"http://169.254.169.254/latest",
"http://93.184.216.34/public",
"https://user:secret@example.test/",
"https://example.test:8443/",
"https://service.internal/",
])("rejects a blocked or credential-bearing target: %s", (url) => {
expect(extractChatLinkPreviewPlaceholders(url)).toEqual([]);
});
it("publishes only identifiers and a body hash, with no URL in the dispatch key", async () => {
mocks.tx.outboxEvent.create.mockImplementation(async ({ data }) => ({
id: "outbox_1",
createdAt: NOW,
processedAt: null,
retries: 0,
lastError: null,
scheduledAt: NOW,
priority: 0,
lockedUntil: null,
status: "PENDING",
...data,
}));
await publishChatLinkPreviewRequest(mocks.tx as never, {
tenantId: "tenant_1",
chatId: "chat_1",
messageId: "message_1",
requestId: "request_1",
body: "Read https://docs.example.test/private?token=do-not-log",
});
const data = mocks.tx.outboxEvent.create.mock.calls[0]?.[0].data;
expect(data).toMatchObject({
tenantId: "tenant_1",
eventType: CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE,
payload: { chatId: "chat_1", messageId: "message_1", bodyHash: expect.stringMatching(/^[a-f0-9]{64}$/u) },
dispatchKey: expect.stringMatching(/^chat-link-preview:[a-f0-9]{64}$/u),
});
expect(JSON.stringify(data)).not.toContain("do-not-log");
expect(JSON.stringify(data)).not.toContain("docs.example.test");
});
it("does not enqueue a job when the message has no eligible URL", async () => {
await expect(
publishChatLinkPreviewRequest(mocks.tx as never, {
tenantId: "tenant_1",
chatId: "chat_1",
messageId: "message_1",
requestId: "request_1",
body: "No external link",
})
).resolves.toBeNull();
expect(mocks.tx.outboxEvent.create).not.toHaveBeenCalled();
});
});
describe("chat link preview metadata fetch", () => {
it("extracts bounded OG and HTML metadata with a clear, secret-free request", async () => {
const html = `<!doctype html><html><head>
<title>Fallback title</title>
<meta property="og:title" content="Safe &amp; useful">
<meta property="og:description" content="A short description">
<meta property="og:site_name" content="Example Docs">
<meta property="og:image" content="/preview.png">
</head></html>`;
const outboundFetch = vi.fn(async (_url: string, init: RequestInit) => {
expect(new Headers(init.headers).get("user-agent")).toBe(CHAT_LINK_PREVIEW_USER_AGENT);
expect(new Headers(init.headers).has("authorization")).toBe(false);
expect(new Headers(init.headers).has("cookie")).toBe(false);
return new Response(html, { status: 200, headers: { "content-type": "text/html; charset=utf-8" } });
});
const result = await fetchChatLinkPreview("https://docs.example.test/article", { outboundFetch });
expect(result).toEqual({
status: "ready",
preview: {
url: "https://docs.example.test/article",
title: "Safe & useful",
description: "A short description",
imageUrl: "https://docs.example.test/preview.png",
siteName: "Example Docs",
},
});
expect(outboundFetch).toHaveBeenCalledWith(
"https://docs.example.test/article",
expect.objectContaining({ method: "GET" }),
expect.objectContaining({ timeoutMs: 5_000, redirectLimit: 3 })
);
});
it("removes Unicode format and bidi controls from remote metadata", async () => {
const outboundFetch = vi.fn(
async () =>
new Response('<meta property="og:title" content="Invoice \u202Egpj.exe\u202C"><meta property="og:description" content="Safe\u2066hidden\u2069 text">', {
status: 200,
headers: { "content-type": "text/html" },
})
);
await expect(fetchChatLinkPreview("https://docs.example.test/article", { outboundFetch })).resolves.toMatchObject({
status: "ready",
preview: {
title: "Invoice gpj.exe",
description: "Safe hidden text",
},
});
});
it("discovers an SSRF-guarded oEmbed endpoint and prefers its metadata", async () => {
const outboundFetch = vi
.fn()
.mockResolvedValueOnce(
new Response(
'<html><head><link rel="alternate" type="application/json+oembed" href="https://embed.example.test/oembed?id=1"><meta property="og:title" content="OG title"></head></html>',
{ status: 200, headers: { "content-type": "text/html" } }
)
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ title: "oEmbed title", author_name: "Ada", provider_name: "Video EU" }), {
status: 200,
headers: { "content-type": "application/json+oembed" },
})
);
const result = await fetchChatLinkPreview("https://video.example.test/watch/1", { outboundFetch });
expect(result).toMatchObject({
status: "ready",
preview: { title: "oEmbed title", description: "Ada", siteName: "Video EU" },
});
expect(outboundFetch.mock.calls.map((call) => call[0])).toEqual(["https://video.example.test/watch/1", "https://embed.example.test/oembed?id=1"]);
});
it("keeps a safe URL card for terminal content and bounds response size", async () => {
const outboundFetch = vi.fn(
async () =>
new Response("binary", {
status: 200,
headers: { "content-type": "application/octet-stream", "content-length": String(CHAT_LINK_PREVIEW_HTML_LIMIT_BYTES + 1) },
})
);
await expect(fetchChatLinkPreview("https://files.example.test/archive", { outboundFetch })).resolves.toMatchObject({
status: "terminal",
reason: "response_too_large",
preview: { url: "https://files.example.test/archive", title: null },
});
});
it("classifies server failures as transient for bounded BullMQ retry", async () => {
const outboundFetch = vi.fn(async () => new Response("down", { status: 503, headers: { "content-type": "text/html" } }));
await expect(fetchChatLinkPreview("https://docs.example.test/article", { outboundFetch })).resolves.toMatchObject({
status: "transient",
reason: "http_503",
});
});
it("rejects a redirect whose final response URL is an IP literal", async () => {
const response = new Response("<title>Internal</title>", { status: 200, headers: { "content-type": "text/html" } });
Object.defineProperty(response, "url", { value: "http://93.184.216.34/metadata" });
const outboundFetch = vi.fn(async () => response);
await expect(fetchChatLinkPreview("https://docs.example.test/article", { outboundFetch })).resolves.toMatchObject({
status: "terminal",
reason: "blocked_redirect_url",
preview: { url: "https://docs.example.test/article", title: null },
});
});
it("applies the same final-URL policy to oEmbed redirects", async () => {
const oEmbedResponse = new Response(JSON.stringify({ title: "Untrusted" }), {
status: 200,
headers: { "content-type": "application/json+oembed" },
});
Object.defineProperty(oEmbedResponse, "url", { value: "http://93.184.216.34/oembed" });
const outboundFetch = vi
.fn()
.mockResolvedValueOnce(
new Response('<link rel="alternate" type="application/json+oembed" href="https://embed.example.test/oembed">', {
status: 200,
headers: { "content-type": "text/html" },
})
)
.mockResolvedValueOnce(oEmbedResponse);
await expect(fetchChatLinkPreview("https://video.example.test/watch/1", { outboundFetch })).resolves.toMatchObject({
status: "terminal",
reason: "blocked_oembed_redirect_url",
preview: { url: "https://video.example.test/watch/1", title: null },
});
});
it("rejects a non-default port on a redirect before the second request", async () => {
const fetchImpl = vi.fn(async () => new Response(null, { status: 302, headers: { location: "https://redirect.example.test:8443/private" } }));
await expect(
fetchChatLinkPreview("https://docs.example.test/article", {
outboundFetch: fetchOutboundHttpWithRedirects,
fetchOptions: {
fetchImpl,
addressResolver: async () => ["93.184.216.34"],
// A caller cannot replace the link-specific per-hop policy.
urlValidator: (value) => value,
},
})
).resolves.toMatchObject({ status: "terminal", reason: "blocked_url" });
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
});
describe("chat link preview job and RLS store", () => {
beforeEach(() => {
mocks.runWithRlsContext.mockImplementation((_context, operation: () => unknown) => operation());
mocks.client.$transaction.mockImplementation((operation: (tx: typeof mocks.tx) => unknown) => operation(mocks.tx));
mocks.moduleEnabled.mockResolvedValue(true);
mocks.tx.tenant.findFirst.mockResolvedValue({ id: "tenant_1" });
mocks.tx.teamChatMessage.findFirst.mockResolvedValue({
body: BODY,
linkPreviews: extractChatLinkPreviewPlaceholders(BODY),
chat: { eventStreamId: "stream_1" },
});
mocks.tx.teamChatMessage.update.mockResolvedValue({ id: "message_1" });
mocks.tx.teamChatEvent.create.mockResolvedValue({
sequence: 7n,
occurredAt: NOW,
tenantId: "tenant_1",
chatId: "chat_1",
requestId: "link-preview-event",
data: {
messageId: "message_1",
linkPreviews: [{ url: "https://docs.example.test/article", title: "Docs", description: null, imageUrl: null, siteName: "Example" }],
},
});
mocks.publishWakeup.mockResolvedValue(undefined);
mocks.tx.outboxEvent.create.mockImplementation(async ({ data }) => ({
id: "outbox_retry",
createdAt: NOW,
processedAt: null,
retries: 0,
lastError: null,
scheduledAt: data.scheduledAt ?? NOW,
priority: 0,
lockedUntil: null,
status: "PENDING",
...data,
}));
});
it("parses only the exact tenant-scoped outbox contract", () => {
expect(parseChatLinkPreviewJob(job())).toEqual(job());
expect(() => parseChatLinkPreviewJob({ ...job(), eventType: "chat.realtime.persistent" })).toThrow("event type");
expect(() => parseChatLinkPreviewJob({ ...job(), payload: { ...job().payload, bodyHash: "bad" } })).toThrow("bodyHash");
expect(() => parseChatLinkPreviewJob({ ...job(), payload: { ...job().payload, attempt: 1 } })).toThrow("urlIndex");
});
it("loads only messages whose channel is still active", async () => {
const store = createPrismaChatLinkPreviewStore();
await expect(store.loadSource(job())).resolves.toEqual({ body: BODY });
expect(mocks.tx.teamChatMessage.findFirst).toHaveBeenCalledWith(
expect.objectContaining({ where: expect.objectContaining({ chat: { archivedAt: null } }) })
);
});
it("persists metadata plus one durable ready event and realtime wakeup under tenant RLS", async () => {
const store = createPrismaChatLinkPreviewStore();
const result = await store.persist({
...job(),
updates: [
{
urlIndex: 0,
preview: { url: "https://docs.example.test/article", title: "Docs", description: null, imageUrl: null, siteName: "Example" },
},
],
retries: [],
});
expect(result).toBe("updated");
expect(mocks.runWithRlsContext).toHaveBeenCalledWith({ tenantId: "tenant_1" }, expect.any(Function));
expect(mocks.tx.$executeRaw).toHaveBeenCalledOnce();
expect(mocks.tx.teamChatMessage.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ tenantId: "tenant_1", id: "message_1", chatId: "chat_1", deletedAt: null, chat: { archivedAt: null } }),
})
);
expect(mocks.tx.teamChatEvent.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
tenantId: "tenant_1",
chatId: "chat_1",
type: "link_preview_ready",
actorUserId: null,
entityId: "message_1",
}),
})
);
expect(mocks.publishWakeup).toHaveBeenCalledWith(mocks.tx, {
event: expect.objectContaining({ event: CHAT_EVENT_NAMES.linkPreviewReady, cursor: "stream_1:7" }),
});
});
it("rechecks the body hash after fetching and skips a stale edit", async () => {
const store = createPrismaChatLinkPreviewStore();
mocks.tx.teamChatMessage.findFirst.mockResolvedValue({
body: "Edited https://new.example.test/",
linkPreviews: [],
chat: { eventStreamId: "stream_1" },
});
await expect(
store.persist({
...job(),
updates: [{ urlIndex: 0, preview: extractChatLinkPreviewPlaceholders(BODY)[0]! }],
retries: [],
})
).resolves.toBe("skipped");
expect(mocks.tx.teamChatMessage.update).not.toHaveBeenCalled();
expect(mocks.tx.teamChatEvent.create).not.toHaveBeenCalled();
});
it("persists the fallback card and schedules only the transient URL with Retry-After", async () => {
const store = {
loadSource: vi.fn(async () => ({ body: BODY })),
persist: vi.fn(async () => "updated" as const),
};
const outboundFetch = vi.fn(async () => new Response("down", { status: 503, headers: { "content-type": "text/html", "retry-after": "120" } }));
await expect(runChatLinkPreviewJob(job(), { store, outboundFetch, now: () => NOW })).resolves.toEqual({
status: "updated",
messageId: "message_1",
transientFailures: 1,
scheduledRetries: 1,
deferredByBudget: 0,
});
expect(store.persist).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant_1",
updates: [{ urlIndex: 0, preview: extractChatLinkPreviewPlaceholders(BODY)[0] }],
retries: [
expect.objectContaining({
urlIndex: 0,
attempt: 1,
budgetDeferrals: 0,
reason: "transient",
scheduledAt: new Date("2026-07-16T10:02:00.000Z"),
}),
],
})
);
});
it("does not refetch successful URLs when a targeted retry runs", async () => {
const body = "One https://one.example.test/a two https://two.example.test/b";
const targetedJob = job({
payload: {
chatId: "chat_1",
messageId: "message_1",
bodyHash: hashChatLinkPreviewBody(body),
urlIndex: 1,
attempt: 1,
budgetDeferrals: 0,
},
});
const store = {
loadSource: vi.fn(async () => ({ body })),
persist: vi.fn(async () => "updated" as const),
};
const outboundFetch = vi.fn(async () => new Response("<title>Second ready</title>", { status: 200, headers: { "content-type": "text/html" } }));
await expect(runChatLinkPreviewJob(targetedJob, { store, outboundFetch })).resolves.toMatchObject({
status: "updated",
transientFailures: 0,
scheduledRetries: 0,
});
expect(outboundFetch).toHaveBeenCalledTimes(1);
expect(outboundFetch).toHaveBeenCalledWith("https://two.example.test/b", expect.anything(), expect.anything());
expect(store.persist).toHaveBeenCalledWith(
expect.objectContaining({
updates: [expect.objectContaining({ urlIndex: 1, preview: expect.objectContaining({ title: "Second ready" }) })],
retries: [],
})
);
});
it("defers only over-budget URLs and does not start their network request", async () => {
const body = "One https://one.example.test/a two https://two.example.test/b";
const initialJob = job({
payload: { chatId: "chat_1", messageId: "message_1", bodyHash: hashChatLinkPreviewBody(body) },
});
const store = {
loadSource: vi.fn(async () => ({ body })),
persist: vi.fn(async () => "updated" as const),
};
const tenantBudget = {
consume: vi.fn().mockResolvedValueOnce({ allowed: true, retryAfterMs: 0 }).mockResolvedValueOnce({ allowed: false, retryAfterMs: 30_000 }),
};
const outboundFetch = vi.fn(async () => new Response("<title>First ready</title>", { status: 200, headers: { "content-type": "text/html" } }));
await expect(runChatLinkPreviewJob(initialJob, { store, outboundFetch, tenantBudget, now: () => NOW })).resolves.toEqual({
status: "updated",
messageId: "message_1",
transientFailures: 0,
scheduledRetries: 1,
deferredByBudget: 1,
});
expect(tenantBudget.consume).toHaveBeenCalledTimes(2);
expect(outboundFetch).toHaveBeenCalledTimes(1);
expect(store.persist).toHaveBeenCalledWith(
expect.objectContaining({
updates: [expect.objectContaining({ urlIndex: 0 })],
retries: [
expect.objectContaining({
urlIndex: 1,
attempt: 0,
budgetDeferrals: 1,
reason: "tenant_budget",
scheduledAt: new Date("2026-07-16T10:00:30.000Z"),
}),
],
})
);
});
it("persists a URL-free targeted retry through the transactional outbox", async () => {
const store = createPrismaChatLinkPreviewStore();
const result = await store.persist({
...job(),
updates: [],
retries: [
{
urlIndex: 0,
attempt: 1,
budgetDeferrals: 0,
scheduledAt: new Date("2026-07-16T10:02:00.000Z"),
reason: "transient",
},
],
});
expect(result).toBe("unchanged");
const retryData = mocks.tx.outboxEvent.create.mock.calls[0]?.[0].data;
expect(retryData).toMatchObject({
tenantId: "tenant_1",
eventType: CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE,
payload: {
chatId: "chat_1",
messageId: "message_1",
bodyHash: hashChatLinkPreviewBody(BODY),
urlIndex: 0,
attempt: 1,
budgetDeferrals: 0,
},
scheduledAt: new Date("2026-07-16T10:02:00.000Z"),
dispatchKey: expect.stringMatching(/^chat-link-preview-retry:[a-f0-9]{64}$/u),
});
expect(JSON.stringify(retryData)).not.toContain("docs.example.test");
expect(mocks.tx.teamChatEvent.create).not.toHaveBeenCalled();
});
it("does not perform any network request for a stale or deleted source", async () => {
const outboundFetch = vi.fn();
const store = { loadSource: vi.fn(async () => null), persist: vi.fn() };
await expect(runChatLinkPreviewJob(job(), { store, outboundFetch })).resolves.toEqual({
status: "skipped",
messageId: "message_1",
transientFailures: 0,
scheduledRetries: 0,
deferredByBudget: 0,
});
expect(outboundFetch).not.toHaveBeenCalled();
expect(store.persist).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,868 @@
import { createHash } from "node:crypto";
import { isIP } from "node:net";
import { getWriteDbClient } from "@hivegrid/db/client.server";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import {
fetchOutboundHttpWithRedirects,
OutboundHttpUrlValidationError,
readLimitedResponseText,
validateOutboundHttpUrl,
type OutboundHttpFetchOptions,
} from "@hivegrid/foundation/outbound-http";
import { CHAT_EVENT_NAMES, CHAT_MESSAGE_MAX_LINK_PREVIEWS, validateChatServerEvent, type ChatLinkPreview, type ChatPersistentEvent } from "@hivegrid/realtime";
import { toPersistedChatEventType } from "./event-type-mapping.js";
import { tenantHasChatModuleForSystemTx } from "./module-access.server.js";
import { publishChatPersistentRealtimeWakeup } from "./realtime-wakeup.server.js";
export const CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE = "chat.linkpreview.requested" as const;
export const CHAT_LINK_PREVIEW_OUTBOX_QUEUE = "outbox.chat-link-preview" as const;
export const CHAT_LINK_PREVIEW_FETCH_TIMEOUT_MS = 5_000;
export const CHAT_LINK_PREVIEW_REDIRECT_LIMIT = 3;
export const CHAT_LINK_PREVIEW_HTML_LIMIT_BYTES = 256 * 1024;
export const CHAT_LINK_PREVIEW_OEMBED_LIMIT_BYTES = 64 * 1024;
export const CHAT_LINK_PREVIEW_USER_AGENT = "TeamChat-LinkPreview/1.0";
export const CHAT_LINK_PREVIEW_MAX_HTTP_RETRIES = 4;
export const CHAT_LINK_PREVIEW_MAX_BUDGET_DEFERRALS = 20;
const CHAT_EVENT_LOCK_SALT = 15_015;
const MAX_IDENTIFIER_LENGTH = 500;
const MAX_URL_LENGTH = 2_048;
const MAX_TITLE_LENGTH = 300;
const MAX_DESCRIPTION_LENGTH = 1_000;
const MAX_SITE_NAME_LENGTH = 300;
const MAX_HTML_TAG_LENGTH = 4_096;
const TRANSIENT_HTTP_STATUSES = new Set([408, 425, 429]);
const RETRY_DELAY_MIN_MS = 1_000;
const RETRY_DELAY_DEFAULT_MS = 15_000;
const RETRY_DELAY_MAX_MS = 15 * 60_000;
const BUDGET_FAILURE_RETRY_MS = 60_000;
export type ChatLinkPreviewRequestedPayload = Readonly<{
chatId: string;
messageId: string;
bodyHash: string;
/** Present only on a targeted retry. Initial jobs process every URL once. */
urlIndex?: number;
/** Number of completed transient HTTP retries for this URL. */
attempt?: number;
/** Number of tenant-budget deferrals for this URL. */
budgetDeferrals?: number;
}>;
export type ChatLinkPreviewJob = Readonly<{
outboxEventId: string;
tenantId: string;
eventType: typeof CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE;
payload: ChatLinkPreviewRequestedPayload;
}>;
export type ChatLinkPreviewFetchOutcome =
| { readonly status: "ready"; readonly preview: ChatLinkPreview }
| { readonly status: "terminal"; readonly preview: ChatLinkPreview; readonly reason: string }
| { readonly status: "transient"; readonly preview: ChatLinkPreview; readonly reason: string; readonly retryAfterMs?: number };
export type ChatLinkPreviewJobResult = Readonly<{
status: "updated" | "unchanged" | "skipped";
messageId: string;
transientFailures: number;
scheduledRetries: number;
deferredByBudget: number;
}>;
export interface ChatLinkPreviewLogger {
info?: (record: Record<string, unknown>, message?: string) => void;
warn?: (record: Record<string, unknown>, message?: string) => void;
}
export interface ChatLinkPreviewStore {
loadSource(input: ChatLinkPreviewJob): Promise<{ body: string } | null>;
persist(
input: ChatLinkPreviewJob & {
updates: readonly ChatLinkPreviewUpdate[];
retries: readonly ChatLinkPreviewRetry[];
}
): Promise<"updated" | "unchanged" | "skipped">;
}
export type ChatLinkPreviewUpdate = Readonly<{ urlIndex: number; preview: ChatLinkPreview }>;
export type ChatLinkPreviewRetry = Readonly<{
urlIndex: number;
attempt: number;
budgetDeferrals: number;
scheduledAt: Date;
reason: "transient" | "tenant_budget";
}>;
export interface ChatLinkPreviewTenantBudget {
consume(tenantId: string): Promise<{ allowed: boolean; retryAfterMs: number }>;
}
export interface ChatLinkPreviewFetchDependencies {
readonly outboundFetch?: typeof fetchOutboundHttpWithRedirects;
readonly fetchOptions?: OutboundHttpFetchOptions;
readonly now?: () => Date;
}
export interface ChatLinkPreviewJobDependencies extends ChatLinkPreviewFetchDependencies {
readonly store?: ChatLinkPreviewStore;
readonly logger?: ChatLinkPreviewLogger;
readonly tenantBudget?: ChatLinkPreviewTenantBudget;
}
export async function publishChatLinkPreviewRequest(
tx: OutboxPublisherTransaction,
input: Readonly<{ tenantId: string; chatId: string; messageId: string; requestId: string; body: string }>
) {
const placeholders = extractChatLinkPreviewPlaceholders(input.body);
if (placeholders.length === 0) return null;
const bodyHash = hashChatLinkPreviewBody(input.body);
return publishOutboxEvent(tx, {
tenantId: normalizeIdentifier(input.tenantId, "tenantId"),
type: CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE,
payload: {
chatId: normalizeIdentifier(input.chatId, "chatId"),
messageId: normalizeIdentifier(input.messageId, "messageId"),
bodyHash,
},
dispatchKey: buildChatLinkPreviewDispatchKey(input, bodyHash),
});
}
export function extractChatLinkPreviewPlaceholders(body: string): ChatLinkPreview[] {
if (typeof body !== "string" || body.length === 0) return [];
const seen = new Set<string>();
const previews: ChatLinkPreview[] = [];
for (const rawMatch of body.match(/https?:\/\/[^\s<>{}]+/giu) ?? []) {
const candidate = rawMatch.replace(/[),.!?;:'"\]]+$/u, "");
const normalized = normalizeLinkPreviewTarget(candidate);
if (!normalized || seen.has(normalized)) continue;
seen.add(normalized);
const url = new URL(normalized);
previews.push({ url: normalized, title: null, description: null, imageUrl: null, siteName: url.hostname.toLowerCase() });
if (previews.length === CHAT_MESSAGE_MAX_LINK_PREVIEWS) break;
}
return previews;
}
export function hashChatLinkPreviewBody(body: string): string {
return createHash("sha256").update(body, "utf8").digest("hex");
}
export function parseChatLinkPreviewJob(data: unknown): ChatLinkPreviewJob {
const envelope = requireRecord(data, "link preview job envelope");
if (envelope.eventType !== CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE) {
throw new Error("Link preview job event type is invalid.");
}
const payload = requireRecord(envelope.payload, "link preview job payload");
const bodyHash = requireString(payload.bodyHash, "bodyHash");
if (!/^[a-f0-9]{64}$/u.test(bodyHash)) throw new Error("Link preview job bodyHash is invalid.");
const urlIndex = optionalBoundedInteger(payload.urlIndex, "urlIndex", CHAT_MESSAGE_MAX_LINK_PREVIEWS - 1);
const attempt = optionalBoundedInteger(payload.attempt, "attempt", CHAT_LINK_PREVIEW_MAX_HTTP_RETRIES);
const budgetDeferrals = optionalBoundedInteger(payload.budgetDeferrals, "budgetDeferrals", CHAT_LINK_PREVIEW_MAX_BUDGET_DEFERRALS);
if (urlIndex === undefined && (attempt !== undefined || budgetDeferrals !== undefined)) {
throw new Error("Link preview retry counters require a urlIndex.");
}
return {
outboxEventId: normalizeIdentifier(envelope.outboxEventId, "outboxEventId"),
tenantId: normalizeIdentifier(envelope.tenantId, "tenantId"),
eventType: CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE,
payload: {
chatId: normalizeIdentifier(payload.chatId, "chatId"),
messageId: normalizeIdentifier(payload.messageId, "messageId"),
bodyHash,
...(urlIndex !== undefined ? { urlIndex } : {}),
...(attempt !== undefined ? { attempt } : {}),
...(budgetDeferrals !== undefined ? { budgetDeferrals } : {}),
},
};
}
export async function runChatLinkPreviewJob(data: unknown, deps: ChatLinkPreviewJobDependencies = {}): Promise<ChatLinkPreviewJobResult> {
const job = parseChatLinkPreviewJob(data);
const store = deps.store ?? createPrismaChatLinkPreviewStore();
const source = await store.loadSource(job);
if (!source) return skippedJobResult(job.payload.messageId);
const placeholders = extractChatLinkPreviewPlaceholders(source.body);
if (placeholders.length === 0 || hashChatLinkPreviewBody(source.body) !== job.payload.bodyHash) {
return skippedJobResult(job.payload.messageId);
}
const targetIndices = job.payload.urlIndex === undefined ? placeholders.map((_, index) => index) : [job.payload.urlIndex];
if (targetIndices.some((index) => !placeholders[index])) return skippedJobResult(job.payload.messageId);
const now = deps.now ?? (() => new Date());
const results = await Promise.all(
targetIndices.map(async (urlIndex) => {
const placeholder = placeholders[urlIndex]!;
const budget = await consumeTenantBudget(job, deps);
if (!budget.allowed) {
const retry = buildBudgetRetry(job, urlIndex, budget.retryAfterMs, now());
return { urlIndex, retry, deferredByBudget: 1, transientFailure: 0 } as const;
}
const outcome = await fetchChatLinkPreview(placeholder.url, deps);
const retry = outcome.status === "transient" ? buildTransientRetry(job, urlIndex, outcome.retryAfterMs, now()) : null;
return {
urlIndex,
update: { urlIndex, preview: outcome.preview },
retry,
deferredByBudget: 0,
transientFailure: outcome.status === "transient" ? 1 : 0,
} as const;
})
);
const updates: ChatLinkPreviewUpdate[] = [];
const retries: ChatLinkPreviewRetry[] = [];
for (const result of results) {
if ("update" in result && result.update) updates.push(result.update);
if (result.retry) retries.push(result.retry);
}
const status = await store.persist({ ...job, updates, retries });
const transientFailures = results.reduce((total, result) => total + result.transientFailure, 0);
const deferredByBudget = results.reduce((total, result) => total + result.deferredByBudget, 0);
const scheduledRetries = status === "skipped" ? 0 : retries.length;
deps.logger?.info?.(
{
component: "chat-link-preview",
outboxEventId: job.outboxEventId,
tenantId: job.tenantId,
chatId: job.payload.chatId,
messageId: job.payload.messageId,
status,
previewCount: updates.length,
transientFailures,
deferredByBudget,
scheduledRetries,
},
"chat link preview job processed"
);
return { status, messageId: job.payload.messageId, transientFailures, scheduledRetries, deferredByBudget };
}
function skippedJobResult(messageId: string): ChatLinkPreviewJobResult {
return { status: "skipped", messageId, transientFailures: 0, scheduledRetries: 0, deferredByBudget: 0 };
}
async function consumeTenantBudget(job: ChatLinkPreviewJob, deps: ChatLinkPreviewJobDependencies): Promise<{ allowed: boolean; retryAfterMs: number }> {
if (!deps.tenantBudget) return { allowed: true, retryAfterMs: 0 };
try {
const decision = await deps.tenantBudget.consume(job.tenantId);
return {
allowed: decision.allowed,
retryAfterMs: clampRetryDelay(decision.retryAfterMs || BUDGET_FAILURE_RETRY_MS),
};
} catch (error) {
deps.logger?.warn?.(
{
component: "chat-link-preview",
tenantId: job.tenantId,
outboxEventId: job.outboxEventId,
errorName: error instanceof Error ? error.name : "UnknownError",
},
"chat link preview tenant budget unavailable; request deferred"
);
return { allowed: false, retryAfterMs: BUDGET_FAILURE_RETRY_MS };
}
}
function buildTransientRetry(job: ChatLinkPreviewJob, urlIndex: number, retryAfterMs: number | undefined, now: Date): ChatLinkPreviewRetry | null {
const attempt = job.payload.attempt ?? 0;
if (attempt >= CHAT_LINK_PREVIEW_MAX_HTTP_RETRIES) return null;
const delayMs = clampRetryDelay(retryAfterMs ?? RETRY_DELAY_DEFAULT_MS * 2 ** attempt);
return {
urlIndex,
attempt: attempt + 1,
budgetDeferrals: job.payload.budgetDeferrals ?? 0,
scheduledAt: new Date(now.getTime() + delayMs),
reason: "transient",
};
}
function buildBudgetRetry(job: ChatLinkPreviewJob, urlIndex: number, retryAfterMs: number, now: Date): ChatLinkPreviewRetry | null {
const budgetDeferrals = job.payload.budgetDeferrals ?? 0;
if (budgetDeferrals >= CHAT_LINK_PREVIEW_MAX_BUDGET_DEFERRALS) return null;
return {
urlIndex,
attempt: job.payload.attempt ?? 0,
budgetDeferrals: budgetDeferrals + 1,
scheduledAt: new Date(now.getTime() + clampRetryDelay(retryAfterMs)),
reason: "tenant_budget",
};
}
function clampRetryDelay(value: number): number {
if (!Number.isFinite(value)) return RETRY_DELAY_MAX_MS;
return Math.max(RETRY_DELAY_MIN_MS, Math.min(RETRY_DELAY_MAX_MS, Math.ceil(value)));
}
export async function fetchChatLinkPreview(url: string, deps: ChatLinkPreviewFetchDependencies = {}): Promise<ChatLinkPreviewFetchOutcome> {
const placeholder = extractChatLinkPreviewPlaceholders(url)[0];
if (!placeholder || placeholder.url !== url) {
return { status: "terminal", preview: fallbackPreview(url), reason: "blocked_url" };
}
let response: Response;
try {
response = await (deps.outboundFetch ?? fetchOutboundHttpWithRedirects)(
placeholder.url,
{
method: "GET",
headers: {
accept: "text/html,application/xhtml+xml,application/json;q=0.8,application/*+json;q=0.7",
"user-agent": CHAT_LINK_PREVIEW_USER_AGENT,
},
},
{
...deps.fetchOptions,
timeoutMs: CHAT_LINK_PREVIEW_FETCH_TIMEOUT_MS,
redirectLimit: CHAT_LINK_PREVIEW_REDIRECT_LIMIT,
urlValidator: validateChatLinkPreviewTarget,
}
);
} catch (error) {
return {
status: error instanceof OutboundHttpUrlValidationError ? "terminal" : "transient",
preview: placeholder,
reason: error instanceof OutboundHttpUrlValidationError ? "blocked_url" : "network_error",
};
}
const finalUrl = validatedResponseUrl(response, placeholder.url);
if (!finalUrl) {
await response.body?.cancel().catch(() => undefined);
return { status: "terminal", preview: placeholder, reason: "blocked_redirect_url" };
}
if (TRANSIENT_HTTP_STATUSES.has(response.status) || response.status >= 500) {
const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), (deps.now ?? (() => new Date()))());
await response.body?.cancel().catch(() => undefined);
return {
status: "transient",
preview: placeholder,
reason: `http_${response.status}`,
...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
};
}
if (!response.ok) {
await response.body?.cancel().catch(() => undefined);
return { status: "terminal", preview: placeholder, reason: `http_${response.status}` };
}
const contentLength = parseContentLength(response.headers.get("content-length"));
if (contentLength !== null && contentLength > CHAT_LINK_PREVIEW_HTML_LIMIT_BYTES) {
await response.body?.cancel().catch(() => undefined);
return { status: "terminal", preview: placeholder, reason: "response_too_large" };
}
const contentType = normalizeContentType(response.headers.get("content-type"));
if (isJsonContentType(contentType)) {
const limited = await readLimitedResponseText(response, CHAT_LINK_PREVIEW_OEMBED_LIMIT_BYTES);
if (limited.truncated) return { status: "terminal", preview: placeholder, reason: "response_too_large" };
const parsed = parseOEmbedJson(limited.body, finalUrl, placeholder.url);
return parsed ? { status: "ready", preview: parsed } : { status: "terminal", preview: placeholder, reason: "invalid_oembed" };
}
if (!isHtmlContentType(contentType)) {
await response.body?.cancel().catch(() => undefined);
return { status: "terminal", preview: placeholder, reason: "unsupported_content_type" };
}
const limited = await readLimitedResponseText(response, CHAT_LINK_PREVIEW_HTML_LIMIT_BYTES);
if (limited.truncated) return { status: "terminal", preview: placeholder, reason: "response_too_large" };
const htmlMetadata = parseHtmlMetadata(limited.body, finalUrl, placeholder.url);
const oEmbedHref = findOEmbedHref(limited.body, finalUrl);
if (!oEmbedHref) return { status: "ready", preview: htmlMetadata };
const oEmbed = await fetchOEmbedPreview(oEmbedHref, finalUrl, placeholder.url, deps);
if (oEmbed.status === "ready") return { status: "ready", preview: mergePreviews(htmlMetadata, oEmbed.preview) };
if (hasUsefulMetadata(htmlMetadata)) return { status: "ready", preview: htmlMetadata };
return oEmbed;
}
export function createPrismaChatLinkPreviewStore(): ChatLinkPreviewStore {
const runTransaction = <T>(tenantId: string, operation: (tx: DbTransactionClient) => Promise<T>) =>
runWithRlsContext({ tenantId }, () => getWriteDbClient().$transaction(operation));
return {
loadSource: (input) =>
runTransaction(input.tenantId, async (tx) => {
if (!(await tenantCanProcessLinkPreview(tx, input.tenantId))) return null;
const message = await tx.teamChatMessage.findFirst({
where: {
tenantId: input.tenantId,
id: input.payload.messageId,
chatId: input.payload.chatId,
bodyFormat: "markdown",
deletedAt: null,
chat: { archivedAt: null },
},
select: { body: true },
});
if (!message || hashChatLinkPreviewBody(message.body) !== input.payload.bodyHash) return null;
return { body: message.body };
}),
persist: (input) =>
runTransaction(input.tenantId, async (tx) => {
await lockChatEventStream(tx, input.tenantId, input.payload.chatId);
if (!(await tenantCanProcessLinkPreview(tx, input.tenantId))) return "skipped";
const message = await tx.teamChatMessage.findFirst({
where: {
tenantId: input.tenantId,
id: input.payload.messageId,
chatId: input.payload.chatId,
bodyFormat: "markdown",
deletedAt: null,
chat: { archivedAt: null },
},
select: { body: true, linkPreviews: true, chat: { select: { eventStreamId: true } } },
});
if (!message || hashChatLinkPreviewBody(message.body) !== input.payload.bodyHash) return "skipped";
const expectedPreviews = extractChatLinkPreviewPlaceholders(message.body);
if (!hasValidTargetIndices(input.updates, input.retries, expectedPreviews.length)) return "skipped";
const nextPreviews = readPersistedLinkPreviews(message.linkPreviews, expectedPreviews);
for (const update of input.updates) {
if (update.preview.url !== expectedPreviews[update.urlIndex]?.url) return "skipped";
nextPreviews[update.urlIndex] = update.preview;
}
const changed = stableJson(message.linkPreviews) !== stableJson(nextPreviews);
if (changed) {
const linkPreviews = nextPreviews as unknown as Prisma.InputJsonValue;
await tx.teamChatMessage.update({
where: { id: input.payload.messageId },
data: { linkPreviews },
select: { id: true },
});
const eventRow = await tx.teamChatEvent.create({
data: {
tenantId: input.tenantId,
chatId: input.payload.chatId,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.linkPreviewReady),
actorUserId: null,
entityId: input.payload.messageId,
requestId: buildReadyEventRequestId(input.outboxEventId, nextPreviews),
data: { messageId: input.payload.messageId, linkPreviews } as unknown as Prisma.InputJsonValue,
},
select: { sequence: true, occurredAt: true, tenantId: true, chatId: true, requestId: true, data: true },
});
const event = validateChatServerEvent({
event: CHAT_EVENT_NAMES.linkPreviewReady,
cursor: `${message.chat.eventStreamId}:${eventRow.sequence.toString()}`,
requestId: eventRow.requestId,
tenantId: eventRow.tenantId,
chatId: eventRow.chatId,
occurredAt: eventRow.occurredAt.toISOString(),
data: eventRow.data,
});
if (event.event !== CHAT_EVENT_NAMES.linkPreviewReady) throw new Error("Link preview event mapping failed.");
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, {
event: event as ChatPersistentEvent,
});
}
for (const retry of input.retries) {
await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
tenantId: input.tenantId,
type: CHAT_LINK_PREVIEW_REQUESTED_OUTBOX_EVENT_TYPE,
payload: {
chatId: input.payload.chatId,
messageId: input.payload.messageId,
bodyHash: input.payload.bodyHash,
urlIndex: retry.urlIndex,
attempt: retry.attempt,
budgetDeferrals: retry.budgetDeferrals,
},
dispatchKey: buildRetryDispatchKey(input.outboxEventId, retry),
scheduledAt: retry.scheduledAt,
});
}
return changed ? "updated" : "unchanged";
}),
};
}
async function tenantCanProcessLinkPreview(tx: DbTransactionClient, tenantId: string): Promise<boolean> {
const tenant = await tx.tenant.findFirst({ where: { id: tenantId, active: true }, select: { id: true } });
return Boolean(tenant) && tenantHasChatModuleForSystemTx(tx, tenantId);
}
async function lockChatEventStream(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<void> {
const lockKey = `chat-event:${tenantId}:${chatId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${CHAT_EVENT_LOCK_SALT}))`;
}
async function fetchOEmbedPreview(
oEmbedUrl: string,
sourceUrl: string,
originalUrl: string,
deps: ChatLinkPreviewFetchDependencies
): Promise<ChatLinkPreviewFetchOutcome> {
const safeOEmbedUrl = normalizeLinkPreviewTarget(oEmbedUrl);
if (!safeOEmbedUrl) return { status: "terminal", preview: fallbackPreview(originalUrl), reason: "blocked_oembed_url" };
try {
const response = await (deps.outboundFetch ?? fetchOutboundHttpWithRedirects)(
safeOEmbedUrl,
{
method: "GET",
headers: { accept: "application/json,application/*+json;q=0.9", "user-agent": CHAT_LINK_PREVIEW_USER_AGENT },
},
{
...deps.fetchOptions,
timeoutMs: CHAT_LINK_PREVIEW_FETCH_TIMEOUT_MS,
redirectLimit: CHAT_LINK_PREVIEW_REDIRECT_LIMIT,
urlValidator: validateChatLinkPreviewTarget,
}
);
if (!validatedResponseUrl(response, safeOEmbedUrl)) {
await response.body?.cancel().catch(() => undefined);
return { status: "terminal", preview: fallbackPreview(originalUrl), reason: "blocked_oembed_redirect_url" };
}
if (TRANSIENT_HTTP_STATUSES.has(response.status) || response.status >= 500) {
const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), (deps.now ?? (() => new Date()))());
await response.body?.cancel().catch(() => undefined);
return {
status: "transient",
preview: fallbackPreview(originalUrl),
reason: `oembed_http_${response.status}`,
...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
};
}
if (!response.ok || !isJsonContentType(normalizeContentType(response.headers.get("content-type")))) {
await response.body?.cancel().catch(() => undefined);
return { status: "terminal", preview: fallbackPreview(originalUrl), reason: "invalid_oembed_response" };
}
const contentLength = parseContentLength(response.headers.get("content-length"));
if (contentLength !== null && contentLength > CHAT_LINK_PREVIEW_OEMBED_LIMIT_BYTES) {
await response.body?.cancel().catch(() => undefined);
return { status: "terminal", preview: fallbackPreview(originalUrl), reason: "oembed_response_too_large" };
}
const limited = await readLimitedResponseText(response, CHAT_LINK_PREVIEW_OEMBED_LIMIT_BYTES);
if (limited.truncated) return { status: "terminal", preview: fallbackPreview(originalUrl), reason: "oembed_response_too_large" };
const preview = parseOEmbedJson(limited.body, sourceUrl, originalUrl);
return preview ? { status: "ready", preview } : { status: "terminal", preview: fallbackPreview(originalUrl), reason: "invalid_oembed" };
} catch (error) {
return {
status: error instanceof OutboundHttpUrlValidationError ? "terminal" : "transient",
preview: fallbackPreview(originalUrl),
reason: error instanceof OutboundHttpUrlValidationError ? "blocked_oembed_url" : "oembed_network_error",
};
}
}
function parseHtmlMetadata(html: string, sourceUrl: string, originalUrl: string): ChatLinkPreview {
const metadata = readMetaTags(html);
const title = firstNonEmpty(metadata.get("og:title"), metadata.get("twitter:title"), readHtmlTitle(html));
const description = firstNonEmpty(metadata.get("og:description"), metadata.get("twitter:description"), metadata.get("description"));
const siteName = firstNonEmpty(metadata.get("og:site_name"), new URL(sourceUrl).hostname.toLowerCase());
const imageCandidate = firstNonEmpty(metadata.get("og:image:secure_url"), metadata.get("og:image"), metadata.get("twitter:image"));
return {
url: originalUrl,
title: normalizeMetadataText(title, MAX_TITLE_LENGTH),
description: normalizeMetadataText(description, MAX_DESCRIPTION_LENGTH),
imageUrl: normalizeDisplayImageUrl(imageCandidate, sourceUrl),
siteName: normalizeMetadataText(siteName, MAX_SITE_NAME_LENGTH),
};
}
function parseOEmbedJson(body: string, sourceUrl: string, originalUrl: string): ChatLinkPreview | null {
let parsed: unknown;
try {
parsed = JSON.parse(body);
} catch {
return null;
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
const record = parsed as Record<string, unknown>;
const title = typeof record.title === "string" ? record.title : null;
const author = typeof record.author_name === "string" ? record.author_name : null;
const provider = typeof record.provider_name === "string" ? record.provider_name : null;
const thumbnail = typeof record.thumbnail_url === "string" ? record.thumbnail_url : null;
return {
url: originalUrl,
title: normalizeMetadataText(title, MAX_TITLE_LENGTH),
description: normalizeMetadataText(author, MAX_DESCRIPTION_LENGTH),
imageUrl: normalizeDisplayImageUrl(thumbnail, sourceUrl),
siteName: normalizeMetadataText(provider ?? new URL(sourceUrl).hostname.toLowerCase(), MAX_SITE_NAME_LENGTH),
};
}
function findOEmbedHref(html: string, baseUrl: string): string | null {
for (const tag of html.match(new RegExp(`<link\\b[^>]{0,${MAX_HTML_TAG_LENGTH}}>`, "giu")) ?? []) {
const attributes = readHtmlAttributes(tag);
const rel = attributes.get("rel")?.toLowerCase().split(/\s+/u) ?? [];
const type = attributes.get("type")?.toLowerCase().split(";", 1)[0]?.trim();
const href = attributes.get("href");
if (!rel.includes("alternate") || !href || (type !== "application/json+oembed" && type !== "text/json+oembed")) continue;
try {
return new URL(decodeHtmlEntities(href), baseUrl).toString();
} catch {
return null;
}
}
return null;
}
function readMetaTags(html: string): Map<string, string> {
const metadata = new Map<string, string>();
for (const tag of html.match(new RegExp(`<meta\\b[^>]{0,${MAX_HTML_TAG_LENGTH}}>`, "giu")) ?? []) {
const attributes = readHtmlAttributes(tag);
const key = (attributes.get("property") ?? attributes.get("name"))?.trim().toLowerCase();
const content = attributes.get("content");
if (key && content !== undefined && !metadata.has(key)) metadata.set(key, decodeHtmlEntities(content));
}
return metadata;
}
function readHtmlAttributes(tag: string): Map<string, string> {
const attributes = new Map<string, string>();
const pattern = /([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gu;
for (const match of tag.matchAll(pattern)) {
const name = match[1]?.toLowerCase();
const value = match[2] ?? match[3] ?? match[4] ?? "";
if (name && !attributes.has(name)) attributes.set(name, value);
}
return attributes;
}
function readHtmlTitle(html: string): string | null {
const match = /<title\b[^>]*>([\s\S]{0,2000}?)<\/title\s*>/iu.exec(html);
return match?.[1] ? decodeHtmlEntities(match[1].replace(/<[^>]*>/gu, " ")) : null;
}
function decodeHtmlEntities(value: string): string {
const named: Readonly<Record<string, string>> = { amp: "&", apos: "'", gt: ">", lt: "<", nbsp: " ", quot: '"' };
return value.replace(/&(?:#(\d{1,7})|#x([a-f0-9]{1,6})|([a-z][a-z0-9]+));/giu, (entity, decimal, hexadecimal, name) => {
if (decimal) return safeCodePoint(Number.parseInt(decimal, 10), entity);
if (hexadecimal) return safeCodePoint(Number.parseInt(hexadecimal, 16), entity);
return named[String(name).toLowerCase()] ?? entity;
});
}
function safeCodePoint(codePoint: number, fallback: string): string {
if (!Number.isInteger(codePoint) || codePoint <= 0 || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) return fallback;
return String.fromCodePoint(codePoint);
}
export function validateChatLinkPreviewTarget(value: string): string {
if (typeof value !== "string" || value.length === 0 || value.length > MAX_URL_LENGTH || /[\u0000-\u001f\u007f]/u.test(value)) {
throw new OutboundHttpUrlValidationError("Chat link preview target is not allowed.");
}
let url: URL;
try {
url = new URL(value);
} catch {
throw new OutboundHttpUrlValidationError("Chat link preview target is not allowed.");
}
if (url.username || url.password || isIP(url.hostname.replace(/^\[|\]$/gu, "")) !== 0) {
throw new OutboundHttpUrlValidationError("Chat link preview target is not allowed.");
}
if ((url.protocol === "http:" && url.port && url.port !== "80") || (url.protocol === "https:" && url.port && url.port !== "443")) {
throw new OutboundHttpUrlValidationError("Chat link preview target is not allowed.");
}
try {
return validateOutboundHttpUrl(url.toString());
} catch {
throw new OutboundHttpUrlValidationError("Chat link preview target is not allowed.");
}
}
function normalizeLinkPreviewTarget(value: string): string | null {
try {
return validateChatLinkPreviewTarget(value);
} catch {
return null;
}
}
function normalizeDisplayImageUrl(value: string | null, sourceUrl: string): string | null {
if (!value) return null;
try {
const resolved = new URL(value, sourceUrl);
// External image hosts are not fetched or embedded in v1. Keeping images
// same-origin avoids turning unvetted metadata into a browser-side probe.
if (resolved.origin !== new URL(sourceUrl).origin) return null;
return normalizeLinkPreviewTarget(resolved.toString());
} catch {
return null;
}
}
function normalizeMetadataText(value: string | null | undefined, maxLength: number): string | null {
if (!value) return null;
// Unicode format controls include bidi overrides/isolation markers. Remote
// metadata must not be able to visually reorder trusted surrounding UI.
const normalized = value
.replace(/[\p{Cf}\u0000-\u001f\u007f]+/gu, " ")
.replace(/\s+/gu, " ")
.trim();
if (!normalized) return null;
return normalized.slice(0, maxLength);
}
function mergePreviews(base: ChatLinkPreview, preferred: ChatLinkPreview): ChatLinkPreview {
return {
url: base.url,
title: preferred.title ?? base.title,
description: preferred.description ?? base.description,
imageUrl: preferred.imageUrl ?? base.imageUrl,
siteName: preferred.siteName ?? base.siteName,
};
}
function hasUsefulMetadata(preview: ChatLinkPreview): boolean {
return Boolean(preview.title || preview.description || preview.imageUrl);
}
function fallbackPreview(value: string): ChatLinkPreview {
const normalized = normalizeLinkPreviewTarget(value);
if (!normalized) return { url: "https://invalid.invalid/", title: null, description: null, imageUrl: null, siteName: null };
return { url: normalized, title: null, description: null, imageUrl: null, siteName: new URL(normalized).hostname.toLowerCase() };
}
function normalizeContentType(value: string | null): string {
return (value ?? "").split(";", 1)[0]?.trim().toLowerCase() ?? "";
}
function validatedResponseUrl(response: Response, fallbackUrl: string): string | null {
const responseUrl = response.url.trim();
return normalizeLinkPreviewTarget(responseUrl || fallbackUrl);
}
function isHtmlContentType(value: string): boolean {
return value === "text/html" || value === "application/xhtml+xml";
}
function isJsonContentType(value: string): boolean {
return value === "application/json" || value === "application/json+oembed" || value === "text/json+oembed" || value.endsWith("+json");
}
function parseContentLength(value: string | null): number | null {
if (!value || !/^\d+$/u.test(value)) return null;
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : Number.POSITIVE_INFINITY;
}
function parseRetryAfterMs(value: string | null, now: Date): number | undefined {
if (!value) return undefined;
const trimmed = value.trim();
if (/^\d+$/u.test(trimmed)) {
const seconds = Number(trimmed);
return Number.isSafeInteger(seconds) ? clampRetryDelay(seconds * 1_000) : RETRY_DELAY_MAX_MS;
}
const retryAt = Date.parse(trimmed);
if (!Number.isFinite(retryAt)) return undefined;
return clampRetryDelay(retryAt - now.getTime());
}
function firstNonEmpty(...values: Array<string | null | undefined>): string | null {
return values.find((value) => typeof value === "string" && value.trim().length > 0) ?? null;
}
function buildChatLinkPreviewDispatchKey(
input: Readonly<{ tenantId: string; chatId: string; messageId: string; requestId: string }>,
bodyHash: string
): string {
const digest = createHash("sha256")
.update(input.tenantId)
.update("\0")
.update(input.chatId)
.update("\0")
.update(input.messageId)
.update("\0")
.update(input.requestId)
.update("\0")
.update(bodyHash)
.digest("hex");
return `chat-link-preview:${digest}`;
}
function buildReadyEventRequestId(outboxEventId: string, linkPreviews: readonly ChatLinkPreview[]): string {
const digest = createHash("sha256").update(outboxEventId).update("\0").update(stableJson(linkPreviews)).digest("hex");
return `link-preview-${digest}`;
}
function buildRetryDispatchKey(outboxEventId: string, retry: ChatLinkPreviewRetry): string {
const digest = createHash("sha256")
.update(outboxEventId)
.update("\0")
.update(String(retry.urlIndex))
.update("\0")
.update(String(retry.attempt))
.update("\0")
.update(String(retry.budgetDeferrals))
.update("\0")
.update(retry.reason)
.digest("hex");
return `chat-link-preview-retry:${digest}`;
}
function hasValidTargetIndices(updates: readonly ChatLinkPreviewUpdate[], retries: readonly ChatLinkPreviewRetry[], previewCount: number): boolean {
return [...updates, ...retries].every((entry) => Number.isInteger(entry.urlIndex) && entry.urlIndex >= 0 && entry.urlIndex < previewCount);
}
function readPersistedLinkPreviews(value: unknown, expected: readonly ChatLinkPreview[]): ChatLinkPreview[] {
if (!Array.isArray(value) || value.length !== expected.length) return expected.map((preview) => ({ ...preview }));
return expected.map((fallback, index) => readPersistedLinkPreview(value[index], fallback));
}
function readPersistedLinkPreview(value: unknown, fallback: ChatLinkPreview): ChatLinkPreview {
if (!value || typeof value !== "object" || Array.isArray(value)) return { ...fallback };
const record = value as Record<string, unknown>;
if (record.url !== fallback.url) return { ...fallback };
return {
url: fallback.url,
title: readPersistedNullableString(record.title, MAX_TITLE_LENGTH),
description: readPersistedNullableString(record.description, MAX_DESCRIPTION_LENGTH),
imageUrl: readPersistedNullableString(record.imageUrl, MAX_URL_LENGTH),
siteName: readPersistedNullableString(record.siteName, MAX_SITE_NAME_LENGTH),
};
}
function readPersistedNullableString(value: unknown, maxLength: number): string | null {
return typeof value === "string" ? value.slice(0, maxLength) : null;
}
function stableJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
if (value !== null && typeof value === "object") {
return `{${Object.entries(value)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)
.join(",")}}`;
}
return JSON.stringify(value);
}
function requireRecord(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
return value as Record<string, unknown>;
}
function requireString(value: unknown, label: string): string {
if (typeof value !== "string") throw new Error(`${label} must be a string.`);
return value;
}
function optionalBoundedInteger(value: unknown, label: string, maximum: number): number | undefined {
if (value === undefined) return undefined;
if (!Number.isInteger(value) || (value as number) < 0 || (value as number) > maximum) {
throw new Error(`Link preview job ${label} is invalid.`);
}
return value as number;
}
function normalizeIdentifier(value: unknown, label: string): string {
const normalized = requireString(value, label).trim();
if (!normalized || normalized.length > MAX_IDENTIFIER_LENGTH || normalized.includes("\0")) throw new Error(`${label} is invalid.`);
return normalized;
}
@@ -0,0 +1,116 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "./permissions.js";
const mocks = vi.hoisted(() => ({
publishAuditEventViaOutbox: vi.fn(),
runChatRepositoryTransaction: vi.fn(),
tx: {
teamChatMember: {
findFirst: vi.fn(),
updateMany: vi.fn(),
},
},
}));
vi.mock("@hivegrid/db/audit-events.server", () => ({
publishAuditEventViaOutbox: (...args: unknown[]) => mocks.publishAuditEventViaOutbox(...args),
}));
vi.mock("./repository.server.js", () => ({
runChatRepositoryTransaction: (...args: unknown[]) => mocks.runChatRepositoryTransaction(...args),
}));
import { setChatMemberPreferences } from "./member-preferences.server.js";
const context = {
tenantId: "tenant_1",
userId: "user_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
requestId: "request_1",
} as const;
describe("chat member preferences", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.runChatRepositoryTransaction.mockImplementation(
async (_input: unknown, _permission: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx)
);
mocks.tx.teamChatMember.findFirst.mockResolvedValue({ id: "member_1", isPinned: false, notificationPref: "all_messages" });
mocks.tx.teamChatMember.updateMany.mockResolvedValue({ count: 1 });
});
it("sets personal pin and notification preferences inside the fresh RLS repository boundary", async () => {
await expect(
setChatMemberPreferences({ ...context, chatId: " chat_1 ", isPinned: true, notificationPreference: "muted" })
).resolves.toEqual({ chatId: "chat_1", isPinned: true, notificationPreference: "muted", changed: true });
expect(mocks.runChatRepositoryTransaction).toHaveBeenCalledWith(
expect.objectContaining({ chatId: " chat_1 " }),
CHAT_PERMISSIONS.readOwnChannels,
expect.any(Function)
);
expect(mocks.tx.teamChatMember.findFirst).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
chatId: "chat_1",
userId: "user_1",
leftAt: null,
chat: { tenantId: "tenant_1" },
},
select: { id: true, isPinned: true, notificationPref: true },
});
expect(mocks.tx.teamChatMember.updateMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", id: "member_1", chatId: "chat_1", userId: "user_1", leftAt: null },
data: { isPinned: true, notificationPref: "muted" },
});
expect(mocks.publishAuditEventViaOutbox).toHaveBeenCalledWith(
mocks.tx,
expect.objectContaining({
action: "chat.member.preferences_updated",
requestId: "request_1",
targetId: "chat_1",
})
);
});
it("is idempotent when the requested preference already matches", async () => {
mocks.tx.teamChatMember.findFirst.mockResolvedValue({ id: "member_1", isPinned: true, notificationPref: "muted" });
await expect(setChatMemberPreferences({ ...context, chatId: "chat_1", isPinned: true })).resolves.toMatchObject({
changed: false,
isPinned: true,
notificationPreference: "muted",
});
expect(mocks.tx.teamChatMember.updateMany).not.toHaveBeenCalled();
expect(mocks.publishAuditEventViaOutbox).not.toHaveBeenCalled();
});
it("fails closed for a non-member without attempting a mutation", async () => {
mocks.tx.teamChatMember.findFirst.mockResolvedValue(null);
await expect(setChatMemberPreferences({ ...context, chatId: "chat_hidden", isPinned: true })).rejects.toMatchObject({
code: "foundation.not_found",
});
expect(mocks.tx.teamChatMember.updateMany).not.toHaveBeenCalled();
});
it.each([
{ chatId: "", isPinned: true },
{ chatId: "chat_1" },
{ chatId: "chat_1", notificationPreference: "invalid" },
])("rejects malformed input before opening a transaction", async (candidate) => {
await expect(
setChatMemberPreferences({ ...context, ...candidate } as Parameters<typeof setChatMemberPreferences>[0])
).rejects.toMatchObject({ code: "chat.invalid_input" });
expect(mocks.runChatRepositoryTransaction).not.toHaveBeenCalled();
});
it("fails closed when the guarded update loses its active member row", async () => {
mocks.tx.teamChatMember.updateMany.mockResolvedValue({ count: 0 });
await expect(setChatMemberPreferences({ ...context, chatId: "chat_1", notificationPreference: "mentions_only" })).rejects.toMatchObject({
code: "chat.integrity_failure",
});
});
});
@@ -0,0 +1,115 @@
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
import type { OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { CatalogError, foundationErrors, withTenantScope } from "@hivegrid/foundation";
import { chatErrors } from "./errors.js";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { runChatRepositoryTransaction } from "./repository.server.js";
import type { ChatNotificationPreference, ChatRouteRepositoryContext } from "./types.js";
const NOTIFICATION_PREFERENCES = new Set<ChatNotificationPreference>(["all_messages", "mentions_only", "muted"]);
export type SetChatMemberPreferencesInput = ChatRouteRepositoryContext &
Readonly<{
chatId: string;
requestId: string;
isPinned?: boolean;
notificationPreference?: ChatNotificationPreference;
}>;
export type ChatMemberPreferencesResult = Readonly<{
chatId: string;
isPinned: boolean;
notificationPreference: ChatNotificationPreference;
changed: boolean;
}>;
/** Updates only the current member's personal channel preferences. The
* repository boundary refreshes permissions and binds tenant/user RLS inside
* the same transaction as the read and write. */
export async function setChatMemberPreferences(input: SetChatMemberPreferencesInput): Promise<ChatMemberPreferencesResult> {
const chatId = normalizeIdentifier(input.chatId);
const requestId = normalizeIdentifier(input.requestId);
const isPinned = normalizeOptionalBoolean(input.isPinned);
const notificationPreference = normalizeOptionalNotificationPreference(input.notificationPreference);
if (isPinned === undefined && notificationPreference === undefined) {
throw new CatalogError(chatErrors.invalidInput);
}
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
const current = await tx.teamChatMember.findFirst({
where: withTenantScope(input.tenantId, {
chatId,
userId: input.userId,
leftAt: null,
chat: { tenantId: input.tenantId },
}),
select: { id: true, isPinned: true, notificationPref: true },
});
if (!current) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
const nextPinned = isPinned ?? current.isPinned;
const nextNotificationPreference = notificationPreference ?? current.notificationPref;
const changed = nextPinned !== current.isPinned || nextNotificationPreference !== current.notificationPref;
if (changed) {
const updated = await tx.teamChatMember.updateMany({
where: withTenantScope(input.tenantId, {
id: current.id,
chatId,
userId: input.userId,
leftAt: null,
}),
data: {
isPinned: nextPinned,
notificationPref: nextNotificationPreference,
},
});
if (updated.count !== 1) throw new CatalogError(chatErrors.integrityFailure);
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId: input.tenantId,
actorId: input.userId,
actorType: "user",
action: "chat.member.preferences_updated",
targetType: "TeamChat",
targetId: chatId,
requestId,
sourceModule: "chat",
outcome: "success",
dataSensitivity: "internal",
metadata: {
isPinned: nextPinned,
notificationPreference: nextNotificationPreference,
},
summaryText: "Persönliche Chat-Einstellungen wurden aktualisiert.",
});
}
return {
chatId,
isPinned: nextPinned,
notificationPreference: nextNotificationPreference,
changed,
};
});
}
function normalizeIdentifier(value: unknown): string {
if (typeof value !== "string") throw new CatalogError(chatErrors.invalidInput);
const normalized = value.trim();
if (!normalized || normalized.length > 191 || normalized.includes("\0")) throw new CatalogError(chatErrors.invalidInput);
return normalized;
}
function normalizeOptionalBoolean(value: unknown): boolean | undefined {
if (value === undefined) return undefined;
if (typeof value !== "boolean") throw new CatalogError(chatErrors.invalidInput);
return value;
}
function normalizeOptionalNotificationPreference(value: unknown): ChatNotificationPreference | undefined {
if (value === undefined) return undefined;
if (typeof value !== "string" || !NOTIFICATION_PREFERENCES.has(value as ChatNotificationPreference)) {
throw new CatalogError(chatErrors.invalidInput);
}
return value as ChatNotificationPreference;
}
@@ -0,0 +1,25 @@
import type { ChatMemberRole } from "./types.js";
export type ChatMemberRoleSources = Readonly<{
isManualMember: boolean;
manualRoleInChat: ChatMemberRole | null;
isProjectManaged: boolean;
projectRoleInChat: ChatMemberRole | null;
isGroupManaged: boolean;
}>;
/**
* Resolve the materialized role from independent membership grants. Manual
* and project sources carry roles; a permission-group source always grants a
* regular member role. A source-less history row deliberately falls back to
* member so a former project lead never keeps an effective admin role.
*/
export function resolveEffectiveChatMemberRole(sources: ChatMemberRoleSources): ChatMemberRole {
if (sources.isManualMember && sources.manualRoleInChat === "admin") return "admin";
if (sources.isProjectManaged && sources.projectRoleInChat === "admin") return "admin";
return "member";
}
export function hasActiveChatMembershipSource(sources: ChatMemberRoleSources): boolean {
return sources.isManualMember || sources.isProjectManaged || sources.isGroupManaged;
}
@@ -0,0 +1,137 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
runTransaction: vi.fn(),
logActivity: vi.fn(),
}));
vi.mock("./repository.server.js", () => ({
runChatRepositoryTransaction: mocks.runTransaction,
}));
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
import { listChatMentionSuggestions, logChatMessageActivitiesWithTx, resolveChatMentionsInBodyWithTx } from "./mentions.server.js";
const context = {
tenantId: "tenant_1",
userId: "user_viewer",
permissions: ["chat.read_own_channels"],
} as const;
function txFixture() {
return {
$queryRaw: vi.fn().mockResolvedValue([{ id: "member_1" }]),
userRole: { findMany: vi.fn().mockResolvedValue([]) },
groupUser: { findMany: vi.fn().mockResolvedValue([]) },
teamChat: {
findFirst: vi.fn().mockResolvedValue({ id: "chat_1", kind: "group", isPrivate: true, projektId: null, name: "Büro" }),
},
teamChatMember: {
findMany: vi.fn().mockResolvedValue([{ userId: "user_visible" }]),
},
tenantUser: {
findMany: vi.fn().mockResolvedValue([
{
userId: "user_visible",
user: { firstName: "Vera", lastName: "Sichtbar", email: "vera@example.test" },
},
]),
},
projekt: { findMany: vi.fn().mockResolvedValue([]) },
kontakt: { findMany: vi.fn().mockResolvedValue([]) },
};
}
describe("chat mention repository", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("limits private-channel user suggestions to active channel members", async () => {
const tx = txFixture();
mocks.runTransaction.mockImplementation(async (_input, _permission, operation) => operation(tx, ["chat.read_own_channels"]));
await expect(listChatMentionSuggestions({ ...context, chatId: "chat_1", query: "ve", type: "user" })).resolves.toEqual([
{ type: "user", id: "user_visible", label: "Vera Sichtbar", detail: "vera@example.test" },
]);
expect(tx.teamChatMember.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: expect.objectContaining({ tenantId: "tenant_1", chatId: "chat_1", leftAt: null }) })
);
expect(tx.tenantUser.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: expect.objectContaining({ tenantId: "tenant_1", userId: { in: ["user_visible"] } }) })
);
});
it("re-resolves body tokens and never accepts a client label", async () => {
const tx = txFixture();
tx.projekt.findMany.mockResolvedValue([{ id: "project_1", projektNummer: "P-100", projektname: "Heizung" }]);
await expect(
resolveChatMentionsInBodyWithTx(
tx as never,
context,
{ id: "chat_1", kind: "group", isPrivate: true, projektId: null, name: "Büro" },
"Hallo <@user:user_visible>, siehe <@project:project_1>",
["chat.read_own_channels", "projects.read_all"]
)
).resolves.toEqual([
{ type: "user", id: "user_visible", label: "Vera Sichtbar" },
{ type: "project", id: "project_1", label: "P-100 · Heizung" },
]);
});
it("rejects a syntactically valid mention when its entity is outside the fresh owner scope", async () => {
const tx = txFixture();
tx.kontakt.findMany.mockResolvedValue([]);
await expect(
resolveChatMentionsInBodyWithTx(
tx as never,
context,
{ id: "chat_1", kind: "group", isPrivate: true, projektId: null, name: "Büro" },
"<@contact:contact_other>",
["chat.read_own_channels", "crm.read_own"]
)
).rejects.toMatchObject({ i18nKey: "chat.errors.invalidInput" });
expect(tx.kontakt.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: expect.objectContaining({ tenantId: "tenant_1", AND: [expect.objectContaining({ zustaendigerUserId: "user_viewer" })] }) })
);
});
it("logs the project-channel activity once and skips a duplicate self-project mention", async () => {
const tx = txFixture();
mocks.logActivity.mockResolvedValue({ id: "activity_1" });
await logChatMessageActivitiesWithTx(tx as never, context, {
channel: { id: "chat_1", projektId: "project_1", name: "Projekt" },
messageId: "message_1",
body: "Update zu <@project:project_1> und <@company:company_1>",
mentions: [
{ type: "project", id: "project_1", label: "P-100" },
{ type: "company", id: "company_1", label: "Muster GmbH" },
],
includeProjectChannelActivity: true,
action: "message_created",
});
expect(mocks.logActivity).toHaveBeenCalledTimes(2);
expect(mocks.logActivity).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
subjectType: "project",
subjectId: "project_1",
summaryText: "activity.runtime.chat.messageCreated",
}),
{ client: tx }
);
expect(mocks.logActivity).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
subjectType: "company",
subjectId: "company_1",
summaryText: "activity.runtime.chat.entityMentioned",
}),
{ client: tx }
);
});
});
@@ -0,0 +1,494 @@
import { logActivity } from "@hivegrid/activity";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import { CatalogError, foundationErrors, withTenantScope } from "@hivegrid/foundation";
import { extractChatMentions, type ChatMention, type ChatMentionType } from "@hivegrid/realtime";
import { chatErrors } from "./errors.js";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { runChatRepositoryTransaction } from "./repository.server.js";
import type { ChatRepositoryContext } from "./types.js";
const ACTIVE_TENANT_USER_STATUS = 2;
const MAX_QUERY_LENGTH = 120;
const MAX_SUGGESTIONS = 10;
const MAX_LABEL_LENGTH = 300;
export type ChatMentionSuggestion = Readonly<{
type: ChatMentionType;
id: string;
label: string;
detail: string | null;
}>;
export type ListChatMentionSuggestionsInput = ChatRepositoryContext &
Readonly<{
chatId: string;
query?: string;
type?: ChatMentionType | null;
limit?: number;
}>;
export type ChatMentionChannel = Readonly<{
id: string;
kind: "project" | "group" | "dm";
isPrivate: boolean;
projektId: string | null;
name: string | null;
}>;
type VisibilityPrincipals = Readonly<{
roleIds: readonly string[];
groupIds: readonly string[];
}>;
/**
* Lists mention candidates through the same fresh-permission and FORCE-RLS
* transaction boundary as channel reads. Results are intentionally bounded on
* the server; the combobox never receives a tenant-wide directory dump.
*/
export async function listChatMentionSuggestions(input: ListChatMentionSuggestionsInput): Promise<readonly ChatMentionSuggestion[]> {
const normalized = normalizeSuggestionInput(input);
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx, currentPermissions) => {
const channel = await requireMentionChannel(tx, input, normalized.chatId, true);
const principals = await loadVisibilityPrincipals(tx, input);
const types = normalized.type ? [normalized.type] : (["user", "project", "contact", "company"] as const);
const suggestions: ChatMentionSuggestion[] = [];
for (const type of types) {
const remaining = normalized.limit - suggestions.length;
if (remaining <= 0) break;
const rows = await listSuggestionsOfType(tx, input, channel, currentPermissions, principals, type, normalized.query, remaining);
suggestions.push(...rows);
}
return suggestions;
});
}
/**
* Extracts canonical tokens from the body and re-resolves every id and label.
* Client-provided mention arrays and labels are never authoritative.
*/
export async function resolveChatMentionsInBodyWithTx(
tx: DbTransactionClient,
context: ChatRepositoryContext,
channel: ChatMentionChannel,
body: string,
currentPermissions: readonly string[]
): Promise<ChatMention[]> {
let extracted: ChatMention[];
try {
extracted = extractChatMentions(body);
} catch {
throw new CatalogError(chatErrors.invalidInput, { field: "body" });
}
if (extracted.length === 0) return [];
const principals = await loadVisibilityPrincipals(tx, context);
const resolvedByKey = new Map<string, ChatMention>();
for (const type of ["user", "project", "contact", "company"] as const) {
const ids = [...new Set(extracted.filter((mention) => mention.type === type).map((mention) => mention.id))];
if (ids.length === 0) continue;
const rows = await resolveMentionsOfType(tx, context, channel, currentPermissions, principals, type, ids);
for (const row of rows) resolvedByKey.set(mentionKey(row), row);
}
const resolved = extracted.map((mention) => resolvedByKey.get(mentionKey(mention)));
if (resolved.some((mention) => mention === undefined)) {
throw new CatalogError(chatErrors.invalidInput, { mention: "not-visible" });
}
return resolved as ChatMention[];
}
/** Writes the project timeline entry and each entity-mention timeline entry. */
export async function logChatMessageActivitiesWithTx(
tx: DbTransactionClient,
context: ChatRepositoryContext,
input: Readonly<{
channel: Pick<ChatMentionChannel, "id" | "projektId" | "name">;
messageId: string;
body: string;
mentions: readonly ChatMention[];
includeProjectChannelActivity: boolean;
skipMentionKeys?: ReadonlySet<string>;
action: "message_created" | "thread_reply_created" | "message_edited";
}>
): Promise<void> {
const loggedSubjects = new Set<string>();
if (input.includeProjectChannelActivity && input.channel.projektId) {
await logActivity(
{
tenantId: context.tenantId,
actorUserId: context.userId,
actorKind: "user",
activityType: "chat_message",
subjectType: "project",
subjectId: input.channel.projektId,
summaryText:
input.action === "thread_reply_created"
? "activity.runtime.chat.threadReplyCreated"
: input.action === "message_edited"
? "activity.runtime.chat.messageEdited"
: "activity.runtime.chat.messageCreated",
metadata: {
sourceModule: "chat",
chatAction: input.action,
chatId: input.channel.id,
messageId: input.messageId,
},
},
{ client: tx }
);
loggedSubjects.add(`project\u0000${input.channel.projektId}`);
}
for (const mention of input.mentions) {
if (mention.type === "user") continue;
const key = mentionKey(mention);
if (input.skipMentionKeys?.has(key) || loggedSubjects.has(`${mention.type}\u0000${mention.id}`)) continue;
await logActivity(
{
tenantId: context.tenantId,
actorUserId: context.userId,
actorKind: "user",
activityType: "chat_message",
subjectType: mention.type,
subjectId: mention.id,
summaryText: "activity.runtime.chat.entityMentioned",
metadata: {
sourceModule: "chat",
chatAction: "entity_mentioned",
chatId: input.channel.id,
messageId: input.messageId,
mentionType: mention.type,
},
},
{ client: tx }
);
loggedSubjects.add(`${mention.type}\u0000${mention.id}`);
}
}
export function chatMentionKey(mention: Pick<ChatMention, "type" | "id">): string {
return mentionKey(mention);
}
async function requireMentionChannel(
tx: DbTransactionClient,
context: ChatRepositoryContext,
chatId: string,
lockMembership: boolean
): Promise<ChatMentionChannel> {
if (lockMembership) {
const rows = await tx.$queryRaw<Array<{ id: string }>>`
SELECT mention_viewer."id"
FROM "TeamChatMember" AS mention_viewer
WHERE mention_viewer."tenantId" = ${context.tenantId}
AND mention_viewer."chatId" = ${chatId}
AND mention_viewer."userId" = ${context.userId}
AND mention_viewer."leftAt" IS NULL
FOR SHARE
`;
if (rows.length !== 1) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
}
const channel = await tx.teamChat.findFirst({
where: withTenantScope(context.tenantId, {
id: chatId,
members: { some: withTenantScope(context.tenantId, { userId: context.userId, leftAt: null }) },
}),
select: { id: true, kind: true, isPrivate: true, projektId: true, name: true },
});
if (!channel) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
return channel;
}
async function loadVisibilityPrincipals(tx: DbTransactionClient, context: Pick<ChatRepositoryContext, "tenantId" | "userId">): Promise<VisibilityPrincipals> {
const [roles, groups] = await Promise.all([
tx.userRole.findMany({
where: { tenantId: context.tenantId, userId: context.userId, role: { type: "app", OR: [{ tenantId: context.tenantId }, { tenantId: null }] } },
select: { roleId: true },
}),
tx.groupUser.findMany({
where: { userId: context.userId, group: { tenantId: context.tenantId } },
select: { groupId: true },
}),
]);
return {
roleIds: [...new Set(roles.map((row) => row.roleId))],
groupIds: [...new Set(groups.map((row) => row.groupId))],
};
}
async function listSuggestionsOfType(
tx: DbTransactionClient,
context: ChatRepositoryContext,
channel: ChatMentionChannel,
permissions: readonly string[],
principals: VisibilityPrincipals,
type: ChatMentionType,
query: string,
limit: number
): Promise<ChatMentionSuggestion[]> {
if (type === "user") return listUserSuggestions(tx, context, channel, query, limit);
if (type === "project") return listProjectSuggestions(tx, context, permissions, principals, query, limit);
return listContactSuggestions(tx, context, permissions, type, query, limit);
}
async function listUserSuggestions(
tx: DbTransactionClient,
context: ChatRepositoryContext,
channel: ChatMentionChannel,
query: string,
limit: number
): Promise<ChatMentionSuggestion[]> {
const memberIds = (
await tx.teamChatMember.findMany({
where: withTenantScope(context.tenantId, { chatId: channel.id, leftAt: null }),
select: { userId: true },
})
).map((row) => row.userId);
if (memberIds.length === 0) return [];
const rows = await tx.tenantUser.findMany({
where: withTenantScope(context.tenantId, {
status: ACTIVE_TENANT_USER_STATUS,
userId: { in: memberIds },
user: {
active: true,
pendingDeletion: false,
...(query
? {
OR: [
{ firstName: { contains: query, mode: "insensitive" as const } },
{ lastName: { contains: query, mode: "insensitive" as const } },
{ email: { contains: query, mode: "insensitive" as const } },
],
}
: {}),
},
}),
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
take: Math.max(limit * 3, limit),
});
return rows
.map((row) => ({
type: "user" as const,
id: row.userId,
label: userDisplayName(row.user),
detail: row.user.email,
}))
.sort(compareSuggestions)
.slice(0, limit);
}
async function listProjectSuggestions(
tx: DbTransactionClient,
context: ChatRepositoryContext,
permissions: readonly string[],
principals: VisibilityPrincipals,
query: string,
limit: number
): Promise<ChatMentionSuggestion[]> {
const scope = projectVisibilityWhere(context, permissions, principals);
if (scope === null) return [];
const rows = await tx.projekt.findMany({
where: withTenantScope(context.tenantId, {
archivedAt: null,
AND: [
scope,
...(query
? [
{
OR: [
{ projektname: { contains: query, mode: "insensitive" as const } },
{ projektNummer: { contains: query, mode: "insensitive" as const } },
],
},
]
: []),
],
}),
select: { id: true, projektNummer: true, projektname: true },
take: Math.max(limit * 3, limit),
});
return rows
.map((row) => ({ type: "project" as const, id: row.id, label: boundedLabel(`${row.projektNummer} · ${row.projektname}`), detail: row.projektNummer }))
.sort(compareSuggestions)
.slice(0, limit);
}
async function listContactSuggestions(
tx: DbTransactionClient,
context: ChatRepositoryContext,
permissions: readonly string[],
type: "contact" | "company",
query: string,
limit: number
): Promise<ChatMentionSuggestion[]> {
const scope = contactVisibilityWhere(context, permissions);
if (scope === null) return [];
const kontaktTyp = type === "company" ? ("organisation" as const) : ("privatperson" as const);
const rows = await tx.kontakt.findMany({
where: withTenantScope(context.tenantId, {
kontaktTyp,
archivedAt: null,
AND: [
scope,
...(query
? [
{
OR: [
{ vorname: { contains: query, mode: "insensitive" as const } },
{ nachname: { contains: query, mode: "insensitive" as const } },
{ orgName: { contains: query, mode: "insensitive" as const } },
{ primaerEmail: { contains: query, mode: "insensitive" as const } },
],
},
]
: []),
],
}),
select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true },
take: Math.max(limit * 3, limit),
});
return rows
.map((row) => ({ type, id: row.id, label: kontaktDisplayName(row, type), detail: row.primaerEmail }))
.sort(compareSuggestions)
.slice(0, limit);
}
async function resolveMentionsOfType(
tx: DbTransactionClient,
context: ChatRepositoryContext,
channel: ChatMentionChannel,
permissions: readonly string[],
principals: VisibilityPrincipals,
type: ChatMentionType,
ids: readonly string[]
): Promise<ChatMention[]> {
if (type === "user") {
const memberIds = (
await tx.teamChatMember.findMany({
where: withTenantScope(context.tenantId, { chatId: channel.id, leftAt: null, userId: { in: [...ids] } }),
select: { userId: true },
})
).map((row) => row.userId);
if (memberIds.length === 0) return [];
const rows = await tx.tenantUser.findMany({
where: withTenantScope(context.tenantId, {
userId: { in: memberIds },
status: ACTIVE_TENANT_USER_STATUS,
user: { active: true, pendingDeletion: false },
}),
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
});
return rows.map((row) => ({ type: "user", id: row.userId, label: userDisplayName(row.user) }));
}
if (type === "project") {
const scope = projectVisibilityWhere(context, permissions, principals);
if (scope === null) return [];
const rows = await tx.projekt.findMany({
where: withTenantScope(context.tenantId, { id: { in: [...ids] }, archivedAt: null, AND: [scope] }),
select: { id: true, projektNummer: true, projektname: true },
});
return rows.map((row) => ({ type, id: row.id, label: boundedLabel(`${row.projektNummer} · ${row.projektname}`) }));
}
const scope = contactVisibilityWhere(context, permissions);
if (scope === null) return [];
const kontaktTyp = type === "company" ? ("organisation" as const) : ("privatperson" as const);
const rows = await tx.kontakt.findMany({
where: withTenantScope(context.tenantId, { id: { in: [...ids] }, kontaktTyp, archivedAt: null, AND: [scope] }),
select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true },
});
return rows.map((row) => ({ type, id: row.id, label: kontaktDisplayName(row, type) }));
}
function projectVisibilityWhere(
context: ChatRepositoryContext,
permissions: readonly string[],
principals: VisibilityPrincipals
): Prisma.ProjektWhereInput | null {
const ownerConditions: Prisma.ProjektWhereInput[] = [];
if (permissions.includes("projects.read_all")) {
// No owner restriction.
} else {
if (permissions.includes("projects.read_own")) ownerConditions.push({ zustaendigePersonId: context.userId });
if (permissions.includes("projects.read_own_pl")) ownerConditions.push({ projektleiterId: context.userId });
if (permissions.includes("projects.read_own_member")) {
ownerConditions.push({
mitglieder: {
some: withTenantScope(context.tenantId, {
archivedAt: null,
OR: [{ userId: context.userId }, ...(principals.groupIds.length > 0 ? [{ groupId: { in: [...principals.groupIds] } }] : [])],
}),
},
});
}
if (ownerConditions.length === 0) return null;
}
const effectivePrincipals: Prisma.PipelineAccessWhereInput[] = [
{ principalType: "user", principalId: context.userId },
...principals.roleIds.map((principalId) => ({ principalType: "role" as const, principalId })),
...principals.groupIds.map((principalId) => ({ principalType: "group" as const, principalId })),
];
return {
AND: [
...(ownerConditions.length > 0 ? [{ OR: ownerConditions }] : []),
{ pipeline: { accessRules: { none: withTenantScope(context.tenantId, { kannSehen: false, OR: effectivePrincipals }) } } },
],
};
}
function contactVisibilityWhere(context: ChatRepositoryContext, permissions: readonly string[]): Prisma.KontaktWhereInput | null {
if (permissions.includes("crm.read_all")) return {};
if (permissions.includes("crm.read_own")) return { zustaendigerUserId: context.userId };
return null;
}
function normalizeSuggestionInput(input: ListChatMentionSuggestionsInput): { chatId: string; query: string; type: ChatMentionType | null; limit: number } {
const chatId = normalizeIdentifier(input.chatId, "chatId");
if (input.type !== undefined && input.type !== null && !["user", "project", "contact", "company"].includes(input.type)) {
throw new CatalogError(chatErrors.invalidInput, { field: "type" });
}
const query = typeof input.query === "string" ? input.query.trim().slice(0, MAX_QUERY_LENGTH) : "";
const limit = input.limit === undefined ? MAX_SUGGESTIONS : input.limit;
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_SUGGESTIONS) {
throw new CatalogError(chatErrors.invalidInput, { field: "limit" });
}
return { chatId, query, type: input.type ?? null, limit };
}
function normalizeIdentifier(value: unknown, field: string): string {
if (typeof value !== "string") throw new CatalogError(chatErrors.invalidInput, { field });
const normalized = value.trim();
if (!normalized || normalized.length > 500 || normalized.includes("\0")) throw new CatalogError(chatErrors.invalidInput, { field });
return normalized;
}
function userDisplayName(user: { firstName: string; lastName: string; email: string }): string {
return boundedLabel(`${user.firstName} ${user.lastName}`.trim() || user.email.trim());
}
function kontaktDisplayName(
row: { vorname: string | null; nachname: string | null; orgName: string | null; primaerEmail: string | null },
type: "contact" | "company"
): string {
const label = type === "company" ? row.orgName?.trim() : `${row.vorname ?? ""} ${row.nachname ?? ""}`.trim();
return boundedLabel(label || row.primaerEmail?.trim() || (type === "company" ? "Firma" : "Kontakt"));
}
function boundedLabel(value: string): string {
const normalized = value.trim().replace(/\s+/gu, " ");
if (!normalized) throw new CatalogError(chatErrors.integrityFailure);
return normalized.slice(0, MAX_LABEL_LENGTH);
}
function compareSuggestions(left: ChatMentionSuggestion, right: ChatMentionSuggestion): number {
return left.label.localeCompare(right.label, "de", { sensitivity: "base" }) || left.id.localeCompare(right.id);
}
function mentionKey(mention: Pick<ChatMention, "type" | "id">): string {
return `${mention.type}\u0000${mention.id}`;
}
@@ -0,0 +1,168 @@
// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { listChatMessageDiscovery } from "./message-discovery.server.js";
import { CHAT_PERMISSIONS } from "./permissions.js";
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_A = "chat_discovery_rls_tenant_a";
const TENANT_B = "chat_discovery_rls_tenant_b";
const VIEWER_A = "chat_discovery_rls_viewer_a";
const OUTSIDER_A = "chat_discovery_rls_outsider_a";
const MEMBER_B = "chat_discovery_rls_member_b";
const VISIBLE_CHAT = "chat_discovery_rls_visible";
const HIDDEN_CHAT = "chat_discovery_rls_hidden";
const ARCHIVED_CHAT = "chat_discovery_rls_archived";
const FOREIGN_CHAT = "chat_discovery_rls_foreign";
const ROLE_ID = "chat_discovery_rls_role";
const PERMISSION_ID = "chat_discovery_rls_permission";
const NEEDLE = "rls-visible-heat-pump";
describeIfDatabase("chat message discovery with restricted FORCE RLS", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
let permissionCreatedByFixture = false;
beforeAll(async () => {
await cleanup(admin);
await admin.user.createMany({
data: [
{ id: VIEWER_A, email: "chat-discovery-viewer-a@example.test", firstName: "Viewer", lastName: "A", active: true },
{ id: OUTSIDER_A, email: "chat-discovery-outsider-a@example.test", firstName: "Outsider", lastName: "A", active: true },
{ id: MEMBER_B, email: "chat-discovery-member-b@example.test", firstName: "Member", lastName: "B", active: true },
],
});
await admin.tenant.createMany({
data: [
{ id: TENANT_A, slug: TENANT_A, name: "Chat discovery tenant A", active: true },
{ id: TENANT_B, slug: TENANT_B, name: "Chat discovery tenant B", active: true },
],
});
await admin.tenantUser.createMany({
data: [
{ id: "chat_discovery_rls_tu_viewer", tenantId: TENANT_A, userId: VIEWER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_discovery_rls_tu_outsider", tenantId: TENANT_A, userId: OUTSIDER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_discovery_rls_tu_member_b", tenantId: TENANT_B, userId: MEMBER_B, type: 0, joined: 1, status: 2 },
],
});
await admin.teamChat.createMany({
data: [
{ id: VISIBLE_CHAT, tenantId: TENANT_A, createdByUserId: VIEWER_A, kind: "group", name: "Visible", eventStreamId: `${VISIBLE_CHAT}_stream` },
{ id: HIDDEN_CHAT, tenantId: TENANT_A, createdByUserId: OUTSIDER_A, kind: "group", name: "Hidden", eventStreamId: `${HIDDEN_CHAT}_stream` },
{
id: ARCHIVED_CHAT,
tenantId: TENANT_A,
createdByUserId: VIEWER_A,
kind: "group",
name: "Archived",
eventStreamId: `${ARCHIVED_CHAT}_stream`,
archivedAt: new Date("2026-07-16T09:00:00.000Z"),
archivedReason: "manual",
},
{ id: FOREIGN_CHAT, tenantId: TENANT_B, createdByUserId: MEMBER_B, kind: "group", name: "Foreign", eventStreamId: `${FOREIGN_CHAT}_stream` },
],
});
await admin.teamChatMember.createMany({
data: [
{ id: "chat_discovery_rls_member_visible", tenantId: TENANT_A, chatId: VISIBLE_CHAT, userId: VIEWER_A, notificationPref: "all_messages" },
{ id: "chat_discovery_rls_member_hidden", tenantId: TENANT_A, chatId: HIDDEN_CHAT, userId: OUTSIDER_A, notificationPref: "all_messages" },
{ id: "chat_discovery_rls_member_archived", tenantId: TENANT_A, chatId: ARCHIVED_CHAT, userId: VIEWER_A, notificationPref: "all_messages" },
{ id: "chat_discovery_rls_member_foreign", tenantId: TENANT_B, chatId: FOREIGN_CHAT, userId: MEMBER_B, notificationPref: "all_messages" },
],
});
await admin.teamChatMessage.createMany({
data: [
message("chat_discovery_rls_message_visible", TENANT_A, VISIBLE_CHAT, VIEWER_A),
message("chat_discovery_rls_message_hidden", TENANT_A, HIDDEN_CHAT, OUTSIDER_A),
message("chat_discovery_rls_message_archived", TENANT_A, ARCHIVED_CHAT, VIEWER_A),
message("chat_discovery_rls_message_foreign", TENANT_B, FOREIGN_CHAT, MEMBER_B),
],
});
const existingPermission = await admin.permission.findUnique({ where: { name: CHAT_PERMISSIONS.readOwnChannels }, select: { id: true } });
permissionCreatedByFixture = existingPermission === null;
const permission =
existingPermission ??
(await admin.permission.create({
data: {
id: PERMISSION_ID,
name: CHAT_PERMISSIONS.readOwnChannels,
description: "Chat discovery RLS fixture",
type: "app",
isDefault: false,
order: 99_980,
},
select: { id: true },
}));
await admin.role.create({
data: {
id: ROLE_ID,
tenantId: null,
name: "Chat discovery RLS role",
description: "Restricted-role proof for chat search and mentions",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 99_980,
},
});
await admin.rolePermission.create({ data: { id: `${ROLE_ID}_permission`, roleId: ROLE_ID, permissionId: permission.id } });
await admin.userRole.create({ data: { id: `${ROLE_ID}_viewer`, tenantId: TENANT_A, userId: VIEWER_A, roleId: ROLE_ID } });
});
afterAll(async () => {
await cleanup(admin);
if (permissionCreatedByFixture) await admin.permission.deleteMany({ where: { id: PERMISSION_ID, name: CHAT_PERMISSIONS.readOwnChannels } });
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("returns search and mention results only from the viewer's active, non-archived member channel", async () => {
const role = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(role).toEqual([{ currentUser: "hivegrid_app" }]);
const state = await app.$queryRaw<Array<{ enabled: boolean; forced: boolean }>>`
SELECT relrowsecurity AS enabled, relforcerowsecurity AS forced
FROM pg_catalog.pg_class
WHERE relnamespace = 'public'::regnamespace
AND relname IN ('TeamChat', 'TeamChatMember', 'TeamChatMessage')
ORDER BY relname ASC
`;
expect(state).toHaveLength(3);
expect(state.every((table) => table.enabled && table.forced)).toBe(true);
await expect(app.teamChatMessage.findMany({ where: { body: { contains: NEEDLE } }, select: { id: true } })).resolves.toEqual([]);
const context = { tenantId: TENANT_A, userId: VIEWER_A, permissions: [CHAT_PERMISSIONS.readOwnChannels] } as const;
const search = await listChatMessageDiscovery({ ...context, mode: "search", query: NEEDLE });
const mentions = await listChatMessageDiscovery({ ...context, mode: "mentions" });
expect(search.messages.map(({ id }) => id)).toEqual(["chat_discovery_rls_message_visible"]);
expect(mentions.messages.map(({ id }) => id)).toEqual(["chat_discovery_rls_message_visible"]);
});
});
function message(id: string, tenantId: string, chatId: string, authorUserId: string) {
return {
id,
tenantId,
chatId,
authorUserId,
clientMessageId: `${id}_client`,
body: `${NEEDLE} ${id}`,
mentions: [{ type: "user", id: VIEWER_A, label: "Viewer A" }],
linkPreviews: [],
} as const;
}
async function cleanup(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.userRole.deleteMany({ where: { id: `${ROLE_ID}_viewer` } });
await admin.rolePermission.deleteMany({ where: { id: `${ROLE_ID}_permission` } });
await admin.role.deleteMany({ where: { id: ROLE_ID } });
await admin.teamChatMessage.deleteMany({ where: { id: { startsWith: "chat_discovery_rls_message_" } } });
await admin.teamChatMember.deleteMany({ where: { id: { startsWith: "chat_discovery_rls_member_" } } });
await admin.teamChat.deleteMany({ where: { id: { in: [VISIBLE_CHAT, HIDDEN_CHAT, ARCHIVED_CHAT, FOREIGN_CHAT] } } });
await admin.tenantUser.deleteMany({ where: { id: { startsWith: "chat_discovery_rls_tu_" } } });
await admin.tenant.deleteMany({ where: { id: { in: [TENANT_A, TENANT_B] } } });
await admin.user.deleteMany({ where: { id: { in: [VIEWER_A, OUTSIDER_A, MEMBER_B] } } });
}
@@ -0,0 +1,143 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "./permissions.js";
const mocks = vi.hoisted(() => ({
runTransaction: vi.fn(),
tx: { $queryRaw: vi.fn() },
}));
vi.mock("./repository.server.js", () => ({
runChatRepositoryTransaction: (...args: unknown[]) => mocks.runTransaction(...args),
}));
import { listChatMessageDiscovery } from "./message-discovery.server.js";
const context = {
tenantId: "tenant_1",
userId: "viewer_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
} as const;
function row(id: string, createdAt: string, overrides: Record<string, unknown> = {}) {
return {
id,
chatId: "chat_1",
channelKind: "group",
channelName: " Montage Nord ",
projectId: null,
authorUserId: "author_1",
body: ` Nachricht ${id} `,
parentMessageId: null,
createdAt: new Date(createdAt),
...overrides,
};
}
describe("chat message discovery repository", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.runTransaction.mockImplementation(
async (_context: unknown, _permission: string, operation: (tx: typeof mocks.tx, permissions: readonly string[]) => Promise<unknown>) =>
operation(mocks.tx, [CHAT_PERMISSIONS.readOwnChannels])
);
mocks.tx.$queryRaw.mockResolvedValue([]);
});
it("searches only through the shared repository gate and returns a filter-bound cursor", async () => {
mocks.tx.$queryRaw
.mockResolvedValueOnce([
row("message_3", "2026-07-16T10:03:00.000Z"),
row("message_2", "2026-07-16T10:02:00.000Z"),
row("message_1", "2026-07-16T10:01:00.000Z"),
])
.mockResolvedValueOnce([
{ chatId: "chat_1", userId: "author_1", displayName: "Ada Lovelace", avatarUrl: "/avatars/ada" },
{ chatId: "chat_1", userId: "viewer_1", displayName: "Raffael Sheikh", avatarUrl: null },
]);
const result = await listChatMessageDiscovery({ ...context, mode: "search", query: " heat%pump ", limit: 2 });
expect(mocks.runTransaction).toHaveBeenCalledWith(
{ ...context, mode: "search", query: " heat%pump ", limit: 2 },
CHAT_PERMISSIONS.readOwnChannels,
expect.any(Function)
);
expect(result.messages).toEqual([
{
id: "message_3",
chatId: "chat_1",
channelKind: "group",
channelName: "Montage Nord",
projectId: null,
authorUserId: "author_1",
body: "Nachricht message_3",
parentMessageId: null,
createdAtIso: "2026-07-16T10:03:00.000Z",
participants: [
{ userId: "author_1", displayName: "Ada Lovelace", avatarUrl: "/avatars/ada" },
{ userId: "viewer_1", displayName: "Raffael Sheikh", avatarUrl: null },
],
},
expect.objectContaining({ id: "message_2" }),
]);
expect(result.nextCursor).toEqual(expect.any(String));
const searchSql = queryText(mocks.tx.$queryRaw.mock.calls[0]);
expect(searchSql).toContain('INNER JOIN "TeamChatMember" AS viewer_member');
expect(searchSql).toContain('viewer_member."leftAt" IS NULL');
expect(searchSql).toContain('channel_row."archivedAt" IS NULL');
expect(searchSql).toContain('message_row."body" ILIKE');
expect(mocks.tx.$queryRaw.mock.calls[0]?.slice(1)).toEqual(expect.arrayContaining(["tenant_1", "viewer_1", "%heat!%pump%", 3]));
mocks.tx.$queryRaw.mockResolvedValueOnce([]);
await listChatMessageDiscovery({ ...context, mode: "search", query: "heat%pump", limit: 2, beforeCursor: result.nextCursor! });
expect(mocks.tx.$queryRaw.mock.calls.at(-1)?.slice(1)).toEqual(
expect.arrayContaining([new Date("2026-07-16T10:02:00.000Z"), "message_2"])
);
});
it("aggregates every visible user mention and keeps the mention predicate server-side", async () => {
mocks.tx.$queryRaw.mockResolvedValueOnce([row("mention_1", "2026-07-16T11:00:00.000Z")]).mockResolvedValueOnce([]);
const result = await listChatMessageDiscovery({ ...context, mode: "mentions" });
expect(result.messages).toHaveLength(1);
const mentionSql = queryText(mocks.tx.$queryRaw.mock.calls[0]);
expect(mentionSql).toContain('message_row."mentions" @> jsonb_build_array');
expect(mentionSql).toContain('viewer_member."userId" =');
expect(mocks.tx.$queryRaw.mock.calls[0]?.slice(1)).toEqual(expect.arrayContaining(["tenant_1", "viewer_1"]));
});
it("still checks current permission and module access for an empty search", async () => {
const result = await listChatMessageDiscovery({ ...context, mode: "search", query: " " });
expect(result).toEqual({ messages: [], nextCursor: null });
expect(mocks.runTransaction).toHaveBeenCalledWith(expect.any(Object), CHAT_PERMISSIONS.readOwnChannels, expect.any(Function));
expect(mocks.tx.$queryRaw).not.toHaveBeenCalled();
});
it("rejects malformed input and a cursor from another filter before querying", async () => {
await expect(listChatMessageDiscovery({ ...context, mode: "search", query: "x".repeat(201) })).rejects.toMatchObject({
code: "chat.invalid_input",
});
await expect(listChatMessageDiscovery({ ...context, mode: "mentions", query: "unexpected" })).rejects.toMatchObject({
code: "chat.invalid_input",
});
await expect(listChatMessageDiscovery({ ...context, mode: "search", beforeCursor: "broken" })).rejects.toMatchObject({
code: "chat.invalid_input",
});
expect(mocks.runTransaction).not.toHaveBeenCalled();
});
it("fails closed on malformed persisted records", async () => {
mocks.tx.$queryRaw.mockResolvedValueOnce([row("bad", "2026-07-16T10:00:00.000Z", { authorUserId: null })]).mockResolvedValueOnce([]);
await expect(listChatMessageDiscovery({ ...context, mode: "mentions" })).rejects.toMatchObject({ code: "chat.integrity_failure" });
});
});
function queryText(call: unknown[] | undefined): string {
const strings = call?.[0];
return Array.isArray(strings) ? strings.join("?") : "";
}
@@ -0,0 +1,315 @@
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import { CatalogError } from "@hivegrid/foundation";
import { chatErrors } from "./errors.js";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { runChatRepositoryTransaction } from "./repository.server.js";
import type { ChatChannelKind, ChatParticipantProfileRecord, ChatRouteRepositoryContext } from "./types.js";
const DEFAULT_LIMIT = 30;
const MAX_LIMIT = 100;
const MAX_QUERY_LENGTH = 200;
const MAX_CURSOR_LENGTH = 2_048;
const ACTIVE_TENANT_USER_STATUS = 2;
export type ChatMessageDiscoveryMode = "search" | "mentions";
export type ChatMessageDiscoveryRecord = Readonly<{
id: string;
chatId: string;
channelKind: ChatChannelKind;
channelName: string | null;
projectId: string | null;
authorUserId: string;
body: string;
parentMessageId: string | null;
createdAtIso: string;
participants: readonly ChatParticipantProfileRecord[];
}>;
export type ListChatMessageDiscoveryInput = ChatRouteRepositoryContext &
Readonly<{
mode: ChatMessageDiscoveryMode;
query?: string;
beforeCursor?: string;
limit?: number;
}>;
export type ListChatMessageDiscoveryResult = Readonly<{
messages: readonly ChatMessageDiscoveryRecord[];
nextCursor: string | null;
}>;
type NormalizedInput = Readonly<{
mode: ChatMessageDiscoveryMode;
query: string;
beforeCursor: DiscoveryCursor | null;
limit: number;
filterKey: string;
}>;
type DiscoveryCursor = Readonly<{
mode: ChatMessageDiscoveryMode;
query: string;
createdAt: Date;
messageId: string;
}>;
type DiscoveryRow = Readonly<{
id: string;
chatId: string;
channelKind: ChatChannelKind;
channelName: string | null;
projectId: string | null;
authorUserId: string | null;
body: string;
parentMessageId: string | null;
createdAt: Date;
}>;
type ParticipantRow = Readonly<{
chatId: string;
userId: string;
displayName: string;
avatarUrl: string | null;
}>;
/**
* Finds user-authored messages only in active channels the viewer currently
* belongs to. The repository transaction re-reads RBAC and module access, and
* PostgreSQL RLS remains an independent tenant boundary underneath the query.
*/
export async function listChatMessageDiscovery(input: ListChatMessageDiscoveryInput): Promise<ListChatMessageDiscoveryResult> {
const normalized = normalizeInput(input);
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
if (normalized.mode === "search" && normalized.query.length === 0) {
return { messages: [], nextCursor: null };
}
const rows = await queryDiscoveryRows(tx, input, normalized);
const hasMore = rows.length > normalized.limit;
const pageRows = rows.slice(0, normalized.limit);
const participantsByChatId = groupParticipants(
await listParticipants(tx, input.tenantId, [...new Set(pageRows.map((row) => row.chatId))])
);
const messages = pageRows.map((row) => mapRow(row, participantsByChatId.get(row.chatId) ?? []));
const lastRow = pageRows.at(-1);
return {
messages,
nextCursor: hasMore && lastRow ? encodeCursor(normalized, lastRow) : null,
};
});
}
async function queryDiscoveryRows(
tx: DbTransactionClient,
context: Pick<ListChatMessageDiscoveryInput, "tenantId" | "userId">,
input: NormalizedInput
): Promise<DiscoveryRow[]> {
const hasCursor = input.beforeCursor !== null;
const cursorCreatedAt = input.beforeCursor?.createdAt ?? new Date(0);
const cursorMessageId = input.beforeCursor?.messageId ?? "cursor-placeholder";
const take = input.limit + 1;
if (input.mode === "mentions") {
return tx.$queryRaw<DiscoveryRow[]>`
SELECT message_row."id" AS "id",
message_row."chatId" AS "chatId",
channel_row."kind"::text AS "channelKind",
channel_row."name" AS "channelName",
channel_row."projektId" AS "projectId",
message_row."authorUserId" AS "authorUserId",
message_row."body" AS "body",
message_row."parentMessageId" AS "parentMessageId",
message_row."createdAt" AS "createdAt"
FROM "TeamChatMessage" AS message_row
INNER JOIN "TeamChat" AS channel_row
ON channel_row."tenantId" = message_row."tenantId"
AND channel_row."id" = message_row."chatId"
INNER JOIN "TeamChatMember" AS viewer_member
ON viewer_member."tenantId" = channel_row."tenantId"
AND viewer_member."chatId" = channel_row."id"
AND viewer_member."userId" = ${context.userId}
AND viewer_member."leftAt" IS NULL
WHERE message_row."tenantId" = ${context.tenantId}
AND channel_row."archivedAt" IS NULL
AND message_row."bodyFormat"::text = 'markdown'
AND message_row."deletedAt" IS NULL
AND message_row."authorUserId" IS NOT NULL
AND message_row."mentions" @> jsonb_build_array(
jsonb_build_object('type', 'user', 'id', ${context.userId}::text)
)
AND (
${hasCursor}::boolean = FALSE
OR (message_row."createdAt", message_row."id") < (${cursorCreatedAt}::timestamp(3), ${cursorMessageId}::text)
)
ORDER BY message_row."createdAt" DESC, message_row."id" DESC
LIMIT ${take}
FOR SHARE OF viewer_member
`;
}
const pattern = `%${escapeLikePattern(input.query)}%`;
return tx.$queryRaw<DiscoveryRow[]>`
SELECT message_row."id" AS "id",
message_row."chatId" AS "chatId",
channel_row."kind"::text AS "channelKind",
channel_row."name" AS "channelName",
channel_row."projektId" AS "projectId",
message_row."authorUserId" AS "authorUserId",
message_row."body" AS "body",
message_row."parentMessageId" AS "parentMessageId",
message_row."createdAt" AS "createdAt"
FROM "TeamChatMessage" AS message_row
INNER JOIN "TeamChat" AS channel_row
ON channel_row."tenantId" = message_row."tenantId"
AND channel_row."id" = message_row."chatId"
INNER JOIN "TeamChatMember" AS viewer_member
ON viewer_member."tenantId" = channel_row."tenantId"
AND viewer_member."chatId" = channel_row."id"
AND viewer_member."userId" = ${context.userId}
AND viewer_member."leftAt" IS NULL
WHERE message_row."tenantId" = ${context.tenantId}
AND channel_row."archivedAt" IS NULL
AND message_row."bodyFormat"::text = 'markdown'
AND message_row."deletedAt" IS NULL
AND message_row."authorUserId" IS NOT NULL
AND message_row."body" ILIKE ${pattern} ESCAPE '!'
AND (
${hasCursor}::boolean = FALSE
OR (message_row."createdAt", message_row."id") < (${cursorCreatedAt}::timestamp(3), ${cursorMessageId}::text)
)
ORDER BY message_row."createdAt" DESC, message_row."id" DESC
LIMIT ${take}
FOR SHARE OF viewer_member
`;
}
async function listParticipants(tx: DbTransactionClient, tenantId: string, chatIds: readonly string[]): Promise<ParticipantRow[]> {
if (chatIds.length === 0) return [];
return tx.$queryRaw<ParticipantRow[]>`
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_membership
ON participant_membership."tenantId" = participant."tenantId"
AND participant_membership."userId" = participant."userId"
AND participant_membership."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 normalizeInput(input: ListChatMessageDiscoveryInput): NormalizedInput {
try {
const mode = input.mode;
if (mode !== "search" && mode !== "mentions") throw new Error("mode is invalid");
if (input.query !== undefined && typeof input.query !== "string") throw new Error("query is invalid");
const query = (input.query ?? "").trim();
if (query.length > MAX_QUERY_LENGTH || query.includes("\0")) throw new Error("query is invalid");
if (mode === "mentions" && query.length > 0) throw new Error("mentions do not accept a query");
const limit = input.limit ?? DEFAULT_LIMIT;
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) throw new Error("limit is invalid");
const filterKey = `${mode}:${query}`;
const beforeCursor = input.beforeCursor ? decodeCursor(input.beforeCursor, filterKey) : null;
return { mode, query, limit, beforeCursor, filterKey };
} catch (error) {
if (error instanceof CatalogError) throw error;
throw new CatalogError(chatErrors.invalidInput);
}
}
function decodeCursor(value: string, expectedFilterKey: string): DiscoveryCursor {
if (typeof value !== "string" || value.length === 0 || value.length > MAX_CURSOR_LENGTH || value.includes("\0")) {
throw new Error("cursor is invalid");
}
const parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8")) as Record<string, unknown>;
const mode = parsed.mode;
const query = parsed.query;
const messageId = parsed.messageId;
const createdAtValue = parsed.createdAt;
if ((mode !== "search" && mode !== "mentions") || typeof query !== "string" || typeof messageId !== "string" || typeof createdAtValue !== "string") {
throw new Error("cursor is invalid");
}
const createdAt = new Date(createdAtValue);
if (!messageId || messageId.length > 500 || Number.isNaN(createdAt.getTime()) || `${mode}:${query}` !== expectedFilterKey) {
throw new Error("cursor is invalid");
}
return { mode, query, messageId, createdAt };
}
function encodeCursor(input: NormalizedInput, row: DiscoveryRow): string {
return Buffer.from(
JSON.stringify({ mode: input.mode, query: input.query, createdAt: row.createdAt.toISOString(), messageId: row.id }),
"utf8"
).toString("base64url");
}
function groupParticipants(rows: readonly ParticipantRow[]): Map<string, ChatParticipantProfileRecord[]> {
const grouped = new Map<string, ChatParticipantProfileRecord[]>();
for (const row of rows) {
const chatId = requiredText(row.chatId);
const userId = requiredText(row.userId);
const displayName = requiredText(row.displayName);
const avatarUrl = optionalText(row.avatarUrl);
const existing = grouped.get(chatId) ?? [];
existing.push({ userId, displayName, avatarUrl });
grouped.set(chatId, existing);
}
return grouped;
}
function mapRow(row: DiscoveryRow, participants: readonly ChatParticipantProfileRecord[]): ChatMessageDiscoveryRecord {
try {
if (!row.createdAt || Number.isNaN(row.createdAt.getTime())) throw new Error("createdAt is invalid");
if (row.channelKind !== "project" && row.channelKind !== "group" && row.channelKind !== "dm") throw new Error("kind is invalid");
return {
id: requiredText(row.id),
chatId: requiredText(row.chatId),
channelKind: row.channelKind,
channelName: optionalText(row.channelName),
projectId: optionalText(row.projectId),
authorUserId: requiredText(row.authorUserId),
body: requiredText(row.body),
parentMessageId: optionalText(row.parentMessageId),
createdAtIso: row.createdAt.toISOString(),
participants,
};
} catch {
throw new CatalogError(chatErrors.integrityFailure);
}
}
function requiredText(value: unknown): string {
if (typeof value !== "string") throw new Error("text is invalid");
const normalized = value.trim();
if (!normalized || normalized.includes("\0")) throw new Error("text is invalid");
return normalized;
}
function optionalText(value: unknown): string | null {
if (value === null || value === undefined) return null;
if (typeof value !== "string") throw new Error("text is invalid");
const normalized = value.trim();
return normalized || null;
}
function escapeLikePattern(value: string): string {
return value.replace(/[!%_]/g, (character) => `!${character}`);
}
@@ -0,0 +1,31 @@
import { describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ audit: vi.fn(), activity: vi.fn() }));
vi.mock("@hivegrid/db/audit-events.server", () => ({ publishAuditEventViaOutbox: mocks.audit }));
vi.mock("./mentions.server.js", () => ({ logChatMessageActivitiesWithTx: mocks.activity }));
import { publishTopLevelChatMessageEffectsWithTx } from "./message-effects.server.js";
describe("publishTopLevelChatMessageEffectsWithTx", () => {
it("publishes one audit record and delegates project/entity activities in the same transaction", async () => {
const tx = {};
const context = { tenantId: "tenant_1", userId: "user_1", permissions: ["chat.write"] } as const;
mocks.audit.mockResolvedValue(undefined);
mocks.activity.mockResolvedValue(undefined);
await publishTopLevelChatMessageEffectsWithTx(tx as never, context, {
channel: { id: "chat_1", kind: "project", isPrivate: true, projektId: "project_1", name: "P-100" },
messageId: "message_1",
requestId: "request_1",
body: "Hallo <@contact:contact_1>",
mentions: [{ type: "contact", id: "contact_1", label: "Anna" }],
});
expect(mocks.audit).toHaveBeenCalledWith(tx, expect.objectContaining({ action: "chat.message.created", requestId: "request_1" }));
expect(mocks.activity).toHaveBeenCalledWith(
tx,
context,
expect.objectContaining({ includeProjectChannelActivity: true, action: "message_created" })
);
});
});
@@ -0,0 +1,42 @@
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
import type { OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import type { ChatMention } from "@hivegrid/realtime";
import { logChatMessageActivitiesWithTx, type ChatMentionChannel } from "./mentions.server.js";
import type { ChatRepositoryContext } from "./types.js";
/** Cross-cutting effects for one newly persisted top-level Markdown message. */
export async function publishTopLevelChatMessageEffectsWithTx(
tx: DbTransactionClient,
context: ChatRepositoryContext,
input: Readonly<{
channel: ChatMentionChannel;
messageId: string;
requestId: string;
body: string;
mentions: readonly ChatMention[];
}>
): Promise<void> {
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId: context.tenantId,
actorId: context.userId,
actorType: "user",
action: "chat.message.created",
targetType: "TeamChatMessage",
targetId: input.messageId,
requestId: input.requestId,
sourceModule: "chat",
dataSensitivity: "internal",
metadata: { chatId: input.channel.id },
summaryText: "Eine Chat-Nachricht wurde erstellt.",
});
await logChatMessageActivitiesWithTx(tx, context, {
channel: input.channel,
messageId: input.messageId,
body: input.body,
mentions: input.mentions,
includeProjectChannelActivity: true,
action: "message_created",
});
}
@@ -0,0 +1,149 @@
// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_A = "chat_feature_rls_tenant_a";
const TENANT_B = "chat_feature_rls_tenant_b";
const USER_A = "chat_feature_rls_user_a";
const USER_B = "chat_feature_rls_user_b";
const CHAT_A = "chat_feature_rls_chat_a";
const CHAT_B = "chat_feature_rls_chat_b";
const MESSAGE_A = "chat_feature_rls_message_a";
const MESSAGE_B = "chat_feature_rls_message_b";
describeIfDatabase("chat message features with the restricted app role", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
beforeAll(async () => {
await cleanup(admin);
await admin.user.createMany({
data: [
{ id: USER_A, email: "chat-feature-rls-a@example.test", firstName: "Feature", lastName: "A", active: true },
{ id: USER_B, email: "chat-feature-rls-b@example.test", firstName: "Feature", lastName: "B", active: true },
],
});
await admin.tenant.createMany({
data: [
{ id: TENANT_A, slug: TENANT_A, name: "Chat feature A", active: true },
{ id: TENANT_B, slug: TENANT_B, name: "Chat feature B", active: true },
],
});
await admin.tenantUser.createMany({
data: [
{ id: "chat_feature_rls_membership_a", tenantId: TENANT_A, userId: USER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_feature_rls_membership_b", tenantId: TENANT_B, userId: USER_B, type: 0, joined: 1, status: 2 },
],
});
await admin.teamChat.createMany({
data: [
{ id: CHAT_A, tenantId: TENANT_A, createdByUserId: USER_A, kind: "group", name: "A", eventStreamId: "chat_feature_rls_stream_a" },
{ id: CHAT_B, tenantId: TENANT_B, createdByUserId: USER_B, kind: "group", name: "B", eventStreamId: "chat_feature_rls_stream_b" },
],
});
await admin.teamChatMember.createMany({
data: [
{ id: "chat_feature_rls_chat_member_a", tenantId: TENANT_A, chatId: CHAT_A, userId: USER_A, notificationPref: "all_messages" },
{ id: "chat_feature_rls_chat_member_b", tenantId: TENANT_B, chatId: CHAT_B, userId: USER_B, notificationPref: "all_messages" },
],
});
await admin.teamChatMessage.createMany({
data: [
{
id: MESSAGE_A,
tenantId: TENANT_A,
chatId: CHAT_A,
authorUserId: USER_A,
clientMessageId: "chat-feature-rls-message-a",
body: "A",
mentions: [],
linkPreviews: [],
},
{
id: MESSAGE_B,
tenantId: TENANT_B,
chatId: CHAT_B,
authorUserId: USER_B,
clientMessageId: "chat-feature-rls-message-b",
body: "B",
mentions: [],
linkPreviews: [],
},
],
});
});
afterAll(async () => {
await cleanup(admin);
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("permits same-tenant features and rejects cross-tenant message targets", async () => {
await expect(app.teamChatReaction.findMany({ where: { messageId: MESSAGE_A } })).resolves.toEqual([]);
const created = await runWithRlsContext({ tenantId: TENANT_A, userId: USER_A }, () =>
app.$transaction(async (tx) => {
const reaction = await tx.teamChatReaction.create({
data: { id: "chat_feature_rls_reaction_a", tenantId: TENANT_A, messageId: MESSAGE_A, userId: USER_A, emoji: "👍" },
select: { id: true },
});
const pin = await tx.teamChatPinnedMessage.create({
data: { id: "chat_feature_rls_pin_a", tenantId: TENANT_A, chatId: CHAT_A, messageId: MESSAGE_A, pinnedByUserId: USER_A },
select: { id: true },
});
const thread = await tx.teamChatThread.create({
data: {
id: MESSAGE_A,
tenantId: TENANT_A,
chatId: CHAT_A,
parentMessageId: MESSAGE_A,
createdByUserId: USER_A,
lastReplyAt: new Date("2026-07-16T08:00:00.000Z"),
replyCount: 0,
participantUserIds: [],
},
select: { id: true },
});
return { reaction, pin, thread };
})
);
expect(created).toEqual({
reaction: { id: "chat_feature_rls_reaction_a" },
pin: { id: "chat_feature_rls_pin_a" },
thread: { id: MESSAGE_A },
});
await expect(
runWithRlsContext({ tenantId: TENANT_A, userId: USER_A }, () =>
app.teamChatReaction.create({
data: { id: "chat_feature_rls_cross_reaction", tenantId: TENANT_A, messageId: MESSAGE_B, userId: USER_A, emoji: "🎉" },
})
)
).rejects.toThrow();
await expect(
runWithRlsContext({ tenantId: TENANT_A, userId: USER_A }, () =>
app.teamChatPinnedMessage.create({
data: { id: "chat_feature_rls_cross_pin", tenantId: TENANT_A, chatId: CHAT_A, messageId: MESSAGE_B, pinnedByUserId: USER_A },
})
)
).rejects.toThrow();
await expect(admin.teamChatReaction.count({ where: { id: "chat_feature_rls_cross_reaction" } })).resolves.toBe(0);
await expect(admin.teamChatPinnedMessage.count({ where: { id: "chat_feature_rls_cross_pin" } })).resolves.toBe(0);
});
});
async function cleanup(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.teamChatReaction.deleteMany({ where: { id: { in: ["chat_feature_rls_reaction_a", "chat_feature_rls_cross_reaction"] } } });
await admin.teamChatPinnedMessage.deleteMany({ where: { id: { in: ["chat_feature_rls_pin_a", "chat_feature_rls_cross_pin"] } } });
await admin.teamChatThread.deleteMany({ where: { id: MESSAGE_A } });
await admin.teamChatMessage.deleteMany({ where: { id: { in: [MESSAGE_A, MESSAGE_B] } } });
await admin.teamChatMember.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.teamChat.deleteMany({ where: { id: { in: [CHAT_A, CHAT_B] } } });
await admin.tenantUser.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.tenant.deleteMany({ where: { id: { in: [TENANT_A, TENANT_B] } } });
await admin.user.deleteMany({ where: { id: { in: [USER_A, USER_B] } } });
}
@@ -0,0 +1,445 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
getMemberChannelDetail: vi.fn(),
runChatRepositoryTransaction: vi.fn(),
publishWakeup: vi.fn(),
publishLinkPreviewRequest: vi.fn(),
publishAudit: vi.fn(),
logActivity: vi.fn(),
}));
vi.mock("./repository.server.js", () => ({
getMemberChannelDetail: mocks.getMemberChannelDetail,
runChatRepositoryTransaction: mocks.runChatRepositoryTransaction,
}));
vi.mock("./realtime-wakeup.server.js", () => ({ publishChatPersistentRealtimeWakeup: mocks.publishWakeup }));
vi.mock("./link-preview.server.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("./link-preview.server.js")>();
return { ...actual, publishChatLinkPreviewRequest: (...args: unknown[]) => mocks.publishLinkPreviewRequest(...args) };
});
vi.mock("@hivegrid/db/audit-events.server", () => ({ publishAuditEventViaOutbox: mocks.publishAudit }));
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
import { CHAT_PERMISSIONS } from "./permissions.js";
import { sendChatThreadReply, setChatMessagePin, setChatReaction } from "./message-features.server.js";
const context = {
tenantId: "tenant_1",
userId: "user_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.write],
} as const;
function eventRow(input: {
type: "message_pin_changed" | "reaction_added" | "reaction_removed" | "thread_reply";
requestId: string;
data: unknown;
entityId?: string;
}) {
return {
sequence: 12n,
occurredAt: new Date("2026-07-16T09:00:00.000Z"),
tenantId: context.tenantId,
chatId: "chat_1",
type: input.type,
actorUserId: context.userId,
entityId: input.entityId ?? "message_1",
requestId: input.requestId,
data: input.data,
};
}
function messageRow(overrides: Record<string, unknown> = {}) {
return {
id: "message_1",
createdAt: new Date("2026-07-16T08:00:00.000Z"),
updatedAt: new Date("2026-07-16T08:00:00.000Z"),
tenantId: context.tenantId,
chatId: "chat_1",
authorUserId: context.userId,
clientMessageId: "client_parent",
body: "Parent",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [],
linkPreviews: [],
editedAt: null,
deletedAt: null,
systemEventKind: null,
systemEventMetadata: null,
...overrides,
};
}
function txFixture() {
return {
$executeRaw: vi.fn().mockResolvedValue(1),
$queryRaw: vi.fn().mockResolvedValue([{ id: "membership_1", roleInChat: "member" }]),
teamChat: {
findFirst: vi.fn().mockResolvedValue({
id: "chat_1",
kind: "group",
name: "Team",
isPrivate: false,
eventStreamId: "stream_1",
projektId: null,
}),
update: vi.fn().mockResolvedValue({ id: "chat_1" }),
},
tenant: { findUnique: vi.fn().mockResolvedValue({ slug: "demo" }) },
teamChatMember: { findMany: vi.fn().mockResolvedValue([]) },
tenantUser: { findMany: vi.fn().mockResolvedValue([]) },
userRole: { findMany: vi.fn().mockResolvedValue([]) },
groupUser: { findMany: vi.fn().mockResolvedValue([]) },
notificationDelivery: { upsert: vi.fn(), create: vi.fn() },
teamChatMessage: {
findFirst: vi.fn().mockResolvedValue({ id: "message_1", authorUserId: context.userId }),
create: vi.fn(),
findMany: vi.fn().mockResolvedValue([]),
},
teamChatEvent: { findFirst: vi.fn().mockResolvedValue(null), create: vi.fn() },
teamChatPinnedMessage: { findFirst: vi.fn().mockResolvedValue(null), create: vi.fn(), delete: vi.fn(), findMany: vi.fn() },
teamChatReaction: { findFirst: vi.fn().mockResolvedValue(null), create: vi.fn(), delete: vi.fn(), findMany: vi.fn(), count: vi.fn().mockResolvedValue(0) },
teamChatThread: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn(), findMany: vi.fn() },
};
}
describe("chat message feature mutations", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.publishWakeup.mockResolvedValue(undefined);
mocks.publishLinkPreviewRequest.mockResolvedValue(undefined);
mocks.publishAudit.mockResolvedValue(undefined);
mocks.logActivity.mockResolvedValue(undefined);
});
it("rechecks chat.write through the shared atomic repository gate", async () => {
const tx = txFixture();
tx.teamChatEvent.create.mockResolvedValue(
eventRow({
type: "reaction_added",
requestId: "request_reaction",
data: {
reaction: { id: "reaction_1", messageId: "message_1", userId: context.userId, emoji: "👍", reactedAt: "2026-07-16T09:00:00.000Z" },
},
})
);
tx.teamChatReaction.create.mockResolvedValue({ id: "reaction_1", reactedAt: new Date("2026-07-16T09:00:00.000Z") });
mocks.runChatRepositoryTransaction.mockImplementation(async (_input, permission, operation) => {
expect(permission).toBe(CHAT_PERMISSIONS.write);
return operation(tx, [CHAT_PERMISSIONS.write]);
});
const result = await setChatReaction({ ...context, requestId: "request_reaction", chatId: "chat_1", messageId: "message_1", emoji: "👍", active: true });
expect(result).toMatchObject({ changed: true, replayed: false, active: true });
expect(mocks.publishWakeup).toHaveBeenCalledWith(tx, { event: result.event });
expect(mocks.publishAudit).toHaveBeenCalledWith(
tx,
expect.objectContaining({
action: "chat.message.reaction_added",
targetId: "message_1",
requestId: "request_reaction",
metadata: { chatId: "chat_1", emoji: "👍" },
})
);
});
it("rejects text disguised as an emoji before opening the repository transaction", async () => {
await expect(
setChatReaction({ ...context, requestId: "request_reaction", chatId: "chat_1", messageId: "message_1", emoji: "👍oops", active: true })
).rejects.toMatchObject({ code: "chat.invalid_input" });
expect(mocks.runChatRepositoryTransaction).not.toHaveBeenCalled();
});
it("strictly rejects pins in direct messages before touching a message", async () => {
const tx = txFixture();
tx.teamChat.findFirst.mockResolvedValue({ kind: "dm", eventStreamId: "stream_1" });
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
await expect(setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true })).rejects.toMatchObject({
code: "chat.pins_not_allowed_in_direct_messages",
});
expect(tx.teamChatMessage.findFirst).not.toHaveBeenCalled();
expect(tx.teamChatPinnedMessage.create).not.toHaveBeenCalled();
});
it("rejects a ninth distinct reaction for one user and message", async () => {
const tx = txFixture();
tx.teamChatReaction.count.mockResolvedValue(8);
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
await expect(
setChatReaction({ ...context, requestId: "request_reaction", chatId: "chat_1", messageId: "message_1", emoji: "👍", active: true })
).rejects.toMatchObject({ code: "chat.reaction_limit_reached" });
expect(tx.teamChatReaction.create).not.toHaveBeenCalled();
});
it("hides pinning from members who neither authored the message nor administer the channel", async () => {
const tx = txFixture();
tx.teamChatMessage.findFirst.mockResolvedValue({ id: "message_1", authorUserId: "user_2" });
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
await expect(setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true })).rejects.toMatchObject({
code: "foundation.not_found",
});
expect(tx.teamChatPinnedMessage.create).not.toHaveBeenCalled();
});
it("enforces the 50-pin channel limit while holding row locks", async () => {
const tx = txFixture();
tx.$queryRaw.mockResolvedValueOnce([{ id: "membership_1" }]).mockResolvedValueOnce(Array.from({ length: 50 }, (_, index) => ({ id: `pin_${index}` })));
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
await expect(setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true })).rejects.toMatchObject({
code: "chat.pin_limit_reached",
});
expect(tx.teamChatPinnedMessage.create).not.toHaveBeenCalled();
});
it("replays an identical pin request without a second write or audit", async () => {
const tx = txFixture();
tx.teamChatEvent.findFirst.mockResolvedValue(
eventRow({
type: "message_pin_changed",
requestId: "request_pin",
data: { messageId: "message_1", pinned: true, changedByUserId: context.userId },
})
);
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
const result = await setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true });
expect(result).toMatchObject({ pinned: true, replayed: true, changed: false });
expect(tx.teamChatPinnedMessage.create).not.toHaveBeenCalled();
expect(mocks.publishAudit).not.toHaveBeenCalled();
});
it("rejects request-id payload drift", async () => {
const tx = txFixture();
tx.teamChatEvent.findFirst.mockResolvedValue(
eventRow({
type: "message_pin_changed",
requestId: "request_pin",
data: { messageId: "message_other", pinned: true, changedByUserId: context.userId },
})
);
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
await expect(setChatMessagePin({ ...context, requestId: "request_pin", chatId: "chat_1", messageId: "message_1", pinned: true })).rejects.toMatchObject({
code: "foundation.idempotency_conflict",
});
});
it("creates exactly one level of replies and publishes the durable thread event atomically", async () => {
const tx = txFixture();
tx.teamChatMessage.findFirst.mockResolvedValueOnce(messageRow()).mockResolvedValueOnce(null);
tx.teamChatMessage.create.mockResolvedValue(messageRow({ id: "reply_1", clientMessageId: "client_reply", body: "Reply", parentMessageId: "message_1" }));
tx.teamChatThread.findFirst.mockResolvedValue(null);
tx.teamChatThread.create.mockResolvedValue({
id: "message_1",
parentMessageId: "message_1",
replyCount: 1,
lastReplyAt: new Date("2026-07-16T08:00:00.000Z"),
participantUserIds: [context.userId],
});
tx.teamChatEvent.create.mockImplementation(({ data }) =>
eventRow({ type: "thread_reply", requestId: "request_reply", data: data.data, entityId: "reply_1" })
);
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
const result = await sendChatThreadReply({
...context,
requestId: "request_reply",
chatId: "chat_1",
threadId: "message_1",
clientMessageId: "client_reply",
body: "Reply",
});
expect(tx.teamChatMessage.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ parentMessageId: "message_1" }) }));
expect(result).toMatchObject({ threadId: "message_1", replayed: false });
expect(mocks.publishWakeup).toHaveBeenCalledWith(tx, { event: result.event });
expect(mocks.publishAudit).toHaveBeenCalledWith(
tx,
expect.objectContaining({ action: "chat.thread.reply_created", targetId: "reply_1", requestId: "request_reply" })
);
});
it("keeps a deleted thread starter readable as a tombstone and accepts new replies", async () => {
const tx = txFixture();
const deletedAt = new Date("2026-07-16T08:30:00.000Z");
tx.teamChatMessage.findFirst
.mockResolvedValueOnce(messageRow({ body: "", deletedAt, authorUserId: "user_parent" }))
.mockResolvedValueOnce(null);
tx.teamChatMessage.create.mockResolvedValue(
messageRow({ id: "reply_after_delete", clientMessageId: "client_after_delete", body: "Weiter im Thread", parentMessageId: "message_1" })
);
tx.teamChatThread.findFirst.mockResolvedValue({ id: "message_1", participantUserIds: ["user_parent"] });
tx.teamChatThread.update.mockResolvedValue({
id: "message_1",
parentMessageId: "message_1",
replyCount: 2,
lastReplyAt: new Date("2026-07-16T09:00:00.000Z"),
participantUserIds: [context.userId, "user_parent"],
});
tx.teamChatEvent.create.mockImplementation(({ data }) =>
eventRow({ type: "thread_reply", requestId: "request_after_delete", data: data.data, entityId: "reply_after_delete" })
);
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
const result = await sendChatThreadReply({
...context,
requestId: "request_after_delete",
chatId: "chat_1",
threadId: "message_1",
clientMessageId: "client_after_delete",
body: "Weiter im Thread",
});
const parentLookup = tx.teamChatMessage.findFirst.mock.calls[0]?.[0];
expect(parentLookup).toEqual(
expect.objectContaining({
where: expect.objectContaining({ chatId: "chat_1", parentMessageId: null, OR: [{ id: "message_1" }, { thread: { id: "message_1" } }] }),
})
);
expect(parentLookup.where).not.toHaveProperty("deletedAt");
expect(tx.teamChatMessage.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ parentMessageId: "message_1", body: "Weiter im Thread" }) })
);
expect(result).toMatchObject({ threadId: "message_1", replayed: false, message: { id: "reply_after_delete" } });
});
it("persists mentioned followers and lets direct mentions, but not ordinary replies, bypass mute", async () => {
const tx = txFixture();
tx.teamChat.findFirst.mockResolvedValue({
id: "chat_1",
kind: "project",
name: "P-100",
isPrivate: true,
eventStreamId: "stream_1",
projektId: "project_1",
});
tx.teamChatMessage.findFirst.mockResolvedValueOnce(messageRow({ authorUserId: "user_parent" })).mockResolvedValueOnce(null);
tx.teamChatMessage.create.mockResolvedValue(
messageRow({ id: "reply_1", clientMessageId: "client_reply", body: "Hallo <@user:user_mentioned>", parentMessageId: "message_1" })
);
tx.teamChatThread.findFirst.mockResolvedValue({ id: "message_1", participantUserIds: ["user_previous", "user_hidden"] });
tx.teamChatThread.update.mockResolvedValue({
id: "message_1",
parentMessageId: "message_1",
replyCount: 2,
lastReplyAt: new Date("2026-07-16T08:00:00.000Z"),
participantUserIds: [context.userId, "user_hidden", "user_mentioned", "user_parent", "user_previous"],
});
tx.teamChatMember.findMany
.mockResolvedValueOnce([{ userId: "user_mentioned" }])
.mockResolvedValueOnce([
{ userId: "user_parent", notificationPref: "all_messages" },
{ userId: "user_previous", notificationPref: "muted" },
{ userId: "user_mentioned", notificationPref: "muted" },
]);
tx.tenantUser.findMany.mockResolvedValue([
{ userId: "user_mentioned", user: { firstName: "Mia", lastName: "Mention", email: "mia@example.test" } },
]);
tx.teamChatEvent.create.mockImplementation(({ data }) =>
eventRow({ type: "thread_reply", requestId: "request_reply", data: data.data, entityId: "reply_1" })
);
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
await sendChatThreadReply({
...context,
requestId: "request_reply",
chatId: "chat_1",
threadId: "message_1",
clientMessageId: "client_reply",
body: "Hallo <@user:user_mentioned>",
});
expect(tx.teamChatThread.update).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ participantUserIds: [context.userId, "user_hidden", "user_mentioned", "user_parent", "user_previous"] }),
})
);
expect(tx.teamChatMember.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ tenantId: context.tenantId, chatId: "chat_1", leftAt: null }),
})
);
expect(tx.notificationDelivery.upsert).toHaveBeenCalledTimes(2);
expect(tx.notificationDelivery.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({
userId: "user_parent",
channel: "IN_APP",
messageKey: "chat.notifications.threadReply",
payloadMetadata: {
deeplink: "/demo/chat/chat_1/thread/message_1?message=reply_1#message-reply_1",
chatId: "chat_1",
threadId: "message_1",
messageId: "reply_1",
},
}),
})
);
expect(tx.notificationDelivery.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({
userId: "user_mentioned",
messageKey: "chat.notifications.mentioned",
}),
})
);
expect(tx.notificationDelivery.upsert).not.toHaveBeenCalledWith(expect.objectContaining({ create: expect.objectContaining({ userId: context.userId }) }));
expect(tx.notificationDelivery.upsert).not.toHaveBeenCalledWith(expect.objectContaining({ create: expect.objectContaining({ userId: "user_hidden" }) }));
expect(tx.notificationDelivery.upsert).not.toHaveBeenCalledWith(expect.objectContaining({ create: expect.objectContaining({ userId: "user_previous" }) }));
expect(mocks.logActivity).toHaveBeenCalledWith(expect.objectContaining({ activityType: "chat_message", subjectType: "project", subjectId: "project_1" }), {
client: tx,
});
});
it("lets direct-message thread replies bypass a muted channel preference", async () => {
const tx = txFixture();
tx.teamChat.findFirst.mockResolvedValue({
id: "chat_1",
kind: "dm",
name: null,
isPrivate: true,
eventStreamId: "stream_1",
projektId: null,
});
tx.teamChatMessage.findFirst.mockResolvedValueOnce(messageRow({ authorUserId: "user_parent" })).mockResolvedValueOnce(null);
tx.teamChatMessage.create.mockResolvedValue(
messageRow({ id: "reply_dm", clientMessageId: "client_reply_dm", body: "Reply", parentMessageId: "message_1" })
);
tx.teamChatThread.findFirst.mockResolvedValue({ id: "message_1", participantUserIds: ["user_parent"] });
tx.teamChatThread.update.mockResolvedValue({
id: "message_1",
parentMessageId: "message_1",
replyCount: 2,
lastReplyAt: new Date("2026-07-16T08:00:00.000Z"),
participantUserIds: [context.userId, "user_parent"],
});
tx.teamChatMember.findMany.mockResolvedValue([{ userId: "user_parent", notificationPref: "muted" }]);
tx.teamChatEvent.create.mockImplementation(({ data }) =>
eventRow({ type: "thread_reply", requestId: "request_dm_reply", data: data.data, entityId: "reply_dm" })
);
mocks.runChatRepositoryTransaction.mockImplementation((_input, _permission, operation) => operation(tx, [CHAT_PERMISSIONS.write]));
await sendChatThreadReply({
...context,
requestId: "request_dm_reply",
chatId: "chat_1",
threadId: "message_1",
clientMessageId: "client_reply_dm",
body: "Reply",
});
expect(tx.notificationDelivery.upsert).toHaveBeenCalledOnce();
expect(tx.notificationDelivery.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({ userId: "user_parent", messageKey: "chat.notifications.directMessage" }),
})
);
});
});
@@ -0,0 +1,832 @@
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, notify, withTenantScope } from "@hivegrid/foundation";
import {
CHAT_EVENT_NAMES,
CHAT_MESSAGE_MAX_BODY_LENGTH,
CHAT_THREAD_MAX_PARTICIPANTS,
isPersistentChatEvent,
validateChatServerEvent,
type ChatPersistentEvent,
type ChatRealtimeMessage,
type ChatRealtimeThread,
} from "@hivegrid/realtime";
import { toChatPersistentEventName, toPersistedChatEventType } from "./event-type-mapping.js";
import { buildChatMessageDeepLink } from "./deep-links.js";
import { chatErrors } from "./errors.js";
import { extractChatLinkPreviewPlaceholders, publishChatLinkPreviewRequest } from "./link-preview.server.js";
import { logChatMessageActivitiesWithTx, resolveChatMentionsInBodyWithTx } from "./mentions.server.js";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { getMemberChannelDetail, listMessageAttachmentRecords, runChatRepositoryTransaction } from "./repository.server.js";
import { publishChatPersistentRealtimeWakeup } from "./realtime-wakeup.server.js";
import type {
ChatMessageFeatureRecord,
ChatPinnedMessageRecord,
ChatRepositoryContext,
ChatThreadDetailRecord,
ChatThreadRecord,
GetChatThreadDetailInput,
ListChatPinnedMessagesInput,
ListChatPinnedMessagesResult,
SendChatThreadReplyInput,
SendChatThreadReplyResult,
SetChatMessagePinInput,
SetChatMessagePinResult,
SetChatReactionInput,
SetChatReactionResult,
} from "./types.js";
const CHAT_EVENT_LOCK_SALT = 15_015;
const CHAT_PIN_LIMIT = 50;
const CHAT_REACTION_LIMIT = 8;
const MAX_IDENTIFIER_LENGTH = 500;
const MAX_REQUEST_ID_LENGTH = 500;
const MAX_EMOJI_LENGTH = 16;
const EMOJI_SEGMENTER = new Intl.Segmenter("und", { granularity: "grapheme" });
const 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;
const EVENT_SELECT = {
sequence: true,
occurredAt: true,
tenantId: true,
chatId: true,
type: true,
actorUserId: true,
entityId: true,
requestId: true,
data: true,
} as const satisfies Prisma.TeamChatEventSelect;
type MessageRow = Prisma.TeamChatMessageGetPayload<{ select: typeof MESSAGE_SELECT }>;
type EventRow = Prisma.TeamChatEventGetPayload<{ select: typeof EVENT_SELECT }>;
export async function getChatThreadDetail(input: GetChatThreadDetailInput): Promise<ChatThreadDetailRecord> {
const chatId = normalizeIdentifier(input.chatId, "chatId");
const threadId = normalizeIdentifier(input.threadId, "threadId");
const channelDetail = await getMemberChannelDetail({ ...input, chatId, messageLimit: 1 });
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
await lockActiveMembership(tx, input, chatId, false);
const parent = await requireThreadParent(tx, input, chatId, threadId);
const persistedThread = await tx.teamChatThread.findFirst({
where: withTenantScope(input.tenantId, { chatId, parentMessageId: parent.id }),
select: { id: true, parentMessageId: true, replyCount: true, lastReplyAt: true, participantUserIds: true },
});
const replies = await tx.teamChatMessage.findMany({
where: withTenantScope(input.tenantId, { chatId, parentMessageId: parent.id }),
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
select: MESSAGE_SELECT,
});
const messageIds = [parent.id, ...replies.map((reply) => reply.id)];
const [features, attachments] = await Promise.all([
listFeatures(tx, input, chatId, messageIds),
listMessageAttachmentRecords(tx, input.tenantId, messageIds),
]);
const thread = persistedThread
? mapThread(persistedThread)
: {
id: parent.id,
parentMessageId: parent.id,
replyCount: 0,
lastReplyAtIso: parent.createdAt.toISOString(),
participantUserIds: [],
};
return {
channel: channelDetail.channel,
parentMessage: mapMessage(parent),
replies: replies.map(mapMessage),
thread,
messageFeatures: features,
attachments,
};
});
}
export async function sendChatThreadReply(input: SendChatThreadReplyInput): Promise<SendChatThreadReplyResult> {
const normalized = {
chatId: normalizeIdentifier(input.chatId, "chatId"),
threadId: normalizeIdentifier(input.threadId, "threadId"),
clientMessageId: normalizeIdentifier(input.clientMessageId, "clientMessageId"),
requestId: normalizeRequestId(input.requestId),
body: normalizeBody(input.body),
};
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.write, async (tx, currentPermissions) => {
await lockFeatureStream(tx, input.tenantId, normalized.chatId);
await lockActiveMembership(tx, input, normalized.chatId, true);
const channel = await requireWritableChannel(tx, input, normalized.chatId);
const parent = await requireThreadParent(tx, input, normalized.chatId, normalized.threadId);
const replayEvent = await findRequestEvent(tx, input, normalized.chatId, normalized.requestId);
if (replayEvent) {
const event = mapEvent(replayEvent, channel.eventStreamId);
if (
event.event !== CHAT_EVENT_NAMES.threadReply ||
event.data.thread.parentMessageId !== parent.id ||
event.data.message.clientMessageId !== normalized.clientMessageId ||
event.data.message.body !== normalized.body
) {
throw new CatalogError(foundationErrors.idempotencyConflict);
}
return { threadId: event.data.thread.id, message: event.data.message, event, replayed: true };
}
const existingMessage = await tx.teamChatMessage.findFirst({
where: withTenantScope(input.tenantId, { authorUserId: input.userId, clientMessageId: normalized.clientMessageId }),
select: MESSAGE_SELECT,
});
if (existingMessage) {
if (
existingMessage.chatId !== normalized.chatId ||
existingMessage.parentMessageId !== parent.id ||
existingMessage.bodyFormat !== "markdown" ||
existingMessage.body !== normalized.body
) {
throw new CatalogError(foundationErrors.idempotencyConflict);
}
throw new CatalogError(chatErrors.integrityFailure);
}
const mentions = await resolveChatMentionsInBodyWithTx(tx, input, channel, normalized.body, currentPermissions);
const message = await tx.teamChatMessage.create({
data: withTenantScope(input.tenantId, {
chatId: normalized.chatId,
authorUserId: input.userId,
clientMessageId: normalized.clientMessageId,
body: normalized.body,
bodyFormat: "markdown",
parentMessageId: parent.id,
mentions: mentions as unknown as Prisma.InputJsonValue,
linkPreviews: extractChatLinkPreviewPlaceholders(normalized.body) as unknown as Prisma.InputJsonValue,
}),
select: MESSAGE_SELECT,
});
const previousThread = await tx.teamChatThread.findFirst({
where: withTenantScope(input.tenantId, { chatId: normalized.chatId, parentMessageId: parent.id }),
select: { id: true, participantUserIds: true },
});
const participantUserIds = uniqueBoundedParticipants([
...(parent.authorUserId ? [parent.authorUserId] : []),
...(previousThread?.participantUserIds ?? []),
...mentions.filter((mention) => mention.type === "user").map((mention) => mention.id),
input.userId,
]);
const threadRow = previousThread
? await tx.teamChatThread.update({
where: { id: previousThread.id },
data: { lastReplyAt: message.createdAt, replyCount: { increment: 1 }, participantUserIds },
select: { id: true, parentMessageId: true, replyCount: true, lastReplyAt: true, participantUserIds: true },
})
: await tx.teamChatThread.create({
data: withTenantScope(input.tenantId, {
id: parent.id,
chatId: normalized.chatId,
parentMessageId: parent.id,
createdByUserId: input.userId,
lastReplyAt: message.createdAt,
replyCount: 1,
participantUserIds,
}),
select: { id: true, parentMessageId: true, replyCount: true, lastReplyAt: true, participantUserIds: true },
});
await tx.teamChat.update({ where: { id: normalized.chatId }, data: { lastMessageAt: message.createdAt }, select: { id: true } });
const realtimeMessage = mapMessage(message);
const thread = mapThread(threadRow);
const realtimeThread = mapRealtimeThread(threadRow);
const eventRow = await tx.teamChatEvent.create({
data: withTenantScope(input.tenantId, {
chatId: normalized.chatId,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.threadReply),
actorUserId: input.userId,
entityId: message.id,
requestId: normalized.requestId,
data: { thread: realtimeThread, message: realtimeMessage } as unknown as Prisma.InputJsonValue,
}),
select: EVENT_SELECT,
});
const event = mapEvent(eventRow, channel.eventStreamId);
if (event.event !== CHAT_EVENT_NAMES.threadReply) throw new CatalogError(chatErrors.integrityFailure);
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event });
await publishChatLinkPreviewRequest(tx as unknown as OutboxPublisherTransaction, {
tenantId: input.tenantId,
chatId: normalized.chatId,
messageId: message.id,
requestId: normalized.requestId,
body: normalized.body,
});
await publishThreadReplyAudit(tx, input, {
chatId: normalized.chatId,
threadId: thread.id,
messageId: message.id,
requestId: normalized.requestId,
});
await logChatMessageActivitiesWithTx(tx, input, {
channel,
messageId: message.id,
body: normalized.body,
mentions,
includeProjectChannelActivity: true,
action: "thread_reply_created",
});
await notifyThreadReplyRecipients(tx, input, {
chatId: normalized.chatId,
threadId: thread.id,
messageId: message.id,
participantUserIds,
mentionedUserIds: mentions.filter((mention) => mention.type === "user").map((mention) => mention.id),
channelKind: channel.kind,
});
return { threadId: thread.id, message: realtimeMessage, event, replayed: false };
});
}
export async function setChatReaction(input: SetChatReactionInput): Promise<SetChatReactionResult> {
const normalized = {
chatId: normalizeIdentifier(input.chatId, "chatId"),
messageId: normalizeIdentifier(input.messageId, "messageId"),
requestId: normalizeRequestId(input.requestId),
emoji: normalizeEmoji(input.emoji),
active: normalizeBoolean(input.active, "active"),
};
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.write, async (tx) => {
await lockFeatureStream(tx, input.tenantId, normalized.chatId);
await lockActiveMembership(tx, input, normalized.chatId, true);
const channel = await requireWritableChannel(tx, input, normalized.chatId);
await requireVisibleMessage(tx, input, normalized.chatId, normalized.messageId);
const replayEvent = await findRequestEvent(tx, input, normalized.chatId, normalized.requestId);
if (replayEvent) {
const event = mapEvent(replayEvent, channel.eventStreamId);
const matches =
normalized.active && event.event === CHAT_EVENT_NAMES.reactionAdded
? event.data.reaction.messageId === normalized.messageId &&
event.data.reaction.userId === input.userId &&
event.data.reaction.emoji === normalized.emoji
: !normalized.active && event.event === CHAT_EVENT_NAMES.reactionRemoved
? event.data.messageId === normalized.messageId && event.data.userId === input.userId && event.data.emoji === normalized.emoji
: false;
if (!matches) throw new CatalogError(foundationErrors.idempotencyConflict);
return { ...normalized, changed: false, replayed: true, event };
}
const existing = await tx.teamChatReaction.findFirst({
where: withTenantScope(input.tenantId, { messageId: normalized.messageId, userId: input.userId, emoji: normalized.emoji }),
select: { id: true, reactedAt: true },
});
let changed = false;
let eventData: Prisma.InputJsonObject;
let eventName: typeof CHAT_EVENT_NAMES.reactionAdded | typeof CHAT_EVENT_NAMES.reactionRemoved;
if (normalized.active) {
if (!existing) {
const reactionCount = await tx.teamChatReaction.count({
where: withTenantScope(input.tenantId, {
messageId: normalized.messageId,
userId: input.userId,
}),
});
if (reactionCount >= CHAT_REACTION_LIMIT) {
throw new CatalogError(chatErrors.reactionLimitReached, { limit: CHAT_REACTION_LIMIT });
}
}
const reaction = existing
? { id: existing.id, reactedAt: existing.reactedAt }
: await tx.teamChatReaction.create({
data: withTenantScope(input.tenantId, { messageId: normalized.messageId, userId: input.userId, emoji: normalized.emoji }),
select: { id: true, reactedAt: true },
});
changed = existing === null;
eventName = CHAT_EVENT_NAMES.reactionAdded;
eventData = {
reaction: {
id: reaction.id,
messageId: normalized.messageId,
userId: input.userId,
emoji: normalized.emoji,
reactedAt: reaction.reactedAt.toISOString(),
},
};
} else {
if (existing) {
await tx.teamChatReaction.delete({ where: { id: existing.id }, select: { id: true } });
changed = true;
}
eventName = CHAT_EVENT_NAMES.reactionRemoved;
eventData = { messageId: normalized.messageId, userId: input.userId, emoji: normalized.emoji, removedAt: new Date().toISOString() };
}
const eventRow = await tx.teamChatEvent.create({
data: withTenantScope(input.tenantId, {
chatId: normalized.chatId,
type: toPersistedChatEventType(eventName),
actorUserId: input.userId,
entityId: normalized.messageId,
requestId: normalized.requestId,
data: eventData as unknown as Prisma.InputJsonValue,
}),
select: EVENT_SELECT,
});
const event = mapEvent(eventRow, channel.eventStreamId);
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event });
if (changed) {
await publishReactionAudit(tx, input, normalized);
}
return { ...normalized, changed, replayed: false, event };
});
}
export async function setChatMessagePin(input: SetChatMessagePinInput): Promise<SetChatMessagePinResult> {
const normalized = {
chatId: normalizeIdentifier(input.chatId, "chatId"),
messageId: normalizeIdentifier(input.messageId, "messageId"),
requestId: normalizeRequestId(input.requestId),
pinned: normalizeBoolean(input.pinned, "pinned"),
};
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.write, async (tx, currentPermissions) => {
await lockFeatureStream(tx, input.tenantId, normalized.chatId);
const membership = await lockActiveMembership(tx, input, normalized.chatId, true);
const channel = await requireWritableChannel(tx, input, normalized.chatId);
if (channel.kind === "dm") throw new CatalogError(chatErrors.pinsNotAllowedInDirectMessages);
const message = await requireVisibleMessage(tx, input, normalized.chatId, normalized.messageId);
const canManagePin = message.authorUserId === input.userId || membership.roleInChat === "admin" || currentPermissions.includes(CHAT_PERMISSIONS.admin);
if (!canManagePin) throw new CatalogError(foundationErrors.notFound, { chat: "pin-not-allowed" });
const replayEvent = await findRequestEvent(tx, input, normalized.chatId, normalized.requestId);
if (replayEvent) {
const event = mapEvent(replayEvent, channel.eventStreamId);
if (event.event !== CHAT_EVENT_NAMES.pinChanged || event.data.messageId !== normalized.messageId || event.data.pinned !== normalized.pinned) {
throw new CatalogError(foundationErrors.idempotencyConflict);
}
return { ...normalized, changed: false, replayed: true, event };
}
const existing = await tx.teamChatPinnedMessage.findFirst({
where: withTenantScope(input.tenantId, { chatId: normalized.chatId, messageId: normalized.messageId }),
select: { id: true },
});
let changed = false;
if (normalized.pinned && !existing) {
const pinnedRows = await tx.$queryRaw<Array<{ id: string }>>`
SELECT "id"
FROM "TeamChatPinnedMessage"
WHERE "tenantId" = ${input.tenantId}
AND "chatId" = ${normalized.chatId}
ORDER BY "id" ASC
FOR UPDATE
`;
if (pinnedRows.length >= CHAT_PIN_LIMIT) throw new CatalogError(chatErrors.pinLimitReached, { limit: CHAT_PIN_LIMIT });
await tx.teamChatPinnedMessage.create({
data: withTenantScope(input.tenantId, { chatId: normalized.chatId, messageId: normalized.messageId, pinnedByUserId: input.userId }),
select: { id: true },
});
changed = true;
} else if (!normalized.pinned && existing) {
await tx.teamChatPinnedMessage.delete({ where: { id: existing.id }, select: { id: true } });
changed = true;
}
const eventRow = await tx.teamChatEvent.create({
data: withTenantScope(input.tenantId, {
chatId: normalized.chatId,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.pinChanged),
actorUserId: input.userId,
entityId: normalized.messageId,
requestId: normalized.requestId,
data: { messageId: normalized.messageId, pinned: normalized.pinned, changedByUserId: input.userId },
}),
select: EVENT_SELECT,
});
const event = mapEvent(eventRow, channel.eventStreamId);
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event });
if (changed) {
await publishPinAudit(tx, input, normalized);
await logPinActivity(tx, input, normalized.pinned);
}
return { ...normalized, changed, replayed: false, event };
});
}
export async function listChatPinnedMessages(input: ListChatPinnedMessagesInput): Promise<ListChatPinnedMessagesResult> {
const chatId = normalizeIdentifier(input.chatId, "chatId");
const channelDetail = await getMemberChannelDetail({ ...input, chatId, messageLimit: 1 });
if (channelDetail.channel.kind === "dm") throw new CatalogError(chatErrors.pinsNotAllowedInDirectMessages);
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
await lockActiveMembership(tx, input, chatId, false);
const pins = await tx.teamChatPinnedMessage.findMany({
where: withTenantScope(input.tenantId, { chatId }),
orderBy: [{ pinnedAt: "desc" }, { id: "desc" }],
take: CHAT_PIN_LIMIT,
select: {
messageId: true,
pinnedByUserId: true,
pinnedAt: true,
note: true,
message: { select: MESSAGE_SELECT },
},
});
const profiles = new Map(channelDetail.channel.participants.map((participant) => [participant.userId, participant]));
const pinnedMessages: ChatPinnedMessageRecord[] = pins.map((row) => ({
message: mapMessage(row.message),
pin: {
messageId: row.messageId,
pinnedByUserId: row.pinnedByUserId,
pinnedAtIso: row.pinnedAt.toISOString(),
note: row.note,
},
author: row.message.authorUserId ? (profiles.get(row.message.authorUserId) ?? null) : null,
pinnedBy: profiles.get(row.pinnedByUserId) ?? null,
}));
return { channel: channelDetail.channel, pinnedMessages };
});
}
async function requireThreadParent(tx: DbTransactionClient, context: ChatRepositoryContext, chatId: string, threadId: string): Promise<MessageRow> {
const parent = await tx.teamChatMessage.findFirst({
where: withTenantScope(context.tenantId, {
chatId,
parentMessageId: null,
bodyFormat: "markdown" as const,
OR: [{ id: threadId }, { thread: { id: threadId } }],
}),
select: MESSAGE_SELECT,
});
if (!parent) throw new CatalogError(foundationErrors.notFound, { chat: "thread-not-visible" });
return parent;
}
async function requireVisibleMessage(
tx: DbTransactionClient,
context: ChatRepositoryContext,
chatId: string,
messageId: string
): Promise<{ id: string; authorUserId: string | null }> {
const message = await tx.teamChatMessage.findFirst({
where: withTenantScope(context.tenantId, { id: messageId, chatId, bodyFormat: "markdown" as const, deletedAt: null }),
select: { id: true, authorUserId: true },
});
if (!message) throw new CatalogError(foundationErrors.notFound, { chat: "message-not-visible" });
return message;
}
async function requireWritableChannel(
tx: DbTransactionClient,
context: ChatRepositoryContext,
chatId: string
): Promise<{
id: string;
kind: "project" | "group" | "dm";
name: string | null;
isPrivate: boolean;
eventStreamId: string;
projektId: string | null;
}> {
const channel = await tx.teamChat.findFirst({
where: withTenantScope(context.tenantId, { id: chatId, archivedAt: null }),
select: { id: true, kind: true, name: true, isPrivate: true, eventStreamId: true, projektId: true },
});
if (!channel) throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
return channel;
}
async function lockActiveMembership(
tx: DbTransactionClient,
context: ChatRepositoryContext,
chatId: string,
requireWrite: boolean
): Promise<{ id: string; roleInChat: "admin" | "member" }> {
const rows = await tx.$queryRaw<Array<{ id: string; roleInChat: "admin" | "member" }>>`
SELECT "id", "roleInChat"
FROM "TeamChatMember"
WHERE "tenantId" = ${context.tenantId}
AND "chatId" = ${chatId}
AND "userId" = ${context.userId}
AND "leftAt" IS NULL
AND (${requireWrite}::boolean = FALSE OR "writeRevokedAt" IS NULL)
FOR SHARE
`;
if (rows.length !== 1) throw new CatalogError(foundationErrors.notFound, { chat: requireWrite ? "not-writable" : "not-visible" });
return rows[0]!;
}
async function lockFeatureStream(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<void> {
const lockKey = `chat-event:${tenantId}:${chatId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${CHAT_EVENT_LOCK_SALT}))`;
}
async function findRequestEvent(tx: DbTransactionClient, context: ChatRepositoryContext, chatId: string, requestId: string): Promise<EventRow | null> {
return tx.teamChatEvent.findFirst({
where: withTenantScope(context.tenantId, { chatId, actorUserId: context.userId, requestId }),
orderBy: { sequence: "asc" },
select: EVENT_SELECT,
});
}
function mapEvent(row: EventRow, eventStreamId: string): ChatPersistentEvent {
const event = validateChatServerEvent({
event: toChatPersistentEventName(row.type),
cursor: `${eventStreamId}:${row.sequence.toString()}`,
requestId: row.requestId,
tenantId: row.tenantId,
chatId: row.chatId,
occurredAt: row.occurredAt.toISOString(),
data: row.data,
});
if (!isPersistentChatEvent(event)) throw new CatalogError(chatErrors.integrityFailure);
return event;
}
function mapMessage(row: MessageRow): ChatRealtimeMessage {
const common = {
id: row.id,
clientMessageId: row.clientMessageId,
body: row.body,
parentMessageId: row.parentMessageId,
mentions: (Array.isArray(row.mentions) ? row.mentions : []) as unknown as ChatRealtimeMessage["mentions"],
attachmentIds: [],
linkPreviews: (Array.isArray(row.linkPreviews) ? row.linkPreviews : []) as unknown as ChatRealtimeMessage["linkPreviews"],
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
editedAt: row.editedAt?.toISOString() ?? null,
deletedAt: row.deletedAt?.toISOString() ?? null,
};
if (row.bodyFormat === "system") {
if (!row.systemEventKind || !row.systemEventMetadata) throw new CatalogError(chatErrors.integrityFailure);
return {
...common,
authorUserId: row.authorUserId,
bodyFormat: "system",
systemEvent: { kind: row.systemEventKind, metadata: row.systemEventMetadata as Record<string, never> },
} as unknown as ChatRealtimeMessage;
}
if (!row.authorUserId) throw new CatalogError(chatErrors.integrityFailure);
return { ...common, authorUserId: row.authorUserId, bodyFormat: "markdown" } as unknown as ChatRealtimeMessage;
}
function mapThread(row: { id: string; parentMessageId: string; replyCount: number; lastReplyAt: Date; participantUserIds: string[] }): ChatThreadRecord {
return {
id: row.id,
parentMessageId: row.parentMessageId,
replyCount: row.replyCount,
lastReplyAtIso: row.lastReplyAt.toISOString(),
participantUserIds: [...row.participantUserIds],
};
}
function mapRealtimeThread(row: {
id: string;
parentMessageId: string;
replyCount: number;
lastReplyAt: Date;
participantUserIds: string[];
}): ChatRealtimeThread {
return {
id: row.id,
parentMessageId: row.parentMessageId,
replyCount: row.replyCount,
lastReplyAt: row.lastReplyAt.toISOString(),
participantUserIds: [...row.participantUserIds],
};
}
async function listFeatures(
tx: DbTransactionClient,
context: ChatRepositoryContext,
chatId: string,
messageIds: readonly string[]
): Promise<ChatMessageFeatureRecord[]> {
if (messageIds.length === 0) return [];
const [reactions, threads, pins] = await Promise.all([
tx.teamChatReaction.findMany({
where: withTenantScope(context.tenantId, { messageId: { in: [...messageIds] }, message: { chatId } }),
orderBy: [{ reactedAt: "asc" }, { id: "asc" }],
select: { id: true, messageId: true, userId: true, emoji: true, reactedAt: true },
}),
tx.teamChatThread.findMany({
where: withTenantScope(context.tenantId, { chatId, parentMessageId: { in: [...messageIds] } }),
select: { id: true, parentMessageId: true, replyCount: true, lastReplyAt: true, participantUserIds: true },
}),
tx.teamChatPinnedMessage.findMany({
where: withTenantScope(context.tenantId, { chatId, messageId: { in: [...messageIds] } }),
select: { messageId: true, pinnedByUserId: true, pinnedAt: true, note: true },
}),
]);
return messageIds.map((messageId) => ({
messageId,
reactions: reactions
.filter((reaction) => reaction.messageId === messageId)
.map((reaction) => ({ ...reaction, reactedAtIso: reaction.reactedAt.toISOString() })),
thread: threads.find((thread) => thread.parentMessageId === messageId) ? mapThread(threads.find((thread) => thread.parentMessageId === messageId)!) : null,
pin: (() => {
const pin = pins.find((candidate) => candidate.messageId === messageId);
return pin ? { ...pin, pinnedAtIso: pin.pinnedAt.toISOString() } : null;
})(),
}));
}
async function publishPinAudit(
tx: DbTransactionClient,
context: ChatRepositoryContext,
input: { chatId: string; messageId: string; requestId: string; pinned: boolean }
): Promise<void> {
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId: context.tenantId,
actorId: context.userId,
actorType: "user",
action: input.pinned ? "chat.message.pinned" : "chat.message.unpinned",
targetType: "TeamChatMessage",
targetId: input.messageId,
requestId: input.requestId,
sourceModule: "chat",
dataSensitivity: "internal",
metadata: { chatId: input.chatId },
summaryText: input.pinned ? "Eine Chat-Nachricht wurde angepinnt." : "Eine Chat-Nachricht wurde gelöst.",
});
}
async function publishThreadReplyAudit(
tx: DbTransactionClient,
context: ChatRepositoryContext,
input: { chatId: string; threadId: string; messageId: string; requestId: string }
): Promise<void> {
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId: context.tenantId,
actorId: context.userId,
actorType: "user",
action: "chat.thread.reply_created",
targetType: "TeamChatMessage",
targetId: input.messageId,
requestId: input.requestId,
sourceModule: "chat",
dataSensitivity: "internal",
metadata: { chatId: input.chatId, threadId: input.threadId },
summaryText: "Eine Antwort wurde in einem Chat-Thread erstellt.",
});
}
async function publishReactionAudit(
tx: DbTransactionClient,
context: ChatRepositoryContext,
input: { chatId: string; messageId: string; requestId: string; emoji: string; active: boolean }
): Promise<void> {
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId: context.tenantId,
actorId: context.userId,
actorType: "user",
action: input.active ? "chat.message.reaction_added" : "chat.message.reaction_removed",
targetType: "TeamChatMessage",
targetId: input.messageId,
requestId: input.requestId,
sourceModule: "chat",
dataSensitivity: "internal",
metadata: { chatId: input.chatId, emoji: input.emoji },
summaryText: input.active ? "Eine Reaktion wurde zu einer Chat-Nachricht hinzugefügt." : "Eine Reaktion wurde von einer Chat-Nachricht entfernt.",
});
}
async function notifyThreadReplyRecipients(
tx: DbTransactionClient,
context: ChatRepositoryContext,
input: {
chatId: string;
threadId: string;
messageId: string;
participantUserIds: readonly string[];
mentionedUserIds: readonly string[];
channelKind: "project" | "group" | "dm";
}
): Promise<void> {
const mentionedUserIds = new Set(input.mentionedUserIds);
const candidateUserIds = [...new Set([...input.participantUserIds, ...input.mentionedUserIds])].filter((userId) => userId !== context.userId);
if (candidateUserIds.length === 0) return;
const [visibleMembers, tenant] = await Promise.all([
tx.teamChatMember.findMany({
where: withTenantScope(context.tenantId, {
chatId: input.chatId,
leftAt: null,
userId: { in: candidateUserIds },
}),
select: { userId: true, notificationPref: true },
}),
tx.tenant.findUnique({ where: { id: context.tenantId }, select: { slug: true } }),
]);
if (!tenant) throw new CatalogError(chatErrors.integrityFailure);
const deeplink = buildChatMessageDeepLink({
tenantSlug: tenant.slug,
chatId: input.chatId,
parentMessageId: input.threadId,
messageId: input.messageId,
});
for (const member of visibleMembers) {
const isMentioned = mentionedUserIds.has(member.userId);
const isDirectMessage = input.channelKind === "dm";
if (!isMentioned && !isDirectMessage && member.notificationPref !== "all_messages") continue;
await notify(
{
tenantId: context.tenantId,
userId: member.userId,
channel: "IN_APP",
category: "chat",
messageKey: isMentioned ? "chat.notifications.mentioned" : isDirectMessage ? "chat.notifications.directMessage" : "chat.notifications.threadReply",
sourceKey: `chat-thread-reply:${input.messageId}:${member.userId}`,
payloadMetadata: {
deeplink,
chatId: input.chatId,
threadId: input.threadId,
messageId: input.messageId,
},
},
tx as unknown as Parameters<typeof notify>[1]
);
}
}
async function logPinActivity(tx: DbTransactionClient, context: ChatRepositoryContext, pinned: boolean): Promise<void> {
await logActivity(
{
tenantId: context.tenantId,
actorUserId: context.userId,
actorKind: "user",
activityType: "audit_event",
subjectType: "tenant",
subjectId: context.tenantId,
summaryText: pinned ? "activity.runtime.chat.messagePinned" : "activity.runtime.chat.messageUnpinned",
metadata: { sourceModule: "chat", chatAction: pinned ? "message_pinned" : "message_unpinned" },
},
{ client: tx }
);
}
function normalizeIdentifier(value: unknown, field: string): string {
if (typeof value !== "string") throw new CatalogError(chatErrors.invalidInput, { field });
const normalized = value.trim();
if (!normalized || normalized.length > MAX_IDENTIFIER_LENGTH || normalized.includes("\0")) {
throw new CatalogError(chatErrors.invalidInput, { field });
}
return normalized;
}
function normalizeRequestId(value: unknown): string {
const normalized = normalizeIdentifier(value, "requestId");
if (normalized.length > MAX_REQUEST_ID_LENGTH) throw new CatalogError(chatErrors.invalidInput, { field: "requestId" });
return normalized;
}
function normalizeBody(value: unknown): string {
if (typeof value !== "string") throw new CatalogError(chatErrors.invalidInput, { field: "body" });
const normalized = value.trim();
if (!normalized || normalized.length > CHAT_MESSAGE_MAX_BODY_LENGTH || normalized.includes("\0")) {
throw new CatalogError(chatErrors.invalidInput, { field: "body" });
}
return normalized;
}
function normalizeEmoji(value: unknown): string {
if (typeof value !== "string") throw new CatalogError(chatErrors.invalidInput, { field: "emoji" });
const normalized = value.trim();
const graphemeCount = [...EMOJI_SEGMENTER.segment(normalized)].length;
if (!normalized || normalized.length > MAX_EMOJI_LENGTH || graphemeCount !== 1 || /\s/u.test(normalized) || !/\p{Extended_Pictographic}/u.test(normalized)) {
throw new CatalogError(chatErrors.invalidInput, { field: "emoji" });
}
return normalized;
}
function normalizeBoolean(value: unknown, field: string): boolean {
if (typeof value !== "boolean") throw new CatalogError(chatErrors.invalidInput, { field });
return value;
}
function uniqueBoundedParticipants(userIds: readonly string[]): string[] {
const participants = [...new Set(userIds)].sort();
if (participants.length > CHAT_THREAD_MAX_PARTICIPANTS) return participants.slice(participants.length - CHAT_THREAD_MAX_PARTICIPANTS);
return participants;
}
export const CHAT_MESSAGE_PIN_LIMIT = CHAT_PIN_LIMIT;
export const CHAT_MESSAGE_REACTION_LIMIT = CHAT_REACTION_LIMIT;
@@ -0,0 +1,101 @@
// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_A = "chat_mutation_rls_tenant_a";
const TENANT_B = "chat_mutation_rls_tenant_b";
const USER_A = "chat_mutation_rls_user_a";
const USER_B = "chat_mutation_rls_user_b";
const CHAT_A = "chat_mutation_rls_chat_a";
const CHAT_B = "chat_mutation_rls_chat_b";
const MESSAGE_A = "chat_mutation_rls_message_a";
const MESSAGE_B = "chat_mutation_rls_message_b";
describeIfDatabase("chat message mutations with the restricted app role", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
beforeAll(async () => {
await cleanup(admin);
await admin.user.createMany({
data: [
{ id: USER_A, email: "chat-mutation-rls-a@example.test", firstName: "Mutation", lastName: "A", active: true },
{ id: USER_B, email: "chat-mutation-rls-b@example.test", firstName: "Mutation", lastName: "B", active: true },
],
});
await admin.tenant.createMany({
data: [
{ id: TENANT_A, slug: TENANT_A, name: "Chat mutation A", active: true },
{ id: TENANT_B, slug: TENANT_B, name: "Chat mutation B", active: true },
],
});
await admin.tenantUser.createMany({
data: [
{ id: "chat_mutation_rls_membership_a", tenantId: TENANT_A, userId: USER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_mutation_rls_membership_b", tenantId: TENANT_B, userId: USER_B, type: 0, joined: 1, status: 2 },
],
});
await admin.teamChat.createMany({
data: [
{ id: CHAT_A, tenantId: TENANT_A, createdByUserId: USER_A, kind: "group", name: "A", eventStreamId: "chat_mutation_rls_stream_a" },
{ id: CHAT_B, tenantId: TENANT_B, createdByUserId: USER_B, kind: "group", name: "B", eventStreamId: "chat_mutation_rls_stream_b" },
],
});
await admin.teamChatMember.createMany({
data: [
{ id: "chat_mutation_rls_chat_member_a", tenantId: TENANT_A, chatId: CHAT_A, userId: USER_A, notificationPref: "all_messages" },
{ id: "chat_mutation_rls_chat_member_b", tenantId: TENANT_B, chatId: CHAT_B, userId: USER_B, notificationPref: "all_messages" },
],
});
await admin.teamChatMessage.createMany({
data: [
{ id: MESSAGE_A, tenantId: TENANT_A, chatId: CHAT_A, authorUserId: USER_A, clientMessageId: "chat-mutation-a", body: "A", mentions: [], linkPreviews: [] },
{ id: MESSAGE_B, tenantId: TENANT_B, chatId: CHAT_B, authorUserId: USER_B, clientMessageId: "chat-mutation-b", body: "B", mentions: [], linkPreviews: [] },
],
});
});
afterAll(async () => {
await cleanup(admin);
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("permits a same-tenant tombstone but cannot update a foreign message", async () => {
const currentRole = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]);
await expect(app.teamChatMessage.findMany({ where: { id: MESSAGE_A }, select: { id: true } })).resolves.toEqual([]);
const deletedAt = new Date("2026-07-16T09:00:00.000Z");
const sameTenant = await runWithRlsContext({ tenantId: TENANT_A, userId: USER_A }, () =>
app.teamChatMessage.updateMany({
where: { id: MESSAGE_A, tenantId: TENANT_A, chatId: CHAT_A },
data: { body: "", mentions: [], linkPreviews: [], deletedAt, deletedByUserId: USER_A },
})
);
expect(sameTenant.count).toBe(1);
const foreign = await runWithRlsContext({ tenantId: TENANT_A, userId: USER_A }, () =>
app.teamChatMessage.updateMany({ where: { id: MESSAGE_B }, data: { body: "cross-tenant write" } })
);
expect(foreign.count).toBe(0);
await expect(admin.teamChatMessage.findUnique({ where: { id: MESSAGE_B }, select: { body: true } })).resolves.toEqual({ body: "B" });
await expect(admin.teamChatMessage.findUnique({ where: { id: MESSAGE_A }, select: { body: true, deletedAt: true, deletedByUserId: true } })).resolves.toEqual({
body: "",
deletedAt,
deletedByUserId: USER_A,
});
});
});
async function cleanup(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.teamChatMessage.deleteMany({ where: { id: { in: [MESSAGE_A, MESSAGE_B] } } });
await admin.teamChatMember.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.teamChat.deleteMany({ where: { id: { in: [CHAT_A, CHAT_B] } } });
await admin.tenantUser.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.tenant.deleteMany({ where: { id: { in: [TENANT_A, TENANT_B] } } });
await admin.user.deleteMany({ where: { id: { in: [USER_A, USER_B] } } });
}
@@ -0,0 +1,315 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
runTransaction: vi.fn(),
listAttachments: vi.fn(),
resolveMentions: vi.fn(),
logMentionActivities: vi.fn(),
publishAudit: vi.fn(),
publishWakeup: vi.fn(),
notify: vi.fn(),
logActivity: vi.fn(),
}));
vi.mock("./repository.server.js", () => ({
runChatRepositoryTransaction: mocks.runTransaction,
listMessageAttachmentRecords: mocks.listAttachments,
}));
vi.mock("./mentions.server.js", () => ({
chatMentionKey: (mention: { type: string; id: string }) => `${mention.type}\u0000${mention.id}`,
resolveChatMentionsInBodyWithTx: mocks.resolveMentions,
logChatMessageActivitiesWithTx: mocks.logMentionActivities,
}));
vi.mock("@hivegrid/db/audit-events.server", () => ({ publishAuditEventViaOutbox: mocks.publishAudit }));
vi.mock("./realtime-wakeup.server.js", () => ({ publishChatPersistentRealtimeWakeup: mocks.publishWakeup }));
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
vi.mock("@hivegrid/foundation", async (importOriginal) => {
const actual = await importOriginal<typeof import("@hivegrid/foundation")>();
return { ...actual, notify: mocks.notify };
});
import { deleteChatMessage, updateChatMessage } from "./message-mutations.server.js";
const context = {
tenantId: "tenant_1",
userId: "user_actor",
permissions: ["chat.read_own_channels", "chat.write"],
} as const;
const createdAt = new Date("2026-07-16T01:00:00.000Z");
const baseMessage = {
id: "message_1",
createdAt,
updatedAt: createdAt,
tenantId: "tenant_1",
chatId: "chat_1",
authorUserId: "user_actor",
clientMessageId: "client_1",
body: "Alt",
bodyFormat: "markdown" as const,
parentMessageId: null,
mentions: [],
linkPreviews: [],
editedAt: null,
deletedAt: null,
deletedByUserId: null,
systemEventKind: null,
systemEventMetadata: null,
};
function transactionFixture() {
const teamChatEvent = {
findFirst: vi.fn().mockResolvedValue(null),
create: vi.fn(async ({ data }) => ({
sequence: 12n,
occurredAt: new Date("2026-07-16T02:00:00.000Z"),
tenantId: data.tenantId,
chatId: data.chatId,
type: data.type,
actorUserId: data.actorUserId,
entityId: data.entityId,
requestId: data.requestId,
data: data.data,
})),
};
const tx = {
$executeRaw: vi.fn().mockResolvedValue(0),
$queryRaw: vi.fn().mockImplementation((strings: TemplateStringsArray) => {
const sql = strings.join("?");
if (sql.includes('FROM "TeamChatMember"')) return Promise.resolve([{ roleInChat: "member" }]);
if (sql.includes('FROM "TeamChatMessage"')) return Promise.resolve([{ id: "message_1" }]);
return Promise.resolve([]);
}),
teamChat: {
findFirst: vi.fn().mockResolvedValue({
id: "chat_1",
kind: "project",
isPrivate: true,
projektId: "project_1",
name: "P-100",
eventStreamId: "stream_1",
}),
update: vi.fn().mockResolvedValue({ id: "chat_1" }),
},
teamChatMessage: {
findFirst: vi.fn().mockResolvedValue(baseMessage),
findMany: vi.fn().mockResolvedValue([]),
update: vi.fn(async ({ data }) => ({ ...baseMessage, ...data, updatedAt: new Date("2026-07-16T02:00:00.000Z") })),
},
teamChatEvent,
fileEntityLink: { deleteMany: vi.fn().mockResolvedValue({ count: 0 }) },
teamChatReaction: { deleteMany: vi.fn().mockResolvedValue({ count: 0 }) },
teamChatPinnedMessage: { deleteMany: vi.fn().mockResolvedValue({ count: 0 }) },
teamChatThread: { findFirst: vi.fn().mockResolvedValue(null), update: vi.fn() },
teamChatMember: { findMany: vi.fn().mockResolvedValue([]) },
tenant: { findUnique: vi.fn().mockResolvedValue({ slug: "acme" }) },
};
return tx;
}
describe("chat message mutations", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-07-16T02:00:00.000Z"));
mocks.runTransaction.mockImplementation(async (_input, _permission, operation) =>
operation(transactionFixture(), ["chat.read_own_channels", "chat.write"])
);
mocks.listAttachments.mockResolvedValue([]);
mocks.resolveMentions.mockResolvedValue([{ type: "project", id: "project_2", label: "P-200" }]);
mocks.logMentionActivities.mockResolvedValue(undefined);
mocks.publishAudit.mockResolvedValue(undefined);
mocks.publishWakeup.mockResolvedValue(undefined);
mocks.logActivity.mockResolvedValue(undefined);
mocks.notify.mockResolvedValue(undefined);
});
it("edits an own fresh message, persists resolved mentions and emits one durable event", async () => {
const result = await updateChatMessage({
...context,
chatId: "chat_1",
messageId: "message_1",
requestId: "request_edit_1",
body: "Neu <@project:project_2>",
});
expect(result).toMatchObject({ replayed: false, message: { id: "message_1", body: "Neu <@project:project_2>" } });
expect(mocks.resolveMentions).toHaveBeenCalledOnce();
expect(mocks.publishWakeup).toHaveBeenCalledOnce();
expect(mocks.publishAudit).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ action: "chat.message.edited", requestId: "request_edit_1" })
);
expect(mocks.logMentionActivities).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
expect.objectContaining({ mentions: [{ type: "project", id: "project_2", label: "P-200" }], action: "message_edited" })
);
});
it("returns the clear 24-hour error for an expired own edit", async () => {
vi.setSystemTime(new Date("2026-07-18T02:00:00.000Z"));
await expect(
updateChatMessage({ ...context, chatId: "chat_1", messageId: "message_1", requestId: "request_edit_old", body: "Zu spät" })
).rejects.toMatchObject({ i18nKey: "chat.errors.messageEditWindowExpired", status: 409 });
expect(mocks.publishWakeup).not.toHaveBeenCalled();
});
it("does not let a channel or global admin edit another author's message in the normal member path", async () => {
const tx = transactionFixture();
tx.$queryRaw.mockImplementation((strings: TemplateStringsArray) => {
const sql = strings.join("?");
if (sql.includes('FROM "TeamChatMember"')) return Promise.resolve([{ roleInChat: "admin" }]);
if (sql.includes('FROM "TeamChatMessage"')) return Promise.resolve([{ id: "message_1" }]);
return Promise.resolve([]);
});
tx.teamChatMessage.findFirst.mockResolvedValue({ ...baseMessage, authorUserId: "user_other" });
mocks.runTransaction.mockImplementation(async (_input, _permission, operation) =>
operation(tx, ["chat.read_own_channels", "chat.write", "chat.admin"])
);
await expect(
updateChatMessage({ ...context, chatId: "chat_1", messageId: "message_1", requestId: "request_admin_edit", body: "Nicht erlaubt" })
).rejects.toMatchObject({ code: "foundation.not_found" });
expect(tx.teamChatMessage.update).not.toHaveBeenCalled();
expect(mocks.publishAudit).not.toHaveBeenCalled();
});
it("uses an edit-event-specific notification key when a user is mentioned again", async () => {
mocks.resolveMentions.mockResolvedValue([{ type: "user", id: "user_2", label: "User 2" }]);
mocks.runTransaction.mockImplementation(async (_input, _permission, operation) => {
const tx = transactionFixture();
tx.teamChatMember.findMany.mockResolvedValue([{ userId: "user_2" }]);
return operation(tx, ["chat.read_own_channels", "chat.write"]);
});
await updateChatMessage({
...context,
chatId: "chat_1",
messageId: "message_1",
requestId: "request_remention_1",
body: "Hallo <@user:user_2>",
});
await updateChatMessage({
...context,
chatId: "chat_1",
messageId: "message_1",
requestId: "request_remention_2",
body: "Nochmals <@user:user_2>",
});
expect(mocks.notify).toHaveBeenCalledTimes(2);
expect(mocks.notify).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ sourceKey: "chat-message-edit-mention:message_1:request_remention_1:user_2" }),
expect.anything()
);
expect(mocks.notify).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ sourceKey: "chat-message-edit-mention:message_1:request_remention_2:user_2" }),
expect.anything()
);
});
it("lets a channel admin tombstone another user's message and removes visible side data", async () => {
const tx = transactionFixture();
tx.$queryRaw.mockImplementation((strings: TemplateStringsArray) => {
const sql = strings.join("?");
if (sql.includes('FROM "TeamChatMember"')) return Promise.resolve([{ roleInChat: "admin" }]);
if (sql.includes('FROM "TeamChatMessage"')) return Promise.resolve([{ id: "message_1" }]);
return Promise.resolve([]);
});
tx.teamChatMessage.findFirst.mockResolvedValueOnce({ ...baseMessage, authorUserId: "user_other" }).mockResolvedValueOnce(null);
mocks.runTransaction.mockImplementation(async (_input, _permission, operation) =>
operation(tx, ["chat.read_own_channels", "chat.write"])
);
const result = await deleteChatMessage({ ...context, chatId: "chat_1", messageId: "message_1", requestId: "request_delete_1" });
expect(result).toMatchObject({ replayed: false, messageId: "message_1" });
expect(tx.fileEntityLink.deleteMany).toHaveBeenCalledOnce();
expect(tx.teamChatReaction.deleteMany).toHaveBeenCalledOnce();
expect(tx.teamChatPinnedMessage.deleteMany).toHaveBeenCalledOnce();
expect(tx.teamChatMessage.update).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ body: "", mentions: [], linkPreviews: [], deletedByUserId: "user_actor" }) })
);
expect(mocks.publishAudit).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ action: "chat.message.deleted" }));
});
it("reconciles the durable thread aggregate after deleting a reply", async () => {
const tx = transactionFixture();
const reply = { ...baseMessage, id: "reply_2", clientMessageId: "client_reply_2", parentMessageId: "message_1" };
const parent = { createdAt, authorUserId: "user_parent" };
const remainingReplyAt = new Date("2026-07-16T01:30:00.000Z");
tx.teamChatMessage.findFirst
.mockResolvedValueOnce(reply)
.mockResolvedValueOnce(parent)
.mockResolvedValueOnce({ createdAt: remainingReplyAt });
tx.teamChatMessage.findMany.mockResolvedValue([
{ createdAt: remainingReplyAt, authorUserId: "user_other" },
]);
tx.teamChatThread.findFirst.mockResolvedValue({ id: "message_1" });
tx.teamChatThread.update.mockResolvedValue({ id: "message_1" });
mocks.runTransaction.mockImplementation(async (_input, _permission, operation) =>
operation(tx, ["chat.read_own_channels", "chat.write"])
);
await deleteChatMessage({
...context,
chatId: "chat_1",
messageId: "reply_2",
requestId: "request_delete_reply",
});
expect(tx.teamChatThread.update).toHaveBeenCalledWith({
where: { id: "message_1" },
data: {
replyCount: 1,
lastReplyAt: remainingReplyAt,
participantUserIds: ["user_parent", "user_other"],
},
select: { id: true },
});
});
it("replays the same update request without a second mutation or side effect", async () => {
const tx = transactionFixture();
tx.teamChatEvent.findFirst.mockResolvedValue({
sequence: 7n,
occurredAt: new Date("2026-07-16T02:00:00.000Z"),
tenantId: "tenant_1",
chatId: "chat_1",
type: "message_updated",
actorUserId: "user_actor",
entityId: "message_1",
requestId: "request_replay",
data: {
message: {
id: "message_1",
clientMessageId: "client_1",
authorUserId: "user_actor",
body: "Neu",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-16T01:00:00.000Z",
updatedAt: "2026-07-16T02:00:00.000Z",
editedAt: "2026-07-16T02:00:00.000Z",
deletedAt: null,
},
},
});
mocks.runTransaction.mockImplementation(async (_input, _permission, operation) =>
operation(tx, ["chat.read_own_channels", "chat.write"])
);
await expect(
updateChatMessage({ ...context, chatId: "chat_1", messageId: "message_1", requestId: "request_replay", body: "Neu" })
).resolves.toMatchObject({ replayed: true });
expect(tx.teamChatMessage.update).not.toHaveBeenCalled();
expect(mocks.publishAudit).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,510 @@
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, notify, withTenantScope } from "@hivegrid/foundation";
import {
CHAT_EVENT_NAMES,
CHAT_MESSAGE_MAX_BODY_LENGTH,
isPersistentChatEvent,
validateChatServerEvent,
type ChatMention,
type ChatPersistentEvent,
type ChatRealtimeMessage,
} from "@hivegrid/realtime";
import { toChatPersistentEventName, toPersistedChatEventType } from "./event-type-mapping.js";
import { buildChatMessageDeepLink } from "./deep-links.js";
import { chatErrors } from "./errors.js";
import { extractChatLinkPreviewPlaceholders, publishChatLinkPreviewRequest } from "./link-preview.server.js";
import { chatMentionKey, logChatMessageActivitiesWithTx, resolveChatMentionsInBodyWithTx, type ChatMentionChannel } from "./mentions.server.js";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { listMessageAttachmentRecords, runChatRepositoryTransaction } from "./repository.server.js";
import { publishChatPersistentRealtimeWakeup } from "./realtime-wakeup.server.js";
import type { ChatRepositoryContext } from "./types.js";
const CHAT_EVENT_LOCK_SALT = 15_015;
const MAX_IDENTIFIER_LENGTH = 500;
const MAX_REQUEST_ID_LENGTH = 500;
const EDIT_WINDOW_MS = 24 * 60 * 60 * 1_000;
export type UpdateChatMessageInput = ChatRepositoryContext &
Readonly<{
chatId: string;
messageId: string;
requestId: string;
body: string;
}>;
export type UpdateChatMessageResult = Readonly<{
message: ChatRealtimeMessage;
event: ChatPersistentEvent;
replayed: boolean;
}>;
export type DeleteChatMessageInput = ChatRepositoryContext &
Readonly<{
chatId: string;
messageId: string;
requestId: string;
}>;
export type DeleteChatMessageResult = Readonly<{
messageId: string;
deletedAtIso: string;
event: ChatPersistentEvent;
replayed: boolean;
}>;
const 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,
deletedByUserId: true,
systemEventKind: true,
systemEventMetadata: true,
} as const satisfies Prisma.TeamChatMessageSelect;
const EVENT_SELECT = {
sequence: true,
occurredAt: true,
tenantId: true,
chatId: true,
type: true,
actorUserId: true,
entityId: true,
requestId: true,
data: true,
} as const satisfies Prisma.TeamChatEventSelect;
type MessageRow = Prisma.TeamChatMessageGetPayload<{ select: typeof MESSAGE_SELECT }>;
type EventRow = Prisma.TeamChatEventGetPayload<{ select: typeof EVENT_SELECT }>;
type WritableChannel = ChatMentionChannel & { eventStreamId: string; roleInChat: "admin" | "member" };
export async function updateChatMessage(input: UpdateChatMessageInput): Promise<UpdateChatMessageResult> {
const normalized = {
chatId: normalizeIdentifier(input.chatId, "chatId"),
messageId: normalizeIdentifier(input.messageId, "messageId"),
requestId: normalizeRequestId(input.requestId),
body: normalizeBody(input.body),
};
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.write, async (tx, currentPermissions) => {
await lockMessageMutationStream(tx, input.tenantId, normalized.chatId);
const channel = await requireWritableMutationChannel(tx, input, normalized.chatId);
const replay = await findMutationEvent(tx, input, normalized.chatId, normalized.requestId);
if (replay) return resolveUpdateReplay(replay, channel.eventStreamId, normalized);
const message = await requireMutableMessage(tx, input, normalized.chatId, normalized.messageId);
if (message.authorUserId !== input.userId) throw new CatalogError(foundationErrors.notFound, { chat: "message-not-editable" });
if (Date.now() - message.createdAt.getTime() > EDIT_WINDOW_MS) {
throw new CatalogError(chatErrors.messageEditWindowExpired);
}
const attachments = await listMessageAttachmentRecords(tx, input.tenantId, [message.id]);
if (!normalized.body.trim() && attachments.length === 0) throw new CatalogError(chatErrors.invalidInput, { field: "body" });
const mentions = await resolveChatMentionsInBodyWithTx(tx, input, channel, normalized.body, currentPermissions);
const previousMentionKeys = new Set(readMentions(message.mentions).map(chatMentionKey));
const editedAt = new Date();
const updated = await tx.teamChatMessage.update({
where: { id: message.id },
data: {
body: normalized.body,
mentions: mentions as unknown as Prisma.InputJsonValue,
linkPreviews: extractChatLinkPreviewPlaceholders(normalized.body) as unknown as Prisma.InputJsonValue,
editedAt,
},
select: MESSAGE_SELECT,
});
const realtimeMessage = mapMessage(
updated,
attachments.map((attachment) => attachment.fileId)
);
const eventRow = await tx.teamChatEvent.create({
data: withTenantScope(input.tenantId, {
chatId: normalized.chatId,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.messageUpdated),
actorUserId: input.userId,
entityId: updated.id,
requestId: normalized.requestId,
data: { message: realtimeMessage } as unknown as Prisma.InputJsonValue,
}),
select: EVENT_SELECT,
});
const event = mapEvent(eventRow, channel.eventStreamId);
if (event.event !== CHAT_EVENT_NAMES.messageUpdated) throw new CatalogError(chatErrors.integrityFailure);
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event });
await publishChatLinkPreviewRequest(tx as unknown as OutboxPublisherTransaction, {
tenantId: input.tenantId,
chatId: normalized.chatId,
messageId: updated.id,
requestId: normalized.requestId,
body: normalized.body,
});
await publishMutationAudit(tx, input, {
action: "chat.message.edited",
chatId: normalized.chatId,
messageId: normalized.messageId,
requestId: normalized.requestId,
summaryText: "Eine Chat-Nachricht wurde bearbeitet.",
});
const addedMentions = mentions.filter((mention) => !previousMentionKeys.has(chatMentionKey(mention)));
await logChatMessageActivitiesWithTx(tx, input, {
channel,
messageId: message.id,
body: normalized.body,
mentions: addedMentions,
includeProjectChannelActivity: false,
action: "message_edited",
});
await notifyAddedUserMentions(tx, input, channel, message, addedMentions, normalized.requestId);
return { message: realtimeMessage, event, replayed: false };
});
}
export async function deleteChatMessage(input: DeleteChatMessageInput): Promise<DeleteChatMessageResult> {
const normalized = {
chatId: normalizeIdentifier(input.chatId, "chatId"),
messageId: normalizeIdentifier(input.messageId, "messageId"),
requestId: normalizeRequestId(input.requestId),
};
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.write, async (tx, currentPermissions) => {
await lockMessageMutationStream(tx, input.tenantId, normalized.chatId);
const channel = await requireWritableMutationChannel(tx, input, normalized.chatId);
const replay = await findMutationEvent(tx, input, normalized.chatId, normalized.requestId);
if (replay) return resolveDeleteReplay(replay, channel.eventStreamId, normalized);
const message = await requireMutableMessage(tx, input, normalized.chatId, normalized.messageId);
const isAuthor = message.authorUserId === input.userId;
const canAdminDelete = channel.roleInChat === "admin" || currentPermissions.includes(CHAT_PERMISSIONS.admin);
if (!isAuthor && !canAdminDelete) throw new CatalogError(foundationErrors.notFound, { chat: "message-not-deletable" });
if (isAuthor && !canAdminDelete && Date.now() - message.createdAt.getTime() > EDIT_WINDOW_MS) {
throw new CatalogError(chatErrors.messageDeleteWindowExpired);
}
const deletedAt = new Date();
await tx.fileEntityLink.deleteMany({
where: withTenantScope(input.tenantId, { entityType: "chat_message" as const, entityId: message.id }),
});
await Promise.all([
tx.teamChatReaction.deleteMany({ where: withTenantScope(input.tenantId, { messageId: message.id }) }),
tx.teamChatPinnedMessage.deleteMany({ where: withTenantScope(input.tenantId, { chatId: normalized.chatId, messageId: message.id }) }),
]);
await tx.teamChatMessage.update({
where: { id: message.id },
data: {
body: "",
mentions: [],
linkPreviews: [],
deletedAt,
deletedByUserId: input.userId,
},
select: { id: true },
});
if (message.parentMessageId) {
await reconcileThreadAfterReplyDeletion(tx, input, normalized.chatId, message.parentMessageId);
}
const latestMessage = await tx.teamChatMessage.findFirst({
where: withTenantScope(input.tenantId, { chatId: normalized.chatId, deletedAt: null }),
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
select: { createdAt: true },
});
await tx.teamChat.update({ where: { id: normalized.chatId }, data: { lastMessageAt: latestMessage?.createdAt ?? null }, select: { id: true } });
const eventRow = await tx.teamChatEvent.create({
data: withTenantScope(input.tenantId, {
chatId: normalized.chatId,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.messageDeleted),
actorUserId: input.userId,
entityId: message.id,
requestId: normalized.requestId,
data: { messageId: message.id, deletedByUserId: input.userId, deletedAt: deletedAt.toISOString() },
}),
select: EVENT_SELECT,
});
const event = mapEvent(eventRow, channel.eventStreamId);
if (event.event !== CHAT_EVENT_NAMES.messageDeleted) throw new CatalogError(chatErrors.integrityFailure);
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event });
await publishMutationAudit(tx, input, {
action: "chat.message.deleted",
chatId: normalized.chatId,
messageId: normalized.messageId,
requestId: normalized.requestId,
summaryText: "Eine Chat-Nachricht wurde gelöscht.",
});
if (channel.projektId) {
await logActivity(
{
tenantId: input.tenantId,
actorUserId: input.userId,
actorKind: "user",
activityType: "chat_message",
subjectType: "project",
subjectId: channel.projektId,
summaryText: "activity.runtime.chat.projectMessageDeleted",
metadata: { sourceModule: "chat", chatAction: "message_deleted", chatId: channel.id, messageId: message.id },
},
{ client: tx }
);
}
return { messageId: message.id, deletedAtIso: deletedAt.toISOString(), event, replayed: false };
});
}
async function requireWritableMutationChannel(tx: DbTransactionClient, context: ChatRepositoryContext, chatId: string): Promise<WritableChannel> {
const membershipRows = await tx.$queryRaw<Array<{ roleInChat: "admin" | "member" }>>`
SELECT mutation_member."roleInChat" AS "roleInChat"
FROM "TeamChatMember" AS mutation_member
WHERE mutation_member."tenantId" = ${context.tenantId}
AND mutation_member."chatId" = ${chatId}
AND mutation_member."userId" = ${context.userId}
AND mutation_member."leftAt" IS NULL
AND mutation_member."writeRevokedAt" IS NULL
FOR SHARE
`;
const membership = membershipRows[0];
if (!membership || membershipRows.length !== 1) throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
const channel = await tx.teamChat.findFirst({
where: withTenantScope(context.tenantId, { id: chatId, archivedAt: null }),
select: { id: true, kind: true, isPrivate: true, projektId: true, name: true, eventStreamId: true },
});
if (!channel) throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
return { ...channel, roleInChat: membership.roleInChat };
}
async function requireMutableMessage(tx: DbTransactionClient, context: ChatRepositoryContext, chatId: string, messageId: string): Promise<MessageRow> {
const locks = await tx.$queryRaw<Array<{ id: string }>>`
SELECT mutable_message."id"
FROM "TeamChatMessage" AS mutable_message
WHERE mutable_message."tenantId" = ${context.tenantId}
AND mutable_message."chatId" = ${chatId}
AND mutable_message."id" = ${messageId}
AND mutable_message."bodyFormat" = 'markdown'
AND mutable_message."deletedAt" IS NULL
FOR UPDATE
`;
if (locks.length !== 1) throw new CatalogError(foundationErrors.notFound, { chat: "message-not-visible" });
const message = await tx.teamChatMessage.findFirst({
where: withTenantScope(context.tenantId, { id: messageId, chatId, bodyFormat: "markdown" as const, deletedAt: null }),
select: MESSAGE_SELECT,
});
if (!message || !message.authorUserId) throw new CatalogError(foundationErrors.notFound, { chat: "message-not-visible" });
return message;
}
async function reconcileThreadAfterReplyDeletion(
tx: DbTransactionClient,
context: ChatRepositoryContext,
chatId: string,
parentMessageId: string
): Promise<void> {
const [thread, parent, replies] = await Promise.all([
tx.teamChatThread.findFirst({
where: withTenantScope(context.tenantId, { chatId, parentMessageId }),
select: { id: true },
}),
tx.teamChatMessage.findFirst({
where: withTenantScope(context.tenantId, { id: parentMessageId, chatId }),
select: { createdAt: true, authorUserId: true },
}),
tx.teamChatMessage.findMany({
where: withTenantScope(context.tenantId, { chatId, parentMessageId, deletedAt: null }),
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
select: { createdAt: true, authorUserId: true },
}),
]);
if (!thread || !parent) throw new CatalogError(chatErrors.integrityFailure);
const participants = [...new Set([parent.authorUserId, ...replies.map((reply) => reply.authorUserId)].filter((value): value is string => Boolean(value)))];
await tx.teamChatThread.update({
where: { id: thread.id },
data: {
replyCount: replies.length,
lastReplyAt: replies.at(-1)?.createdAt ?? parent.createdAt,
participantUserIds: participants,
},
select: { id: true },
});
}
async function notifyAddedUserMentions(
tx: DbTransactionClient,
context: ChatRepositoryContext,
channel: ChatMentionChannel,
message: MessageRow,
mentions: readonly ChatMention[],
requestId: string
): Promise<void> {
const userIds = [...new Set(mentions.filter((mention) => mention.type === "user").map((mention) => mention.id))].filter(
(userId) => userId !== context.userId
);
if (userIds.length === 0) return;
const [members, tenant] = await Promise.all([
tx.teamChatMember.findMany({
where: withTenantScope(context.tenantId, { chatId: channel.id, userId: { in: userIds }, leftAt: null }),
select: { userId: true },
}),
tx.tenant.findUnique({ where: { id: context.tenantId }, select: { slug: true } }),
]);
if (!tenant) throw new CatalogError(chatErrors.integrityFailure);
const deeplink = buildChatMessageDeepLink({
tenantSlug: tenant.slug,
chatId: channel.id,
messageId: message.id,
parentMessageId: message.parentMessageId,
});
for (const member of members) {
await notify(
{
tenantId: context.tenantId,
userId: member.userId,
channel: "IN_APP",
category: "chat",
messageKey: "chat.notifications.mentioned",
sourceKey: `chat-message-edit-mention:${message.id}:${requestId}:${member.userId}`,
payloadMetadata: { deeplink, chatId: channel.id, messageId: message.id, ...(message.parentMessageId ? { threadId: message.parentMessageId } : {}) },
},
tx as unknown as Parameters<typeof notify>[1]
);
}
}
async function findMutationEvent(tx: DbTransactionClient, context: ChatRepositoryContext, chatId: string, requestId: string): Promise<EventRow | null> {
return tx.teamChatEvent.findFirst({
where: withTenantScope(context.tenantId, { chatId, actorUserId: context.userId, requestId }),
orderBy: { sequence: "asc" },
select: EVENT_SELECT,
});
}
function resolveUpdateReplay(eventRow: EventRow, eventStreamId: string, input: { messageId: string; body: string }): UpdateChatMessageResult {
const event = mapEvent(eventRow, eventStreamId);
if (event.event !== CHAT_EVENT_NAMES.messageUpdated || event.data.message.id !== input.messageId || event.data.message.body !== input.body) {
throw new CatalogError(foundationErrors.idempotencyConflict);
}
return { message: event.data.message, event, replayed: true };
}
function resolveDeleteReplay(eventRow: EventRow, eventStreamId: string, input: { messageId: string }): DeleteChatMessageResult {
const event = mapEvent(eventRow, eventStreamId);
if (event.event !== CHAT_EVENT_NAMES.messageDeleted || event.data.messageId !== input.messageId) {
throw new CatalogError(foundationErrors.idempotencyConflict);
}
return { messageId: event.data.messageId, deletedAtIso: event.data.deletedAt, event, replayed: true };
}
function mapEvent(row: EventRow, eventStreamId: string): ChatPersistentEvent {
const event = validateChatServerEvent({
event: toChatPersistentEventName(row.type),
cursor: `${eventStreamId}:${row.sequence.toString()}`,
requestId: row.requestId,
tenantId: row.tenantId,
chatId: row.chatId,
occurredAt: row.occurredAt.toISOString(),
data: row.data,
});
if (!isPersistentChatEvent(event)) throw new CatalogError(chatErrors.integrityFailure);
return event;
}
function mapMessage(row: MessageRow, attachmentIds: readonly string[]): ChatRealtimeMessage {
const event = validateChatServerEvent({
event: CHAT_EVENT_NAMES.messageUpdated,
cursor: "validation:1",
requestId: `message-${row.id}`,
tenantId: row.tenantId,
chatId: row.chatId,
occurredAt: row.updatedAt.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,
},
},
});
if (event.event !== CHAT_EVENT_NAMES.messageUpdated) throw new CatalogError(chatErrors.integrityFailure);
return event.data.message;
}
async function publishMutationAudit(
tx: DbTransactionClient,
context: ChatRepositoryContext,
input: { action: string; chatId: string; messageId: string; requestId: string; summaryText: string }
): Promise<void> {
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId: context.tenantId,
actorId: context.userId,
actorType: "user",
action: input.action,
targetType: "TeamChatMessage",
targetId: input.messageId,
requestId: input.requestId,
sourceModule: "chat",
dataSensitivity: "internal",
metadata: { chatId: input.chatId },
summaryText: input.summaryText,
});
}
async function lockMessageMutationStream(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<void> {
const lockKey = `chat-event:${tenantId}:${chatId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${CHAT_EVENT_LOCK_SALT}))`;
}
function readMentions(value: unknown): ChatMention[] {
if (!Array.isArray(value)) return [];
return value.filter((entry): entry is ChatMention => {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false;
const mention = entry as Partial<ChatMention>;
return (
(mention.type === "user" || mention.type === "project" || mention.type === "contact" || mention.type === "company") &&
typeof mention.id === "string" &&
(typeof mention.label === "string" || mention.label === null)
);
});
}
function normalizeIdentifier(value: unknown, field: string): string {
if (typeof value !== "string") throw new CatalogError(chatErrors.invalidInput, { field });
const normalized = value.trim();
if (!normalized || normalized.length > MAX_IDENTIFIER_LENGTH || normalized.includes("\0")) {
throw new CatalogError(chatErrors.invalidInput, { field });
}
return normalized;
}
function normalizeRequestId(value: unknown): string {
const normalized = normalizeIdentifier(value, "requestId");
if (normalized.length > MAX_REQUEST_ID_LENGTH) throw new CatalogError(chatErrors.invalidInput, { field: "requestId" });
return normalized;
}
function normalizeBody(value: unknown): string {
if (typeof value !== "string" || value.length > CHAT_MESSAGE_MAX_BODY_LENGTH || value.includes("\0")) {
throw new CatalogError(chatErrors.invalidInput, { field: "body" });
}
return value;
}
@@ -0,0 +1,40 @@
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import { describe, expect, it, vi } from "vitest";
import {
tenantHasChatModuleForSystemTx,
tenantHasChatModuleWithPermissionsTx,
tenantHasFilesModuleWithPermissionsTx,
tenantHasTasksModuleWithPermissionsTx,
} from "./module-access.server.js";
describe("chat module transaction gate", () => {
it("honors a disabled tenant override for system lifecycle hooks", async () => {
const tx = transactionReturning([{ blueprintId: "crm-saas", tenantOverride: "disabled" }]);
await expect(tenantHasChatModuleForSystemTx(tx, "tenant_1")).resolves.toBe(false);
});
it("bypasses user RBAC only for the explicit system helper", async () => {
const userTx = transactionReturning([{ blueprintId: "crm-saas", tenantOverride: "inherit" }]);
const systemTx = transactionReturning([{ blueprintId: "crm-saas", tenantOverride: "inherit" }]);
await expect(tenantHasChatModuleWithPermissionsTx(userTx, "tenant_1", [])).resolves.toBe(false);
await expect(tenantHasChatModuleForSystemTx(systemTx, "tenant_1")).resolves.toBe(true);
});
it("evaluates Files and Tasks against their own feature override in the current transaction", async () => {
const filesTx = transactionReturning([{ blueprintId: "crm-saas", tenantOverride: "disabled" }]);
const tasksTx = transactionReturning([{ blueprintId: "crm-saas", tenantOverride: "inherit" }]);
await expect(tenantHasFilesModuleWithPermissionsTx(filesTx, "tenant_1", ["files.read_own", "files.write"])).resolves.toBe(false);
await expect(tenantHasTasksModuleWithPermissionsTx(tasksTx, "tenant_1", ["tasks.read_own", "tasks.write"])).resolves.toBe(true);
expect(filesTx.$queryRaw).toHaveBeenCalledOnce();
expect(tasksTx.$queryRaw).toHaveBeenCalledOnce();
});
});
function transactionReturning(rows: unknown[]): DbTransactionClient {
return { $queryRaw: vi.fn(async () => rows) } as unknown as DbTransactionClient;
}
@@ -0,0 +1,71 @@
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import { evaluateProductAccess, featureKeys, getDefaultProductBlueprint, type FeatureKey } from "@hivegrid/entitlements";
import { CHAT_PERMISSIONS } from "./permissions.js";
type ModuleConfigurationRow = {
blueprintId: string | null;
tenantOverride: string | null;
};
export async function tenantHasChatModuleWithPermissionsTx(
tx: DbTransactionClient,
tenantId: string,
tenantRolePermissionNames: readonly string[]
): Promise<boolean> {
return tenantHasModuleWithPermissionsTx(tx, tenantId, featureKeys.chat, tenantRolePermissionNames);
}
export async function tenantHasFilesModuleWithPermissionsTx(
tx: DbTransactionClient,
tenantId: string,
tenantRolePermissionNames: readonly string[]
): Promise<boolean> {
return tenantHasModuleWithPermissionsTx(tx, tenantId, featureKeys.files, tenantRolePermissionNames);
}
export async function tenantHasTasksModuleWithPermissionsTx(
tx: DbTransactionClient,
tenantId: string,
tenantRolePermissionNames: readonly string[]
): Promise<boolean> {
return tenantHasModuleWithPermissionsTx(tx, tenantId, featureKeys.tasks, tenantRolePermissionNames);
}
export async function tenantHasModuleWithPermissionsTx(
tx: DbTransactionClient,
tenantId: string,
featureKey: FeatureKey,
tenantRolePermissionNames: readonly string[]
): Promise<boolean> {
const configuration = await loadModuleConfiguration(tx, tenantId, featureKey);
return evaluateProductAccess({
blueprintId: configuration?.blueprintId ?? getDefaultProductBlueprint().id,
featureKey,
hasSubscription: true,
tenantOverride: normalizeTenantOverride(configuration?.tenantOverride),
tenantRolePermissionNames,
}).allowed;
}
/** System lifecycle hooks bypass user RBAC but still honor blueprint and tenant overrides. */
export function tenantHasChatModuleForSystemTx(tx: DbTransactionClient, tenantId: string): Promise<boolean> {
return tenantHasChatModuleWithPermissionsTx(tx, tenantId, [CHAT_PERMISSIONS.readOwnChannels]);
}
async function loadModuleConfiguration(tx: DbTransactionClient, tenantId: string, featureKey: FeatureKey): Promise<ModuleConfigurationRow | undefined> {
const rows = await tx.$queryRaw<ModuleConfigurationRow[]>`
SELECT configuration."blueprintId", feature_override."override" AS "tenantOverride"
FROM (VALUES (1)) AS singleton(value)
LEFT JOIN "TenantProductConfiguration" AS configuration
ON configuration."tenantId" = ${tenantId}
LEFT JOIN "TenantFeatureOverride" AS feature_override
ON feature_override."tenantId" = ${tenantId}
AND feature_override."featureKey" = ${featureKey}
`;
return rows[0];
}
function normalizeTenantOverride(value: string | null | undefined): "enabled" | "disabled" | "inherit" {
return value === "enabled" || value === "disabled" || value === "inherit" ? value : "inherit";
}
@@ -0,0 +1,10 @@
export const CHAT_PERMISSIONS = {
readOwnChannels: "chat.read_own_channels",
write: "chat.write",
createChannel: "chat.create_channel",
createDm: "chat.create_dm",
admin: "chat.admin",
readAllChannels: "chat.read_all_channels",
} as const;
export type ChatPermission = (typeof CHAT_PERMISSIONS)[keyof typeof CHAT_PERMISSIONS];
@@ -0,0 +1,75 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
runChatRepositoryTransaction: vi.fn(),
tx: { teamChat: { findFirst: vi.fn() } },
}));
vi.mock("./repository.server.js", () => ({
runChatRepositoryTransaction: (...args: unknown[]) => mocks.runChatRepositoryTransaction(...args),
}));
import { findMemberProjectChatLink } from "./project-link.server.js";
const context = {
tenantId: "tenant_1",
userId: "user_1",
permissions: ["chat.read_own_channels"],
projectId: "project_1",
} as const;
describe("member project chat link", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.runChatRepositoryTransaction.mockImplementation(
async (_context: unknown, _permission: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx)
);
});
it("prefers the active member channel and preserves read-only project history state", async () => {
mocks.tx.teamChat.findFirst.mockResolvedValueOnce({
id: "chat_active",
archivedAt: null,
members: [{ writeRevokedAt: new Date("2026-07-15T12:00:00.000Z") }],
});
await expect(findMemberProjectChatLink(context)).resolves.toEqual({
chatId: "chat_active",
archivedAtIso: null,
canWrite: false,
});
expect(mocks.runChatRepositoryTransaction).toHaveBeenCalledWith(context, "chat.read_own_channels", expect.any(Function));
expect(mocks.tx.teamChat.findFirst).toHaveBeenCalledOnce();
});
it("falls back to the newest archived channel without exposing another user's membership", async () => {
const archivedAt = new Date("2026-07-15T12:00:00.000Z");
mocks.tx.teamChat.findFirst.mockResolvedValueOnce(null).mockResolvedValueOnce({
id: "chat_archived",
archivedAt,
members: [{ writeRevokedAt: null }],
});
await expect(findMemberProjectChatLink(context)).resolves.toEqual({
chatId: "chat_archived",
archivedAtIso: archivedAt.toISOString(),
canWrite: false,
});
expect(mocks.tx.teamChat.findFirst).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
where: expect.objectContaining({
tenantId: "tenant_1",
projektId: "project_1",
archivedAt: { not: null },
members: { some: { tenantId: "tenant_1", userId: "user_1", leftAt: null } },
}),
})
);
});
it("returns null when no readable project chat exists", async () => {
mocks.tx.teamChat.findFirst.mockResolvedValue(null);
await expect(findMemberProjectChatLink(context)).resolves.toBeNull();
});
});
@@ -0,0 +1,81 @@
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { withTenantScope } from "@hivegrid/foundation";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { runChatRepositoryTransaction } from "./repository.server.js";
import type { ChatRouteRepositoryContext } from "./types.js";
export type FindMemberProjectChatLinkInput = ChatRouteRepositoryContext & {
readonly projectId: string;
};
export type MemberProjectChatLink = Readonly<{
chatId: string;
archivedAtIso: string | null;
canWrite: boolean;
}>;
const PROJECT_CHAT_LINK_SELECT = {
id: true,
archivedAt: true,
members: {
select: { writeRevokedAt: true },
},
} as const satisfies Prisma.TeamChatSelect;
/** Returns only a project chat the current member may already read. */
export async function findMemberProjectChatLink(input: FindMemberProjectChatLinkInput): Promise<MemberProjectChatLink | null> {
const projectId = normalizeIdentifier(input.projectId);
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx) => {
const active = await findProjectChat(tx, input, projectId, false);
if (active) return mapProjectChatLink(active);
const archived = await findProjectChat(tx, input, projectId, true);
return archived ? mapProjectChatLink(archived) : null;
});
}
type ProjectChatLinkRow = Readonly<{
id: string;
archivedAt: Date | null;
members: readonly Readonly<{ writeRevokedAt: Date | null }>[];
}>;
async function findProjectChat(
tx: DbTransactionClient,
context: ChatRouteRepositoryContext,
projectId: string,
archived: boolean
): Promise<ProjectChatLinkRow | null> {
const memberScope = withTenantScope(context.tenantId, { userId: context.userId, leftAt: null });
return tx.teamChat.findFirst({
where: withTenantScope(context.tenantId, {
kind: "project" as const,
projektId: projectId,
archivedAt: archived ? { not: null } : null,
members: { some: memberScope },
}),
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
select: {
...PROJECT_CHAT_LINK_SELECT,
members: { ...PROJECT_CHAT_LINK_SELECT.members, where: memberScope, take: 1 },
},
});
}
function mapProjectChatLink(row: ProjectChatLinkRow): MemberProjectChatLink {
const membership = row.members[0];
if (!membership) throw new Error("Project chat link lost its tenant-scoped membership");
return {
chatId: row.id,
archivedAtIso: row.archivedAt?.toISOString() ?? null,
canWrite: row.archivedAt === null && membership.writeRevokedAt === null,
};
}
function normalizeIdentifier(value: string): string {
if (typeof value !== "string") throw new Error("projectId must be a string");
const normalized = value.trim();
if (!normalized || normalized.length > 500 || normalized.includes("\0")) throw new Error("projectId is invalid");
return normalized;
}
@@ -0,0 +1,636 @@
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
logActivity: vi.fn(),
publishAuditEventViaOutbox: vi.fn(),
publishRealtimeWakeup: vi.fn(),
tenantHasChatModuleForSystemTx: vi.fn(),
writeSystemMessage: vi.fn(),
tx: {
$executeRaw: vi.fn(),
projekt: { findFirst: vi.fn() },
projektMitglied: { findMany: vi.fn() },
group: { findMany: vi.fn() },
tenantUser: { findMany: vi.fn() },
teamChat: { findFirst: vi.fn(), create: vi.fn(), updateMany: vi.fn() },
teamChatMember: { findMany: vi.fn(), create: vi.fn(), updateMany: vi.fn() },
teamChatEvent: { create: vi.fn() },
},
}));
vi.mock("@hivegrid/activity", () => ({
logActivity: mocks.logActivity,
}));
vi.mock("@hivegrid/db/audit-events.server", () => ({
publishAuditEventViaOutbox: mocks.publishAuditEventViaOutbox,
}));
vi.mock("./module-access.server.js", () => ({
tenantHasChatModuleForSystemTx: (...args: unknown[]) => mocks.tenantHasChatModuleForSystemTx(...args),
}));
vi.mock("./realtime-wakeup.server.js", () => ({
publishChatPersistentRealtimeWakeup: (...args: unknown[]) => mocks.publishRealtimeWakeup(...args),
}));
vi.mock("./system-message.server.js", () => ({
writeChatSystemMessageWithTx: (...args: unknown[]) => mocks.writeSystemMessage(...args),
}));
import { archiveProjectChannelIfEnabledWithTx, ensureAndSyncProjectChannelWithTx } from "./project-sync.server.js";
const NOW = new Date("2026-07-16T08:00:00.000Z");
const CHANNEL = {
id: "chat_project_1",
eventStreamId: "stream_project_1",
name: "Wärmepumpe Müller",
description: "Projekt-Chat für Wärmepumpe Müller, P-2026-0042",
isDemoData: false,
notificationDefault: "all_messages" as const,
};
const BASE_PROJECT = {
id: "project_1",
projektname: "Wärmepumpe Müller",
projektNummer: "P-2026-0042",
projektleiterId: "user_pl",
zustaendigePersonId: null,
isDemoData: false,
};
const TX = mocks.tx as unknown as DbTransactionClient;
describe("project channel synchronization", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(NOW);
mocks.tx.$executeRaw.mockResolvedValue(1);
mocks.tenantHasChatModuleForSystemTx.mockResolvedValue(true);
mocks.tx.projekt.findFirst.mockResolvedValue(BASE_PROJECT);
mocks.tx.projektMitglied.findMany.mockResolvedValue([]);
mocks.tx.group.findMany.mockResolvedValue([]);
mocks.tx.tenantUser.findMany.mockResolvedValue([tenantUser("user_pl")]);
mocks.tx.teamChat.findFirst.mockResolvedValue(CHANNEL);
mocks.tx.teamChat.create.mockResolvedValue(CHANNEL);
mocks.tx.teamChat.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.teamChatMember.findMany.mockResolvedValue([]);
mocks.tx.teamChatMember.create.mockResolvedValue({ id: "chat_member_1" });
mocks.tx.teamChatMember.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.teamChatEvent.create.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({
...data,
sequence: BigInt(mocks.tx.teamChatEvent.create.mock.calls.length),
occurredAt: NOW,
}));
mocks.logActivity.mockResolvedValue({ id: "activity_1" });
mocks.publishAuditEventViaOutbox.mockResolvedValue(undefined);
mocks.publishRealtimeWakeup.mockResolvedValue(undefined);
mocks.writeSystemMessage.mockImplementation(async (_tx: unknown, input: { tenantId: string; chatId: string; requestId: string }) => ({
replayed: false,
event: realtimeSystemEvent(input),
}));
});
afterEach(() => {
vi.useRealTimers();
});
it("creates one tenant-scoped project channel and unions all active effective members", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue({
...BASE_PROJECT,
zustaendigePersonId: "user_responsible",
});
mocks.tx.projektMitglied.findMany.mockResolvedValue([
{ userId: "user_direct", groupId: null },
{ userId: "user_pl", groupId: null },
{ userId: "user_inactive", groupId: null },
{ userId: null, groupId: "group_1" },
]);
mocks.tx.group.findMany.mockResolvedValue([{ users: [{ userId: "user_group" }, { userId: "user_direct" }, { userId: "user_outside_tenant" }] }]);
mocks.tx.tenantUser.findMany.mockResolvedValue([
tenantUser("user_responsible"),
tenantUser("user_group"),
tenantUser("user_pl"),
tenantUser("user_direct"),
]);
mocks.tx.teamChat.findFirst.mockResolvedValue(null);
const result = await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
actorUserId: null,
requestId: "request_create",
});
expect(result).toMatchObject({
chatId: CHANNEL.id,
created: true,
reactivated: false,
changed: true,
effectiveUserIds: ["user_direct", "user_group", "user_pl", "user_responsible"],
writeRestoredUserIds: ["user_direct", "user_group", "user_pl", "user_responsible"],
});
expect(mocks.tx.teamChat.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: "tenant_1",
createdByUserId: null,
kind: "project",
projektId: "project_1",
isPrivate: true,
description: "Projekt-Chat für Wärmepumpe Müller, P-2026-0042",
isDemoData: false,
}),
select: { id: true, eventStreamId: true, name: true, description: true, isDemoData: true, notificationDefault: true },
});
expect(mocks.tx.teamChatMember.create).toHaveBeenCalledTimes(4);
const createdMembers = mocks.tx.teamChatMember.create.mock.calls.map((call) => call[0].data);
expect(createdMembers).toEqual(
expect.arrayContaining([
expect.objectContaining({
userId: "user_pl",
roleInChat: "admin",
isProjectManaged: true,
projectRoleInChat: "admin",
isManualMember: false,
manualRoleInChat: null,
}),
expect.objectContaining({
userId: "user_direct",
roleInChat: "member",
isProjectManaged: true,
projectRoleInChat: "member",
isManualMember: false,
}),
expect.objectContaining({ userId: "user_group", roleInChat: "member", isProjectManaged: true, projectRoleInChat: "member" }),
expect.objectContaining({ userId: "user_responsible", roleInChat: "member", isProjectManaged: true, projectRoleInChat: "member" }),
])
);
expect(mocks.tx.group.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: "tenant_1", id: { in: ["group_1"] } } }));
expect(mocks.tx.tenantUser.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
tenantId: "tenant_1",
status: 2,
user: { active: true, pendingDeletion: false, pseudonymized: false },
}),
})
);
expect(mocks.tx.teamChatEvent.create).toHaveBeenCalledTimes(4);
expect(mocks.writeSystemMessage).toHaveBeenCalledTimes(5);
expect(mocks.writeSystemMessage).toHaveBeenCalledWith(
TX,
expect.objectContaining({
kind: "project_created",
metadata: expect.objectContaining({ projectId: "project_1", projectName: "Wärmepumpe Müller" }),
})
);
expect(mocks.writeSystemMessage).toHaveBeenCalledWith(
TX,
expect.objectContaining({ kind: "member_added", metadata: expect.objectContaining({ memberUserId: "user_pl" }) })
);
expect(mocks.publishRealtimeWakeup).toHaveBeenCalledTimes(9);
const projectLeaderEvent = mocks.tx.teamChatEvent.create.mock.calls.find((call) => call[0].data.entityId === "user_pl");
expect(projectLeaderEvent?.[0].data.data).toEqual({
userId: "user_pl",
roleInChat: "admin",
joinedAt: NOW.toISOString(),
});
expect(mocks.publishAuditEventViaOutbox).toHaveBeenCalledOnce();
expect(mocks.logActivity).toHaveBeenCalledOnce();
const projectLock = mocks.tx.$executeRaw.mock.calls.find((call) => call.includes("project-channel:tenant_1:project_1"));
expect(String(projectLock?.[0])).toContain("pg_advisory_xact_lock");
});
it("is a no-op when the channel and project-derived membership already match", async () => {
mocks.tx.teamChatMember.findMany.mockResolvedValue([projectMember({ userId: "user_pl", roleInChat: "admin" })]);
const result = await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
actorUserId: "user_actor",
requestId: "request_noop",
});
expect(result).toMatchObject({ created: false, reactivated: false, changed: false });
expect(mocks.tx.teamChat.create).not.toHaveBeenCalled();
expect(mocks.tx.teamChatMember.create).not.toHaveBeenCalled();
expect(mocks.tx.teamChatMember.updateMany).not.toHaveBeenCalled();
expect(mocks.tx.teamChatEvent.create).not.toHaveBeenCalled();
expect(mocks.writeSystemMessage).not.toHaveBeenCalled();
expect(mocks.publishRealtimeWakeup).not.toHaveBeenCalled();
expect(mocks.publishAuditEventViaOutbox).not.toHaveBeenCalled();
expect(mocks.logActivity).not.toHaveBeenCalled();
});
it("revokes only pure project write access and leaves manual guests writable", async () => {
mocks.tx.teamChatMember.findMany.mockResolvedValue([
projectMember({ userId: "user_pl", roleInChat: "admin" }),
projectMember({ id: "member_removed", userId: "user_removed" }),
projectMember({ id: "member_overlap", userId: "user_overlap", isManualMember: true }),
projectMember({ id: "member_guest", userId: "user_manual_guest", isProjectManaged: false, isManualMember: true }),
]);
const result = await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
actorUserId: "user_actor",
requestId: "request_remove",
});
expect(result.projectSourceRemovedUserIds).toEqual(["user_overlap", "user_removed"]);
expect(result.writeRevokedUserIds).toEqual(["user_removed"]);
const removedUpdate = memberUpdateFor("user_removed");
expect(removedUpdate?.data).toEqual({
isProjectManaged: false,
projectRoleInChat: null,
roleInChat: "member",
writeRevokedAt: NOW,
leftAt: null,
});
const overlapUpdate = memberUpdateFor("user_overlap");
expect(overlapUpdate?.data).toEqual({
isProjectManaged: false,
projectRoleInChat: null,
roleInChat: "member",
writeRevokedAt: null,
leftAt: null,
});
expect(memberUpdateFor("user_manual_guest")).toBeUndefined();
expect(mocks.tx.teamChatEvent.create).toHaveBeenCalledOnce();
expect(mocks.tx.teamChatEvent.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
type: "member_removed",
entityId: "user_removed",
data: { userId: "user_removed", leftAt: NOW.toISOString() },
}),
})
);
expect(mocks.writeSystemMessage).toHaveBeenCalledWith(
TX,
expect.objectContaining({
kind: "member_write_access_changed",
metadata: expect.objectContaining({ memberUserId: "user_removed", canWrite: false }),
})
);
expect(mocks.publishRealtimeWakeup).toHaveBeenCalledTimes(2);
});
it("restores a former project member without creating a duplicate membership", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue({
...BASE_PROJECT,
projektleiterId: null,
});
mocks.tx.projektMitglied.findMany.mockResolvedValue([{ userId: "user_readded", groupId: null }]);
mocks.tx.tenantUser.findMany.mockResolvedValue([tenantUser("user_readded")]);
mocks.tx.teamChatMember.findMany.mockResolvedValue([
projectMember({
id: "member_readded",
userId: "user_readded",
isProjectManaged: false,
isManualMember: false,
writeRevokedAt: new Date("2026-07-15T08:00:00.000Z"),
}),
]);
const result = await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
actorUserId: "user_actor",
requestId: "request_readd",
});
expect(result.projectSourceAddedUserIds).toEqual(["user_readded"]);
expect(result.writeRestoredUserIds).toEqual(["user_readded"]);
expect(mocks.tx.teamChatMember.create).not.toHaveBeenCalled();
expect(memberUpdateFor("user_readded")?.data).toEqual({
isProjectManaged: true,
projectRoleInChat: "member",
roleInChat: "member",
writeRevokedAt: null,
leftAt: null,
joinedAt: NOW,
joinedViaUserId: "user_actor",
});
expect(mocks.tx.teamChatEvent.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ type: "member_added", entityId: "user_readded" }) })
);
expect(mocks.writeSystemMessage).toHaveBeenCalledWith(
TX,
expect.objectContaining({
kind: "member_write_access_changed",
metadata: expect.objectContaining({ memberUserId: "user_readded", canWrite: true }),
})
);
});
it("reactivates the existing archived project channel instead of creating a duplicate", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue({ ...BASE_PROJECT, projektleiterId: null });
mocks.tx.tenantUser.findMany.mockResolvedValue([]);
mocks.tx.teamChat.findFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(CHANNEL);
const result = await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
requestId: "request_reactivate",
reactivateArchived: true,
});
expect(result).toMatchObject({ chatId: CHANNEL.id, created: false, reactivated: true, changed: true });
expect(mocks.tx.teamChat.create).not.toHaveBeenCalled();
expect(mocks.tx.teamChat.updateMany).toHaveBeenCalledWith({
where: {
id: CHANNEL.id,
tenantId: "tenant_1",
projektId: "project_1",
kind: "project",
archivedAt: { not: null },
},
data: {
archivedAt: null,
archivedReason: null,
name: "Wärmepumpe Müller",
description: "Projekt-Chat für Wärmepumpe Müller, P-2026-0042",
isDemoData: false,
},
});
});
it("does not reopen an archived project channel during an ordinary member sync", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue({ ...BASE_PROJECT, projektleiterId: null });
mocks.tx.tenantUser.findMany.mockResolvedValue([]);
mocks.tx.teamChat.findFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(CHANNEL);
const result = await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
requestId: "request_sync_archived",
});
expect(result).toMatchObject({ chatId: CHANNEL.id, created: false, reactivated: false, changed: false });
expect(mocks.tx.teamChat.create).not.toHaveBeenCalled();
expect(mocks.tx.teamChat.updateMany).not.toHaveBeenCalled();
expect(mocks.tx.projektMitglied.findMany).not.toHaveBeenCalled();
expect(mocks.tx.teamChatMember.findMany).not.toHaveBeenCalled();
expect(mocks.tx.teamChatMember.updateMany).not.toHaveBeenCalled();
});
it("preserves a manually granted admin role when that user also becomes project-managed", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue({ ...BASE_PROJECT, projektleiterId: null });
mocks.tx.projektMitglied.findMany.mockResolvedValue([{ userId: "user_manual_admin", groupId: null }]);
mocks.tx.tenantUser.findMany.mockResolvedValue([tenantUser("user_manual_admin")]);
mocks.tx.teamChatMember.findMany.mockResolvedValue([
projectMember({
id: "member_manual_admin",
userId: "user_manual_admin",
roleInChat: "admin",
isProjectManaged: false,
isManualMember: true,
}),
]);
await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
requestId: "request_manual_admin",
});
expect(memberUpdateFor("user_manual_admin")?.data).toEqual({
isProjectManaged: true,
projectRoleInChat: "member",
roleInChat: "admin",
writeRevokedAt: null,
leftAt: null,
});
});
it("promotes a manual member while they are project lead and falls back to manual member after project removal", async () => {
mocks.tx.teamChatMember.findMany.mockResolvedValue([
projectMember({
id: "member_overlap",
userId: "user_pl",
roleInChat: "member",
isProjectManaged: false,
isManualMember: true,
manualRoleInChat: "member",
projectRoleInChat: null,
}),
]);
await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
requestId: "request_promote_project_lead",
});
expect(memberUpdateFor("user_pl")?.data).toEqual({
isProjectManaged: true,
projectRoleInChat: "admin",
roleInChat: "admin",
writeRevokedAt: null,
leftAt: null,
});
expect(mocks.writeSystemMessage).toHaveBeenCalledWith(
TX,
expect.objectContaining({ kind: "project_leader_changed", metadata: expect.objectContaining({ newLeaderUserId: "user_pl" }) })
);
vi.clearAllMocks();
mocks.tx.$executeRaw.mockResolvedValue(1);
mocks.tx.projekt.findFirst.mockResolvedValue({ ...BASE_PROJECT, projektleiterId: null });
mocks.tx.projektMitglied.findMany.mockResolvedValue([]);
mocks.tx.tenantUser.findMany.mockResolvedValue([]);
mocks.tx.teamChat.findFirst.mockResolvedValue(CHANNEL);
mocks.tx.teamChatMember.findMany.mockResolvedValue([
projectMember({
id: "member_overlap",
userId: "user_pl",
roleInChat: "admin",
isManualMember: true,
manualRoleInChat: "member",
projectRoleInChat: "admin",
}),
]);
mocks.tx.teamChatMember.updateMany.mockResolvedValue({ count: 1 });
mocks.publishAuditEventViaOutbox.mockResolvedValue(undefined);
mocks.logActivity.mockResolvedValue({ id: "activity_2" });
const removed = await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
requestId: "request_remove_project_lead",
});
expect(removed.writeRevokedUserIds).toEqual([]);
expect(memberUpdateFor("user_pl")?.data).toEqual({
isProjectManaged: false,
projectRoleInChat: null,
roleInChat: "member",
writeRevokedAt: null,
leftAt: null,
});
});
it("keeps a manual admin effective after losing the project-lead source", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue({ ...BASE_PROJECT, projektleiterId: null });
mocks.tx.tenantUser.findMany.mockResolvedValue([]);
mocks.tx.teamChatMember.findMany.mockResolvedValue([
projectMember({
id: "member_manual_admin",
userId: "user_old_pl",
roleInChat: "admin",
isManualMember: true,
manualRoleInChat: "admin",
projectRoleInChat: "admin",
}),
]);
const result = await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
requestId: "request_manual_admin_fallback",
});
expect(result.writeRevokedUserIds).toEqual([]);
expect(memberUpdateFor("user_old_pl")?.data).toEqual({
isProjectManaged: false,
projectRoleInChat: null,
roleInChat: "admin",
writeRevokedAt: null,
leftAt: null,
});
});
it("demotes and write-revokes a pure former project lead without retaining admin", async () => {
mocks.tx.projekt.findFirst.mockResolvedValue({ ...BASE_PROJECT, projektleiterId: null });
mocks.tx.tenantUser.findMany.mockResolvedValue([]);
mocks.tx.teamChatMember.findMany.mockResolvedValue([
projectMember({
id: "member_old_pl",
userId: "user_old_pl",
roleInChat: "admin",
projectRoleInChat: "admin",
}),
]);
const result = await ensureAndSyncProjectChannelWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
requestId: "request_revoke_old_project_lead",
});
expect(result.writeRevokedUserIds).toEqual(["user_old_pl"]);
expect(memberUpdateFor("user_old_pl")?.data).toEqual({
isProjectManaged: false,
projectRoleInChat: null,
roleInChat: "member",
writeRevokedAt: NOW,
leftAt: null,
});
});
it("archives an active project channel with a durable event and audit trail", async () => {
const result = await archiveProjectChannelIfEnabledWithTx(TX, {
tenantId: "tenant_1",
projectId: "project_1",
actorUserId: null,
requestId: "request_archive",
reason: "project_completed",
archivedAt: NOW,
});
expect(result).toEqual({ chatId: CHANNEL.id, archived: true });
expect(mocks.tx.teamChat.updateMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", id: CHANNEL.id, projektId: "project_1", kind: "project", archivedAt: null },
data: { archivedAt: NOW, archivedReason: "project_completed" },
});
expect(mocks.tx.teamChatEvent.create).toHaveBeenCalledWith({
data: {
tenantId: "tenant_1",
chatId: CHANNEL.id,
type: "channel_archived",
actorUserId: null,
entityId: "project_1",
requestId: "request_archive",
data: { archivedAt: NOW.toISOString(), reason: "project_completed" },
},
select: {
sequence: true,
occurredAt: true,
tenantId: true,
chatId: true,
type: true,
actorUserId: true,
entityId: true,
requestId: true,
data: true,
},
});
expect(mocks.writeSystemMessage).toHaveBeenCalledWith(
TX,
expect.objectContaining({ kind: "channel_archived", metadata: { projectId: "project_1", reason: "project_completed" } })
);
expect(mocks.publishRealtimeWakeup).toHaveBeenCalledTimes(2);
expect(mocks.publishAuditEventViaOutbox).toHaveBeenCalledOnce();
expect(mocks.logActivity).toHaveBeenCalledOnce();
});
});
function projectMember(overrides: Record<string, unknown> = {}) {
const merged = {
id: "member_project",
userId: "user_project",
roleInChat: "member",
isProjectManaged: true,
isManualMember: false,
isGroupManaged: false,
manualRoleInChat: null,
projectRoleInChat: "member",
writeRevokedAt: null,
leftAt: null,
...overrides,
};
return {
...merged,
manualRoleInChat:
Object.prototype.hasOwnProperty.call(overrides, "manualRoleInChat")
? merged.manualRoleInChat
: merged.isManualMember
? merged.roleInChat
: null,
projectRoleInChat:
Object.prototype.hasOwnProperty.call(overrides, "projectRoleInChat")
? merged.projectRoleInChat
: merged.isProjectManaged
? merged.roleInChat
: null,
};
}
function memberUpdateFor(userId: string): { where: Record<string, unknown>; data: Record<string, unknown> } | undefined {
const call = mocks.tx.teamChatMember.updateMany.mock.calls.find((candidate) => candidate[0].where.userId === userId);
return call?.[0];
}
function tenantUser(userId: string) {
return {
userId,
user: {
firstName: userId,
lastName: null,
email: `${userId}@example.test`,
},
};
}
function realtimeSystemEvent(input: { tenantId: string; chatId: string; requestId: string }) {
return {
event: "chat.message.created",
cursor: `${CHANNEL.eventStreamId}:99`,
requestId: input.requestId,
tenantId: input.tenantId,
chatId: input.chatId,
occurredAt: NOW.toISOString(),
data: {},
};
}
@@ -0,0 +1,926 @@
import { createHash, randomUUID } from "node:crypto";
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 { withTenantScope } from "@hivegrid/foundation";
import { CHAT_EVENT_NAMES, isPersistentChatEvent, validateChatServerEvent } from "@hivegrid/realtime";
import { toChatPersistentEventName, toPersistedChatEventType } from "./event-type-mapping.js";
import { hasActiveChatMembershipSource, resolveEffectiveChatMemberRole } from "./member-role.js";
import { tenantHasChatModuleForSystemTx } from "./module-access.server.js";
import { publishChatPersistentRealtimeWakeup } from "./realtime-wakeup.server.js";
import { writeChatSystemMessageWithTx } from "./system-message.server.js";
const ACTIVE_TENANT_USER_STATUS = 2;
const PROJECT_CHANNEL_LOCK_SALT = 15_017;
const CHAT_EVENT_LOCK_SALT = 15_015;
const PERSISTED_EVENT_SELECT = {
sequence: true,
occurredAt: true,
tenantId: true,
chatId: true,
type: true,
actorUserId: true,
entityId: true,
requestId: true,
data: true,
} as const satisfies Prisma.TeamChatEventSelect;
type PersistedProjectEvent = Prisma.TeamChatEventGetPayload<{ select: typeof PERSISTED_EVENT_SELECT }>;
export type ProjectChannelSyncInput = Readonly<{
tenantId: string;
projectId: string;
actorUserId?: string | null;
requestId?: string;
/** Only a real project reactivation may reopen an archived channel. */
reactivateArchived?: boolean;
}>;
export type ProjectChannelSyncResult = Readonly<{
chatId: string;
created: boolean;
reactivated: boolean;
metadataUpdated: boolean;
changed: boolean;
effectiveUserIds: readonly string[];
projectSourceAddedUserIds: readonly string[];
projectSourceRemovedUserIds: readonly string[];
writeRestoredUserIds: readonly string[];
writeRevokedUserIds: readonly string[];
}>;
export type PermissionGroupProjectChannelSyncInput = Readonly<{
tenantId: string;
groupId: string;
actorUserId: string;
requestId: string;
}>;
export type ProjectChannelArchiveInput = Readonly<{
tenantId: string;
projectId: string;
actorUserId?: string | null;
requestId: string;
reason: "project_completed" | "project_cancelled";
archivedAt?: Date;
}>;
export async function ensureAndSyncProjectChannelIfEnabledWithTx(
tx: DbTransactionClient,
input: ProjectChannelSyncInput
): Promise<ProjectChannelSyncResult | null> {
if (!(await tenantHasChatModuleForSystemTx(tx, input.tenantId))) return null;
return ensureAndSyncProjectChannelWithTx(tx, input);
}
/**
* Reconcile project channels affected by one permission-group membership
* mutation. Stable project ordering prevents advisory-lock inversion when two
* group changes touch overlapping projects concurrently.
*/
export async function syncProjectChannelsForPermissionGroupWithTx(
tx: DbTransactionClient,
input: PermissionGroupProjectChannelSyncInput
): Promise<readonly string[]> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const groupId = normalizeIdentifier(input.groupId, "groupId");
const actorUserId = normalizeIdentifier(input.actorUserId, "actorUserId");
const requestId = normalizeIdentifier(input.requestId, "requestId");
if (!(await tenantHasChatModuleForSystemTx(tx, tenantId))) return [];
const memberships = await tx.projektMitglied.findMany({
where: withTenantScope(tenantId, {
groupId,
archivedAt: null,
projekt: { archivedAt: null },
}),
select: { projektId: true },
distinct: ["projektId"],
orderBy: { projektId: "asc" },
});
const projectIds = sortIdentifiers(memberships.map((membership) => membership.projektId));
for (const projectId of projectIds) {
await ensureAndSyncProjectChannelWithTx(tx, {
tenantId,
projectId,
actorUserId,
requestId: `${requestId}:project:${projectId}`,
});
}
return projectIds;
}
export async function archiveProjectChannelIfEnabledWithTx(
tx: DbTransactionClient,
input: ProjectChannelArchiveInput
): Promise<{ chatId: string; archived: boolean } | null> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const projectId = normalizeIdentifier(input.projectId, "projectId");
const actorUserId = normalizeOptionalIdentifier(input.actorUserId, "actorUserId");
const requestId = normalizeIdentifier(input.requestId, "requestId");
if (!(await tenantHasChatModuleForSystemTx(tx, tenantId))) return null;
await lockProjectChannel(tx, tenantId, projectId);
const channel = await tx.teamChat.findFirst({
where: withTenantScope(tenantId, { projektId: projectId, kind: "project" as const, archivedAt: null }),
select: { id: true, eventStreamId: true },
});
if (!channel) return null;
const archivedAt = input.archivedAt ?? new Date();
await writeAndWakeProjectSystemMessage(tx, {
tenantId,
chatId: channel.id,
systemEventKey: `project:${projectId}:archived:${stableEventKeyPart(requestId)}`,
requestId: `${requestId}:system:channel-archived`,
kind: "channel_archived",
metadata: { projectId, reason: input.reason },
actorUserId,
});
const archived = await tx.teamChat.updateMany({
where: withTenantScope(tenantId, { id: channel.id, projektId: projectId, kind: "project" as const, archivedAt: null }),
data: { archivedAt, archivedReason: input.reason },
});
if (archived.count !== 1) throw new Error("Project channel archive changed outside its transaction lock");
await lockChatEventStream(tx, tenantId, channel.id);
const archivedEvent = await tx.teamChatEvent.create({
data: withTenantScope(tenantId, {
chatId: channel.id,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.channelArchived),
actorUserId,
entityId: projectId,
requestId,
data: { archivedAt: archivedAt.toISOString(), reason: input.reason } as Prisma.InputJsonValue,
}),
select: PERSISTED_EVENT_SELECT,
});
await publishPersistedProjectEventWakeup(tx, channel.eventStreamId, archivedEvent);
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId,
actorId: actorUserId,
actorType: actorUserId ? "user" : "system",
action: "chat.project.archived",
targetType: "TeamChat",
targetId: channel.id,
requestId,
sourceModule: "chat",
dataSensitivity: "internal",
metadata: { projectId, reason: input.reason, archivedAt: archivedAt.toISOString() },
summaryText: "Der Projektchat wurde nach Projektabschluss archiviert.",
});
await logActivity(
{
tenantId,
actorUserId,
actorKind: actorUserId ? "user" : "system",
activityType: "audit_event",
subjectType: "project",
subjectId: projectId,
summaryText: "activity.runtime.chat.projectChatArchived",
metadata: { sourceModule: "chat", chatId: channel.id, reason: input.reason },
},
{ client: tx }
);
return { chatId: channel.id, archived: true };
}
type ProjectRecord = Readonly<{
id: string;
projektname: string;
projektNummer: string;
projektleiterId: string | null;
zustaendigePersonId: string | null;
isDemoData: boolean;
}>;
type ProjectChannelRecord = Readonly<{
id: string;
eventStreamId: string;
name: string | null;
description: string | null;
isDemoData: boolean;
notificationDefault: "all_messages" | "mentions_only" | "muted";
}>;
type ExistingProjectChatMember = Readonly<{
id: string;
userId: string;
roleInChat: "admin" | "member";
isProjectManaged: boolean;
isManualMember: boolean;
isGroupManaged: boolean;
manualRoleInChat: "admin" | "member" | null;
projectRoleInChat: "admin" | "member" | null;
writeRevokedAt: Date | null;
leftAt: Date | null;
}>;
/**
* Ensure the one project-linked channel and reconcile all project-derived
* members inside the caller's existing tenant/RLS transaction.
*
* Project membership and a manual invite are independent grants. Losing the
* project source therefore never deletes a row or sets `leftAt`: pure project
* members retain read access but receive `writeRevokedAt`, while manual guests
* remain untouched and writable.
*/
export async function ensureAndSyncProjectChannelWithTx(tx: DbTransactionClient, input: ProjectChannelSyncInput): Promise<ProjectChannelSyncResult> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const projectId = normalizeIdentifier(input.projectId, "projectId");
const actorUserId = normalizeOptionalIdentifier(input.actorUserId, "actorUserId");
const requestId = input.requestId === undefined ? randomUUID() : normalizeIdentifier(input.requestId, "requestId");
const changedAt = new Date();
await lockProjectChannel(tx, tenantId, projectId);
const project = await requireProject(tx, tenantId, projectId);
const channelState = await ensureProjectChannel(tx, tenantId, project, actorUserId, input.reactivateArchived === true);
if (!channelState.reconcileMembers) {
return {
chatId: channelState.channel.id,
created: false,
reactivated: false,
metadataUpdated: false,
changed: false,
effectiveUserIds: [],
projectSourceAddedUserIds: [],
projectSourceRemovedUserIds: [],
writeRestoredUserIds: [],
writeRevokedUserIds: [],
};
}
const existingMembers = await listProjectChannelMembers(tx, tenantId, channelState.channel.id);
const effectiveMembers = await resolveEffectiveProjectMembers(
tx,
tenantId,
project,
existingMembers.map((member) => member.userId)
);
const existingByUserId = new Map(existingMembers.map((member) => [member.userId, member]));
const previousProjectLeaderUserId =
existingMembers.find((member) => member.isProjectManaged && member.projectRoleInChat === "admin")?.userId ?? null;
const projectSourceAddedUserIds: string[] = [];
const projectSourceRemovedUserIds: string[] = [];
const writeRestoredUserIds: string[] = [];
const writeRevokedUserIds: string[] = [];
const roleChangedUserIds: string[] = [];
const createdMemberUserIds: string[] = [];
const effectiveRoleByUserId = new Map<string, "admin" | "member">();
for (const userId of effectiveMembers.userIds) {
const existing = existingByUserId.get(userId);
const desiredProjectRole = userId === project.projektleiterId ? "admin" : "member";
const desiredRole = resolveEffectiveChatMemberRole({
isManualMember: existing?.isManualMember ?? false,
manualRoleInChat: existing?.manualRoleInChat ?? null,
isProjectManaged: true,
projectRoleInChat: desiredProjectRole,
isGroupManaged: existing?.isGroupManaged ?? false,
});
if (!existing) {
await createProjectChatMember(tx, {
tenantId,
chatId: channelState.channel.id,
userId,
joinedAt: changedAt,
joinedViaUserId: actorUserId,
roleInChat: desiredRole,
notificationPref: channelState.channel.notificationDefault,
isProjectManaged: true,
isManualMember: false,
isGroupManaged: false,
manualRoleInChat: null,
projectRoleInChat: desiredProjectRole,
writeRevokedAt: null,
leftAt: null,
});
projectSourceAddedUserIds.push(userId);
writeRestoredUserIds.push(userId);
createdMemberUserIds.push(userId);
effectiveRoleByUserId.set(userId, desiredRole);
continue;
}
const sourceAdded = !existing.isProjectManaged;
const writeRestored = existing.leftAt !== null || existing.writeRevokedAt !== null;
const roleChanged = existing.roleInChat !== desiredRole || existing.projectRoleInChat !== desiredProjectRole;
if (!sourceAdded && !writeRestored && !roleChanged) continue;
const update: Prisma.TeamChatMemberUncheckedUpdateManyInput = {
isProjectManaged: true,
projectRoleInChat: desiredProjectRole,
roleInChat: desiredRole,
writeRevokedAt: null,
leftAt: null,
...(writeRestored ? { joinedAt: changedAt, joinedViaUserId: actorUserId } : {}),
};
await updateProjectChatMember(tx, tenantId, channelState.channel.id, existing.id, userId, update);
if (sourceAdded) projectSourceAddedUserIds.push(userId);
if (writeRestored) {
writeRestoredUserIds.push(userId);
effectiveRoleByUserId.set(userId, desiredRole);
}
if (roleChanged) roleChangedUserIds.push(userId);
}
for (const existing of existingMembers) {
if (!existing.isProjectManaged || effectiveMembers.userIdSet.has(existing.userId)) continue;
projectSourceRemovedUserIds.push(existing.userId);
const remainingSources = {
isManualMember: existing.isManualMember,
manualRoleInChat: existing.manualRoleInChat,
isProjectManaged: false,
projectRoleInChat: null,
isGroupManaged: existing.isGroupManaged,
} as const;
const remainsWritable = hasActiveChatMembershipSource(remainingSources);
const desiredRole = resolveEffectiveChatMemberRole(remainingSources);
await updateProjectChatMember(tx, tenantId, channelState.channel.id, existing.id, existing.userId, {
isProjectManaged: false,
projectRoleInChat: null,
roleInChat: desiredRole,
...(remainsWritable
? { writeRevokedAt: null, leftAt: null }
: {
writeRevokedAt: changedAt,
// L.6: former project members remain readable until auto-archive.
leftAt: null,
}),
});
if (existing.roleInChat !== desiredRole || existing.projectRoleInChat !== null) {
roleChangedUserIds.push(existing.userId);
}
if (!remainsWritable) writeRevokedUserIds.push(existing.userId);
}
if (writeRestoredUserIds.length > 0 || writeRevokedUserIds.length > 0) {
await lockChatEventStream(tx, tenantId, channelState.channel.id);
await appendMembershipEvents(tx, {
tenantId,
chatId: channelState.channel.id,
eventStreamId: channelState.channel.eventStreamId,
actorUserId,
requestId,
changedAt,
projectLeaderUserId: project.projektleiterId,
writeRestoredUserIds,
writeRevokedUserIds,
effectiveRoleByUserId,
});
}
await appendProjectTimelineSystemMessages(tx, {
tenantId,
project,
chatId: channelState.channel.id,
actorUserId,
requestId,
created: channelState.created,
previousProjectLeaderUserId,
createdMemberUserIds,
writeRestoredUserIds: writeRestoredUserIds.filter((userId) => !createdMemberUserIds.includes(userId)),
writeRevokedUserIds,
labelsByUserId: effectiveMembers.labelsByUserId,
});
const changed =
channelState.created ||
channelState.reactivated ||
channelState.metadataUpdated ||
projectSourceAddedUserIds.length > 0 ||
projectSourceRemovedUserIds.length > 0 ||
writeRestoredUserIds.length > 0 ||
writeRevokedUserIds.length > 0 ||
roleChangedUserIds.length > 0;
if (changed) {
await recordProjectChannelSync(tx, {
tenantId,
projectId,
chatId: channelState.channel.id,
actorUserId,
requestId,
created: channelState.created,
reactivated: channelState.reactivated,
metadataUpdated: channelState.metadataUpdated,
projectSourceAddedUserIds,
projectSourceRemovedUserIds,
writeRestoredUserIds,
writeRevokedUserIds,
roleChangedUserIds,
});
}
return {
chatId: channelState.channel.id,
created: channelState.created,
reactivated: channelState.reactivated,
metadataUpdated: channelState.metadataUpdated,
changed,
effectiveUserIds: effectiveMembers.userIds,
projectSourceAddedUserIds: sortIdentifiers(projectSourceAddedUserIds),
projectSourceRemovedUserIds: sortIdentifiers(projectSourceRemovedUserIds),
writeRestoredUserIds: sortIdentifiers(writeRestoredUserIds),
writeRevokedUserIds: sortIdentifiers(writeRevokedUserIds),
};
}
async function requireProject(tx: DbTransactionClient, tenantId: string, projectId: string): Promise<ProjectRecord> {
const project = await tx.projekt.findFirst({
where: withTenantScope(tenantId, { id: projectId, archivedAt: null }),
select: {
id: true,
projektname: true,
projektNummer: true,
projektleiterId: true,
zustaendigePersonId: true,
isDemoData: true,
},
});
if (!project) throw new Error("Project channel sync requires a tenant-owned project");
return project;
}
async function ensureProjectChannel(
tx: DbTransactionClient,
tenantId: string,
project: ProjectRecord,
actorUserId: string | null,
reactivateArchived: boolean
): Promise<{ channel: ProjectChannelRecord; created: boolean; reactivated: boolean; metadataUpdated: boolean; reconcileMembers: boolean }> {
const description = projectChannelDescription(project);
const activeChannel = await tx.teamChat.findFirst({
where: withTenantScope(tenantId, { projektId: project.id, kind: "project" as const, archivedAt: null }),
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
select: { id: true, eventStreamId: true, name: true, description: true, isDemoData: true, notificationDefault: true },
});
if (activeChannel) {
const metadataUpdated = await syncProjectChannelMetadata(tx, tenantId, activeChannel, project.projektname, description, project.isDemoData);
return {
channel: { ...activeChannel, name: project.projektname, description, isDemoData: project.isDemoData },
created: false,
reactivated: false,
metadataUpdated,
reconcileMembers: true,
};
}
const archivedChannel = await tx.teamChat.findFirst({
where: withTenantScope(tenantId, { projektId: project.id, kind: "project" as const, archivedAt: { not: null } }),
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
select: { id: true, eventStreamId: true, name: true, description: true, isDemoData: true, notificationDefault: true },
});
if (archivedChannel && reactivateArchived) {
const updated = await tx.teamChat.updateMany({
where: withTenantScope(tenantId, { id: archivedChannel.id, projektId: project.id, kind: "project" as const, archivedAt: { not: null } }),
data: { archivedAt: null, archivedReason: null, name: project.projektname, description, isDemoData: project.isDemoData },
});
if (updated.count !== 1) throw new Error("Project channel reactivation lost its transaction lock");
return {
channel: { ...archivedChannel, name: project.projektname, description, isDemoData: project.isDemoData },
created: false,
reactivated: true,
metadataUpdated:
archivedChannel.name !== project.projektname || archivedChannel.description !== description || archivedChannel.isDemoData !== project.isDemoData,
reconcileMembers: true,
};
}
if (archivedChannel) {
return { channel: archivedChannel, created: false, reactivated: false, metadataUpdated: false, reconcileMembers: false };
}
const channel = await tx.teamChat.create({
data: withTenantScope(tenantId, {
createdByUserId: actorUserId,
kind: "project",
name: project.projektname,
description,
projektId: project.id,
isPrivate: true,
archivedAt: null,
archivedReason: null,
dmPairKey: null,
isDemoData: project.isDemoData,
}),
select: { id: true, eventStreamId: true, name: true, description: true, isDemoData: true, notificationDefault: true },
});
return { channel, created: true, reactivated: false, metadataUpdated: false, reconcileMembers: true };
}
async function syncProjectChannelMetadata(
tx: DbTransactionClient,
tenantId: string,
channel: ProjectChannelRecord,
projectName: string,
description: string,
isDemoData: boolean
): Promise<boolean> {
if (channel.name === projectName && channel.description === description && channel.isDemoData === isDemoData) return false;
const updated = await tx.teamChat.updateMany({
where: withTenantScope(tenantId, { id: channel.id, kind: "project" as const }),
data: { name: projectName, description, isDemoData },
});
if (updated.count !== 1) throw new Error("Project channel metadata changed outside its transaction lock");
return true;
}
function projectChannelDescription(project: ProjectRecord): string {
return `Projekt-Chat für ${project.projektname}, ${project.projektNummer}`;
}
async function resolveEffectiveProjectMembers(
tx: DbTransactionClient,
tenantId: string,
project: ProjectRecord,
existingChatUserIds: readonly string[]
): Promise<{ userIds: string[]; userIdSet: ReadonlySet<string>; labelsByUserId: ReadonlyMap<string, string> }> {
const projectMembers = await tx.projektMitglied.findMany({
where: withTenantScope(tenantId, { projektId: project.id, archivedAt: null }),
select: { userId: true, groupId: true },
});
const groupIds = sortIdentifiers(projectMembers.flatMap((member) => (member.groupId ? [member.groupId] : [])));
const groups =
groupIds.length === 0
? []
: await tx.group.findMany({
where: withTenantScope(tenantId, { id: { in: groupIds } }),
select: { users: { select: { userId: true } } },
});
const candidateUserIds = sortIdentifiers([
...(project.projektleiterId ? [project.projektleiterId] : []),
...(project.zustaendigePersonId ? [project.zustaendigePersonId] : []),
...projectMembers.flatMap((member) => (member.userId ? [member.userId] : [])),
...groups.flatMap((group) => group.users.map((membership) => membership.userId)),
]);
const lookupUserIds = sortIdentifiers([...candidateUserIds, ...existingChatUserIds]);
if (lookupUserIds.length === 0) return { userIds: [], userIdSet: new Set(), labelsByUserId: new Map() };
const activeTenantUsers = await tx.tenantUser.findMany({
where: withTenantScope(tenantId, {
userId: { in: lookupUserIds },
status: ACTIVE_TENANT_USER_STATUS,
user: { active: true, pendingDeletion: false, pseudonymized: false },
}),
select: {
userId: true,
user: { select: { firstName: true, lastName: true, email: true } },
},
});
const activeUserIdSet = new Set(activeTenantUsers.map((membership) => membership.userId));
const userIds = candidateUserIds.filter((userId) => activeUserIdSet.has(userId));
const labelsByUserId = new Map(
activeTenantUsers.map((membership) => [membership.userId, chatUserDisplayName(membership.user)] as const)
);
return { userIds, userIdSet: new Set(userIds), labelsByUserId };
}
function chatUserDisplayName(user: { firstName: string | null; lastName: string | null; email: string }): string {
return [user.firstName, user.lastName]
.map((part) => part?.trim())
.filter((part): part is string => Boolean(part))
.join(" ") || user.email;
}
async function listProjectChannelMembers(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<ExistingProjectChatMember[]> {
return tx.teamChatMember.findMany({
where: withTenantScope(tenantId, { chatId }),
orderBy: { userId: "asc" },
select: {
id: true,
userId: true,
roleInChat: true,
isProjectManaged: true,
isManualMember: true,
isGroupManaged: true,
manualRoleInChat: true,
projectRoleInChat: true,
writeRevokedAt: true,
leftAt: true,
},
});
}
async function createProjectChatMember(tx: DbTransactionClient, data: Prisma.TeamChatMemberUncheckedCreateInput): Promise<void> {
await tx.teamChatMember.create({
data,
select: { id: true },
});
}
async function updateProjectChatMember(
tx: DbTransactionClient,
tenantId: string,
chatId: string,
memberId: string,
userId: string,
data: Prisma.TeamChatMemberUncheckedUpdateManyInput
): Promise<void> {
const updated = await tx.teamChatMember.updateMany({
where: withTenantScope(tenantId, { id: memberId, chatId, userId }),
data,
});
if (updated.count !== 1) throw new Error("Project channel membership changed outside its transaction lock");
}
async function appendMembershipEvents(
tx: DbTransactionClient,
input: Readonly<{
tenantId: string;
chatId: string;
eventStreamId: string;
actorUserId: string | null;
requestId: string;
changedAt: Date;
projectLeaderUserId: string | null;
writeRestoredUserIds: readonly string[];
writeRevokedUserIds: readonly string[];
effectiveRoleByUserId: ReadonlyMap<string, "admin" | "member">;
}>
): Promise<void> {
for (const userId of sortIdentifiers(input.writeRestoredUserIds)) {
const event = await tx.teamChatEvent.create({
data: withTenantScope(input.tenantId, {
chatId: input.chatId,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.memberAdded),
actorUserId: input.actorUserId,
entityId: userId,
requestId: `${input.requestId}:member-added:${userId}`,
data: {
userId,
roleInChat: input.effectiveRoleByUserId.get(userId) ?? (userId === input.projectLeaderUserId ? "admin" : "member"),
joinedAt: input.changedAt.toISOString(),
} as Prisma.InputJsonValue,
}),
select: PERSISTED_EVENT_SELECT,
});
await publishPersistedProjectEventWakeup(tx, input.eventStreamId, event);
}
for (const userId of sortIdentifiers(input.writeRevokedUserIds)) {
const event = await tx.teamChatEvent.create({
data: withTenantScope(input.tenantId, {
chatId: input.chatId,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.memberRemoved),
actorUserId: input.actorUserId,
entityId: userId,
requestId: `${input.requestId}:member-removed:${userId}`,
data: {
userId,
// The persistent wire contract calls the revocation timestamp
// `leftAt`; the membership row deliberately keeps leftAt=null so
// project history remains readable per spec L.6.
leftAt: input.changedAt.toISOString(),
} as Prisma.InputJsonValue,
}),
select: PERSISTED_EVENT_SELECT,
});
await publishPersistedProjectEventWakeup(tx, input.eventStreamId, event);
}
}
async function appendProjectTimelineSystemMessages(
tx: DbTransactionClient,
input: Readonly<{
tenantId: string;
project: ProjectRecord;
chatId: string;
actorUserId: string | null;
requestId: string;
created: boolean;
previousProjectLeaderUserId: string | null;
createdMemberUserIds: readonly string[];
writeRestoredUserIds: readonly string[];
writeRevokedUserIds: readonly string[];
labelsByUserId: ReadonlyMap<string, string>;
}>
): Promise<void> {
const projectKey = stableEventKeyPart(input.project.id);
const transitionKey = stableEventKeyPart(input.requestId);
if (input.created) {
await writeAndWakeProjectSystemMessage(tx, {
tenantId: input.tenantId,
chatId: input.chatId,
systemEventKey: `project:${projectKey}:created`,
requestId: `chat-project:${projectKey}:created`,
kind: "project_created",
metadata: {
projectId: input.project.id,
projectName: input.project.projektname,
projectNumber: input.project.projektNummer,
},
actorUserId: input.actorUserId,
isDemoData: input.project.isDemoData,
});
}
const leaderChanged =
!input.created && input.previousProjectLeaderUserId !== input.project.projektleiterId;
if (leaderChanged) {
const previousLeaderUserId = input.previousProjectLeaderUserId;
const newLeaderUserId = input.project.projektleiterId;
await writeAndWakeProjectSystemMessage(tx, {
tenantId: input.tenantId,
chatId: input.chatId,
systemEventKey: `project:${projectKey}:leader:${transitionKey}`,
requestId: `chat-project:${projectKey}:leader:${transitionKey}`,
kind: "project_leader_changed",
metadata: {
projectId: input.project.id,
...(previousLeaderUserId
? {
previousLeaderUserId,
previousLeaderName: input.labelsByUserId.get(previousLeaderUserId) ?? previousLeaderUserId,
}
: {}),
...(newLeaderUserId
? {
newLeaderUserId,
newLeaderName: input.labelsByUserId.get(newLeaderUserId) ?? newLeaderUserId,
}
: {}),
},
actorUserId: input.actorUserId,
isDemoData: input.project.isDemoData,
});
}
for (const userId of sortIdentifiers(input.createdMemberUserIds)) {
const userKey = stableEventKeyPart(userId);
await writeAndWakeProjectSystemMessage(tx, {
tenantId: input.tenantId,
chatId: input.chatId,
systemEventKey: `project:${projectKey}:member:${userKey}:added:${transitionKey}`,
requestId: `chat-project:${projectKey}:member-added:${userKey}:${transitionKey}`,
kind: "member_added",
metadata: { memberUserId: userId, memberName: input.labelsByUserId.get(userId) ?? userId },
actorUserId: input.actorUserId,
isDemoData: input.project.isDemoData,
});
}
for (const userId of sortIdentifiers(input.writeRestoredUserIds)) {
await writeProjectMemberWriteAccessSystemMessage(tx, input, projectKey, transitionKey, userId, true);
}
for (const userId of sortIdentifiers(input.writeRevokedUserIds)) {
await writeProjectMemberWriteAccessSystemMessage(tx, input, projectKey, transitionKey, userId, false);
}
}
async function writeProjectMemberWriteAccessSystemMessage(
tx: DbTransactionClient,
input: Readonly<{
tenantId: string;
project: ProjectRecord;
chatId: string;
actorUserId: string | null;
labelsByUserId: ReadonlyMap<string, string>;
}>,
projectKey: string,
transitionKey: string,
userId: string,
canWrite: boolean
): Promise<void> {
const userKey = stableEventKeyPart(userId);
const access = canWrite ? "granted" : "revoked";
await writeAndWakeProjectSystemMessage(tx, {
tenantId: input.tenantId,
chatId: input.chatId,
systemEventKey: `project:${projectKey}:member:${userKey}:write-${access}:${transitionKey}`,
requestId: `chat-project:${projectKey}:write-${access}:${userKey}:${transitionKey}`,
kind: "member_write_access_changed",
metadata: {
memberUserId: userId,
memberName: input.labelsByUserId.get(userId) ?? userId,
canWrite,
},
actorUserId: input.actorUserId,
isDemoData: input.project.isDemoData,
});
}
async function recordProjectChannelSync(
tx: DbTransactionClient,
input: Readonly<{
tenantId: string;
projectId: string;
chatId: string;
actorUserId: string | null;
requestId: string;
created: boolean;
reactivated: boolean;
metadataUpdated: boolean;
projectSourceAddedUserIds: readonly string[];
projectSourceRemovedUserIds: readonly string[];
writeRestoredUserIds: readonly string[];
writeRevokedUserIds: readonly string[];
roleChangedUserIds: readonly string[];
}>
): Promise<void> {
const metadata = {
projectId: input.projectId,
created: input.created,
reactivated: input.reactivated,
metadataUpdated: input.metadataUpdated,
projectSourceAddedUserIds: sortIdentifiers(input.projectSourceAddedUserIds),
projectSourceRemovedUserIds: sortIdentifiers(input.projectSourceRemovedUserIds),
writeRestoredUserIds: sortIdentifiers(input.writeRestoredUserIds),
writeRevokedUserIds: sortIdentifiers(input.writeRevokedUserIds),
roleChangedUserIds: sortIdentifiers(input.roleChangedUserIds),
};
const summaryText = input.created
? "Der Projektchat wurde erstellt und mit den Projektmitgliedern synchronisiert."
: "Die Mitgliedschaften des Projektchats wurden synchronisiert.";
const activitySummaryKey = input.created
? "activity.runtime.chat.projectChatCreated"
: "activity.runtime.chat.projectMembersSynced";
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId: input.tenantId,
actorId: input.actorUserId,
actorType: input.actorUserId ? "user" : "system",
action: input.created ? "chat.project.created" : "chat.project.members_synced",
targetType: "TeamChat",
targetId: input.chatId,
requestId: input.requestId,
sourceModule: "chat",
dataSensitivity: "internal",
metadata,
summaryText,
});
await logActivity(
{
tenantId: input.tenantId,
actorUserId: input.actorUserId,
actorKind: input.actorUserId ? "user" : "system",
activityType: "audit_event",
subjectType: "project",
subjectId: input.projectId,
summaryText: activitySummaryKey,
metadata: { sourceModule: "chat", chatId: input.chatId, ...metadata },
},
{ client: tx }
);
}
async function lockProjectChannel(tx: DbTransactionClient, tenantId: string, projectId: string): Promise<void> {
const lockKey = `project-channel:${tenantId}:${projectId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${PROJECT_CHANNEL_LOCK_SALT}))`;
}
async function lockChatEventStream(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<void> {
const lockKey = `chat-event:${tenantId}:${chatId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${CHAT_EVENT_LOCK_SALT}))`;
}
async function writeAndWakeProjectSystemMessage(
tx: DbTransactionClient,
input: Parameters<typeof writeChatSystemMessageWithTx>[1]
): Promise<void> {
const result = await writeChatSystemMessageWithTx(tx, input);
if (!result.replayed) {
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event: result.event });
}
}
async function publishPersistedProjectEventWakeup(
tx: DbTransactionClient,
eventStreamId: string,
row: PersistedProjectEvent
): Promise<void> {
const event = validateChatServerEvent({
event: toChatPersistentEventName(row.type),
cursor: `${eventStreamId}:${row.sequence.toString()}`,
requestId: row.requestId,
tenantId: row.tenantId,
chatId: row.chatId,
occurredAt: row.occurredAt.toISOString(),
data: row.data,
});
if (!isPersistentChatEvent(event)) throw new Error("Project chat mutation produced an ephemeral durable event");
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event });
}
function stableEventKeyPart(value: string): string {
return createHash("sha256").update(value).digest("hex").slice(0, 24);
}
function normalizeIdentifier(value: string, label: string): string {
if (typeof value !== "string") throw new Error(`${label} must be a string`);
const normalized = value.trim();
if (!normalized || normalized.includes("\0")) throw new Error(`${label} is invalid`);
return normalized;
}
function normalizeOptionalIdentifier(value: string | null | undefined, label: string): string | null {
return value == null ? null : normalizeIdentifier(value, label);
}
function sortIdentifiers(values: readonly string[]): string[] {
return [...new Set(values)].sort((left, right) => left.localeCompare(right));
}
@@ -0,0 +1,327 @@
// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { ensureAndSyncProjectChannelWithTx } from "./project-sync.server.js";
import { assertMemberChannelAccess, assertMemberChannelWriteAccess, getMemberChannelDetail, sendTopLevelChatMessage } from "./repository.server.js";
/**
* This suite deliberately skips during ordinary unit runs because a mocked
* client cannot prove FORCE RLS. Run it through
* `pnpm run verify:rls-live`; that gate owns a
* fresh database, applies the feature schema/policies, and supplies both the
* admin fixture URL and the restricted `hivegrid_app` runtime URL.
*/
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_ID = "chat_project_revoke_rls_tenant";
const USER_ID = "chat_project_revoke_rls_user";
const TENANT_USER_ID = "chat_project_revoke_rls_tenant_user";
const SESSION_ID = "chat_project_revoke_rls_session";
const ROLE_ID = "chat_project_revoke_rls_role";
const ROLE_NAME = "Chat project revocation RLS role";
const USER_ROLE_ID = "chat_project_revoke_rls_user_role";
const READ_PERMISSION_ID = "chat_project_revoke_rls_read_permission";
const WRITE_PERMISSION_ID = "chat_project_revoke_rls_write_permission";
const READ_ROLE_PERMISSION_ID = "chat_project_revoke_rls_read_role_permission";
const WRITE_ROLE_PERMISSION_ID = "chat_project_revoke_rls_write_role_permission";
const PIPELINE_ID = "chat_project_revoke_rls_pipeline";
const STAGE_ID = "chat_project_revoke_rls_stage";
const PROJECT_ID = "chat_project_revoke_rls_project";
const PROJECT_MEMBER_ID = "chat_project_revoke_rls_project_member";
const gatewayContext = { tenantId: TENANT_ID, userId: USER_ID, sessionId: SESSION_ID } as const;
describeIfDatabase("project-chat write revocation with the restricted app role", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
let readPermissionOwned = false;
let writePermissionOwned = false;
beforeAll(async () => {
await cleanupFixtures(admin);
await admin.user.create({
data: {
id: USER_ID,
email: "chat-project-revoke-rls@example.test",
firstName: "Project",
lastName: "Member",
active: true,
},
});
await admin.tenant.create({
data: {
id: TENANT_ID,
slug: TENANT_ID,
name: "Chat project revocation RLS tenant",
active: true,
},
});
await admin.tenantUser.create({
data: {
id: TENANT_USER_ID,
tenantId: TENANT_ID,
userId: USER_ID,
type: 0,
joined: 1,
status: 2,
},
});
await admin.pipeline.create({
data: {
id: PIPELINE_ID,
tenantId: TENANT_ID,
createdByUserId: USER_ID,
name: "Chat RLS project pipeline",
typHint: "auftrag",
},
});
await admin.pipelineStage.create({
data: {
id: STAGE_ID,
tenantId: TENANT_ID,
pipelineId: PIPELINE_ID,
name: "Active",
stageKind: "offen",
},
});
await admin.projekt.create({
data: {
id: PROJECT_ID,
tenantId: TENANT_ID,
createdByUserId: USER_ID,
projektNummer: "RLS-CHAT-001",
projektname: "Project chat revocation proof",
pipelineId: PIPELINE_ID,
stageId: STAGE_ID,
},
});
await admin.projektMitglied.create({
data: {
id: PROJECT_MEMBER_ID,
tenantId: TENANT_ID,
projektId: PROJECT_ID,
userId: USER_ID,
rolle: "monteur",
createdByUserId: USER_ID,
},
});
const readPermission = await ensurePermission(admin, {
fixtureId: READ_PERMISSION_ID,
name: CHAT_PERMISSIONS.readOwnChannels,
description: "Read permission for the live project-chat revocation proof",
});
readPermissionOwned = readPermission.owned;
const writePermission = await ensurePermission(admin, {
fixtureId: WRITE_PERMISSION_ID,
name: CHAT_PERMISSIONS.write,
description: "Write permission for the live project-chat revocation proof",
});
writePermissionOwned = writePermission.owned;
await admin.role.create({
data: {
id: ROLE_ID,
tenantId: null,
name: ROLE_NAME,
description: "Global app role for the live project-chat revocation proof",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 99_992,
},
});
await admin.rolePermission.createMany({
data: [
{ id: READ_ROLE_PERMISSION_ID, roleId: ROLE_ID, permissionId: readPermission.id },
{ id: WRITE_ROLE_PERMISSION_ID, roleId: ROLE_ID, permissionId: writePermission.id },
],
});
await admin.userRole.create({
data: {
id: USER_ROLE_ID,
tenantId: TENANT_ID,
userId: USER_ID,
roleId: ROLE_ID,
},
});
await admin.userSession.create({
data: {
id: SESSION_ID,
userId: USER_ID,
tokenHash: "chat_project_revoke_rls_session_hash",
expiresAt: new Date(Date.now() + 60 * 60 * 1_000),
},
});
});
afterAll(async () => {
await cleanupFixtures(admin);
if (readPermissionOwned) {
await admin.permission.deleteMany({ where: { id: READ_PERMISSION_ID, name: CHAT_PERMISSIONS.readOwnChannels } });
}
if (writePermissionOwned) {
await admin.permission.deleteMany({ where: { id: WRITE_PERMISSION_ID, name: CHAT_PERMISSIONS.write } });
}
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("keeps project history readable, blocks message and typing writes after removal, and restores writes after re-add", async () => {
const currentRole = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]);
const rlsState = await app.$queryRaw<Array<{ tableName: string; enabled: boolean; forced: boolean }>>`
SELECT relname AS "tableName", relrowsecurity AS enabled, relforcerowsecurity AS forced
FROM pg_catalog.pg_class
WHERE relnamespace = 'public'::regnamespace
AND relname IN ('Projekt', 'ProjektMitglied', 'TeamChat', 'TeamChatMember', 'TeamChatMessage')
ORDER BY relname ASC
`;
expect(rlsState).toHaveLength(5);
expect(rlsState.every((table) => table.enabled && table.forced)).toBe(true);
// No transaction-local RLS identity means the runtime role sees nothing.
await expect(app.projekt.findMany({ where: { id: PROJECT_ID }, select: { id: true } })).resolves.toEqual([]);
const initialSync = await syncProjectChannel(app, "chat_project_revoke_rls_initial_sync");
expect(initialSync).toMatchObject({
created: true,
projectSourceAddedUserIds: [USER_ID],
writeRestoredUserIds: [USER_ID],
writeRevokedUserIds: [],
});
const initialSend = await sendTopLevelChatMessage({
...gatewayContext,
chatId: initialSync.chatId,
clientMessageId: "chat_project_revoke_rls_initial_message",
requestId: "chat_project_revoke_rls_initial_message_request",
body: "History stays visible after project removal.",
});
expect(initialSend.replayed).toBe(false);
await expect(assertMemberChannelWriteAccess({ ...gatewayContext, chatId: initialSync.chatId })).resolves.toBeUndefined();
await admin.projektMitglied.update({
where: { id: PROJECT_MEMBER_ID },
data: { archivedAt: new Date("2026-07-16T10:00:00.000Z") },
});
const removalSync = await syncProjectChannel(app, "chat_project_revoke_rls_remove_sync");
expect(removalSync).toMatchObject({
chatId: initialSync.chatId,
projectSourceRemovedUserIds: [USER_ID],
writeRevokedUserIds: [USER_ID],
writeRestoredUserIds: [],
});
const historyAfterRemoval = await getMemberChannelDetail({ ...gatewayContext, chatId: initialSync.chatId });
expect(historyAfterRemoval.channel.member.canWrite).toBe(false);
expect(historyAfterRemoval.messages.map((message) => message.id)).toContain(initialSend.message.id);
await expect(assertMemberChannelAccess({ ...gatewayContext, chatId: initialSync.chatId })).resolves.toBeUndefined();
// The gateway invokes this exact live repository boundary before it emits
// a typing-started event, so rejection here proves typing stays silent.
await expect(assertMemberChannelWriteAccess({ ...gatewayContext, chatId: initialSync.chatId })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
sendTopLevelChatMessage({
...gatewayContext,
chatId: initialSync.chatId,
clientMessageId: "chat_project_revoke_rls_denied_message",
requestId: "chat_project_revoke_rls_denied_message_request",
body: "This message must never be persisted.",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
admin.teamChatMessage.count({
where: { tenantId: TENANT_ID, chatId: initialSync.chatId, clientMessageId: "chat_project_revoke_rls_denied_message" },
})
).resolves.toBe(0);
await admin.projektMitglied.update({
where: { id: PROJECT_MEMBER_ID },
data: { archivedAt: null },
});
const reAddSync = await syncProjectChannel(app, "chat_project_revoke_rls_readd_sync");
expect(reAddSync).toMatchObject({
chatId: initialSync.chatId,
projectSourceAddedUserIds: [USER_ID],
writeRestoredUserIds: [USER_ID],
writeRevokedUserIds: [],
});
const historyAfterReAdd = await getMemberChannelDetail({ ...gatewayContext, chatId: initialSync.chatId });
expect(historyAfterReAdd.channel.member.canWrite).toBe(true);
expect(historyAfterReAdd.messages.map((message) => message.id)).toContain(initialSend.message.id);
// The same boundary now permits typing again.
await expect(assertMemberChannelWriteAccess({ ...gatewayContext, chatId: initialSync.chatId })).resolves.toBeUndefined();
await expect(
sendTopLevelChatMessage({
...gatewayContext,
chatId: initialSync.chatId,
clientMessageId: "chat_project_revoke_rls_restored_message",
requestId: "chat_project_revoke_rls_restored_message_request",
body: "Writing is restored after the project member is re-added.",
})
).resolves.toMatchObject({ replayed: false });
});
});
async function syncProjectChannel(app: ReturnType<typeof getWriteDbClient>, requestId: string) {
return runWithRlsContext({ tenantId: TENANT_ID, userId: USER_ID }, () =>
app.$transaction((tx) =>
ensureAndSyncProjectChannelWithTx(tx, {
tenantId: TENANT_ID,
projectId: PROJECT_ID,
actorUserId: USER_ID,
requestId,
})
)
);
}
async function ensurePermission(
admin: ReturnType<typeof createDbClient>,
input: Readonly<{ fixtureId: string; name: string; description: string }>
): Promise<{ id: string; owned: boolean }> {
const existing = await admin.permission.findUnique({ where: { name: input.name }, select: { id: true } });
if (existing) return { id: existing.id, owned: existing.id === input.fixtureId };
const created = await admin.permission.create({
data: {
id: input.fixtureId,
name: input.name,
description: input.description,
type: "app",
isDefault: false,
order: 99_992,
},
select: { id: true },
});
return { id: created.id, owned: true };
}
async function cleanupFixtures(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.teamChatMember.updateMany({ where: { tenantId: TENANT_ID }, data: { lastReadMessageId: null, lastReadAt: null } });
await admin.teamChatEvent.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.teamChatMessage.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.teamChatMember.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.teamChat.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.activity.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.outboxEvent.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.projektMitglied.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.projekt.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.pipelineStage.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.pipeline.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.userSession.deleteMany({ where: { id: SESSION_ID } });
await admin.userRole.deleteMany({ where: { id: USER_ROLE_ID } });
await admin.rolePermission.deleteMany({ where: { roleId: ROLE_ID } });
await admin.role.deleteMany({ where: { OR: [{ id: ROLE_ID }, { tenantId: null, name: ROLE_NAME }] } });
await admin.tenantUser.deleteMany({ where: { tenantId: TENANT_ID } });
await admin.tenant.deleteMany({ where: { id: TENANT_ID } });
await admin.user.deleteMany({ where: { id: USER_ID } });
}
@@ -0,0 +1,92 @@
import type { OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { CHAT_EVENT_NAMES, type ChatPersistentEvent } from "@hivegrid/realtime";
import { describe, expect, it, vi } from "vitest";
import {
CHAT_PERSISTENT_REALTIME_OUTBOX_EVENT_TYPE,
buildChatPersistentRealtimeDispatchKey,
publishChatPersistentRealtimeWakeup,
} from "./realtime-wakeup.server.js";
function persistentEvent(overrides: Partial<ChatPersistentEvent> = {}): ChatPersistentEvent {
return {
event: CHAT_EVENT_NAMES.readReceipt,
cursor: "stream_1:7",
requestId: "request_1",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-16T08:00:00.000Z",
data: {
messageId: "message_1",
userId: "user_1",
readAt: "2026-07-16T08:00:00.000Z",
},
...overrides,
} as ChatPersistentEvent;
}
function fakeTransaction() {
const create = vi.fn(async ({ data }: { data: Record<string, unknown> }) => ({
id: "outbox_1",
status: "PENDING",
createdAt: new Date("2026-07-16T08:00:00.000Z"),
processedAt: null,
retries: 0,
lastError: null,
scheduledAt: new Date("2026-07-16T08:00:00.000Z"),
priority: 0,
lockedUntil: null,
...data,
}));
const findUnique = vi.fn(async () => null);
const tx = { outboxEvent: { create, findUnique } } as unknown as OutboxPublisherTransaction;
return { tx, create };
}
describe("publishChatPersistentRealtimeWakeup", () => {
it("writes the complete persistent event to the transactional outbox", async () => {
const { tx, create } = fakeTransaction();
const event = persistentEvent();
await publishChatPersistentRealtimeWakeup(tx, { event });
expect(create).toHaveBeenCalledWith({
data: {
tenantId: "tenant_1",
eventType: CHAT_PERSISTENT_REALTIME_OUTBOX_EVENT_TYPE,
payload: { event },
dispatchKey: buildChatPersistentRealtimeDispatchKey(event),
},
});
});
it("builds a stable, bounded and PII-free dispatch key", () => {
const event = persistentEvent();
const key = buildChatPersistentRealtimeDispatchKey(event);
expect(key).toMatch(/^chat-realtime:[a-f0-9]{64}$/);
expect(key).toBe(buildChatPersistentRealtimeDispatchKey({ ...event }));
expect(key).not.toContain(event.tenantId);
expect(key).not.toContain(event.chatId);
expect(key.length).toBeLessThanOrEqual(256);
});
it("rejects ephemeral or malformed events before writing", async () => {
const { tx, create } = fakeTransaction();
await expect(
publishChatPersistentRealtimeWakeup(tx, {
event: {
event: CHAT_EVENT_NAMES.typingStarted,
cursor: null,
requestId: "request_1",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-16T08:00:00.000Z",
data: { userId: "user_1" },
} as unknown as ChatPersistentEvent,
})
).rejects.toThrow("persistent chat event");
expect(create).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,35 @@
import { createHash } from "node:crypto";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { isPersistentChatEvent, validateChatServerEvent, type ChatPersistentEvent } from "@hivegrid/realtime";
export const CHAT_PERSISTENT_REALTIME_OUTBOX_EVENT_TYPE = "chat.realtime.persistent" as const;
export type PublishChatPersistentRealtimeWakeupInput = Readonly<{
event: ChatPersistentEvent;
}>;
/**
* Persists a crash-safe Redis wakeup descriptor in the caller's transaction.
* The durable TeamChatEvent ledger remains the source of truth; Redis only
* prompts connected gateways to gap-fill that ledger from the event cursor.
*/
export async function publishChatPersistentRealtimeWakeup(tx: OutboxPublisherTransaction, input: PublishChatPersistentRealtimeWakeupInput) {
const event = validateChatServerEvent(input.event);
if (!isPersistentChatEvent(event)) {
throw new Error("chat realtime wakeup requires a persistent chat event");
}
return publishOutboxEvent(tx, {
tenantId: event.tenantId,
type: CHAT_PERSISTENT_REALTIME_OUTBOX_EVENT_TYPE,
payload: { event } as unknown as Prisma.InputJsonValue,
dispatchKey: buildChatPersistentRealtimeDispatchKey(event),
});
}
export function buildChatPersistentRealtimeDispatchKey(event: ChatPersistentEvent): string {
const digest = createHash("sha256").update(event.tenantId).update("\0").update(event.chatId).update("\0").update(event.cursor).digest("hex");
return `chat-realtime:${digest}`;
}
@@ -0,0 +1,915 @@
// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { CHAT_EVENT_NAMES } from "@hivegrid/realtime";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { loadChatChannelSettings } from "./channel-settings.server.js";
import { setChatMemberPreferences } from "./member-preferences.server.js";
import {
assertMemberChannelAccess,
authorizeChatGatewayConnection,
fillChatEventGap,
getMemberChannelDetail,
listMemberChannels,
markChatMessageRead,
revalidateChatGatewayAccess,
sendTopLevelChatMessage,
} from "./repository.server.js";
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_A = "chat_repo_rls_tenant_a";
const TENANT_B = "chat_repo_rls_tenant_b";
const MEMBER_A = "chat_repo_rls_member_a";
const OUTSIDER_A = "chat_repo_rls_outsider_a";
const MEMBER_B = "chat_repo_rls_member_b";
const CHAT_A = "chat_repo_rls_channel_a";
const STREAM_A = "chat_repo_rls_stream_a";
const SEARCH_MEMBER_A = "chat_repo_rls_search_member_a";
const PAGE_CHAT_NEWER = "chat_repo_rls_page_channel_newer";
const PAGE_CHAT_OLDER = "chat_repo_rls_page_channel_older";
const PAGE_CHAT_FOREIGN = "chat_repo_rls_page_channel_foreign";
const PAGE_MESSAGE_OLDER = "chat_repo_rls_page_message_older";
const CLIENT_MESSAGE_ID = "chat_repo_rls_client_message_a";
const REQUEST_ID = "chat_repo_rls_request_a";
const GLOBAL_APP_ROLE_ID = "chat_repo_rls_global_app_role";
const GLOBAL_APP_ROLE_NAME = "Chat Repository RLS Global App Role";
const READ_PERMISSION_FIXTURE_ID = "chat_repo_rls_read_permission";
const WRITE_PERMISSION_FIXTURE_ID = "chat_repo_rls_write_permission";
const FILES_READ_PERMISSION_FIXTURE_ID = "chat_repo_rls_files_read_permission";
const FILES_WRITE_PERMISSION_FIXTURE_ID = "chat_repo_rls_files_write_permission";
const MEMBER_A_ROLE_ID = "chat_repo_rls_member_a_role";
const OUTSIDER_A_ROLE_ID = "chat_repo_rls_outsider_a_role";
const MEMBER_B_ROLE_ID = "chat_repo_rls_member_b_role";
const MEMBER_A_SESSION_ID = "chat_repo_rls_member_a_session";
const MEMBER_A_REVOKED_SESSION_ID = "chat_repo_rls_member_a_revoked_session";
const MEMBER_B_SESSION_ID = "chat_repo_rls_member_b_session";
const FILE_A = "chat_repo_rls_file_a";
const FILE_B = "chat_repo_rls_file_b";
const READ_PERMISSIONS = [CHAT_PERMISSIONS.readOwnChannels] as const;
const WRITE_PERMISSIONS = [CHAT_PERMISSIONS.write] as const;
describeIfDatabase("chat repository with the restricted app role", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
let readPermissionCreatedByFixture = false;
let writePermissionCreatedByFixture = false;
let filesReadPermissionCreatedByFixture = false;
let filesWritePermissionCreatedByFixture = false;
beforeAll(async () => {
await cleanupFixtures(admin);
await admin.user.createMany({
data: [
{ id: MEMBER_A, email: "chat-repo-member-a@example.test", firstName: "Member", lastName: "A", active: true },
{ id: OUTSIDER_A, email: "chat-repo-outsider-a@example.test", firstName: "Outsider", lastName: "A", active: true },
{ id: MEMBER_B, email: "chat-repo-member-b@example.test", firstName: "Member", lastName: "B", active: true },
],
});
await admin.tenant.createMany({
data: [
{ id: TENANT_A, slug: TENANT_A, name: "Chat repository RLS tenant A", active: true },
{ id: TENANT_B, slug: TENANT_B, name: "Chat repository RLS tenant B", active: true },
],
});
await admin.tenantUser.createMany({
data: [
{ id: "chat_repo_rls_membership_member_a", tenantId: TENANT_A, userId: MEMBER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_repo_rls_membership_outsider_a", tenantId: TENANT_A, userId: OUTSIDER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_repo_rls_membership_member_b", tenantId: TENANT_B, userId: MEMBER_B, type: 0, joined: 1, status: 2 },
],
});
await admin.teamChat.create({
data: {
id: CHAT_A,
tenantId: TENANT_A,
createdByUserId: MEMBER_A,
kind: "group",
name: "Restricted channel A",
isPrivate: true,
eventStreamId: STREAM_A,
},
});
await admin.teamChatMember.create({
data: {
id: "chat_repo_rls_channel_member_a",
tenantId: TENANT_A,
chatId: CHAT_A,
userId: MEMBER_A,
notificationPref: "all_messages",
},
});
await admin.file.createMany({
data: [
{
id: FILE_A,
tenantId: TENANT_A,
createdByUserId: MEMBER_A,
displayName: "voice-note.webm",
mimeType: "audio/webm",
sizeBytes: 12,
storageKey: `tenants/${TENANT_A}/files/${FILE_A}`,
scanStatus: "clean",
previewStatus: "not_supported",
},
{
id: FILE_B,
tenantId: TENANT_B,
createdByUserId: MEMBER_B,
displayName: "foreign.pdf",
mimeType: "application/pdf",
sizeBytes: 20,
storageKey: `tenants/${TENANT_B}/files/${FILE_B}`,
scanStatus: "clean",
previewStatus: "not_supported",
},
],
});
const existingReadPermission = await admin.permission.findUnique({
where: { name: CHAT_PERMISSIONS.readOwnChannels },
select: { id: true },
});
readPermissionCreatedByFixture = existingReadPermission === null || existingReadPermission.id === READ_PERMISSION_FIXTURE_ID;
const readPermission =
existingReadPermission ??
(await admin.permission.create({
data: {
id: READ_PERMISSION_FIXTURE_ID,
name: CHAT_PERMISSIONS.readOwnChannels,
description: "Chat repository restricted-role integration fixture",
type: "app",
isDefault: false,
order: 99_991,
},
select: { id: true },
}));
const existingWritePermission = await admin.permission.findUnique({
where: { name: CHAT_PERMISSIONS.write },
select: { id: true },
});
writePermissionCreatedByFixture = existingWritePermission === null || existingWritePermission.id === WRITE_PERMISSION_FIXTURE_ID;
const writePermission =
existingWritePermission ??
(await admin.permission.create({
data: {
id: WRITE_PERMISSION_FIXTURE_ID,
name: CHAT_PERMISSIONS.write,
description: "Chat repository restricted-role write integration fixture",
type: "app",
isDefault: false,
order: 99_992,
},
select: { id: true },
}));
const existingFilesReadPermission = await admin.permission.findUnique({
where: { name: "files.read_own" },
select: { id: true },
});
filesReadPermissionCreatedByFixture =
existingFilesReadPermission === null || existingFilesReadPermission.id === FILES_READ_PERMISSION_FIXTURE_ID;
const filesReadPermission =
existingFilesReadPermission ??
(await admin.permission.create({
data: {
id: FILES_READ_PERMISSION_FIXTURE_ID,
name: "files.read_own",
description: "Files read permission for the chat restricted-role integration fixture",
type: "app",
isDefault: false,
order: 99_993,
},
select: { id: true },
}));
const existingFilesWritePermission = await admin.permission.findUnique({
where: { name: "files.write" },
select: { id: true },
});
filesWritePermissionCreatedByFixture =
existingFilesWritePermission === null || existingFilesWritePermission.id === FILES_WRITE_PERMISSION_FIXTURE_ID;
const filesWritePermission =
existingFilesWritePermission ??
(await admin.permission.create({
data: {
id: FILES_WRITE_PERMISSION_FIXTURE_ID,
name: "files.write",
description: "Files write permission for the chat restricted-role integration fixture",
type: "app",
isDefault: false,
order: 99_994,
},
select: { id: true },
}));
await admin.role.create({
data: {
id: GLOBAL_APP_ROLE_ID,
tenantId: null,
name: GLOBAL_APP_ROLE_NAME,
description: "Global app role for the chat restricted-role integration proof",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 99_991,
},
});
await admin.rolePermission.createMany({
data: [
{
id: "chat_repo_rls_global_role_read_permission",
roleId: GLOBAL_APP_ROLE_ID,
permissionId: readPermission.id,
},
{
id: "chat_repo_rls_global_role_write_permission",
roleId: GLOBAL_APP_ROLE_ID,
permissionId: writePermission.id,
},
{
id: "chat_repo_rls_global_role_files_read_permission",
roleId: GLOBAL_APP_ROLE_ID,
permissionId: filesReadPermission.id,
},
{
id: "chat_repo_rls_global_role_files_write_permission",
roleId: GLOBAL_APP_ROLE_ID,
permissionId: filesWritePermission.id,
},
],
});
await admin.userRole.createMany({
data: [
{ id: MEMBER_A_ROLE_ID, tenantId: TENANT_A, userId: MEMBER_A, roleId: GLOBAL_APP_ROLE_ID },
{ id: OUTSIDER_A_ROLE_ID, tenantId: TENANT_A, userId: OUTSIDER_A, roleId: GLOBAL_APP_ROLE_ID },
{ id: MEMBER_B_ROLE_ID, tenantId: TENANT_B, userId: MEMBER_B, roleId: GLOBAL_APP_ROLE_ID },
],
});
const expiresAt = new Date(Date.now() + 60 * 60 * 1_000);
await admin.userSession.createMany({
data: [
{
id: MEMBER_A_SESSION_ID,
userId: MEMBER_A,
tokenHash: "chat_repo_rls_member_a_session_hash",
expiresAt,
},
{
id: MEMBER_A_REVOKED_SESSION_ID,
userId: MEMBER_A,
tokenHash: "chat_repo_rls_member_a_revoked_session_hash",
expiresAt,
revokedAt: new Date(),
},
{
id: MEMBER_B_SESSION_ID,
userId: MEMBER_B,
tokenHash: "chat_repo_rls_member_b_session_hash",
expiresAt,
},
],
});
});
afterAll(async () => {
await cleanupFixtures(admin);
if (readPermissionCreatedByFixture) {
await admin.permission.deleteMany({ where: { id: READ_PERMISSION_FIXTURE_ID, name: CHAT_PERMISSIONS.readOwnChannels } });
}
if (writePermissionCreatedByFixture) {
await admin.permission.deleteMany({ where: { id: WRITE_PERMISSION_FIXTURE_ID, name: CHAT_PERMISSIONS.write } });
}
if (filesReadPermissionCreatedByFixture) {
await admin.permission.deleteMany({ where: { id: FILES_READ_PERMISSION_FIXTURE_ID, name: "files.read_own" } });
}
if (filesWritePermissionCreatedByFixture) {
await admin.permission.deleteMany({ where: { id: FILES_WRITE_PERMISSION_FIXTURE_ID, name: "files.write" } });
}
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("revalidates gateway sessions, global app-role permissions, tenant scope, and live channel membership under FORCE RLS", async () => {
const currentRole = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]);
const rlsState = await app.$queryRaw<Array<{ tableName: string; enabled: boolean; forced: boolean }>>`
SELECT relname AS "tableName", relrowsecurity AS enabled, relforcerowsecurity AS forced
FROM pg_catalog.pg_class
WHERE relnamespace = 'public'::regnamespace
AND relname IN ('TeamChat', 'TeamChatMember', 'UserSession', 'UserRole', 'Role', 'RolePermission')
ORDER BY relname ASC
`;
expect(rlsState).toHaveLength(6);
expect(rlsState.every((table) => table.enabled && table.forced)).toBe(true);
const visibleGatewayPermissions = await runWithRlsContext(
{ tenantId: TENANT_A, userId: MEMBER_A },
() =>
app.$queryRaw<Array<{ name: string; roleTenantId: string | null; assignmentTenantId: string }>>`
SELECT
permission_row."name",
role_row."tenantId" AS "roleTenantId",
user_role."tenantId" AS "assignmentTenantId"
FROM "UserRole" AS user_role
INNER JOIN "Role" AS role_row ON role_row."id" = user_role."roleId"
INNER JOIN "RolePermission" AS role_permission ON role_permission."roleId" = role_row."id"
INNER JOIN "Permission" AS permission_row ON permission_row."id" = role_permission."permissionId"
WHERE user_role."tenantId" = ${TENANT_A}
AND user_role."userId" = ${MEMBER_A}
AND role_row."type" = 'app'
AND (role_row."tenantId" IS NULL OR role_row."tenantId" = ${TENANT_A})
ORDER BY permission_row."name" ASC
`
);
expect(visibleGatewayPermissions).toEqual([
{
name: CHAT_PERMISSIONS.readOwnChannels,
roleTenantId: null,
assignmentTenantId: TENANT_A,
},
{
name: CHAT_PERMISSIONS.write,
roleTenantId: null,
assignmentTenantId: TENANT_A,
},
{
name: "files.read_own",
roleTenantId: null,
assignmentTenantId: TENANT_A,
},
{
name: "files.write",
roleTenantId: null,
assignmentTenantId: TENANT_A,
},
]);
const memberGatewayContext = { tenantId: TENANT_A, userId: MEMBER_A, sessionId: MEMBER_A_SESSION_ID } as const;
await expect(authorizeChatGatewayConnection(memberGatewayContext)).resolves.toBeUndefined();
await expect(assertMemberChannelAccess({ ...memberGatewayContext, chatId: CHAT_A })).resolves.toBeUndefined();
await expect(revalidateChatGatewayAccess({ ...memberGatewayContext, chatIds: [CHAT_A] })).resolves.toBeUndefined();
await expect(fillChatEventGap({ ...memberGatewayContext, chatId: CHAT_A, afterCursor: "0" })).resolves.toEqual({
status: "ok",
events: [],
nextCursor: "0",
hasMore: false,
});
await expect(
setChatMemberPreferences({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: READ_PERMISSIONS,
chatId: CHAT_A,
requestId: "chat_repo_rls_preferences_member_a",
isPinned: true,
notificationPreference: "muted",
})
).resolves.toMatchObject({ chatId: CHAT_A, isPinned: true, notificationPreference: "muted", changed: true });
await expect(
setChatMemberPreferences({
tenantId: TENANT_A,
userId: OUTSIDER_A,
permissions: READ_PERMISSIONS,
chatId: CHAT_A,
requestId: "chat_repo_rls_preferences_outsider_a",
isPinned: true,
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
setChatMemberPreferences({
tenantId: TENANT_B,
userId: MEMBER_B,
permissions: READ_PERMISSIONS,
chatId: CHAT_A,
requestId: "chat_repo_rls_preferences_member_b",
notificationPreference: "muted",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(authorizeChatGatewayConnection({ tenantId: TENANT_A, userId: MEMBER_A, sessionId: MEMBER_A_REVOKED_SESSION_ID })).rejects.toMatchObject({
code: "foundation.not_found",
});
const foreignTenantGatewayContext = { tenantId: TENANT_B, userId: MEMBER_B, sessionId: MEMBER_B_SESSION_ID } as const;
await expect(authorizeChatGatewayConnection(foreignTenantGatewayContext)).resolves.toBeUndefined();
await expect(assertMemberChannelAccess({ ...foreignTenantGatewayContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...foreignTenantGatewayContext, chatId: CHAT_A, afterCursor: "0" })).rejects.toMatchObject({
code: "foundation.not_found",
});
await admin.teamChatMember.update({
where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } },
data: { leftAt: new Date() },
});
try {
await expect(assertMemberChannelAccess({ ...memberGatewayContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(revalidateChatGatewayAccess({ ...memberGatewayContext, chatIds: [CHAT_A] })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...memberGatewayContext, chatId: CHAT_A, afterCursor: "0" })).rejects.toMatchObject({
code: "foundation.not_found",
});
} finally {
await admin.teamChatMember.update({
where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } },
data: { leftAt: null },
});
}
});
it("filters and paginates the channel index before hydration without crossing tenant RLS", async () => {
const newerLastMessageAt = new Date("2026-07-15T12:00:00.000Z");
const olderLastMessageAt = new Date("2026-07-15T11:00:00.000Z");
await admin.user.create({
data: {
id: SEARCH_MEMBER_A,
email: "chat-repo-cursor-needle@example.test",
firstName: "Cursor",
lastName: "Needle",
active: true,
},
});
await admin.tenantUser.create({
data: {
id: "chat_repo_rls_membership_search_member_a",
tenantId: TENANT_A,
userId: SEARCH_MEMBER_A,
type: 0,
joined: 1,
status: 2,
},
});
await admin.teamChat.createMany({
data: [
{
id: PAGE_CHAT_NEWER,
tenantId: TENANT_A,
createdByUserId: MEMBER_A,
kind: "group",
name: "Newest candidate",
isPrivate: true,
eventStreamId: "chat_repo_rls_page_stream_newer",
lastMessageAt: newerLastMessageAt,
},
{
id: PAGE_CHAT_OLDER,
tenantId: TENANT_A,
createdByUserId: MEMBER_A,
kind: "group",
name: "Older candidate",
isPrivate: true,
eventStreamId: "chat_repo_rls_page_stream_older",
lastMessageAt: olderLastMessageAt,
},
{
id: PAGE_CHAT_FOREIGN,
tenantId: TENANT_B,
createdByUserId: MEMBER_B,
kind: "group",
name: "Cursor Needle foreign candidate",
isPrivate: true,
eventStreamId: "chat_repo_rls_page_stream_foreign",
lastMessageAt: new Date("2026-07-15T13:00:00.000Z"),
},
],
});
await admin.teamChatMember.createMany({
data: [
{
id: "chat_repo_rls_page_newer_viewer",
tenantId: TENANT_A,
chatId: PAGE_CHAT_NEWER,
userId: MEMBER_A,
isPinned: true,
notificationPref: "all_messages",
},
{
id: "chat_repo_rls_page_newer_search_member",
tenantId: TENANT_A,
chatId: PAGE_CHAT_NEWER,
userId: SEARCH_MEMBER_A,
notificationPref: "all_messages",
},
{
id: "chat_repo_rls_page_older_viewer",
tenantId: TENANT_A,
chatId: PAGE_CHAT_OLDER,
userId: MEMBER_A,
notificationPref: "all_messages",
},
{
id: "chat_repo_rls_page_older_search_member",
tenantId: TENANT_A,
chatId: PAGE_CHAT_OLDER,
userId: SEARCH_MEMBER_A,
notificationPref: "all_messages",
},
{
id: "chat_repo_rls_page_foreign_viewer",
tenantId: TENANT_B,
chatId: PAGE_CHAT_FOREIGN,
userId: MEMBER_B,
notificationPref: "all_messages",
},
],
});
await admin.teamChatMessage.create({
data: {
id: PAGE_MESSAGE_OLDER,
tenantId: TENANT_A,
chatId: PAGE_CHAT_OLDER,
authorUserId: SEARCH_MEMBER_A,
clientMessageId: "chat_repo_rls_page_message_client",
body: "Searchable message body needle",
bodyFormat: "markdown",
mentions: [],
linkPreviews: [],
createdAt: olderLastMessageAt,
},
});
try {
const context = { tenantId: TENANT_A, userId: MEMBER_A, permissions: READ_PERMISSIONS } as const;
const firstPage = await listMemberChannels({ ...context, query: " Cursor Needle ", limit: 1 });
expect(firstPage.channels.map((channel) => channel.id)).toEqual([PAGE_CHAT_NEWER]);
expect(firstPage.nextCursor).toEqual(expect.any(String));
const secondPage = await listMemberChannels({
...context,
query: "Cursor Needle",
limit: 1,
afterCursor: firstPage.nextCursor!,
});
expect(secondPage.channels.map((channel) => channel.id)).toEqual([PAGE_CHAT_OLDER]);
expect(secondPage.nextCursor).toBeNull();
expect([...firstPage.channels, ...secondPage.channels].some((channel) => channel.id === PAGE_CHAT_FOREIGN)).toBe(false);
await expect(listMemberChannels({ ...context, query: "Cursor Needle", view: "pinned" })).resolves.toMatchObject({
channels: [{ id: PAGE_CHAT_NEWER }],
nextCursor: null,
});
await expect(listMemberChannels({ ...context, query: "Searchable message body needle", view: "unread" })).resolves.toMatchObject({
channels: [
{
id: PAGE_CHAT_OLDER,
participants: [{ userId: SEARCH_MEMBER_A, displayName: "Cursor Needle", avatarUrl: null }],
unreadCount: 1,
hasUnreadMention: false,
},
],
nextCursor: null,
});
} finally {
await admin.teamChatMember.updateMany({
where: { chatId: { in: [PAGE_CHAT_NEWER, PAGE_CHAT_OLDER, PAGE_CHAT_FOREIGN] } },
data: { lastReadMessageId: null, lastReadAt: null },
});
await admin.teamChatMessage.deleteMany({ where: { id: PAGE_MESSAGE_OLDER } });
await admin.teamChatMember.deleteMany({ where: { chatId: { in: [PAGE_CHAT_NEWER, PAGE_CHAT_OLDER, PAGE_CHAT_FOREIGN] } } });
await admin.teamChat.deleteMany({ where: { id: { in: [PAGE_CHAT_NEWER, PAGE_CHAT_OLDER, PAGE_CHAT_FOREIGN] } } });
await admin.tenantUser.deleteMany({ where: { tenantId: TENANT_A, userId: SEARCH_MEMBER_A } });
await admin.user.deleteMany({ where: { id: SEARCH_MEMBER_A } });
}
});
it("keeps Files attachments tenant-bound and projects them only through an active channel membership", async () => {
const context = { tenantId: TENANT_A, userId: MEMBER_A, permissions: [...WRITE_PERMISSIONS, "files.write"] } as const;
await expect(
sendTopLevelChatMessage({
...context,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_foreign_attachment",
requestId: "chat_repo_rls_foreign_attachment_request",
body: "",
attachmentFileIds: [FILE_B],
})
).rejects.toMatchObject({ code: "foundation.not_found" });
const sent = await sendTopLevelChatMessage({
...context,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_owned_attachment",
requestId: "chat_repo_rls_owned_attachment_request",
body: "",
attachmentFileIds: [FILE_A],
});
expect(sent.message.attachmentIds).toEqual([FILE_A]);
await expect(
getMemberChannelDetail({ tenantId: TENANT_A, userId: MEMBER_A, permissions: READ_PERMISSIONS, chatId: CHAT_A })
).resolves.toMatchObject({
messages: [{ id: sent.message.id, attachmentIds: [FILE_A] }],
attachments: [{ messageId: sent.message.id, fileId: FILE_A, mimeType: "audio/webm", scanStatus: "clean" }],
});
await expect(admin.fileEntityLink.findMany({ where: { tenantId: TENANT_A, entityType: "chat_message", entityId: sent.message.id } })).resolves.toHaveLength(1);
await admin.fileEntityLink.deleteMany({ where: { tenantId: TENANT_A, entityType: "chat_message", entityId: sent.message.id } });
await admin.teamChatEvent.deleteMany({ where: { tenantId: TENANT_A, entityId: sent.message.id } });
await admin.teamChatMessage.delete({ where: { id: sent.message.id } });
await admin.teamChat.update({ where: { id: CHAT_A }, data: { lastMessageAt: null } });
});
it("combines PostgreSQL tenant RLS with active channel membership for every repository path", async () => {
const currentRole = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]);
await expect(app.teamChat.findMany({ where: { id: CHAT_A }, select: { id: true } })).resolves.toEqual([]);
await expect(app.teamChatMessage.findMany({ where: { chatId: CHAT_A }, select: { id: true } })).resolves.toEqual([]);
await expect(app.teamChatEvent.findMany({ where: { chatId: CHAT_A }, select: { id: true } })).resolves.toEqual([]);
const outsiderContext = { tenantId: TENANT_A, userId: OUTSIDER_A, permissions: READ_PERMISSIONS } as const;
await expect(listMemberChannels(outsiderContext)).resolves.toEqual({ channels: [], nextCursor: null });
await expect(getMemberChannelDetail({ ...outsiderContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(loadChatChannelSettings({ ...outsiderContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...outsiderContext, chatId: CHAT_A, afterCursor: "0" })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: OUTSIDER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_outsider_send",
requestId: "chat_repo_rls_outsider_request",
body: "Must not be written",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
const wrongTenantContext = { tenantId: TENANT_B, userId: MEMBER_B, permissions: READ_PERMISSIONS } as const;
await expect(listMemberChannels(wrongTenantContext)).resolves.toEqual({ channels: [], nextCursor: null });
await expect(getMemberChannelDetail({ ...wrongTenantContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(loadChatChannelSettings({ ...wrongTenantContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...wrongTenantContext, chatId: CHAT_A, afterCursor: "0" })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_B,
userId: MEMBER_B,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_cross_tenant_send",
requestId: "chat_repo_rls_cross_tenant_request",
body: "Must not cross tenants",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(countWrites(admin)).resolves.toEqual({ messages: 0, events: 0 });
const memberReadContext = { tenantId: TENANT_A, userId: MEMBER_A, permissions: READ_PERMISSIONS } as const;
const listed = await listMemberChannels(memberReadContext);
expect(listed.channels.map((channel) => channel.id)).toEqual([CHAT_A]);
expect(listed.channels[0]).toMatchObject({
eventCursor: "0",
participants: [],
unreadCount: 0,
hasUnreadMention: false,
});
await expect(getMemberChannelDetail({ ...memberReadContext, chatId: CHAT_A })).resolves.toMatchObject({
channel: {
id: CHAT_A,
participants: [{ userId: MEMBER_A, displayName: "Member A", avatarUrl: null }],
unreadCount: 0,
hasUnreadMention: false,
},
messages: [],
readReceipts: [],
olderMessageCursor: null,
eventCursor: "0",
});
await expect(loadChatChannelSettings({ ...memberReadContext, chatId: CHAT_A })).resolves.toMatchObject({
channel: { id: CHAT_A, kind: "group", privacy: "private", archivedAtIso: null },
members: [{ userId: MEMBER_A, roleInChat: "member" }],
candidateUsers: [],
capabilities: {
canManageMembers: false,
canManageAdmins: false,
canChangePrivacy: false,
canArchive: false,
canLeave: true,
isReadOnly: false,
},
});
const sent = await sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: CLIENT_MESSAGE_ID,
requestId: REQUEST_ID,
body: "Restricted-role message",
});
expect(sent).toMatchObject({ replayed: false, message: { clientMessageId: CLIENT_MESSAGE_ID } });
expect(sent.event.cursor).toMatch(new RegExp(`^${STREAM_A}:[1-9]\\d*$`));
await expect(fillChatEventGap({ ...memberReadContext, chatId: CHAT_A, afterCursor: "0" })).resolves.toMatchObject({
status: "ok",
hasMore: false,
events: [{ cursor: sent.event.cursor }],
nextCursor: sent.event.cursor,
});
await expect(countWrites(admin)).resolves.toEqual({ messages: 1, events: 1 });
await expect(
markChatMessageRead({
...outsiderContext,
chatId: CHAT_A,
messageId: sent.message.id,
requestId: "chat_repo_rls_outsider_read",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
markChatMessageRead({
...wrongTenantContext,
chatId: CHAT_A,
messageId: sent.message.id,
requestId: "chat_repo_rls_cross_tenant_read",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_nonmember_mention",
requestId: "chat_repo_rls_nonmember_mention_request",
body: `Tenant membership alone must not allow <@user:${OUTSIDER_A}>`,
mentions: [{ type: "user", id: OUTSIDER_A, label: "Untrusted label" }],
})
).rejects.toMatchObject({ code: "chat.invalid_input" });
await expect(countWrites(admin)).resolves.toEqual({ messages: 1, events: 1 });
await admin.teamChatMember.create({
data: {
id: "chat_repo_rls_channel_outsider_a",
tenantId: TENANT_A,
chatId: CHAT_A,
userId: OUTSIDER_A,
notificationPref: "all_messages",
},
});
await admin.tenantUser.update({
where: { tenantId_userId: { tenantId: TENANT_A, userId: OUTSIDER_A } },
data: { status: 1 },
});
try {
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_inactive_tenant_member_mention",
requestId: "chat_repo_rls_inactive_tenant_member_mention_request",
body: `Inactive tenant members must not resolve <@user:${OUTSIDER_A}>`,
mentions: [{ type: "user", id: OUTSIDER_A, label: "Untrusted label" }],
})
).rejects.toMatchObject({ code: "chat.invalid_input" });
} finally {
await admin.tenantUser.update({
where: { tenantId_userId: { tenantId: TENANT_A, userId: OUTSIDER_A } },
data: { status: 2 },
});
}
await admin.user.update({ where: { id: OUTSIDER_A }, data: { active: false } });
try {
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_inactive_user_mention",
requestId: "chat_repo_rls_inactive_user_mention_request",
body: `Inactive users must not resolve <@user:${OUTSIDER_A}>`,
mentions: [{ type: "user", id: OUTSIDER_A, label: "Untrusted label" }],
})
).rejects.toMatchObject({ code: "chat.invalid_input" });
} finally {
await admin.user.update({ where: { id: OUTSIDER_A }, data: { active: true } });
}
const channelMemberMention = await sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_channel_member_mention",
requestId: "chat_repo_rls_channel_member_mention_request",
body: `Active channel member <@user:${OUTSIDER_A}>`,
mentions: [{ type: "user", id: OUTSIDER_A, label: "Untrusted label" }],
});
expect(channelMemberMention.message.mentions).toEqual([{ type: "user", id: OUTSIDER_A, label: "Outsider A" }]);
const mentioned = await sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: OUTSIDER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_outsider_mention",
requestId: "chat_repo_rls_outsider_mention_request",
body: `Restricted-role <@user:${MEMBER_A}>`,
mentions: [{ type: "user", id: MEMBER_A, label: "Untrusted label" }],
});
const markedRead = await markChatMessageRead({
...memberReadContext,
chatId: CHAT_A,
messageId: mentioned.message.id,
requestId: "chat_repo_rls_member_a_read_request",
});
expect(markedRead).toMatchObject({
replayed: false,
event: {
event: CHAT_EVENT_NAMES.readReceipt,
data: { messageId: mentioned.message.id, userId: MEMBER_A },
},
});
await expect(
markChatMessageRead({
...memberReadContext,
chatId: CHAT_A,
messageId: mentioned.message.id,
requestId: "chat_repo_rls_member_a_read_retry",
})
).resolves.toMatchObject({ replayed: true, event: { cursor: markedRead.event.cursor } });
await expect(listMemberChannels(memberReadContext)).resolves.toMatchObject({
channels: [
{
id: CHAT_A,
eventCursor: markedRead.event.cursor,
participants: [{ userId: OUTSIDER_A, displayName: "Outsider A", avatarUrl: null }],
unreadCount: 0,
hasUnreadMention: false,
},
],
});
await expect(getMemberChannelDetail({ ...memberReadContext, chatId: CHAT_A })).resolves.toMatchObject({
readReceipts: [{ messageId: mentioned.message.id, userId: MEMBER_A }],
});
await expect(admin.teamChatRead.count({ where: { tenantId: TENANT_A, messageId: mentioned.message.id, userId: MEMBER_A } })).resolves.toBe(1);
await expect(countWrites(admin)).resolves.toEqual({ messages: 3, events: 4 });
await admin.teamChatMember.update({
where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } },
data: { leftAt: new Date() },
});
await expect(listMemberChannels(memberReadContext)).resolves.toEqual({ channels: [], nextCursor: null });
await expect(getMemberChannelDetail({ ...memberReadContext, chatId: CHAT_A })).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(fillChatEventGap({ ...memberReadContext, chatId: CHAT_A, afterCursor: sent.event.cursor })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
sendTopLevelChatMessage({
tenantId: TENANT_A,
userId: MEMBER_A,
permissions: WRITE_PERMISSIONS,
chatId: CHAT_A,
clientMessageId: "chat_repo_rls_after_leave_send",
requestId: "chat_repo_rls_after_leave_request",
body: "Must not be written after leaving",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(
markChatMessageRead({
...memberReadContext,
chatId: CHAT_A,
messageId: mentioned.message.id,
requestId: "chat_repo_rls_after_leave_read",
})
).rejects.toMatchObject({ code: "foundation.not_found" });
await expect(countWrites(admin)).resolves.toEqual({ messages: 3, events: 4 });
});
});
async function countWrites(admin: ReturnType<typeof createDbClient>): Promise<{ messages: number; events: number }> {
const [messages, events] = await Promise.all([
admin.teamChatMessage.count({ where: { tenantId: TENANT_A, chatId: CHAT_A } }),
admin.teamChatEvent.count({ where: { tenantId: TENANT_A, chatId: CHAT_A } }),
]);
return { messages, events };
}
async function cleanupFixtures(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.teamChatMember.updateMany({
where: { tenantId: { in: [TENANT_A, TENANT_B] } },
data: { lastReadMessageId: null, lastReadAt: null },
});
await admin.teamChatEvent.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.fileEntityLink.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] }, entityType: "chat_message" } });
await admin.teamChatMessage.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.teamChatMember.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.teamChat.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.userSession.deleteMany({
where: { id: { in: [MEMBER_A_SESSION_ID, MEMBER_A_REVOKED_SESSION_ID, MEMBER_B_SESSION_ID] } },
});
await admin.userRole.deleteMany({ where: { id: { in: [MEMBER_A_ROLE_ID, OUTSIDER_A_ROLE_ID, MEMBER_B_ROLE_ID] } } });
await admin.rolePermission.deleteMany({ where: { roleId: GLOBAL_APP_ROLE_ID } });
await admin.role.deleteMany({ where: { OR: [{ id: GLOBAL_APP_ROLE_ID }, { tenantId: null, name: GLOBAL_APP_ROLE_NAME }] } });
await admin.file.deleteMany({ where: { id: { in: [FILE_A, FILE_B] } } });
await admin.tenantUser.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.tenant.deleteMany({ where: { id: { in: [TENANT_A, TENANT_B] } } });
await admin.user.deleteMany({ where: { id: { in: [MEMBER_A, OUTSIDER_A, MEMBER_B, SEARCH_MEMBER_A] } } });
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,27 @@
import { describe, expect, it, vi } from "vitest";
import { lockChatMembershipWithTx, lockPermissionGroupsWithTx } from "./sync-locks.server.js";
describe("chat synchronization advisory locks", () => {
it("uses one shared membership key for every channel membership mutation", async () => {
const tx = { $executeRaw: vi.fn().mockResolvedValue(1) };
await lockChatMembershipWithTx(tx as never, " tenant_1 ", " chat_1 ");
expect(tx.$executeRaw).toHaveBeenCalledOnce();
expect(tx.$executeRaw.mock.calls[0]?.[1]).toBe("chat-membership:tenant_1:chat_1");
});
it("deduplicates and locks permission groups in stable order", async () => {
const tx = { $executeRaw: vi.fn().mockResolvedValue(1) };
await expect(lockPermissionGroupsWithTx(tx as never, "tenant_1", ["group_b", "group_a", "group_b"])).resolves.toEqual([
"group_a",
"group_b",
]);
expect(tx.$executeRaw.mock.calls.map((call) => call[1])).toEqual([
"permission-group:tenant_1:group_a",
"permission-group:tenant_1:group_b",
]);
});
});
@@ -0,0 +1,47 @@
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
const CHAT_MEMBERSHIP_LOCK_SALT = 15_018;
const PERMISSION_GROUP_LOCK_SALT = 15_019;
/**
* Serializes every mutation that derives or changes one channel membership.
* Callers must acquire this before loading TeamChatMember state and keep all
* source reconciliation in the same transaction.
*/
export async function lockChatMembershipWithTx(
tx: DbTransactionClient,
tenantId: string,
chatId: string
): Promise<void> {
const normalizedTenantId = normalizeIdentifier(tenantId, "tenantId");
const normalizedChatId = normalizeIdentifier(chatId, "chatId");
const lockKey = `chat-membership:${normalizedTenantId}:${normalizedChatId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${CHAT_MEMBERSHIP_LOCK_SALT}))`;
}
/**
* Cross-module permission-group references intentionally have no FK (AD-21).
* A stable, sorted advisory-lock order therefore protects validation plus the
* subsequent bare-id write from concurrent membership changes/deletion.
*/
export async function lockPermissionGroupsWithTx(
tx: DbTransactionClient,
tenantId: string,
groupIds: readonly string[]
): Promise<readonly string[]> {
const normalizedTenantId = normalizeIdentifier(tenantId, "tenantId");
const normalizedGroupIds = [...new Set(groupIds.map((groupId) => normalizeIdentifier(groupId, "groupId")))].sort();
for (const groupId of normalizedGroupIds) {
const lockKey = `permission-group:${normalizedTenantId}:${groupId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${PERMISSION_GROUP_LOCK_SALT}))`;
}
return normalizedGroupIds;
}
function normalizeIdentifier(value: string, label: "tenantId" | "chatId" | "groupId"): string {
const normalized = value.trim();
if (!normalized || normalized.length > 500 || normalized.includes("\0")) {
throw new Error(`${label} is invalid`);
}
return normalized;
}
@@ -0,0 +1,184 @@
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import { describe, expect, it, vi } from "vitest";
import { writeChatSystemMessageWithTx } from "./system-message.server.js";
const NOW = new Date("2026-07-16T00:00:00.000Z");
const INPUT = {
tenantId: "tenant_1",
chatId: "chat_1",
systemEventKey: "project:project_1:created",
requestId: "request_project_1_created",
kind: "project_created",
metadata: { projectId: "project_1", projectNumber: "P-1001" },
} as const;
function persistedMessage(overrides: Record<string, unknown> = {}) {
return {
id: "message_system_1",
createdAt: NOW,
updatedAt: NOW,
tenantId: INPUT.tenantId,
chatId: INPUT.chatId,
authorUserId: null,
clientMessageId: `system:${INPUT.systemEventKey}`,
body: "",
bodyFormat: "system",
parentMessageId: null,
mentions: [],
linkPreviews: [],
editedAt: null,
deletedAt: null,
systemEventKey: INPUT.systemEventKey,
systemEventKind: INPUT.kind,
systemEventMetadata: INPUT.metadata,
isDemoData: false,
...overrides,
};
}
function persistedEvent(data: unknown, overrides: Record<string, unknown> = {}) {
return {
id: "event_1",
sequence: 7n,
occurredAt: NOW,
tenantId: INPUT.tenantId,
chatId: INPUT.chatId,
actorUserId: null,
entityId: "message_system_1",
requestId: INPUT.requestId,
data,
...overrides,
};
}
function createTx(options: { existingMessage?: ReturnType<typeof persistedMessage> | null; archivedAt?: Date | null } = {}) {
const message = persistedMessage();
const tx = {
$executeRaw: vi.fn(async () => 1),
teamChat: {
findFirst: vi.fn(async () => ({ id: INPUT.chatId, eventStreamId: "stream_1", archivedAt: options.archivedAt ?? null })),
updateMany: vi.fn(async () => ({ count: 1 })),
},
teamChatMessage: {
findUnique: vi.fn(async () => options.existingMessage ?? null),
create: vi.fn(async () => message),
},
teamChatEvent: {
create: vi.fn(async (args: { data: { data: unknown } }) => persistedEvent(args.data.data)),
findFirst: vi.fn(async () =>
persistedEvent({
message: {
id: message.id,
clientMessageId: message.clientMessageId,
authorUserId: null,
body: "",
bodyFormat: "system",
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: NOW.toISOString(),
updatedAt: NOW.toISOString(),
editedAt: null,
deletedAt: null,
systemEvent: { kind: INPUT.kind, metadata: INPUT.metadata },
},
})
),
},
};
return { tx: tx as unknown as DbTransactionClient, mocks: tx, message };
}
describe("writeChatSystemMessageWithTx", () => {
it("atomically creates an actorless system message, event cursor and wakeup descriptor", async () => {
const { tx, mocks } = createTx();
const result = await writeChatSystemMessageWithTx(tx, INPUT);
expect(mocks.$executeRaw).toHaveBeenCalledOnce();
expect(mocks.teamChatMessage.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
tenantId: INPUT.tenantId,
chatId: INPUT.chatId,
authorUserId: null,
bodyFormat: "system",
systemEventKey: INPUT.systemEventKey,
systemEventKind: INPUT.kind,
systemEventMetadata: INPUT.metadata,
}),
})
);
expect(mocks.teamChat.updateMany).toHaveBeenCalledWith(
expect.objectContaining({ data: { lastMessageAt: NOW } })
);
expect(mocks.teamChatEvent.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
type: "message_created",
actorUserId: null,
entityId: "message_system_1",
}),
})
);
expect(result).toMatchObject({
replayed: false,
message: {
authorUserId: null,
bodyFormat: "system",
systemEvent: { kind: INPUT.kind, metadata: INPUT.metadata },
},
event: { event: "chat.message.created", cursor: "stream_1:7" },
realtimeWakeup: {
tenantId: INPUT.tenantId,
chatId: INPUT.chatId,
eventId: "event_1",
cursor: "stream_1:7",
requestId: INPUT.requestId,
},
});
expect("outboxEvent" in mocks).toBe(false);
});
it("replays the existing message and durable event for the same semantic key", async () => {
const existing = persistedMessage();
const { tx, mocks } = createTx({ existingMessage: existing });
const result = await writeChatSystemMessageWithTx(tx, INPUT);
expect(result.replayed).toBe(true);
expect(result.message.id).toBe(existing.id);
expect(result.realtimeWakeup.cursor).toBe("stream_1:7");
expect(mocks.teamChatMessage.create).not.toHaveBeenCalled();
expect(mocks.teamChat.updateMany).not.toHaveBeenCalled();
expect(mocks.teamChatEvent.create).not.toHaveBeenCalled();
expect(mocks.teamChatEvent.findFirst).toHaveBeenCalledOnce();
});
it("rejects payload drift when a semantic key is reused", async () => {
const { tx, mocks } = createTx({
existingMessage: persistedMessage({ systemEventMetadata: { projectId: "other_project" } }),
});
await expect(writeChatSystemMessageWithTx(tx, INPUT)).rejects.toMatchObject({
code: "foundation.idempotency_conflict",
status: 409,
});
expect(mocks.teamChatEvent.findFirst).not.toHaveBeenCalled();
expect(mocks.teamChatMessage.create).not.toHaveBeenCalled();
});
it("does not append a new system entry to an archived channel", async () => {
const { tx, mocks } = createTx({ archivedAt: NOW });
await expect(writeChatSystemMessageWithTx(tx, INPUT)).rejects.toMatchObject({
code: "foundation.not_found",
status: 404,
});
expect(mocks.teamChatMessage.create).not.toHaveBeenCalled();
expect(mocks.teamChatEvent.create).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,363 @@
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,
validateChatServerEvent,
type ChatMessageCreatedEvent,
type ChatRealtimeSystemMessage,
type ChatSystemEventKind,
type ChatSystemEventMetadata,
} from "@hivegrid/realtime";
import { toPersistedChatEventType } from "./event-type-mapping.js";
import { chatErrors } from "./errors.js";
const CHAT_EVENT_LOCK_SALT = 15_015;
const MAX_SYSTEM_EVENT_KEY_LENGTH = 480;
const SYSTEM_CLIENT_MESSAGE_PREFIX = "system:";
const SYSTEM_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,
systemEventKey: true,
systemEventKind: true,
systemEventMetadata: true,
isDemoData: true,
} as const satisfies Prisma.TeamChatMessageSelect;
const SYSTEM_EVENT_SELECT = {
id: true,
sequence: true,
occurredAt: true,
tenantId: true,
chatId: true,
actorUserId: true,
entityId: true,
requestId: true,
data: true,
} as const satisfies Prisma.TeamChatEventSelect;
type PersistedSystemMessage = Prisma.TeamChatMessageGetPayload<{ select: typeof SYSTEM_MESSAGE_SELECT }>;
type PersistedSystemEvent = Prisma.TeamChatEventGetPayload<{ select: typeof SYSTEM_EVENT_SELECT }>;
export type WriteChatSystemMessageInput = {
readonly tenantId: string;
readonly chatId: string;
/** Stable semantic key, for example `project:<id>:created`. */
readonly systemEventKey: string;
readonly requestId: string;
readonly kind: ChatSystemEventKind;
readonly metadata: ChatSystemEventMetadata;
/** Optional fallback copy. The UI renders the semantic event through i18n. */
readonly body?: string;
readonly actorUserId?: string | null;
readonly isDemoData?: boolean;
};
export type ChatSystemMessageRealtimeWakeup = {
readonly tenantId: string;
readonly chatId: string;
readonly eventId: string;
readonly cursor: string;
readonly requestId: string;
};
export type WriteChatSystemMessageResult = {
readonly message: ChatRealtimeSystemMessage;
readonly event: ChatMessageCreatedEvent;
readonly replayed: boolean;
/**
* Durable delivery descriptor for the caller's later transactional wakeup
* integration. This core deliberately does not invent an outbox route.
*/
readonly realtimeWakeup: ChatSystemMessageRealtimeWakeup;
};
/**
* Writes one semantic system timeline entry inside the caller's transaction.
* The channel advisory lock makes the message, durable event cursor and
* `lastMessageAt` mutation one ordered unit. Reusing `systemEventKey` returns
* the original unit and rejects payload drift.
*/
export async function writeChatSystemMessageWithTx(
tx: DbTransactionClient,
input: WriteChatSystemMessageInput
): Promise<WriteChatSystemMessageResult> {
const normalized = normalizeInput(input);
await lockChatEventStream(tx, normalized.tenantId, normalized.chatId);
const channel = await tx.teamChat.findFirst({
where: withTenantScope(normalized.tenantId, { id: normalized.chatId }),
select: { id: true, eventStreamId: true, archivedAt: true },
});
if (!channel) {
throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
}
const existing = await tx.teamChatMessage.findUnique({
where: {
tenantId_chatId_systemEventKey: {
tenantId: normalized.tenantId,
chatId: normalized.chatId,
systemEventKey: normalized.systemEventKey,
},
},
select: SYSTEM_MESSAGE_SELECT,
});
if (existing) {
return resolveReplay(tx, normalized, channel.eventStreamId, existing);
}
if (channel.archivedAt !== null) {
throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
}
const message = await tx.teamChatMessage.create({
data: withTenantScope(normalized.tenantId, {
chatId: normalized.chatId,
authorUserId: normalized.actorUserId,
clientMessageId: normalized.clientMessageId,
body: normalized.body,
bodyFormat: "system",
parentMessageId: null,
mentions: [],
linkPreviews: [],
systemEventKey: normalized.systemEventKey,
systemEventKind: normalized.kind,
systemEventMetadata: normalized.metadata as Prisma.InputJsonValue,
isDemoData: normalized.isDemoData,
}),
select: SYSTEM_MESSAGE_SELECT,
});
const realtimeMessage = mapSystemMessage(message, channel.eventStreamId);
const updated = await tx.teamChat.updateMany({
where: withTenantScope(normalized.tenantId, { id: normalized.chatId, archivedAt: null }),
data: { lastMessageAt: message.createdAt },
});
if (updated.count !== 1) {
throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
}
const event = await tx.teamChatEvent.create({
data: withTenantScope(normalized.tenantId, {
chatId: normalized.chatId,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.messageCreated),
actorUserId: normalized.actorUserId,
entityId: message.id,
requestId: normalized.requestId,
occurredAt: message.createdAt,
data: { message: realtimeMessage } as unknown as Prisma.InputJsonValue,
}),
select: SYSTEM_EVENT_SELECT,
});
return buildResult(realtimeMessage, event, channel.eventStreamId, false);
}
type NormalizedInput = {
readonly tenantId: string;
readonly chatId: string;
readonly systemEventKey: string;
readonly clientMessageId: string;
readonly requestId: string;
readonly kind: ChatSystemEventKind;
readonly metadata: ChatSystemEventMetadata;
readonly body: string;
readonly actorUserId: string | null;
readonly isDemoData: boolean;
};
function normalizeInput(input: WriteChatSystemMessageInput): NormalizedInput {
const systemEventKey = normalizeIdentifier(input.systemEventKey, "systemEventKey", MAX_SYSTEM_EVENT_KEY_LENGTH);
const clientMessageId = `${SYSTEM_CLIENT_MESSAGE_PREFIX}${systemEventKey}`;
const occurredAt = new Date(0).toISOString();
const event = validateChatServerEvent({
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "validation:1",
requestId: input.requestId,
tenantId: input.tenantId,
chatId: input.chatId,
occurredAt,
data: {
message: {
id: "pending-system-message",
clientMessageId,
authorUserId: input.actorUserId ?? null,
body: input.body ?? "",
bodyFormat: "system",
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: occurredAt,
updatedAt: occurredAt,
editedAt: null,
deletedAt: null,
systemEvent: { kind: input.kind, metadata: input.metadata },
},
},
});
if (event.event !== CHAT_EVENT_NAMES.messageCreated || event.data.message.bodyFormat !== "system") {
throw new CatalogError(chatErrors.invalidInput);
}
return {
tenantId: event.tenantId,
chatId: event.chatId,
systemEventKey,
clientMessageId: event.data.message.clientMessageId,
requestId: event.requestId,
kind: event.data.message.systemEvent.kind,
metadata: event.data.message.systemEvent.metadata,
body: event.data.message.body,
actorUserId: event.data.message.authorUserId,
isDemoData: input.isDemoData ?? false,
};
}
async function resolveReplay(
tx: DbTransactionClient,
input: NormalizedInput,
eventStreamId: string,
existing: PersistedSystemMessage
): Promise<WriteChatSystemMessageResult> {
if (!isIdenticalSystemMessage(existing, input)) {
throw new CatalogError(foundationErrors.idempotencyConflict);
}
const message = mapSystemMessage(existing, eventStreamId);
const event = await tx.teamChatEvent.findFirst({
where: withTenantScope(input.tenantId, {
chatId: input.chatId,
entityId: existing.id,
type: toPersistedChatEventType(CHAT_EVENT_NAMES.messageCreated),
}),
orderBy: { sequence: "asc" },
select: SYSTEM_EVENT_SELECT,
});
if (!event) throw new CatalogError(chatErrors.integrityFailure);
return buildResult(message, event, eventStreamId, true);
}
function isIdenticalSystemMessage(message: PersistedSystemMessage, input: NormalizedInput): boolean {
return (
message.tenantId === input.tenantId &&
message.chatId === input.chatId &&
message.authorUserId === input.actorUserId &&
message.clientMessageId === input.clientMessageId &&
message.body === input.body &&
message.bodyFormat === "system" &&
message.parentMessageId === null &&
message.editedAt === null &&
message.deletedAt === null &&
message.systemEventKey === input.systemEventKey &&
message.systemEventKind === input.kind &&
stableJson(message.systemEventMetadata) === stableJson(input.metadata) &&
message.isDemoData === input.isDemoData
);
}
function mapSystemMessage(message: PersistedSystemMessage, eventStreamId: string): ChatRealtimeSystemMessage {
const event = validateChatServerEvent({
event: CHAT_EVENT_NAMES.messageCreated,
cursor: `${eventStreamId}:1`,
requestId: `stored-system-message-${message.id}`,
tenantId: message.tenantId,
chatId: message.chatId,
occurredAt: message.createdAt.toISOString(),
data: {
message: {
id: message.id,
clientMessageId: message.clientMessageId,
authorUserId: message.authorUserId,
body: message.body,
bodyFormat: message.bodyFormat,
parentMessageId: message.parentMessageId,
mentions: message.mentions,
attachmentIds: [],
linkPreviews: message.linkPreviews,
createdAt: message.createdAt.toISOString(),
updatedAt: message.updatedAt.toISOString(),
editedAt: message.editedAt?.toISOString() ?? null,
deletedAt: message.deletedAt?.toISOString() ?? null,
systemEvent: {
kind: message.systemEventKind,
metadata: message.systemEventMetadata,
},
},
},
});
if (event.event !== CHAT_EVENT_NAMES.messageCreated || event.data.message.bodyFormat !== "system") {
throw new CatalogError(chatErrors.integrityFailure);
}
return event.data.message;
}
function buildResult(
message: ChatRealtimeSystemMessage,
eventRow: PersistedSystemEvent,
eventStreamId: string,
replayed: boolean
): WriteChatSystemMessageResult {
const cursor = `${eventStreamId}:${eventRow.sequence.toString()}`;
const event = validateChatServerEvent({
event: CHAT_EVENT_NAMES.messageCreated,
cursor,
requestId: eventRow.requestId,
tenantId: eventRow.tenantId,
chatId: eventRow.chatId,
occurredAt: eventRow.occurredAt.toISOString(),
data: eventRow.data,
});
if (event.event !== CHAT_EVENT_NAMES.messageCreated || event.data.message.bodyFormat !== "system") {
throw new CatalogError(chatErrors.integrityFailure);
}
return {
message,
event,
replayed,
realtimeWakeup: {
tenantId: event.tenantId,
chatId: event.chatId,
eventId: eventRow.id,
cursor,
requestId: event.requestId,
},
};
}
async function lockChatEventStream(tx: DbTransactionClient, tenantId: string, chatId: string): Promise<void> {
const lockKey = `chat-event:${tenantId}:${chatId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, ${CHAT_EVENT_LOCK_SALT}))`;
}
function normalizeIdentifier(value: string, label: string, maxLength: number): string {
if (typeof value !== "string") throw new CatalogError(chatErrors.invalidInput);
const normalized = value.trim();
if (!normalized || normalized.length > maxLength) {
throw new CatalogError(chatErrors.invalidInput, { field: label });
}
return normalized;
}
function stableJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
if (value !== null && typeof value === "object") {
return `{${Object.entries(value)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)
.join(",")}}`;
}
return JSON.stringify(value);
}
@@ -0,0 +1,223 @@
// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
/**
* This suite must run against the restricted runtime role. Ordinary unit runs
* skip it because a mocked client cannot prove FORCE RLS or policy WITH CHECK
* behavior. `verify:rls-live` owns the ephemeral database and both URLs.
*/
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_A = "chat_system_rls_tenant_a";
const TENANT_B = "chat_system_rls_tenant_b";
const USER_A = "chat_system_rls_user_a";
const USER_B = "chat_system_rls_user_b";
const PIPELINE_A = "chat_system_rls_pipeline_a";
const STAGE_A = "chat_system_rls_stage_a";
const PROJECT_A = "chat_system_rls_project_a";
const GROUP_A = "chat_system_rls_group_a";
const GROUP_B = "chat_system_rls_group_b";
const CHAT_A = "chat_system_rls_project_channel_a";
const MESSAGE_A = "chat_system_rls_message_a";
const GROUP_SOURCE_A = "chat_system_rls_group_source_a";
const CROSS_TENANT_GROUP_SOURCE = "chat_system_rls_cross_tenant_group_source";
describeIfDatabase("chat system ownership with the restricted app role", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
beforeAll(async () => {
await cleanupFixtures(admin);
await admin.user.createMany({
data: [
{ id: USER_A, email: "chat-system-rls-a@example.test", firstName: "System", lastName: "A", active: true },
{ id: USER_B, email: "chat-system-rls-b@example.test", firstName: "System", lastName: "B", active: true },
],
});
await admin.tenant.createMany({
data: [
{ id: TENANT_A, slug: TENANT_A, name: "Chat system RLS tenant A", active: true },
{ id: TENANT_B, slug: TENANT_B, name: "Chat system RLS tenant B", active: true },
],
});
await admin.tenantUser.createMany({
data: [
{ id: "chat_system_rls_tenant_user_a", tenantId: TENANT_A, userId: USER_A, type: 0, joined: 1, status: 2 },
{ id: "chat_system_rls_tenant_user_b", tenantId: TENANT_B, userId: USER_B, type: 0, joined: 1, status: 2 },
],
});
await admin.pipeline.create({
data: {
id: PIPELINE_A,
tenantId: TENANT_A,
createdByUserId: USER_A,
name: "Chat system RLS pipeline",
typHint: "auftrag",
},
});
await admin.pipelineStage.create({
data: {
id: STAGE_A,
tenantId: TENANT_A,
pipelineId: PIPELINE_A,
name: "Active",
stageKind: "offen",
},
});
await admin.projekt.create({
data: {
id: PROJECT_A,
tenantId: TENANT_A,
createdByUserId: USER_A,
projektNummer: "CHAT-SYSTEM-RLS-001",
projektname: "System-created project channel proof",
pipelineId: PIPELINE_A,
stageId: STAGE_A,
},
});
await admin.group.createMany({
data: [
{
id: GROUP_A,
tenantId: TENANT_A,
createdByUserId: USER_A,
name: "Same-tenant group",
description: "Allowed chat source",
color: 1,
},
{
id: GROUP_B,
tenantId: TENANT_B,
createdByUserId: USER_B,
name: "Foreign-tenant group",
description: "Denied chat source",
color: 2,
},
],
});
});
afterAll(async () => {
await cleanupFixtures(admin);
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("allows actorless project records and rejects a cross-tenant group source through FORCE RLS", async () => {
const currentRole = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]);
const rlsState = await app.$queryRaw<Array<{ tableName: string; enabled: boolean; forced: boolean }>>`
SELECT relname AS "tableName", relrowsecurity AS enabled, relforcerowsecurity AS forced
FROM pg_catalog.pg_class
WHERE relnamespace = 'public'::regnamespace
AND relname IN ('TeamChat', 'TeamChatMessage', 'TeamChatGroupSource', 'Group')
ORDER BY relname ASC
`;
expect(rlsState).toHaveLength(4);
expect(rlsState.every((table) => table.enabled && table.forced)).toBe(true);
// The restricted role sees no tenant rows without a bound identity.
await expect(app.teamChat.findMany({ where: { id: CHAT_A }, select: { id: true } })).resolves.toEqual([]);
const created = await runWithRlsContext({ tenantId: TENANT_A, userId: USER_A }, () =>
app.$transaction(async (tx) => {
const chat = await tx.teamChat.create({
data: {
id: CHAT_A,
tenantId: TENANT_A,
createdByUserId: null,
kind: "project",
name: "System project channel",
projektId: PROJECT_A,
isPrivate: true,
eventStreamId: "chat_system_rls_stream_a",
},
select: { id: true, tenantId: true, createdByUserId: true, projektId: true },
});
const message = await tx.teamChatMessage.create({
data: {
id: MESSAGE_A,
tenantId: TENANT_A,
chatId: CHAT_A,
authorUserId: null,
clientMessageId: "system:project-created:chat-system-rls",
body: "",
bodyFormat: "system",
parentMessageId: null,
mentions: [],
linkPreviews: [],
systemEventKey: "project-created:chat-system-rls",
systemEventKind: "project_created",
systemEventMetadata: {
projectId: PROJECT_A,
projectName: "System-created project channel proof",
},
},
select: {
id: true,
tenantId: true,
authorUserId: true,
bodyFormat: true,
systemEventKind: true,
systemEventMetadata: true,
},
});
const groupSource = await tx.teamChatGroupSource.create({
data: {
id: GROUP_SOURCE_A,
tenantId: TENANT_A,
chatId: CHAT_A,
groupId: GROUP_A,
syncEnabled: true,
},
select: { id: true, tenantId: true, chatId: true, groupId: true },
});
return { chat, message, groupSource };
})
);
expect(created.chat).toEqual({ id: CHAT_A, tenantId: TENANT_A, createdByUserId: null, projektId: PROJECT_A });
expect(created.message).toEqual({
id: MESSAGE_A,
tenantId: TENANT_A,
authorUserId: null,
bodyFormat: "system",
systemEventKind: "project_created",
systemEventMetadata: {
projectId: PROJECT_A,
projectName: "System-created project channel proof",
},
});
expect(created.groupSource).toEqual({ id: GROUP_SOURCE_A, tenantId: TENANT_A, chatId: CHAT_A, groupId: GROUP_A });
await expect(
runWithRlsContext({ tenantId: TENANT_A, userId: USER_A }, () =>
app.teamChatGroupSource.create({
data: {
id: CROSS_TENANT_GROUP_SOURCE,
tenantId: TENANT_A,
chatId: CHAT_A,
groupId: GROUP_B,
syncEnabled: true,
},
})
)
).rejects.toThrow();
await expect(admin.teamChatGroupSource.count({ where: { id: CROSS_TENANT_GROUP_SOURCE } })).resolves.toBe(0);
});
});
async function cleanupFixtures(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.teamChatGroupSource.deleteMany({ where: { id: { in: [GROUP_SOURCE_A, CROSS_TENANT_GROUP_SOURCE] } } });
await admin.teamChatMessage.deleteMany({ where: { id: MESSAGE_A } });
await admin.teamChat.deleteMany({ where: { id: CHAT_A } });
await admin.group.deleteMany({ where: { id: { in: [GROUP_A, GROUP_B] } } });
await admin.projekt.deleteMany({ where: { id: PROJECT_A } });
await admin.pipelineStage.deleteMany({ where: { id: STAGE_A } });
await admin.pipeline.deleteMany({ where: { id: PIPELINE_A } });
await admin.tenantUser.deleteMany({ where: { tenantId: { in: [TENANT_A, TENANT_B] } } });
await admin.tenant.deleteMany({ where: { id: { in: [TENANT_A, TENANT_B] } } });
await admin.user.deleteMany({ where: { id: { in: [USER_A, USER_B] } } });
}
@@ -0,0 +1,374 @@
import type { ChatMention, ChatPersistentEvent, ChatRealtimeMessage } from "@hivegrid/realtime";
export type ChatRouteRepositoryContext = {
readonly tenantId: string;
readonly userId: string;
/** Full tenant permission set; repository boundaries check exact chat keys. */
readonly permissions: readonly string[];
readonly sessionId?: never;
};
export type ChatGatewayRepositoryContext = {
readonly tenantId: string;
readonly userId: string;
/**
* Server-side session id from a verified short-lived gateway token. Gateway
* calls re-read and lock the current session and permissions in the same
* transaction as the channel operation.
*/
readonly sessionId: string;
readonly permissions?: never;
};
export type ChatRepositoryContext = ChatRouteRepositoryContext | ChatGatewayRepositoryContext;
export type ChatChannelKind = "project" | "group" | "dm";
export type ChatMemberRole = "admin" | "member";
export type ChatNotificationPreference = "all_messages" | "mentions_only" | "muted";
export type ChatMemberChannelListView = "all" | "unread" | "mentions" | "pinned" | "projects" | "groups" | "direct";
export type ChatParticipantProfileRecord = {
readonly userId: string;
readonly displayName: string;
readonly avatarUrl: string | null;
};
export type ChatMessageReadReceiptRecord = {
readonly messageId: string;
readonly userId: string;
readonly readAtIso: string;
};
export type ChatReactionRecord = {
readonly id: string;
readonly messageId: string;
readonly userId: string;
readonly emoji: string;
readonly reactedAtIso: string;
};
export type ChatThreadRecord = {
readonly id: string;
readonly parentMessageId: string;
readonly replyCount: number;
readonly lastReplyAtIso: string;
readonly participantUserIds: readonly string[];
};
export type ChatMessagePinRecord = {
readonly messageId: string;
readonly pinnedByUserId: string;
readonly pinnedAtIso: string;
readonly note: string | null;
};
export type ChatMessageFeatureRecord = {
readonly messageId: string;
readonly reactions: readonly ChatReactionRecord[];
readonly thread: ChatThreadRecord | null;
readonly pin: ChatMessagePinRecord | null;
};
export type ChatAttachmentRecord = {
readonly messageId: string;
readonly fileId: string;
readonly displayName: string;
readonly mimeType: string;
readonly sizeBytes: number;
readonly linkRole: string | null;
readonly previewStatus: "pending" | "generating" | "ready" | "failed" | "not_supported";
readonly scanStatus: "pending" | "clean" | "infected" | "skipped";
};
export type CreateGroupChatInput = ChatRouteRepositoryContext & {
readonly requestId: string;
readonly name: string;
readonly description?: string | null;
readonly isPrivate: boolean;
readonly notificationDefault?: ChatNotificationPreference;
readonly initialMemberUserIds?: readonly string[];
/** Tenant permission groups expanded to their active users at creation. */
readonly initialGroupIds?: readonly string[];
/** Keep members derived from `initialGroupIds` aligned with GroupUser. */
readonly syncGroupMembership?: boolean;
};
export type CreateGroupChatResult = {
readonly chatId: string;
};
export type JoinPublicGroupChatInput = ChatRouteRepositoryContext & {
readonly requestId: string;
readonly chatId: string;
};
export type SetGroupChatMemberInput = ChatRouteRepositoryContext & {
readonly requestId: string;
readonly chatId: string;
readonly memberUserId: string;
readonly roleInChat: ChatMemberRole;
};
/** Settings mutation shared by group channels and manual project-chat guests. */
export type SetChatChannelMemberInput = SetGroupChatMemberInput;
export type RemoveGroupChatMemberInput = ChatRouteRepositoryContext & {
readonly requestId: string;
readonly chatId: string;
readonly memberUserId: string;
};
/** Settings mutation shared by group channels and manual project-chat guests. */
export type RemoveChatChannelMemberInput = RemoveGroupChatMemberInput;
export type LeaveGroupChatInput = ChatRouteRepositoryContext & {
readonly requestId: string;
readonly chatId: string;
};
export type SetGroupChatPrivacyInput = ChatRouteRepositoryContext & {
readonly requestId: string;
readonly chatId: string;
readonly isPrivate: boolean;
};
export type SetGroupChatPrivacyResult = {
readonly chatId: string;
readonly isPrivate: boolean;
readonly changed: boolean;
};
export type ArchiveGroupChatInput = ChatRouteRepositoryContext & {
readonly requestId: string;
readonly chatId: string;
};
/** Manual archive supported for group and project channels. */
export type ArchiveChatChannelInput = ArchiveGroupChatInput;
export type ArchiveGroupChatResult = {
readonly chatId: string;
readonly archivedAtIso: string;
readonly changed: boolean;
};
export type GroupChatMemberMutationResult = {
readonly chatId: string;
readonly memberUserId: string;
readonly roleInChat: ChatMemberRole;
readonly changed: boolean;
};
export type GetOrCreateDirectMessageInput = ChatRouteRepositoryContext & {
readonly requestId: string;
readonly peerUserId: string;
};
export type GetOrCreateDirectMessageResult = {
readonly chatId: string;
readonly dmPairKey: string;
readonly created: boolean;
};
export type ChatMemberChannelRecord = {
readonly id: string;
readonly kind: ChatChannelKind;
readonly name: string | null;
readonly description: string | null;
readonly projektId: string | null;
readonly isPrivate: boolean;
readonly archivedAtIso: string | null;
readonly lastMessageAtIso: string | null;
readonly eventStreamId: string;
/** Latest durable cursor for opening/reconnecting the channel subscription; "0" only means no durable event exists yet. */
readonly eventCursor: string;
readonly member: {
readonly roleInChat: ChatMemberRole;
readonly notificationPreference: ChatNotificationPreference;
readonly lastReadMessageId: string | null;
readonly lastReadAtIso: string | null;
readonly isPinned: boolean;
/** False for former project members who retain history access only. */
readonly canWrite: boolean;
};
readonly memberCount: number;
/** List rows contain DM peers and last-message authors; channel details contain every active participant. */
readonly participants: readonly ChatParticipantProfileRecord[];
readonly unreadCount: number;
readonly hasUnreadMention: boolean;
readonly lastMessage: ChatRealtimeMessage | null;
};
export type ListMemberChannelsInput = ChatRepositoryContext & {
readonly query?: string;
readonly view?: ChatMemberChannelListView;
readonly includeArchived?: boolean;
readonly afterCursor?: string;
readonly limit?: number;
};
export type ListMemberChannelsResult = {
readonly channels: readonly ChatMemberChannelRecord[];
readonly nextCursor: string | null;
};
export type GetMemberChannelDetailInput = ChatRepositoryContext & {
readonly chatId: string;
readonly messageLimit?: number;
readonly beforeMessageCursor?: string;
/** Deep-link target. When outside the latest page, history is loaded from this top-level message backwards. */
readonly focusMessageId?: string;
};
export type ChatMemberChannelDetail = {
readonly channel: ChatMemberChannelRecord;
readonly messages: readonly ChatRealtimeMessage[];
readonly readReceipts: readonly ChatMessageReadReceiptRecord[];
readonly messageFeatures?: readonly ChatMessageFeatureRecord[];
readonly attachments: readonly ChatAttachmentRecord[];
readonly hasOlderMessages: boolean;
readonly olderMessageCursor: string | null;
readonly eventCursor: string;
};
export type ChatThreadDetailRecord = {
readonly channel: ChatMemberChannelRecord;
readonly parentMessage: ChatRealtimeMessage;
readonly replies: readonly ChatRealtimeMessage[];
readonly thread: ChatThreadRecord;
readonly messageFeatures: readonly ChatMessageFeatureRecord[];
readonly attachments: readonly ChatAttachmentRecord[];
};
export type GetChatThreadDetailInput = ChatRepositoryContext & {
readonly chatId: string;
/** The stable thread id is the parent message id in chat v1. */
readonly threadId: string;
};
export type SendChatThreadReplyInput = ChatRepositoryContext & {
readonly requestId: string;
readonly chatId: string;
readonly threadId: string;
readonly clientMessageId: string;
readonly body: string;
};
export type SendChatThreadReplyResult = {
readonly threadId: string;
readonly message: ChatRealtimeMessage;
readonly event: ChatPersistentEvent;
readonly replayed: boolean;
};
export type SetChatReactionInput = ChatRepositoryContext & {
readonly requestId: string;
readonly chatId: string;
readonly messageId: string;
readonly emoji: string;
readonly active: boolean;
};
export type SetChatReactionResult = {
readonly messageId: string;
readonly emoji: string;
readonly active: boolean;
readonly changed: boolean;
readonly replayed: boolean;
readonly event: ChatPersistentEvent;
};
export type SetChatMessagePinInput = ChatRepositoryContext & {
readonly requestId: string;
readonly chatId: string;
readonly messageId: string;
readonly pinned: boolean;
};
export type SetChatMessagePinResult = {
readonly messageId: string;
readonly pinned: boolean;
readonly changed: boolean;
readonly replayed: boolean;
readonly event: ChatPersistentEvent;
};
export type ChatPinnedMessageRecord = {
readonly message: ChatRealtimeMessage;
readonly pin: ChatMessagePinRecord;
readonly author: ChatParticipantProfileRecord | null;
readonly pinnedBy: ChatParticipantProfileRecord | null;
};
export type ListChatPinnedMessagesInput = ChatRepositoryContext & {
readonly chatId: string;
};
export type ListChatPinnedMessagesResult = {
readonly channel: ChatMemberChannelRecord;
readonly pinnedMessages: readonly ChatPinnedMessageRecord[];
};
export type SendTopLevelChatMessageInput = ChatRepositoryContext & {
readonly chatId: string;
readonly clientMessageId: string;
readonly requestId: string;
readonly body: string;
readonly mentions?: readonly ChatMention[];
/** Existing Files-pipeline ids uploaded by the current user. */
readonly attachmentFileIds?: readonly string[];
};
export type SendTopLevelChatMessageResult = {
readonly message: ChatRealtimeMessage;
readonly event: ChatPersistentEvent;
readonly replayed: boolean;
};
export type GetChatMessageTaskSourceInput = ChatRepositoryContext & {
readonly chatId: string;
readonly messageId: string;
};
export type ChatMessageTaskSourceRecord = {
readonly chatId: string;
readonly messageId: string;
readonly body: string;
readonly projectId: string | null;
};
export type WithWritableChatMessageTaskSourceInput = GetChatMessageTaskSourceInput;
export type FillChatEventGapInput = ChatRepositoryContext & {
readonly chatId: string;
readonly afterCursor: string;
readonly limit?: number;
};
export type ChatEventGapResult =
| {
readonly status: "ok";
readonly events: readonly ChatPersistentEvent[];
readonly nextCursor: string;
readonly hasMore: boolean;
}
| {
readonly status: "reset_required";
readonly currentStreamId: string;
};
export type MarkChatMessageReadInput = ChatRepositoryContext & {
readonly chatId: string;
readonly messageId: string;
readonly requestId: string;
};
export type MarkChatMessageReadResult = {
readonly event: ChatPersistentEvent;
readonly replayed: boolean;
};
export type RevalidateChatGatewayAccessInput = ChatGatewayRepositoryContext & {
/** Active socket subscriptions that must still belong to this user. */
readonly chatIds: readonly string[];
};
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"allowJs": false,
"allowImportingTsExtensions": false,
"lib": ["ES2022"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noEmit": true,
"types": ["node"]
},
"include": ["src/**/*.ts"]
}