Skip to content

CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.

fix(server): apply the upload limits to every shape a file arrives in

codingFeng1014011b944a1c2
diff --git a/server/chat/files.ts b/server/chat/files.ts
index 5a01366..6dd0b08 100644
--- a/server/chat/files.ts
+++ b/server/chat/files.ts
@@ -167,35 +167,64 @@ export function validateUploadedFiles(uploadedFiles: UploadedFilePayload[]): {
return { valid: true }
}
-// Helper function to validate file parts in messages
-export function validateFileParts(messages: any[]): {
+/**
+ * The payload each attachment on a turn carries, from whichever shape it
+ * arrived in.
+ *
+ * `/api/chat` accepts three, because the AI SDK sends whichever the client
+ * used: a `parts` entry with `url`, one with `image`, and a `content` entry
+ * with `image_url.url`. The limits below have to see all three -- one that
+ * only sees `url` is not a limit, it is a limit on well-behaved clients.
+ */
+function attachmentUrls(message: unknown): string[] {
+ const record = message as { parts?: unknown; content?: unknown } | null
+ const entries = [
+ ...(Array.isArray(record?.parts) ? record.parts : []),
+ ...(Array.isArray(record?.content) ? record.content : []),
+ ]
+
+ return entries
+ .map((entry) => {
+ const part = entry as {
+ type?: unknown
+ url?: unknown
+ image?: unknown
+ image_url?: { url?: unknown }
+ } | null
+ if (!part || typeof part !== "object") return ""
+ const type = String(part.type || "")
+ if (type !== "file" && type !== "image" && type !== "image_url") return ""
+ const url = part.url ?? part.image ?? part.image_url?.url
+ return typeof url === "string" ? url : ""
+ })
+ .filter(Boolean)
+}
+
+/** Rejects a turn carrying more attachments, or larger ones, than allowed. */
+export function validateFileParts(messages: unknown[]): {
valid: boolean
error?: string
} {
- const lastMessage = messages[messages.length - 1]
- const fileParts =
- lastMessage?.parts?.filter((p: any) => p.type === "file") || []
+ const urls = attachmentUrls(messages[messages.length - 1])
- if (fileParts.length > MAX_FILES) {
+ if (urls.length > MAX_FILES) {
return {
valid: false,
error: `Too many files. Maximum ${MAX_FILES} allowed.`,
}
}
- for (const filePart of fileParts) {
- // Data URLs format: data:image/png;base64,<data>
- // Base64 increases size by ~33%, so we check the decoded size
- if (filePart.url?.startsWith("data:")) {
- const base64Data = filePart.url.split(",")[1]
- if (base64Data) {
- const sizeInBytes = Math.ceil((base64Data.length * 3) / 4)
- if (sizeInBytes > MAX_FILE_SIZE) {
- return {
- valid: false,
- error: `File exceeds ${MAX_FILE_SIZE / 1024 / 1024}MB limit.`,
- }
- }
+ for (const url of urls) {
+ // Only an inline payload has a size we are carrying; a remote URL is
+ // a reference, and weighing it here would measure the wrong thing.
+ if (!url.startsWith("data:")) continue
+ const base64 = url.split(",")[1]
+ if (!base64) continue
+ // Base64 costs about a third in size, so the decoded length is what counts.
+ if (Math.ceil((base64.length * 3) / 4) > MAX_FILE_SIZE) {
+ return {
+ valid: false,
+ error: `File exceeds ${MAX_FILE_SIZE / 1024 / 1024}MB limit.`,
}
}
}
diff --git a/tests/chat-file-limits.test.ts b/tests/chat-file-limits.test.ts
new file mode 100644
index 0000000..26ab704
--- /dev/null
+++ b/tests/chat-file-limits.test.ts
@@ -0,0 +1,77 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { MAX_FILES, MAX_FILE_SIZE, validateFileParts } from "../server/chat/files";
+
+/**
+ * The size and count limits on what a chat turn may carry.
+ *
+ * `/api/chat` accepts a file in three shapes, because the AI SDK sends
+ * whichever the client used: a `parts` entry with `url`, one with `image`, and
+ * a `content` entry with `image_url.url`. The limits have to cover all three —
+ * a limit that only sees one of them is not a limit.
+ */
+
+/** A data URL whose decoded size is just over the cap. */
+const oversized = `data:image/png;base64,${"A".repeat(Math.ceil((MAX_FILE_SIZE + 1024) * 4) / 3)}`;
+const small = "data:image/png;base64,QUJD";
+
+const turn = (parts: unknown[], content?: unknown[]) => [
+ { role: "user", parts: [{ type: "text", text: "hi" }] },
+ content ? { role: "user", parts, content } : { role: "user", parts },
+];
+
+test("an oversized file sent as a parts url is refused", () => {
+ const result = validateFileParts(turn([{ type: "file", url: oversized }]));
+ assert.equal(result.valid, false);
+ assert.match(result.error || "", /limit/);
+});
+
+test("an oversized file sent as a parts image is refused too", () => {
+ // The route's own extractor reads `image` as readily as `url`.
+ const result = validateFileParts(turn([{ type: "file", image: oversized }]));
+ assert.equal(result.valid, false, "the size limit has to see this shape as well");
+});
+
+test("an oversized file sent in a content array is refused too", () => {
+ const result = validateFileParts(
+ turn([{ type: "text", text: "hi" }], [{ type: "image_url", image_url: { url: oversized } }]),
+ );
+ assert.equal(result.valid, false, "the standard array form is accepted, so it must be checked");
+});
+
+test("a small file passes in every shape", () => {
+ assert.equal(validateFileParts(turn([{ type: "file", url: small }])).valid, true);
+ assert.equal(validateFileParts(turn([{ type: "file", image: small }])).valid, true);
+ assert.equal(
+ validateFileParts(turn([], [{ type: "image_url", image_url: { url: small } }])).valid,
+ true,
+ );
+});
+
+test("too many files is refused however they are shaped", () => {
+ const many = Array.from({ length: MAX_FILES + 1 }, () => ({ type: "file", url: small }));
+ assert.equal(validateFileParts(turn(many)).valid, false);
+
+ const manyImages = Array.from({ length: MAX_FILES + 1 }, () => ({ type: "file", image: small }));
+ assert.equal(validateFileParts(turn(manyImages)).valid, false);
+
+ const manyInContent = Array.from({ length: MAX_FILES + 1 }, () => ({
+ type: "image_url",
+ image_url: { url: small },
+ }));
+ assert.equal(validateFileParts(turn([], manyInContent)).valid, false);
+});
+
+test("a remote url carries nothing, so it is not weighed", () => {
+ const result = validateFileParts(turn([{ type: "file", url: "https://example.com/a.png" }]));
+ assert.equal(result.valid, true);
+});
+
+test("a turn with no files at all passes", () => {
+ assert.equal(validateFileParts([{ role: "user", parts: [{ type: "text", text: "hi" }] }]).valid, true);
+ assert.equal(validateFileParts([]).valid, true);
+});
+
+test("a malformed part does not throw", () => {
+ assert.equal(validateFileParts(turn([null, "nonsense", { type: "file" }])).valid, true);
+});