Skip to content

Build your personal knowledge base with Trilium Notes

fix(pwa): accept Samsung Internet's share-target bodies

Elian Doran680754520f4b
diff --git a/apps/server/src/routes/api/share_target.spec.ts b/apps/server/src/routes/api/share_target.spec.ts
index 840ea09d2a..f70184be01 100644
--- a/apps/server/src/routes/api/share_target.spec.ts
+++ b/apps/server/src/routes/api/share_target.spec.ts
@@ -87,6 +87,28 @@ describe("POST /share-target", () => {
expect(note.getParentNotes().map((parent) => parent.noteId)).toEqual([ inbox.noteId ]);
});
+ it("accepts Samsung Internet's NUL byte between a CRLF and a boundary delimiter", async () => {
+ const boundary = "----MultipartBoundary--eyLOlXbH76aoDXmj8rZPdIY8RnUN0YjNE3TJOXyUwe----";
+ const body = Buffer.concat([
+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="text"\r\n\r\nFrom the gallery\r\n\0`),
+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="files"; filename="IMG_1.png"\r\nContent-Type: image/png\r\n\r\n`),
+ PNG,
+ Buffer.from(`\r\n\0--${boundary}--\r\n`)
+ ]);
+
+ const res = await agent
+ .post("/share-target")
+ .set("Content-Type", `multipart/form-data; boundary=${boundary}`)
+ .send(body)
+ .expect(303);
+
+ const parent = redirectedNote(res.headers.location);
+ expect(parent.getContent()).toBe("<p>From the gallery</p>");
+ const [ image ] = parent.getChildNotes();
+ expect(image?.title).toBe("IMG_1.png");
+ expect(image?.mime).toBe("image/png");
+ });
+
it("groups several files under a parent note, with their images already stored", async () => {
const res = await agent
.post("/share-target")
diff --git a/apps/server/src/routes/route_api.spec.ts b/apps/server/src/routes/route_api.spec.ts
index 11716afc68..c9fa396fcc 100644
--- a/apps/server/src/routes/route_api.spec.ts
+++ b/apps/server/src/routes/route_api.spec.ts
@@ -10,6 +10,7 @@ import {
importMiddlewareWithErrorHandling,
route,
router,
+ stripNulBeforeDelimiters,
uploadMiddlewareWithErrorHandling
} from "./route_api.js";
@@ -141,6 +142,24 @@ describe("uploadMiddlewareWithErrorHandling (in-memory)", () => {
});
});
+describe("stripNulBeforeDelimiters", () => {
+ it("drops the NUL before every delimiter, wherever the chunks split it", async () => {
+ const input = Buffer.from("--b\r\n\r\nx\0y\r\n\0--b\r\n\r\nz\r\n\0--b--\r\n", "latin1");
+ const expected = "--b\r\n\r\nx\0y\r\n--b\r\n\r\nz\r\n--b--\r\n";
+
+ for (let split = 0; split <= input.length; split++) {
+ const filter = stripNulBeforeDelimiters("b");
+ const output: Buffer[] = [];
+ filter.on("data", (chunk: Buffer) => output.push(chunk));
+ const ended = new Promise((resolve) => filter.on("end", resolve));
+ filter.write(input.subarray(0, split));
+ filter.end(input.subarray(split));
+ await ended;
+ expect(Buffer.concat(output).toString("latin1"), `split at ${split}`).toBe(expected);
+ }
+ });
+});
+
/**
* `internalRoute` opens the CLS context every API handler runs in and seeds it from the
* `trilium-*` request headers. Entity changes are collected against that context, so losing it
diff --git a/apps/server/src/routes/route_api.ts b/apps/server/src/routes/route_api.ts
index 2b9077c11a..b4d20b32db 100644
--- a/apps/server/src/routes/route_api.ts
+++ b/apps/server/src/routes/route_api.ts
@@ -5,6 +5,7 @@ import { mkdirSync } from "fs";
import { readFile, rm } from "fs/promises";
import multer from "multer";
import { join } from "path";
+import { Transform } from "stream";
import { bindEmitter } from "../cls_provider.js";
import auth from "../services/auth.js";
@@ -200,13 +201,53 @@ export const MAX_SHARED_FILES = 20;
export function createShareTargetUploadMiddleware(): RequestHandler {
// Disk storage: a share can carry several large files, so the handler reads them back from
// `file.path` one at a time instead of holding all of them in memory.
- const options = baseMulterOptions();
+ const options: multer.Options & { streamHandler?: (req: express.Request, busboy: NodeJS.WritableStream) => void } = {
+ ...baseMulterOptions(),
+ storage: tmpDirStorage(),
+ // `streamHandler` is not yet in @types/multer 2.3.0.
+ streamHandler: (req, busboy) => {
+ const boundary = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(req.headers["content-type"] ?? "");
+ const delimiterBoundary = boundary?.[1] ?? boundary?.[2];
+ if (delimiterBoundary) {
+ req.pipe(stripNulBeforeDelimiters(delimiterBoundary)).pipe(busboy);
+ } else {
+ req.pipe(busboy);
+ }
+ }
+ };
+ options.limits = { ...options.limits, files: MAX_SHARED_FILES };
- return multer({
- ...options,
- limits: { ...options.limits, files: MAX_SHARED_FILES },
- storage: tmpDirStorage()
- }).array("files");
+ return multer(options).array("files");
+}
+
+/**
+ * Removes the NUL byte that Samsung Internet writes between the CRLF and a boundary delimiter
+ * (`\r\n\0--boundary`) in a Web Share Target body; busboy rejects that body as "Unexpected end of
+ * form".
+ */
+export function stripNulBeforeDelimiters(boundary: string): Transform {
+ const needle = Buffer.from(`\r\n\0--${boundary}`, "latin1");
+ let pending = Buffer.alloc(0);
+
+ return new Transform({
+ transform(chunk: Buffer, _encoding, callback) {
+ const data = Buffer.concat([ pending, chunk ]);
+ const parts: Buffer[] = [];
+ let start = 0;
+ for (let index = data.indexOf(needle); index !== -1; index = data.indexOf(needle, start)) {
+ parts.push(data.subarray(start, index + 2));
+ start = index + 3;
+ }
+ // Holds back a tail that could be the start of a needle split across chunks.
+ const keepFrom = Math.max(start, data.length - (needle.length - 1));
+ parts.push(data.subarray(start, keepFrom));
+ pending = data.subarray(keepFrom);
+ callback(null, Buffer.concat(parts));
+ },
+ flush(callback) {
+ callback(null, pending);
+ }
+ });
}
/** Writes each uploaded file to `upload/` under `dataDirs.TMP_DIR`. */