Refresh HiveGrid Cloud reference snapshot

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

No files matched your search

@@ -0,0 +1,155 @@
// @vitest-environment node
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/components/screens/admin/AdminSupportTicketPage", () => ({ AdminSupportTicketPage: () => null }));
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
vi.mock("~/services/admin/admin-identity.server", () => ({
requireAdminIdentityPermission: vi.fn(),
}));
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: vi.fn() }));
vi.mock("~/utils/db.server", () => ({
db: {
supportTicket: { findUnique: vi.fn() },
adminUser: { findMany: vi.fn() },
},
}));
vi.mock("~/services/admin/support-inbox.server", async () => {
const actual = await vi.importActual<typeof import("~/services/admin/support-inbox.server")>("~/services/admin/support-inbox.server");
return {
...actual,
postSupportReply: vi.fn(),
postSupportInternalNote: vi.fn(),
setSupportTicketStatus: vi.fn(),
assignSupportTicket: vi.fn(),
};
});
import { getTranslations } from "~/locale/i18next.server";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { getUser } from "~/utils/db/users.db.server";
import { db } from "~/utils/db.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { assignSupportTicket, postSupportInternalNote, postSupportReply, setSupportTicketStatus } from "~/services/admin/support-inbox.server";
import { action, loader } from "./$id";
const TICKET = {
id: "ticket_1",
createdAt: new Date("2026-07-01T10:00:00.000Z"),
subject: "Upload geht nicht",
message: "Der Upload bricht ab.",
status: "open",
priority: "high",
source: "in_app_feedback_widget",
fromEmail: null,
assignedToUserId: null,
tenant: { name: "Acme" },
user: { email: "kunde@example.test" },
messages: [
{
id: "msg_1",
createdAt: new Date("2026-07-02T10:00:00.000Z"),
internalNote: true,
body: "Interne Einschätzung",
author: { id: "admin_1", email: "op@example.test" },
},
],
};
function loaderArgs(): LoaderFunctionArgs {
return {
request: new Request("https://admin.example.test/support/ticket_1"),
params: { id: "ticket_1" },
context: {},
} as LoaderFunctionArgs;
}
function actionArgs(body: URLSearchParams): ActionFunctionArgs {
return {
request: new Request("https://admin.example.test/support/ticket_1", { method: "POST", body }),
params: { id: "ticket_1" },
context: {},
} as ActionFunctionArgs;
}
describe("admin support ticket detail", () => {
beforeEach(() => {
vi.clearAllMocks();
process.env.APP_NAME = "HiveGrid";
vi.mocked(requireAdminIdentityPermission).mockResolvedValue({
adminUserId: "admin_1",
} as never);
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
vi.mocked(getUserInfo).mockResolvedValue({ userId: "admin_1" } as never);
vi.mocked(getUser).mockResolvedValue({ id: "admin_1", email: "op@example.test" } as never);
vi.mocked(db.supportTicket.findUnique).mockResolvedValue(TICKET as never);
vi.mocked(db.adminUser.findMany).mockResolvedValue([{ id: "admin_1", email: "op@example.test" }] as never);
});
it("requires admin auth and builds the conversation with the inbound message first", async () => {
const data = await loader(loaderArgs());
expect(requireAdminIdentityPermission).toHaveBeenCalledWith(
expect.any(Request),
"admin_identity.impersonation.start"
);
expect(data.vm.status).toBe("ready");
const messages = data.vm.status === "ready" ? data.vm.data.messages : [];
expect(messages).toHaveLength(2);
expect(messages[0]).toMatchObject({ kind: "inbound", body: "Der Upload bricht ab." });
expect(messages[1]).toMatchObject({ kind: "internalNote", authorLabel: "op@example.test" });
expect(data.assignees).toEqual([{ id: "admin_1", email: "op@example.test" }]);
});
it("posts a reply through the audited service", async () => {
const response = (await action(actionArgs(new URLSearchParams({ action: "reply", body: "Wir schauen drauf." })))) as Response;
expect(postSupportReply).toHaveBeenCalledWith(
expect.objectContaining({ ticketId: "ticket_1", authorUserId: "admin_1", body: "Wir schauen drauf." })
);
expect(response.status).toBe(200);
});
it("adds internal notes, sets status, and assigns via the services", async () => {
await action(actionArgs(new URLSearchParams({ action: "internal-note", body: "Nur intern." })));
expect(postSupportInternalNote).toHaveBeenCalledWith(expect.objectContaining({ body: "Nur intern." }));
await action(actionArgs(new URLSearchParams({ action: "set-status", status: "closed" })));
expect(setSupportTicketStatus).toHaveBeenCalledWith(expect.objectContaining({ status: "closed" }));
await action(actionArgs(new URLSearchParams({ action: "assign", assigneeUserId: "unassigned" })));
expect(assignSupportTicket).toHaveBeenCalledWith(expect.objectContaining({ assigneeUserId: null }));
});
it("rejects unknown actions with a Klartext error", async () => {
const response = (await action(actionArgs(new URLSearchParams({ action: "nope" })))) as Response;
expect(response.status).toBe(400);
});
// AK-P21 — the operator download link only appears for a cleared file. The
// proxy re-checks the verdict; this keeps the UI from offering a link that
// would 404 while the scan is still running.
it("offers a download link only for a scanned-clean attachment", async () => {
vi.mocked(db.supportTicket.findUnique).mockResolvedValue({ ...TICKET, tenantId: "tenant_1" } as never);
vi.mocked(withTenantRLS).mockImplementation((async (_tenantId: string, run: (tx: unknown) => unknown) =>
run({
fileEntityLink: {
findMany: vi.fn().mockResolvedValue([
{ file: { id: "file_clean", displayName: "a.png", mimeType: "image/png", sizeBytes: 10, scanStatus: "clean" } },
{ file: { id: "file_pending", displayName: "b.png", mimeType: "image/png", sizeBytes: 10, scanStatus: "pending" } },
]),
},
})) as never);
const data = await loader(loaderArgs());
expect(data.attachments[0].downloadHref).toContain("support/attachments/ticket_1/file_clean");
expect(data.attachments[1].downloadHref).toBeNull();
});
});
@@ -0,0 +1,244 @@
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData, useNavigation } from "react-router";
import { buildSupportConversationVM, type SupportConversationVM } from "@hivegrid/view-models";
import {
AdminSupportTicketPage,
type AdminSupportAssigneeOption,
type AdminSupportTicketMeta,
} from "~/components/screens/admin/AdminSupportTicketPage";
import ServerError from "~/components/ui/errors/ServerError";
import { getTranslations } from "~/locale/i18next.server";
import { redactFeedbackText } from "~/modules/helpDesk/services/FeedbackRedaction";
import { AdminActionInputError } from "~/services/admin/admin-action-audit.server";
import {
assignSupportTicket,
postSupportInternalNote,
postSupportReply,
setSupportTicketStatus,
SUPPORT_TICKET_STATUSES,
SupportInboxError,
} from "~/services/admin/support-inbox.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { useRootData } from "~/utils/data/useRootData";
import { db } from "~/utils/db.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { getUser } from "~/utils/db/users.db.server";
import { isFileScanDeliverable } from "~/utils/integrations/fileScanPolicy";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
/** AK-P21 — feedback attachment as shown to the operator. */
export type AdminSupportTicketAttachment = {
id: string;
displayName: string;
mimeType: string;
sizeBytes: number;
scanStatus: string;
downloadHref: string | null;
};
type LoaderData = {
title: string;
vm: SupportConversationVM;
meta: AdminSupportTicketMeta;
assignees: AdminSupportAssigneeOption[];
statuses: readonly string[];
attachments: AdminSupportTicketAttachment[];
};
type ActionData = {
success?: string;
error?: string;
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
async function loadTicket(ticketId: string) {
return db.supportTicket.findUnique({
where: { id: ticketId },
select: {
id: true,
createdAt: true,
subject: true,
message: true,
status: true,
priority: true,
source: true,
fromEmail: true,
assignedToUserId: true,
tenantId: true,
tenant: { select: { name: true } },
user: { select: { email: true } },
messages: {
orderBy: { createdAt: "asc" },
select: {
id: true,
createdAt: true,
internalNote: true,
body: true,
author: { select: { id: true, email: true } },
},
},
},
});
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAdminIdentityPermission(request, ADMIN_AREA_ACCESS.support);
const ticketId = params.id;
if (!ticketId) {
throw redirect(adminPath("support", { mode: "host-aware" }));
}
const ticket = await loadTicket(ticketId);
if (!ticket) {
throw redirect(adminPath("support", { mode: "host-aware" }));
}
const adminUsers = await db.adminUser.findMany({
where: { status: "active" },
select: { id: true, email: true },
orderBy: { email: "asc" },
});
// AK-P21 — feedback attachments hang off FileEntityLink, which (unlike
// SupportTicket) has NO operator escape in its RLS policy: it is strictly
// tenant-bound. So bind the one tenant this ticket belongs to instead of
// reading across tenants. A tenant-less ticket can never carry an
// attachment, because File.tenantId is NOT NULL.
const attachments = ticket.tenantId
? await withTenantRLS(ticket.tenantId, (tx) =>
tx.fileEntityLink.findMany({
where: { tenantId: ticket.tenantId!, entityType: "support_ticket", entityId: ticket.id },
select: { file: { select: { id: true, displayName: true, mimeType: true, sizeBytes: true, scanStatus: true } } },
orderBy: { createdAt: "asc" },
})
)
: [];
const vm = buildSupportConversationVM({
ticketId: ticket.id,
subject: redactFeedbackText(ticket.subject),
status: ticket.status,
priority: ticket.priority,
messages: [
// The ticket's original message opens the thread as the inbound customer message.
{
id: `${ticket.id}-inbound`,
createdAtIso: ticket.createdAt.toISOString(),
internalNote: false,
authorEmail: null,
authorId: null,
body: redactFeedbackText(ticket.message),
},
...ticket.messages.map((message) => ({
id: message.id,
createdAtIso: message.createdAt.toISOString(),
internalNote: message.internalNote,
authorEmail: message.author?.email ?? null,
authorId: message.author?.id ?? null,
body: message.body,
})),
],
});
return {
title: `${redactFeedbackText(ticket.subject)} | ${process.env.APP_NAME}`,
vm,
meta: {
tenantName: ticket.tenant?.name ?? null,
userEmail: ticket.user?.email ?? null,
fromEmail: ticket.fromEmail,
source: ticket.source,
createdAtIso: ticket.createdAt.toISOString(),
status: ticket.status,
priority: ticket.priority,
assignedToUserId: ticket.assignedToUserId,
},
attachments: attachments.map((link) => ({
id: link.file.id,
displayName: link.file.displayName,
mimeType: link.file.mimeType,
sizeBytes: link.file.sizeBytes,
scanStatus: link.file.scanStatus,
// Offer the download only once the scanner cleared the file. The route
// re-checks this — the null here just avoids showing a link that would
// 404 anyway.
downloadHref: isFileScanDeliverable(link.file.scanStatus)
? adminPath(`support/attachments/${ticket.id}/${link.file.id}`, { mode: "host-aware" })
: null,
})),
assignees: adminUsers.map((adminUser) => ({ id: adminUser.id, email: adminUser.email })),
statuses: SUPPORT_TICKET_STATUSES,
} satisfies LoaderData;
};
function badRequest(data: ActionData) {
return Response.json(data, { status: 400 });
}
export const action = async ({ request, params }: ActionFunctionArgs) => {
await requireAdminIdentityPermission(request, ADMIN_AREA_ACCESS.support);
const { t } = await getTranslations(request);
await validateCSRFToken(request);
const ticketId = params.id;
if (!ticketId) {
throw redirect(adminPath("support", { mode: "host-aware" }));
}
const ticket = await db.supportTicket.findUnique({ where: { id: ticketId }, select: { id: true } });
if (!ticket) {
throw redirect(adminPath("support", { mode: "host-aware" }));
}
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const userInfo = await getUserInfo(request);
const actor = await getUser(userInfo.userId);
const base = { ticketId, actorUserId: userInfo.userId, actorEmail: actor?.email ?? null, request };
try {
if (action === "reply") {
await postSupportReply({ ...base, authorUserId: userInfo.userId, body: form.get("body")?.toString() ?? "" });
return Response.json({ success: t("admin.support.actions.replied") } satisfies ActionData);
}
if (action === "internal-note") {
await postSupportInternalNote({ ...base, authorUserId: userInfo.userId, body: form.get("body")?.toString() ?? "" });
return Response.json({ success: t("admin.support.actions.noteAdded") } satisfies ActionData);
}
if (action === "set-status") {
await setSupportTicketStatus({ ...base, status: form.get("status")?.toString() ?? "" });
return Response.json({ success: t("admin.support.actions.statusChanged") } satisfies ActionData);
}
if (action === "assign") {
const assigneeRaw = form.get("assigneeUserId")?.toString() ?? "";
await assignSupportTicket({ ...base, assigneeUserId: assigneeRaw === "unassigned" || assigneeRaw === "" ? null : assigneeRaw });
return Response.json({ success: t("admin.support.actions.assigned") } satisfies ActionData);
}
return badRequest({ error: t("shared.invalidForm") });
} catch (error) {
if (error instanceof SupportInboxError || error instanceof AdminActionInputError) {
return badRequest({ error: t(error.i18nKey) });
}
throw error;
}
};
export default function AdminSupportTicketRoute() {
const data = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
const navigation = useNavigation();
const rootData = useRootData();
return (
<AdminSupportTicketPage
vm={data.vm}
meta={data.meta}
assignees={data.assignees}
statuses={data.statuses}
csrf={rootData.csrf ?? ""}
submitting={navigation.state === "submitting"}
feedback={actionData}
attachments={data.attachments}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
@@ -0,0 +1,160 @@
// @vitest-environment node
//
// AK-P21 — the operator attachment proxy is a security surface, so the tests
// are written around the denial paths, not the happy path: every rejection
// must answer 404 (never 403) and must never reach the signer.
import type { LoaderFunctionArgs } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/services/admin/admin-identity.server", () => ({
requireAdminIdentityPermission: vi.fn(),
}));
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn() }));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
vi.mock("~/utils/db.server", () => ({ db: { supportTicket: { findUnique: vi.fn() } } }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: vi.fn() }));
vi.mock("~/utils/integrations/mediaSigning.server", () => ({ createMediaDownloadUrl: vi.fn() }));
vi.mock("~/services/admin/admin-action-audit.server", () => ({ recordAdminAction: vi.fn() }));
vi.mock("@hivegrid/storage", () => ({ assertFileKeyBelongsToTenant: vi.fn() }));
import { assertFileKeyBelongsToTenant } from "@hivegrid/storage";
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
import { db } from "~/utils/db.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { getUser } from "~/utils/db/users.db.server";
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { getUserInfo } from "~/utils/session.server";
import { loader } from "./attachments.$ticketId.$fileId";
const CLEAN_FILE = {
id: "file_1",
displayName: "bug.png",
mimeType: "image/png",
storageKey: "tenants/tenant_1/files/file_1",
scanStatus: "clean",
archivedAt: null,
};
function args(): LoaderFunctionArgs {
return {
request: new Request("https://admin.example.test/support/attachments/ticket_1/file_1"),
params: { ticketId: "ticket_1", fileId: "file_1" },
context: {},
} as LoaderFunctionArgs;
}
/** The loader signals every denial by throwing a 404 Response. */
async function statusOf(): Promise<number> {
try {
await loader(args());
} catch (error) {
if (error instanceof Response) return error.status;
throw error;
}
return 200;
}
function linkResolves(file: unknown): void {
vi.mocked(withTenantRLS).mockImplementation((async (_tenantId: string, run: (tx: unknown) => unknown) =>
run({ fileEntityLink: { findFirst: vi.fn().mockResolvedValue(file === null ? null : { file }) } })) as never);
}
describe("admin support attachment proxy", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(requireAdminIdentityPermission).mockResolvedValue({
adminUserId: "admin_1",
} as never);
vi.mocked(getUserInfo).mockResolvedValue({ userId: "admin_1" } as never);
vi.mocked(getUser).mockResolvedValue({ id: "admin_1", email: "op@example.test" } as never);
vi.mocked(db.supportTicket.findUnique).mockResolvedValue({ id: "ticket_1", tenantId: "tenant_1" } as never);
vi.mocked(createMediaDownloadUrl).mockResolvedValue("https://storage.example.test/signed");
linkResolves(CLEAN_FILE);
});
it("redirects a platform admin to a short-lived signed URL", async () => {
const response = (await loader(args())) as Response;
expect(requireAdminIdentityPermission).toHaveBeenCalledWith(
expect.any(Request),
"admin_identity.impersonation.start"
);
expect(response.status).toBe(302);
expect(response.headers.get("location")).toBe("https://storage.example.test/signed");
expect(createMediaDownloadUrl).toHaveBeenCalledWith({ key: CLEAN_FILE.storageKey, filename: "bug.png" });
});
it("binds the owning tenant, because FileEntityLink has no operator escape in its policy", async () => {
await loader(args());
expect(withTenantRLS).toHaveBeenCalledWith("tenant_1", expect.any(Function));
});
it("audits the read before handing out the URL", async () => {
await loader(args());
expect(recordAdminAction).toHaveBeenCalledWith(
expect.objectContaining({
action: "support.attachmentDownloaded",
actorUserId: "admin_1",
targetId: "ticket_1",
extraMeta: expect.objectContaining({ fileId: "file_1", fileTenantId: "tenant_1" }),
})
);
const auditOrder = vi.mocked(recordAdminAction).mock.invocationCallOrder[0];
const signOrder = vi.mocked(createMediaDownloadUrl).mock.invocationCallOrder[0];
expect(auditOrder).toBeLessThan(signOrder);
});
it("refuses the download when the read cannot be audited", async () => {
vi.mocked(recordAdminAction).mockRejectedValueOnce(new Error("audit chain unavailable"));
await expect(loader(args())).rejects.toThrow("audit chain unavailable");
expect(createMediaDownloadUrl).not.toHaveBeenCalled();
});
it("answers 404 for a non-admin instead of 403", async () => {
vi.mocked(requireAdminIdentityPermission).mockRejectedValueOnce(
new Response("Not found", { status: 404 })
);
expect(await statusOf()).toBe(404);
expect(createMediaDownloadUrl).not.toHaveBeenCalled();
});
it("answers 404 for a file that is not linked to this ticket", async () => {
linkResolves(null);
expect(await statusOf()).toBe(404);
expect(createMediaDownloadUrl).not.toHaveBeenCalled();
});
it.each([
["pending", { ...CLEAN_FILE, scanStatus: "pending" }],
["infected", { ...CLEAN_FILE, scanStatus: "infected" }],
["skipped", { ...CLEAN_FILE, scanStatus: "skipped" }],
["archived", { ...CLEAN_FILE, archivedAt: new Date() }],
])("answers 404 for a %s file", async (_label, file) => {
linkResolves(file);
expect(await statusOf()).toBe(404);
expect(createMediaDownloadUrl).not.toHaveBeenCalled();
});
it("answers 404 when the storage key does not belong to the tenant", async () => {
vi.mocked(assertFileKeyBelongsToTenant).mockImplementationOnce(() => {
throw new Error("Storage key does not belong to tenant (foreign_prefix).");
});
expect(await statusOf()).toBe(404);
expect(createMediaDownloadUrl).not.toHaveBeenCalled();
});
it("answers 404 for a tenant-less ticket, which can never carry an attachment", async () => {
vi.mocked(db.supportTicket.findUnique).mockResolvedValue({ id: "ticket_1", tenantId: null } as never);
expect(await statusOf()).toBe(404);
expect(withTenantRLS).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,132 @@
// AK-P21 — operator download for a feedback attachment (AD-23 auth proxy).
//
// The tenant media proxy (`app/:tenant/media/...`) cannot serve this: a
// platform operator is not necessarily a member of the tenant that owns the
// file, so that route's membership check would deny it. This is the operator
// counterpart, and it is deliberately NARROWER than a general operator file
// proxy — it serves ONLY a file that is linked to the named support ticket,
// never an arbitrary tenant file.
//
// Order of checks is the security contract, and it is fail-closed at each
// step. Every denial answers 404, never 403 (Bauprinzip A.5.3): an operator
// probing ids learns nothing about what exists.
//
// 1. platform-admin identity -> else 404
// 2. ticket exists and is tenant-bound -> else 404
// 3. file is LINKED to exactly this ticket-> else 404 (no arbitrary access)
// 4. file is not archived -> else 404
// 5. scanner verdict is explicitly clean -> else 404 (fail-closed, §13)
// 6. storage key belongs to that tenant -> else 404 (defense in depth)
// 7. audit the read -> throws, so no URL is handed out
// 8. redirect to a short-lived signed URL
//
// Step 7 before step 8 on purpose: an operator read of customer-uploaded
// material that cannot be audited must not happen at all.
import type { LoaderFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { assertFileKeyBelongsToTenant } from "@hivegrid/storage";
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
import { db } from "~/utils/db.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { getUser } from "~/utils/db/users.db.server";
import { isFileScanDeliverable } from "~/utils/integrations/fileScanPolicy";
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
import { getUserInfo } from "~/utils/session.server";
/**
* Recorded as the audit `reason`. Unlike the destructive operator actions,
* opening an attachment carries no operator-typed justification: it is a read
* reached by clicking the file in the ticket the operator is already working.
* The constant keeps that context honest in the log instead of pretending a
* reason was given.
*/
const DOWNLOAD_AUDIT_REASON = "Attachment opened from the support ticket detail view";
/**
* Every denial leaves through here. The body stays empty on purpose: this is a
* redirect endpoint, never a rendered page, so there is no user-facing text to
* translate — and a bodyless 404 tells a probing caller nothing about which of
* the checks above rejected it.
*/
function notFound(): never {
throw new Response(null, { status: 404 });
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
try {
await requireAdminIdentityPermission(request, ADMIN_AREA_ACCESS.support);
} catch {
notFound();
}
const ticketId = params.ticketId;
const fileId = params.fileId;
if (!ticketId || !fileId) {
notFound();
}
const ticket = await db.supportTicket.findUnique({
where: { id: ticketId },
select: { id: true, tenantId: true },
});
// A tenant-less ticket can never carry an attachment: File.tenantId is NOT NULL.
if (!ticket?.tenantId) {
notFound();
}
const tenantId = ticket.tenantId;
// FileEntityLink has no operator escape in its RLS policy (unlike
// SupportTicket) — it is strictly tenant-bound, so bind the owning tenant.
// Matching on fileId AND the ticket link is what keeps this route from
// becoming a general "operator reads any tenant file" hole.
const link = await withTenantRLS(tenantId, (tx) =>
tx.fileEntityLink.findFirst({
where: { tenantId, entityType: "support_ticket", entityId: ticket.id, fileId },
select: {
file: {
select: { id: true, displayName: true, mimeType: true, storageKey: true, scanStatus: true, archivedAt: true },
},
},
})
);
if (!link || link.file.archivedAt) {
notFound();
}
// Fail closed: only an explicit clean verdict is deliverable. Pending means
// ClamAV has not answered yet, and infected obviously never becomes a link.
if (!isFileScanDeliverable(link.file.scanStatus)) {
notFound();
}
try {
assertFileKeyBelongsToTenant(tenantId, link.file.storageKey, "download");
} catch {
notFound();
}
const userInfo = await getUserInfo(request);
const actor = await getUser(userInfo.userId);
// recordAdminAction propagates on failure — an unauditable read is refused.
await recordAdminAction({
action: "support.attachmentDownloaded",
actorUserId: userInfo.userId,
actorEmail: actor?.email ?? null,
targetKind: "SupportTicket",
targetId: ticket.id,
reason: DOWNLOAD_AUDIT_REASON,
request,
extraMeta: {
fileId: link.file.id,
fileTenantId: tenantId,
displayName: link.file.displayName,
mimeType: link.file.mimeType,
},
});
const url = await createMediaDownloadUrl({ key: link.file.storageKey, filename: link.file.displayName });
return redirect(url, 302);
};
@@ -0,0 +1,98 @@
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
import { FeedbackWithDetails, getAllFeedback } from "~/modules/helpDesk/db/feedback.db.server";
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
import FeedbackServer from "~/modules/helpDesk/services/Feedback.server";
import FeedbackTable from "~/modules/helpDesk/components/FeedbackTable";
import { useTranslation } from "react-i18next";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
import { validateCSRFToken } from "~/utils/session.server";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = {
items: FeedbackWithDetails[];
filterableProperties: FilterablePropertyDto[];
pagination: PaginationDto;
};
type ActionData = { intent: "delete"; ok?: true; messageKey?: string; messageValues?: { count: number }; errorKey?: string };
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
void params;
await requireAdminIdentityPermission(request, ADMIN_AREA_ACCESS.support);
const filterableProperties: FilterablePropertyDto[] = [
{
name: "tenantId",
title: "models.tenant.object",
options: [
{ value: "null", name: "{null}" },
...(await adminGetAllTenantsIdsAndNames()).map((item) => {
return {
value: item.id,
name: item.name,
};
}),
],
},
{
name: "userId",
title: "models.user.object",
options: [
{ value: "null", name: "{null}" },
...(await adminGetAllUsersNames()).map((item) => {
return {
value: item.id,
name: item.email,
};
}),
],
},
];
const urlSearchParams = new URL(request.url).searchParams;
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
const { items, pagination } = await getAllFeedback({ filters, filterableProperties, pagination: currentPagination });
const data: LoaderData = {
items,
filterableProperties,
pagination,
};
return Response.json(data);
};
export const action: ActionFunction = async ({ request, params }) => {
void params;
await requireAdminIdentityPermission(request, ADMIN_AREA_ACCESS.support);
await validateCSRFToken(request);
const form = await request.formData();
if (form.get("action") === "delete") {
const ids = (form.get("ids")?.toString().split(",") ?? []).map((x) => x.toString() ?? "");
try {
await FeedbackServer.deleteMany({ ids });
return Response.json({ intent: "delete", ok: true, messageKey: "feedback.toast.deleted", messageValues: { count: ids.length } } satisfies ActionData);
} catch {
return Response.json({ intent: "delete", errorKey: "feedback.deleteFailed" } satisfies ActionData, { status: 400 });
}
} else {
return Response.json({ intent: "delete", errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
}
};
export default function () {
const { t } = useTranslation();
const data = useLoaderData<LoaderData>();
const actionData = useActionData<ActionData>();
useSaveToast(actionData);
return (
<div className="flex w-full flex-col">
<AdminPageHeader title={t("feedback.plural")} description={t("admin.supportInbox.feedback.description")} />
<div className="mobile:px-4 w-full space-y-3 px-6 py-6">
<FeedbackTable data={data} />
</div>
</div>
);
}
@@ -0,0 +1,73 @@
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
import { AdminSupportInboxPage } from "~/components/screens/admin/AdminSupportInboxPage";
import ServerError from "~/components/ui/errors/ServerError";
import { getTranslations } from "~/locale/i18next.server";
import { redactFeedbackText } from "~/modules/helpDesk/services/FeedbackRedaction";
import { db } from "~/utils/db.server";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
type LoaderData = {
title: string;
summary: { ticketsTotal: number; feedbackTotal: number; openTickets: number; assignedTickets: number; urgentTickets: number };
ticketsByStatus: { status: string; count: number }[];
recentTickets: { id: string; subject: string; status: string; priority: string; source: string; createdAt: string; tenantName: string | null; userEmail: string | null }[];
recentFeedback: { id: string; message: string; createdAt: string; tenantName: string | null; userEmail: string | null }[];
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
void params;
await requireAdminIdentityPermission(request, ADMIN_AREA_ACCESS.support);
const { t } = await getTranslations(request);
const [ticketsTotal, feedbackTotal, openTickets, assignedTickets, urgentTickets, ticketsByStatus, recentTickets, recentFeedback] = await Promise.all([
db.supportTicket.count(),
db.feedback.count(),
db.supportTicket.count({ where: { status: "open" } }),
db.supportTicket.count({ where: { assignedToUserId: { not: null } } }),
db.supportTicket.count({ where: { priority: { in: ["high", "urgent"] } } }),
db.supportTicket.groupBy({ by: ["status"], _count: { _all: true } }),
db.supportTicket.findMany({
orderBy: { createdAt: "desc" },
take: 8,
select: { id: true, subject: true, status: true, priority: true, source: true, createdAt: true, tenant: { select: { name: true } }, user: { select: { email: true } } },
}),
db.feedback.findMany({
orderBy: { createdAt: "desc" },
take: 8,
select: { id: true, message: true, createdAt: true, tenant: { select: { name: true } }, user: { select: { email: true } } },
}),
]);
return {
title: `${t("admin.supportInbox.title")} | ${process.env.APP_NAME}`,
summary: { ticketsTotal, feedbackTotal, openTickets, assignedTickets, urgentTickets },
ticketsByStatus: ticketsByStatus.map((row) => ({ status: row.status, count: row._count._all })),
recentTickets: recentTickets.map((ticket) => ({
id: ticket.id,
subject: redactFeedbackText(ticket.subject),
status: ticket.status,
priority: ticket.priority,
source: ticket.source,
createdAt: ticket.createdAt.toISOString(),
tenantName: ticket.tenant?.name ?? null,
userEmail: ticket.user?.email ?? null,
})),
recentFeedback: recentFeedback.map((feedback) => ({
id: feedback.id,
message: redactFeedbackText(feedback.message),
createdAt: feedback.createdAt.toISOString(),
tenantName: feedback.tenant?.name ?? null,
userEmail: feedback.user?.email ?? null,
})),
} satisfies LoaderData;
};
export default function HelpDeskOverviewRoute() {
return <AdminSupportInboxPage vm={useLoaderData<LoaderData>()} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
@@ -0,0 +1,71 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
verifyUserHasPermission: vi.fn(),
getTranslations: vi.fn(),
getUserInfo: vi.fn(),
getKwpContractAdminSnapshot: vi.fn(),
buildKwpContractAdminVM: vi.fn(),
}));
vi.mock("@hivegrid/view-models", () => ({
buildKwpContractAdminVM: mocks.buildKwpContractAdminVM,
}));
vi.mock("~/components/screens/admin/AdminKwpContractsPage", () => ({
AdminKwpContractsPage: () => null,
}));
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: mocks.getTranslations,
}));
vi.mock("~/services/admin/kwp-contract-admin.server", () => ({
getKwpContractAdminSnapshot: mocks.getKwpContractAdminSnapshot,
}));
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
verifyUserHasPermission: mocks.verifyUserHasPermission,
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: mocks.getUserInfo,
}));
import { loader } from "./kwp-contracts";
beforeEach(() => {
vi.clearAllMocks();
mocks.verifyUserHasPermission.mockResolvedValue(true);
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
mocks.getUserInfo.mockResolvedValue({ userId: "operator-1" });
mocks.getKwpContractAdminSnapshot.mockResolvedValue([]);
mocks.buildKwpContractAdminVM.mockReturnValue({ status: "empty" });
});
describe("admin KWP contract alarms", () => {
it("returns 404 instead of exposing the route to an unauthorized user", async () => {
mocks.verifyUserHasPermission.mockRejectedValueOnce(new Error("denied"));
await expect(loader({
request: new Request("https://admin.example.test/support/kwp-contracts"),
params: {},
context: {},
} as never)).rejects.toMatchObject({ status: 404 });
expect(mocks.getKwpContractAdminSnapshot).not.toHaveBeenCalled();
});
it("loads only after the operator permission gate", async () => {
await expect(loader({
request: new Request("https://admin.example.test/support/kwp-contracts"),
params: {},
context: {},
} as never)).resolves.toMatchObject({
vm: { status: "empty" },
});
expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(
expect.any(Request),
"admin.metrics.view",
);
expect(mocks.verifyUserHasPermission.mock.invocationCallOrder[0]).toBeLessThan(
mocks.getKwpContractAdminSnapshot.mock.invocationCallOrder[0]!,
);
});
});
@@ -0,0 +1,59 @@
import { buildKwpContractAdminVM, type KwpContractAdminVM } from "@hivegrid/view-models";
import {
useLoaderData,
type LoaderFunctionArgs,
type MetaFunction,
} from "react-router";
import { AdminKwpContractsPage } from "~/components/screens/admin/AdminKwpContractsPage";
import ServerError from "~/components/ui/errors/ServerError";
import { getTranslations } from "~/locale/i18next.server";
import { getKwpContractAdminSnapshot } from "~/services/admin/kwp-contract-admin.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import { getUserInfo } from "~/utils/session.server";
type LoaderData = {
title: string;
vm: KwpContractAdminVM;
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export const loader = async ({ request }: LoaderFunctionArgs) => {
try {
await verifyUserHasPermission(request, "admin.metrics.view");
} catch {
throw new Response(null, { status: 404 });
}
const [{ t }, user] = await Promise.all([
getTranslations(request),
getUserInfo(request),
]);
try {
const snapshot = await getKwpContractAdminSnapshot(user.userId);
return {
title: `${t("admin.kwpContracts.title")} | ${process.env.APP_NAME}`,
vm: buildKwpContractAdminVM(snapshot),
} satisfies LoaderData;
} catch {
return {
title: `${t("admin.kwpContracts.title")} | ${process.env.APP_NAME}`,
vm: {
status: "error",
error: {
messageKey: "admin.kwpContracts.error.body",
code: "KWP_CONTRACTS_UNAVAILABLE",
},
},
} satisfies LoaderData;
}
};
export default function AdminKwpContractsRoute() {
const data = useLoaderData<LoaderData>();
return <AdminKwpContractsPage vm={data.vm} />;
}
export function ErrorBoundary() {
return <ServerError />;
}
@@ -0,0 +1,93 @@
import { Link, LoaderFunctionArgs, useLoaderData } from "react-router";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
import TableSimple from "~/components/ui/tables/TableSimple";
import { getAllSupportTickets, SupportTicketWithDetails } from "~/modules/helpDesk/db/supportTickets.db.server";
import { redactFeedbackText } from "~/modules/helpDesk/services/FeedbackRedaction";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
import { useTranslation } from "react-i18next";
import { useLocaleFormatters } from "~/locale/format";
type LoaderData = {
items: SupportTicketWithDetails[];
filterableProperties: FilterablePropertyDto[];
pagination: PaginationDto;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
void params;
await requireAdminIdentityPermission(request, ADMIN_AREA_ACCESS.support);
const filterableProperties: FilterablePropertyDto[] = [
{
name: "tenantId",
title: "models.tenant.object",
options: [{ value: "null", name: "{null}" }, ...(await adminGetAllTenantsIdsAndNames()).map((item) => ({ value: item.id, name: item.name }))],
},
{
name: "userId",
title: "models.user.object",
options: [{ value: "null", name: "{null}" }, ...(await adminGetAllUsersNames()).map((item) => ({ value: item.id, name: item.email }))],
},
];
const urlSearchParams = new URL(request.url).searchParams;
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
return Response.json({
...(await getAllSupportTickets({ filters, filterableProperties, pagination })),
filterableProperties,
} satisfies LoaderData);
};
export default function HelpDeskTicketsRoute() {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const data = useLoaderData<LoaderData>();
return (
<div className="flex w-full flex-col">
<AdminPageHeader title={t("helpDesk.tickets.plural")} description={t("admin.supportInbox.tickets.description")} />
<div className="mobile:px-4 w-full space-y-3 px-6 py-6">
<TableSimple
items={data.items}
pagination={data.pagination}
headers={[
{
name: "createdAt",
title: t("shared.createdAt"),
value: (item) => formatters.dateTime(item.createdAt, { timeStyle: "medium" }),
},
{
name: "subject",
title: t("helpDesk.tickets.subject"),
value: (item) => (
<Link to={adminPath(`support/${item.id}`, { mode: "host-aware" })} className="text-foreground hover:underline">
{redactFeedbackText(item.subject)}
</Link>
),
},
{
name: "status",
title: t("helpDesk.tickets.status"),
value: (item) => item.status,
},
{
name: "source",
title: t("helpDesk.tickets.source"),
value: (item) => item.source,
},
{
name: "message",
title: t("feedback.message"),
value: (item) => <div className="max-w-xl truncate">{redactFeedbackText(item.message)}</div>,
},
]}
/>
</div>
</div>
);
}