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,22 @@
import { describe, expect, it } from "vitest";
import { fileTypeLabelKey, normalizeMimeType } from "./fileTypeLabel";
describe("fileTypeLabel", () => {
it("normalizes case, whitespace and MIME parameters", () => {
expect(normalizeMimeType(" Image/PNG ; charset=binary ")).toBe("image/png");
});
it.each([
["application/pdf", "files.typeLabels.pdf"],
["image/png", "files.typeLabels.png"],
["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "files.typeLabels.word"],
["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "files.typeLabels.excel"],
["application/x-zip-compressed", "files.typeLabels.zip"],
["audio/ogg", "files.typeLabels.audio"],
["video/mp4", "files.typeLabels.video"],
["application/x-unknown", "files.typeLabels.file"],
["", "files.typeLabels.file"],
])("maps %s to %s", (mimeType, expected) => {
expect(fileTypeLabelKey(mimeType)).toBe(expected);
});
});
@@ -0,0 +1,31 @@
const EXACT_TYPE_KEYS: Readonly<Record<string, string>> = {
"application/pdf": "files.typeLabels.pdf",
"image/png": "files.typeLabels.png",
"image/jpeg": "files.typeLabels.jpeg",
"image/webp": "files.typeLabels.webp",
"image/svg+xml": "files.typeLabels.svg",
"image/heic": "files.typeLabels.heic",
"text/csv": "files.typeLabels.csv",
"application/csv": "files.typeLabels.csv",
"application/msword": "files.typeLabels.word",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "files.typeLabels.word",
"application/vnd.ms-excel": "files.typeLabels.excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "files.typeLabels.excel",
"application/zip": "files.typeLabels.zip",
"application/x-zip-compressed": "files.typeLabels.zip",
};
export function normalizeMimeType(value: string | null | undefined): string {
return value?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
}
export function fileTypeLabelKey(value: string | null | undefined): string {
const mimeType = normalizeMimeType(value);
const exact = EXACT_TYPE_KEYS[mimeType];
if (exact) return exact;
if (mimeType.startsWith("image/")) return "files.typeLabels.image";
if (mimeType.startsWith("audio/")) return "files.typeLabels.audio";
if (mimeType.startsWith("video/")) return "files.typeLabels.video";
if (mimeType.startsWith("text/")) return "files.typeLabels.text";
return "files.typeLabels.file";
}
@@ -0,0 +1,78 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { uploadFileInChunks, waitForChatAttachmentScan } from "./uploadFileClient";
afterEach(() => {
vi.unstubAllGlobals();
document.head.replaceChildren();
});
describe("uploadFileInChunks", () => {
it("sends the session CSRF token with every upload mutation", async () => {
document.head.innerHTML = '<meta name="csrf-token" content="csrf-token">';
const fetchMock = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ uploadId: "upload_1", chunkSize: 4, totalChunks: 1 }))
.mockResolvedValueOnce(Response.json({ receivedChunks: 1, totalChunks: 1 }))
.mockResolvedValueOnce(Response.json({ id: "file_1", displayName: "pilot.txt" }));
vi.stubGlobal("fetch", fetchMock);
await uploadFileInChunks({
tenantSlug: "demo",
file: new File(["test"], "pilot.txt", { type: "text/plain" }),
});
expect(fetchMock).toHaveBeenCalledTimes(3);
for (const [, init] of fetchMock.mock.calls) {
expect(init?.headers).toMatchObject({ "x-csrf-token": "csrf-token" });
}
});
});
describe("waitForChatAttachmentScan", () => {
it("polls pending scans until the owner-only endpoint reports clean", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ scanStatus: "pending" }))
.mockResolvedValueOnce(Response.json({ scanStatus: "clean" }));
await expect(waitForChatAttachmentScan({ tenantSlug: "demo", fileId: "file_1", fetchImpl, pollIntervalMs: 0, maxAttempts: 2 })).resolves.toBeUndefined();
expect(fetchImpl).toHaveBeenNthCalledWith(1, "/demo/chat/attachments/file_1/status", expect.objectContaining({ headers: { accept: "application/json" } }));
});
it("removes each abort listener after a completed polling delay", async () => {
const controller = new AbortController();
const add = vi.spyOn(controller.signal, "addEventListener");
const remove = vi.spyOn(controller.signal, "removeEventListener");
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ scanStatus: "pending" }))
.mockResolvedValueOnce(Response.json({ scanStatus: "clean" }));
await waitForChatAttachmentScan({
tenantSlug: "demo",
fileId: "file_1",
fetchImpl,
signal: controller.signal,
pollIntervalMs: 1,
maxAttempts: 2,
});
expect(add).toHaveBeenCalledOnce();
expect(remove).toHaveBeenCalledWith("abort", expect.any(Function));
});
it.each(["infected", "skipped"])("fails closed when the scan result is %s", async (scanStatus) => {
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ scanStatus }));
await expect(waitForChatAttachmentScan({ tenantSlug: "demo", fileId: "file_1", fetchImpl, pollIntervalMs: 0, maxAttempts: 1 })).rejects.toMatchObject({
errorKey: "chat.attachments.blocked",
});
});
it("returns a clear retry error when scanning stays pending", async () => {
const fetchImpl = vi.fn<typeof fetch>().mockImplementation(async () => Response.json({ scanStatus: "pending" }));
await expect(waitForChatAttachmentScan({ tenantSlug: "demo", fileId: "file_1", fetchImpl, pollIntervalMs: 0, maxAttempts: 2 })).rejects.toMatchObject({
errorKey: "chat.attachments.scanPendingRetry",
});
});
});
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { resolveUploadMimeType } from "./uploadFileClient";
describe("resolveUploadMimeType", () => {
it("keeps what the browser reports", () => {
expect(resolveUploadMimeType({ name: "angebot.pdf", type: "application/pdf" })).toBe("application/pdf");
});
it("falls back to the extension when the browser reports nothing", () => {
// macOS has no system type for .md, so Chrome hands over an empty string —
// declaring octet-stream there got a file the store allows rejected.
expect(resolveUploadMimeType({ name: "notiz.md", type: "" })).toBe("text/markdown");
expect(resolveUploadMimeType({ name: "Notiz.MARKDOWN", type: "" })).toBe("text/markdown");
expect(resolveUploadMimeType({ name: "liste.csv", type: "" })).toBe("text/csv");
});
it("stays at octet-stream for anything the store would not take anyway", () => {
expect(resolveUploadMimeType({ name: "tool.exe", type: "" })).toBe("application/octet-stream");
expect(resolveUploadMimeType({ name: "ohne-endung", type: "" })).toBe("application/octet-stream");
});
});
@@ -0,0 +1,155 @@
// P4 Files — client-side chunked upload sequence (init -> chunk -> complete)
// extracted from the files upload route so other flows (e.g. the AK-P16d
// signature wizard) can upload a file and get its file id back. Pure fetch
// client, no React; errors carry the server's i18n error key.
import { csrfRequestHeaders } from "~/utils/csrf";
export type UploadFileClientResult = { id: string; displayName: string };
export type ChatAttachmentScanStatus = "pending" | "clean" | "infected" | "skipped";
export class UploadFileClientError extends Error {
readonly errorKey: string;
constructor(errorKey: string) {
super(errorKey);
this.name = "UploadFileClientError";
this.errorKey = errorKey;
}
}
/**
* MIME types a browser commonly leaves empty on `File.type`, by extension.
*
* Markdown is the one that bites: macOS has no system type for `.md`, so Chrome
* hands over an empty string, the upload declares `application/octet-stream` and
* the store rejects it as a blocked type — for a file it does allow. Only types
* the file store accepts are mapped; anything else keeps the octet-stream
* fallback and gets the store's plain "type not allowed" answer.
*/
const MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
md: "text/markdown",
markdown: "text/markdown",
txt: "text/plain",
csv: "text/csv",
pdf: "application/pdf",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
webp: "image/webp",
gif: "image/gif",
heic: "image/heic",
heif: "image/heif",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
};
/** The type to declare for a file: what the browser says, else its extension. */
export function resolveUploadMimeType(file: { name: string; type: string }): string {
if (file.type) return file.type;
const extension = file.name.split(".").pop()?.toLowerCase() ?? "";
return MIME_BY_EXTENSION[extension] ?? "application/octet-stream";
}
export async function uploadFileInChunks(input: {
tenantSlug: string;
file: File;
onProgress?: (percent: number) => void;
onProcessing?: () => void;
signal?: AbortSignal;
}): Promise<UploadFileClientResult> {
const { tenantSlug, file } = input;
const initRes = await fetch(`/${tenantSlug}/files/upload/init`, {
method: "POST",
headers: csrfRequestHeaders({ "content-type": "application/json" }),
body: JSON.stringify({ originalFilename: file.name, mimeType: resolveUploadMimeType(file), totalSizeBytes: file.size }),
signal: input.signal,
});
if (!initRes.ok) {
const body = (await initRes.json().catch(() => ({}))) as { error?: string };
throw new UploadFileClientError(body.error ?? "files.error.invalidUploadRequest");
}
// The server's chunk size is authoritative for slicing so client and server
// always agree on chunk boundaries.
const { uploadId, chunkSize, totalChunks } = (await initRes.json()) as { uploadId: string; chunkSize: number; totalChunks: number };
for (let index = 0; index < totalChunks; index += 1) {
const slice = file.slice(index * chunkSize, (index + 1) * chunkSize);
const chunkRes = await fetch(`/${tenantSlug}/files/upload/${uploadId}/chunk/${index}`, {
method: "POST",
headers: csrfRequestHeaders(),
body: slice,
signal: input.signal,
});
if (!chunkRes.ok) {
const body = (await chunkRes.json().catch(() => ({}))) as { error?: string };
throw new UploadFileClientError(body.error ?? "files.error.uploadIncomplete");
}
input.onProgress?.(Math.round(((index + 1) / totalChunks) * 100));
}
input.onProcessing?.();
const completeRes = await fetch(`/${tenantSlug}/files/upload/${uploadId}/complete`, {
method: "POST",
headers: csrfRequestHeaders({ "content-type": "application/json" }),
body: JSON.stringify({}),
signal: input.signal,
});
if (!completeRes.ok) {
const body = (await completeRes.json().catch(() => ({}))) as { error?: string };
throw new UploadFileClientError(body.error ?? "files.error.uploadIncomplete");
}
return (await completeRes.json()) as UploadFileClientResult;
}
export async function waitForChatAttachmentScan(input: {
tenantSlug: string;
fileId: string;
signal?: AbortSignal;
fetchImpl?: typeof fetch;
pollIntervalMs?: number;
maxAttempts?: number;
}): Promise<void> {
const fetchImpl = input.fetchImpl ?? fetch;
const maxAttempts = input.maxAttempts ?? 80;
const pollIntervalMs = input.pollIntervalMs ?? 750;
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
assertNotAborted(input.signal);
const response = await fetchImpl(`/${input.tenantSlug}/chat/attachments/${encodeURIComponent(input.fileId)}/status`, {
headers: { accept: "application/json" },
signal: input.signal,
});
if (!response.ok) {
throw new UploadFileClientError("chat.attachments.scanStatusFailed");
}
const body = (await response.json()) as { scanStatus?: ChatAttachmentScanStatus };
if (body.scanStatus === "clean") return;
if (body.scanStatus === "infected" || body.scanStatus === "skipped") {
throw new UploadFileClientError("chat.attachments.blocked");
}
if (body.scanStatus !== "pending") {
throw new UploadFileClientError("chat.attachments.scanStatusFailed");
}
if (attempt + 1 < maxAttempts) await abortableDelay(pollIntervalMs, input.signal);
}
throw new UploadFileClientError("chat.attachments.scanPendingRetry");
}
function assertNotAborted(signal?: AbortSignal): void {
if (signal?.aborted) throw new DOMException("The operation was aborted", "AbortError");
}
function abortableDelay(delayMs: number, signal?: AbortSignal): Promise<void> {
if (delayMs <= 0) return Promise.resolve();
return new Promise((resolve, reject) => {
const cleanup = () => signal?.removeEventListener("abort", onAbort);
const timeout = setTimeout(() => {
cleanup();
resolve();
}, delayMs);
const onAbort = () => {
clearTimeout(timeout);
cleanup();
reject(new DOMException("The operation was aborted", "AbortError"));
};
signal?.addEventListener("abort", onAbort, { once: true });
});
}