Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): enforce image thumbnail policy (#621)

Gustavo Ye916cb79028bf
diff --git a/src/daemon/scripts/thumbnail-pack-smoke.mjs b/src/daemon/scripts/thumbnail-pack-smoke.mjs
index cee55b6f7..0a16eaa44 100644
--- a/src/daemon/scripts/thumbnail-pack-smoke.mjs
+++ b/src/daemon/scripts/thumbnail-pack-smoke.mjs
@@ -2,6 +2,7 @@ import assert from "node:assert/strict"
import { execFileSync, spawn } from "node:child_process"
import fs from "node:fs"
import http from "node:http"
+import { createRequire } from "node:module"
import os from "node:os"
import path from "node:path"
@@ -15,8 +16,12 @@ try {
assert(installedPackage.dependencies?.sharp, "packed daemon must declare sharp as a runtime dependency")
const png = path.join(temp, "valid.png")
- // 1x1 opaque PNG.
- fs.writeFileSync(png, Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", "base64"))
+ const requireFromDaemon = createRequire(path.join(temp, "node_modules/@alook/daemon/package.json"))
+ const sharp = requireFromDaemon("sharp")
+ await sharp({
+ create: { width: 1200, height: 800, channels: 3, background: "#336699" },
+ }).png().toFile(png)
+ const originalSize = fs.statSync(png).size
const token = path.join(temp, "voucher")
fs.writeFileSync(token, "crk_smoke", { mode: 0o600 })
@@ -28,7 +33,7 @@ try {
req.on("end", () => {
resolveBody({ body: Buffer.concat(chunks), contentType: req.headers["content-type"] ?? "" })
res.writeHead(200, { "content-type": "application/json" })
- res.end(JSON.stringify({ id: "att_smoke", filename: "valid.png", contentType: "image/png", size: 68, hasThumbnail: true }))
+ res.end(JSON.stringify({ id: "att_smoke", filename: "valid.png", contentType: "image/png", size: originalSize, hasThumbnail: true }))
})
})
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))
@@ -51,7 +56,7 @@ try {
server.close()
assert.equal(status, 0, stderr)
assert.deepEqual(JSON.parse(stdout), {
- success: { id: "att_smoke", filename: "valid.png", contentType: "image/png", size: 68, hasThumbnail: true },
+ success: { id: "att_smoke", filename: "valid.png", contentType: "image/png", size: originalSize, hasThumbnail: true },
})
const { body, contentType } = await bodyPromise
@@ -61,15 +66,17 @@ try {
assert(binary.includes('name="file"; filename="valid.png"'))
assert(binary.includes('name="thumbnail"; filename="thumbnail.jpg"'))
assert(binary.includes("Content-Type: image/jpeg"))
- assert(binary.includes('name="width"\r\n\r\n1'))
- assert(binary.includes('name="height"\r\n\r\n1'))
+ assert(binary.includes('name="width"\r\n\r\n1200'))
+ assert(binary.includes('name="height"\r\n\r\n800'))
const thumbnailStart = binary.indexOf('name="thumbnail"')
const payloadStart = binary.indexOf("\r\n\r\n", thumbnailStart) + 4
const payloadEnd = binary.indexOf(`\r\n--${boundary}`, payloadStart)
const thumbnail = body.subarray(payloadStart, payloadEnd)
- assert(thumbnail.length <= 50 * 1024)
+ assert(thumbnail.length <= 512 * 1024)
assert.deepEqual([...thumbnail.subarray(0, 2)], [0xff, 0xd8])
assert.deepEqual([...thumbnail.subarray(-2)], [0xff, 0xd9])
+ const thumbnailMetadata = await sharp(thumbnail).metadata()
+ assert(Math.max(thumbnailMetadata.width ?? 0, thumbnailMetadata.height ?? 0) <= 1024)
process.stdout.write("daemon thumbnail pack smoke passed\n")
} finally {
fs.rmSync(temp, { recursive: true, force: true })
diff --git a/src/daemon/src/cli/imageThumbnail.test.ts b/src/daemon/src/cli/imageThumbnail.test.ts
new file mode 100644
index 000000000..9cbcb2c2c
--- /dev/null
+++ b/src/daemon/src/cli/imageThumbnail.test.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { prepareCommunityImageUpload } from "./imageThumbnail";
+
+const mockSharp = vi.hoisted(() => vi.fn());
+
+vi.mock("sharp", () => ({ default: mockSharp }));
+
+describe("prepareCommunityImageUpload", () => {
+ beforeEach(() => mockSharp.mockReset());
+
+ it("handles missing decoded dimensions according to the byte-size requirement", async () => {
+ mockSharp.mockReturnValue({
+ metadata: vi.fn().mockResolvedValue({ width: undefined, height: 480 }),
+ });
+
+ await expect(
+ prepareCommunityImageUpload(new Uint8Array(1), "image/png"),
+ ).resolves.toEqual({});
+ await expect(
+ prepareCommunityImageUpload(new Uint8Array(512 * 1024 + 1), "image/png"),
+ ).rejects.toThrow("required image preview");
+ });
+
+ it("rejects when every bounded JPEG candidate remains over the byte cap", async () => {
+ const pipeline = {
+ metadata: vi.fn().mockResolvedValue({ width: 1025, height: 512 }),
+ resize: vi.fn(),
+ jpeg: vi.fn(),
+ toBuffer: vi.fn().mockResolvedValue(new Uint8Array(512 * 1024 + 1)),
+ };
+ pipeline.resize.mockReturnValue(pipeline);
+ pipeline.jpeg.mockReturnValue(pipeline);
+ mockSharp.mockReturnValue(pipeline);
+
+ await expect(
+ prepareCommunityImageUpload(new Uint8Array(1), "image/png"),
+ ).rejects.toThrow("required image preview");
+ expect(pipeline.toBuffer).toHaveBeenCalledTimes(70);
+ });
+});
diff --git a/src/daemon/src/cli/imageThumbnail.ts b/src/daemon/src/cli/imageThumbnail.ts
new file mode 100644
index 000000000..473142cd2
--- /dev/null
+++ b/src/daemon/src/cli/imageThumbnail.ts
@@ -0,0 +1,75 @@
+import {
+ MAX_ATTACHMENT_THUMBNAIL_EDGE_PX,
+ MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
+} from "@alook/shared/constants/community";
+
+const RASTER_CONTENT_TYPES = new Set([
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+ "image/gif",
+]);
+const QUALITIES = [80, 70, 60, 50, 40, 30, 20];
+const DIMENSION_ATTEMPTS = 10;
+const DIMENSION_SCALE = 0.85;
+
+export type CommunityImageUploadPreparation = {
+ thumbnail?: Uint8Array;
+ width?: number;
+ height?: number;
+};
+
+export async function prepareCommunityImageUpload(
+ bytes: Uint8Array,
+ contentType: string,
+): Promise<CommunityImageUploadPreparation> {
+ if (!RASTER_CONTENT_TYPES.has(contentType)) return {};
+
+ let required = bytes.byteLength > MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES;
+ try {
+ const { default: sharp } = await import("sharp");
+ const metadata = await sharp(bytes, { failOn: "error" }).metadata();
+ const width = metadata.width;
+ const height = metadata.height;
+ if (!width || !height) {
+ if (required) throw new Error("missing image dimensions");
+ return {};
+ }
+
+ required = required || Math.max(width, height) > MAX_ATTACHMENT_THUMBNAIL_EDGE_PX;
+ if (!required) return { width, height };
+
+ const fittedScale = Math.min(
+ 1,
+ MAX_ATTACHMENT_THUMBNAIL_EDGE_PX / Math.max(width, height),
+ );
+ const fittedWidth = Math.max(1, Math.round(width * fittedScale));
+ const fittedHeight = Math.max(1, Math.round(height * fittedScale));
+
+ for (let attempt = 0; attempt < DIMENSION_ATTEMPTS; attempt++) {
+ const scale = DIMENSION_SCALE ** attempt;
+ const targetWidth = Math.max(1, Math.round(fittedWidth * scale));
+ const targetHeight = Math.max(1, Math.round(fittedHeight * scale));
+ for (const quality of QUALITIES) {
+ const jpeg = await sharp(bytes, { failOn: "error" })
+ .resize({
+ width: targetWidth,
+ height: targetHeight,
+ fit: "inside",
+ withoutEnlargement: true,
+ })
+ .jpeg({ quality })
+ .toBuffer();
+ if (jpeg.byteLength <= MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES) {
+ return { thumbnail: new Uint8Array(jpeg), width, height };
+ }
+ }
+ }
+ throw new Error("no policy-compliant JPEG candidate");
+ } catch {
+ if (required) {
+ throw new Error("could not generate a required image preview");
+ }
+ return {};
+ }
+}
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index f387532f7..0699f100f 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -1332,7 +1332,7 @@ describe("message mark", () => {
});
describe("message attachment upload", () => {
- it("generates a bounded JPEG thumbnail and sends original dimensions", async () => {
+ it("skips a separate thumbnail when the original satisfies both limits", async () => {
const fs = await import("node:fs")
const os = await import("node:os")
const path = await import("node:path")
@@ -1357,23 +1357,18 @@ describe("message attachment upload", () => {
}
const request = uploadSpy.mock.calls[0]![0]
expect(request).toMatchObject({ width: 640, height: 480 })
- expect(request.thumbnail?.contentType).toBe("image/jpeg")
- expect(request.thumbnail?.data).toBeInstanceOf(Uint8Array)
- const bytes = request.thumbnail!.data as Uint8Array
- expect(bytes.byteLength).toBeLessThanOrEqual(50 * 1024)
- expect([...bytes.slice(0, 2)]).toEqual([0xff, 0xd8])
- expect([...bytes.slice(-2)]).toEqual([0xff, 0xd9])
- expect(parseEnvelope(cap.lines())).toMatchObject({ success: { hasThumbnail: true } })
+ expect(request.thumbnail).toBeUndefined()
+ expect(parseEnvelope(cap.lines())).toMatchObject({ success: { hasThumbnail: false } })
})
- it.each(["jpg", "webp", "gif"])("generates a thumbnail for valid .%s raster input", async (extension) => {
+ it.each(["jpg", "webp", "gif"])("generates a thumbnail for dimension-oversized .%s raster input", async (extension) => {
const fs = await import("node:fs")
const os = await import("node:os")
const path = await import("node:path")
const { default: sharp } = await import("sharp")
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-raster-matrix-"))
const file = path.join(dir, `source.${extension}`)
- let pipeline = sharp({ create: { width: 32, height: 24, channels: 3, background: "#123456" } })
+ let pipeline = sharp({ create: { width: 1025, height: 24, channels: 3, background: "#123456" } })
pipeline = extension === "jpg" ? pipeline.jpeg() : extension === "webp" ? pipeline.webp() : pipeline.gif()
fs.writeFileSync(file, await pipeline.toBuffer())
const uploadSpy = vi.fn(async () => ({
@@ -1385,8 +1380,38 @@ describe("message attachment upload", () => {
} finally {
fs.rmSync(dir, { recursive: true, force: true })
}
- expect(uploadSpy.mock.calls[0]![0]).toMatchObject({ width: 32, height: 24 })
- expect(uploadSpy.mock.calls[0]![0].thumbnail?.contentType).toBe("image/jpeg")
+ const request = uploadSpy.mock.calls[0]![0]
+ expect(request).toMatchObject({ width: 1025, height: 24 })
+ expect(request.thumbnail?.contentType).toBe("image/jpeg")
+ expect((request.thumbnail?.data as Uint8Array).byteLength).toBeLessThanOrEqual(512 * 1024)
+ })
+
+ it("generates a bounded JPEG when only the original byte limit is exceeded", async () => {
+ const fs = await import("node:fs")
+ const os = await import("node:os")
+ const path = await import("node:path")
+ const { randomBytes } = await import("node:crypto")
+ const { default: sharp } = await import("sharp")
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-byte-thumbnail-"))
+ const file = path.join(dir, "source.png")
+ const source = await sharp(randomBytes(640 * 480 * 3), {
+ raw: { width: 640, height: 480, channels: 3 },
+ }).png({ compressionLevel: 0 }).toBuffer()
+ expect(source.byteLength).toBeGreaterThan(512 * 1024)
+ fs.writeFileSync(file, source)
+ const uploadSpy = vi.fn(async (req: Parameters<ServerApi["attachmentUpload"]>[0]) => ({
+ id: "att", filename: "source.png", contentType: "image/png", size: source.byteLength,
+ hasThumbnail: req.thumbnail !== undefined,
+ }))
+ setApiForTesting(stubApi({ attachmentUpload: uploadSpy }))
+ try {
+ await main(["message", "attachment", "upload", "--target", "/demo#0042/general", "--file", file])
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ const request = uploadSpy.mock.calls[0]![0]
+ expect(request).toMatchObject({ width: 640, height: 480 })
+ expect((request.thumbnail?.data as Uint8Array).byteLength).toBeLessThanOrEqual(512 * 1024)
})
it("uploads corrupt declared raster input without thumbnail or dimensions", async () => {
@@ -1412,6 +1437,24 @@ describe("message attachment upload", () => {
expect(parseEnvelope(cap.lines())).toMatchObject({ success: { hasThumbnail: false } })
})
+ it("rejects corrupt declared raster input when its byte size requires a thumbnail", async () => {
+ 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-corrupt-large-image-"))
+ const file = path.join(dir, "corrupt.png")
+ fs.writeFileSync(file, new Uint8Array(512 * 1024 + 1))
+ const uploadSpy = vi.fn()
+ setApiForTesting(stubApi({ attachmentUpload: uploadSpy }))
+ try {
+ await main(["message", "attachment", "upload", "--target", "/demo#0042/general", "--file", file])
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ expect(uploadSpy).not.toHaveBeenCalled()
+ expect(parseEnvelope(cap.lines())).toMatchObject({ error: expect.stringContaining("required image preview") })
+ })
+
it.each([
{ extension: "html", contentType: "text/html" },
{ extension: "htm", contentType: "text/html" },
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index c5832d928..7889895df 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -27,13 +27,13 @@ import { armMessageReminderFromEnv, parseRemindAfter } from "./messageReminderCl
import { parseInviteToken } from "@alook/shared/lib/invite-link";
import {
ALLOWED_ICON_MIME_TYPES,
- MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
MAX_EMOJI_BYTES,
MAX_PROFILE_ABOUT_LENGTH,
MAX_SERVER_ICON_SIZE_BYTES,
} from "@alook/shared/constants/community";
import { nowLocalISO, toLocalISO } from "../util/localTime.js";
import { MESSAGE_SEND_STDIN_POLICY } from "../drivers/systemPrompt.js";
+import { prepareCommunityImageUpload } from "./imageThumbnail.js";
/**
* Rewrite every message's UTC `.time` (server-stamped) into local-tz ISO with
@@ -489,26 +489,20 @@ async function cmdAttachmentUpload(opts: Record<string, unknown>): Promise<unkno
let height: number | undefined;
if (["image/png", "image/jpeg", "image/webp", "image/gif"].includes(contentType)) {
try {
- const { default: sharp } = await import("sharp");
- const image = sharp(bytes, { failOn: "error" });
- const metadata = await image.metadata();
- if (metadata.width && metadata.height) {
- width = metadata.width;
- height = metadata.height;
- }
- const jpeg = await image
- .resize({ width: 200, height: 200, fit: "inside", withoutEnlargement: true })
- .jpeg({ quality: 70 })
- .toBuffer();
- if (jpeg.byteLength <= MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES) {
+ const prepared = await prepareCommunityImageUpload(bytes, contentType);
+ width = prepared.width;
+ height = prepared.height;
+ if (prepared.thumbnail) {
thumbnail = {
- data: new Uint8Array(jpeg),
+ data: prepared.thumbnail,
filename: "thumbnail.jpg",
contentType: "image/jpeg",
};
}
- } catch {
- // Thumbnailing is an optimization. Corrupt/unsupported images still upload.
+ } catch (error) {
+ throw new CliError(
+ `message attachment upload: ${(error as Error).message}`,
+ );
}
}
diff --git a/src/shared/src/constants/community.test.ts b/src/shared/src/constants/community.test.ts
index 11a982c05..469ac4dc5 100644
--- a/src/shared/src/constants/community.test.ts
+++ b/src/shared/src/constants/community.test.ts
@@ -6,10 +6,21 @@ import {
ICON_CROP_OUTPUT_SIZE,
MAX_ICON_SOURCE_FILE_SIZE_BYTES,
ALLOWED_ICON_SOURCE_MIME_TYPES,
+ MAX_ATTACHMENT_THUMBNAIL_EDGE_PX,
+ MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
MESSAGE_PREVIEW_LENGTH,
truncateMessagePreview,
} from "./community"
+describe("Community attachment thumbnail constants", () => {
+ it("locks the 1024px and 512 KiB policy through both export surfaces", () => {
+ expect(MAX_ATTACHMENT_THUMBNAIL_EDGE_PX).toBe(1024)
+ expect(MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES).toBe(512 * 1024)
+ expect(alook.MAX_ATTACHMENT_THUMBNAIL_EDGE_PX).toBe(MAX_ATTACHMENT_THUMBNAIL_EDGE_PX)
+ expect(alook.MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES).toBe(MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES)
+ })
+})
+
describe("icon-crop constants", () => {
it("ICON_CROP_MIN_ZOOM is less than ICON_CROP_MAX_ZOOM", () => {
expect(ICON_CROP_MIN_ZOOM).toBeLessThan(ICON_CROP_MAX_ZOOM)
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.ts
index 2422993ec..e272f55ca 100644
--- a/src/shared/src/constants/community.ts
+++ b/src/shared/src/constants/community.ts
@@ -27,7 +27,8 @@ export const MAX_EMOJI_BYTES = 32
// Attachments / uploads
export const MAX_ATTACHMENTS_PER_MESSAGE = 10
export const MAX_ATTACHMENT_SIZE_BYTES = 25 * 1024 * 1024 // 25 MB
-export const MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 50 * 1024 // 50 KiB
+export const MAX_ATTACHMENT_THUMBNAIL_EDGE_PX = 1024
+export const MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 512 * 1024 // 512 KiB
export const MAX_SERVER_ICON_SIZE_BYTES = 5 * 1024 * 1024 // 5 MB
export const ALLOWED_ICON_MIME_TYPES = [
"image/png",
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 67a925a67..3b6bdece6 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -146,6 +146,7 @@ export {
MAX_EMOJI_BYTES,
MAX_ATTACHMENTS_PER_MESSAGE,
MAX_ATTACHMENT_SIZE_BYTES,
+ MAX_ATTACHMENT_THUMBNAIL_EDGE_PX,
MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
MAX_SERVER_ICON_SIZE_BYTES,
ALLOWED_ICON_MIME_TYPES,
diff --git a/src/web/src/components/community/channels/text-channel-surface.test.ts b/src/web/src/components/community/channels/text-channel-surface.test.ts
index 6f0fdd2a9..5582ef921 100644
--- a/src/web/src/components/community/channels/text-channel-surface.test.ts
+++ b/src/web/src/components/community/channels/text-channel-surface.test.ts
@@ -52,7 +52,7 @@ vi.mock("@/components/community/messages/message-context-sheet", () => ({
}))
vi.mock("@alook/shared", () => ({
deriveThreadName: () => "thread",
- MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES: 50 * 1024,
+ MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES: 512 * 1024,
}))
vi.mock("@/stores/community", () => {
const state = {
diff --git a/src/web/src/components/community/messages/use-composer-controller.test.ts b/src/web/src/components/community/messages/use-composer-controller.test.ts
index 64eea7c92..7b91d7c18 100644
--- a/src/web/src/components/community/messages/use-composer-controller.test.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.test.ts
@@ -241,6 +241,17 @@ describe("useComposerController", () => {
return preventDefault
}
+ it("enables the Community thumbnail policy at the composer boundary", async () => {
+ await act(async () => {
+ TestRenderer.create(createElement(Harness, acceptedProps(vi.fn(() => true))))
+ })
+
+ expect(mocks.useFileAttachments).toHaveBeenCalledWith({
+ maxFileSize: 25 * 1024 * 1024,
+ thumbnailPolicy: "community",
+ })
+ })
+
it("forwards the optional channel source into suggestions and its presentation into the view", async () => {
const channelRefCandidateSource = { loading: true, failed: false }
const props = {
diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.ts
index 981469289..90358a8cf 100644
--- a/src/web/src/components/community/messages/use-composer-controller.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.ts
@@ -66,9 +66,7 @@ export function useComposerController(
useLayoutEffect(() => {
breakpointRef.current = breakpoint
}, [breakpoint])
- const attachments = useFileAttachments({
- maxFileSize: MAX_ATTACHMENT_SIZE_BYTES,
- })
+ const attachments = useFileAttachments({ maxFileSize: MAX_ATTACHMENT_SIZE_BYTES, thumbnailPolicy: "community" })
const {
pendingFiles,
setPendingFiles,
diff --git a/src/web/src/hooks/community/mutations/uploads.test.ts b/src/web/src/hooks/community/mutations/uploads.test.ts
index 081bc70b7..ee1e5b806 100644
--- a/src/web/src/hooks/community/mutations/uploads.test.ts
+++ b/src/web/src/hooks/community/mutations/uploads.test.ts
@@ -69,10 +69,17 @@ describe("appendGeneratedThumbnail", () => {
expect((form.get("thumbnail") as File).type).toBe("image/jpeg")
})
- it("degrades to original-only when the generated thumbnail exceeds 50 KiB", () => {
+ it("rejects a generated thumbnail over 512 KiB instead of silently dropping it", () => {
const form = new FormData()
- const blob = new Blob([new Uint8Array(50 * 1024 + 1)], { type: "image/jpeg" })
- expect(appendGeneratedThumbnail(form, "image/png", blob)).toBe(false)
+ const blob = new Blob([new Uint8Array(512 * 1024 + 1)], { type: "image/jpeg" })
+ expect(() => appendGeneratedThumbnail(form, "image/png", blob)).toThrow("512 KiB")
+ expect(form.has("thumbnail")).toBe(false)
+ })
+
+ it("rejects a non-JPEG generated thumbnail", () => {
+ const form = new FormData()
+ const blob = new Blob([new Uint8Array(1)], { type: "image/png" })
+ expect(() => appendGeneratedThumbnail(form, "image/png", blob)).toThrow("image/jpeg")
expect(form.has("thumbnail")).toBe(false)
})
diff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.ts
index 738d65f87..b2882066d 100644
--- a/src/web/src/hooks/community/mutations/uploads.ts
+++ b/src/web/src/hooks/community/mutations/uploads.ts
@@ -51,9 +51,16 @@ export function appendGeneratedThumbnail(
): boolean {
if (
!isInlineAttachmentContentType(originalContentType) ||
- !thumbnailBlob ||
- thumbnailBlob.size > MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES
+ !thumbnailBlob
) return false
+ if (thumbnailBlob.type !== "image/jpeg") {
+ throw new Error("Generated thumbnail must be image/jpeg")
+ }
+ if (thumbnailBlob.size > MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES) {
+ throw new Error(
+ `Generated thumbnail exceeds ${MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES / 1024} KiB`,
+ )
+ }
formData.append("thumbnail", thumbnailBlob, "thumbnail.jpg")
return true
}
diff --git a/src/web/src/hooks/use-file-attachments.test.ts b/src/web/src/hooks/use-file-attachments.test.ts
index 9aff30fdd..0a478004d 100644
--- a/src/web/src/hooks/use-file-attachments.test.ts
+++ b/src/web/src/hooks/use-file-attachments.test.ts
@@ -9,12 +9,18 @@ import { useFileAttachments, type PendingFile } from "./use-file-attachments"
// hook's result, not `generateThumbnail` itself, which has its own direct
// unit tests in `lib/image-thumbnail.test.ts`).
const generateThumbnailMock = vi.fn()
+const prepareCommunityImageMock = vi.fn()
+const toastErrorMock = vi.fn()
vi.mock("../lib/image-thumbnail", () => ({
generateThumbnail: (...args: unknown[]) => generateThumbnailMock(...args),
+ prepareCommunityImage: (...args: unknown[]) => prepareCommunityImageMock(...args),
}))
+vi.mock("sonner", () => ({ toast: { error: (...args: unknown[]) => toastErrorMock(...args) } }))
beforeEach(() => {
generateThumbnailMock.mockReset()
+ prepareCommunityImageMock.mockReset()
+ toastErrorMock.mockReset()
vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:fake"), revokeObjectURL: vi.fn() })
})
@@ -25,17 +31,23 @@ afterEach(() => {
// Renders the hook via a tiny consumer component — this repo's existing
// pattern for testing hooks without @testing-library (see
// use-messages.loading-state.test.ts).
-function Capture({ onResult }: { onResult: (r: ReturnType<typeof useFileAttachments>) => void }) {
- const result = useFileAttachments()
+function Capture({
+ onResult,
+ options,
+}: {
+ onResult: (r: ReturnType<typeof useFileAttachments>) => void
+ options?: Parameters<typeof useFileAttachments>[0]
+}) {
+ const result = useFileAttachments(options)
onResult(result)
return null
}
-async function renderCapture() {
+async function renderCapture(options?: Parameters<typeof useFileAttachments>[0]) {
let latest!: ReturnType<typeof useFileAttachments>
await act(async () => {
TestRenderer.create(
- React.createElement(Capture, { onResult: (r) => { latest = r } }),
+ React.createElement(Capture, { onResult: (r) => { latest = r }, options }),
)
})
return {
@@ -124,4 +136,45 @@ describe("useFileAttachments — PendingFile width/height", () => {
expect(snapshot[0].thumbnailBlob).toBe(thumbnailBlob)
expect(hook.current.pendingFiles[0]).toBe(snapshot[0])
})
+
+ it("uses the original file as the Community preview when no thumbnail is required", async () => {
+ prepareCommunityImageMock.mockResolvedValue({ blob: null, width: 1024, height: 768 })
+ const hook = await renderCapture({ thumbnailPolicy: "community" })
+ const file = new File([new Uint8Array(1)], "photo.png", { type: "image/png" })
+
+ await hook.addFiles([file])
+
+ expect(URL.createObjectURL).toHaveBeenCalledWith(file)
+ expect(hook.current.pendingFiles[0]).toMatchObject({
+ file,
+ thumbnailUrl: "blob:fake",
+ thumbnailBlob: null,
+ width: 1024,
+ height: 768,
+ })
+ expect(generateThumbnailMock).not.toHaveBeenCalled()
+ })
+
+ it("uses the generated Community JPEG for preview and upload", async () => {
+ const thumbnail = new Blob([new Uint8Array(10)], { type: "image/jpeg" })
+ prepareCommunityImageMock.mockResolvedValue({ blob: thumbnail, width: 2048, height: 1024 })
+ const hook = await renderCapture({ thumbnailPolicy: "community" })
+ const file = new File([new Uint8Array(1)], "photo.png", { type: "image/png" })
+
+ await hook.addFiles([file])
+
+ expect(URL.createObjectURL).toHaveBeenCalledWith(thumbnail)
+ expect(hook.current.pendingFiles[0]?.thumbnailBlob).toBe(thumbnail)
+ })
+
+ it("rejects a Community image when a required preview cannot be prepared", async () => {
+ prepareCommunityImageMock.mockRejectedValue(new Error("required image preview"))
+ const hook = await renderCapture({ thumbnailPolicy: "community" })
+ const file = new File([new Uint8Array(1)], "photo.png", { type: "image/png" })
+
+ await hook.addFiles([file])
+
+ expect(hook.current.pendingFiles).toEqual([])
+ expect(toastErrorMock).toHaveBeenCalledWith('Could not prepare "photo.png" for upload')
+ })
})
diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.ts
index ee809d36a..ecd146235 100644
--- a/src/web/src/hooks/use-file-attachments.ts
+++ b/src/web/src/hooks/use-file-attachments.ts
@@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
-import { generateThumbnail } from "../lib/image-thumbnail";
+import { generateThumbnail, prepareCommunityImage } from "../lib/image-thumbnail";
const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
@@ -15,6 +15,7 @@ export type PendingFile = {
export type UseFileAttachmentsOptions = {
/** Per-file byte ceiling. Defaults to 10 MB. */
maxFileSize?: number;
+ thumbnailPolicy?: "legacy" | "community";
};
function revokeThumbnailUrls(files: PendingFile[]) {
@@ -25,11 +26,12 @@ function revokeThumbnailUrls(files: PendingFile[]) {
export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
const maxFileSize = opts.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
+ const thumbnailPolicy = opts.thumbnailPolicy ?? "legacy";
// Options are read via ref so `addPendingFiles`'s stable identity survives
// caller re-renders while still observing an updated size limit.
- const optsRef = useRef({ maxFileSize });
+ const optsRef = useRef({ maxFileSize, thumbnailPolicy });
useEffect(() => {
- optsRef.current = { maxFileSize };
+ optsRef.current = { maxFileSize, thumbnailPolicy };
});
const [pendingFiles, _setPendingFiles] = useState<PendingFile[]>([]);
const pendingFilesRef = useRef(pendingFiles);
@@ -59,7 +61,7 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
const addPendingFiles = useCallback(async (files: File[]) => {
const prior = preparationTailRef.current;
const preparation = prior.then(async () => {
- const { maxFileSize: maxSize } = optsRef.current;
+ const { maxFileSize: maxSize, thumbnailPolicy: policy } = optsRef.current;
const valid: File[] = [];
for (const file of files) {
if (file.size > maxSize) {
@@ -71,8 +73,24 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
}
if (valid.length === 0) return;
- const pending: PendingFile[] = await Promise.all(
- valid.map(async (file) => {
+ const prepared = await Promise.all(
+ valid.map(async (file): Promise<PendingFile | null> => {
+ if (policy === "community") {
+ try {
+ const image = await prepareCommunityImage(file);
+ const previewSource = image?.blob ?? (image ? file : null);
+ return {
+ file,
+ thumbnailUrl: previewSource ? URL.createObjectURL(previewSource) : null,
+ thumbnailBlob: image?.blob ?? null,
+ width: image?.width,
+ height: image?.height,
+ } satisfies PendingFile;
+ } catch {
+ toast.error(`Could not prepare "${file.name}" for upload`);
+ return null;
+ }
+ }
const thumbnail = await generateThumbnail(file);
const thumbnailUrl = thumbnail ? URL.createObjectURL(thumbnail.blob) : null;
return {
@@ -84,6 +102,8 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
};
}),
);
+ const pending = prepared.filter((file): file is PendingFile => file !== null);
+ if (pending.length === 0) return;
const next = [...pendingFilesRef.current, ...pending];
pendingFilesRef.current = next;
diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.ts
index 06fb4983b..579086902 100644
--- a/src/web/src/lib/community/upload.test.ts
+++ b/src/web/src/lib/community/upload.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
+import { readFileSync } from "node:fs"
vi.mock("@/lib/middleware/helpers", () => {
const { NextResponse } = require("next/server")
@@ -112,6 +113,63 @@ function fakeFile(name: string, type: string, size: number) {
}
}
+const DECODABLE_JPEG = Uint8Array.from(readFileSync(new URL(
+ "../../../public/blog/claude-code-dynamic-workflow-alternative/chat-interface.jpg",
+ import.meta.url,
+)))
+
+function fakeJpegFile(width = 640, height = 360) {
+ const bytes = DECODABLE_JPEG.slice()
+ for (let index = 2; index < bytes.length - 8; index++) {
+ if (bytes[index] !== 0xff || bytes[index + 1] !== 0xc0) continue
+ bytes[index + 5] = (height >> 8) & 0xff
+ bytes[index + 6] = height & 0xff
+ bytes[index + 7] = (width >> 8) & 0xff
+ bytes[index + 8] = width & 0xff
+ break
+ }
+ return {
+ ...fakeFile("thumbnail.jpg", "image/jpeg", bytes.byteLength),
+ arrayBuffer: async () => bytes.buffer,
+ }
+}
+
+function sofOnlyJpegFile(width = 640, height = 480) {
+ const bytes = Uint8Array.from([
+ 0xff, 0xd8,
+ 0xff, 0xc0, 0x00, 0x11, 0x08,
+ (height >> 8) & 0xff, height & 0xff,
+ (width >> 8) & 0xff, width & 0xff,
+ 0x03,
+ 0x01, 0x11, 0x00,
+ 0x02, 0x11, 0x00,
+ 0x03, 0x11, 0x00,
+ 0xff, 0xd9,
+ ])
+ return {
+ ...fakeFile("thumbnail.jpg", "image/jpeg", bytes.byteLength),
+ arrayBuffer: async () => bytes.buffer,
+ }
+}
+
+function structuredJpegFile(bytes: number[]) {
+ const data = Uint8Array.from(bytes)
+ return {
+ ...fakeFile("thumbnail.jpg", "image/jpeg", data.byteLength),
+ arrayBuffer: async () => data.buffer,
+ }
+}
+
+function restartMarkerJpegFile() {
+ return structuredJpegFile([
+ 0xff, 0xd8,
+ 0xff, 0xc0, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00,
+ 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3f, 0x00,
+ 0x01, 0xff, 0xd0, 0x02,
+ 0xff, 0xd9,
+ ])
+}
+
describe("handleAttachmentUpload", () => {
beforeEach(() => vi.clearAllMocks())
@@ -131,13 +189,40 @@ describe("handleAttachmentUpload", () => {
expect(options.customMetadata).toMatchObject({ uploader: "user" })
})
+ it("accepts an original-only image at the exact policy boundaries", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const res = await handleAttachmentUpload(
+ reqWithUpload(fakeFile("edge.png", "image/png", 512 * 1024), null, "1024", "768"),
+ envWithR2(put), "channel", "c1", USER_TAG,
+ )
+
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.thumbnailR2Key).toBeNull()
+ expect(put).toHaveBeenCalledOnce()
+ })
+
+ it.each([
+ ["byte size", fakeFile("large.png", "image/png", 512 * 1024 + 1), "640", "480"],
+ ["width", fakeFile("wide.png", "image/png", 10), "1025", "480"],
+ ["height", fakeFile("tall.png", "image/png", 10), "480", "1025"],
+ ])("rejects a missing required thumbnail proved by %s before either R2 put", async (_label, file, width, height) => {
+ const put = vi.fn()
+ const res = await handleAttachmentUpload(
+ reqWithUpload(file, null, width, height), envWithR2(put), "channel", "c1", USER_TAG,
+ )
+
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(res.response.status).toBe(400)
+ expect(await res.response.json()).toMatchObject({ error: "thumbnail required" })
+ expect(put).not.toHaveBeenCalled()
+ })
+
it("stores a validated JPEG thumbnail beside the original with matching provenance", async () => {
const put = vi.fn().mockResolvedValue(undefined)
const file = fakeFile("hi.png", "image/png", 10)
- const thumbnail = {
- ...fakeFile("thumbnail.jpg", "image/jpeg", 4),
- arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,
- }
+ const thumbnail = fakeJpegFile()
const res = await handleAttachmentUpload(
reqWithUpload(file, thumbnail), envWithR2(put), "channel", "c1", USER_TAG,
)
@@ -171,21 +256,93 @@ describe("handleAttachmentUpload", () => {
expect(put).not.toHaveBeenCalled()
})
+ it("rejects a SOF-only JPEG-shaped thumbnail before either R2 put", async () => {
+ const put = vi.fn()
+ const res = await handleAttachmentUpload(
+ reqWithUpload(fakeFile("hi.png", "image/png", 10), sofOnlyJpegFile()),
+ envWithR2(put), "channel", "c1", USER_TAG,
+ )
+
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(await res.response.json()).toMatchObject({ error: "invalid jpeg thumbnail" })
+ expect(put).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ {
+ label: "a mismatched SOF component length",
+ thumbnail: structuredJpegFile([
+ 0xff, 0xd8,
+ 0xff, 0xc0, 0x00, 0x0c, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00, 0x00,
+ 0xff, 0xd9,
+ ]),
+ },
+ {
+ label: "a mismatched SOS component length",
+ thumbnail: structuredJpegFile([
+ 0xff, 0xd8,
+ 0xff, 0xc0, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00,
+ 0xff, 0xda, 0x00, 0x09, 0x01, 0x01, 0x00, 0x00, 0x3f, 0x00, 0x00,
+ 0x01, 0xff, 0xd9,
+ ]),
+ },
+ {
+ label: "a segment stream without EOI",
+ thumbnail: structuredJpegFile([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x02]),
+ },
+ ])("rejects $label before either R2 put", async ({ thumbnail }) => {
+ const put = vi.fn()
+ const res = await handleAttachmentUpload(
+ reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),
+ envWithR2(put), "channel", "c1", USER_TAG,
+ )
+
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(await res.response.json()).toMatchObject({ error: "invalid jpeg thumbnail" })
+ expect(put).not.toHaveBeenCalled()
+ })
+
+ it("accepts entropy data containing a JPEG restart marker", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const res = await handleAttachmentUpload(
+ reqWithUpload(fakeFile("hi.png", "image/png", 10), restartMarkerJpegFile()),
+ envWithR2(put), "channel", "c1", USER_TAG,
+ )
+
+ expect(res.ok).toBe(true)
+ expect(put).toHaveBeenCalledTimes(2)
+ })
+
+ it("rejects a JPEG thumbnail over 1024px before either R2 put", async () => {
+ const put = vi.fn()
+ const res = await handleAttachmentUpload(
+ reqWithUpload(fakeFile("hi.png", "image/png", 10), fakeJpegFile(1025, 512)),
+ envWithR2(put), "channel", "c1", USER_TAG,
+ )
+
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(await res.response.json()).toMatchObject({ error: "thumbnail dimensions too large" })
+ expect(put).not.toHaveBeenCalled()
+ })
+
it.each([
{
label: "non-raster original",
file: fakeFile("doc.pdf", "application/pdf", 10),
- thumbnail: { ...fakeFile("thumbnail.jpg", "image/jpeg", 4), arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer },
+ thumbnail: fakeJpegFile(),
},
{
label: "wrong thumbnail MIME",
file: fakeFile("photo.png", "image/png", 10),
- thumbnail: { ...fakeFile("thumbnail.png", "image/png", 4), arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer },
+ thumbnail: { ...fakeJpegFile(), type: "image/png", name: "thumbnail.png" },
},
{
label: "oversized thumbnail",
file: fakeFile("photo.png", "image/png", 10),
- thumbnail: { ...fakeFile("thumbnail.jpg", "image/jpeg", 50 * 1024 + 1), arrayBuffer: async () => new ArrayBuffer(0) },
+ thumbnail: { ...fakeFile("thumbnail.jpg", "image/jpeg", 512 * 1024 + 1), arrayBuffer: async () => new ArrayBuffer(0) },
},
])("rejects $label before either R2 put", async ({ file, thumbnail }) => {
const put = vi.fn()
@@ -206,10 +363,7 @@ describe("handleAttachmentUpload", () => {
const put = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(thumbnailFailure)
const cleanupSecret = "provider-secret channel/c1/original.png"
const del = vi.fn().mockRejectedValueOnce(new TypeError(cleanupSecret))
- const thumbnail = {
- ...fakeFile("thumbnail.jpg", "image/jpeg", 4),
- arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,
- }
+ const thumbnail = fakeJpegFile()
const upload = handleAttachmentUpload(
reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),
envWithR2(put, del), "channel", "c1", uploaderTag,
@@ -589,6 +743,7 @@ describe("runAttachmentUpload", () => {
it("threads client-supplied image dimensions onto the pending row (single source = upload)", async () => {
surfaceChannel("text")
const put = vi.fn().mockResolvedValue(undefined)
+ const thumbnail = fakeJpegFile()
// reqWithFile only stubs `get('file')`; extend it to also return w/h so the
// form-dimension parse in readFile sees them.
const req = reqWithFile(fakeFile("hi.png", "image/png", 10))
@@ -598,6 +753,8 @@ describe("runAttachmentUpload", () => {
value: (key: string) =>
key === "file"
? fakeFile("hi.png", "image/png", 10)
+ : key === "thumbnail"
+ ? thumbnail
: key === "width"
? "1920"
: key === "height"
@@ -669,10 +826,7 @@ describe("runAttachmentUpload", () => {
mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))
const put = vi.fn().mockResolvedValue(undefined)
const del = vi.fn().mockResolvedValue(undefined)
- const thumbnail = {
- ...fakeFile("thumbnail.jpg", "image/jpeg", 4),
- arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,
- }
+ const thumbnail = fakeJpegFile()
const response = await runAttachmentUpload(
reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),
ctxWith(envWithR2(put, del), { id: "c1" }),
@@ -689,10 +843,7 @@ describe("runAttachmentUpload", () => {
mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))
const put = vi.fn().mockResolvedValue(undefined)
const del = vi.fn().mockRejectedValueOnce(new TypeError("secret provider detail"))
- const thumbnail = {
- ...fakeFile("thumbnail.jpg", "image/jpeg", 4),
- arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,
- }
+ const thumbnail = fakeJpegFile()
const response = await runAttachmentUpload(
reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),
diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.ts
index 9f0b4e76e..8e55454a9 100644
--- a/src/web/src/lib/community/upload.ts
+++ b/src/web/src/lib/community/upload.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server"
import {
MAX_ATTACHMENT_SIZE_BYTES,
+ MAX_ATTACHMENT_THUMBNAIL_EDGE_PX,
MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
MAX_SERVER_ICON_SIZE_BYTES,
ALLOWED_ICON_MIME_TYPES,
@@ -109,6 +110,106 @@ function parseDimension(raw: FormDataEntryValue | null): number | undefined {
return Number.isInteger(n) && n >= 0 ? n : undefined
}
+const JPEG_SOF_MARKERS = new Set([
+ 0xc0, 0xc1, 0xc2, 0xc3,
+ 0xc5, 0xc6, 0xc7,
+ 0xc9, 0xca, 0xcb,
+ 0xcd, 0xce, 0xcf,
+])
+
+function jpegDimensions(bytes: Uint8Array): { width: number; height: number } | null {
+ if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null
+ let offset = 2
+ let dimensions: { width: number; height: number } | null = null
+ let frameComponentIds: Set<number> | null = null
+ let sawScan = false
+
+ while (offset < bytes.length) {
+ if (bytes[offset] !== 0xff) return null
+ while (bytes[offset] === 0xff) offset++
+ const marker = bytes[offset++]
+ if (marker === undefined || marker === 0x00 || marker === 0xd8) return null
+ if (marker === 0xd9) {
+ return sawScan && dimensions && offset === bytes.length ? dimensions : null
+ }
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) return null
+ if (offset + 1 >= bytes.length) return null
+ const length = (bytes[offset]! << 8) | bytes[offset + 1]!
+ if (length < 2 || offset + length > bytes.length) return null
+
+ if (JPEG_SOF_MARKERS.has(marker)) {
+ if (dimensions || length < 11) return null
+ const height = (bytes[offset + 3]! << 8) | bytes[offset + 4]!
+ const width = (bytes[offset + 5]! << 8) | bytes[offset + 6]!
+ const componentCount = bytes[offset + 7]!
+ if (
+ width === 0 || height === 0 || componentCount === 0 || componentCount > 4
+ || length !== 8 + 3 * componentCount
+ ) return null
+
+ frameComponentIds = new Set<number>()
+ for (let index = 0; index < componentCount; index++) {
+ const componentOffset = offset + 8 + index * 3
+ const id = bytes[componentOffset]!
+ const sampling = bytes[componentOffset + 1]!
+ if (frameComponentIds.has(id) || sampling === 0) return null
+ frameComponentIds.add(id)
+ }
+ dimensions = { width, height }
+ }
+
+ if (marker === 0xda) {
+ if (!dimensions || !frameComponentIds || length < 8) return null
+ const scanComponentCount = bytes[offset + 2]!
+ if (
+ scanComponentCount === 0 || scanComponentCount > frameComponentIds.size
+ || length !== 6 + 2 * scanComponentCount
+ ) return null
+
+ const scanComponentIds = new Set<number>()
+ for (let index = 0; index < scanComponentCount; index++) {
+ const id = bytes[offset + 3 + index * 2]!
+ if (!frameComponentIds.has(id) || scanComponentIds.has(id)) return null
+ scanComponentIds.add(id)
+ }
+
+ offset += length
+ let sawEntropyData = false
+ while (offset < bytes.length) {
+ if (bytes[offset] !== 0xff) {
+ sawEntropyData = true
+ offset++
+ continue
+ }
+
+ const markerOffset = offset
+ while (bytes[offset] === 0xff) offset++
+ const scanMarker = bytes[offset]
+ if (scanMarker === undefined) return null
+ if (scanMarker === 0x00) {
+ sawEntropyData = true
+ offset++
+ continue
+ }
+ if (scanMarker >= 0xd0 && scanMarker <= 0xd7) {
+ offset++
+ continue
+ }
+ if (!sawEntropyData) return null
+
+ sawScan = true
+ offset = markerOffset
+ break
+ }
+ if (!sawScan) return null
+ continue
+ }
+
+ offset += length
+ }
+ return null
+}
+
async function readFile(req: NextRequest): Promise<ParsedUpload | UploadErr> {
let formData: FormData
try {
@@ -165,6 +266,15 @@ export async function handleAttachmentUpload(
}
}
const contentType = file.type || "application/octet-stream"
+ const thumbnailRequired = isInlineAttachmentContentType(contentType) && (
+ file.size > MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES
+ || (width !== undefined && width > MAX_ATTACHMENT_THUMBNAIL_EDGE_PX)
+ || (height !== undefined && height > MAX_ATTACHMENT_THUMBNAIL_EDGE_PX)
+ )
+
+ if (thumbnailRequired && !thumbnail) {
+ return { ok: false, response: writeError("thumbnail required", 400) }
+ }
if (thumbnail) {
if (!isInlineAttachmentContentType(contentType)) {
@@ -177,15 +287,13 @@ export async function handleAttachmentUpload(
return { ok: false, response: writeError("thumbnail too large", 400) }
}
const signature = new Uint8Array(await thumbnail.arrayBuffer())
- if (
- signature.length < 4 ||
- signature[0] !== 0xff ||
- signature[1] !== 0xd8 ||
- signature.at(-2) !== 0xff ||
- signature.at(-1) !== 0xd9
- ) {
+ const dimensions = jpegDimensions(signature)
+ if (!dimensions) {
return { ok: false, response: writeError("invalid jpeg thumbnail", 400) }
}
+ if (Math.max(dimensions.width, dimensions.height) > MAX_ATTACHMENT_THUMBNAIL_EDGE_PX) {
+ return { ok: false, response: writeError("thumbnail dimensions too large", 400) }
+ }
}
const fileId = crypto.randomUUID()
diff --git a/src/web/src/lib/image-thumbnail.test.ts b/src/web/src/lib/image-thumbnail.test.ts
index e0b29995f..7003324cf 100644
--- a/src/web/src/lib/image-thumbnail.test.ts
+++ b/src/web/src/lib/image-thumbnail.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest"
-import { generateThumbnail } from "./image-thumbnail"
+import { generateThumbnail, prepareCommunityImage } from "./image-thumbnail"
// `generateThumbnail` runs entirely against browser APIs (Image decode,
// canvas draw, URL.createObjectURL) that don't exist under this repo's
@@ -32,7 +32,9 @@ class FakeImage {
static nextShouldError = false
}
-function stubBrowserImageApis() {
+function stubBrowserImageApis(blobSizes = [1]) {
+ const canvases: Array<{ width: number; height: number }> = []
+ let blobIndex = 0
vi.stubGlobal("Image", FakeImage)
vi.stubGlobal("URL", {
createObjectURL: vi.fn(() => "blob:fake"),
@@ -41,14 +43,20 @@ function stubBrowserImageApis() {
vi.stubGlobal("document", {
createElement: (tag: string) => {
if (tag !== "canvas") throw new Error(`unexpected createElement(${tag})`)
- return {
+ const canvas = {
width: 0,
height: 0,
getContext: () => ({ drawImage: vi.fn() }),
- toBlob: (cb: (b: Blob | null) => void) => cb({ size: 1 } as Blob),
+ toBlob: (cb: (b: Blob | null) => void) => {
+ const size = blobSizes[Math.min(blobIndex++, blobSizes.length - 1)]!
+ cb(new Blob([new Uint8Array(size)], { type: "image/jpeg" }))
+ },
}
+ canvases.push(canvas)
+ return canvas
},
})
+ return canvases
}
describe("generateThumbnail", () => {
@@ -90,4 +98,85 @@ describe("generateThumbnail", () => {
expect(result).toBeNull()
})
+
+ it("uses the original at the exact 1024px and 512 KiB boundaries", async () => {
+ const canvases = stubBrowserImageApis()
+ FakeImage.nextWidth = 1024
+ FakeImage.nextHeight = 768
+ const file = new File([new Uint8Array(512 * 1024)], "photo.png", { type: "image/png" })
+
+ const result = await prepareCommunityImage(file)
+
+ expect(result).toEqual({ blob: null, width: 1024, height: 768 })
+ expect(canvases).toHaveLength(0)
+ })
+
+ it("generates a 1024px preview when dimensions exceed the edge limit", async () => {
+ const canvases = stubBrowserImageApis([100])
+ FakeImage.nextWidth = 1025
+ FakeImage.nextHeight = 512
+ const file = new File([new Uint8Array(100)], "photo.png", { type: "image/png" })
+
+ const result = await prepareCommunityImage(file)
+
+ expect(result?.blob?.size).toBe(100)
+ expect(result).toMatchObject({ width: 1025, height: 512 })
+ expect(canvases[0]).toMatchObject({ width: 1024, height: 512 })
+ })
+
+ it("generates at original dimensions when only the byte limit is exceeded", async () => {
+ const canvases = stubBrowserImageApis([100])
+ FakeImage.nextWidth = 640
+ FakeImage.nextHeight = 480
+ const file = new File([new Uint8Array(512 * 1024 + 1)], "photo.png", { type: "image/png" })
+
+ const result = await prepareCommunityImage(file)
+
+ expect(result?.blob?.size).toBe(100)
+ expect(canvases[0]).toMatchObject({ width: 640, height: 480 })
+ })
+
+ it("reduces dimensions after exhausting bounded quality attempts", async () => {
+ const oversized = new Array(7).fill(512 * 1024 + 1)
+ const canvases = stubBrowserImageApis([...oversized, 256 * 1024])
+ FakeImage.nextWidth = 2048
+ FakeImage.nextHeight = 1024
+ const file = new File([new Uint8Array(100)], "photo.png", { type: "image/png" })
+
+ const result = await prepareCommunityImage(file)
+
+ expect(result?.blob?.size).toBe(256 * 1024)
+ expect(canvases).toHaveLength(2)
+ expect(canvases[0]).toMatchObject({ width: 1024, height: 512 })
+ expect(canvases[1]).toMatchObject({ width: 870, height: 435 })
+ })
+
+ it("throws when a thumbnail is required but encoding cannot satisfy the cap", async () => {
+ stubBrowserImageApis([512 * 1024 + 1])
+ FakeImage.nextWidth = 1025
+ FakeImage.nextHeight = 512
+ const file = new File([new Uint8Array(100)], "photo.png", { type: "image/png" })
+
+ await expect(prepareCommunityImage(file)).rejects.toThrow("required image preview")
+ })
+
+ it("throws when an over-byte-limit image cannot be decoded", async () => {
+ stubBrowserImageApis()
+ FakeImage.nextShouldError = true
+ const file = new File(
+ [new Uint8Array(512 * 1024 + 1)],
+ "corrupt.png",
+ { type: "image/png" },
+ )
+
+ await expect(prepareCommunityImage(file)).rejects.toThrow("required image preview")
+ })
+
+ it("returns null when an under-limit image cannot be decoded", async () => {
+ stubBrowserImageApis()
+ FakeImage.nextShouldError = true
+ const file = new File([new Uint8Array([0])], "corrupt.png", { type: "image/png" })
+
+ await expect(prepareCommunityImage(file)).resolves.toBeNull()
+ })
})
diff --git a/src/web/src/lib/image-thumbnail.ts b/src/web/src/lib/image-thumbnail.ts
index 8a37453e2..b87fbe901 100644
--- a/src/web/src/lib/image-thumbnail.ts
+++ b/src/web/src/lib/image-thumbnail.ts
@@ -1,48 +1,134 @@
-const MAX_SIZE = 200;
+import {
+ MAX_ATTACHMENT_THUMBNAIL_EDGE_PX,
+ MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
+} from "@alook/shared"
-export type ThumbnailResult = { blob: Blob; width: number; height: number };
+const LEGACY_MAX_SIZE = 200
+const COMMUNITY_QUALITIES = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]
+const COMMUNITY_DIMENSION_ATTEMPTS = 10
+const COMMUNITY_DIMENSION_SCALE = 0.85
+const COMMUNITY_RASTER_MIME_TYPES = new Set([
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+ "image/gif",
+])
+
+class RequiredThumbnailError extends Error {}
+
+export type ThumbnailResult = { blob: Blob; width: number; height: number }
+export type CommunityImagePreparation = { blob: Blob | null; width: number; height: number }
export async function generateThumbnail(file: File): Promise<ThumbnailResult | null> {
- if (!file.type.startsWith("image/") || file.type === "image/svg+xml") return null;
+ if (!isRasterImage(file)) return null
- let objectUrl: string | undefined;
+ let objectUrl: string | undefined
try {
- objectUrl = URL.createObjectURL(file);
- const img = await loadImage(objectUrl);
- const { w, h } = fitWithin(img.naturalWidth, img.naturalHeight, MAX_SIZE);
-
- const canvas = document.createElement("canvas");
- canvas.width = w;
- canvas.height = h;
- const ctx = canvas.getContext("2d");
- if (!ctx) return null;
- ctx.drawImage(img, 0, 0, w, h);
-
- const blob = await canvasToBlob(canvas, "image/jpeg", 0.7);
- if (!blob) return null;
- return { blob, width: img.naturalWidth, height: img.naturalHeight };
+ objectUrl = URL.createObjectURL(file)
+ const img = await loadImage(objectUrl)
+ const { w, h } = fitWithin(img.naturalWidth, img.naturalHeight, LEGACY_MAX_SIZE)
+
+ const blob = await renderJpeg(img, w, h, 0.7)
+ if (!blob) return null
+ return { blob, width: img.naturalWidth, height: img.naturalHeight }
} catch {
- return null;
+ return null
} finally {
- if (objectUrl) URL.revokeObjectURL(objectUrl);
+ if (objectUrl) URL.revokeObjectURL(objectUrl)
+ }
+}
+
+export async function prepareCommunityImage(
+ file: File,
+): Promise<CommunityImagePreparation | null> {
+ if (!COMMUNITY_RASTER_MIME_TYPES.has(file.type.toLowerCase())) return null
+
+ let objectUrl: string | undefined
+ let requiredThumbnail = file.size > MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES
+ try {
+ objectUrl = URL.createObjectURL(file)
+ const img = await loadImage(objectUrl)
+ const width = img.naturalWidth
+ const height = img.naturalHeight
+ requiredThumbnail = Math.max(width, height) > MAX_ATTACHMENT_THUMBNAIL_EDGE_PX
+ || requiredThumbnail
+ if (!requiredThumbnail) return { blob: null, width, height }
+
+ const blob = await renderCommunityJpeg(img)
+ if (!blob) throw new RequiredThumbnailError()
+ return { blob, width, height }
+ } catch (error) {
+ if (error instanceof RequiredThumbnailError) {
+ throw new Error("could not generate a required image preview")
+ }
+ if (requiredThumbnail) {
+ throw new Error("could not generate a required image preview")
+ }
+ return null
+ } finally {
+ if (objectUrl) URL.revokeObjectURL(objectUrl)
}
}
function loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = reject;
- img.src = src;
- });
+ const img = new Image()
+ img.onload = () => resolve(img)
+ img.onerror = reject
+ img.src = src
+ })
}
function fitWithin(srcW: number, srcH: number, max: number) {
- if (srcW <= max && srcH <= max) return { w: srcW, h: srcH };
- const scale = Math.min(max / srcW, max / srcH);
- return { w: Math.round(srcW * scale), h: Math.round(srcH * scale) };
+ if (srcW <= max && srcH <= max) return { w: srcW, h: srcH }
+ const scale = Math.min(max / srcW, max / srcH)
+ return { w: Math.round(srcW * scale), h: Math.round(srcH * scale) }
}
function canvasToBlob(canvas: HTMLCanvasElement, type: string, quality: number): Promise<Blob | null> {
- return new Promise((resolve) => canvas.toBlob(resolve, type, quality));
+ return new Promise((resolve) => canvas.toBlob(resolve, type, quality))
+}
+
+function isRasterImage(file: File): boolean {
+ return file.type.startsWith("image/") && file.type !== "image/svg+xml"
+}
+
+async function renderJpeg(
+ img: HTMLImageElement,
+ width: number,
+ height: number,
+ quality: number,
+): Promise<Blob | null> {
+ const canvas = document.createElement("canvas")
+ canvas.width = width
+ canvas.height = height
+ const ctx = canvas.getContext("2d")
+ if (!ctx) return null
+ ctx.drawImage(img, 0, 0, width, height)
+ return canvasToBlob(canvas, "image/jpeg", quality)
+}
+
+async function renderCommunityJpeg(img: HTMLImageElement): Promise<Blob | null> {
+ const fitted = fitWithin(
+ img.naturalWidth,
+ img.naturalHeight,
+ MAX_ATTACHMENT_THUMBNAIL_EDGE_PX,
+ )
+ for (let attempt = 0; attempt < COMMUNITY_DIMENSION_ATTEMPTS; attempt++) {
+ const scale = COMMUNITY_DIMENSION_SCALE ** attempt
+ const width = Math.max(1, Math.round(fitted.w * scale))
+ const height = Math.max(1, Math.round(fitted.h * scale))
+ const canvas = document.createElement("canvas")
+ canvas.width = width
+ canvas.height = height
+ const ctx = canvas.getContext("2d")
+ if (!ctx) return null
+ ctx.drawImage(img, 0, 0, width, height)
+ for (const quality of COMMUNITY_QUALITIES) {
+ const blob = await canvasToBlob(canvas, "image/jpeg", quality)
+ if (!blob) return null
+ if (blob.size <= MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES) return blob
+ }
+ }
+ return null
}
diff --git a/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts b/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts
index 3d421ddd1..21f3db810 100644
--- a/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts
+++ b/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts
@@ -1,10 +1,17 @@
import type { Page, WebSocket } from "@playwright/test"
+import { readFileSync } from "node:fs"
+import { resolve } from "node:path"
import { test, expect, sessionCookie } from "./_fixtures/community-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { seedChannel, seedJoinServer, seedServer } from "./_fixtures/seed"
import { tid } from "./_fixtures/testids"
import { WEB_URL } from "./_setup/paths"
+const VALID_JPEG_THUMBNAIL = readFileSync(resolve(
+ process.cwd(),
+ "public/blog/claude-code-dynamic-workflow-alternative/chat-interface.jpg",
+))
+
type DeleteFrame = {
type: "community:channel.delete" | "community:server.delete"
serverId: string
@@ -43,7 +50,7 @@ async function uploadPending(
if (withThumbnail) {
form.append(
"thumbnail",
- new Blob([new Uint8Array([0xff, 0xd8, 0xff, 0xd9])], { type: "image/jpeg" }),
+ new Blob([VALID_JPEG_THUMBNAIL], { type: "image/jpeg" }),
`${name}.thumbnail.jpg`,
)
}