Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): allow arbitrary attachment types

Gus7ded47c223b7
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index db90f6fc0..d06543d6a 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -956,6 +956,63 @@ describe("message emoji", () => {
});
});
+describe("message attachment upload", () => {
+ it.each([
+ { extension: "html", contentType: "text/html" },
+ { extension: "htm", contentType: "text/html" },
+ { extension: "blend", contentType: "application/octet-stream" },
+ ])("uploads .$extension files as $contentType", async ({ extension, contentType }) => {
+ const fs = await import("node:fs");
+ const os = await import("node:os");
+ const path = await import("node:path");
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-attachment-upload-"));
+ const file = path.join(dir, `prototype.${extension}`);
+ const body = "<!doctype html><title>Motion prototype</title>";
+ fs.writeFileSync(file, body);
+
+ const uploadSpy = vi.fn(async (req: Parameters<ServerApi["attachmentUpload"]>[0]) => ({
+ id: "att_file",
+ filename: req.file.filename,
+ contentType: req.file.contentType ?? "application/octet-stream",
+ size: req.file.data instanceof Uint8Array ? req.file.data.byteLength : req.file.data.size,
+ }));
+ setApiForTesting(stubApi({ attachmentUpload: uploadSpy }));
+
+ try {
+ await main([
+ "message",
+ "attachment",
+ "upload",
+ "--target",
+ "/demo/general",
+ "--file",
+ file,
+ ]);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+
+ expect(uploadSpy).toHaveBeenCalledTimes(1);
+ expect(uploadSpy).toHaveBeenCalledWith({
+ agentId: "agent_test",
+ target: "/demo/general",
+ file: {
+ data: new Uint8Array(Buffer.from(body)),
+ filename: `prototype.${extension}`,
+ contentType,
+ },
+ });
+ expect(parseEnvelope(cap.lines())).toEqual({
+ success: {
+ id: "att_file",
+ filename: `prototype.${extension}`,
+ contentType,
+ size: Buffer.byteLength(body),
+ },
+ });
+ });
+});
+
describe("channel subscribe removed", () => {
it("`channel subscribe ...` is no longer a recognized command", async () => {
setApiForTesting(stubApi());
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index ef47f4500..4c11d3c07 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -137,28 +137,11 @@ export function decodeTextEscapes(s: string): string {
/* ------------------------------------------------------------------ */
const CLIENT_MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
-const CLIENT_ALLOWED_MIME_PREFIXES: readonly string[] = [
- "image/",
- "video/",
- "audio/",
- "text/",
- "application/pdf",
- "application/json",
- "application/zip",
- "application/octet-stream",
-];
-
-function mimeAllowed(contentType: string): boolean {
- if (!contentType) return false;
- return CLIENT_ALLOWED_MIME_PREFIXES.some((entry) =>
- entry.endsWith("/") ? contentType.startsWith(entry) : contentType === entry,
- );
-}
/**
* Guess a content-type from a filename extension. Kept trivial — the server
- * re-validates with its own MIME allowlist. Falls back to
- * `application/octet-stream` so an unknown extension still uploads.
+ * stores MIME as descriptive metadata. Falls back to `application/octet-stream`
+ * for unknown extensions.
*/
function contentTypeFromFilename(filename: string): string {
const ext = filename.slice(filename.lastIndexOf(".") + 1).toLowerCase();
@@ -169,6 +152,7 @@ function contentTypeFromFilename(filename: string): string {
case "webp": return "image/webp";
case "svg": return "image/svg+xml";
case "pdf": return "application/pdf";
+ case "html": case "htm": return "text/html";
case "txt": case "md": case "log": return "text/plain";
case "json": return "application/json";
case "zip": return "application/zip";
@@ -448,9 +432,6 @@ async function cmdAttachmentUpload(opts: Record<string, unknown>): Promise<unkno
const pathMod = await import("path");
const filename = pathMod.basename(filePath);
const contentType = contentTypeFromFilename(filename);
- if (!mimeAllowed(contentType)) {
- throw new CliError(`message attachment upload: content type not allowed: ${contentType}`);
- }
const result = await api.attachmentUpload({
agentId: agent,
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.ts
index ba7bae76f..0d08bb9d7 100644
--- a/src/shared/src/constants/community.ts
+++ b/src/shared/src/constants/community.ts
@@ -29,13 +29,6 @@ export const MAX_EMOJI_BYTES = 32
export const MAX_ATTACHMENTS_PER_MESSAGE = 10
export const MAX_ATTACHMENT_SIZE_BYTES = 25 * 1024 * 1024 // 25 MB
export const MAX_SERVER_ICON_SIZE_BYTES = 5 * 1024 * 1024 // 5 MB
-export const ALLOWED_ATTACHMENT_MIME_PREFIXES = [
- "image/",
- "video/",
- "audio/",
- "application/pdf",
- "text/",
-] as const
export const ALLOWED_ICON_MIME_TYPES = [
"image/png",
"image/jpeg",
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 949873c26..f26e1f7cc 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -135,7 +135,6 @@ export {
MAX_ATTACHMENTS_PER_MESSAGE,
MAX_ATTACHMENT_SIZE_BYTES,
MAX_SERVER_ICON_SIZE_BYTES,
- ALLOWED_ATTACHMENT_MIME_PREFIXES,
ALLOWED_ICON_MIME_TYPES,
MAX_ICON_SOURCE_FILE_SIZE_BYTES,
ICON_CROP_OUTPUT_SIZE,
diff --git a/src/web/src/app/api/community/media/[...key]/route.test.ts b/src/web/src/app/api/community/media/[...key]/route.test.ts
index c02a91626..b73be3dfe 100644
--- a/src/web/src/app/api/community/media/[...key]/route.test.ts
+++ b/src/web/src/app/api/community/media/[...key]/route.test.ts
@@ -105,6 +105,7 @@ describe("GET /api/community/media/[...key]", () => {
expect(res.status).toBe(200)
expect(res.headers.get("Content-Type")).toBe("image/png")
expect(res.headers.get("Content-Disposition")).toBe("inline")
+ expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff")
expect(r2Get).toHaveBeenCalledWith("channel/c1/f1/x.png")
})
@@ -158,13 +159,30 @@ describe("GET /api/community/media/[...key]", () => {
expect(r2Get).not.toHaveBeenCalled()
})
- it("sets attachment Content-Disposition for non-image content types", async () => {
+ it.each(["image/png", "image/jpeg", "image/webp", "image/gif"])(
+ "serves the safe raster type %s inline",
+ async (contentType) => {
+ getChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
+ r2Get.mockResolvedValue({ body: new ReadableStream(), httpMetadata: { contentType } })
+ const res = await call(["channel", "c1", "f1", "safe-image"])
+ expect(res.headers.get("Content-Disposition")).toBe("inline")
+ expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff")
+ },
+ )
+
+ it.each([
+ ["image/svg+xml", "vector.svg"],
+ ["image/x-custom", "forged.img"],
+ ["text/html", "prototype.html"],
+ ["application/octet-stream", "unknown.blend"],
+ ])("forces %s downloads and disables sniffing", async (contentType, filename) => {
getChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
r2Get.mockResolvedValue({
body: new ReadableStream(),
- httpMetadata: { contentType: "application/pdf" },
+ httpMetadata: { contentType },
})
- const res = await call(["channel", "c1", "f1", "spec.pdf"])
- expect(res.headers.get("Content-Disposition")).toBe('attachment; filename="spec.pdf"')
+ const res = await call(["channel", "c1", "f1", filename])
+ expect(res.headers.get("Content-Disposition")).toBe(`attachment; filename="${filename}"`)
+ expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff")
})
})
diff --git a/src/web/src/app/api/community/media/[...key]/route.ts b/src/web/src/app/api/community/media/[...key]/route.ts
index 69b62d472..8635d0076 100644
--- a/src/web/src/app/api/community/media/[...key]/route.ts
+++ b/src/web/src/app/api/community/media/[...key]/route.ts
@@ -7,6 +7,7 @@ import { createAuth } from "@/lib/auth"
import { bindCacheKV } from "@/lib/cache"
import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"
import { isChannelTarget, isThreadTarget, isDmTarget } from "@/lib/community/message-handler"
+import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"
// Reject any segment that could smuggle traversal or escape the bucket.
function isSafeSegment(s: string): boolean {
@@ -67,13 +68,14 @@ export const GET = async (
if (!obj) return writeError("not found", 404)
const contentType = obj.httpMetadata?.contentType ?? "application/octet-stream"
- const isImage = contentType.startsWith("image/")
+ const isInline = isInlineAttachmentContentType(contentType)
const lastSegment = key[key.length - 1] ?? "file"
return new Response(obj.body, {
headers: {
"Content-Type": contentType,
- "Content-Disposition": isImage ? "inline" : `attachment; filename="${lastSegment}"`,
+ "Content-Disposition": isInline ? "inline" : `attachment; filename="${lastSegment}"`,
+ "X-Content-Type-Options": "nosniff",
"Cache-Control": CACHE_IMMUTABLE,
},
})
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index d2d1adb2d..8bb2f8bcf 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -13,7 +13,7 @@ import { readComposerDraft, writeComposerDraft, clearComposerDraft } from "@/lib
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
import { useFileAttachments, type PendingFile } from "@/hooks/use-file-attachments"
-import { ALLOWED_ATTACHMENT_MIME_PREFIXES, MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"
+import { MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"
import { tid } from "@/lib/community/testids"
import { Avatar } from "./avatar"
import { ChannelIcon } from "./channel-icon"
@@ -165,11 +165,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
handleDragOver,
handleDrop: handleDropRaw,
} = useFileAttachments({
- // Community server enforces both. Passing them here rejects oversized /
- // wrong-mime files at the drag-drop OR file-picker boundary so users
- // see a scoped toast instead of a generic 400 on send.
maxFileSize: MAX_ATTACHMENT_SIZE_BYTES,
- allowedMimePrefixes: ALLOWED_ATTACHMENT_MIME_PREFIXES,
})
const typingTimer = useRef<NodeJS.Timeout | null>(null)
@@ -547,13 +543,6 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
ref={fileInputRef}
type="file"
multiple
- // Mirror `ALLOWED_ATTACHMENT_MIME_PREFIXES` — the server-side
- // allowlist. Keep this list a superset of what the server takes:
- // browsers filter aggressively by extension, so `text/*` alone
- // won't offer `.md`/`.log`/`.json` in the picker. The MIME check
- // in `useFileAttachments` is authoritative; `accept` just biases
- // the picker.
- accept="image/*,video/*,audio/*,application/pdf,text/*,.md,.log,.json,.csv,.yaml,.yml,.ts,.tsx,.js,.jsx"
onChange={handleFileSelect}
className="hidden"
/>
diff --git a/src/web/src/hooks/community/insert-message-into-cache.test.ts b/src/web/src/hooks/community/insert-message-into-cache.test.ts
index e08e7ad3d..bee8381d5 100644
--- a/src/web/src/hooks/community/insert-message-into-cache.test.ts
+++ b/src/web/src/hooks/community/insert-message-into-cache.test.ts
@@ -60,6 +60,22 @@ describe("insertMessageIntoCache — attachment width/height", () => {
{ kind: "file", name: "a.pdf", url: "/a.pdf", size: "2 KB" },
])
})
+
+ it.each(["image/svg+xml", "image/x-forged"])(
+ "materializes unsafe %s attachments as file-kind",
+ (contentType) => {
+ const msg = baseMessage({
+ attachments: [
+ { id: "a1", filename: "unsafe.img", url: "/unsafe.img", contentType, size: 2048, width: 1920, height: 1080 },
+ ],
+ })
+ const result = insertMessageIntoCache(emptyCache as never, msg)
+ const inserted = result?.pages[0].messages[0]
+ expect(inserted?.attachments).toEqual([
+ { kind: "file", name: "unsafe.img", url: "/unsafe.img", size: "2 KB" },
+ ])
+ },
+ )
})
// reply-disappear root-cause fix (step 2): a message.create echo of the
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index 8b704b85a..dca9ab1b3 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -10,6 +10,7 @@ import { toast } from "sonner"
import { apiFetch, toastApiError } from "@/lib/api/client"
import { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
+import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"
import { useCommunityStore } from "@/stores/community"
import type { Msg, Attachment } from "@/components/community/_types"
import type { MessagesPage } from "@/hooks/community/use-messages"
@@ -163,7 +164,7 @@ function markFailedById(
export function toAttachmentVm(
a: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number },
): Attachment {
- const isImage = a.contentType.startsWith("image/")
+ const isImage = isInlineAttachmentContentType(a.contentType)
if (isImage) return { kind: "image", name: a.filename, url: a.url, width: a.width, height: a.height }
return {
kind: "file",
diff --git a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
index c983ea5ad..322316ff6 100644
--- a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
+++ b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
@@ -38,4 +38,19 @@ describe("toAttachmentVm", () => {
})
expect(result).toEqual({ kind: "file", name: "a.pdf", url: "/media/a.pdf", size: "2 KB" })
})
+
+ it.each(["image/svg+xml", "image/x-forged"])(
+ "materializes unsafe %s attachments as file-kind",
+ (contentType) => {
+ const result = toAttachmentVm({
+ url: "/media/unsafe.img",
+ filename: "unsafe.img",
+ contentType,
+ size: 2048,
+ width: 1920,
+ height: 1080,
+ })
+ expect(result).toEqual({ kind: "file", name: "unsafe.img", url: "/media/unsafe.img", size: "2 KB" })
+ },
+ )
})
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index fc6eb8a7b..aaf74a13b 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -6,6 +6,7 @@ import { useUserWs } from "@/lib/use-user-ws"
import { useCommunityStore } from "@/stores/community"
import { useCommunityWsStore } from "@/stores/community/ws"
import { communityKeys } from "@/lib/query-keys"
+import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"
import {
patchCacheJoin,
patchCacheLeave,
@@ -176,7 +177,7 @@ export function insertMessageIntoCache(
}
}
const attachments: Attachment[] | undefined = msg.attachments?.map((a) => {
- const isImage = a.contentType?.startsWith("image/")
+ const isImage = isInlineAttachmentContentType(a.contentType)
return isImage
? { kind: "image", name: a.filename, url: a.url, width: a.width ?? undefined, height: a.height ?? undefined }
: {
@@ -1319,4 +1320,3 @@ function removeTypingUser(
else nextByScope.set(scopeKey, nextMap)
return { typingByScope: nextByScope, typingTimers: nextTimers }
}
-
diff --git a/src/web/src/hooks/use-file-attachments.test.ts b/src/web/src/hooks/use-file-attachments.test.ts
index b28472f1b..571644f4c 100644
--- a/src/web/src/hooks/use-file-attachments.test.ts
+++ b/src/web/src/hooks/use-file-attachments.test.ts
@@ -1,53 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
-import { isMimeAllowed, useFileAttachments, type PendingFile } from "./use-file-attachments"
-
-// Pin the MIME allowlist logic against the server-side `mimeAllowed` in
-// `src/web/src/lib/community/upload.ts`. Both must agree — if this fires the
-// client filter and the server would still reject, users see two rejections
-// for one upload; if the client accepts and server rejects, users see the
-// dreaded generic "file type not allowed" 400 after the round-trip.
-describe("isMimeAllowed", () => {
- const ATTACHMENT_ALLOWED = [
- "image/",
- "video/",
- "audio/",
- "application/pdf",
- "text/",
- ] as const
-
- it("prefix entries match by prefix", () => {
- expect(isMimeAllowed("image/png", ATTACHMENT_ALLOWED)).toBe(true)
- expect(isMimeAllowed("image/jpeg", ATTACHMENT_ALLOWED)).toBe(true)
- expect(isMimeAllowed("video/mp4", ATTACHMENT_ALLOWED)).toBe(true)
- expect(isMimeAllowed("audio/mpeg", ATTACHMENT_ALLOWED)).toBe(true)
- expect(isMimeAllowed("text/plain", ATTACHMENT_ALLOWED)).toBe(true)
- expect(isMimeAllowed("text/markdown", ATTACHMENT_ALLOWED)).toBe(true)
- expect(isMimeAllowed("text/csv", ATTACHMENT_ALLOWED)).toBe(true)
- })
-
- it("exact-match entries require full equality", () => {
- expect(isMimeAllowed("application/pdf", ATTACHMENT_ALLOWED)).toBe(true)
- // Not a prefix match — the entry is `application/pdf`, not `application/`.
- expect(isMimeAllowed("application/zip", ATTACHMENT_ALLOWED)).toBe(false)
- expect(isMimeAllowed("application/x-zip-compressed", ATTACHMENT_ALLOWED)).toBe(false)
- expect(isMimeAllowed("application/octet-stream", ATTACHMENT_ALLOWED)).toBe(false)
- })
-
- it("empty content-type is rejected", () => {
- // Browsers report `""` for files whose type can't be sniffed. Server
- // would 400 these too — align.
- expect(isMimeAllowed("", ATTACHMENT_ALLOWED)).toBe(false)
- })
-
- it("respects a bare exact-only list (no prefixes)", () => {
- const ICONS_ONLY = ["image/png", "image/jpeg", "image/webp", "image/gif"] as const
- expect(isMimeAllowed("image/png", ICONS_ONLY)).toBe(true)
- expect(isMimeAllowed("image/svg+xml", ICONS_ONLY)).toBe(false)
- expect(isMimeAllowed("video/mp4", ICONS_ONLY)).toBe(false)
- })
-})
+import { useFileAttachments, type PendingFile } from "./use-file-attachments"
// `generateThumbnail` runs entirely against browser APIs unavailable under
// this repo's `environment: "node"` vitest config — mocked at the module
diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.ts
index e7a32888f..0efb61237 100644
--- a/src/web/src/hooks/use-file-attachments.ts
+++ b/src/web/src/hooks/use-file-attachments.ts
@@ -15,16 +15,6 @@ export type PendingFile = {
export type UseFileAttachmentsOptions = {
/** Per-file byte ceiling. Defaults to 10 MB. */
maxFileSize?: number;
- /**
- * Whitelist of allowed MIME prefixes. An entry ending in `/` (e.g.
- * `"image/"`) matches any MIME with that prefix; otherwise the full
- * MIME string must match exactly (e.g. `"application/pdf"`). When
- * unset, all MIMEs are accepted — that's the historical behavior. Pass
- * the server-side allowlist here so drag-drop AND file-picker paths
- * both reject unsupported types at the client boundary instead of
- * failing on upload.
- */
- allowedMimePrefixes?: readonly string[];
};
function revokeThumbnailUrls(files: PendingFile[]) {
@@ -33,29 +23,13 @@ function revokeThumbnailUrls(files: PendingFile[]) {
}
}
-/**
- * MIME allowlist check. Mirrors the server-side `mimeAllowed` in
- * `src/web/src/lib/community/upload.ts`: an allowlist entry ending in `/`
- * (e.g. `"image/"`) matches any MIME with that prefix; otherwise the full
- * MIME string must match exactly (e.g. `"application/pdf"`). Exported for
- * unit tests — do not depend on it from outside this file.
- */
-export function isMimeAllowed(contentType: string, allowed: readonly string[]): boolean {
- if (!contentType) return false;
- return allowed.some((entry) =>
- entry.endsWith("/") ? contentType.startsWith(entry) : contentType === entry,
- );
-}
-
export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
const maxFileSize = opts.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
- const allowedMimePrefixes = opts.allowedMimePrefixes;
// Options are read via ref so `addPendingFiles`'s stable identity survives
- // caller re-renders — callers pass the constant array from shared
- // constants but the reference identity isn't guaranteed after HMR.
- const optsRef = useRef({ maxFileSize, allowedMimePrefixes });
+ // caller re-renders while still observing an updated size limit.
+ const optsRef = useRef({ maxFileSize });
useEffect(() => {
- optsRef.current = { maxFileSize, allowedMimePrefixes };
+ optsRef.current = { maxFileSize };
});
const [pendingFiles, _setPendingFiles] = useState<PendingFile[]>([]);
const pendingFilesRef = useRef(pendingFiles);
@@ -80,7 +54,7 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
const fileInputRef = useRef<HTMLInputElement>(null);
const addPendingFiles = useCallback(async (files: File[]) => {
- const { maxFileSize: maxSize, allowedMimePrefixes: allowed } = optsRef.current;
+ const { maxFileSize: maxSize } = optsRef.current;
const valid: File[] = [];
for (const file of files) {
if (file.size > maxSize) {
@@ -88,10 +62,6 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
toast.error(`"${file.name}" exceeds ${mb} MB limit`);
continue;
}
- if (allowed && !isMimeAllowed(file.type, allowed)) {
- toast.error(`"${file.name}" — file type not allowed`);
- continue;
- }
valid.push(file);
}
if (valid.length === 0) return;
diff --git a/src/web/src/lib/community/attachment-content-type.ts b/src/web/src/lib/community/attachment-content-type.ts
new file mode 100644
index 000000000..f2aa7db0a
--- /dev/null
+++ b/src/web/src/lib/community/attachment-content-type.ts
@@ -0,0 +1,10 @@
+const INLINE_ATTACHMENT_CONTENT_TYPES = new Set([
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+ "image/gif",
+])
+
+export function isInlineAttachmentContentType(contentType: string | null | undefined): boolean {
+ return contentType != null && INLINE_ATTACHMENT_CONTENT_TYPES.has(contentType.toLowerCase())
+}
diff --git a/src/web/src/lib/community/messages.test.ts b/src/web/src/lib/community/messages.test.ts
index 264794247..55f616ce5 100644
--- a/src/web/src/lib/community/messages.test.ts
+++ b/src/web/src/lib/community/messages.test.ts
@@ -81,6 +81,18 @@ describe("groupAttachments", () => {
])
})
+ it.each(["image/svg+xml", "image/x-forged"])(
+ "materializes unsafe %s attachments as file-kind",
+ (contentType) => {
+ const result = groupAttachments([
+ { messageId: "m1", filename: "unsafe.img", r2Key: "channel/c1/uuid/unsafe.img", contentType, size: 2048, width: 1920, height: 1080 },
+ ])
+ expect(result.m1).toEqual([
+ { kind: "file", name: "unsafe.img", url: "/api/community/media/channel/c1/uuid/unsafe.img", size: "2.0 KB" },
+ ])
+ },
+ )
+
it("skips pending rows (messageId=null) so agent-uploaded pending attachments never surface", () => {
const result = groupAttachments([
{ messageId: null, filename: "pending.png", r2Key: "channel/c1/uuid/pending.png", contentType: "image/png", size: 100, width: null, height: null },
diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.ts
index 4ee4872b2..9a536d34e 100644
--- a/src/web/src/lib/community/messages.ts
+++ b/src/web/src/lib/community/messages.ts
@@ -1,5 +1,6 @@
import { DEFAULT_MESSAGE_PAGE_SIZE, MAX_MESSAGE_PAGE_SIZE } from "@alook/shared"
import { mediaUrlFromKey } from "./storage"
+import { isInlineAttachmentContentType } from "./attachment-content-type"
// Format file sizes for display
function formatBytes(bytes: number): string {
@@ -157,7 +158,7 @@ export function groupAttachments(
const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }>> = {}
for (const a of attachments) {
if (!a.messageId) continue
- const kind = a.contentType?.startsWith("image/") ? "image" : "file"
+ const kind = isInlineAttachmentContentType(a.contentType) ? "image" : "file"
const entry = {
kind,
name: a.filename,
diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.ts
index 513cc4769..212d71596 100644
--- a/src/web/src/lib/community/upload.test.ts
+++ b/src/web/src/lib/community/upload.test.ts
@@ -93,7 +93,7 @@ describe("handleAttachmentUpload", () => {
const USER_TAG = { uploader: "user" as const, uploaderUserId: "u1" }
- it("uploads an in-allowlist file under the size cap", async () => {
+ it("uploads a file under the size cap", async () => {
const put = vi.fn().mockResolvedValue(undefined)
const file = fakeFile("hi.png", "image/png", 10)
const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)
@@ -150,14 +150,25 @@ describe("handleAttachmentUpload", () => {
expect(put).not.toHaveBeenCalled()
})
- it("rejects disallowed MIME types with 400", async () => {
- const put = vi.fn()
+ it("accepts arbitrary MIME types", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
const file = fakeFile("evil.exe", "application/x-msdownload", 2)
const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)
- expect(res.ok).toBe(false)
- if (res.ok) return
- expect(res.response.status).toBe(400)
- expect(put).not.toHaveBeenCalled()
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.contentType).toBe("application/x-msdownload")
+ expect(put).toHaveBeenCalledOnce()
+ expect(put.mock.calls[0]?.[2]?.httpMetadata).toEqual({ contentType: "application/x-msdownload" })
+ })
+
+ it("normalizes an empty browser MIME to application/octet-stream", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const file = fakeFile("unknown.blend", "", 2)
+ const res = await handleAttachmentUpload(reqWithFile(file), envWithR2(put), "channel", "c1", USER_TAG)
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.contentType).toBe("application/octet-stream")
+ expect(put.mock.calls[0]?.[2]?.httpMetadata).toEqual({ contentType: "application/octet-stream" })
})
it("accepts video, audio, pdf and text MIME types", async () => {
diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.ts
index 0178d97d2..6bb1e93ed 100644
--- a/src/web/src/lib/community/upload.ts
+++ b/src/web/src/lib/community/upload.ts
@@ -2,7 +2,6 @@ import { NextRequest, NextResponse } from "next/server"
import {
MAX_ATTACHMENT_SIZE_BYTES,
MAX_SERVER_ICON_SIZE_BYTES,
- ALLOWED_ATTACHMENT_MIME_PREFIXES,
ALLOWED_ICON_MIME_TYPES,
queries,
} from "@alook/shared"
@@ -85,14 +84,14 @@ async function readFile(req: NextRequest): Promise<File | UploadErr> {
/**
* Validate + upload an attachment for a channel / DM / thread.
*
- * Enforces `MAX_ATTACHMENT_SIZE_BYTES` and `ALLOWED_ATTACHMENT_MIME_PREFIXES`.
+ * Enforces `MAX_ATTACHMENT_SIZE_BYTES`.
* Returns the R2 key + a `/api/community/media/<key>` URL that the auth-gated
* media route can serve.
*
* R2 requires stream bodies to have a known length. Passing the `File` itself
* preserves that length for the Workers runtime while avoiding an explicit
* `arrayBuffer()` copy in application code. Size and content-type are
- * validated against the `File` object before the put.
+ * read from the `File` object before the put.
*/
export async function handleAttachmentUpload(
req: NextRequest,
@@ -114,15 +113,13 @@ export async function handleAttachmentUpload(
),
}
}
- if (!mimeAllowed(file.type, ALLOWED_ATTACHMENT_MIME_PREFIXES as readonly string[])) {
- return { ok: false, response: writeError("file type not allowed", 400) }
- }
+ const contentType = file.type || "application/octet-stream"
const fileId = crypto.randomUUID()
const key = buildMediaKey(kind, targetId, fileId, file.name)
await env.COMMUNITY_MEDIA.put(key, file, {
- httpMetadata: { contentType: file.type },
+ httpMetadata: { contentType },
customMetadata: {
uploader: uploaderTag.uploader,
bot_user_id: uploaderTag.uploader === "bot" ? uploaderTag.uploaderUserId : "",
@@ -133,7 +130,7 @@ export async function handleAttachmentUpload(
ok: true,
r2Key: key,
filename: file.name,
- contentType: file.type,
+ contentType,
size: file.size,
}
}