Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -61,6 +61,14 @@ describe("logActivity", () => {
|
||||
expect(create.mock.calls[0]?.[0].data.actorUserId).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts the canonical missed-call activity type", async () => {
|
||||
const { client, create } = makeMockClient();
|
||||
|
||||
await logActivity({ ...base, activityType: "call_missed" }, { client });
|
||||
|
||||
expect(create.mock.calls[0]?.[0].data.activityType).toBe("call_missed");
|
||||
});
|
||||
|
||||
it("requires tenantId, subjectId and a non-empty summaryText", async () => {
|
||||
const { client } = makeMockClient();
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ export type ActivityActorKind = "user" | "system" | "automation" | "ki_agent";
|
||||
*/
|
||||
export type ActivityType =
|
||||
| "call_inbound"
|
||||
| "call_missed"
|
||||
| "call_outbound"
|
||||
| "email_sent"
|
||||
| "email_received"
|
||||
@@ -24,8 +25,14 @@ export type ActivityType =
|
||||
| "assignee_changed"
|
||||
| "deal_stage_changed"
|
||||
| "project_stage_changed"
|
||||
| "project_updated" // P8 Projekt core (R-P8a) — Stammdaten inline-edit
|
||||
| "project_member_added"
|
||||
| "project_member_removed"
|
||||
| "project_appointment_created"
|
||||
// WF-P8 S02-N / M04 — project notes and the pipeline handover.
|
||||
| "project_note_created"
|
||||
| "project_note_archived"
|
||||
| "project_pipeline_handover"
|
||||
| "project_invoice_created"
|
||||
| "project_invoice_status_changed"
|
||||
| "project_checklist_created"
|
||||
@@ -34,6 +41,7 @@ export type ActivityType =
|
||||
| "project_signature_changed"
|
||||
| "file_uploaded"
|
||||
| "form_submitted"
|
||||
| "portal_complaint_submitted"
|
||||
| "task_created"
|
||||
| "task_completed"
|
||||
| "contact_created" // P6 CRM core (R-P6)
|
||||
@@ -52,6 +60,7 @@ export type ActivityType =
|
||||
| "deal_won"
|
||||
| "deal_lost"
|
||||
| "automation_triggered"
|
||||
| "automation_reversed"
|
||||
| "ki_action"
|
||||
| "audit_event"
|
||||
| "billing_state_changed";
|
||||
@@ -62,7 +71,7 @@ export type ActivitySubjectType = "contact" | "company" | "lead" | "deal" | "pro
|
||||
/** Additional entities referenced by an activity (denormalized for the timeline). */
|
||||
export type ActivityRelatedRef = { type: ActivitySubjectType; id: string };
|
||||
|
||||
/** Input for {@link logActivity}. `summaryText` is the mandatory DE Klartext line. */
|
||||
/** Input for {@link logActivity}. Machine events use a semantic i18n key; user-authored summaries remain verbatim text. */
|
||||
export type LogActivityInput = {
|
||||
tenantId: string;
|
||||
actorUserId?: string | null;
|
||||
|
||||
@@ -7,6 +7,8 @@ Higher-Level-Wrapper that adds:
|
||||
|
||||
- Bearer-token, API-key, and async-getter auth modes
|
||||
- Retry with exponential backoff and jitter, honoring `Retry-After`
|
||||
- HTTPS/same-origin request enforcement with redirects disabled
|
||||
- Per-attempt timeouts and bounded response-body streaming
|
||||
- Auto-generated `Idempotency-Key` headers on POST/PUT/PATCH
|
||||
- Async iterator pagination (cursor / token / page)
|
||||
- HMAC-SHA256 webhook signature verification with constant-time compare
|
||||
@@ -20,6 +22,8 @@ const client = createHiveGridClient({
|
||||
baseUrl: "https://api.hivegrid.de",
|
||||
auth: { apiKey: process.env.HIVEGRID_API_KEY! },
|
||||
tenantId: process.env.HIVEGRID_TENANT_ID,
|
||||
timeoutMs: 30_000,
|
||||
maxResponseBodyBytes: 10 * 1024 * 1024,
|
||||
});
|
||||
|
||||
const me = await client.request({ method: "GET", path: "/v1/me" });
|
||||
@@ -29,6 +33,11 @@ for await (const contact of client.paginate("/v1/contacts")) {
|
||||
}
|
||||
```
|
||||
|
||||
`baseUrl` must use HTTPS. Local HTTP development requires the explicit
|
||||
`allowInsecureLocalhost: true` option and is restricted to loopback hosts.
|
||||
Request paths may be relative or absolute same-origin URLs; cross-origin paths
|
||||
and redirects fail closed so auth, tenant, and trace headers cannot leak.
|
||||
|
||||
## Codegen
|
||||
|
||||
The `src/generated/` directory is produced from the upstream OpenAPI document
|
||||
@@ -38,7 +47,7 @@ checked into this package as `openapi.json`. Regenerate with:
|
||||
pnpm --filter @hivegrid/api-client-ts generate:all
|
||||
```
|
||||
|
||||
The CI workflow `.github/workflows/sdk-codegen.yml` rejects PRs whose generated
|
||||
The CI workflow `.gitea/workflows/sdk-codegen.yml` rejects pull requests whose generated
|
||||
output drifts from the committed spec.
|
||||
|
||||
## See also
|
||||
|
||||
+1
-2
@@ -33,8 +33,7 @@ export default defineConfig({
|
||||
input: "./openapi.json",
|
||||
output: {
|
||||
path: "./src/generated",
|
||||
format: "prettier",
|
||||
lint: false,
|
||||
postProcess: ["prettier"],
|
||||
},
|
||||
plugins: ["@hey-api/typescript", "@hey-api/sdk", "@hey-api/client-fetch"],
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -28,7 +28,7 @@
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hey-api/openapi-ts": "0.97.1",
|
||||
"@hey-api/openapi-ts": "0.97.3",
|
||||
"@hivegrid/api": "workspace:*",
|
||||
"@types/node": "^25.0.0",
|
||||
"tsup": "^8.5.1",
|
||||
|
||||
+3
-1
@@ -1,10 +1,12 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const scriptPath = resolve(here, "generate-spec.ts");
|
||||
const tsxCli = createRequire(import.meta.url).resolve("tsx/cli");
|
||||
|
||||
/**
|
||||
* Smoke test: the script exits 0 in write mode, then `--check` mode confirms
|
||||
@@ -22,7 +24,7 @@ describe("generate-spec script", () => {
|
||||
// Just verify the script is importable / syntactically valid by running --help-equivalent.
|
||||
// We invoke the file with --check, which only succeeds when openapi.json already exists;
|
||||
// when it doesn't, the script exits with code 1 (missing) or 2 (drift). Either is a "ran" signal.
|
||||
const result = spawnSync("pnpm", ["exec", "tsx", scriptPath, "--check"], {
|
||||
const result = spawnSync(process.execPath, [tsxCli, scriptPath, "--check"], {
|
||||
cwd: resolve(here, ".."),
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createClient } from "./generated/client/client.gen.js";
|
||||
import { createAnalyticsEvent, getAdminAnalyticsOverview, getPublicAnalyticsOverview } from "./generated/sdk.gen.js";
|
||||
|
||||
describe("generated analytics client contract", () => {
|
||||
it("keeps ingest, public read, and operator admin credentials separate", async () => {
|
||||
const requests: Request[] = [];
|
||||
const client = createClient({
|
||||
auth: ({ name, scheme }) => {
|
||||
if (name === "x-analytics-token") return "ingest-secret";
|
||||
if (scheme === "bearer") return "service-secret";
|
||||
return undefined;
|
||||
},
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async (requestInfo) => {
|
||||
requests.push(requestInfo as Request);
|
||||
return new Response("{}", { headers: { "Content-Type": "application/json" } });
|
||||
},
|
||||
responseStyle: "data",
|
||||
});
|
||||
|
||||
await createAnalyticsEvent({
|
||||
body: {
|
||||
action: "opened",
|
||||
category: "navigation",
|
||||
analytics: { userAnalyticsId: "anonymous-visitor" },
|
||||
},
|
||||
client,
|
||||
});
|
||||
await getPublicAnalyticsOverview({ client, query: { period: "last-7-days" } });
|
||||
await getAdminAnalyticsOverview({
|
||||
client,
|
||||
headers: { "x-hivegrid-operator-user-id": "operator_1" },
|
||||
query: { period: "last-30-days", portalId: "portal_1", tenantId: "tenant_1" },
|
||||
});
|
||||
|
||||
expect(requests).toHaveLength(3);
|
||||
expect(requests[0]?.headers.get("x-analytics-token")).toBe("ingest-secret");
|
||||
expect(await requests[0]?.json()).toEqual({
|
||||
action: "opened",
|
||||
category: "navigation",
|
||||
analytics: { userAnalyticsId: "anonymous-visitor" },
|
||||
});
|
||||
|
||||
expect(requests[1]?.url).toBe("https://api.example.test/v1/analytics/public?period=last-7-days");
|
||||
expect(requests[1]?.headers.get("x-analytics-token")).toBeNull();
|
||||
expect(requests[1]?.headers.get("authorization")).toBeNull();
|
||||
|
||||
expect(requests[2]?.url).toBe("https://api.example.test/v1/analytics/admin?period=last-30-days&portalId=portal_1&tenantId=tenant_1");
|
||||
expect(requests[2]?.headers.get("authorization")).toBe("Bearer service-secret");
|
||||
expect(requests[2]?.headers.get("x-hivegrid-operator-user-id")).toBe("operator_1");
|
||||
});
|
||||
});
|
||||
+42
-3
@@ -71,7 +71,7 @@ describe("createHiveGridClient — idempotency edge cases", () => {
|
||||
});
|
||||
|
||||
describe("createHiveGridClient — URL building", () => {
|
||||
it("uses an absolute path verbatim instead of prefixing the base url", async () => {
|
||||
it("allows an absolute path only when it stays on the configured origin", async () => {
|
||||
const captured: { url: string | null } = { url: null };
|
||||
const stub: typeof fetch = (async (url: string) => {
|
||||
captured.url = url;
|
||||
@@ -79,8 +79,47 @@ describe("createHiveGridClient — URL building", () => {
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
||||
await client.request({ method: "GET", path: "https://other.example.test/v2/thing" });
|
||||
expect(captured.url).toBe("https://other.example.test/v2/thing");
|
||||
await client.request({ method: "GET", path: "https://api.example.com/v2/thing" });
|
||||
expect(captured.url).toBe("https://api.example.com/v2/thing");
|
||||
});
|
||||
|
||||
it.each(["https://other.example.test/v2/thing", "//other.example.test/v2/thing"])(
|
||||
"fails closed for a cross-origin request path: %s",
|
||||
async (path) => {
|
||||
let calls = 0;
|
||||
const stub: typeof fetch = (async () => {
|
||||
calls += 1;
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
auth: { apiKey: "must-not-leak" },
|
||||
tenantId: "tenant-must-not-leak",
|
||||
fetch: stub,
|
||||
});
|
||||
|
||||
await expect(client.request({ method: "GET", path })).rejects.toThrow(/cross-origin/);
|
||||
expect(calls).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("disables automatic redirects so custom credentials cannot cross origins", async () => {
|
||||
const captured: { redirect: RequestRedirect | undefined; calls: number } = { redirect: undefined, calls: 0 };
|
||||
const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => {
|
||||
captured.calls += 1;
|
||||
captured.redirect = init.redirect;
|
||||
return new Response(null, { status: 302, headers: { location: "https://other.example.test/collect" } });
|
||||
}) as unknown as typeof fetch;
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
auth: { apiKey: "must-not-leak" },
|
||||
retry: { maxAttempts: 1 },
|
||||
fetch: stub,
|
||||
});
|
||||
|
||||
await expect(client.request({ method: "GET", path: "/v1/redirect" })).rejects.toMatchObject({ status: 302 });
|
||||
expect(captured.redirect).toBe("manual");
|
||||
expect(captured.calls).toBe(1);
|
||||
});
|
||||
|
||||
it("skips undefined query values while serializing the rest", async () => {
|
||||
|
||||
+101
-1
@@ -1,5 +1,10 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { createHiveGridClient, HiveGridApiError, HiveGridNetworkError } from "./client.js";
|
||||
import {
|
||||
createHiveGridClient,
|
||||
HiveGridApiError,
|
||||
HiveGridNetworkError,
|
||||
HiveGridResponseTooLargeError,
|
||||
} from "./client.js";
|
||||
|
||||
function mockFetchSequence(responses: Array<Response | Error>): typeof fetch {
|
||||
let index = 0;
|
||||
@@ -25,6 +30,33 @@ describe("createHiveGridClient", () => {
|
||||
expect(() => createHiveGridClient({ baseUrl: "" } as never)).toThrow(/baseUrl/);
|
||||
});
|
||||
|
||||
it("requires HTTPS unless insecure loopback development is explicitly enabled", () => {
|
||||
expect(() => createHiveGridClient({ baseUrl: "http://api.example.com", fetch: mockFetchSequence([]) })).toThrow(/HTTPS/);
|
||||
expect(() => createHiveGridClient({ baseUrl: "http://localhost:3000", fetch: mockFetchSequence([]) })).toThrow(/HTTPS/);
|
||||
expect(
|
||||
createHiveGridClient({
|
||||
baseUrl: "http://127.0.0.1:3000",
|
||||
allowInsecureLocalhost: true,
|
||||
fetch: mockFetchSequence([]),
|
||||
}).baseUrl,
|
||||
).toBe("http://127.0.0.1:3000");
|
||||
expect(() =>
|
||||
createHiveGridClient({
|
||||
baseUrl: "http://api.example.com",
|
||||
allowInsecureLocalhost: true,
|
||||
fetch: mockFetchSequence([]),
|
||||
}),
|
||||
).toThrow(/HTTPS/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://user:pass@api.example.com",
|
||||
"https://api.example.com?target=other",
|
||||
"https://api.example.com#fragment",
|
||||
])("rejects ambiguous or credential-bearing base URLs: %s", (baseUrl) => {
|
||||
expect(() => createHiveGridClient({ baseUrl, fetch: mockFetchSequence([]) })).toThrow(/baseUrl/);
|
||||
});
|
||||
|
||||
it("strips trailing slashes from the base url", () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com///",
|
||||
@@ -146,6 +178,28 @@ describe("createHiveGridClient", () => {
|
||||
expect(captured.headers!.get("baggage")).toBe("k=v");
|
||||
});
|
||||
|
||||
it.each(["Authorization", "authorization", "X-API-Key", "x-tenant-id", "Host", "Content-Length"])(
|
||||
"rejects caller overrides for protected header %s",
|
||||
async (header) => {
|
||||
let calls = 0;
|
||||
const stub: typeof fetch = (async () => {
|
||||
calls += 1;
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
auth: { bearerToken: "configured-secret" },
|
||||
tenantId: "tenant-configured",
|
||||
fetch: stub,
|
||||
});
|
||||
|
||||
await expect(client.request({ method: "GET", path: "/v1/me", headers: { [header]: "attacker-value" } })).rejects.toThrow(
|
||||
/cannot be overridden/,
|
||||
);
|
||||
expect(calls).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("retries on 5xx then succeeds", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
@@ -196,6 +250,52 @@ describe("createHiveGridClient", () => {
|
||||
await expect(client.request({ method: "GET", path: "/v1/ping" })).rejects.toBeInstanceOf(HiveGridNetworkError);
|
||||
});
|
||||
|
||||
it("aborts each network attempt after the configured timeout", async () => {
|
||||
const stub: typeof fetch = ((_url: unknown, init: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true });
|
||||
})) as unknown as typeof fetch;
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 1 },
|
||||
timeoutMs: 5,
|
||||
fetch: stub,
|
||||
});
|
||||
|
||||
await expect(client.request({ method: "GET", path: "/v1/slow" })).rejects.toBeInstanceOf(HiveGridNetworkError);
|
||||
});
|
||||
|
||||
it("rejects a response whose declared body exceeds the configured limit", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
maxResponseBodyBytes: 4,
|
||||
fetch: mockFetchSequence([
|
||||
new Response("12345", { status: 200, headers: { "content-type": "text/plain", "content-length": "5" } }),
|
||||
]),
|
||||
});
|
||||
|
||||
await expect(client.request({ method: "GET", path: "/v1/large" })).rejects.toBeInstanceOf(HiveGridResponseTooLargeError);
|
||||
});
|
||||
|
||||
it("enforces the response limit while streaming when Content-Length is absent", async () => {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode("123"));
|
||||
controller.enqueue(new TextEncoder().encode("45"));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
maxResponseBodyBytes: 4,
|
||||
fetch: mockFetchSequence([new Response(stream, { status: 200, headers: { "content-type": "text/plain" } })]),
|
||||
});
|
||||
|
||||
await expect(client.request({ method: "GET", path: "/v1/chunked-large" })).rejects.toBeInstanceOf(
|
||||
HiveGridResponseTooLargeError,
|
||||
);
|
||||
});
|
||||
|
||||
it("paginate auto-follows nextCursor and stops on null", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
|
||||
@@ -39,6 +39,8 @@ export interface HiveGridIdempotencyConfig {
|
||||
export interface HiveGridClientConfig {
|
||||
/** Base URL of the hivegrid API, e.g. `https://api.hivegrid.de`. */
|
||||
baseUrl: string;
|
||||
/** Explicit development-only escape hatch for http://localhost/loopback base URLs. */
|
||||
allowInsecureLocalhost?: boolean;
|
||||
/** Auth configuration. Exactly one of bearerToken / apiKey / getToken should be set. */
|
||||
auth?: HiveGridAuthConfig;
|
||||
/** Optional tenant scope; forwarded as `X-Tenant-ID` on every call. */
|
||||
@@ -53,6 +55,10 @@ export interface HiveGridClientConfig {
|
||||
fetch?: typeof fetch;
|
||||
/** Sentry trace headers to forward (optional). */
|
||||
sentry?: { trace?: string; baggage?: string };
|
||||
/** Per-attempt request timeout in milliseconds (default 30000, maximum 300000). */
|
||||
timeoutMs?: number;
|
||||
/** Maximum decoded response body size in bytes (default 10 MiB, maximum 100 MiB). */
|
||||
maxResponseBodyBytes?: number;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
@@ -94,6 +100,15 @@ export class HiveGridNetworkError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class HiveGridResponseTooLargeError extends Error {
|
||||
public readonly limitBytes: number;
|
||||
constructor(limitBytes: number) {
|
||||
super(`HiveGrid API response exceeds the configured ${limitBytes}-byte limit`);
|
||||
this.name = "HiveGridResponseTooLargeError";
|
||||
this.limitBytes = limitBytes;
|
||||
}
|
||||
}
|
||||
|
||||
export interface HiveGridClient {
|
||||
/** Issue a typed request against the API. */
|
||||
request<T = unknown>(input: {
|
||||
@@ -115,8 +130,23 @@ export interface HiveGridClient {
|
||||
const DEFAULT_RETRY_MAX_ATTEMPTS = 5;
|
||||
const DEFAULT_RETRY_BASE_MS = 1000;
|
||||
const DEFAULT_RETRY_MAX_MS = 30_000;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
||||
const MAX_REQUEST_TIMEOUT_MS = 5 * 60_000;
|
||||
const DEFAULT_MAX_RESPONSE_BODY_BYTES = 10 * 1024 * 1024;
|
||||
const MAX_RESPONSE_BODY_BYTES = 100 * 1024 * 1024;
|
||||
const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH"]);
|
||||
const RETRY_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);
|
||||
const PROTECTED_REQUEST_HEADERS = new Set([
|
||||
"authorization",
|
||||
"proxy-authorization",
|
||||
"x-api-key",
|
||||
"x-tenant-id",
|
||||
"host",
|
||||
"content-length",
|
||||
"transfer-encoding",
|
||||
"connection",
|
||||
"cookie",
|
||||
]);
|
||||
const PACKAGE_VERSION = "0.1.0";
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
@@ -145,17 +175,79 @@ function parseRetryAfter(header: string | null): number | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function readBody(response: Response): Promise<unknown> {
|
||||
async function readBody(response: Response, maxBytes: number): Promise<unknown> {
|
||||
const text = await readResponseText(response, maxBytes);
|
||||
if (text.length === 0) return null;
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
if (contentType.includes("application/json")) {
|
||||
try {
|
||||
return await response.json();
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const text = await response.text();
|
||||
return text.length === 0 ? null : text;
|
||||
return text;
|
||||
}
|
||||
|
||||
async function readResponseText(response: Response, maxBytes: number): Promise<string> {
|
||||
const contentLength = response.headers.get("content-length");
|
||||
if (contentLength && /^\d+$/u.test(contentLength.trim()) && Number(contentLength) > maxBytes) {
|
||||
await response.body?.cancel().catch(() => undefined);
|
||||
throw new HiveGridResponseTooLargeError(maxBytes);
|
||||
}
|
||||
if (!response.body) return "";
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let totalBytes = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
totalBytes += value.byteLength;
|
||||
if (totalBytes > maxBytes) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
throw new HiveGridResponseTooLargeError(maxBytes);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(totalBytes);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(rawBaseUrl: string, allowInsecureLocalhost: boolean): URL {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(rawBaseUrl);
|
||||
} catch {
|
||||
throw new Error("createHiveGridClient: baseUrl must be an absolute URL");
|
||||
}
|
||||
if (url.username || url.password || url.search || url.hash) {
|
||||
throw new Error("createHiveGridClient: baseUrl must not contain credentials, a query, or a fragment");
|
||||
}
|
||||
const isLoopback = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(url.hostname.toLowerCase());
|
||||
if (url.protocol !== "https:" && !(allowInsecureLocalhost && url.protocol === "http:" && isLoopback)) {
|
||||
throw new Error("createHiveGridClient: baseUrl must use HTTPS (or explicit insecure localhost development mode)");
|
||||
}
|
||||
url.pathname = url.pathname.replace(/\/+$/u, "") || "/";
|
||||
return url;
|
||||
}
|
||||
|
||||
function resolvePositiveBoundedInteger(value: number | undefined, fallback: number, maximum: number, field: string): number {
|
||||
const resolved = value ?? fallback;
|
||||
if (!Number.isSafeInteger(resolved) || resolved <= 0 || resolved > maximum) {
|
||||
throw new Error(`createHiveGridClient: ${field} must be an integer between 1 and ${maximum}`);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClient {
|
||||
@@ -163,7 +255,9 @@ export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClie
|
||||
throw new Error("createHiveGridClient: baseUrl is required");
|
||||
}
|
||||
|
||||
const baseUrl = config.baseUrl.replace(/\/+$/, "");
|
||||
const parsedBaseUrl = normalizeBaseUrl(config.baseUrl, config.allowInsecureLocalhost === true);
|
||||
const baseUrl = parsedBaseUrl.toString().replace(/\/+$/u, "");
|
||||
const baseOrigin = parsedBaseUrl.origin;
|
||||
const fetchImpl: typeof fetch =
|
||||
config.fetch ?? (typeof fetch !== "undefined" ? fetch.bind(globalThis) : (undefined as unknown as typeof fetch));
|
||||
if (!fetchImpl) {
|
||||
@@ -172,6 +266,13 @@ export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClie
|
||||
const retryMaxAttempts = config.retry?.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;
|
||||
const retryBaseMs = config.retry?.baseDelayMs ?? DEFAULT_RETRY_BASE_MS;
|
||||
const retryMaxMs = config.retry?.maxDelayMs ?? DEFAULT_RETRY_MAX_MS;
|
||||
const timeoutMs = resolvePositiveBoundedInteger(config.timeoutMs, DEFAULT_REQUEST_TIMEOUT_MS, MAX_REQUEST_TIMEOUT_MS, "timeoutMs");
|
||||
const maxResponseBodyBytes = resolvePositiveBoundedInteger(
|
||||
config.maxResponseBodyBytes,
|
||||
DEFAULT_MAX_RESPONSE_BODY_BYTES,
|
||||
MAX_RESPONSE_BODY_BYTES,
|
||||
"maxResponseBodyBytes",
|
||||
);
|
||||
const autoIdempotency = config.idempotency?.autoGenerate ?? true;
|
||||
let cachedToken: string | undefined = config.auth?.bearerToken;
|
||||
|
||||
@@ -190,7 +291,12 @@ export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClie
|
||||
return {};
|
||||
}
|
||||
|
||||
function buildHeaders(method: string, extra?: Record<string, string>, idempotencyKey?: string): Headers {
|
||||
function buildHeaders(
|
||||
method: string,
|
||||
authHeaders: Record<string, string>,
|
||||
extra?: Record<string, string>,
|
||||
idempotencyKey?: string,
|
||||
): Headers {
|
||||
const headers = new Headers();
|
||||
headers.set("Accept", "application/json");
|
||||
headers.set("Content-Type", "application/json");
|
||||
@@ -203,8 +309,14 @@ export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClie
|
||||
} else if (idempotencyKey) {
|
||||
headers.set("Idempotency-Key", idempotencyKey);
|
||||
}
|
||||
for (const [key, value] of Object.entries(authHeaders)) {
|
||||
headers.set(key, value);
|
||||
}
|
||||
if (extra) {
|
||||
for (const [key, value] of Object.entries(extra)) {
|
||||
if (PROTECTED_REQUEST_HEADERS.has(key.toLowerCase())) {
|
||||
throw new Error(`createHiveGridClient: request header ${key} is managed by the client and cannot be overridden`);
|
||||
}
|
||||
headers.set(key, value);
|
||||
}
|
||||
}
|
||||
@@ -212,7 +324,18 @@ export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClie
|
||||
}
|
||||
|
||||
function buildUrl(path: string, query?: Record<string, string | number | boolean | undefined>): string {
|
||||
const url = new URL(path.startsWith("http") ? path : `${baseUrl}${path.startsWith("/") ? "" : "/"}${path}`);
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(path, `${baseUrl}/`);
|
||||
} catch {
|
||||
throw new Error("createHiveGridClient: request path is not a valid URL");
|
||||
}
|
||||
if (url.origin !== baseOrigin) {
|
||||
throw new Error("createHiveGridClient: cross-origin request paths are not allowed");
|
||||
}
|
||||
if (url.username || url.password || url.hash) {
|
||||
throw new Error("createHiveGridClient: request path must not contain credentials or a fragment");
|
||||
}
|
||||
if (query) {
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
if (value === undefined) continue;
|
||||
@@ -228,15 +351,21 @@ export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClie
|
||||
headers: Headers,
|
||||
body: string | undefined,
|
||||
): Promise<{ response: Response | null; error: unknown }> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(new Error(`HiveGrid API request timed out after ${timeoutMs}ms`)), timeoutMs);
|
||||
try {
|
||||
const response = await fetchImpl(url, {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
redirect: "manual",
|
||||
signal: controller.signal,
|
||||
});
|
||||
return { response, error: null };
|
||||
} catch (err) {
|
||||
return { response: null, error: err };
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,7 +380,7 @@ export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClie
|
||||
const method = input.method.toUpperCase();
|
||||
const url = buildUrl(input.path, input.query);
|
||||
const authHeaders = await resolveAuthHeader();
|
||||
const headers = buildHeaders(method, { ...authHeaders, ...input.headers }, input.idempotencyKey);
|
||||
const headers = buildHeaders(method, authHeaders, input.headers, input.idempotencyKey);
|
||||
const body = input.body === undefined ? undefined : JSON.stringify(input.body);
|
||||
|
||||
let attempt = 1;
|
||||
@@ -261,19 +390,20 @@ export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClie
|
||||
|
||||
if (response) {
|
||||
if (response.ok) {
|
||||
return (await readBody(response)) as T;
|
||||
return (await readBody(response, maxResponseBodyBytes)) as T;
|
||||
}
|
||||
|
||||
// Retry conditions
|
||||
if (RETRY_STATUS.has(response.status) && attempt < retryMaxAttempts) {
|
||||
const retryAfter = parseRetryAfter(response.headers.get("Retry-After"));
|
||||
const delay = retryAfter !== null ? Math.min(retryMaxMs, retryAfter) : computeBackoff(attempt, retryBaseMs, retryMaxMs);
|
||||
await response.body?.cancel().catch(() => undefined);
|
||||
await sleep(delay);
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const errorBody = await readBody(response);
|
||||
const errorBody = await readBody(response, maxResponseBodyBytes);
|
||||
const requestId = response.headers.get("x-request-id") ?? undefined;
|
||||
const message =
|
||||
errorBody && typeof errorBody === "object" && "error" in errorBody && errorBody.error && typeof errorBody.error === "object"
|
||||
|
||||
+1
-4
@@ -40,10 +40,7 @@ export const createClient = (config: Config = {}): Client => {
|
||||
};
|
||||
|
||||
if (opts.security) {
|
||||
await setAuthParams({
|
||||
...opts,
|
||||
security: opts.security,
|
||||
});
|
||||
await setAuthParams(opts);
|
||||
}
|
||||
|
||||
if (opts.requestValidator) {
|
||||
|
||||
+8
-2
@@ -132,9 +132,15 @@ type MethodFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">
|
||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
||||
|
||||
type SseFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = "fields">(
|
||||
type SseFn = <
|
||||
TData = unknown,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
_TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = "fields",
|
||||
>(
|
||||
options: Omit<RequestOptions<never, TResponseStyle, ThrowOnError>, "method">
|
||||
) => Promise<ServerSentEventsResult<TData, TError>>;
|
||||
) => Promise<ServerSentEventsResult<TData>>;
|
||||
|
||||
type RequestFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = "fields">(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method"> & Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, "method">
|
||||
|
||||
+6
-8
@@ -105,14 +105,12 @@ const checkForExistence = (
|
||||
return false;
|
||||
};
|
||||
|
||||
export const setAuthParams = async ({
|
||||
security,
|
||||
...options
|
||||
}: Pick<Required<RequestOptions>, "security"> &
|
||||
Pick<RequestOptions, "auth" | "query"> & {
|
||||
export async function setAuthParams(
|
||||
options: Pick<RequestOptions, "auth" | "query" | "security"> & {
|
||||
headers: Headers;
|
||||
}) => {
|
||||
for (const auth of security) {
|
||||
}
|
||||
): Promise<void> {
|
||||
for (const auth of options.security ?? []) {
|
||||
if (checkForExistence(options, auth.name)) {
|
||||
continue;
|
||||
}
|
||||
@@ -141,7 +139,7 @@ export const setAuthParams = async ({
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const buildUrl: Client["buildUrl"] = (options) =>
|
||||
getUrl({
|
||||
|
||||
+4
-4
@@ -104,10 +104,10 @@ const stripEmptySlots = (params: Params) => {
|
||||
|
||||
export const buildClientParams = (args: ReadonlyArray<unknown>, fields: FieldsConfig) => {
|
||||
const params: Params = {
|
||||
body: {},
|
||||
headers: {},
|
||||
path: {},
|
||||
query: {},
|
||||
body: Object.create(null),
|
||||
headers: Object.create(null),
|
||||
path: Object.create(null),
|
||||
query: Object.create(null),
|
||||
};
|
||||
|
||||
const map = buildKeyMap(fields);
|
||||
|
||||
+42
-6
@@ -4,6 +4,7 @@ export {
|
||||
acceptWorkspaceInvite,
|
||||
createAnalyticsEvent,
|
||||
createAnalyticsPageView,
|
||||
createPlatformLead,
|
||||
createSupportTicketFromInboundEmail,
|
||||
createWorkspaceInvite,
|
||||
enqueueExportArtifactRetention,
|
||||
@@ -21,6 +22,8 @@ export {
|
||||
getReadyz,
|
||||
getStatus,
|
||||
getV1Health,
|
||||
ingestAdminSalesEmailBccCopy,
|
||||
ingestTenantInboundEmailFromMailjet,
|
||||
listAccounts,
|
||||
listPublicApiCompanies,
|
||||
listPublicApiContacts,
|
||||
@@ -35,7 +38,12 @@ export {
|
||||
type Options,
|
||||
postDeviceRegister,
|
||||
postDeviceRevoke,
|
||||
receiveAdminAircallTelephonyWebhook,
|
||||
receiveAdminSalesEmailProviderEvent,
|
||||
receiveAircallTelephonyWebhook,
|
||||
receiveEmailSequenceMailjetWebhook,
|
||||
receiveHalloPetraTelephonyWebhook,
|
||||
receiveLagoBillingWebhook,
|
||||
receiveMollieBillingWebhook,
|
||||
receivePublicApiIncomingWebhook,
|
||||
refreshJwtToken,
|
||||
@@ -43,7 +51,6 @@ export {
|
||||
revalidateWorkspaceContext,
|
||||
revokeWorkspaceInvite,
|
||||
streamNotifications,
|
||||
uploadAiFile,
|
||||
validateApiKey,
|
||||
} from "./sdk.gen";
|
||||
export type {
|
||||
@@ -63,6 +70,11 @@ export type {
|
||||
CreateAnalyticsPageViewErrors,
|
||||
CreateAnalyticsPageViewResponse,
|
||||
CreateAnalyticsPageViewResponses,
|
||||
CreatePlatformLeadData,
|
||||
CreatePlatformLeadError,
|
||||
CreatePlatformLeadErrors,
|
||||
CreatePlatformLeadResponse,
|
||||
CreatePlatformLeadResponses,
|
||||
CreateSupportTicketFromInboundEmailData,
|
||||
CreateSupportTicketFromInboundEmailError,
|
||||
CreateSupportTicketFromInboundEmailErrors,
|
||||
@@ -137,6 +149,15 @@ export type {
|
||||
GetV1HealthData,
|
||||
GetV1HealthResponse,
|
||||
GetV1HealthResponses,
|
||||
IngestAdminSalesEmailBccCopyData,
|
||||
IngestAdminSalesEmailBccCopyError,
|
||||
IngestAdminSalesEmailBccCopyErrors,
|
||||
IngestAdminSalesEmailBccCopyResponses,
|
||||
IngestTenantInboundEmailFromMailjetData,
|
||||
IngestTenantInboundEmailFromMailjetError,
|
||||
IngestTenantInboundEmailFromMailjetErrors,
|
||||
IngestTenantInboundEmailFromMailjetResponse,
|
||||
IngestTenantInboundEmailFromMailjetResponses,
|
||||
ListAccountsData,
|
||||
ListAccountsError,
|
||||
ListAccountsErrors,
|
||||
@@ -200,10 +221,30 @@ export type {
|
||||
PostDeviceRevokeErrors,
|
||||
PostDeviceRevokeResponse,
|
||||
PostDeviceRevokeResponses,
|
||||
ReceiveAdminAircallTelephonyWebhookData,
|
||||
ReceiveAdminAircallTelephonyWebhookError,
|
||||
ReceiveAdminAircallTelephonyWebhookErrors,
|
||||
ReceiveAdminAircallTelephonyWebhookResponses,
|
||||
ReceiveAdminSalesEmailProviderEventData,
|
||||
ReceiveAdminSalesEmailProviderEventError,
|
||||
ReceiveAdminSalesEmailProviderEventErrors,
|
||||
ReceiveAdminSalesEmailProviderEventResponses,
|
||||
ReceiveAircallTelephonyWebhookData,
|
||||
ReceiveAircallTelephonyWebhookError,
|
||||
ReceiveAircallTelephonyWebhookErrors,
|
||||
ReceiveAircallTelephonyWebhookResponses,
|
||||
ReceiveEmailSequenceMailjetWebhookData,
|
||||
ReceiveEmailSequenceMailjetWebhookError,
|
||||
ReceiveEmailSequenceMailjetWebhookErrors,
|
||||
ReceiveEmailSequenceMailjetWebhookResponses,
|
||||
ReceiveHalloPetraTelephonyWebhookData,
|
||||
ReceiveHalloPetraTelephonyWebhookError,
|
||||
ReceiveHalloPetraTelephonyWebhookErrors,
|
||||
ReceiveHalloPetraTelephonyWebhookResponses,
|
||||
ReceiveLagoBillingWebhookData,
|
||||
ReceiveLagoBillingWebhookError,
|
||||
ReceiveLagoBillingWebhookErrors,
|
||||
ReceiveLagoBillingWebhookResponses,
|
||||
ReceiveMollieBillingWebhookData,
|
||||
ReceiveMollieBillingWebhookError,
|
||||
ReceiveMollieBillingWebhookErrors,
|
||||
@@ -236,11 +277,6 @@ export type {
|
||||
StreamNotificationsErrors,
|
||||
StreamNotificationsResponse,
|
||||
StreamNotificationsResponses,
|
||||
UploadAiFileData,
|
||||
UploadAiFileError,
|
||||
UploadAiFileErrors,
|
||||
UploadAiFileResponse,
|
||||
UploadAiFileResponses,
|
||||
ValidateApiKeyData,
|
||||
ValidateApiKeyError,
|
||||
ValidateApiKeyErrors,
|
||||
|
||||
+157
-16
@@ -12,6 +12,9 @@ import type {
|
||||
CreateAnalyticsPageViewData,
|
||||
CreateAnalyticsPageViewErrors,
|
||||
CreateAnalyticsPageViewResponses,
|
||||
CreatePlatformLeadData,
|
||||
CreatePlatformLeadErrors,
|
||||
CreatePlatformLeadResponses,
|
||||
CreateSupportTicketFromInboundEmailData,
|
||||
CreateSupportTicketFromInboundEmailErrors,
|
||||
CreateSupportTicketFromInboundEmailResponses,
|
||||
@@ -59,6 +62,12 @@ import type {
|
||||
GetStatusResponses,
|
||||
GetV1HealthData,
|
||||
GetV1HealthResponses,
|
||||
IngestAdminSalesEmailBccCopyData,
|
||||
IngestAdminSalesEmailBccCopyErrors,
|
||||
IngestAdminSalesEmailBccCopyResponses,
|
||||
IngestTenantInboundEmailFromMailjetData,
|
||||
IngestTenantInboundEmailFromMailjetErrors,
|
||||
IngestTenantInboundEmailFromMailjetResponses,
|
||||
ListAccountsData,
|
||||
ListAccountsErrors,
|
||||
ListAccountsResponses,
|
||||
@@ -98,9 +107,24 @@ import type {
|
||||
PostDeviceRevokeData,
|
||||
PostDeviceRevokeErrors,
|
||||
PostDeviceRevokeResponses,
|
||||
ReceiveAdminAircallTelephonyWebhookData,
|
||||
ReceiveAdminAircallTelephonyWebhookErrors,
|
||||
ReceiveAdminAircallTelephonyWebhookResponses,
|
||||
ReceiveAdminSalesEmailProviderEventData,
|
||||
ReceiveAdminSalesEmailProviderEventErrors,
|
||||
ReceiveAdminSalesEmailProviderEventResponses,
|
||||
ReceiveAircallTelephonyWebhookData,
|
||||
ReceiveAircallTelephonyWebhookErrors,
|
||||
ReceiveAircallTelephonyWebhookResponses,
|
||||
ReceiveEmailSequenceMailjetWebhookData,
|
||||
ReceiveEmailSequenceMailjetWebhookErrors,
|
||||
ReceiveEmailSequenceMailjetWebhookResponses,
|
||||
ReceiveHalloPetraTelephonyWebhookData,
|
||||
ReceiveHalloPetraTelephonyWebhookErrors,
|
||||
ReceiveHalloPetraTelephonyWebhookResponses,
|
||||
ReceiveLagoBillingWebhookData,
|
||||
ReceiveLagoBillingWebhookErrors,
|
||||
ReceiveLagoBillingWebhookResponses,
|
||||
ReceiveMollieBillingWebhookData,
|
||||
ReceiveMollieBillingWebhookErrors,
|
||||
ReceiveMollieBillingWebhookResponses,
|
||||
@@ -123,9 +147,6 @@ import type {
|
||||
StreamNotificationsErrors,
|
||||
StreamNotificationsResponse,
|
||||
StreamNotificationsResponses,
|
||||
UploadAiFileData,
|
||||
UploadAiFileErrors,
|
||||
UploadAiFileResponses,
|
||||
ValidateApiKeyData,
|
||||
ValidateApiKeyErrors,
|
||||
ValidateApiKeyResponses,
|
||||
@@ -219,11 +240,18 @@ export const validateApiKey = <ThrowOnError extends boolean = false>(options?: O
|
||||
},
|
||||
});
|
||||
|
||||
export const uploadAiFile = <ThrowOnError extends boolean = false>(options?: Options<UploadAiFileData, ThrowOnError>) =>
|
||||
(options?.client ?? client).post<UploadAiFileResponses, UploadAiFileErrors, ThrowOnError>({
|
||||
/**
|
||||
* Creates a tenantless platform sales lead for the source authenticated by a rotatable bearer capability. The source cannot be supplied by the request body. Persistence, first activity, outbox event, and idempotency response commit atomically.
|
||||
*/
|
||||
export const createPlatformLead = <ThrowOnError extends boolean = false>(options: Options<CreatePlatformLeadData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<CreatePlatformLeadResponses, CreatePlatformLeadErrors, ThrowOnError>({
|
||||
security: [{ scheme: "bearer", type: "http" }],
|
||||
url: "/v1/ai/upload",
|
||||
url: "/v1/platform/leads",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -242,6 +270,22 @@ export const createSupportTicketFromInboundEmail = <ThrowOnError extends boolean
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Accepts Mailjet inbound (parse) email webhooks authenticated with HTTP Basic Auth, resolves the tenant inbound address, persists the mail, and creates the matching lead/contact activity.
|
||||
*/
|
||||
export const ingestTenantInboundEmailFromMailjet = <ThrowOnError extends boolean = false>(
|
||||
options: Options<IngestTenantInboundEmailFromMailjetData, ThrowOnError>
|
||||
) =>
|
||||
(options.client ?? client).post<IngestTenantInboundEmailFromMailjetResponses, IngestTenantInboundEmailFromMailjetErrors, ThrowOnError>({
|
||||
security: [{ scheme: "basic", type: "http" }],
|
||||
url: "/v1/email/inbound-mailjet",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
export const createAnalyticsEvent = <ThrowOnError extends boolean = false>(options: Options<CreateAnalyticsEventData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<CreateAnalyticsEventResponses, CreateAnalyticsEventErrors, ThrowOnError>({
|
||||
security: [{ name: "x-analytics-token", type: "apiKey" }],
|
||||
@@ -264,9 +308,11 @@ export const createAnalyticsPageView = <ThrowOnError extends boolean = false>(op
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns tenantless platform analytics aggregates only when the operator-controlled public setting is enabled.
|
||||
*/
|
||||
export const getPublicAnalyticsOverview = <ThrowOnError extends boolean = false>(options?: Options<GetPublicAnalyticsOverviewData, ThrowOnError>) =>
|
||||
(options?.client ?? client).get<GetPublicAnalyticsOverviewResponses, GetPublicAnalyticsOverviewErrors, ThrowOnError>({
|
||||
security: [{ name: "x-analytics-token", type: "apiKey" }],
|
||||
url: "/v1/analytics/public",
|
||||
...options,
|
||||
});
|
||||
@@ -347,8 +393,8 @@ export const revokeWorkspaceInvite = <ThrowOnError extends boolean = false>(opti
|
||||
},
|
||||
});
|
||||
|
||||
export const getAdminAnalyticsOverview = <ThrowOnError extends boolean = false>(options?: Options<GetAdminAnalyticsOverviewData, ThrowOnError>) =>
|
||||
(options?.client ?? client).get<GetAdminAnalyticsOverviewResponses, GetAdminAnalyticsOverviewErrors, ThrowOnError>({
|
||||
export const getAdminAnalyticsOverview = <ThrowOnError extends boolean = false>(options: Options<GetAdminAnalyticsOverviewData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<GetAdminAnalyticsOverviewResponses, GetAdminAnalyticsOverviewErrors, ThrowOnError>({
|
||||
security: [{ scheme: "bearer", type: "http" }],
|
||||
url: "/v1/analytics/admin",
|
||||
...options,
|
||||
@@ -367,17 +413,17 @@ export const streamNotifications = <ThrowOnError extends boolean = false>(
|
||||
});
|
||||
|
||||
/**
|
||||
* Lists tenant account metadata and subscription summaries for service-token callers from the canonical API runtime.
|
||||
* Lists tenant account metadata and subscription summaries after service-token authentication and an explicit RLS-verified platform operator identity.
|
||||
*/
|
||||
export const listAccounts = <ThrowOnError extends boolean = false>(options?: Options<ListAccountsData, ThrowOnError>) =>
|
||||
(options?.client ?? client).get<ListAccountsResponses, ListAccountsErrors, ThrowOnError>({
|
||||
export const listAccounts = <ThrowOnError extends boolean = false>(options: Options<ListAccountsData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<ListAccountsResponses, ListAccountsErrors, ThrowOnError>({
|
||||
security: [{ scheme: "bearer", type: "http" }],
|
||||
url: "/v1/accounts",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Looks up one tenant account by id or slug for service-token callers from the canonical API runtime.
|
||||
* Looks up one tenant account by id or slug after service-token authentication and an explicit RLS-verified platform operator identity.
|
||||
*/
|
||||
export const getAccount = <ThrowOnError extends boolean = false>(options: Options<GetAccountData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<GetAccountResponses, GetAccountErrors, ThrowOnError>({
|
||||
@@ -457,7 +503,7 @@ export const listPublicApiLeads = <ThrowOnError extends boolean = false>(options
|
||||
});
|
||||
|
||||
/**
|
||||
* Tenant-scoped incoming lead webhook. The endpoint authenticates by the endpoint's configured mode: API key, HMAC token/signature, or URL/header token. Successful requests create an InboxLead and queue webhook.received automation executions.
|
||||
* Tenant-scoped incoming lead webhook. Credentials are verified before payload, billing, or ingestion work. HMAC timestamps have a five-minute freshness window and exact signed replays are deduplicated through the persistent idempotency store. Successful requests create an InboxLead and queue webhook.received automation executions.
|
||||
*/
|
||||
export const receivePublicApiIncomingWebhook = <ThrowOnError extends boolean = false>(options: Options<ReceivePublicApiIncomingWebhookData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<ReceivePublicApiIncomingWebhookResponses, ReceivePublicApiIncomingWebhookErrors, ThrowOnError>({
|
||||
@@ -474,6 +520,24 @@ export const receivePublicApiIncomingWebhook = <ThrowOnError extends boolean = f
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Canonical API-host entry point for Lago lifecycle webhooks. The API verifies Lago's HMAC-SHA256 signature over the exact JSON request body, binds the embedded customer tenant, and applies subscription changes idempotently using the provider event key.
|
||||
*/
|
||||
export const receiveLagoBillingWebhook = <ThrowOnError extends boolean = false>(options: Options<ReceiveLagoBillingWebhookData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<ReceiveLagoBillingWebhookResponses, ReceiveLagoBillingWebhookErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ name: "X-Lago-Signature", type: "apiKey" },
|
||||
{ name: "X-Lago-Signature-Algorithm", type: "apiKey" },
|
||||
{ name: "X-Lago-Unique-Key", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/billing/lago/webhooks",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Canonical API-host entry point for Mollie payment lifecycle webhooks. Mollie posts a payment id; the API refetches that payment from Mollie server-side before syncing tenant billing state.
|
||||
*/
|
||||
@@ -488,6 +552,50 @@ export const receiveMollieBillingWebhook = <ThrowOnError extends boolean = false
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Canonical API-host entry point for Aircall call lifecycle webhooks. The provider token is supplied in the JSON body, resolved to an RLS identity through its stored hash, and never echoed or persisted in the event payload.
|
||||
*/
|
||||
export const receiveAircallTelephonyWebhook = <ThrowOnError extends boolean = false>(options: Options<ReceiveAircallTelephonyWebhookData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<ReceiveAircallTelephonyWebhookResponses, ReceiveAircallTelephonyWebhookErrors, ThrowOnError>({
|
||||
url: "/v1/webhooks/telephony/aircall",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Canonical API-host entry point for HalloPetra post-call webhooks. A separately generated webhook secret is supplied as an Authorization Bearer credential, resolved to one RLS identity through its stored hash, and never echoed or persisted in the event payload.
|
||||
*/
|
||||
export const receiveHalloPetraTelephonyWebhook = <ThrowOnError extends boolean = false>(
|
||||
options: Options<ReceiveHalloPetraTelephonyWebhookData, ThrowOnError>
|
||||
) =>
|
||||
(options.client ?? client).post<ReceiveHalloPetraTelephonyWebhookResponses, ReceiveHalloPetraTelephonyWebhookErrors, ThrowOnError>({
|
||||
security: [{ scheme: "bearer", type: "http" }],
|
||||
url: "/v1/webhooks/telephony/hallopetra",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Canonical API-host entry point for tenantless Admin Sales Aircall lifecycle webhooks. The provider token is supplied in the JSON body, resolved to an AdminUser RLS identity through its stored hash, and never echoed or persisted in the event payload.
|
||||
*/
|
||||
export const receiveAdminAircallTelephonyWebhook = <ThrowOnError extends boolean = false>(
|
||||
options: Options<ReceiveAdminAircallTelephonyWebhookData, ThrowOnError>
|
||||
) =>
|
||||
(options.client ?? client).post<ReceiveAdminAircallTelephonyWebhookResponses, ReceiveAdminAircallTelephonyWebhookErrors, ThrowOnError>({
|
||||
url: "/v1/webhooks/admin-telephony/aircall",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Accepts Mailjet provider event webhooks for email sequences, authenticated with HTTP Basic Auth. Bounce, blocked, and spam events correlate by provider message id (Message_GUID), mark the sequence delivery bounced, and fail the in-flight run without echoing provider payloads.
|
||||
*/
|
||||
@@ -504,6 +612,39 @@ export const receiveEmailSequenceMailjetWebhook = <ThrowOnError extends boolean
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Accepts provider-neutral delivery and bounce events for the tenantless Admin Sales workspace. The exact request body is authenticated with a timestamp-bound HMAC before the AdminUser RLS context is bound; consented open and click events use HiveGrid's signed tracking routes.
|
||||
*/
|
||||
export const receiveAdminSalesEmailProviderEvent = <ThrowOnError extends boolean = false>(
|
||||
options: Options<ReceiveAdminSalesEmailProviderEventData, ThrowOnError>
|
||||
) =>
|
||||
(options.client ?? client).post<ReceiveAdminSalesEmailProviderEventResponses, ReceiveAdminSalesEmailProviderEventErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ name: "X-HiveGrid-Signature", type: "apiKey" },
|
||||
{ name: "X-HiveGrid-Timestamp", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/admin-sales/email/provider-events",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Logs an externally sent message in the tenantless Admin Sales workspace. Mailjet HTTP Basic authentication and exactly one signed, rotatable BCC recipient capability are verified before the capability's AdminUser RLS context is bound.
|
||||
*/
|
||||
export const ingestAdminSalesEmailBccCopy = <ThrowOnError extends boolean = false>(options: Options<IngestAdminSalesEmailBccCopyData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<IngestAdminSalesEmailBccCopyResponses, IngestAdminSalesEmailBccCopyErrors, ThrowOnError>({
|
||||
security: [{ scheme: "basic", type: "http" }],
|
||||
url: "/v1/admin-sales/email/bcc-inbound",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
export const retryEventWebhookAttempt = <ThrowOnError extends boolean = false>(options: Options<RetryEventWebhookAttemptData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<RetryEventWebhookAttemptResponses, RetryEventWebhookAttemptErrors, ThrowOnError>({
|
||||
security: [{ scheme: "basic", type: "http" }],
|
||||
@@ -552,7 +693,7 @@ export const getExportJobProgress = <ThrowOnError extends boolean = false>(optio
|
||||
});
|
||||
|
||||
/**
|
||||
* Register or update a Web Push token for the authenticated principal. Requires a service-token bearer credential; the body's userId + tenantId are reconciled downstream against the authenticated principal. Tokens are upserted by their globally unique value so cold-start replays are idempotent.
|
||||
* Register or update a Web Push token for the owner of a verified, active API session JWT. The user identity comes exclusively from signed session claims; body or header identity overrides are rejected. An optional tenantId is accepted only after active membership is revalidated inside the tenant/user RLS context. Same-owner cold-start replays are idempotent, while foreign token ownership fails closed.
|
||||
*/
|
||||
export const postDeviceRegister = <ThrowOnError extends boolean = false>(options: Options<PostDeviceRegisterData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<PostDeviceRegisterResponses, PostDeviceRegisterErrors, ThrowOnError>({
|
||||
@@ -566,7 +707,7 @@ export const postDeviceRegister = <ThrowOnError extends boolean = false>(options
|
||||
});
|
||||
|
||||
/**
|
||||
* Revoke a Web Push token. Requires a service-token bearer credential; the handler revokes by token hash and never echoes the raw token in the response.
|
||||
* Revoke a Web Push token for the owner of a verified, active API session JWT. The user identity comes exclusively from signed session claims; body or header identity overrides are rejected. An optional tenantId is membership-revalidated. The ownership-constrained write treats foreign user or tenant tokens as not found and never echoes the raw token.
|
||||
*/
|
||||
export const postDeviceRevoke = <ThrowOnError extends boolean = false>(options: Options<PostDeviceRevokeData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<PostDeviceRevokeResponses, PostDeviceRevokeErrors, ThrowOnError>({
|
||||
|
||||
+949
-96
File diff suppressed because it is too large.
Load diff
@@ -15,6 +15,7 @@ export {
|
||||
createHiveGridClient,
|
||||
HiveGridApiError,
|
||||
HiveGridNetworkError,
|
||||
HiveGridResponseTooLargeError,
|
||||
type HiveGridClient,
|
||||
type HiveGridClientConfig,
|
||||
type HiveGridAuthConfig,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
export * from "./types.js";
|
||||
export * from "./lago.js";
|
||||
export * from "./mollie.js";
|
||||
export * from "./mollie-payment-policy.js";
|
||||
export * from "./payment-reservation.js";
|
||||
export * from "./sync-outbox.js";
|
||||
export * from "./sandbox-flow.js";
|
||||
export * from "./webhook.js";
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createLagoBillingGateway, LagoBillingGatewayError, normalizeLagoApiUrl, redactLagoValue } from "./lago.js";
|
||||
import { createLagoBillingGateway, ensureActiveLagoSubscription, LagoBillingGatewayError, normalizeLagoApiUrl, redactLagoValue } from "./lago.js";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
@@ -96,6 +96,8 @@ describe("LagoBillingGateway", () => {
|
||||
planCode: "business",
|
||||
seatQuantity: 5,
|
||||
subscriptionAt: new Date("2026-07-04T00:00:00Z"),
|
||||
paymentMethodType: "manual",
|
||||
consolidateInvoice: false,
|
||||
});
|
||||
|
||||
expect(subscription).toMatchObject({
|
||||
@@ -113,10 +115,455 @@ describe("LagoBillingGateway", () => {
|
||||
plan_code: "business",
|
||||
billing_time: "anniversary",
|
||||
subscription_at: "2026-07-04T00:00:00.000Z",
|
||||
payment_method: { payment_method_type: "manual" },
|
||||
consolidate_invoice: false,
|
||||
});
|
||||
expect(request.subscription).not.toHaveProperty("seatQuantity");
|
||||
});
|
||||
|
||||
it("reuses the exact active plan version for idempotent paid return and webhook races", async () => {
|
||||
const subscription = {
|
||||
provider: "lago" as const,
|
||||
externalId: "hgco_1",
|
||||
providerSubscriptionId: "lago_subscription_1",
|
||||
externalCustomerId: "tenant_1",
|
||||
planCode: "hg_price_swarm_123",
|
||||
status: "active" as const,
|
||||
name: "swarm (20 seats)",
|
||||
currentBillingPeriodStartedAt: "2026-08-01T00:00:00Z",
|
||||
currentBillingPeriodEndingAt: "2026-09-01T00:00:00Z",
|
||||
createdAt: "2026-08-01T00:00:00Z",
|
||||
};
|
||||
const gateway = {
|
||||
getSubscription: vi.fn(async () => subscription),
|
||||
createSubscription: vi.fn(),
|
||||
} as unknown as Parameters<typeof ensureActiveLagoSubscription>[0];
|
||||
|
||||
const input = {
|
||||
tenantId: "tenant_1",
|
||||
subscriptionExternalId: "hgco_1",
|
||||
planCode: "hg_price_swarm_123",
|
||||
seatQuantity: 20,
|
||||
paymentMethodType: "manual" as const,
|
||||
consolidateInvoice: false,
|
||||
};
|
||||
const [fromReturn, fromWebhook] = await Promise.all([ensureActiveLagoSubscription(gateway, input), ensureActiveLagoSubscription(gateway, input)]);
|
||||
|
||||
expect(fromReturn.providerSubscriptionId).toBe("lago_subscription_1");
|
||||
expect(fromWebhook.providerSubscriptionId).toBe("lago_subscription_1");
|
||||
expect(gateway.getSubscription).toHaveBeenCalledTimes(2);
|
||||
expect(gateway.createSubscription).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates and assigns an immutable managed plan without premium plan overrides", async () => {
|
||||
const managedPlan = {
|
||||
code: "hg_price_2026_07_29_1_starter_annual_sepa_abcd1234",
|
||||
name: "Core · 4 Büro · 8 Baustelle · Speicher: +500 GB Speicher",
|
||||
invoiceDisplayName: "Core · 4 Büro · 8 Baustelle · Speicher: +500 GB Speicher",
|
||||
description: "Core · HiveGrid Katalog 2026-07-29.1",
|
||||
interval: "monthly" as const,
|
||||
amountCents: 38_170,
|
||||
currency: "EUR",
|
||||
payInAdvance: true,
|
||||
taxCodes: ["de-vat-19"],
|
||||
metadata: {
|
||||
hivegrid_catalog_version: "2026-07-29.1",
|
||||
hivegrid_resource_kind: "selected_price",
|
||||
},
|
||||
};
|
||||
const providerPlan = {
|
||||
plan: {
|
||||
code: managedPlan.code,
|
||||
name: managedPlan.name,
|
||||
invoice_display_name: managedPlan.invoiceDisplayName,
|
||||
description: managedPlan.description,
|
||||
interval: managedPlan.interval,
|
||||
amount_cents: managedPlan.amountCents,
|
||||
amount_currency: managedPlan.currency,
|
||||
pay_in_advance: managedPlan.payInAdvance,
|
||||
taxes: [{ code: "de-vat-19" }],
|
||||
metadata: managedPlan.metadata,
|
||||
},
|
||||
};
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response("{}", { status: 404 }))
|
||||
.mockResolvedValueOnce(jsonResponse(providerPlan))
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
subscription: {
|
||||
lago_id: "lago_subscription_1",
|
||||
external_id: "sub_tenant_1_core",
|
||||
external_customer_id: "tenant_1",
|
||||
plan_code: managedPlan.code,
|
||||
status: "active",
|
||||
name: "Acme GmbH · Core",
|
||||
current_billing_period_started_at: null,
|
||||
current_billing_period_ending_at: null,
|
||||
created_at: "2026-07-29T00:00:00Z",
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(
|
||||
gateway.createSubscription({
|
||||
tenantId: "tenant_1",
|
||||
subscriptionExternalId: "sub_tenant_1_core",
|
||||
planCode: "starter_annual_sepa",
|
||||
seatQuantity: 12,
|
||||
name: "Acme GmbH · Core",
|
||||
managedPlan,
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
planCode: managedPlan.code,
|
||||
externalId: "sub_tenant_1_core",
|
||||
});
|
||||
|
||||
expect(fetchImpl.mock.calls.map((call) => [call[0], call[1]?.method])).toEqual([
|
||||
[`https://lago.example.test/api/v1/plans/${managedPlan.code}`, "GET"],
|
||||
["https://lago.example.test/api/v1/plans", "POST"],
|
||||
["https://lago.example.test/api/v1/subscriptions", "POST"],
|
||||
]);
|
||||
expect(JSON.parse(String(fetchImpl.mock.calls[1]?.[1]?.body))).toEqual({
|
||||
plan: {
|
||||
name: managedPlan.name,
|
||||
code: managedPlan.code,
|
||||
invoice_display_name: managedPlan.invoiceDisplayName,
|
||||
description: managedPlan.description,
|
||||
interval: "monthly",
|
||||
amount_cents: 38_170,
|
||||
amount_currency: "EUR",
|
||||
pay_in_advance: true,
|
||||
tax_codes: ["de-vat-19"],
|
||||
metadata: {
|
||||
hivegrid_catalog_version: "2026-07-29.1",
|
||||
hivegrid_resource_kind: "selected_price",
|
||||
},
|
||||
},
|
||||
});
|
||||
const subscriptionRequest = JSON.parse(String(fetchImpl.mock.calls[2]?.[1]?.body));
|
||||
expect(subscriptionRequest.subscription.plan_code).toBe(managedPlan.code);
|
||||
expect(subscriptionRequest.subscription).not.toHaveProperty("plan_overrides");
|
||||
});
|
||||
|
||||
it("activates only the pending subscription and keeps the paid commitment end", async () => {
|
||||
const pendingResponse = {
|
||||
subscription: {
|
||||
lago_id: "lago_pending_1",
|
||||
external_id: "checkout_1",
|
||||
external_customer_id: "tenant_1",
|
||||
plan_code: "swarm",
|
||||
status: "pending",
|
||||
name: "Swarm",
|
||||
current_billing_period_started_at: null,
|
||||
current_billing_period_ending_at: null,
|
||||
created_at: "2026-07-31T18:00:00Z",
|
||||
},
|
||||
};
|
||||
const activeResponse = {
|
||||
subscription: {
|
||||
...pendingResponse.subscription,
|
||||
status: "active",
|
||||
current_billing_period_started_at: "2026-07-31T18:30:00Z",
|
||||
current_billing_period_ending_at: "2026-08-31T18:30:00Z",
|
||||
},
|
||||
};
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(jsonResponse(pendingResponse))
|
||||
.mockResolvedValueOnce(jsonResponse(pendingResponse))
|
||||
.mockResolvedValueOnce(jsonResponse(activeResponse));
|
||||
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
|
||||
|
||||
await expect(
|
||||
gateway.activatePendingSubscription(" checkout_1 ", new Date("2026-07-31T18:30:00Z"), new Date("2027-07-31T18:30:00Z"))
|
||||
).resolves.toMatchObject({ externalId: "checkout_1", status: "active" });
|
||||
|
||||
expect(fetchImpl.mock.calls.map((call) => [call[0], call[1]?.method])).toEqual([
|
||||
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", "GET"],
|
||||
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", "PUT"],
|
||||
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=active", "GET"],
|
||||
]);
|
||||
expect(JSON.parse(String(fetchImpl.mock.calls[1]?.[1]?.body))).toEqual({
|
||||
subscription: {
|
||||
status: "pending",
|
||||
subscription_at: "2026-07-31T18:30:00.000Z",
|
||||
ending_at: "2027-07-31T18:30:00.000Z",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("waits for the exact pending Lago version instead of accepting an older active plan version", async () => {
|
||||
vi.useFakeTimers();
|
||||
const pendingResponse = {
|
||||
subscription: {
|
||||
lago_id: "lago_pending_2",
|
||||
external_id: "checkout_2",
|
||||
external_customer_id: "tenant_1",
|
||||
plan_code: "colony",
|
||||
status: "pending",
|
||||
name: "Colony",
|
||||
current_billing_period_started_at: null,
|
||||
current_billing_period_ending_at: null,
|
||||
created_at: "2026-07-31T18:00:00Z",
|
||||
},
|
||||
};
|
||||
const olderActiveResponse = {
|
||||
subscription: {
|
||||
...pendingResponse.subscription,
|
||||
lago_id: "lago_active_old",
|
||||
plan_code: "swarm",
|
||||
status: "active",
|
||||
},
|
||||
};
|
||||
const exactActiveResponse = {
|
||||
subscription: {
|
||||
...pendingResponse.subscription,
|
||||
status: "active",
|
||||
current_billing_period_started_at: "2026-07-31T18:30:00Z",
|
||||
current_billing_period_ending_at: "2026-08-31T18:30:00Z",
|
||||
},
|
||||
};
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(jsonResponse(pendingResponse))
|
||||
.mockResolvedValueOnce(jsonResponse(pendingResponse))
|
||||
.mockResolvedValueOnce(jsonResponse(olderActiveResponse))
|
||||
.mockResolvedValueOnce(jsonResponse(exactActiveResponse));
|
||||
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
|
||||
|
||||
const activation = gateway.activatePendingSubscription("checkout_2", "2026-07-31T18:30:00Z");
|
||||
await vi.runAllTimersAsync();
|
||||
|
||||
await expect(activation).resolves.toMatchObject({ providerSubscriptionId: "lago_pending_2", status: "active" });
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(4);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("treats an already-active subscription activation as an idempotent replay", async () => {
|
||||
const activeResponse = {
|
||||
subscription: {
|
||||
lago_id: "lago_active_1",
|
||||
external_id: "checkout_1",
|
||||
external_customer_id: "tenant_1",
|
||||
plan_code: "swarm",
|
||||
status: "active",
|
||||
name: "Swarm",
|
||||
current_billing_period_started_at: "2026-07-31T18:30:00Z",
|
||||
current_billing_period_ending_at: "2026-08-31T18:30:00Z",
|
||||
created_at: "2026-07-31T18:00:00Z",
|
||||
},
|
||||
};
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response("{}", { status: 404 }))
|
||||
.mockResolvedValueOnce(jsonResponse(activeResponse));
|
||||
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
|
||||
|
||||
await expect(gateway.activatePendingSubscription("checkout_1", "2026-07-31T18:30:00Z")).resolves.toMatchObject({ status: "active" });
|
||||
expect(fetchImpl.mock.calls.map((call) => [call[0], call[1]?.method])).toEqual([
|
||||
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", "GET"],
|
||||
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=active", "GET"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("terminates only a pending checkout subscription", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
subscription: {
|
||||
lago_id: "lago_pending_1",
|
||||
external_id: "checkout_1",
|
||||
external_customer_id: "tenant_1",
|
||||
plan_code: "swarm",
|
||||
status: "canceled",
|
||||
name: "Swarm",
|
||||
current_billing_period_started_at: null,
|
||||
current_billing_period_ending_at: null,
|
||||
created_at: "2026-07-31T18:00:00Z",
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
|
||||
|
||||
await expect(gateway.terminatePendingSubscription("checkout_1")).resolves.toMatchObject({ status: "canceled" });
|
||||
expect(fetchImpl).toHaveBeenCalledWith(
|
||||
"https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending",
|
||||
expect.objectContaining({ method: "DELETE" })
|
||||
);
|
||||
});
|
||||
|
||||
it("reuses an exact managed plan and rejects immutable price drift", async () => {
|
||||
const managedPlan = {
|
||||
code: "hg_price_starter_exact",
|
||||
name: "Core · 2 Büro · 5 Baustelle",
|
||||
invoiceDisplayName: "Core · 2 Büro · 5 Baustelle",
|
||||
description: "Core · HiveGrid Katalog 2026-07-29.1",
|
||||
interval: "monthly" as const,
|
||||
amountCents: 19_900,
|
||||
currency: "EUR",
|
||||
payInAdvance: true,
|
||||
taxCodes: ["de-vat-19"],
|
||||
metadata: { hivegrid_catalog_version: "2026-07-29.1" },
|
||||
};
|
||||
const providerPlan = {
|
||||
plan: {
|
||||
code: managedPlan.code,
|
||||
name: managedPlan.name,
|
||||
invoice_display_name: managedPlan.invoiceDisplayName,
|
||||
description: managedPlan.description,
|
||||
interval: managedPlan.interval,
|
||||
amount_cents: managedPlan.amountCents,
|
||||
amount_currency: managedPlan.currency,
|
||||
pay_in_advance: managedPlan.payInAdvance,
|
||||
taxes: [{ code: "de-vat-19" }],
|
||||
metadata: managedPlan.metadata,
|
||||
},
|
||||
};
|
||||
const subscriptionResponse = {
|
||||
subscription: {
|
||||
lago_id: "lago_subscription_exact",
|
||||
external_id: "sub_exact",
|
||||
external_customer_id: "tenant_1",
|
||||
plan_code: managedPlan.code,
|
||||
status: "active",
|
||||
name: managedPlan.name,
|
||||
current_billing_period_started_at: null,
|
||||
current_billing_period_ending_at: null,
|
||||
created_at: null,
|
||||
},
|
||||
};
|
||||
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValueOnce(jsonResponse(providerPlan)).mockResolvedValueOnce(jsonResponse(subscriptionResponse));
|
||||
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
|
||||
|
||||
await expect(
|
||||
gateway.createSubscription({
|
||||
tenantId: "tenant_1",
|
||||
subscriptionExternalId: "sub_exact",
|
||||
planCode: "starter",
|
||||
seatQuantity: 7,
|
||||
managedPlan,
|
||||
})
|
||||
).resolves.toMatchObject({ planCode: managedPlan.code });
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
expect(fetchImpl.mock.calls[0]?.[1]?.method).toBe("GET");
|
||||
expect(fetchImpl.mock.calls[1]?.[1]?.method).toBe("POST");
|
||||
|
||||
const driftFetch = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
plan: {
|
||||
...providerPlan.plan,
|
||||
amount_cents: 19_901,
|
||||
},
|
||||
})
|
||||
);
|
||||
const driftGateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl: driftFetch,
|
||||
});
|
||||
await expect(
|
||||
driftGateway.createSubscription({
|
||||
tenantId: "tenant_1",
|
||||
subscriptionExternalId: "sub_drift",
|
||||
planCode: "starter",
|
||||
seatQuantity: 7,
|
||||
managedPlan,
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "RESPONSE_INVALID",
|
||||
message: "Managed Lago plan conflicts with the requested immutable pricing.",
|
||||
});
|
||||
expect(driftFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("creates one-off invoices through a Lago add-on fee", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
invoice: {
|
||||
lago_id: "invoice_setup_1",
|
||||
number: "LAG-SETUP-001",
|
||||
external_customer_id: "tenant_1",
|
||||
status: "finalized",
|
||||
payment_status: "pending",
|
||||
invoice_type: "one_off",
|
||||
currency: "EUR",
|
||||
total_amount_cents: 29999,
|
||||
issuing_date: "2026-07-16",
|
||||
file_url: null,
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(
|
||||
gateway.createOneOffInvoice({
|
||||
tenantId: " tenant_1 ",
|
||||
addOnCode: " portal_domain_setup ",
|
||||
amountCents: 29999,
|
||||
currency: "eur",
|
||||
quantity: 1,
|
||||
description: "Portal domain setup",
|
||||
taxCodes: ["de-vat-19"],
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
providerInvoiceId: "invoice_setup_1",
|
||||
externalCustomerId: "tenant_1",
|
||||
invoiceType: "one_off",
|
||||
totalAmountCents: 29999,
|
||||
paymentStatus: "pending",
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledWith(
|
||||
"https://lago.example.test/api/v1/invoices",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
invoice: {
|
||||
external_customer_id: "tenant_1",
|
||||
currency: "EUR",
|
||||
fees: [
|
||||
{
|
||||
add_on_code: "portal_domain_setup",
|
||||
units: 1,
|
||||
unit_amount_cents: 29999,
|
||||
tax_codes: ["de-vat-19"],
|
||||
description: "Portal domain setup",
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects invalid one-off invoice inputs before contacting Lago", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>();
|
||||
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
|
||||
|
||||
await expect(gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: "setup", amountCents: 0, currency: "EUR" })).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
});
|
||||
await expect(gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: " ", amountCents: 29999, currency: "EUR" })).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
});
|
||||
await expect(gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: "setup", amountCents: 29999, currency: "EURO" })).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
});
|
||||
await expect(
|
||||
gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: "setup", amountCents: 29999, currency: "EUR", taxCodes: ["de-vat-19", "de-vat-19"] })
|
||||
).rejects.toMatchObject({ code: "CONFIG_INVALID" });
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reads invoice status with optional tenant filter", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
@@ -132,6 +579,13 @@ describe("LagoBillingGateway", () => {
|
||||
total_amount_cents: 4900,
|
||||
issuing_date: "2026-07-04",
|
||||
file_url: "https://files.example.test/invoice_1.pdf",
|
||||
billing_periods: [
|
||||
{
|
||||
external_subscription_id: "checkout_1",
|
||||
lago_subscription_id: "lago_subscription_1",
|
||||
invoicing_reason: "subscription_periodic",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
@@ -155,11 +609,75 @@ describe("LagoBillingGateway", () => {
|
||||
totalAmountCents: 4900,
|
||||
issuingDate: "2026-07-04",
|
||||
fileUrl: "https://files.example.test/invoice_1.pdf",
|
||||
billingPeriods: [
|
||||
{
|
||||
externalSubscriptionId: "checkout_1",
|
||||
providerSubscriptionId: "lago_subscription_1",
|
||||
invoicingReason: "subscription_periodic",
|
||||
},
|
||||
],
|
||||
subscriptionExternalIds: ["checkout_1"],
|
||||
subscriptionProviderIds: ["lago_subscription_1"],
|
||||
},
|
||||
]);
|
||||
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices?external_customer_id=tenant_1&page=2&per_page=10");
|
||||
});
|
||||
|
||||
it("reads an invoice detail with its exact subscription correlation", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
invoice: {
|
||||
lago_id: "invoice_1",
|
||||
number: "LAG-001",
|
||||
external_customer_id: "tenant_1",
|
||||
status: "finalized",
|
||||
payment_status: "pending",
|
||||
invoice_type: "subscription",
|
||||
currency: "EUR",
|
||||
total_amount_cents: 4_900,
|
||||
issuing_date: "2026-08-01",
|
||||
file_url: null,
|
||||
billing_periods: [
|
||||
{
|
||||
external_subscription_id: " checkout_1 ",
|
||||
lago_subscription_id: " lago_subscription_1 ",
|
||||
invoicing_reason: "subscription_starting",
|
||||
},
|
||||
{
|
||||
external_subscription_id: "checkout_1",
|
||||
lago_subscription_id: "lago_subscription_1",
|
||||
invoicing_reason: "future_lago_reason",
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(gateway.getInvoice("invoice_1")).resolves.toMatchObject({
|
||||
providerInvoiceId: "invoice_1",
|
||||
billingPeriods: [
|
||||
{
|
||||
externalSubscriptionId: "checkout_1",
|
||||
providerSubscriptionId: "lago_subscription_1",
|
||||
invoicingReason: "subscription_starting",
|
||||
},
|
||||
{
|
||||
externalSubscriptionId: "checkout_1",
|
||||
providerSubscriptionId: "lago_subscription_1",
|
||||
invoicingReason: null,
|
||||
},
|
||||
],
|
||||
subscriptionExternalIds: ["checkout_1"],
|
||||
subscriptionProviderIds: ["lago_subscription_1"],
|
||||
});
|
||||
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices/invoice_1");
|
||||
});
|
||||
|
||||
it("downloads an invoice and maps the generated file url", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
@@ -253,6 +771,43 @@ describe("LagoBillingGateway", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("terminates active subscriptions and falls back to the required pending-status endpoint", async () => {
|
||||
const terminated = {
|
||||
subscription: {
|
||||
lago_id: "lago_subscription_1",
|
||||
external_id: "acquisition_1",
|
||||
external_customer_id: "tenant_1",
|
||||
plan_code: "customer_portal_monthly",
|
||||
status: "terminated",
|
||||
name: "Customer Portal",
|
||||
current_billing_period_started_at: null,
|
||||
current_billing_period_ending_at: null,
|
||||
created_at: null,
|
||||
},
|
||||
};
|
||||
const activeFetch = vi.fn<typeof fetch>(async () => jsonResponse(terminated));
|
||||
const activeGateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl: activeFetch });
|
||||
await expect(activeGateway.terminateSubscription(" acquisition_1 ")).resolves.toMatchObject({ status: "terminated" });
|
||||
expect(activeFetch).toHaveBeenCalledWith("https://lago.example.test/api/v1/subscriptions/acquisition_1", expect.objectContaining({ method: "DELETE" }));
|
||||
|
||||
const pendingFetch = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response("{}", { status: 405 }))
|
||||
.mockResolvedValueOnce(jsonResponse(terminated));
|
||||
const pendingGateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl: pendingFetch });
|
||||
await expect(pendingGateway.terminateSubscription("acquisition_1")).resolves.toMatchObject({ status: "terminated" });
|
||||
expect(pendingFetch.mock.calls[1]?.[0]).toBe("https://lago.example.test/api/v1/subscriptions/acquisition_1?status=pending");
|
||||
expect(pendingFetch.mock.calls[1]?.[1]).toMatchObject({ method: "DELETE" });
|
||||
});
|
||||
|
||||
it("treats two termination 404s as an idempotent already-terminated result", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => new Response("{}", { status: 404 }));
|
||||
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
|
||||
|
||||
await expect(gateway.terminateSubscription("acquisition_1")).resolves.toBeNull();
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("rejects invalid configuration and invalid response shapes", async () => {
|
||||
expect(() => normalizeLagoApiUrl("file:///tmp/lago")).toThrow(LagoBillingGatewayError);
|
||||
expect(() => createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: " " })).toThrow(LagoBillingGatewayError);
|
||||
|
||||
@@ -5,10 +5,14 @@ import type {
|
||||
BillingGatewayCustomer,
|
||||
BillingGatewayCustomerInput,
|
||||
BillingGatewayInvoice,
|
||||
BillingGatewayInvoiceInvoicingReason,
|
||||
BillingGatewayInvoiceListInput,
|
||||
BillingGatewayOneOffInvoiceInput,
|
||||
BillingGatewaySubscription,
|
||||
BillingGatewaySubscriptionInput,
|
||||
BillingGatewaySubscriptionStatus,
|
||||
} from "./types.js";
|
||||
import { readBillingJsonResponse } from "./provider-http.js";
|
||||
|
||||
const DEFAULT_LAGO_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_LAGO_PER_PAGE = 20;
|
||||
@@ -55,6 +59,23 @@ const lagoSubscriptionSchema = z.object({
|
||||
created_at: nullableString,
|
||||
});
|
||||
|
||||
const lagoPlanSchema = z.object({
|
||||
code: z.string(),
|
||||
name: z.string(),
|
||||
invoice_display_name: nullableString,
|
||||
description: nullableString,
|
||||
interval: z.string(),
|
||||
amount_cents: z.number().int(),
|
||||
amount_currency: z.string(),
|
||||
pay_in_advance: z.boolean(),
|
||||
taxes: z.array(
|
||||
z.object({
|
||||
code: z.string(),
|
||||
})
|
||||
),
|
||||
metadata: z.record(z.string(), z.unknown()).nullable().optional(),
|
||||
});
|
||||
|
||||
const lagoInvoiceSchema = z.object({
|
||||
lago_id: z.string(),
|
||||
number: nullableString,
|
||||
@@ -72,13 +93,36 @@ const lagoInvoiceSchema = z.object({
|
||||
total_amount_cents: z.number().nullable().optional(),
|
||||
issuing_date: nullableString,
|
||||
file_url: nullableString,
|
||||
billing_periods: z
|
||||
.array(
|
||||
z.object({
|
||||
external_subscription_id: nullableString,
|
||||
lago_subscription_id: nullableString,
|
||||
invoicing_reason: nullableString,
|
||||
})
|
||||
)
|
||||
.nullable()
|
||||
.optional(),
|
||||
metadata: z
|
||||
.array(
|
||||
z.object({
|
||||
key: z.string(),
|
||||
value: z.string(),
|
||||
})
|
||||
)
|
||||
.nullable()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const customerResponseSchema = z.object({ customer: lagoCustomerSchema });
|
||||
const subscriptionResponseSchema = z.object({ subscription: lagoSubscriptionSchema });
|
||||
const planResponseSchema = z.object({ plan: lagoPlanSchema });
|
||||
const invoiceResponseSchema = z.object({ invoice: lagoInvoiceSchema });
|
||||
const invoicesResponseSchema = z.object({ invoices: z.array(lagoInvoiceSchema) });
|
||||
|
||||
const subscriptionActivationReadAttempts = 5;
|
||||
const subscriptionActivationReadDelayMs = 100;
|
||||
|
||||
type LagoCustomer = z.infer<typeof lagoCustomerSchema>;
|
||||
type LagoSubscription = z.infer<typeof lagoSubscriptionSchema>;
|
||||
type LagoInvoice = z.infer<typeof lagoInvoiceSchema>;
|
||||
@@ -147,15 +191,19 @@ class LagoBillingGateway implements BillingGateway {
|
||||
|
||||
async createSubscription(input: BillingGatewaySubscriptionInput): Promise<BillingGatewaySubscription> {
|
||||
assertPositiveSeatQuantity(input.seatQuantity);
|
||||
const managedPlan = normalizeManagedPlan(input.managedPlan);
|
||||
if (managedPlan) await this.ensureManagedPlan(managedPlan);
|
||||
const response = await this.request("/subscriptions", {
|
||||
method: "POST",
|
||||
body: {
|
||||
subscription: {
|
||||
external_customer_id: input.tenantId,
|
||||
external_id: input.subscriptionExternalId,
|
||||
plan_code: input.planCode,
|
||||
plan_code: managedPlan?.code ?? input.planCode,
|
||||
name: input.name ?? `${input.planCode} (${input.seatQuantity} seats)`,
|
||||
billing_time: "anniversary",
|
||||
...(input.paymentMethodType ? { payment_method: { payment_method_type: input.paymentMethodType } } : {}),
|
||||
...(typeof input.consolidateInvoice === "boolean" ? { consolidate_invoice: input.consolidateInvoice } : {}),
|
||||
...(input.subscriptionAt ? { subscription_at: toIsoString(input.subscriptionAt) } : {}),
|
||||
...(input.endingAt ? { ending_at: toIsoString(input.endingAt) } : {}),
|
||||
},
|
||||
@@ -164,20 +212,178 @@ class LagoBillingGateway implements BillingGateway {
|
||||
return toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
|
||||
}
|
||||
|
||||
async getSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null> {
|
||||
const response = await this.request(`/subscriptions/${encodeURIComponent(subscriptionExternalId)}`, { method: "GET", allowNotFound: true });
|
||||
async ensureManagedPlan(planInput: NonNullable<BillingGatewaySubscriptionInput["managedPlan"]>): Promise<void> {
|
||||
const plan = normalizeManagedPlan(planInput);
|
||||
if (!plan) {
|
||||
throw new LagoBillingGatewayError("Managed plan is required.", "CONFIG_INVALID");
|
||||
}
|
||||
const path = `/plans/${encodeURIComponent(plan.code)}`;
|
||||
let response = await this.request(path, { method: "GET", allowNotFound: true });
|
||||
if (response === null) {
|
||||
try {
|
||||
response = await this.request("/plans", {
|
||||
method: "POST",
|
||||
body: {
|
||||
plan: {
|
||||
name: plan.name,
|
||||
code: plan.code,
|
||||
invoice_display_name: plan.invoiceDisplayName,
|
||||
description: plan.description,
|
||||
interval: plan.interval,
|
||||
amount_cents: plan.amountCents,
|
||||
amount_currency: plan.currency,
|
||||
pay_in_advance: plan.payInAdvance,
|
||||
tax_codes: plan.taxCodes,
|
||||
metadata: plan.metadata,
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (!(error instanceof LagoBillingGatewayError) || (error.status !== 409 && error.status !== 422)) throw error;
|
||||
response = await this.request(path, { method: "GET" });
|
||||
}
|
||||
}
|
||||
assertManagedPlanMatches(plan, parseLagoResponse(planResponseSchema, response).plan);
|
||||
}
|
||||
|
||||
async getSubscription(subscriptionExternalId: string, status?: BillingGatewaySubscriptionStatus): Promise<BillingGatewaySubscription | null> {
|
||||
const id = normalizeSubscriptionExternalId(subscriptionExternalId);
|
||||
const query = status ? `?status=${encodeURIComponent(status)}` : "";
|
||||
const response = await this.request(`/subscriptions/${encodeURIComponent(id)}${query}`, { method: "GET", allowNotFound: true });
|
||||
return response === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
|
||||
}
|
||||
|
||||
async activatePendingSubscription(
|
||||
subscriptionExternalId: string,
|
||||
activatedAt: Date | string,
|
||||
endingAt?: Date | string | null
|
||||
): Promise<BillingGatewaySubscription | null> {
|
||||
const id = normalizeSubscriptionExternalId(subscriptionExternalId);
|
||||
const pending = await this.getSubscription(id, "pending");
|
||||
if (!pending) return this.getSubscription(id, "active");
|
||||
|
||||
const response = await this.request(`/subscriptions/${encodeURIComponent(id)}?status=pending`, {
|
||||
method: "PUT",
|
||||
allowNotFound: true,
|
||||
body: {
|
||||
subscription: {
|
||||
status: "pending",
|
||||
subscription_at: toIsoString(activatedAt),
|
||||
...(endingAt === undefined ? {} : { ending_at: endingAt === null ? null : toIsoString(endingAt) }),
|
||||
},
|
||||
},
|
||||
});
|
||||
const updated = response === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
|
||||
if (updated?.status === "active" && updated.providerSubscriptionId === pending.providerSubscriptionId) return updated;
|
||||
|
||||
// Lago v1.50 may return the selected pending version even though moving
|
||||
// subscription_at has already started the same provider version. Re-read
|
||||
// the active view and require the exact Lago id so an older active version
|
||||
// from a plan change can never satisfy this payment confirmation.
|
||||
for (let attempt = 0; attempt < subscriptionActivationReadAttempts; attempt += 1) {
|
||||
const active = await this.getSubscription(id, "active");
|
||||
if (active?.providerSubscriptionId === pending.providerSubscriptionId) return active;
|
||||
if (attempt < subscriptionActivationReadAttempts - 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, subscriptionActivationReadDelayMs * (attempt + 1)));
|
||||
}
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
async terminatePendingSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null> {
|
||||
const id = normalizeSubscriptionExternalId(subscriptionExternalId);
|
||||
const response = await this.request(`/subscriptions/${encodeURIComponent(id)}?status=pending`, {
|
||||
method: "DELETE",
|
||||
allowNotFound: true,
|
||||
});
|
||||
return response === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
|
||||
}
|
||||
|
||||
async terminateSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null> {
|
||||
const id = normalizeSubscriptionExternalId(subscriptionExternalId);
|
||||
let active: unknown | null;
|
||||
try {
|
||||
active = await this.request(`/subscriptions/${encodeURIComponent(id)}`, { method: "DELETE", allowNotFound: true });
|
||||
} catch (error) {
|
||||
// Lago may answer 405 when the external id currently resolves only to a
|
||||
// pending subscription. That case must be retried with status=pending.
|
||||
if (!(error instanceof LagoBillingGatewayError) || error.status !== 405) throw error;
|
||||
active = null;
|
||||
}
|
||||
if (active !== null) return toSubscription(parseLagoResponse(subscriptionResponseSchema, active));
|
||||
|
||||
// Lago requires an explicit status filter when the subscription has not
|
||||
// started yet. A second 404 is an idempotent already-terminated result.
|
||||
const pending = await this.request(`/subscriptions/${encodeURIComponent(id)}?status=pending`, {
|
||||
method: "DELETE",
|
||||
allowNotFound: true,
|
||||
});
|
||||
return pending === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, pending));
|
||||
}
|
||||
|
||||
async createOneOffInvoice(input: BillingGatewayOneOffInvoiceInput): Promise<BillingGatewayInvoice> {
|
||||
const tenantId = input.tenantId.trim();
|
||||
const addOnCode = input.addOnCode.trim();
|
||||
const quantity = input.quantity ?? 1;
|
||||
const currency = input.currency.trim().toUpperCase();
|
||||
if (!tenantId) throw new LagoBillingGatewayError("Tenant id is required.", "CONFIG_INVALID");
|
||||
if (!addOnCode) throw new LagoBillingGatewayError("Add-on code is required.", "CONFIG_INVALID");
|
||||
if (!Number.isInteger(quantity) || quantity < 1) {
|
||||
throw new LagoBillingGatewayError("One-off invoice quantity must be a positive integer.", "CONFIG_INVALID");
|
||||
}
|
||||
if (!Number.isInteger(input.amountCents) || input.amountCents <= 0) {
|
||||
throw new LagoBillingGatewayError("One-off invoice amount must be a positive cent integer.", "CONFIG_INVALID");
|
||||
}
|
||||
if (!/^[A-Z]{3}$/u.test(currency)) {
|
||||
throw new LagoBillingGatewayError("One-off invoice currency must be a three-letter ISO code.", "CONFIG_INVALID");
|
||||
}
|
||||
const taxCodes = normalizeTaxCodes(input.taxCodes ?? [], "One-off invoice");
|
||||
const metadata = normalizeInvoiceMetadata(input.metadata);
|
||||
|
||||
const response = await this.request("/invoices", {
|
||||
method: "POST",
|
||||
body: {
|
||||
invoice: {
|
||||
external_customer_id: tenantId,
|
||||
currency,
|
||||
fees: [
|
||||
{
|
||||
add_on_code: addOnCode,
|
||||
units: quantity,
|
||||
unit_amount_cents: input.amountCents,
|
||||
...(taxCodes.length > 0 ? { tax_codes: taxCodes } : {}),
|
||||
...(input.description?.trim() ? { description: input.description.trim() } : {}),
|
||||
},
|
||||
],
|
||||
...(metadata.length > 0 ? { metadata } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
return toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
|
||||
}
|
||||
|
||||
async listInvoices(input: BillingGatewayInvoiceListInput = {}): Promise<BillingGatewayInvoice[]> {
|
||||
const query = new URLSearchParams();
|
||||
if (input.tenantId) query.set("external_customer_id", input.tenantId);
|
||||
for (const [key, value] of Object.entries(input.metadata ?? {}).sort(([left], [right]) => left.localeCompare(right))) {
|
||||
query.set(`metadata[${key}]`, value);
|
||||
}
|
||||
query.set("page", String(input.page ?? 1));
|
||||
query.set("per_page", String(input.perPage ?? DEFAULT_LAGO_PER_PAGE));
|
||||
const response = await this.request(`/invoices?${query.toString()}`, { method: "GET" });
|
||||
return parseLagoResponse(invoicesResponseSchema, response).invoices.map(toInvoice);
|
||||
}
|
||||
|
||||
async getInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null> {
|
||||
const id = providerInvoiceId.trim();
|
||||
if (!id) {
|
||||
throw new LagoBillingGatewayError("Invoice id is required.", "CONFIG_INVALID");
|
||||
}
|
||||
const response = await this.request(`/invoices/${encodeURIComponent(id)}`, { method: "GET", allowNotFound: true });
|
||||
return response === null ? null : toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
|
||||
}
|
||||
|
||||
async downloadInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null> {
|
||||
const id = providerInvoiceId.trim();
|
||||
if (!id) {
|
||||
@@ -206,7 +412,10 @@ class LagoBillingGateway implements BillingGateway {
|
||||
return toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
|
||||
}
|
||||
|
||||
private async request(path: string, options: { method: "GET" | "POST" | "PUT"; body?: unknown; allowNotFound?: boolean }): Promise<unknown | null> {
|
||||
private async request(
|
||||
path: string,
|
||||
options: { method: "GET" | "POST" | "PUT" | "DELETE"; body?: unknown; allowNotFound?: boolean }
|
||||
): Promise<unknown | null> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||
try {
|
||||
@@ -218,6 +427,7 @@ class LagoBillingGateway implements BillingGateway {
|
||||
...(options.body ? { "content-type": "application/json" } : {}),
|
||||
},
|
||||
body: options.body ? JSON.stringify(options.body) : undefined,
|
||||
redirect: "error",
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.status === 404 && options.allowNotFound) {
|
||||
@@ -226,7 +436,7 @@ class LagoBillingGateway implements BillingGateway {
|
||||
if (!response.ok) {
|
||||
throw new LagoBillingGatewayError(`Lago request failed with status ${response.status}.`, "REQUEST_FAILED", response.status);
|
||||
}
|
||||
return await response.json();
|
||||
return await readBillingJsonResponse(response);
|
||||
} catch (error) {
|
||||
if (error instanceof LagoBillingGatewayError) throw error;
|
||||
throw new LagoBillingGatewayError("Lago request failed.", "REQUEST_FAILED");
|
||||
@@ -236,6 +446,35 @@ class LagoBillingGateway implements BillingGateway {
|
||||
}
|
||||
}
|
||||
|
||||
const activeSubscriptionReadAttempts = 5;
|
||||
const activeSubscriptionReadDelayMs = 100;
|
||||
|
||||
export async function ensureActiveLagoSubscription(
|
||||
gateway: BillingGateway,
|
||||
input: Omit<BillingGatewaySubscriptionInput, "subscriptionAt" | "managedPlan">
|
||||
): Promise<BillingGatewaySubscription> {
|
||||
const expectedPlanCode = input.planCode.trim();
|
||||
const existing = await gateway.getSubscription(input.subscriptionExternalId, "active");
|
||||
if (existing?.status === "active" && existing.planCode === expectedPlanCode) return existing;
|
||||
|
||||
try {
|
||||
const created = await gateway.createSubscription(input);
|
||||
if (created.status === "active" && created.planCode === expectedPlanCode) return created;
|
||||
} catch (error) {
|
||||
if (!(error instanceof LagoBillingGatewayError) || (error.status !== 409 && error.status !== 422)) throw error;
|
||||
}
|
||||
|
||||
for (let attempt = 0; attempt < activeSubscriptionReadAttempts; attempt += 1) {
|
||||
const active = await gateway.getSubscription(input.subscriptionExternalId, "active");
|
||||
if (active?.status === "active" && active.planCode === expectedPlanCode) return active;
|
||||
if (attempt < activeSubscriptionReadAttempts - 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, activeSubscriptionReadDelayMs * (attempt + 1)));
|
||||
}
|
||||
}
|
||||
|
||||
throw new LagoBillingGatewayError("Lago subscription could not be created as the requested active version.", "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function parseLagoResponse<T>(schema: z.ZodType<T>, response: unknown): T {
|
||||
const result = schema.safeParse(response);
|
||||
if (!result.success) {
|
||||
@@ -274,6 +513,18 @@ function toSubscription(response: { subscription: LagoSubscription }): BillingGa
|
||||
}
|
||||
|
||||
function toInvoice(invoice: LagoInvoice): BillingGatewayInvoice {
|
||||
const metadata = Object.fromEntries((invoice.metadata ?? []).map((item) => [item.key, item.value]));
|
||||
const billingPeriods = (invoice.billing_periods ?? []).map((period) => ({
|
||||
externalSubscriptionId: normalizeOptionalString(period.external_subscription_id),
|
||||
providerSubscriptionId: normalizeOptionalString(period.lago_subscription_id),
|
||||
invoicingReason: normalizeInvoiceInvoicingReason(period.invoicing_reason),
|
||||
}));
|
||||
const subscriptionExternalIds = [
|
||||
...new Set(billingPeriods.map((period) => period.externalSubscriptionId).filter((value): value is string => value !== null)),
|
||||
];
|
||||
const subscriptionProviderIds = [
|
||||
...new Set(billingPeriods.map((period) => period.providerSubscriptionId).filter((value): value is string => value !== null)),
|
||||
];
|
||||
return {
|
||||
provider: "lago",
|
||||
providerInvoiceId: invoice.lago_id,
|
||||
@@ -286,9 +537,37 @@ function toInvoice(invoice: LagoInvoice): BillingGatewayInvoice {
|
||||
totalAmountCents: invoice.total_amount_cents ?? null,
|
||||
issuingDate: invoice.issuing_date ?? null,
|
||||
fileUrl: invoice.file_url ?? null,
|
||||
...(billingPeriods.length > 0 ? { billingPeriods } : {}),
|
||||
...(subscriptionExternalIds.length > 0 ? { subscriptionExternalIds } : {}),
|
||||
...(subscriptionProviderIds.length > 0 ? { subscriptionProviderIds } : {}),
|
||||
...(Object.keys(metadata).length > 0 ? { metadata } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeOptionalString(value: string | null | undefined): string | null {
|
||||
const normalized = value?.trim();
|
||||
return normalized ? normalized : null;
|
||||
}
|
||||
|
||||
function normalizeInvoiceInvoicingReason(value: string | null | undefined): BillingGatewayInvoiceInvoicingReason | null {
|
||||
const normalized = normalizeOptionalString(value);
|
||||
if (normalized === "subscription_starting" || normalized === "subscription_periodic") return normalized;
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeInvoiceMetadata(metadata: Readonly<Record<string, string>> | undefined): Array<{ key: string; value: string }> {
|
||||
return Object.entries(metadata ?? {})
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([rawKey, rawValue]) => {
|
||||
const key = rawKey.trim();
|
||||
const value = rawValue.trim();
|
||||
if (!/^[A-Za-z0-9_.-]{1,20}$/u.test(key) || value.length < 1 || value.length > 255) {
|
||||
throw new LagoBillingGatewayError("Invoice metadata is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
return { key, value };
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeTimeout(timeoutMs: number | undefined): number {
|
||||
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_LAGO_TIMEOUT_MS;
|
||||
}
|
||||
@@ -299,6 +578,96 @@ function assertPositiveSeatQuantity(seatQuantity: number): void {
|
||||
}
|
||||
}
|
||||
|
||||
type NormalizedManagedPlan = NonNullable<BillingGatewaySubscriptionInput["managedPlan"]>;
|
||||
|
||||
function normalizeManagedPlan(value: BillingGatewaySubscriptionInput["managedPlan"]): NormalizedManagedPlan | null {
|
||||
if (!value) return null;
|
||||
const code = value.code.trim();
|
||||
if (!/^[A-Za-z0-9_-]{1,120}$/u.test(code)) {
|
||||
throw new LagoBillingGatewayError("Managed plan code is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
const name = normalizeManagedPlanText(value.name, "name");
|
||||
const invoiceDisplayName = normalizeManagedPlanText(value.invoiceDisplayName, "invoice display name");
|
||||
const description = normalizeManagedPlanText(value.description, "description");
|
||||
if (!Number.isSafeInteger(value.amountCents) || value.amountCents <= 0) {
|
||||
throw new LagoBillingGatewayError("Managed plan amount must be a positive cent integer.", "CONFIG_INVALID");
|
||||
}
|
||||
const currency = value.currency.trim().toUpperCase();
|
||||
if (!/^[A-Z]{3}$/u.test(currency)) {
|
||||
throw new LagoBillingGatewayError("Managed plan currency must be a three-letter ISO code.", "CONFIG_INVALID");
|
||||
}
|
||||
const taxCodes = normalizeTaxCodes(value.taxCodes, "Managed plan");
|
||||
const metadata = Object.fromEntries(
|
||||
Object.entries(value.metadata)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([rawKey, rawValue]) => {
|
||||
const key = rawKey.trim();
|
||||
const metadataValue = rawValue.trim();
|
||||
if (!/^[A-Za-z0-9_.-]{1,64}$/u.test(key) || metadataValue.length < 1 || metadataValue.length > 255) {
|
||||
throw new LagoBillingGatewayError("Managed plan metadata is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
return [key, metadataValue];
|
||||
})
|
||||
);
|
||||
return {
|
||||
code,
|
||||
name,
|
||||
invoiceDisplayName,
|
||||
description,
|
||||
interval: value.interval,
|
||||
amountCents: value.amountCents,
|
||||
currency,
|
||||
payInAdvance: value.payInAdvance,
|
||||
taxCodes,
|
||||
metadata,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeTaxCodes(values: readonly string[], label: string): string[] {
|
||||
const taxCodes = [...new Set(values.map((taxCode) => taxCode.trim()).filter(Boolean))].sort();
|
||||
if (taxCodes.length !== values.length || taxCodes.some((taxCode) => !/^[A-Za-z0-9_-]{1,100}$/u.test(taxCode))) {
|
||||
throw new LagoBillingGatewayError(`${label} tax codes are invalid.`, "CONFIG_INVALID");
|
||||
}
|
||||
return taxCodes;
|
||||
}
|
||||
|
||||
function normalizeManagedPlanText(value: string, label: string): string {
|
||||
const normalized = value.trim();
|
||||
if (!normalized || normalized.length > 255) {
|
||||
throw new LagoBillingGatewayError(`Managed plan ${label} is invalid.`, "CONFIG_INVALID");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function assertManagedPlanMatches(expected: NormalizedManagedPlan, actual: z.infer<typeof lagoPlanSchema>): void {
|
||||
const actualMetadata = Object.fromEntries(
|
||||
Object.entries(actual.metadata ?? {})
|
||||
.filter((entry): entry is [string, string] => typeof entry[1] === "string")
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
);
|
||||
const actualTaxCodes = actual.taxes.map((tax) => tax.code).sort();
|
||||
const matches =
|
||||
actual.code === expected.code &&
|
||||
actual.name === expected.name &&
|
||||
(actual.invoice_display_name ?? "") === expected.invoiceDisplayName &&
|
||||
(actual.description ?? "") === expected.description &&
|
||||
actual.interval === expected.interval &&
|
||||
actual.amount_cents === expected.amountCents &&
|
||||
actual.amount_currency.toUpperCase() === expected.currency &&
|
||||
actual.pay_in_advance === expected.payInAdvance &&
|
||||
JSON.stringify(actualTaxCodes) === JSON.stringify(expected.taxCodes) &&
|
||||
JSON.stringify(actualMetadata) === JSON.stringify(expected.metadata);
|
||||
if (!matches) {
|
||||
throw new LagoBillingGatewayError("Managed Lago plan conflicts with the requested immutable pricing.", "RESPONSE_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeSubscriptionExternalId(value: string): string {
|
||||
const id = value.trim();
|
||||
if (!id) throw new LagoBillingGatewayError("Subscription external id is required.", "CONFIG_INVALID");
|
||||
return id;
|
||||
}
|
||||
|
||||
function toIsoString(value: Date | string): string {
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
}
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
defaultMollieFirstPaymentMethod,
|
||||
MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS,
|
||||
requiresMollieCardForAmount,
|
||||
resolveMollieCheckoutPaymentMethodRequirement,
|
||||
resolveMollieRecurringPaymentMethod,
|
||||
selectMollieRecurringMandate,
|
||||
} from "./mollie-payment-policy.js";
|
||||
|
||||
describe("Mollie payment policy", () => {
|
||||
it("switches from SEPA to card only above the exact EUR 1,000 boundary", () => {
|
||||
expect(requiresMollieCardForAmount({ amountCents: MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS, currency: "eur" })).toBe(false);
|
||||
expect(requiresMollieCardForAmount({ amountCents: MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS + 1, currency: "EUR" })).toBe(true);
|
||||
expect(
|
||||
resolveMollieCheckoutPaymentMethodRequirement({
|
||||
amountCents: MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS + 1,
|
||||
currency: "EUR",
|
||||
configuredRequirement: "sepa",
|
||||
})
|
||||
).toBe("card");
|
||||
});
|
||||
|
||||
it("keeps the configured method contract at or below the boundary", () => {
|
||||
expect(
|
||||
resolveMollieCheckoutPaymentMethodRequirement({
|
||||
amountCents: MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS,
|
||||
currency: "EUR",
|
||||
configuredRequirement: "sepa",
|
||||
})
|
||||
).toBe("sepa");
|
||||
expect(resolveMollieCheckoutPaymentMethodRequirement({ amountCents: 29_900, currency: "EUR", configuredRequirement: "any" })).toBe("any");
|
||||
});
|
||||
|
||||
it("pins high-value first and recurring payments to credit card", () => {
|
||||
expect(defaultMollieFirstPaymentMethod("card", ["ideal"])).toBe("creditcard");
|
||||
expect(resolveMollieRecurringPaymentMethod({ amountCents: 100_001, currency: "EUR", billingCadence: "monthly" })).toBe("creditcard");
|
||||
expect(resolveMollieRecurringPaymentMethod({ amountCents: 100_000, currency: "EUR", billingCadence: "annual_sepa" })).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the latest valid customer-selected mandate below the boundary", () => {
|
||||
expect(
|
||||
selectMollieRecurringMandate({
|
||||
amountCents: 100_000,
|
||||
currency: "EUR",
|
||||
mandates: [
|
||||
{ provider: "mollie", providerMandateId: "mdt_sepa", status: "valid", method: "directdebit", createdAt: "2026-08-01T10:00:00.000Z" },
|
||||
{ provider: "mollie", providerMandateId: "mdt_card", status: "valid", method: "creditcard", createdAt: "2026-08-02T10:00:00.000Z" },
|
||||
],
|
||||
})
|
||||
).toMatchObject({ providerMandateId: "mdt_card", method: "creditcard" });
|
||||
});
|
||||
|
||||
it("requires a valid card mandate above the boundary without SEPA fallback", () => {
|
||||
const mandates = [
|
||||
{ provider: "mollie" as const, providerMandateId: "mdt_sepa", status: "valid" as const, method: "directdebit" as const, createdAt: null },
|
||||
{ provider: "mollie" as const, providerMandateId: "mdt_pending", status: "pending" as const, method: "creditcard" as const, createdAt: null },
|
||||
];
|
||||
expect(selectMollieRecurringMandate({ amountCents: 100_001, currency: "EUR", mandates })).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects malformed amounts and currencies before choosing a method", () => {
|
||||
expect(() => requiresMollieCardForAmount({ amountCents: -1, currency: "EUR" })).toThrow("non-negative integer");
|
||||
expect(() => requiresMollieCardForAmount({ amountCents: 100_001, currency: "EURO" })).toThrow("ISO 4217");
|
||||
});
|
||||
});
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import type { MolliePaymentMethodId, MollieSepaFirstPaymentMethod, PaymentGatewayMandate } from "./types.js";
|
||||
|
||||
/** Mollie's documented default upper limit for one SEPA Direct Debit charge. */
|
||||
export const MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS = 100_000;
|
||||
|
||||
export type MollieCheckoutPaymentMethodRequirement = "any" | "sepa" | "card";
|
||||
|
||||
type MollieAmountInput = {
|
||||
readonly amountCents: number;
|
||||
readonly currency: string;
|
||||
};
|
||||
|
||||
function normalizeMollieAmount(input: MollieAmountInput): { amountCents: number; currency: string } {
|
||||
if (!Number.isSafeInteger(input.amountCents) || input.amountCents < 0) {
|
||||
throw new TypeError("Mollie payment amount must be a non-negative integer.");
|
||||
}
|
||||
const currency = input.currency.trim().toUpperCase();
|
||||
if (!/^[A-Z]{3}$/u.test(currency)) {
|
||||
throw new TypeError("Mollie payment currency must be an ISO 4217 code.");
|
||||
}
|
||||
return { amountCents: input.amountCents, currency };
|
||||
}
|
||||
|
||||
export function requiresMollieCardForAmount(input: MollieAmountInput): boolean {
|
||||
const normalized = normalizeMollieAmount(input);
|
||||
return normalized.currency === "EUR" && normalized.amountCents > MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS;
|
||||
}
|
||||
|
||||
export function resolveMollieCheckoutPaymentMethodRequirement(
|
||||
input: MollieAmountInput & { readonly configuredRequirement: MollieCheckoutPaymentMethodRequirement }
|
||||
): MollieCheckoutPaymentMethodRequirement {
|
||||
if (input.configuredRequirement === "card" || requiresMollieCardForAmount(input)) return "card";
|
||||
return input.configuredRequirement;
|
||||
}
|
||||
|
||||
export function defaultMollieFirstPaymentMethod(
|
||||
requirement: MollieCheckoutPaymentMethodRequirement,
|
||||
sepaFirstPaymentMethods: readonly MollieSepaFirstPaymentMethod[]
|
||||
): MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null {
|
||||
if (requirement === "card") return "creditcard";
|
||||
if (requirement === "sepa") return sepaFirstPaymentMethods;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveMollieRecurringPaymentMethod(input: MollieAmountInput & { readonly billingCadence?: string }): MolliePaymentMethodId | null {
|
||||
if (requiresMollieCardForAmount(input)) return "creditcard";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function selectMollieRecurringMandate(
|
||||
input: MollieAmountInput & { readonly mandates: readonly PaymentGatewayMandate[] }
|
||||
): PaymentGatewayMandate | null {
|
||||
const cardRequired = requiresMollieCardForAmount(input);
|
||||
const eligible = input.mandates.filter(
|
||||
(mandate) => mandate.status === "valid" && (cardRequired ? mandate.method === "creditcard" : mandate.method === "creditcard" || mandate.method === "directdebit")
|
||||
);
|
||||
return eligible.reduce<PaymentGatewayMandate | null>((latest, candidate) => {
|
||||
if (!latest) return candidate;
|
||||
const latestCreatedAt = latest.createdAt ? Date.parse(latest.createdAt) : Number.NEGATIVE_INFINITY;
|
||||
const candidateCreatedAt = candidate.createdAt ? Date.parse(candidate.createdAt) : Number.NEGATIVE_INFINITY;
|
||||
return candidateCreatedAt > latestCreatedAt ? candidate : latest;
|
||||
}, null);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ function jsonResponse(body: unknown, status = 200): Response {
|
||||
function molliePayment(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "tr_123",
|
||||
customerId: null,
|
||||
status: "open",
|
||||
amount: { currency: "EUR", value: "49.00" },
|
||||
amountRefunded: { currency: "EUR", value: "0.00" },
|
||||
@@ -31,10 +32,14 @@ function molliePayment(overrides: Record<string, unknown> = {}) {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
paymentExternalId: "payment_1",
|
||||
mollieCustomerId: null,
|
||||
lagoCustomerId: null,
|
||||
lagoSubscriptionId: null,
|
||||
planCode: null,
|
||||
seatQuantity: null,
|
||||
trialEndsAt: null,
|
||||
changeEffectiveAt: null,
|
||||
changeEffectiveAtDate: null,
|
||||
},
|
||||
_links: {
|
||||
checkout: { href: "https://www.mollie.com/checkout/select-method/tr_123" },
|
||||
@@ -43,8 +48,178 @@ function molliePayment(overrides: Record<string, unknown> = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function mollieCustomer(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "cst_123",
|
||||
name: "Ada Lovelace",
|
||||
email: "ada@example.test",
|
||||
locale: "de_DE",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
},
|
||||
createdAt: "2026-07-15T08:00:00+00:00",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("MolliePaymentGateway", () => {
|
||||
it("creates checkout payments without HiveGrid domain data in the Mollie payload", async () => {
|
||||
it("creates Mollie customers with PII only in the designated customer fields", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(mollieCustomer()));
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(
|
||||
gateway.createCustomer({
|
||||
tenantId: " tenant_1 ",
|
||||
name: " Ada Lovelace ",
|
||||
email: " ada@example.test ",
|
||||
locale: " de_DE ",
|
||||
})
|
||||
).resolves.toEqual({
|
||||
provider: "mollie",
|
||||
providerCustomerId: "cst_123",
|
||||
tenantId: "tenant_1",
|
||||
name: "Ada Lovelace",
|
||||
email: "ada@example.test",
|
||||
locale: "de_DE",
|
||||
createdAt: "2026-07-15T08:00:00+00:00",
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledWith("https://api.mollie.com/v2/customers", expect.objectContaining({ method: "POST" }));
|
||||
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
|
||||
expect(request).toEqual({
|
||||
name: "Ada Lovelace",
|
||||
email: "ada@example.test",
|
||||
locale: "de_DE",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(request.metadata)).not.toContain("Ada");
|
||||
expect(JSON.stringify(request.metadata)).not.toContain("example.test");
|
||||
});
|
||||
|
||||
it("forwards deterministic idempotency keys on customer and payment POST requests", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValueOnce(jsonResponse(mollieCustomer())).mockResolvedValueOnce(jsonResponse(molliePayment()));
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await gateway.createCustomer({
|
||||
tenantId: "tenant_1",
|
||||
name: "Ada Lovelace",
|
||||
email: "ada@example.test",
|
||||
idempotencyKey: "hivegrid-customer-acquisition-1",
|
||||
});
|
||||
await gateway.createPayment({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
amountCents: 4_900,
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
idempotencyKey: "hivegrid-payment-acquisition-1",
|
||||
});
|
||||
|
||||
expect(fetchImpl.mock.calls[0]?.[1]?.headers).toEqual(expect.objectContaining({ "idempotency-key": "hivegrid-customer-acquisition-1" }));
|
||||
expect(fetchImpl.mock.calls[1]?.[1]?.headers).toEqual(expect.objectContaining({ "idempotency-key": "hivegrid-payment-acquisition-1" }));
|
||||
});
|
||||
|
||||
it("recovers a customer payment by its stable external acquisition id", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
_embedded: {
|
||||
payments: [
|
||||
molliePayment({ id: "tr_other", metadata: { tenantId: "tenant_1", paymentExternalId: "other" } }),
|
||||
molliePayment({
|
||||
id: "tr_recovered",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
paymentExternalId: "acquisition_1",
|
||||
productAcquisitionId: "acquisition_1",
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await expect(gateway.findCustomerPaymentByExternalId(" cst_123 ", " acquisition_1 ")).resolves.toMatchObject({
|
||||
providerPaymentId: "tr_recovered",
|
||||
externalId: "acquisition_1",
|
||||
});
|
||||
expect(fetchImpl).toHaveBeenCalledWith(
|
||||
"https://api.mollie.com/v2/customers/cst_123/payments?limit=250&sort=desc",
|
||||
expect.objectContaining({ method: "GET" })
|
||||
);
|
||||
});
|
||||
|
||||
it("exhausts Mollie customer-payment pagination before proving an attempt absent", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
_embedded: {
|
||||
payments: [molliePayment({ id: "tr_other", metadata: { tenantId: "tenant_1", paymentExternalId: "other" } })],
|
||||
},
|
||||
_links: {
|
||||
next: { href: "https://api.mollie.com/v2/customers/cst_123/payments?limit=250&from=tr_other" },
|
||||
},
|
||||
})
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
_embedded: {
|
||||
payments: [
|
||||
molliePayment({
|
||||
id: "tr_recovered",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
paymentExternalId: "acquisition_1:attempt:2",
|
||||
productAcquisitionId: "acquisition_1",
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
_links: { next: null },
|
||||
})
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await expect(gateway.findCustomerPaymentByExternalIdExhaustive("cst_123", "acquisition_1:attempt:2")).resolves.toMatchObject({
|
||||
providerPaymentId: "tr_recovered",
|
||||
});
|
||||
expect(fetchImpl.mock.calls.map(([url]) => url)).toEqual([
|
||||
"https://api.mollie.com/v2/customers/cst_123/payments?limit=250&sort=desc",
|
||||
"https://api.mollie.com/v2/customers/cst_123/payments?limit=250&from=tr_other",
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails closed when exhaustive payment lookup receives an off-collection next link", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
_embedded: { payments: [] },
|
||||
_links: { next: { href: "https://attacker.example/v2/customers/cst_123/payments?from=tr_1" } },
|
||||
})
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await expect(gateway.findCustomerPaymentByExternalIdExhaustive("cst_123", "acquisition_1")).rejects.toMatchObject({ code: "RESPONSE_INVALID" });
|
||||
expect(fetchImpl).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("rejects malformed idempotency keys before sending a POST request", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>();
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await expect(
|
||||
gateway.createCustomer({ tenantId: "tenant_1", name: "Ada", email: "ada@example.test", idempotencyKey: "contains whitespace" })
|
||||
).rejects.toMatchObject({ code: "CONFIG_INVALID" });
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps omitted sequence types backwards-compatible as oneoff payments", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment()));
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
@@ -93,6 +268,7 @@ describe("MolliePaymentGateway", () => {
|
||||
description: "Invoice invoice_1",
|
||||
redirectUrl: "https://app.hivegrid.de/admin/billing/return?invoice=invoice_1",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
sequenceType: "oneoff",
|
||||
profileId: "pfl_123",
|
||||
customerId: "cst_123",
|
||||
metadata: {
|
||||
@@ -106,12 +282,519 @@ describe("MolliePaymentGateway", () => {
|
||||
expect(JSON.stringify(request)).not.toContain("billing@example.test");
|
||||
});
|
||||
|
||||
it("creates zero-value first payments and preserves technical trial metadata", async () => {
|
||||
const trialEndsAt = "2026-08-15T10:30:00.000Z";
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse(
|
||||
molliePayment({
|
||||
customerId: " cst_response ",
|
||||
amount: { currency: "EUR", value: "0.00" },
|
||||
amountRemaining: { currency: "EUR", value: "0.00" },
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
paymentExternalId: "payment_1",
|
||||
mollieCustomerId: "cst_metadata",
|
||||
trialEndsAt,
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
paymentExternalId: "payment_1",
|
||||
amountCents: 0,
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
mollieCustomerId: " cst_input ",
|
||||
sequenceType: "first",
|
||||
trialEndsAt: "2026-08-15T12:30:00+02:00",
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
amountCents: 0,
|
||||
metadata: {
|
||||
mollieCustomerId: "cst_response",
|
||||
trialEndsAt,
|
||||
},
|
||||
});
|
||||
|
||||
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
|
||||
expect(request).toMatchObject({
|
||||
amount: { currency: "EUR", value: "0.00" },
|
||||
customerId: "cst_input",
|
||||
sequenceType: "first",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
paymentExternalId: "payment_1",
|
||||
mollieCustomerId: "cst_input",
|
||||
trialEndsAt,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("restricts an annual first payment to methods that establish a SEPA mandate", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment({ customerId: "cst_123" })));
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl,
|
||||
});
|
||||
const methods = ["bancontact", "belfius", "eps", "ideal", "kbc", "mybank", "paybybank"] as const;
|
||||
|
||||
await gateway.createPayment({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_annual_1",
|
||||
amountCents: 45_422,
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
mollieCustomerId: "cst_123",
|
||||
sequenceType: "first",
|
||||
method: methods,
|
||||
});
|
||||
|
||||
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
|
||||
expect(request).toMatchObject({
|
||||
customerId: "cst_123",
|
||||
sequenceType: "first",
|
||||
method: methods,
|
||||
});
|
||||
});
|
||||
|
||||
it("loads enabled methods for the exact first-payment context", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
_embedded: {
|
||||
methods: [
|
||||
{ id: "creditcard", description: " Kreditkarte " },
|
||||
{ id: "paypal", description: "PayPal" },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
profileId: "pfl_123",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(
|
||||
gateway.listPaymentMethods({
|
||||
amountCents: 17_731,
|
||||
currency: "eur",
|
||||
sequenceType: "first",
|
||||
locale: "de_DE",
|
||||
})
|
||||
).resolves.toEqual([
|
||||
{ provider: "mollie", id: "creditcard", description: "Kreditkarte" },
|
||||
{ provider: "mollie", id: "paypal", description: "PayPal" },
|
||||
]);
|
||||
expect(fetchImpl).toHaveBeenCalledWith(
|
||||
"https://api.mollie.com/v2/methods?sequenceType=first&locale=de_DE&amount%5Bvalue%5D=177.31&amount%5Bcurrency%5D=EUR&profileId=pfl_123",
|
||||
expect.objectContaining({ method: "GET" })
|
||||
);
|
||||
});
|
||||
|
||||
it("loads and validates customer mandates without exposing payment details", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
_embedded: {
|
||||
mandates: [
|
||||
{ id: "mdt_card", status: "valid", method: "creditcard", createdAt: "2026-08-02T12:30:00+02:00" },
|
||||
{ id: "mdt_sepa", status: "invalid", method: "directdebit", createdAt: null },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await expect(gateway.listCustomerMandates(" cst_123 ")).resolves.toEqual([
|
||||
{
|
||||
provider: "mollie",
|
||||
providerMandateId: "mdt_card",
|
||||
status: "valid",
|
||||
method: "creditcard",
|
||||
createdAt: "2026-08-02T10:30:00.000Z",
|
||||
},
|
||||
{ provider: "mollie", providerMandateId: "mdt_sepa", status: "invalid", method: "directdebit", createdAt: null },
|
||||
]);
|
||||
expect(fetchImpl).toHaveBeenCalledWith(
|
||||
"https://api.mollie.com/v2/customers/cst_123/mandates?limit=250",
|
||||
expect.objectContaining({ method: "GET" })
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a zero-value first-payment amount so Mollie can filter mandate methods safely", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
_embedded: {
|
||||
methods: [{ id: "creditcard", description: "Credit card" }],
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await gateway.listPaymentMethods({
|
||||
amountCents: 0,
|
||||
currency: "EUR",
|
||||
sequenceType: "first",
|
||||
locale: "en_GB",
|
||||
});
|
||||
|
||||
expect(String(fetchImpl.mock.calls[0]?.[0])).toContain("amount%5Bvalue%5D=0.00");
|
||||
expect(String(fetchImpl.mock.calls[0]?.[0])).toContain("amount%5Bcurrency%5D=EUR");
|
||||
});
|
||||
|
||||
it("omits an unsupported checkout locale so Mollie can use browser detection", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse({ _embedded: { methods: [] } }));
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await gateway.listPaymentMethods({ currency: "EUR", sequenceType: "first", locale: null });
|
||||
|
||||
expect(String(fetchImpl.mock.calls[0]?.[0])).toBe("https://api.mollie.com/v2/methods?sequenceType=first");
|
||||
});
|
||||
|
||||
it("passes a selected method and locale into the hosted checkout", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment({ customerId: "cst_123" })));
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await gateway.createPayment({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
amountCents: 4_900,
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
mollieCustomerId: "cst_123",
|
||||
sequenceType: "first",
|
||||
method: "creditcard",
|
||||
locale: "de_DE",
|
||||
});
|
||||
|
||||
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
|
||||
expect(request).toMatchObject({
|
||||
sequenceType: "first",
|
||||
method: "creditcard",
|
||||
locale: "de_DE",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects ambiguous method responses and unsupported method input", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
_embedded: {
|
||||
methods: [
|
||||
{ id: "paypal", description: "PayPal" },
|
||||
{ id: "paypal", description: "PayPal duplicate" },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await expect(gateway.listPaymentMethods({ currency: "EUR", sequenceType: "first", locale: "de_DE" })).rejects.toMatchObject({ code: "RESPONSE_INVALID" });
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
amountCents: 4_900,
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
mollieCustomerId: "cst_123",
|
||||
sequenceType: "first",
|
||||
method: "unsupported" as never,
|
||||
})
|
||||
).rejects.toMatchObject({ code: "CONFIG_INVALID", message: "Payment method is invalid." });
|
||||
});
|
||||
|
||||
it("falls back to technical metadata when a Mollie payment omits customerId", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse(
|
||||
molliePayment({
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
mollieCustomerId: "cst_metadata",
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(gateway.getPayment("tr_123")).resolves.toMatchObject({
|
||||
metadata: {
|
||||
mollieCustomerId: "cst_metadata",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("maps a paid Mollie response with omitted expiresAt to the terminal null contract", async () => {
|
||||
const { expiresAt: _omittedExpiresAt, ...paidPayment } = molliePayment({
|
||||
status: "paid",
|
||||
paidAt: "2026-07-04T12:00:00+00:00",
|
||||
});
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(paidPayment));
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await expect(gateway.getPayment("tr_123")).resolves.toMatchObject({
|
||||
status: "paid",
|
||||
paidAt: "2026-07-04T12:00:00+00:00",
|
||||
expiresAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips deferred change metadata without putting PII into metadata", async () => {
|
||||
const changeEffectiveAtDate = "2026-09-01T00:00:00.000Z";
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse(
|
||||
molliePayment({
|
||||
customerId: "cst_123",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
mollieCustomerId: "cst_123",
|
||||
lagoPlanCode: "hg_price_business_yearly_123",
|
||||
subscriptionPriceId: "price_business_yearly",
|
||||
changeEffectiveAt: "period_end",
|
||||
changeEffectiveAtDate: "2026-09-01T02:00:00+02:00",
|
||||
billingFlow: "self_service_change",
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
amountCents: 4900,
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
mollieCustomerId: "cst_123",
|
||||
mandateId: "mdt_card",
|
||||
method: "creditcard",
|
||||
lagoPlanCode: "hg_price_business_yearly_123",
|
||||
sequenceType: "recurring",
|
||||
subscriptionPriceId: "price_business_yearly",
|
||||
changeEffectiveAt: "period_end",
|
||||
changeEffectiveAtDate: "2026-09-01T02:00:00+02:00",
|
||||
billingFlow: "self_service_change",
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
metadata: {
|
||||
changeEffectiveAt: "period_end",
|
||||
changeEffectiveAtDate,
|
||||
lagoPlanCode: "hg_price_business_yearly_123",
|
||||
subscriptionPriceId: "price_business_yearly",
|
||||
billingFlow: "self_service_change",
|
||||
},
|
||||
});
|
||||
|
||||
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
|
||||
expect(request).toMatchObject({ sequenceType: "recurring", method: "creditcard", mandateId: "mdt_card" });
|
||||
expect(request.metadata).toMatchObject({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
mollieCustomerId: "cst_123",
|
||||
lagoPlanCode: "hg_price_business_yearly_123",
|
||||
subscriptionPriceId: "price_business_yearly",
|
||||
changeEffectiveAt: "period_end",
|
||||
changeEffectiveAtDate,
|
||||
billingFlow: "self_service_change",
|
||||
});
|
||||
expect(JSON.stringify(request.metadata)).not.toContain("@");
|
||||
});
|
||||
|
||||
it("round-trips product-acquisition identity without treating it as a base-plan flow", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse(
|
||||
molliePayment({
|
||||
customerId: "cst_123",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_portal_1",
|
||||
paymentExternalId: "acq_1",
|
||||
mollieCustomerId: "cst_123",
|
||||
lagoCustomerId: "lago_customer_1",
|
||||
lagoSubscriptionId: "acq_1",
|
||||
subscriptionProductId: "product_portal",
|
||||
subscriptionPriceId: "price_portal_monthly",
|
||||
productAcquisitionId: "acq_1",
|
||||
productKind: "recurring_add_on",
|
||||
productScopeKey: "tenant",
|
||||
billingFlow: "product_acquisition",
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_portal_1",
|
||||
paymentExternalId: "acq_1",
|
||||
amountCents: 1999,
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
mollieCustomerId: "cst_123",
|
||||
lagoCustomerId: "lago_customer_1",
|
||||
lagoSubscriptionId: "acq_1",
|
||||
subscriptionProductId: "product_portal",
|
||||
subscriptionPriceId: "price_portal_monthly",
|
||||
productAcquisitionId: "acq_1",
|
||||
productKind: "recurring_add_on",
|
||||
productScopeKey: "tenant",
|
||||
billingFlow: "product_acquisition",
|
||||
sequenceType: "first",
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
metadata: {
|
||||
productAcquisitionId: "acq_1",
|
||||
productKind: "recurring_add_on",
|
||||
productScopeKey: "tenant",
|
||||
subscriptionProductId: "product_portal",
|
||||
billingFlow: "product_acquisition",
|
||||
},
|
||||
});
|
||||
|
||||
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
|
||||
expect(request.metadata).toMatchObject({
|
||||
productAcquisitionId: "acq_1",
|
||||
productKind: "recurring_add_on",
|
||||
productScopeKey: "tenant",
|
||||
subscriptionProductId: "product_portal",
|
||||
billingFlow: "product_acquisition",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects incomplete or non-payable product-acquisition metadata", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>();
|
||||
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
|
||||
const base = {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
amountCents: 1999,
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
billingFlow: "product_acquisition" as const,
|
||||
};
|
||||
|
||||
await expect(gateway.createPayment(base)).rejects.toMatchObject({ code: "CONFIG_INVALID", message: "Product acquisition metadata is incomplete." });
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
...base,
|
||||
productAcquisitionId: "acq_1",
|
||||
productKind: "contract_override",
|
||||
productScopeKey: "tenant",
|
||||
subscriptionProductId: "product_contract",
|
||||
subscriptionPriceId: "price_contract",
|
||||
})
|
||||
).rejects.toMatchObject({ code: "CONFIG_INVALID", message: "Product acquisition kind is not payable." });
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("enforces amount and customer requirements for payment sequences", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment()));
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl,
|
||||
});
|
||||
const baseInput = {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
} as const;
|
||||
|
||||
await expect(gateway.createPayment({ ...baseInput, amountCents: 0 })).rejects.toMatchObject({ code: "CONFIG_INVALID" });
|
||||
await expect(gateway.createPayment({ ...baseInput, amountCents: 0, sequenceType: "first" })).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
message: "Mollie customer id is required for first and recurring payments.",
|
||||
});
|
||||
await expect(gateway.createPayment({ ...baseInput, amountCents: 100, sequenceType: "recurring" })).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
message: "Mollie customer id is required for first and recurring payments.",
|
||||
});
|
||||
await expect(
|
||||
gateway.createPayment({ ...baseInput, amountCents: 100, sequenceType: "recurring", mollieCustomerId: "cst_123", method: "creditcard" })
|
||||
).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
message: "Mollie mandate id is required for recurring payments.",
|
||||
});
|
||||
await expect(gateway.createPayment({ ...baseInput, amountCents: -1, sequenceType: "first", mollieCustomerId: "cst_123" })).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
});
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
...baseInput,
|
||||
amountCents: 100,
|
||||
sequenceType: "first",
|
||||
mollieCustomerId: "cst_123",
|
||||
method: "directdebit",
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
message: "Direct debit is valid only for recurring collection payments.",
|
||||
});
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
...baseInput,
|
||||
amountCents: 0,
|
||||
sequenceType: "first",
|
||||
mollieCustomerId: "cst_123",
|
||||
trialEndsAt: "15.08.2026",
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
message: "Trial end must be an ISO timestamp with timezone.",
|
||||
});
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
...baseInput,
|
||||
amountCents: 100,
|
||||
changeEffectiveAt: "period_end",
|
||||
changeEffectiveAtDate: "next billing period",
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: "CONFIG_INVALID",
|
||||
message: "Change effective date must be an ISO timestamp with timezone.",
|
||||
});
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("verifies classic Mollie webhooks by parsing the id and refetching payment status", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse(
|
||||
molliePayment({
|
||||
status: "paid",
|
||||
paidAt: "2026-07-04T12:00:00+00:00",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
changeEffectiveAt: "period_end",
|
||||
changeEffectiveAtDate: "2026-08-01T02:00:00+02:00",
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
@@ -126,6 +809,10 @@ describe("MolliePaymentGateway", () => {
|
||||
providerPaymentId: "tr_123",
|
||||
status: "paid",
|
||||
paidAt: "2026-07-04T12:00:00+00:00",
|
||||
metadata: {
|
||||
changeEffectiveAt: "period_end",
|
||||
changeEffectiveAtDate: "2026-08-01T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://api.mollie.com/v2/payments/tr_123");
|
||||
});
|
||||
|
||||
@@ -1,9 +1,35 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { PaymentGateway, PaymentGatewayCreatePaymentInput, PaymentGatewayPayment, PaymentGatewayPaymentStatus } from "./types.js";
|
||||
import { readBillingJsonResponse } from "./provider-http.js";
|
||||
import {
|
||||
mollieLocales,
|
||||
mollieMandatePaymentMethods,
|
||||
molliePaymentMethodIds,
|
||||
mollieSepaFirstPaymentMethods,
|
||||
paymentBillingFlows,
|
||||
subscriptionProductKinds,
|
||||
} from "./types.js";
|
||||
import type {
|
||||
ExhaustiveCustomerPaymentGateway,
|
||||
MollieLocale,
|
||||
MolliePaymentMethodId,
|
||||
MollieSepaFirstPaymentMethod,
|
||||
PaymentGateway,
|
||||
PaymentGatewayCreateCustomerInput,
|
||||
PaymentGatewayCreatePaymentInput,
|
||||
PaymentGatewayCustomer,
|
||||
PaymentGatewayListMethodsInput,
|
||||
PaymentGatewayMandate,
|
||||
PaymentGatewayPayment,
|
||||
PaymentGatewayPaymentMethod,
|
||||
PaymentGatewayPaymentStatus,
|
||||
PaymentBillingFlow,
|
||||
SubscriptionProductKind,
|
||||
} from "./types.js";
|
||||
|
||||
const DEFAULT_MOLLIE_API_URL = "https://api.mollie.com";
|
||||
const DEFAULT_MOLLIE_TIMEOUT_MS = 10_000;
|
||||
const MAX_EXHAUSTIVE_CUSTOMER_PAYMENT_PAGES = 1_000;
|
||||
|
||||
export type MolliePaymentGatewayConfig = {
|
||||
apiKey: string;
|
||||
@@ -39,16 +65,34 @@ const metadataSchema = z
|
||||
tenantId: z.string().nullable().optional(),
|
||||
invoiceExternalId: z.string().nullable().optional(),
|
||||
paymentExternalId: z.string().nullable().optional(),
|
||||
mollieCustomerId: z.string().nullable().optional(),
|
||||
lagoCustomerId: z.string().nullable().optional(),
|
||||
lagoSubscriptionId: z.string().nullable().optional(),
|
||||
lagoProviderSubscriptionId: z.string().nullable().optional(),
|
||||
lagoPlanCode: z.string().nullable().optional(),
|
||||
planCode: z.string().nullable().optional(),
|
||||
subscriptionPriceId: z.string().nullable().optional(),
|
||||
seatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
officeSeatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
fieldSeatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
billingCadence: z.string().nullable().optional(),
|
||||
commitmentEndsAt: z.string().nullable().optional(),
|
||||
storageAddOnCodes: z.array(z.string()).nullable().optional(),
|
||||
trialEndsAt: z.string().nullable().optional(),
|
||||
changeEffectiveAt: z.string().nullable().optional(),
|
||||
changeEffectiveAtDate: z.string().nullable().optional(),
|
||||
billingFlow: z.string().nullable().optional(),
|
||||
productAcquisitionId: z.string().nullable().optional(),
|
||||
productKind: z.string().nullable().optional(),
|
||||
productScopeKey: z.string().nullable().optional(),
|
||||
subscriptionProductId: z.string().nullable().optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional();
|
||||
|
||||
const molliePaymentSchema = z.object({
|
||||
id: z.string(),
|
||||
customerId: z.string().nullable().optional(),
|
||||
status: z.string().nullable().optional(),
|
||||
amount: amountSchema.nullable().optional(),
|
||||
amountRefunded: amountSchema.nullable().optional(),
|
||||
@@ -69,9 +113,63 @@ const molliePaymentSchema = z.object({
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type MolliePaymentResponse = z.infer<typeof molliePaymentSchema>;
|
||||
const mollieCustomerSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(),
|
||||
locale: z.string().nullable().optional(),
|
||||
metadata: z
|
||||
.object({
|
||||
tenantId: z.string().nullable().optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
createdAt: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): PaymentGateway {
|
||||
const mollieCustomerPaymentsSchema = z.object({
|
||||
_embedded: z.object({ payments: z.array(molliePaymentSchema) }),
|
||||
_links: z
|
||||
.object({
|
||||
next: z
|
||||
.object({
|
||||
href: z.string(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const mollieMethodSchema = z.object({
|
||||
id: z.enum(molliePaymentMethodIds),
|
||||
description: z.string(),
|
||||
});
|
||||
|
||||
const mollieMethodsSchema = z.object({
|
||||
_embedded: z.object({
|
||||
methods: z.array(mollieMethodSchema),
|
||||
}),
|
||||
});
|
||||
|
||||
const mollieMandateSchema = z.object({
|
||||
id: z.string(),
|
||||
status: z.enum(["valid", "pending", "invalid"]),
|
||||
method: z.enum(mollieMandatePaymentMethods),
|
||||
createdAt: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
const mollieMandatesSchema = z.object({
|
||||
_embedded: z.object({
|
||||
mandates: z.array(mollieMandateSchema),
|
||||
}),
|
||||
});
|
||||
|
||||
type MolliePaymentResponse = z.infer<typeof molliePaymentSchema>;
|
||||
type MollieCustomerResponse = z.infer<typeof mollieCustomerSchema>;
|
||||
|
||||
export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): ExhaustiveCustomerPaymentGateway {
|
||||
return new MolliePaymentGateway(config);
|
||||
}
|
||||
|
||||
@@ -104,7 +202,10 @@ export function parseMollieWebhookEvent(input: URLSearchParams | FormData | Reco
|
||||
return { providerPaymentId: id };
|
||||
}
|
||||
|
||||
export async function resolveMollieWebhookPayment(gateway: PaymentGateway, input: URLSearchParams | FormData | Record<string, unknown>): Promise<PaymentGatewayPayment> {
|
||||
export async function resolveMollieWebhookPayment(
|
||||
gateway: PaymentGateway,
|
||||
input: URLSearchParams | FormData | Record<string, unknown>
|
||||
): Promise<PaymentGatewayPayment> {
|
||||
const event = parseMollieWebhookEvent(input);
|
||||
const payment = await gateway.getPayment(event.providerPaymentId);
|
||||
if (!payment) {
|
||||
@@ -113,7 +214,7 @@ export async function resolveMollieWebhookPayment(gateway: PaymentGateway, input
|
||||
return payment;
|
||||
}
|
||||
|
||||
class MolliePaymentGateway implements PaymentGateway {
|
||||
class MolliePaymentGateway implements ExhaustiveCustomerPaymentGateway {
|
||||
private readonly apiUrl: string;
|
||||
private readonly apiKey: string;
|
||||
private readonly profileId: string | null;
|
||||
@@ -131,34 +232,167 @@ class MolliePaymentGateway implements PaymentGateway {
|
||||
this.fetchImpl = config.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
async createCustomer(input: PaymentGatewayCreateCustomerInput): Promise<PaymentGatewayCustomer> {
|
||||
const normalizedInput = validateCreateCustomerInput(input);
|
||||
const response = await this.request("/customers", {
|
||||
method: "POST",
|
||||
idempotencyKey: normalizeIdempotencyKey(input.idempotencyKey),
|
||||
body: {
|
||||
name: normalizedInput.name,
|
||||
email: normalizedInput.email,
|
||||
...(normalizedInput.locale ? { locale: normalizedInput.locale } : {}),
|
||||
metadata: {
|
||||
tenantId: normalizedInput.tenantId,
|
||||
},
|
||||
},
|
||||
});
|
||||
return toCustomer(parseMollieCustomerResponse(response));
|
||||
}
|
||||
|
||||
async createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment> {
|
||||
validateCreatePaymentInput(input);
|
||||
const normalizedInput = validateCreatePaymentInput(input);
|
||||
const response = await this.request("/payments", {
|
||||
method: "POST",
|
||||
idempotencyKey: normalizeIdempotencyKey(input.idempotencyKey),
|
||||
body: {
|
||||
amount: {
|
||||
currency: input.currency.toUpperCase(),
|
||||
value: centsToMollieValue(input.amountCents),
|
||||
},
|
||||
description: input.description?.trim() || `Invoice ${input.invoiceExternalId}`,
|
||||
redirectUrl: input.redirectUrl,
|
||||
...(input.redirectUrl ? { redirectUrl: input.redirectUrl } : {}),
|
||||
webhookUrl: input.webhookUrl,
|
||||
sequenceType: normalizedInput.sequenceType,
|
||||
...(normalizedInput.method ? { method: normalizedInput.method } : {}),
|
||||
...(normalizedInput.mandateId ? { mandateId: normalizedInput.mandateId } : {}),
|
||||
...(normalizedInput.locale ? { locale: normalizedInput.locale } : {}),
|
||||
...(this.profileId ? { profileId: this.profileId } : {}),
|
||||
...(input.mollieCustomerId ? { customerId: input.mollieCustomerId } : {}),
|
||||
...(normalizedInput.mollieCustomerId ? { customerId: normalizedInput.mollieCustomerId } : {}),
|
||||
metadata: {
|
||||
tenantId: input.tenantId,
|
||||
invoiceExternalId: input.invoiceExternalId,
|
||||
...(input.paymentExternalId ? { paymentExternalId: input.paymentExternalId } : {}),
|
||||
...(normalizedInput.mollieCustomerId ? { mollieCustomerId: normalizedInput.mollieCustomerId } : {}),
|
||||
...(input.lagoCustomerId ? { lagoCustomerId: input.lagoCustomerId } : {}),
|
||||
...(input.lagoSubscriptionId ? { lagoSubscriptionId: input.lagoSubscriptionId } : {}),
|
||||
...(normalizedInput.lagoProviderSubscriptionId ? { lagoProviderSubscriptionId: normalizedInput.lagoProviderSubscriptionId } : {}),
|
||||
...(normalizedInput.lagoPlanCode ? { lagoPlanCode: normalizedInput.lagoPlanCode } : {}),
|
||||
...(input.planCode ? { planCode: input.planCode } : {}),
|
||||
...(input.subscriptionPriceId ? { subscriptionPriceId: input.subscriptionPriceId } : {}),
|
||||
...(input.seatQuantity ? { seatQuantity: input.seatQuantity } : {}),
|
||||
...(input.officeSeatQuantity !== null && input.officeSeatQuantity !== undefined ? { officeSeatQuantity: input.officeSeatQuantity } : {}),
|
||||
...(input.fieldSeatQuantity !== null && input.fieldSeatQuantity !== undefined ? { fieldSeatQuantity: input.fieldSeatQuantity } : {}),
|
||||
...(input.billingCadence ? { billingCadence: input.billingCadence } : {}),
|
||||
...(normalizedInput.commitmentEndsAt ? { commitmentEndsAt: normalizedInput.commitmentEndsAt } : {}),
|
||||
...(normalizedInput.storageAddOnCodes.length > 0 ? { storageAddOnCodes: normalizedInput.storageAddOnCodes } : {}),
|
||||
...(normalizedInput.trialEndsAt ? { trialEndsAt: normalizedInput.trialEndsAt } : {}),
|
||||
...(normalizedInput.changeEffectiveAt ? { changeEffectiveAt: normalizedInput.changeEffectiveAt } : {}),
|
||||
...(normalizedInput.changeEffectiveAtDate ? { changeEffectiveAtDate: normalizedInput.changeEffectiveAtDate } : {}),
|
||||
...(normalizedInput.billingFlow ? { billingFlow: normalizedInput.billingFlow } : {}),
|
||||
...(normalizedInput.productAcquisitionId ? { productAcquisitionId: normalizedInput.productAcquisitionId } : {}),
|
||||
...(normalizedInput.productKind ? { productKind: normalizedInput.productKind } : {}),
|
||||
...(normalizedInput.productScopeKey ? { productScopeKey: normalizedInput.productScopeKey } : {}),
|
||||
...(normalizedInput.subscriptionProductId ? { subscriptionProductId: normalizedInput.subscriptionProductId } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
return toPayment(parseMollieResponse(response));
|
||||
}
|
||||
|
||||
async listPaymentMethods(input: PaymentGatewayListMethodsInput): Promise<PaymentGatewayPaymentMethod[]> {
|
||||
const normalized = validateListPaymentMethodsInput(input);
|
||||
const query = new URLSearchParams({ sequenceType: normalized.sequenceType });
|
||||
if (normalized.locale) query.set("locale", normalized.locale);
|
||||
if (normalized.amountCents !== null) {
|
||||
query.set("amount[value]", centsToMollieValue(normalized.amountCents));
|
||||
query.set("amount[currency]", normalized.currency);
|
||||
}
|
||||
if (this.profileId) query.set("profileId", this.profileId);
|
||||
|
||||
const response = await this.request(`/methods?${query.toString()}`, { method: "GET" });
|
||||
const parsed = mollieMethodsSchema.safeParse(response);
|
||||
if (!parsed.success) {
|
||||
throw new MolliePaymentGatewayError("Mollie payment methods response shape is invalid.", "RESPONSE_INVALID");
|
||||
}
|
||||
const ids = parsed.data._embedded.methods.map((method) => method.id);
|
||||
if (new Set(ids).size !== ids.length || parsed.data._embedded.methods.some((method) => !method.description.trim())) {
|
||||
throw new MolliePaymentGatewayError("Mollie payment methods response is ambiguous.", "RESPONSE_INVALID");
|
||||
}
|
||||
return parsed.data._embedded.methods.map((method) => ({
|
||||
provider: "mollie",
|
||||
id: method.id,
|
||||
description: method.description.trim(),
|
||||
}));
|
||||
}
|
||||
|
||||
async listCustomerMandates(mollieCustomerId: string): Promise<PaymentGatewayMandate[]> {
|
||||
const customerId = mollieCustomerId.trim();
|
||||
if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID");
|
||||
const response = await this.request(`/customers/${encodeURIComponent(customerId)}/mandates?limit=250`, { method: "GET" });
|
||||
const parsed = mollieMandatesSchema.safeParse(response);
|
||||
if (!parsed.success) {
|
||||
throw new MolliePaymentGatewayError("Mollie mandates response shape is invalid.", "RESPONSE_INVALID");
|
||||
}
|
||||
const ids = parsed.data._embedded.mandates.map((mandate) => mandate.id);
|
||||
if (new Set(ids).size !== ids.length || ids.some((id) => !/^mdt_.+/u.test(id))) {
|
||||
throw new MolliePaymentGatewayError("Mollie mandates response is ambiguous.", "RESPONSE_INVALID");
|
||||
}
|
||||
return parsed.data._embedded.mandates.map((mandate) => ({
|
||||
provider: "mollie",
|
||||
providerMandateId: mandate.id,
|
||||
status: mandate.status,
|
||||
method: mandate.method,
|
||||
createdAt: normalizeProviderTimestamp(mandate.createdAt),
|
||||
}));
|
||||
}
|
||||
|
||||
async findCustomerPaymentByExternalId(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null> {
|
||||
const customerId = mollieCustomerId.trim();
|
||||
const externalId = paymentExternalId.trim();
|
||||
if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID");
|
||||
if (!externalId) throw new MolliePaymentGatewayError("Payment external id is required.", "CONFIG_INVALID");
|
||||
const response = await this.request(`/customers/${encodeURIComponent(customerId)}/payments?limit=250&sort=desc`, { method: "GET" });
|
||||
const parsed = mollieCustomerPaymentsSchema.safeParse(response);
|
||||
if (!parsed.success) throw new MolliePaymentGatewayError("Mollie customer payments response shape is invalid.", "RESPONSE_INVALID");
|
||||
const payment = parsed.data._embedded.payments.find((candidate) => {
|
||||
const metadata = candidate.metadata ?? {};
|
||||
return metadata.paymentExternalId === externalId || metadata.productAcquisitionId === externalId;
|
||||
});
|
||||
return payment ? toPayment(payment) : null;
|
||||
}
|
||||
|
||||
async findCustomerPaymentByExternalIdExhaustive(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null> {
|
||||
const customerId = mollieCustomerId.trim();
|
||||
const externalId = paymentExternalId.trim();
|
||||
if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID");
|
||||
if (!externalId) throw new MolliePaymentGatewayError("Payment external id is required.", "CONFIG_INVALID");
|
||||
|
||||
const expectedPathPrefix = `/customers/${encodeURIComponent(customerId)}/payments`;
|
||||
let path = `${expectedPathPrefix}?limit=250&sort=desc`;
|
||||
const visited = new Set<string>();
|
||||
for (let page = 0; page < MAX_EXHAUSTIVE_CUSTOMER_PAYMENT_PAGES; page += 1) {
|
||||
if (visited.has(path)) {
|
||||
throw new MolliePaymentGatewayError("Mollie customer payments pagination looped.", "RESPONSE_INVALID");
|
||||
}
|
||||
visited.add(path);
|
||||
const response = await this.request(path, { method: "GET" });
|
||||
const parsed = mollieCustomerPaymentsSchema.safeParse(response);
|
||||
if (!parsed.success) {
|
||||
throw new MolliePaymentGatewayError("Mollie customer payments response shape is invalid.", "RESPONSE_INVALID");
|
||||
}
|
||||
const payment = parsed.data._embedded.payments.find((candidate) => {
|
||||
const metadata = candidate.metadata ?? {};
|
||||
return metadata.paymentExternalId === externalId || metadata.productAcquisitionId === externalId;
|
||||
});
|
||||
if (payment) return toPayment(payment);
|
||||
|
||||
const nextHref = parsed.data._links?.next?.href;
|
||||
if (!nextHref) return null;
|
||||
path = normalizeMollieCustomerPaymentsNextPath(nextHref, this.apiUrl, expectedPathPrefix);
|
||||
}
|
||||
throw new MolliePaymentGatewayError("Mollie customer payments pagination exceeded its safety bound.", "RESPONSE_INVALID");
|
||||
}
|
||||
|
||||
async getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null> {
|
||||
const id = providerPaymentId.trim();
|
||||
if (!id) {
|
||||
@@ -168,7 +402,10 @@ class MolliePaymentGateway implements PaymentGateway {
|
||||
return response === null ? null : toPayment(parseMollieResponse(response));
|
||||
}
|
||||
|
||||
private async request(path: string, options: { method: "GET" | "POST"; body?: unknown; allowNotFound?: boolean }): Promise<unknown | null> {
|
||||
private async request(
|
||||
path: string,
|
||||
options: { method: "GET" | "POST"; body?: unknown; allowNotFound?: boolean; idempotencyKey?: string | null }
|
||||
): Promise<unknown | null> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||
try {
|
||||
@@ -178,8 +415,10 @@ class MolliePaymentGateway implements PaymentGateway {
|
||||
authorization: `Bearer ${this.apiKey}`,
|
||||
accept: "application/json",
|
||||
...(options.body ? { "content-type": "application/json" } : {}),
|
||||
...(options.method === "POST" && options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {}),
|
||||
},
|
||||
body: options.body ? JSON.stringify(options.body) : undefined,
|
||||
redirect: "error",
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.status === 404 && options.allowNotFound) {
|
||||
@@ -188,7 +427,7 @@ class MolliePaymentGateway implements PaymentGateway {
|
||||
if (!response.ok) {
|
||||
throw new MolliePaymentGatewayError(`Mollie request failed with status ${response.status}.`, "REQUEST_FAILED", response.status);
|
||||
}
|
||||
return await response.json();
|
||||
return await readBillingJsonResponse(response);
|
||||
} catch (error) {
|
||||
if (error instanceof MolliePaymentGatewayError) throw error;
|
||||
throw new MolliePaymentGatewayError("Mollie request failed.", "REQUEST_FAILED");
|
||||
@@ -198,6 +437,21 @@ class MolliePaymentGateway implements PaymentGateway {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeMollieCustomerPaymentsNextPath(href: string, apiUrl: string, expectedPathPrefix: string): string {
|
||||
let next: URL;
|
||||
try {
|
||||
next = new URL(href, `${apiUrl}/v2/`);
|
||||
} catch {
|
||||
throw new MolliePaymentGatewayError("Mollie customer payments next link is invalid.", "RESPONSE_INVALID");
|
||||
}
|
||||
const base = new URL(apiUrl);
|
||||
const expectedPath = `/v2${expectedPathPrefix}`;
|
||||
if (next.origin !== base.origin || next.pathname !== expectedPath) {
|
||||
throw new MolliePaymentGatewayError("Mollie customer payments next link is outside the requested collection.", "RESPONSE_INVALID");
|
||||
}
|
||||
return `${expectedPathPrefix}${next.search}`;
|
||||
}
|
||||
|
||||
function parseMollieResponse(response: unknown): MolliePaymentResponse {
|
||||
const result = molliePaymentSchema.safeParse(response);
|
||||
if (!result.success) {
|
||||
@@ -206,13 +460,33 @@ function parseMollieResponse(response: unknown): MolliePaymentResponse {
|
||||
return result.data;
|
||||
}
|
||||
|
||||
function parseMollieCustomerResponse(response: unknown): MollieCustomerResponse {
|
||||
const result = mollieCustomerSchema.safeParse(response);
|
||||
if (!result.success) {
|
||||
throw new MolliePaymentGatewayError("Mollie customer response shape is invalid.", "RESPONSE_INVALID");
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
function toCustomer(customer: MollieCustomerResponse): PaymentGatewayCustomer {
|
||||
return {
|
||||
provider: "mollie",
|
||||
providerCustomerId: customer.id,
|
||||
tenantId: customer.metadata?.tenantId ?? null,
|
||||
name: customer.name ?? null,
|
||||
email: customer.email ?? null,
|
||||
locale: customer.locale ?? null,
|
||||
createdAt: customer.createdAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function toPayment(payment: MolliePaymentResponse): PaymentGatewayPayment {
|
||||
const metadata = payment.metadata ?? {};
|
||||
return {
|
||||
provider: "mollie",
|
||||
providerPaymentId: payment.id,
|
||||
externalId: metadata.paymentExternalId ?? null,
|
||||
status: normalizePaymentStatus(payment.status, payment.amountRefunded?.value),
|
||||
status: normalizePaymentStatus(payment.status, payment.amountRefunded?.value, payment.amount?.value),
|
||||
amountCents: mollieValueToCents(payment.amount?.value),
|
||||
amountRefundedCents: mollieValueToCents(payment.amountRefunded?.value),
|
||||
amountRemainingCents: mollieValueToCents(payment.amountRemaining?.value),
|
||||
@@ -224,10 +498,27 @@ function toPayment(payment: MolliePaymentResponse): PaymentGatewayPayment {
|
||||
tenantId: metadata.tenantId ?? null,
|
||||
invoiceExternalId: metadata.invoiceExternalId ?? null,
|
||||
paymentExternalId: metadata.paymentExternalId ?? null,
|
||||
mollieCustomerId: normalizeMetadataString(payment.customerId) ?? normalizeMetadataString(metadata.mollieCustomerId),
|
||||
lagoCustomerId: metadata.lagoCustomerId ?? null,
|
||||
lagoSubscriptionId: metadata.lagoSubscriptionId ?? null,
|
||||
lagoProviderSubscriptionId: normalizeMetadataString(metadata.lagoProviderSubscriptionId),
|
||||
lagoPlanCode: normalizeMetadataString(metadata.lagoPlanCode),
|
||||
planCode: metadata.planCode ?? null,
|
||||
subscriptionPriceId: normalizeMetadataString(metadata.subscriptionPriceId),
|
||||
seatQuantity: normalizeMetadataSeatQuantity(metadata.seatQuantity),
|
||||
officeSeatQuantity: normalizeMetadataNonNegativeSeatQuantity(metadata.officeSeatQuantity),
|
||||
fieldSeatQuantity: normalizeMetadataNonNegativeSeatQuantity(metadata.fieldSeatQuantity),
|
||||
billingCadence: normalizeMetadataString(metadata.billingCadence),
|
||||
commitmentEndsAt: normalizeMetadataIsoTimestamp(metadata.commitmentEndsAt),
|
||||
storageAddOnCodes: [...new Set((metadata.storageAddOnCodes ?? []).map((code) => code.trim()).filter(Boolean))],
|
||||
trialEndsAt: normalizeMetadataIsoTimestamp(metadata.trialEndsAt),
|
||||
changeEffectiveAt: normalizeChangeEffectiveAt(metadata.changeEffectiveAt),
|
||||
changeEffectiveAtDate: normalizeMetadataIsoTimestamp(metadata.changeEffectiveAtDate),
|
||||
billingFlow: normalizeBillingFlow(metadata.billingFlow),
|
||||
productAcquisitionId: normalizeMetadataString(metadata.productAcquisitionId),
|
||||
productKind: normalizeProductKind(metadata.productKind),
|
||||
productScopeKey: normalizeMetadataString(metadata.productScopeKey),
|
||||
subscriptionProductId: normalizeMetadataString(metadata.subscriptionProductId),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -244,17 +535,236 @@ function normalizeMetadataSeatQuantity(value: string | number | null | undefined
|
||||
return null;
|
||||
}
|
||||
|
||||
function validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): void {
|
||||
function normalizeMetadataNonNegativeSeatQuantity(value: string | number | null | undefined): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
const normalized = Math.trunc(value);
|
||||
return normalized >= 0 ? normalized : null;
|
||||
}
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const normalized = Number.parseInt(value, 10);
|
||||
return Number.isFinite(normalized) && normalized >= 0 ? normalized : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function validateCreateCustomerInput(input: PaymentGatewayCreateCustomerInput): {
|
||||
tenantId: string;
|
||||
name: string;
|
||||
email: string;
|
||||
locale: string | null;
|
||||
} {
|
||||
const tenantId = input.tenantId.trim();
|
||||
const name = input.name.trim();
|
||||
const email = input.email.trim();
|
||||
const locale = input.locale?.trim() || null;
|
||||
if (!tenantId) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID");
|
||||
if (!name) throw new MolliePaymentGatewayError("Customer name is required.", "CONFIG_INVALID");
|
||||
if (!z.string().email().safeParse(email).success) {
|
||||
throw new MolliePaymentGatewayError("Customer email must be valid.", "CONFIG_INVALID");
|
||||
}
|
||||
return { tenantId, name, email, locale };
|
||||
}
|
||||
|
||||
function validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): {
|
||||
sequenceType: "oneoff" | "first" | "recurring";
|
||||
method: MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null;
|
||||
locale: MollieLocale | null;
|
||||
mollieCustomerId: string | null;
|
||||
mandateId: string | null;
|
||||
trialEndsAt: string | null;
|
||||
commitmentEndsAt: string | null;
|
||||
storageAddOnCodes: readonly string[];
|
||||
changeEffectiveAt: "immediate" | "period_end" | null;
|
||||
changeEffectiveAtDate: string | null;
|
||||
billingFlow: PaymentBillingFlow | null;
|
||||
productAcquisitionId: string | null;
|
||||
productKind: SubscriptionProductKind | null;
|
||||
productScopeKey: string | null;
|
||||
subscriptionProductId: string | null;
|
||||
lagoProviderSubscriptionId: string | null;
|
||||
lagoPlanCode: string | null;
|
||||
} {
|
||||
if (!input.tenantId.trim()) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID");
|
||||
if (!input.invoiceExternalId.trim()) throw new MolliePaymentGatewayError("Invoice reference is required.", "CONFIG_INVALID");
|
||||
if (!Number.isInteger(input.amountCents) || input.amountCents < 1) {
|
||||
throw new MolliePaymentGatewayError("Amount must be a positive cent integer.", "CONFIG_INVALID");
|
||||
const sequenceType = input.sequenceType ?? "oneoff";
|
||||
if (sequenceType !== "oneoff" && sequenceType !== "first" && sequenceType !== "recurring") {
|
||||
throw new MolliePaymentGatewayError("Payment sequence type is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
if (!Number.isInteger(input.amountCents) || input.amountCents < 0 || (input.amountCents === 0 && sequenceType !== "first")) {
|
||||
throw new MolliePaymentGatewayError(
|
||||
sequenceType === "first" ? "Amount must be a non-negative cent integer." : "Amount must be a positive cent integer.",
|
||||
"CONFIG_INVALID"
|
||||
);
|
||||
}
|
||||
if (!/^[A-Za-z]{3}$/u.test(input.currency)) {
|
||||
throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID");
|
||||
}
|
||||
assertHttpUrl(input.redirectUrl, "Redirect URL");
|
||||
const mollieCustomerId = input.mollieCustomerId?.trim() || null;
|
||||
if ((sequenceType === "first" || sequenceType === "recurring") && !mollieCustomerId) {
|
||||
throw new MolliePaymentGatewayError("Mollie customer id is required for first and recurring payments.", "CONFIG_INVALID");
|
||||
}
|
||||
const changeEffectiveAt = input.changeEffectiveAt ?? null;
|
||||
if (changeEffectiveAt !== null && changeEffectiveAt !== "immediate" && changeEffectiveAt !== "period_end") {
|
||||
throw new MolliePaymentGatewayError("Change effective mode is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
if (sequenceType === "recurring") {
|
||||
if (input.redirectUrl) assertHttpUrl(input.redirectUrl, "Redirect URL");
|
||||
} else {
|
||||
if (!input.redirectUrl) {
|
||||
throw new MolliePaymentGatewayError("Redirect URL is required.", "CONFIG_INVALID");
|
||||
}
|
||||
assertHttpUrl(input.redirectUrl, "Redirect URL");
|
||||
}
|
||||
assertHttpUrl(input.webhookUrl, "Webhook URL");
|
||||
const billingFlow = normalizeBillingFlow(input.billingFlow);
|
||||
const productAcquisitionId = normalizeMetadataString(input.productAcquisitionId);
|
||||
const productKind = normalizeProductKind(input.productKind);
|
||||
const productScopeKey = normalizeMetadataString(input.productScopeKey);
|
||||
const subscriptionProductId = normalizeMetadataString(input.subscriptionProductId);
|
||||
const lagoProviderSubscriptionId = normalizeMetadataString(input.lagoProviderSubscriptionId);
|
||||
const lagoPlanCode = normalizeMetadataString(input.lagoPlanCode);
|
||||
const method = normalizePaymentMethod(input.method, sequenceType);
|
||||
const mandateId = normalizeMandateId(input.mandateId, sequenceType);
|
||||
if (sequenceType === "recurring" && !mandateId) {
|
||||
throw new MolliePaymentGatewayError("Mollie mandate id is required for recurring payments.", "CONFIG_INVALID");
|
||||
}
|
||||
const storageAddOnCodes = (input.storageAddOnCodes ?? []).map((code) => normalizeMetadataString(code));
|
||||
if (storageAddOnCodes.some((code) => code === null) || new Set(storageAddOnCodes).size !== storageAddOnCodes.length) {
|
||||
throw new MolliePaymentGatewayError("Storage add-on metadata is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
if (billingFlow === "product_acquisition") {
|
||||
if (!productAcquisitionId || !productKind || !productScopeKey || !subscriptionProductId || !input.subscriptionPriceId?.trim()) {
|
||||
throw new MolliePaymentGatewayError("Product acquisition metadata is incomplete.", "CONFIG_INVALID");
|
||||
}
|
||||
if (productKind === "base_plan" || productKind === "contract_override") {
|
||||
throw new MolliePaymentGatewayError("Product acquisition kind is not payable.", "CONFIG_INVALID");
|
||||
}
|
||||
}
|
||||
return {
|
||||
sequenceType,
|
||||
method,
|
||||
locale: normalizeLocale(input.locale),
|
||||
mollieCustomerId,
|
||||
mandateId,
|
||||
trialEndsAt: normalizeIsoTimestamp(input.trialEndsAt, "Trial end"),
|
||||
commitmentEndsAt: normalizeIsoTimestamp(input.commitmentEndsAt, "Commitment end"),
|
||||
storageAddOnCodes: storageAddOnCodes as string[],
|
||||
changeEffectiveAt,
|
||||
changeEffectiveAtDate: normalizeIsoTimestamp(input.changeEffectiveAtDate, "Change effective date"),
|
||||
billingFlow,
|
||||
productAcquisitionId,
|
||||
productKind,
|
||||
productScopeKey,
|
||||
subscriptionProductId,
|
||||
lagoProviderSubscriptionId,
|
||||
lagoPlanCode,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePaymentMethod(
|
||||
value: PaymentGatewayCreatePaymentInput["method"],
|
||||
sequenceType: "oneoff" | "first" | "recurring"
|
||||
): MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
if (typeof value === "string") {
|
||||
if (!molliePaymentMethodIds.includes(value as MolliePaymentMethodId)) {
|
||||
throw new MolliePaymentGatewayError("Payment method is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
if (sequenceType === "recurring" && value !== "directdebit" && value !== "creditcard" && value !== "paypal") {
|
||||
throw new MolliePaymentGatewayError("Recurring collection method is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
if (sequenceType !== "recurring" && value === "directdebit") {
|
||||
throw new MolliePaymentGatewayError("Direct debit is valid only for recurring collection payments.", "CONFIG_INVALID");
|
||||
}
|
||||
return value as MolliePaymentMethodId;
|
||||
}
|
||||
if (sequenceType !== "first" || value.length === 0) {
|
||||
throw new MolliePaymentGatewayError("SEPA authorization methods are valid only for first payments.", "CONFIG_INVALID");
|
||||
}
|
||||
const allowed = new Set<string>(mollieSepaFirstPaymentMethods);
|
||||
if (value.some((method) => !allowed.has(method)) || new Set(value).size !== value.length) {
|
||||
throw new MolliePaymentGatewayError("SEPA authorization payment methods are invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
return [...value];
|
||||
}
|
||||
|
||||
function normalizeMandateId(value: string | null | undefined, sequenceType: "oneoff" | "first" | "recurring"): string | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
const mandateId = value.trim();
|
||||
if (sequenceType !== "recurring" || !/^mdt_[A-Za-z0-9]+$/u.test(mandateId)) {
|
||||
throw new MolliePaymentGatewayError("Mollie mandate id is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
return mandateId;
|
||||
}
|
||||
|
||||
function normalizeProviderTimestamp(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
const parsed = new Date(value);
|
||||
return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
|
||||
}
|
||||
|
||||
function normalizeLocale(value: MollieLocale | null | undefined): MollieLocale | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
if (!mollieLocales.includes(value)) {
|
||||
throw new MolliePaymentGatewayError("Mollie locale is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function validateListPaymentMethodsInput(input: PaymentGatewayListMethodsInput): {
|
||||
amountCents: number | null;
|
||||
currency: string;
|
||||
sequenceType: "oneoff" | "first" | "recurring";
|
||||
locale: MollieLocale | null;
|
||||
} {
|
||||
const currency = input.currency.trim().toUpperCase();
|
||||
if (!/^[A-Z]{3}$/u.test(currency)) {
|
||||
throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID");
|
||||
}
|
||||
if (input.sequenceType !== "oneoff" && input.sequenceType !== "first" && input.sequenceType !== "recurring") {
|
||||
throw new MolliePaymentGatewayError("Payment sequence type is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
const amountCents = input.amountCents === null || input.amountCents === undefined ? null : input.amountCents;
|
||||
if (amountCents !== null && (!Number.isSafeInteger(amountCents) || amountCents < 0)) {
|
||||
throw new MolliePaymentGatewayError("Amount must be a non-negative cent integer.", "CONFIG_INVALID");
|
||||
}
|
||||
return {
|
||||
amountCents,
|
||||
currency,
|
||||
sequenceType: input.sequenceType,
|
||||
locale: normalizeLocale(input.locale),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeBillingFlow(value: string | null | undefined): PaymentBillingFlow | null {
|
||||
return paymentBillingFlows.includes(value as PaymentBillingFlow) ? (value as PaymentBillingFlow) : null;
|
||||
}
|
||||
|
||||
function normalizeProductKind(value: string | null | undefined): SubscriptionProductKind | null {
|
||||
return subscriptionProductKinds.includes(value as SubscriptionProductKind) ? (value as SubscriptionProductKind) : null;
|
||||
}
|
||||
|
||||
function normalizeIsoTimestamp(value: string | null | undefined, label: string): string | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
const normalized = value.trim();
|
||||
if (!z.string().datetime({ offset: true }).safeParse(normalized).success) {
|
||||
throw new MolliePaymentGatewayError(`${label} must be an ISO timestamp with timezone.`, "CONFIG_INVALID");
|
||||
}
|
||||
return new Date(normalized).toISOString();
|
||||
}
|
||||
|
||||
function normalizeChangeEffectiveAt(value: string | null | undefined): "immediate" | "period_end" | null {
|
||||
return value === "immediate" || value === "period_end" ? value : null;
|
||||
}
|
||||
|
||||
function normalizeMetadataString(value: string | null | undefined): string | null {
|
||||
return value?.trim() || null;
|
||||
}
|
||||
|
||||
function normalizeMetadataIsoTimestamp(value: string | null | undefined): string | null {
|
||||
const normalized = normalizeMetadataString(value);
|
||||
if (!normalized || !z.string().datetime({ offset: true }).safeParse(normalized).success) return null;
|
||||
return new Date(normalized).toISOString();
|
||||
}
|
||||
|
||||
function assertHttpUrl(value: string, label: string): void {
|
||||
@@ -273,6 +783,15 @@ function normalizeTimeout(timeoutMs: number | undefined): number {
|
||||
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_MOLLIE_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
function normalizeIdempotencyKey(value: string | null | undefined): string | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
const key = value.trim();
|
||||
if (!key || key.length > 255 || !/^[\x21-\x7e]+$/u.test(key)) {
|
||||
throw new MolliePaymentGatewayError("Idempotency key must contain 1 to 255 visible ASCII characters.", "CONFIG_INVALID");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function centsToMollieValue(amountCents: number): string {
|
||||
return (amountCents / 100).toFixed(2);
|
||||
}
|
||||
@@ -284,9 +803,21 @@ function mollieValueToCents(value: string | null | undefined): number | null {
|
||||
return Math.round(Number(normalized) * 100);
|
||||
}
|
||||
|
||||
function normalizePaymentStatus(status: string | null | undefined, refundedValue: string | null | undefined): PaymentGatewayPaymentStatus {
|
||||
function normalizePaymentStatus(
|
||||
status: string | null | undefined,
|
||||
refundedValue: string | null | undefined,
|
||||
originalValue: string | null | undefined
|
||||
): PaymentGatewayPaymentStatus {
|
||||
const refundedCents = mollieValueToCents(refundedValue);
|
||||
if (typeof refundedCents === "number" && refundedCents > 0) return "refunded";
|
||||
const originalCents = mollieValueToCents(originalValue);
|
||||
// Mollie exposes partial and full refunds through the same amountRefunded
|
||||
// field. Only a full refund is a terminal payment state; a partial refund
|
||||
// keeps the provider status (normally `paid`) so the product ledger can
|
||||
// quarantine it for operator reconciliation without revoking the complete
|
||||
// entitlement.
|
||||
if (typeof refundedCents === "number" && typeof originalCents === "number" && originalCents > 0 && refundedCents >= originalCents) {
|
||||
return "refunded";
|
||||
}
|
||||
if (
|
||||
status === "open" ||
|
||||
status === "pending" ||
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { MAX_MOLLIE_PAYMENT_LIFETIME_MS, MOLLIE_RECONCILIATION_GRACE_MS, resolvePaymentReservation } from "./payment-reservation.js";
|
||||
|
||||
describe("Mollie product-acquisition reservation", () => {
|
||||
const now = new Date("2026-07-17T12:00:00.000Z");
|
||||
|
||||
it("uses the provider expiry plus reconciliation grace", () => {
|
||||
expect(resolvePaymentReservation({ expiresAt: "2026-07-30T12:00:00.000Z" }, now)).toEqual({
|
||||
expiresAt: new Date("2026-08-01T12:00:00.000Z"),
|
||||
trusted: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([null, "invalid", "2026-07-17T11:59:59.000Z", "2027-01-01T00:00:00.000Z"])(
|
||||
"quarantines an untrusted provider expiry %s under a bounded deadline",
|
||||
(expiresAt) => {
|
||||
expect(resolvePaymentReservation({ expiresAt }, now)).toEqual({
|
||||
expiresAt: new Date(now.getTime() + MAX_MOLLIE_PAYMENT_LIFETIME_MS + MOLLIE_RECONCILIATION_GRACE_MS),
|
||||
trusted: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { PaymentGatewayPayment } from "./types.js";
|
||||
|
||||
/**
|
||||
* Longest normal hosted-checkout lifetime in HiveGrid's one-off EUR Mollie
|
||||
* scope. SEPA bank transfer is documented as 12+2 calendar days; the two-day
|
||||
* safety slack absorbs day-boundary/timezone rounding while keeping malformed
|
||||
* provider timestamps bounded.
|
||||
*/
|
||||
export const MAX_MOLLIE_PAYMENT_LIFETIME_MS = 16 * 24 * 60 * 60 * 1000;
|
||||
export const MOLLIE_RECONCILIATION_GRACE_MS = 48 * 60 * 60 * 1000;
|
||||
|
||||
export type PaymentReservation = {
|
||||
readonly expiresAt: Date;
|
||||
readonly trusted: boolean;
|
||||
};
|
||||
|
||||
const ABSOLUTE_ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/u;
|
||||
|
||||
export function parsePaymentTimestamp(value: string | null | undefined): Date | null {
|
||||
const normalized = value?.trim();
|
||||
if (!normalized || !ABSOLUTE_ISO_TIMESTAMP.test(normalized)) return null;
|
||||
const milliseconds = Date.parse(normalized);
|
||||
return Number.isFinite(milliseconds) ? new Date(milliseconds) : null;
|
||||
}
|
||||
|
||||
export function reservationFromProviderExpiry(expiresAt: Date | null): Date | null {
|
||||
return expiresAt ? new Date(expiresAt.getTime() + MOLLIE_RECONCILIATION_GRACE_MS) : null;
|
||||
}
|
||||
|
||||
export function resolvePaymentReservation(payment: Pick<PaymentGatewayPayment, "expiresAt">, now: Date): PaymentReservation {
|
||||
const providerExpiry = parsePaymentTimestamp(payment.expiresAt);
|
||||
const maximumProviderExpiry = new Date(now.getTime() + MAX_MOLLIE_PAYMENT_LIFETIME_MS);
|
||||
if (
|
||||
!providerExpiry ||
|
||||
!Number.isFinite(providerExpiry.getTime()) ||
|
||||
providerExpiry <= now ||
|
||||
providerExpiry > maximumProviderExpiry
|
||||
) {
|
||||
return {
|
||||
expiresAt: new Date(maximumProviderExpiry.getTime() + MOLLIE_RECONCILIATION_GRACE_MS),
|
||||
trusted: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
expiresAt: new Date(providerExpiry.getTime() + MOLLIE_RECONCILIATION_GRACE_MS),
|
||||
trusted: true,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { readBillingJsonResponse } from "./provider-http.js";
|
||||
|
||||
describe("billing provider response boundary", () => {
|
||||
it("parses bounded JSON", async () => {
|
||||
await expect(readBillingJsonResponse(new Response('{"ok":true}'))).resolves.toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it("rejects an oversized streamed response", async () => {
|
||||
await expect(readBillingJsonResponse(new Response('{"large":true}'), 8)).rejects.toThrow("size limit");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
export const BILLING_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export async function readBillingJsonResponse(response: Response, maxBytes = BILLING_RESPONSE_MAX_BYTES): Promise<unknown> {
|
||||
const contentLength = response.headers.get("content-length");
|
||||
if (contentLength && /^\d+$/u.test(contentLength) && Number(contentLength) > maxBytes) {
|
||||
await response.body?.cancel().catch(() => undefined);
|
||||
throw new Error("Billing provider response exceeds the configured size limit.");
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new Error("Billing provider returned an empty JSON response.");
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let totalBytes = 0;
|
||||
while (true) {
|
||||
const chunk = await reader.read();
|
||||
if (chunk.done) break;
|
||||
totalBytes += chunk.value.byteLength;
|
||||
if (totalBytes > maxBytes) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
throw new Error("Billing provider response exceeds the configured size limit.");
|
||||
}
|
||||
chunks.push(chunk.value);
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(totalBytes);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return JSON.parse(new TextDecoder().decode(bytes)) as unknown;
|
||||
}
|
||||
@@ -1,14 +1,5 @@
|
||||
import {
|
||||
applyLagoSubscriptionSync,
|
||||
applyMolliePaymentSync,
|
||||
type BillingSyncClient,
|
||||
type BillingSyncResult,
|
||||
} from "@hivegrid/db/billing-sync.server";
|
||||
import {
|
||||
resolveTenantBillingState,
|
||||
type TenantBillingState,
|
||||
type TenantBillingStateClient,
|
||||
} from "@hivegrid/db/billing-domain.server";
|
||||
import { applyLagoSubscriptionSync, applyMolliePaymentSync, type BillingSyncClient, type BillingSyncResult } from "@hivegrid/db/billing-sync.server";
|
||||
import { resolveTenantBillingState, type TenantBillingState, type TenantBillingStateClient } from "@hivegrid/db/billing-domain.server";
|
||||
|
||||
import type {
|
||||
BillingGateway,
|
||||
@@ -121,7 +112,13 @@ type TenantSubscriptionProductUpdateManyArgs = Parameters<BillingSyncClient["ten
|
||||
|
||||
function normalizeRunId(value: string | undefined): string {
|
||||
const fallback = `bill-07-${Date.now().toString(36)}`;
|
||||
return (value ?? fallback).trim().toLowerCase().replace(/[^a-z0-9-]+/gu, "-").replace(/^-+|-+$/gu, "") || fallback;
|
||||
return (
|
||||
(value ?? fallback)
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]+/gu, "-")
|
||||
.replace(/^-+|-+$/gu, "") || fallback
|
||||
);
|
||||
}
|
||||
|
||||
function positiveSeatQuantity(value: number | undefined): number {
|
||||
@@ -163,18 +160,29 @@ function createSandboxState(input: Required<Pick<BillingSandboxFlowInput, "planC
|
||||
}
|
||||
|
||||
function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBillingStateClient {
|
||||
return {
|
||||
let client: BillingSyncClient & TenantBillingStateClient;
|
||||
client = {
|
||||
async $transaction(callback: (transaction: BillingSyncClient & TenantBillingStateClient) => Promise<unknown>) {
|
||||
return callback(client);
|
||||
},
|
||||
async $queryRaw() {
|
||||
return [];
|
||||
},
|
||||
idempotencyKey: {
|
||||
async findUnique({ where }: IdempotencyFindUniqueArgs) {
|
||||
const row = state.idempotency.get(`${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`);
|
||||
const unique = where.idempotency_key_partition_scope_key;
|
||||
const row = state.idempotency.get(`${unique.partitionKey}:${unique.scope}:${unique.key}`);
|
||||
return row
|
||||
? ({
|
||||
id: "idem_1",
|
||||
createdAt: new Date("2026-07-04T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-04T00:00:00.000Z"),
|
||||
expiresAt: null,
|
||||
scope: where.idempotency_key_scope_key.scope,
|
||||
key: where.idempotency_key_scope_key.key,
|
||||
tenantId: unique.partitionKey.startsWith("tenant:") ? unique.partitionKey.slice("tenant:".length) : null,
|
||||
partitionKey: unique.partitionKey,
|
||||
systemOwned: unique.partitionKey === "system",
|
||||
scope: unique.scope,
|
||||
key: unique.key,
|
||||
requestHash: "sandbox",
|
||||
responseStatus: 200,
|
||||
responseBody: row.responseBody,
|
||||
@@ -183,7 +191,7 @@ function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBil
|
||||
: null;
|
||||
},
|
||||
async create({ data }: IdempotencyCreateArgs) {
|
||||
state.idempotency.set(`${data.scope}:${data.key}`, { responseBody: data.responseBody });
|
||||
state.idempotency.set(`${data.partitionKey}:${data.scope}:${data.key}`, { responseBody: data.responseBody });
|
||||
return { id: `idem_${state.idempotency.size}`, createdAt: new Date(), updatedAt: new Date(), ...data } as never;
|
||||
},
|
||||
},
|
||||
@@ -193,7 +201,7 @@ function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBil
|
||||
},
|
||||
async create({ data }: AuditCreateArgs) {
|
||||
state.auditEvents.push(data);
|
||||
return { id: `audit_${state.auditEvents.length}`, createdAt: new Date(), ...data } as never;
|
||||
return { ...data } as never;
|
||||
},
|
||||
},
|
||||
activity: {
|
||||
@@ -298,7 +306,24 @@ function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBil
|
||||
return { count };
|
||||
},
|
||||
},
|
||||
portalDomainHostnameClaim: {
|
||||
async findMany() {
|
||||
return [];
|
||||
},
|
||||
async findFirst() {
|
||||
return null;
|
||||
},
|
||||
async updateMany() {
|
||||
return { count: 0 };
|
||||
},
|
||||
},
|
||||
portalCustomDomain: {
|
||||
async updateMany() {
|
||||
return { count: 0 };
|
||||
},
|
||||
},
|
||||
} as unknown as BillingSyncClient & TenantBillingStateClient;
|
||||
return client;
|
||||
}
|
||||
|
||||
function createSandboxBillingGateway(state: SandboxState, now: Date): BillingGateway {
|
||||
@@ -352,8 +377,53 @@ function createSandboxBillingGateway(state: SandboxState, now: Date): BillingGat
|
||||
async getSubscription(subscriptionExternalId) {
|
||||
return state.providerSubscriptions.get(subscriptionExternalId) ?? null;
|
||||
},
|
||||
async activatePendingSubscription(subscriptionExternalId, activatedAt) {
|
||||
const subscription = state.providerSubscriptions.get(subscriptionExternalId);
|
||||
if (!subscription) return null;
|
||||
const active = {
|
||||
...subscription,
|
||||
status: "active" as const,
|
||||
currentBillingPeriodStartedAt: new Date(activatedAt).toISOString(),
|
||||
};
|
||||
state.providerSubscriptions.set(subscriptionExternalId, active);
|
||||
return active;
|
||||
},
|
||||
async terminatePendingSubscription(subscriptionExternalId) {
|
||||
const subscription = state.providerSubscriptions.get(subscriptionExternalId);
|
||||
if (!subscription || subscription.status !== "pending") return null;
|
||||
const terminated = { ...subscription, status: "canceled" as const };
|
||||
state.providerSubscriptions.set(subscriptionExternalId, terminated);
|
||||
return terminated;
|
||||
},
|
||||
async terminateSubscription(subscriptionExternalId) {
|
||||
const subscription = state.providerSubscriptions.get(subscriptionExternalId);
|
||||
if (!subscription) return null;
|
||||
const terminated = { ...subscription, status: "terminated" as const };
|
||||
state.providerSubscriptions.set(subscriptionExternalId, terminated);
|
||||
return terminated;
|
||||
},
|
||||
async createOneOffInvoice(input) {
|
||||
const invoice: BillingGatewayInvoice = {
|
||||
provider: "lago",
|
||||
providerInvoiceId: `lago_invoice_one_off_${input.tenantId}_${input.addOnCode}`,
|
||||
number: `HG-ONE-OFF-${input.addOnCode}`,
|
||||
externalCustomerId: input.tenantId,
|
||||
status: "finalized",
|
||||
paymentStatus: "pending",
|
||||
invoiceType: "one_off",
|
||||
currency: input.currency.toUpperCase(),
|
||||
totalAmountCents: input.amountCents * (input.quantity ?? 1),
|
||||
issuingDate: now.toISOString(),
|
||||
fileUrl: null,
|
||||
};
|
||||
state.invoices.set(input.tenantId, [...(state.invoices.get(input.tenantId) ?? []), invoice]);
|
||||
return invoice;
|
||||
},
|
||||
async listInvoices(input = {}) {
|
||||
return input.tenantId ? state.invoices.get(input.tenantId) ?? [] : [...state.invoices.values()].flat();
|
||||
return input.tenantId ? (state.invoices.get(input.tenantId) ?? []) : [...state.invoices.values()].flat();
|
||||
},
|
||||
async getInvoice(providerInvoiceId) {
|
||||
return [...state.invoices.values()].flat().find((invoice) => invoice.providerInvoiceId === providerInvoiceId) ?? null;
|
||||
},
|
||||
async downloadInvoice(providerInvoiceId) {
|
||||
return [...state.invoices.values()].flat().find((invoice) => invoice.providerInvoiceId === providerInvoiceId) ?? null;
|
||||
@@ -548,9 +618,21 @@ export async function runBillingSandboxFlow(input: BillingSandboxFlowInput = {})
|
||||
const referencesVisible = Boolean(activeState.lastInvoiceExternalId && activeState.lastPaymentExternalId);
|
||||
const steps = [
|
||||
buildStep("lago.customer", customer.externalId === tenantId, `Customer ${customer.providerCustomerId} created for ${tenantId}.`),
|
||||
buildStep("lago.subscription", subscription.planCode === planCode && subscription.status === "active", `Subscription ${subscription.providerSubscriptionId} uses ${planCode}.`),
|
||||
buildStep("mollie.payment", payment.status === "open" && paidPayment.status === "paid", `Payment ${payment.providerPaymentId} was created and simulated as paid.`),
|
||||
buildStep("local.sync", activeState.status === "active" && activeState.lastInvoiceExternalId === invoice.providerInvoiceId, "Provider sync updated the local subscription."),
|
||||
buildStep(
|
||||
"lago.subscription",
|
||||
subscription.planCode === planCode && subscription.status === "active",
|
||||
`Subscription ${subscription.providerSubscriptionId} uses ${planCode}.`
|
||||
),
|
||||
buildStep(
|
||||
"mollie.payment",
|
||||
payment.status === "open" && paidPayment.status === "paid",
|
||||
`Payment ${payment.providerPaymentId} was created and simulated as paid.`
|
||||
),
|
||||
buildStep(
|
||||
"local.sync",
|
||||
activeState.status === "active" && activeState.lastInvoiceExternalId === invoice.providerInvoiceId,
|
||||
"Provider sync updated the local subscription."
|
||||
),
|
||||
buildStep("module.gate", activeAllowed && !activeState.readOnly, `${moduleKey} is allowed while the subscription is active.`),
|
||||
buildStep("references.audit", referencesVisible && state.auditEvents.length >= 2, "Invoice/payment references are visible and syncs are audited."),
|
||||
buildStep(
|
||||
|
||||
@@ -9,7 +9,12 @@ import {
|
||||
LAGO_BILLING_SYNC_EVENT_TYPE,
|
||||
MOLLIE_PAYMENT_SYNC_EVENT_TYPE,
|
||||
} from "./sync-outbox.js";
|
||||
import { buildLagoWebhookSyncOutboxArgs, parseLagoWebhookEvent } from "./webhook.js";
|
||||
import {
|
||||
buildLagoWebhookSyncOutboxArgs,
|
||||
isLagoV1WebhookEvent,
|
||||
parseLagoWebhookEvent,
|
||||
resolveLagoWebhookTenantId,
|
||||
} from "./webhook.js";
|
||||
|
||||
describe("Lago billing sync outbox", () => {
|
||||
it("builds idempotent outbox args for Lago pull sync actions", () => {
|
||||
@@ -48,12 +53,18 @@ describe("Lago billing sync outbox", () => {
|
||||
|
||||
it("maps Lago webhook events to idempotent sync events", () => {
|
||||
const event = parseLagoWebhookEvent({
|
||||
event_type: "invoice.finalized",
|
||||
lago_id: "invoice_1",
|
||||
external_customer_id: "tenant_1",
|
||||
data: { status: "finalized" },
|
||||
webhook_type: "invoice.created",
|
||||
object_type: "invoice",
|
||||
organization_id: "organization_1",
|
||||
invoice: {
|
||||
lago_id: "invoice_1",
|
||||
external_customer_id: "tenant_1",
|
||||
status: "finalized",
|
||||
},
|
||||
});
|
||||
|
||||
expect(isLagoV1WebhookEvent(event)).toBe(true);
|
||||
expect(resolveLagoWebhookTenantId(event)).toBe("tenant_1");
|
||||
expect(
|
||||
buildLagoWebhookSyncOutboxArgs({
|
||||
tenantId: "tenant_1",
|
||||
@@ -71,6 +82,71 @@ describe("Lago billing sync outbox", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps only recognized invoice reasons eligible for exact webhook correlation", () => {
|
||||
const starting = parseLagoWebhookEvent({
|
||||
webhook_type: "invoice.created",
|
||||
object_type: "invoice",
|
||||
organization_id: "organization_1",
|
||||
invoice: {
|
||||
lago_id: "invoice_1",
|
||||
billing_periods: [
|
||||
{
|
||||
external_subscription_id: "subscription_1",
|
||||
lago_subscription_id: "lago_subscription_1",
|
||||
invoicing_reason: "subscription_starting",
|
||||
},
|
||||
{
|
||||
external_subscription_id: "subscription_2",
|
||||
lago_subscription_id: "lago_subscription_2",
|
||||
invoicing_reason: "future_lago_reason",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(starting.invoice?.billing_periods?.map((period) => period.invoicing_reason)).toEqual(["subscription_starting", null]);
|
||||
});
|
||||
|
||||
it("resolves tenant ids from nested Lago v1.50 subscription and customer payloads", () => {
|
||||
const subscription = parseLagoWebhookEvent({
|
||||
webhook_type: "subscription.started",
|
||||
object_type: "subscription",
|
||||
organization_id: "organization_1",
|
||||
subscription: {
|
||||
lago_id: "lago_subscription_1",
|
||||
external_id: "subscription_1",
|
||||
external_customer_id: "tenant_subscription",
|
||||
plan_code: "starter",
|
||||
status: "active",
|
||||
},
|
||||
});
|
||||
const customer = parseLagoWebhookEvent({
|
||||
webhook_type: "customer.created",
|
||||
object_type: "customer",
|
||||
organization_id: "organization_1",
|
||||
customer: {
|
||||
lago_id: "lago_customer_1",
|
||||
external_id: "tenant_customer",
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveLagoWebhookTenantId(subscription)).toBe("tenant_subscription");
|
||||
expect(resolveLagoWebhookTenantId(customer)).toBe("tenant_customer");
|
||||
expect(isLagoV1WebhookEvent(subscription)).toBe(true);
|
||||
expect(isLagoV1WebhookEvent(customer)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not treat the legacy flat fixture shape as a Lago v1 webhook", () => {
|
||||
const event = parseLagoWebhookEvent({
|
||||
event_type: "invoice.finalized",
|
||||
lago_id: "invoice_1",
|
||||
external_customer_id: "tenant_1",
|
||||
});
|
||||
|
||||
expect(isLagoV1WebhookEvent(event)).toBe(false);
|
||||
expect(resolveLagoWebhookTenantId(event)).toBe("tenant_1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Mollie payment sync outbox", () => {
|
||||
|
||||
@@ -1,3 +1,89 @@
|
||||
export const subscriptionProductKinds = ["base_plan", "recurring_add_on", "one_time_setup", "contract_override"] as const;
|
||||
|
||||
export type SubscriptionProductKind = (typeof subscriptionProductKinds)[number];
|
||||
|
||||
export const paymentBillingFlows = ["self_service_new", "self_service_change", "product_acquisition", "recurring_invoice"] as const;
|
||||
|
||||
export type PaymentBillingFlow = (typeof paymentBillingFlows)[number];
|
||||
|
||||
/**
|
||||
* Customer-present methods which Mollie documents as creating a SEPA
|
||||
* direct-debit mandate after a successful `sequenceType=first` payment.
|
||||
*/
|
||||
export const mollieSepaFirstPaymentMethods = Object.freeze(["bancontact", "belfius", "eps", "ideal", "kbc", "mybank", "paybybank"] as const);
|
||||
|
||||
export type MollieSepaFirstPaymentMethod = (typeof mollieSepaFirstPaymentMethods)[number];
|
||||
|
||||
export const molliePaymentMethodIds = Object.freeze([
|
||||
"alma",
|
||||
"applepay",
|
||||
"bacs",
|
||||
"bancomatpay",
|
||||
"bancontact",
|
||||
"banktransfer",
|
||||
"belfius",
|
||||
"billie",
|
||||
"bizum",
|
||||
"blik",
|
||||
"creditcard",
|
||||
"directdebit",
|
||||
"eps",
|
||||
"giftcard",
|
||||
"ideal",
|
||||
"in3",
|
||||
"kbc",
|
||||
"klarna",
|
||||
"mbway",
|
||||
"mobilepay",
|
||||
"multibanco",
|
||||
"mybank",
|
||||
"paybybank",
|
||||
"paypal",
|
||||
"paysafecard",
|
||||
"pointofsale",
|
||||
"przelewy24",
|
||||
"riverty",
|
||||
"satispay",
|
||||
"swish",
|
||||
"trustly",
|
||||
"twint",
|
||||
"vipps",
|
||||
"voucher",
|
||||
] as const);
|
||||
|
||||
export type MolliePaymentMethodId = (typeof molliePaymentMethodIds)[number];
|
||||
|
||||
export const mollieLocales = Object.freeze([
|
||||
"ca_ES",
|
||||
"cs_CZ",
|
||||
"da_DK",
|
||||
"de_AT",
|
||||
"de_CH",
|
||||
"de_DE",
|
||||
"de_LU",
|
||||
"en_GB",
|
||||
"en_US",
|
||||
"es_ES",
|
||||
"fi_FI",
|
||||
"fr_BE",
|
||||
"fr_FR",
|
||||
"fr_LU",
|
||||
"hu_HU",
|
||||
"is_IS",
|
||||
"it_IT",
|
||||
"lt_LT",
|
||||
"lv_LV",
|
||||
"nb_NO",
|
||||
"nl_BE",
|
||||
"nl_NL",
|
||||
"pl_PL",
|
||||
"pt_PT",
|
||||
"sk_SK",
|
||||
"sv_SE",
|
||||
] as const);
|
||||
|
||||
export type MollieLocale = (typeof mollieLocales)[number];
|
||||
|
||||
export type BillingGatewayCustomerInput = {
|
||||
tenantId: string;
|
||||
name: string;
|
||||
@@ -25,6 +111,22 @@ export type BillingGatewaySubscriptionInput = {
|
||||
name?: string | null;
|
||||
subscriptionAt?: Date | string | null;
|
||||
endingAt?: Date | string | null;
|
||||
paymentMethodType?: "manual" | null;
|
||||
consolidateInvoice?: boolean | null;
|
||||
managedPlan?: BillingGatewayManagedPlan | null;
|
||||
};
|
||||
|
||||
export type BillingGatewayManagedPlan = {
|
||||
code: string;
|
||||
name: string;
|
||||
invoiceDisplayName: string;
|
||||
description: string;
|
||||
interval: "monthly";
|
||||
amountCents: number;
|
||||
currency: string;
|
||||
payInAdvance: boolean;
|
||||
taxCodes: readonly string[];
|
||||
metadata: Readonly<Record<string, string>>;
|
||||
};
|
||||
|
||||
export type BillingGatewaySubscription = {
|
||||
@@ -40,6 +142,18 @@ export type BillingGatewaySubscription = {
|
||||
createdAt: string | null;
|
||||
};
|
||||
|
||||
export type BillingGatewaySubscriptionStatus = "active" | "pending";
|
||||
|
||||
export const billingGatewayInvoiceInvoicingReasons = ["subscription_starting", "subscription_periodic"] as const;
|
||||
|
||||
export type BillingGatewayInvoiceInvoicingReason = (typeof billingGatewayInvoiceInvoicingReasons)[number];
|
||||
|
||||
export type BillingGatewayInvoiceBillingPeriod = {
|
||||
externalSubscriptionId: string | null;
|
||||
providerSubscriptionId: string | null;
|
||||
invoicingReason: BillingGatewayInvoiceInvoicingReason | null;
|
||||
};
|
||||
|
||||
export type BillingGatewayInvoice = {
|
||||
provider: "lago";
|
||||
providerInvoiceId: string;
|
||||
@@ -52,20 +166,46 @@ export type BillingGatewayInvoice = {
|
||||
totalAmountCents: number | null;
|
||||
issuingDate: string | null;
|
||||
fileUrl: string | null;
|
||||
billingPeriods?: readonly BillingGatewayInvoiceBillingPeriod[];
|
||||
subscriptionExternalIds?: readonly string[];
|
||||
subscriptionProviderIds?: readonly string[];
|
||||
metadata?: Readonly<Record<string, string>>;
|
||||
};
|
||||
|
||||
export type BillingGatewayInvoiceListInput = {
|
||||
tenantId?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
metadata?: Readonly<Record<string, string>>;
|
||||
};
|
||||
|
||||
export type BillingGatewayOneOffInvoiceInput = {
|
||||
tenantId: string;
|
||||
addOnCode: string;
|
||||
amountCents: number;
|
||||
currency: string;
|
||||
quantity?: number;
|
||||
description?: string | null;
|
||||
taxCodes?: readonly string[];
|
||||
metadata?: Readonly<Record<string, string>>;
|
||||
};
|
||||
|
||||
export type BillingGateway = {
|
||||
createCustomer(input: BillingGatewayCustomerInput): Promise<BillingGatewayCustomer>;
|
||||
getCustomer(tenantId: string): Promise<BillingGatewayCustomer | null>;
|
||||
createSubscription(input: BillingGatewaySubscriptionInput): Promise<BillingGatewaySubscription>;
|
||||
getSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null>;
|
||||
ensureManagedPlan?(plan: BillingGatewayManagedPlan): Promise<void>;
|
||||
getSubscription(subscriptionExternalId: string, status?: BillingGatewaySubscriptionStatus): Promise<BillingGatewaySubscription | null>;
|
||||
activatePendingSubscription(
|
||||
subscriptionExternalId: string,
|
||||
activatedAt: Date | string,
|
||||
endingAt?: Date | string | null
|
||||
): Promise<BillingGatewaySubscription | null>;
|
||||
terminatePendingSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null>;
|
||||
terminateSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null>;
|
||||
createOneOffInvoice(input: BillingGatewayOneOffInvoiceInput): Promise<BillingGatewayInvoice>;
|
||||
listInvoices(input?: BillingGatewayInvoiceListInput): Promise<BillingGatewayInvoice[]>;
|
||||
getInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null>;
|
||||
downloadInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null>;
|
||||
updateInvoicePaymentStatus(providerInvoiceId: string, paymentStatus: BillingGatewayInvoice["paymentStatus"]): Promise<BillingGatewayInvoice>;
|
||||
};
|
||||
@@ -75,15 +215,79 @@ export type PaymentGatewayCreatePaymentInput = {
|
||||
invoiceExternalId: string;
|
||||
amountCents: number;
|
||||
currency: string;
|
||||
redirectUrl: string;
|
||||
redirectUrl?: string | null;
|
||||
webhookUrl: string;
|
||||
paymentExternalId?: string | null;
|
||||
mollieCustomerId?: string | null;
|
||||
lagoCustomerId?: string | null;
|
||||
lagoSubscriptionId?: string | null;
|
||||
lagoProviderSubscriptionId?: string | null;
|
||||
lagoPlanCode?: string | null;
|
||||
planCode?: string | null;
|
||||
subscriptionPriceId?: string | null;
|
||||
seatQuantity?: number | null;
|
||||
officeSeatQuantity?: number | null;
|
||||
fieldSeatQuantity?: number | null;
|
||||
billingCadence?: string | null;
|
||||
commitmentEndsAt?: string | null;
|
||||
storageAddOnCodes?: readonly string[] | null;
|
||||
description?: string | null;
|
||||
sequenceType?: "oneoff" | "first" | "recurring";
|
||||
method?: MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null;
|
||||
mandateId?: string | null;
|
||||
locale?: MollieLocale | null;
|
||||
trialEndsAt?: string | null;
|
||||
changeEffectiveAt?: "immediate" | "period_end" | null;
|
||||
changeEffectiveAtDate?: string | null;
|
||||
billingFlow?: PaymentBillingFlow | null;
|
||||
productAcquisitionId?: string | null;
|
||||
productKind?: SubscriptionProductKind | null;
|
||||
productScopeKey?: string | null;
|
||||
subscriptionProductId?: string | null;
|
||||
idempotencyKey?: string | null;
|
||||
};
|
||||
|
||||
export type PaymentGatewayCreateCustomerInput = {
|
||||
tenantId: string;
|
||||
name: string;
|
||||
email: string;
|
||||
locale?: string | null;
|
||||
idempotencyKey?: string | null;
|
||||
};
|
||||
|
||||
export type PaymentGatewayCustomer = {
|
||||
provider: "mollie";
|
||||
providerCustomerId: string;
|
||||
tenantId: string | null;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
locale: string | null;
|
||||
createdAt: string | null;
|
||||
};
|
||||
|
||||
export type PaymentGatewayListMethodsInput = {
|
||||
amountCents?: number | null;
|
||||
currency: string;
|
||||
sequenceType: "oneoff" | "first" | "recurring";
|
||||
locale?: MollieLocale | null;
|
||||
};
|
||||
|
||||
export type PaymentGatewayPaymentMethod = {
|
||||
provider: "mollie";
|
||||
id: MolliePaymentMethodId;
|
||||
description: string;
|
||||
};
|
||||
|
||||
export const mollieMandatePaymentMethods = Object.freeze(["creditcard", "directdebit", "paypal"] as const);
|
||||
|
||||
export type MollieMandatePaymentMethod = (typeof mollieMandatePaymentMethods)[number];
|
||||
|
||||
export type PaymentGatewayMandate = {
|
||||
provider: "mollie";
|
||||
providerMandateId: string;
|
||||
status: "valid" | "pending" | "invalid";
|
||||
method: MollieMandatePaymentMethod;
|
||||
createdAt: string | null;
|
||||
};
|
||||
|
||||
export type PaymentGatewayPaymentStatus =
|
||||
@@ -102,10 +306,27 @@ export type PaymentGatewayPaymentMetadata = {
|
||||
tenantId: string | null;
|
||||
invoiceExternalId: string | null;
|
||||
paymentExternalId: string | null;
|
||||
mollieCustomerId?: string | null;
|
||||
lagoCustomerId: string | null;
|
||||
lagoSubscriptionId: string | null;
|
||||
lagoProviderSubscriptionId?: string | null;
|
||||
lagoPlanCode?: string | null;
|
||||
planCode: string | null;
|
||||
subscriptionPriceId?: string | null;
|
||||
seatQuantity: number | null;
|
||||
officeSeatQuantity?: number | null;
|
||||
fieldSeatQuantity?: number | null;
|
||||
billingCadence?: string | null;
|
||||
commitmentEndsAt?: string | null;
|
||||
storageAddOnCodes?: readonly string[];
|
||||
trialEndsAt?: string | null;
|
||||
changeEffectiveAt?: "immediate" | "period_end" | null;
|
||||
changeEffectiveAtDate?: string | null;
|
||||
billingFlow?: PaymentBillingFlow | null;
|
||||
productAcquisitionId?: string | null;
|
||||
productKind?: SubscriptionProductKind | null;
|
||||
productScopeKey?: string | null;
|
||||
subscriptionProductId?: string | null;
|
||||
};
|
||||
|
||||
export type PaymentGatewayPayment = {
|
||||
@@ -127,3 +348,20 @@ export type PaymentGateway = {
|
||||
createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment>;
|
||||
getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null>;
|
||||
};
|
||||
|
||||
export type CustomerPaymentGateway = PaymentGateway & {
|
||||
createCustomer(input: PaymentGatewayCreateCustomerInput): Promise<PaymentGatewayCustomer>;
|
||||
listPaymentMethods(input: PaymentGatewayListMethodsInput): Promise<PaymentGatewayPaymentMethod[]>;
|
||||
listCustomerMandates(mollieCustomerId: string): Promise<PaymentGatewayMandate[]>;
|
||||
findCustomerPaymentByExternalId(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Operator-only extension for proving that an ambiguous payment POST did not
|
||||
* create a Mollie payment. Normal request/reconciliation paths intentionally
|
||||
* use the bounded single-page lookup above; a destructive retry release must
|
||||
* exhaust the provider pagination before treating a payment as absent.
|
||||
*/
|
||||
export type ExhaustiveCustomerPaymentGateway = CustomerPaymentGateway & {
|
||||
findCustomerPaymentByExternalIdExhaustive(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null>;
|
||||
};
|
||||
@@ -2,11 +2,74 @@ import { z } from "zod";
|
||||
|
||||
import { buildLagoBillingSyncOutboxArgs, type LagoBillingSyncAction } from "./sync-outbox.js";
|
||||
|
||||
const nullableString = z.string().nullable().optional();
|
||||
|
||||
const lagoInvoiceInvoicingReasonSchema = nullableString.transform((value) => {
|
||||
const normalized = value?.trim();
|
||||
return normalized === "subscription_starting" || normalized === "subscription_periodic" ? normalized : null;
|
||||
});
|
||||
|
||||
const lagoWebhookCustomerSchema = z
|
||||
.object({
|
||||
lago_id: z.string(),
|
||||
external_id: z.string(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const lagoWebhookSubscriptionSchema = z
|
||||
.object({
|
||||
lago_id: z.string(),
|
||||
external_id: z.string(),
|
||||
external_customer_id: z.string(),
|
||||
plan_code: z.string(),
|
||||
status: nullableString,
|
||||
current_billing_period_started_at: nullableString,
|
||||
current_billing_period_ending_at: nullableString,
|
||||
started_at: nullableString,
|
||||
ending_at: nullableString,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const lagoWebhookInvoiceSchema = z
|
||||
.object({
|
||||
lago_id: z.string(),
|
||||
external_customer_id: nullableString,
|
||||
invoice_type: nullableString,
|
||||
status: nullableString,
|
||||
payment_status: nullableString,
|
||||
currency: nullableString,
|
||||
total_amount_cents: z.number().int().nullable().optional(),
|
||||
created_at: nullableString,
|
||||
billing_periods: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
external_subscription_id: nullableString,
|
||||
lago_subscription_id: nullableString,
|
||||
invoicing_reason: lagoInvoiceInvoicingReasonSchema,
|
||||
})
|
||||
.passthrough()
|
||||
)
|
||||
.optional(),
|
||||
customer: z
|
||||
.object({
|
||||
external_id: nullableString,
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const lagoWebhookEventSchema = z
|
||||
.object({
|
||||
event_type: z.string().optional(),
|
||||
webhook_type: z.string().optional(),
|
||||
object_type: z.string().optional(),
|
||||
organization_id: z.string().optional(),
|
||||
customer: lagoWebhookCustomerSchema.optional(),
|
||||
subscription: lagoWebhookSubscriptionSchema.optional(),
|
||||
invoice: lagoWebhookInvoiceSchema.optional(),
|
||||
// Kept for backwards-compatible parsing of the pre-v1.50 fixture shape.
|
||||
lago_id: z.string().optional(),
|
||||
external_id: z.string().optional(),
|
||||
external_customer_id: z.string().optional(),
|
||||
@@ -22,7 +85,13 @@ export function parseLagoWebhookEvent(value: unknown): LagoWebhookEvent {
|
||||
|
||||
export function buildLagoWebhookSyncOutboxArgs(input: { tenantId: string; event: LagoWebhookEvent; receivedAt?: Date }) {
|
||||
const action = resolveWebhookAction(input.event);
|
||||
const externalId = input.event.external_id ?? input.event.lago_id ?? `${action}:${input.tenantId}`;
|
||||
const externalId =
|
||||
input.event.subscription?.external_id ??
|
||||
input.event.invoice?.lago_id ??
|
||||
input.event.customer?.external_id ??
|
||||
input.event.external_id ??
|
||||
input.event.lago_id ??
|
||||
`${action}:${input.tenantId}`;
|
||||
return buildLagoBillingSyncOutboxArgs({
|
||||
tenantId: input.tenantId,
|
||||
action,
|
||||
@@ -32,6 +101,25 @@ export function buildLagoWebhookSyncOutboxArgs(input: { tenantId: string; event:
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveLagoWebhookTenantId(event: LagoWebhookEvent): string | null {
|
||||
return firstNonEmptyString(
|
||||
event.subscription?.external_customer_id,
|
||||
event.invoice?.external_customer_id,
|
||||
event.invoice?.customer?.external_id,
|
||||
event.customer?.external_id,
|
||||
event.external_customer_id
|
||||
);
|
||||
}
|
||||
|
||||
export function isLagoV1WebhookEvent(event: LagoWebhookEvent): boolean {
|
||||
const objectType = event.object_type?.trim();
|
||||
if (!event.webhook_type?.trim() || !objectType || !event.organization_id?.trim()) return false;
|
||||
if (objectType === "subscription") return event.subscription !== undefined;
|
||||
if (objectType === "invoice") return event.invoice !== undefined;
|
||||
if (objectType === "customer") return event.customer !== undefined;
|
||||
return true;
|
||||
}
|
||||
|
||||
function resolveWebhookAction(event: LagoWebhookEvent): LagoBillingSyncAction {
|
||||
const type = [event.event_type, event.webhook_type, event.object_type].filter(Boolean).join(":").toLowerCase();
|
||||
if (type.includes("invoice")) return "invoice.refresh";
|
||||
@@ -39,3 +127,11 @@ function resolveWebhookAction(event: LagoWebhookEvent): LagoBillingSyncAction {
|
||||
if (type.includes("customer")) return "customer.upsert";
|
||||
return "webhook.received";
|
||||
}
|
||||
|
||||
function firstNonEmptyString(...values: Array<string | null | undefined>): string | null {
|
||||
for (const value of values) {
|
||||
const normalized = value?.trim();
|
||||
if (normalized) return normalized;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,12 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
brandCssVariables,
|
||||
createBrandTokens,
|
||||
defaultBrandLinks,
|
||||
defaultBrandTokens,
|
||||
resolveTransactionalBrandTokens,
|
||||
} from "./index.js";
|
||||
import { brandCssVariables, createBrandTokens, defaultBrandLinks, defaultBrandTokens, resolveTransactionalBrandTokens } from "./index.js";
|
||||
|
||||
describe("brand token helpers", () => {
|
||||
it("exposes stable default brand tokens", () => {
|
||||
@@ -20,18 +14,18 @@ describe("brand token helpers", () => {
|
||||
},
|
||||
support: {
|
||||
email: "support@hivegrid.de",
|
||||
fromName: "HiveGrid Support",
|
||||
fromName: "HiveGrid-Team",
|
||||
},
|
||||
assets: {
|
||||
logoUrl: "/android-chrome-512x512.png",
|
||||
logoUrl: "https://hivegrid.de/hivegrid-logo.png",
|
||||
faviconUrl: "/favicon.ico",
|
||||
},
|
||||
socials: {},
|
||||
mail: {
|
||||
colors: {
|
||||
primary: "#2563eb",
|
||||
primaryText: "#ffffff",
|
||||
link: "#2563eb",
|
||||
primary: "#f1b729",
|
||||
primaryText: "#231f20",
|
||||
link: "#735400",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -91,10 +91,10 @@ export const defaultBrandLinks: BrandLinkConfiguration = {
|
||||
},
|
||||
support: {
|
||||
email: "support@hivegrid.de",
|
||||
fromName: "HiveGrid Support",
|
||||
fromName: "HiveGrid-Team",
|
||||
},
|
||||
assets: {
|
||||
logoUrl: "/android-chrome-512x512.png",
|
||||
logoUrl: "https://hivegrid.de/hivegrid-logo.png",
|
||||
faviconUrl: "/favicon.ico",
|
||||
},
|
||||
socials: {},
|
||||
@@ -109,14 +109,14 @@ export const defaultBrandTokens: BrandTokens = {
|
||||
socials: defaultBrandLinks.socials,
|
||||
mail: {
|
||||
colors: {
|
||||
background: "#f6f8fb",
|
||||
background: "#f7f5f1",
|
||||
surface: "#ffffff",
|
||||
primary: "#2563eb",
|
||||
primaryText: "#ffffff",
|
||||
text: "#111827",
|
||||
mutedText: "#6b7280",
|
||||
border: "#e5e7eb",
|
||||
link: "#2563eb",
|
||||
primary: "#f1b729",
|
||||
primaryText: "#231f20",
|
||||
text: "#231f20",
|
||||
mutedText: "#655f59",
|
||||
border: "#e7e1d8",
|
||||
link: "#735400",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -36,10 +36,13 @@ describe("resolveCaptchaConfig", () => {
|
||||
expect(isCaptchaConfigured(cfg)).toBe(true);
|
||||
});
|
||||
|
||||
it("defaults failOpen to true and respects explicit false", () => {
|
||||
expect(resolveCaptchaConfig({}).failOpen).toBe(true);
|
||||
it("defaults failOpen to false and honors opt-in only in local runtimes", () => {
|
||||
expect(resolveCaptchaConfig({}).failOpen).toBe(false);
|
||||
expect(resolveCaptchaConfig({ CAPTCHA_FAIL_OPEN: "false" }).failOpen).toBe(false);
|
||||
expect(resolveCaptchaConfig({ CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(true);
|
||||
expect(resolveCaptchaConfig({ CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(false);
|
||||
expect(resolveCaptchaConfig({ NODE_ENV: "development", CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(true);
|
||||
expect(resolveCaptchaConfig({ NODE_ENV: "test", CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(true);
|
||||
expect(resolveCaptchaConfig({ NODE_ENV: "production", CAPTCHA_FAIL_OPEN: "true" }).failOpen).toBe(false);
|
||||
});
|
||||
|
||||
it("treats blank env values as undefined and reports unconfigured", () => {
|
||||
|
||||
@@ -21,7 +21,7 @@ function present(value: string | undefined): string | undefined {
|
||||
* CAP_SITE_SECRET_LOGIN / _FORMS / _BOOKING=<per-surface site secrets>
|
||||
* CAP_SITEKEY_LOGIN / _FORMS / _BOOKING=<public sitekeys>
|
||||
*
|
||||
* CAPTCHA_FAIL_OPEN=true|false (default true)
|
||||
* CAPTCHA_FAIL_OPEN=true|false (development/test only; default false)
|
||||
*/
|
||||
export function resolveCaptchaConfig(env: EnvLike): CaptchaConfig {
|
||||
const provider = resolveProvider(env);
|
||||
@@ -41,7 +41,7 @@ export function resolveCaptchaConfig(env: EnvLike): CaptchaConfig {
|
||||
forms: present(env.CAP_SITE_SECRET_FORMS) ?? sharedSecret,
|
||||
booking: present(env.CAP_SITE_SECRET_BOOKING) ?? sharedSecret,
|
||||
},
|
||||
failOpen: present(env.CAPTCHA_FAIL_OPEN) !== "false",
|
||||
failOpen: resolveFailOpen(env),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -60,10 +60,15 @@ export function resolveCaptchaConfig(env: EnvLike): CaptchaConfig {
|
||||
forms: accountSecret,
|
||||
booking: accountSecret,
|
||||
},
|
||||
failOpen: present(env.CAPTCHA_FAIL_OPEN) !== "false",
|
||||
failOpen: resolveFailOpen(env),
|
||||
};
|
||||
}
|
||||
|
||||
function resolveFailOpen(env: EnvLike): boolean {
|
||||
const runtime = present(env.NODE_ENV)?.toLowerCase();
|
||||
return (runtime === "development" || runtime === "test") && present(env.CAPTCHA_FAIL_OPEN)?.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
function resolveProvider(env: EnvLike): CaptchaProvider {
|
||||
const explicit = present(env.CAPTCHA_PROVIDER)?.toLowerCase();
|
||||
if (explicit === "cap") return "cap";
|
||||
|
||||
@@ -22,8 +22,8 @@ export type CaptchaConfig = {
|
||||
secrets: Record<CaptchaSurface, string | undefined>;
|
||||
/**
|
||||
* When the instance is unreachable/misconfigured: true = let the request
|
||||
* through (fail-open, default), false = block it (fail-closed). A missing
|
||||
* token is always a hard failure regardless of this flag.
|
||||
* through, false = block it (secure default). Fail-open is honored only in
|
||||
* development/test; a missing token is always a hard failure.
|
||||
*/
|
||||
failOpen: boolean;
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { verifyCaptchaToken } from "./verify.js";
|
||||
|
||||
const base = {
|
||||
@@ -9,20 +9,21 @@ const base = {
|
||||
};
|
||||
|
||||
function jsonResponse(body: unknown, ok = true, status = 200): Response {
|
||||
return {
|
||||
ok,
|
||||
status,
|
||||
json: async () => body,
|
||||
} as unknown as Response;
|
||||
return new Response(JSON.stringify(body), {
|
||||
status: ok ? status : status || 500,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("verifyCaptchaToken", () => {
|
||||
it("returns true when mCaptcha reports valid", async () => {
|
||||
let calledUrl = "";
|
||||
let calledBody: unknown = null;
|
||||
let calledInit: RequestInit | undefined;
|
||||
const fetchImpl = (async (url: string, init?: RequestInit) => {
|
||||
calledUrl = url;
|
||||
calledBody = JSON.parse(String(init?.body));
|
||||
calledInit = init;
|
||||
return jsonResponse({ valid: true });
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
@@ -30,6 +31,7 @@ describe("verifyCaptchaToken", () => {
|
||||
expect(ok).toBe(true);
|
||||
expect(calledUrl).toBe("https://captcha.example.test/api/v1/pow/siteverify");
|
||||
expect(calledBody).toEqual({ token: "pow-token", key: "site-key", secret: "account-secret" });
|
||||
expect(calledInit?.redirect).toBe("manual");
|
||||
});
|
||||
|
||||
it("returns true when Cap reports success", async () => {
|
||||
@@ -62,11 +64,11 @@ describe("verifyCaptchaToken", () => {
|
||||
expect(await verifyCaptchaToken({ ...base, token: "", fetchImpl })).toBe(false);
|
||||
});
|
||||
|
||||
it("fails open (true) on network error by default", async () => {
|
||||
it("fails closed (false) on network error by default", async () => {
|
||||
const fetchImpl = (async () => {
|
||||
throw new Error("ECONNREFUSED");
|
||||
}) as unknown as typeof fetch;
|
||||
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(true);
|
||||
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(false);
|
||||
});
|
||||
|
||||
it("fails closed (false) on network error when failOpen=false", async () => {
|
||||
@@ -76,16 +78,40 @@ describe("verifyCaptchaToken", () => {
|
||||
expect(await verifyCaptchaToken({ ...base, failOpen: false, fetchImpl })).toBe(false);
|
||||
});
|
||||
|
||||
it("fails open on non-OK HTTP status", async () => {
|
||||
it("fails closed on non-OK HTTP status by default", async () => {
|
||||
const fetchImpl = (async () => jsonResponse({}, false, 502)) as unknown as typeof fetch;
|
||||
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(true);
|
||||
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(false);
|
||||
});
|
||||
|
||||
it("applies fail policy when misconfigured (no secret)", async () => {
|
||||
const fetchImpl = (async () => jsonResponse({ valid: true })) as unknown as typeof fetch;
|
||||
expect(await verifyCaptchaToken({ ...base, secret: undefined, fetchImpl })).toBe(true);
|
||||
expect(await verifyCaptchaToken({ ...base, secret: undefined, fetchImpl })).toBe(false);
|
||||
expect(await verifyCaptchaToken({ ...base, secret: undefined, failOpen: true, fetchImpl })).toBe(true);
|
||||
expect(
|
||||
await verifyCaptchaToken({ ...base, secret: undefined, failOpen: false, fetchImpl }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects non-HTTPS non-loopback instance URLs before fetch", async () => {
|
||||
const fetchImpl = vi.fn() as unknown as typeof fetch;
|
||||
expect(await verifyCaptchaToken({ ...base, instanceUrl: "http://captcha.example.test", fetchImpl })).toBe(false);
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows HTTP only for a loopback development instance", async () => {
|
||||
const fetchImpl = vi.fn(async () => jsonResponse({ valid: true })) as unknown as typeof fetch;
|
||||
expect(await verifyCaptchaToken({ ...base, instanceUrl: "http://127.0.0.1:7000", fetchImpl })).toBe(true);
|
||||
expect(fetchImpl).toHaveBeenCalledWith("http://127.0.0.1:7000/api/v1/pow/siteverify", expect.objectContaining({ redirect: "manual" }));
|
||||
});
|
||||
|
||||
it("fails closed when the provider response exceeds the hard limit", async () => {
|
||||
const fetchImpl = (async () => jsonResponse({ valid: true, padding: "x".repeat(70 * 1024) })) as unknown as typeof fetch;
|
||||
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects oversized challenge tokens before fetch", async () => {
|
||||
const fetchImpl = vi.fn() as unknown as typeof fetch;
|
||||
expect(await verifyCaptchaToken({ ...base, token: "x".repeat(9 * 1024), fetchImpl })).toBe(false);
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,11 @@ import type { CaptchaLogger, CaptchaProvider } from "./types.js";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 3_000;
|
||||
const MCAPTCHA_SITEVERIFY_PATH = "/api/v1/pow/siteverify";
|
||||
const MAX_RESPONSE_BYTES = 64 * 1024;
|
||||
const MAX_TOKEN_BYTES = 8 * 1024;
|
||||
const MAX_SITEKEY_BYTES = 1024;
|
||||
const MAX_SECRET_BYTES = 4 * 1024;
|
||||
const MAX_INSTANCE_URL_BYTES = 2048;
|
||||
|
||||
export type VerifyCaptchaArgs = {
|
||||
/** Challenge token produced by the captcha widget. */
|
||||
@@ -13,7 +18,7 @@ export type VerifyCaptchaArgs = {
|
||||
/** Base URL of the captcha instance. */
|
||||
instanceUrl: string | undefined;
|
||||
provider?: CaptchaProvider;
|
||||
/** Outage/misconfig policy: true (default) lets the request through. */
|
||||
/** Outage/misconfig policy: false (default) blocks the request. */
|
||||
failOpen?: boolean;
|
||||
logger?: CaptchaLogger;
|
||||
fetchImpl?: typeof fetch;
|
||||
@@ -33,7 +38,7 @@ export type VerifyCaptchaArgs = {
|
||||
*
|
||||
* Semantics:
|
||||
* - missing token -> false (real client failure, never fail-open)
|
||||
* - misconfigured / outage -> `failOpen` (default true), with a warn log
|
||||
* - misconfigured / outage -> `failOpen` (default false), with a warn log
|
||||
* - valid:true -> true, otherwise false
|
||||
*/
|
||||
export async function verifyCaptchaToken({
|
||||
@@ -42,12 +47,19 @@ export async function verifyCaptchaToken({
|
||||
secret,
|
||||
instanceUrl,
|
||||
provider = "mcaptcha",
|
||||
failOpen = true,
|
||||
failOpen = false,
|
||||
logger,
|
||||
fetchImpl = fetch,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
}: VerifyCaptchaArgs): Promise<boolean> {
|
||||
if (!instanceUrl || !secret || !sitekey) {
|
||||
if (
|
||||
!instanceUrl ||
|
||||
!secret ||
|
||||
!sitekey ||
|
||||
byteLength(instanceUrl) > MAX_INSTANCE_URL_BYTES ||
|
||||
byteLength(secret) > MAX_SECRET_BYTES ||
|
||||
byteLength(sitekey) > MAX_SITEKEY_BYTES
|
||||
) {
|
||||
logger?.warn(
|
||||
{
|
||||
op: "captcha.misconfigured",
|
||||
@@ -61,16 +73,18 @@ export async function verifyCaptchaToken({
|
||||
return failOpen;
|
||||
}
|
||||
|
||||
if (!token) return false;
|
||||
if (!token || byteLength(token) > MAX_TOKEN_BYTES) return false;
|
||||
|
||||
const url = buildSiteverifyUrl({ provider, instanceUrl, sitekey });
|
||||
const safeTimeoutMs = Number.isSafeInteger(timeoutMs) && timeoutMs >= 100 && timeoutMs <= 10_000 ? timeoutMs : DEFAULT_TIMEOUT_MS;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
||||
const timeout = setTimeout(() => controller.abort(), safeTimeoutMs);
|
||||
try {
|
||||
const url = buildSiteverifyUrl({ provider, instanceUrl, sitekey });
|
||||
const res = await fetchImpl(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(buildSiteverifyBody({ provider, token, sitekey, secret })),
|
||||
redirect: "manual",
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!res.ok) {
|
||||
@@ -80,14 +94,14 @@ export async function verifyCaptchaToken({
|
||||
);
|
||||
return failOpen;
|
||||
}
|
||||
const data = (await res.json()) as { valid?: boolean; success?: boolean };
|
||||
const data = (await readBoundedJson(res)) as { valid?: boolean; success?: boolean };
|
||||
return provider === "cap" ? data.success === true : data.valid === true;
|
||||
} catch (err) {
|
||||
logger?.warn(
|
||||
{
|
||||
op: "captcha.error",
|
||||
provider,
|
||||
err: err instanceof Error ? err.message : String(err),
|
||||
errorName: err instanceof Error ? err.name : "UnknownError",
|
||||
failOpen,
|
||||
},
|
||||
"captcha verification failed — applying fail policy",
|
||||
@@ -107,9 +121,61 @@ function buildSiteverifyUrl({
|
||||
instanceUrl: string;
|
||||
sitekey: string;
|
||||
}): string {
|
||||
const base = instanceUrl.replace(/\/+$/, "");
|
||||
if (provider === "cap") return `${base}/${encodeURIComponent(sitekey)}/siteverify`;
|
||||
return base + MCAPTCHA_SITEVERIFY_PATH;
|
||||
const url = new URL(instanceUrl);
|
||||
const isLoopback = url.hostname === "localhost" || url.hostname === "::1" || url.hostname === "[::1]" || url.hostname.startsWith("127.");
|
||||
if ((url.protocol !== "https:" && !(url.protocol === "http:" && isLoopback)) || url.username || url.password || url.search || url.hash) {
|
||||
throw new Error("Captcha instance URL is not allowed.");
|
||||
}
|
||||
const basePath = url.pathname.replace(/\/+$/u, "");
|
||||
url.pathname = provider === "cap" ? `${basePath}/${encodeURIComponent(sitekey)}/siteverify` : `${basePath}${MCAPTCHA_SITEVERIFY_PATH}`;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
async function readBoundedJson(response: Response): Promise<unknown> {
|
||||
const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
||||
if (contentType !== "application/json") {
|
||||
throw new Error("Captcha response is not JSON.");
|
||||
}
|
||||
const declaredLength = response.headers.get("content-length");
|
||||
if (declaredLength) {
|
||||
const parsedLength = Number(declaredLength);
|
||||
if (!Number.isSafeInteger(parsedLength) || parsedLength < 0 || parsedLength > MAX_RESPONSE_BYTES) {
|
||||
throw new Error("Captcha response is too large.");
|
||||
}
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new Error("Captcha response body is missing.");
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let totalBytes = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
totalBytes += value.byteLength;
|
||||
if (totalBytes > MAX_RESPONSE_BYTES) {
|
||||
await reader.cancel("captcha response too large");
|
||||
throw new Error("Captcha response is too large.");
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
const body = new Uint8Array(totalBytes);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
body.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return JSON.parse(new TextDecoder().decode(body));
|
||||
}
|
||||
|
||||
function byteLength(value: string): number {
|
||||
return Buffer.byteLength(value, "utf8");
|
||||
}
|
||||
|
||||
function buildSiteverifyBody({
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
+67
@@ -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)");
|
||||
});
|
||||
});
|
||||
+447
@@ -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;
|
||||
}
|
||||
+252
@@ -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();
|
||||
});
|
||||
});
|
||||
+228
@@ -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];
|
||||
}
|
||||
+151
@@ -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
File diff suppressed because it is too large.
Load diff
+143
@@ -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] } } });
|
||||
}
|
||||
+551
@@ -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 & 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;
|
||||
}
|
||||
+116
@@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
+115
@@ -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}`;
|
||||
}
|
||||
+168
@@ -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] } } });
|
||||
}
|
||||
+143
@@ -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("?") : "";
|
||||
}
|
||||
+315
@@ -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}`);
|
||||
}
|
||||
+31
@@ -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",
|
||||
});
|
||||
}
|
||||
+149
@@ -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] } } });
|
||||
}
|
||||
+445
@@ -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" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+832
@@ -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;
|
||||
+101
@@ -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] } } });
|
||||
}
|
||||
+315
@@ -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();
|
||||
});
|
||||
});
|
||||
+510
@@ -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;
|
||||
}
|
||||
+40
@@ -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];
|
||||
+75
@@ -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;
|
||||
}
|
||||
+636
@@ -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));
|
||||
}
|
||||
+327
@@ -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 } });
|
||||
}
|
||||
+92
@@ -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}`;
|
||||
}
|
||||
+915
@@ -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] } } });
|
||||
}
|
||||
+1547
File diff suppressed because it is too large.
Load diff
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;
|
||||
}
|
||||
+184
@@ -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);
|
||||
}
|
||||
+223
@@ -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] } } });
|
||||
}
|
||||
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user