Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Accept attachments of any file type as plain downloads
Bugfixer 2f42488d0b10c
diff --git a/server/attachments.test.ts b/server/attachments.test.tsindex 3096a58dac..a71a353a57 100644--- a/server/attachments.test.ts+++ b/server/attachments.test.ts@@ -554,7 +554,24 @@ describe("shared files", () => {expect(() => sanitizeSharedFileName("..\\..\\secret.txt", "text/plain")).toThrow(/filename, not a path/);expect(() => sanitizeSharedFileName("..%2F..%2Fsecret.txt", "text/plain")).toThrow(/filename, not a path/);expect(sanitizeSharedFileName("logs.tar.gz", "application/gzip")).toBe("logs.tar.gz");- expect(() => sanitizeSharedFileName("notes.txt", "application/x-msdownload")).toThrow(/supported document/);+ expect(sanitizeSharedFileName("Setup Tool.EXE", "application/x-msdownload")).toBe("Setup Tool.exe");+ expect(sanitizeSharedFileName("Makefile", "")).toBe("Makefile");+ expect(sanitizeSharedFileName("odd.name~", "application/octet-stream")).toBe("odd.name~");+ });++ it.each([+ ["script.py", "text/x-python", "script.py"],+ ["Setup.exe", "application/x-msdownload", "Setup.exe"],+ ["page.html", "text/html", "page.html"],+ ["logo.svg", "image/svg+xml", "logo.svg"],+ ["Makefile", "", "Makefile"],+ ["photo.png", "application/octet-stream", "photo.png"],+ ])("keeps %s (%s) as an inert download", async (original, mime, name) => {+ const saved = await saveFile((async function* () { yield Buffer.from("<b>x</b>"); })(), original, mime, { uploadId: UPLOAD_A });+ expect(saved).toMatchObject({ name, mime: "application/octet-stream", bytes: 8 });+ expect(saved.path).toBe(join(ATTACHMENTS_DIR, `${UPLOAD_A}.bin`));+ expect(readdirSync(ATTACHMENTS_DIR)).toEqual([`${UPLOAD_A}.bin`]);+ await expect(saveFile((async function* () { yield Buffer.from("x"); })(), "../evil.sh", mime)).rejects.toThrow(/filename, not a path/);});it("streams a file under a generated name with private permissions", async () => {diff --git a/server/attachments.ts b/server/attachments.tsindex cfc7bc7ece..6d8fbf027b 100644--- a/server/attachments.ts+++ b/server/attachments.ts@@ -69,7 +69,7 @@ const IMAGE_MIMES: Record<string, string> = {"image/webp": ".webp",};-/** No binaries, HTML, SVG or scripts; archives are kept as sent, never unpacked. The claimed mime picks the extension; an attacker's filename never does. */+/** Types kept under their own extension; archives are kept as sent, never unpacked. The claimed mime picks the stored extension; an attacker's filename never does. */const FILE_MIMES: Readonly<Record<string, string>> = {"video/mp4": ".mp4","video/webm": ".webm",@@ -113,6 +113,10 @@ const FILE_MIMES: Readonly<Record<string, string>> = {"application/x-xz": ".xz",};+/** Every other type (binaries, HTML, SVG, scripts) is stored as an inert `.bin` download, never rendered. */+const GENERIC_FILE_MIME = "application/octet-stream";+const GENERIC_FILE_EXTENSION = ".bin";+export function extensionForMime(mime: string | undefined): string | null {if (!mime) return null;return IMAGE_MIMES[mime.split(";")[0]!.trim().toLowerCase()] ?? null;@@ -352,7 +356,7 @@ async function withUploadLock<T>(uploadId: string | undefined, operation: () =>/** saveFile/saveImage only ever write `${uuid}${extension}` with one of these extensions. */const KNOWN_ATTACHMENT_EXTENSIONS = Array.from(- new Set([...Object.values(IMAGE_MIMES), ...Object.values(FILE_MIMES)]),+ new Set([...Object.values(IMAGE_MIMES), ...Object.values(FILE_MIMES), GENERIC_FILE_EXTENSION]),);function statSizeIfFile(path: string): number | null {@@ -407,11 +411,9 @@ export function extensionForFileMime(mime: string | undefined): string | null {return value ? FILE_MIMES[value] ?? null : null;}-/** Separators and encoded separators are rejected, not massaged, so traversal attempts stay visible as bad requests. */+/** Separators and encoded separators are rejected, not massaged, so traversal attempts stay visible as bad requests.+ * A known type takes its extension from the mime; any other keeps its own short one, in the display name only. */export function sanitizeSharedFileName(name: string, mime: string): string {- const extension = extensionForFileMime(mime);- if (!extension) throw statusError(400, "content-type must be a supported document or audio type");-const normalized = name.normalize("NFKC").trim();if (!normalized) throw statusError(400, "name is required");if (normalized.length > 512) throw statusError(400, "name is too long");@@ -420,7 +422,9 @@ export function sanitizeSharedFileName(name: string, mime: string): string {}const dot = normalized.lastIndexOf(".");- const withoutExtension = dot > 0 ? normalized.slice(0, dot) : normalized;+ const own = dot > 0 ? normalized.slice(dot).toLowerCase() : "";+ const extension = extensionForFileMime(mime) ?? (/^\.[a-z0-9]{1,10}$/.test(own) ? own : "");+ const withoutExtension = dot > 0 && extension ? normalized.slice(0, dot) : normalized;const safeCharacters = Array.from(withoutExtension, (character) => {const code = character.charCodeAt(0);return code <= 31 || code === 127 || "<>:\"|?*".includes(character) ? "_" : character;@@ -442,12 +446,10 @@ export async function saveFile(mime: string,options: { uploadId?: string; expectedBytes?: number } = {},): Promise<SavedFile> {- const normalized = normalizedMime(mime);- if (!normalized || !extensionForFileMime(normalized)) {- throw statusError(400, "content-type must be a supported document or audio type");- }+ const known = extensionForFileMime(mime);+ const normalized = known ? normalizedMime(mime)! : GENERIC_FILE_MIME;+ const extension = known ?? GENERIC_FILE_EXTENSION;const name = sanitizeSharedFileName(originalName, normalized);- const extension = extensionForFileMime(normalized)!;const uploadId = validateAttachmentUploadId(options.uploadId);const expectedBytes = options.expectedBytes;if (expectedBytes !== undefined && (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0)) {diff --git a/server/index.test.ts b/server/index.test.tsindex 47bef2248a..a4ae544118 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -5414,12 +5414,17 @@ describe("harness HTTP API", () => {expect(zipResult).toMatchObject({ name: "payload.zip", mime: "application/zip", bytes: archive.byteLength });expect(zipResult.path).toMatch(/\.zip$/);- const unsupported = await fetch(`${BASE}/api/files?name=payload.exe`, {+ const binary = await fetch(`${BASE}/api/files?name=payload.exe`, {method: "POST",headers: { "content-type": "application/x-msdownload" },body: Buffer.from("binary"),});- expect(unsupported.status).toBe(400);+ expect(binary.status).toBe(201);+ const binaryResult = await binary.json() as { path: string; name: string; mime: string };+ expect(binaryResult).toMatchObject({ name: "payload.exe", mime: "application/octet-stream" });+ expect(binaryResult.path).toMatch(/[\\/]attachments[\\/][0-9a-f-]+\.bin$/);+ const served = await fetch(`${BASE}/api/attachments/${binaryResult.path.split(/[\\/]/).at(-1)}`);+ expect(served.status).toBe(404);const missingName = await fetch(`${BASE}/api/files`, {method: "POST",diff --git a/src/lib/composer-attachments.ts b/src/lib/composer-attachments.tsindex 5cad7066dc..e280d0c7ac 100644--- a/src/lib/composer-attachments.ts+++ b/src/lib/composer-attachments.ts@@ -368,13 +368,15 @@ export async function imageAttachmentFromFile(};}-/** Copied into the private store so the companion route never sees an arbitrary Finder path. */-export async function fileAttachmentFromFile(file: File): Promise<FileAttachment | null> {+/** Copied into the private store so the companion route never sees an arbitrary Finder path.+ * `anyType` sends a file of any other type, which the server keeps as a plain download. */+export async function fileAttachmentFromFile(file: File, anyType = false): Promise<FileAttachment | null> {const declared = file.type.split(";", 1)[0]!.trim().toLowerCase();const extension = file.name.split(".").at(-1)?.toLowerCase() ?? "";const mime = documentMime(file) ??(ACCEPTED_AUDIO_MIMES.has(declared) ? declared : AUDIO_MIMES_BY_EXTENSION[extension]) ??- ARCHIVE_MIMES_BY_EXTENSION[extension];+ ARCHIVE_MIMES_BY_EXTENSION[extension] ??+ (anyType ? declared || "application/octet-stream" : undefined);if (!mime) return null;if (file.size > FILE_MAX_BYTES) throw new AttachError(file.name, FILE_MAX_BYTES);const uploadId = newUploadId();@@ -767,7 +769,8 @@ export async function intakeFiles<T extends DroppedFile & { type: string }>(allowImages: boolean;getPath: (file: T) => string;uploadImage: (file: T) => Promise<Attachment | null>;- uploadFile?: (file: T) => Promise<FileAttachment | null>;+ /** `anyType` is set for a file nothing else takes, to upload it as a plain download. */+ uploadFile?: (file: T, anyType?: boolean) => Promise<FileAttachment | null>;/** Images the message can still take; the rest are left out and named in the notice. */imageSlots?: number;/** Image bytes the message can still take; images past it are left out the same way. */@@ -779,9 +782,9 @@ export async function intakeFiles<T extends DroppedFile & { type: string }>(const overflow = new Set(fitImagesToSlots(images, _opts.imageSlots ?? Infinity, _opts.imageBytes).leftOut);const leftOut = [...overflow].map((file) => file.name);const files = _files.filter((file) => !overflow.has(file));- const uploadFile = _opts.uploadFile ?? (async (file: T) => {+ const uploadFile = _opts.uploadFile ?? (async (file: T, anyType?: boolean) => {if (!file.arrayBuffer) return null;- return fileAttachmentFromFile(file as unknown as File);+ return fileAttachmentFromFile(file as unknown as File, anyType);});const failed = (file: T, err: unknown): { uploadError: AttachProblem; uploadErrorText: string } => ({uploadError: err instanceof AttachError ? err.problem@@ -811,7 +814,13 @@ export async function intakeFiles<T extends DroppedFile & { type: string }>(return { attachments: [], rejectedNames: [], ...failed(file, err) };}const result = await attachmentsFromDroppedFiles([file], getPath);- return result;+ if (!result.rejectedNames.length) return result;+ try {+ const attachment = await uploadFile(file, true);+ return attachment ? { attachments: [attachment], rejectedNames: [] } : result;+ } catch (err) {+ return { attachments: [], rejectedNames: [], ...failed(file, err) };+ }}));const attachments = results.flatMap((result) => result.attachments);const rejectedNames = results.flatMap((result) => result.rejectedNames);diff --git a/src/lib/intake-files.test.ts b/src/lib/intake-files.test.tsindex 6317d7f97d..7bce323494 100644--- a/src/lib/intake-files.test.ts+++ b/src/lib/intake-files.test.ts@@ -181,6 +181,23 @@ describe("intakeFiles", () => {expect(out.notice).toBe("Unable to attach run.exe. Choose a supported image, document, or audio file.");});+ it("uploads a browser file of any other type as a plain download", async () => {+ const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({+ path: "/private/attachments/id.bin", name: "Setup.exe", bytes: 2,+ }), { status: 201, headers: { "content-type": "application/json" } }));+ try {+ const out = await intakeFiles([new File(["MZ"], "Setup.exe", { type: "application/x-msdownload" })], {+ allowImages: true, getPath: () => "", uploadImage: async () => null,+ });+ expect(fetch.mock.calls[0]![1]).toMatchObject({ headers: { "content-type": "application/x-msdownload" } });+ expect(out.attachments).toEqual([expect.objectContaining({ kind: "file", name: "Setup.exe", path: "/private/attachments/id.bin" })]);+ expect(out.problems).toEqual([]);+ expect(out.notice).toBeNull();+ } finally {+ fetch.mockRestore();+ }+ });+it("counts the images already in the draft, and names pasted images past the slots left", () => {const draft = [{ kind: "image" }, { kind: "file" }, { kind: "image" }] as unknown as Attachment[];expect(imageSlotsLeft(draft)).toBe(TURN_IMAGE_MAX_COUNT - 2);