Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix: keep browser download filenames portable and valid

Afloatbdb05d66cfb4
diff --git a/server/browser/cdp/downloads.ts b/server/browser/cdp/downloads.ts
index c2dc015794..b7a024107a 100644
--- a/server/browser/cdp/downloads.ts
+++ b/server/browser/cdp/downloads.ts
@@ -31,13 +31,22 @@ export interface DownloadLimits {
export const DOWNLOAD_LIMITS: DownloadLimits = { maxBytes: 1024 ** 3, perOwner: 20 };
const UNSAFE_NAME = /[\p{Cc}<>:"/\\|?*]/gu;
+const WINDOWS_DEVICE = /^(?:con|prn|aux|nul|conin\$|conout\$|clock\$|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3]) *(?:\..*)?$/iu;
export function safeFileName(suggested: string): string {
const base = suggested.split(/[\\/]/).pop() ?? "";
const cleaned = base.replace(UNSAFE_NAME, "_").replace(/^[.\s]+|[.\s]+$/g, "");
- let name = cleaned || "download";
- while (Buffer.byteLength(name, "utf8") > 255) name = name.slice(0, -1);
- return name;
+ const maxBytes = WINDOWS_DEVICE.test(cleaned) ? 254 : 255;
+ let name = "";
+ let bytes = 0;
+ for (const character of cleaned || "download") {
+ const size = Buffer.byteLength(character, "utf8");
+ if (bytes + size > maxBytes) break;
+ name += character;
+ bytes += size;
+ }
+ name = name.replace(/[.\s]+$/g, "") || "download";
+ return WINDOWS_DEVICE.test(name) ? `_${name}` : name;
}
/** Downloads land as `<dir>/<id>/<name>`: Chrome writes `<dir>/<guid>` (allowAndName) and the finished file moves. */
diff --git a/server/browser/cdp/driver-parts.test.ts b/server/browser/cdp/driver-parts.test.ts
index d9ec64154f..4a2e585160 100644
--- a/server/browser/cdp/driver-parts.test.ts
+++ b/server/browser/cdp/driver-parts.test.ts
@@ -170,6 +170,21 @@ describe("small rules", () => {
expect(Buffer.byteLength(safeFileName(`${"é".repeat(300)}.txt`))).toBeLessThanOrEqual(255);
});
+ it.each(["CON", "con.txt", "AUX.csv", "NUL .txt", "COM1.log", "LPT².txt", "CONIN$"])("makes reserved Windows download name %s usable", (name) => {
+ expect(safeFileName(name)).toBe(`_${name}`);
+ });
+
+ it("truncates long download names at complete Unicode characters", () => {
+ const name = safeFileName(`${"a".repeat(252)}🙂.txt`);
+ expect(name).toBe("a".repeat(252));
+ expect(Buffer.from(name, "utf8").toString("utf8")).toBe(name);
+ });
+
+ it("removes trailing dots or spaces introduced by the byte limit", () => {
+ expect(safeFileName(`${"a".repeat(254)}.txt`)).toBe("a".repeat(254));
+ expect(safeFileName(`${"a".repeat(254)} remainder.txt`)).toBe("a".repeat(254));
+ });
+
it("reports addresses without their queries, and names human checks by their frames", () => {
expect(reportableUrl("https://shop.example/api/cart?token=secret#x")).toBe("https://shop.example/api/cart");
expect(reportableUrl("data:text/html,<p>hi")).toBe("data:…");