Skip to content

Build your personal knowledge base with Trilium Notes

test(pwa): cover the share target's error paths, drop dead fallbacks

Elian Doran14ff18c5163d
diff --git a/apps/server/src/routes/api/share_target.spec.ts b/apps/server/src/routes/api/share_target.spec.ts
index 25682474d3..850289d23c 100644
--- a/apps/server/src/routes/api/share_target.spec.ts
+++ b/apps/server/src/routes/api/share_target.spec.ts
@@ -100,6 +100,21 @@ describe("POST /share-target", () => {
expect(note.getParentNotes().map((parent) => parent.noteId)).toEqual([ inbox.noteId ]);
});
+ it("saves into a protected inbox unprotected while the protected session is locked", async () => {
+ const inbox = cls.init(() => specialNotes.getInboxNote(dateUtils.localNowDate()));
+ inbox.isProtected = true;
+ try {
+ const res = await agent.post("/share-target").field("text", "while locked").expect(303);
+
+ const note = redirectedNote(res.headers.location);
+ expect(note.getParentNotes().map((parent) => parent.noteId)).toEqual([ inbox.noteId ]);
+ expect(note.isProtected).toBe(false);
+ expect(note.getContent()).toBe("<p>while locked</p>");
+ } finally {
+ inbox.isProtected = false;
+ }
+ });
+
it("accepts Samsung Internet's NUL byte between a CRLF and a boundary delimiter", async () => {
const boundary = "----MultipartBoundary--eyLOlXbH76aoDXmj8rZPdIY8RnUN0YjNE3TJOXyUwe----";
const body = Buffer.concat([
diff --git a/apps/server/src/routes/api/share_target.ts b/apps/server/src/routes/api/share_target.ts
index 599e8313f4..63de9cad1d 100644
--- a/apps/server/src/routes/api/share_target.ts
+++ b/apps/server/src/routes/api/share_target.ts
@@ -16,7 +16,7 @@ async function handleShare(req: Request, res: Response) {
const text = getOptionalString(req.body?.text);
const rawUrl = getOptionalString(req.body?.url);
const url = rawUrl ? sanitize.sanitizeUrl(rawUrl) : undefined;
- const files = (req.files as Express.Multer.File[] | undefined) ?? [];
+ const files = req.files as Express.Multer.File[];
if (!text && !url && files.length === 0) {
res.status(400).type("text/plain").send(t("share_target.nothing-to-share"));
@@ -71,11 +71,11 @@ function saveShare(rawTitle: unknown, text: string | undefined, url: string | un
}
const fileParent = containerNote ?? inboxNote;
- let firstFileNote: BNote | undefined;
+ const fileNotes: BNote[] = [];
for (const file of files) {
const content = readFileSync(file.path);
- const originalName = file.originalname || "file";
+ const originalName = file.originalname;
let note: BNote;
if (isAcceptedImageMime(file.mimetype)) {
@@ -87,17 +87,18 @@ function saveShare(rawTitle: unknown, text: string | undefined, url: string | un
title: deriveTitle(originalName, undefined),
content,
type: "file",
- mime: file.mimetype || "application/octet-stream",
+ mime: file.mimetype,
isProtected: isProtectedUnder(fileParent)
}));
note.addLabel("originalFileName", originalName);
}
note.addLabel("clipType", "share");
- firstFileNote ??= note;
+ fileNotes.push(note);
}
- const openNote = containerNote ?? firstFileNote ?? inboxNote;
+ // Without a parent note there is exactly one file: handleShare() refuses an empty share.
+ const openNote = containerNote ?? fileNotes[0];
return { openNote, imageNoteIds };
}
@@ -114,7 +115,7 @@ export function deriveTitle(rawTitle: unknown, fallbackBody: string | undefined)
return rawTitle.trim().slice(0, SAFE_TITLE_MAX);
}
if (fallbackBody) {
- const firstLine = fallbackBody.trim().split(/\r?\n/, 1)[0] ?? "";
+ const [ firstLine ] = fallbackBody.trim().split(/\r?\n/, 1);
if (firstLine) {
return firstLine.slice(0, SAFE_TITLE_MAX);
}
diff --git a/apps/server/src/routes/route_api.spec.ts b/apps/server/src/routes/route_api.spec.ts
index d9f9ada6da..1864425d96 100644
--- a/apps/server/src/routes/route_api.spec.ts
+++ b/apps/server/src/routes/route_api.spec.ts
@@ -9,6 +9,7 @@ import {
asyncRoute,
createShareTargetMiddleware,
importMiddlewareWithErrorHandling,
+ multipartBoundary,
route,
router,
stripNulBeforeDelimiters,
@@ -156,6 +157,47 @@ describe("createShareTargetMiddleware", () => {
expect(handler).not.toHaveBeenCalled();
await request(app).post("/share").attach("files", Buffer.from("1234"), "fits.bin").expect(200);
});
+
+ it("forwards a body busboy cannot parse as an error instead of reaching the handler", async () => {
+ const app = express();
+ const handler = vi.fn((_req: express.Request, res: express.Response) => res.sendStatus(200));
+ app.post("/share", createShareTargetMiddleware(), handler);
+ app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
+ res.status(500).send(err.message);
+ });
+
+ const unterminated = await request(app)
+ .post("/share")
+ .set("Content-Type", "multipart/form-data; boundary=b")
+ .send("--b\r\nContent-Disposition: form-data; name=\"text\"\r\n\r\nhi");
+ expect(unterminated.status).toBe(500);
+ expect(unterminated.text).toBe("Unexpected end of form");
+
+ const noBoundary = await request(app).post("/share").set("Content-Type", "multipart/form-data").send("x");
+ expect(noBoundary.status).toBe(500);
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("parses a body whose boundary is quoted", async () => {
+ const app = express();
+ app.post("/share", createShareTargetMiddleware(), (req, res) => res.json(req.body));
+
+ const res = await request(app)
+ .post("/share")
+ .set("Content-Type", "multipart/form-data; boundary=\"b c\"")
+ .send("--b c\r\nContent-Disposition: form-data; name=\"text\"\r\n\r\nhi\r\n\0--b c--\r\n");
+
+ expect(res.body).toEqual({ text: "hi" });
+ });
+});
+
+describe("multipartBoundary", () => {
+ it("reads a plain or quoted boundary parameter", () => {
+ expect(multipartBoundary("multipart/form-data; boundary=----abc")).toBe("----abc");
+ expect(multipartBoundary("multipart/form-data; charset=utf-8; BOUNDARY=\"a b\"")).toBe("a b");
+ expect(multipartBoundary("multipart/form-data")).toBeUndefined();
+ expect(multipartBoundary(undefined)).toBeUndefined();
+ });
});
describe("stripNulBeforeDelimiters", () => {
@@ -174,6 +216,16 @@ describe("stripNulBeforeDelimiters", () => {
expect(Buffer.concat(output).toString("latin1"), `split at ${split}`).toBe(expected);
}
});
+
+ it("passes the bytes through unchanged without a boundary", async () => {
+ const filter = stripNulBeforeDelimiters(undefined);
+ const output: Buffer[] = [];
+ filter.on("data", (chunk: Buffer) => output.push(chunk));
+ const ended = new Promise((resolve) => filter.on("end", resolve));
+ filter.end(Buffer.from("x\r\n\0--b", "latin1"));
+ await ended;
+ expect(Buffer.concat(output).toString("latin1")).toBe("x\r\n\0--b");
+ });
});
/**
diff --git a/apps/server/src/routes/route_api.ts b/apps/server/src/routes/route_api.ts
index 1d7d6208df..5f24dca90f 100644
--- a/apps/server/src/routes/route_api.ts
+++ b/apps/server/src/routes/route_api.ts
@@ -6,7 +6,7 @@ import { readFile, rm } from "fs/promises";
import { t } from "i18next";
import multer from "multer";
import { join } from "path";
-import { Transform } from "stream";
+import { PassThrough, Transform } from "stream";
import { bindEmitter } from "../cls_provider.js";
import auth from "../services/auth.js";
@@ -240,13 +240,7 @@ function createShareTargetUploadMiddleware(maxFileSize: number): RequestHandler
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);
- }
+ req.pipe(stripNulBeforeDelimiters(multipartBoundary(req.headers["content-type"]))).pipe(busboy);
}
};
options.limits = { ...options.limits, files: MAX_SHARED_FILES, fileSize: maxFileSize };
@@ -254,12 +248,22 @@ function createShareTargetUploadMiddleware(maxFileSize: number): RequestHandler
return multer(options).array("files");
}
+/** The `boundary` parameter of a multipart `Content-Type`, quoted or not. */
+export function multipartBoundary(contentType: string | undefined): string | undefined {
+ const match = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType ?? "");
+ return match?.[1] ?? match?.[2];
+}
+
/**
* 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 {
+export function stripNulBeforeDelimiters(boundary: string | undefined): Transform {
+ if (!boundary) {
+ return new PassThrough();
+ }
+
const needle = Buffer.from(`\r\n\0--${boundary}`, "latin1");
let pending = Buffer.alloc(0);