Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(standalone/import): don't mangle UTF-8 ZIP entry names
Elian Doran294307522c1a
diff --git a/apps/standalone/src/lightweight/zip_provider.spec.ts b/apps/standalone/src/lightweight/zip_provider.spec.tsindex 91fb645083..afcb7f964b 100644--- a/apps/standalone/src/lightweight/zip_provider.spec.ts+++ b/apps/standalone/src/lightweight/zip_provider.spec.ts@@ -28,6 +28,52 @@ async function readNames(buffer: Uint8Array, encoding?: string): Promise<string[return names;}+/**+ * Builds a ZIP whose entry names are raw bytes with the language-encoding flag (general purpose bit 11)+ * *clear* — what a legacy Windows archiver writes for a non-ASCII name, and the only case the encoding+ * detection is meant to rescue. fflate always writes UTF-8 and sets that flag, so the names are patched+ * in afterwards: each replacement must be the same byte length as its ASCII placeholder so every header+ * offset stays valid (the file name is not covered by the CRC or the recorded sizes). An entry given no+ * `nameBytes` is left exactly as fflate wrote it, so one archive can mix both conventions.+ */+function makeLegacyZip(entries: { placeholder: string; nameBytes?: number[] }[]): Uint8Array {+ const zip = zipSync(Object.fromEntries(entries.map(({ placeholder }) => [placeholder, strToU8("x")])));+ const byPlaceholder = new Map(+ entries.flatMap((e) => (e.nameBytes ? [[e.placeholder, e.nameBytes] as const] : []))+ );+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);++ for (let i = 0; i + 4 <= zip.length; i++) {+ const signature = view.getUint32(i, true);+ const isLocalHeader = signature === 0x04034b50;+ if (!isLocalHeader && signature !== 0x02014b50) {+ continue;+ }++ // Field offsets differ between the local file header and the central directory header.+ const flagsOffset = i + (isLocalHeader ? 6 : 8);+ const nameLength = view.getUint16(i + (isLocalHeader ? 26 : 28), true);+ const nameOffset = i + (isLocalHeader ? 30 : 46);+ const name = String.fromCharCode(...zip.subarray(nameOffset, nameOffset + nameLength));+ const replacement = byPlaceholder.get(name);++ if (!replacement) {+ continue;+ }+ if (replacement.length !== nameLength) {+ throw new Error(`Replacement for '${name}' must be ${nameLength} bytes, got ${replacement.length}.`);+ }++ zip.set(replacement, nameOffset);+ view.setUint16(flagsOffset, view.getUint16(flagsOffset, true) & ~0x800, true);+ }++ return zip;+}++// "啊.txt" as a legacy Chinese-Windows archiver writes it: 0xB0 0xA1 is the GBK encoding of 啊.+const GBK_NAME_BYTES = [0xb0, 0xa1, 0x2e, 0x74, 0x78, 0x74];+describe("BrowserZipArchive", () => {it("appends string and binary entries and sends them to a send()-style destination", async () => {const archive = provider.createZipArchive();@@ -151,26 +197,32 @@ describe("BrowserZipProvider.detectFilenameEncoding", () => {});it("detects GBK when a filename's raw bytes are a valid GBK pair", async () => {- // "°¡" round-trips through fflate as char codes 0xB0/0xA1, whose raw bytes- // [0xB0, 0xA1] are invalid UTF-8 but a valid GBK character.- const zip = makeZip({ "°¡.txt": "x" });+ // Raw bytes [0xB0, 0xA1] are invalid UTF-8 but a valid GBK character.+ const zip = makeLegacyZip([{ placeholder: "AB.txt", nameBytes: GBK_NAME_BYTES }]);expect(await provider.detectFilenameEncoding(zip)).toBe("gbk");});it("skips a failing candidate and detects a later one", async () => {- // "°.txt" → raw bytes [0xB0, 0x2E, ...]: 0x2E is an invalid GBK trail- // (so GBK is skipped), but 0xB0 is a valid single-byte Shift_JIS katakana.- const zip = makeZip({ "°.txt": "x" });+ // Raw bytes [0xB0, 0x2E, ...]: 0x2E is an invalid GBK trail (so GBK is skipped),+ // but 0xB0 is a valid single-byte Shift_JIS katakana.+ const zip = makeLegacyZip([{ placeholder: "A.txt", nameBytes: [0xb0, 0x2e, 0x74, 0x78, 0x74] }]);expect(await provider.detectFilenameEncoding(zip)).toBe("shift_jis");});it("falls back to utf-8 when no candidate encoding matches", async () => {// Raw byte 0xFE is invalid UTF-8 and an incomplete/invalid lead byte in// every CJK candidate (GBK/Shift_JIS/EUC-KR/Big5), so detection gives up.- const zip = makeZip({ [String.fromCharCode(0xfe)]: "x" });+ const zip = makeLegacyZip([{ placeholder: "A", nameBytes: [0xfe] }]);expect(await provider.detectFilenameEncoding(zip)).toBe("utf-8");});+ it("does not mistake a UTF-8-flagged archive for a CJK encoding", async () => {+ // "°" is one byte in Latin-1 but two in UTF-8. Reading a flagged entry's name back as if its+ // char codes were raw bytes makes detection see invalid UTF-8, pick GBK, and then mis-decode+ // every other name in the archive.+ expect(await provider.detectFilenameEncoding(makeZip({ "40°C.txt": "x" }))).toBe("utf-8");+ });+it("rejects when the archive cannot be read during detection", async () => {await expect(provider.detectFilenameEncoding(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))).rejects.toBeDefined();});@@ -192,6 +244,31 @@ describe("BrowserZipProvider.detectFilenameEncoding", () => {});});+describe("BrowserZipProvider UTF-8 filenames", () => {+ it("preserves a character outside Latin-1 in a UTF-8-flagged entry name", async () => {+ // An export names its entries after note titles, so a curly apostrophe (U+2019) is routine.+ // fflate sets the language-encoding flag for such an entry and hands back an already-decoded+ // string; truncating its char codes to single bytes silently corrupts the name, which then+ // matches nothing in !!!meta.json and derails the import.+ const name = "Private Murnahan’s Holotape.html";+ expect(await readNames(makeZip({ [name]: "x" }))).toEqual([name]);+ });++ it("keeps UTF-8-flagged names intact even when the archive also needs a legacy encoding", async () => {+ // A mixed archive: one entry written by a legacy archiver (raw GBK bytes, flag clear) and one+ // written with the flag set. Detection settles on GBK for the former; the latter must not be+ // re-decoded through it.+ const zip = makeLegacyZip([+ { placeholder: "AB.txt", nameBytes: GBK_NAME_BYTES },+ { placeholder: "Café.txt" } // no nameBytes: stays as fflate wrote it, flag and all+ ]);+ const encoding = await provider.detectFilenameEncoding(zip);++ expect(encoding).toBe("gbk");+ expect((await readNames(zip, encoding)).sort()).toEqual(["Café.txt", "啊.txt"]);+ });+});+describe("BrowserZipProvider filename re-decoding", () => {it("retries with utf-8 when the requested encoding cannot be constructed", async () => {// An unknown encoding makes the primary TextDecoder throw; the ASCII namediff --git a/apps/standalone/src/lightweight/zip_provider.ts b/apps/standalone/src/lightweight/zip_provider.tsindex 7fa963c705..98738480aa 100644--- a/apps/standalone/src/lightweight/zip_provider.ts+++ b/apps/standalone/src/lightweight/zip_provider.ts@@ -64,9 +64,7 @@ class BrowserZipArchive implements ZipArchive {export default class BrowserZipProvider implements ZipProvider {async detectFilenameEncoding(source: ZipSource): Promise<string> {const buffer = requireBuffer(source);- // fflate decodes filenames as CP437/Latin-1 (preserving raw bytes).- // We recover raw bytes and detect the encoding.- const rawSamples = await this.#collectRawFilenameSamples(buffer);+ const rawSamples = collectRawFilenameSamples(buffer);if (rawSamples.length === 0) {return "utf-8";}@@ -88,13 +86,17 @@ export default class BrowserZipProvider implements ZipProvider {): Promise<void> {const buffer = requireBuffer(source);return new Promise<void>((res, rej) => {+ // Read inside the executor so a malformed archive rejects rather than throwing+ // synchronously, matching how an unzip() failure surfaces.+ const fileNames = readCentralDirectory(buffer);+unzip(buffer, async (err, files) => {if (err) { rej(err); return; }try {for (const [fileName, data] of Object.entries(files)) {await processEntry(- { fileName: decodeZipFileName(fileName, filenameEncoding) },+ { fileName: decodeZipFileName(fileName, fileNames.get(fileName), filenameEncoding) },() => Promise.resolve(data));}@@ -105,56 +107,66 @@ export default class BrowserZipProvider implements ZipProvider {});});}+}- /**- * Does a first pass over the ZIP to collect raw filename bytes- * from entries that aren't valid UTF-8.- */- #collectRawFilenameSamples(buffer: Uint8Array): Promise<Uint8Array[]> {- return new Promise<Uint8Array[]>((res, rej) => {- unzip(buffer, (err, files) => {- if (err) { rej(err); return; }-- const samples: Uint8Array[] = [];- const utf8 = new TextDecoder("utf-8", { fatal: true });- for (const fileName of Object.keys(files)) {- const bytes = recoverRawBytes(fileName);- try {- utf8.decode(bytes);- } catch {- samples.push(bytes);- }- }- res(samples);- });- });- }+/** What an entry's name actually is on disk, as opposed to what fflate made of it. */+interface FileNameInfo {+ /** The name exactly as stored, undecoded. */+ rawBytes: Uint8Array;+ /** Whether the language encoding flag (general purpose bit 11) is set, i.e. the archive declares UTF-8. */+ isUtf8Flagged: boolean;}-/** Recover original raw bytes from fflate's CP437/Latin-1 decoded string. */-function recoverRawBytes(name: string): Uint8Array {- const bytes = new Uint8Array(name.length);- for (let i = 0; i < name.length; i++) {- bytes[i] = name.charCodeAt(i) & 0xff;+/**+ * Collects the raw name bytes of every entry whose encoding is genuinely unknown: the archive did not+ * flag it as UTF-8 and it does not decode as UTF-8 either.+ *+ * A flagged entry is excluded even when its bytes look unusual. Its encoding is already declared, so it+ * needs no rescuing — and sampling it would let one such name drag every *other* name in the archive+ * through the wrong decoder.+ */+function collectRawFilenameSamples(buffer: Uint8Array): Uint8Array[] {+ const utf8 = new TextDecoder("utf-8", { fatal: true });+ const samples: Uint8Array[] = [];++ for (const { rawBytes, isUtf8Flagged } of readCentralDirectory(buffer).values()) {+ if (isUtf8Flagged) {+ continue;+ }+ try {+ utf8.decode(rawBytes);+ } catch {+ samples.push(rawBytes);+ }}- return bytes;++ return samples;}/**- * fflate decodes ZIP entry filenames as CP437/Latin-1 unless the language- * encoding flag (general purpose bit 11) is set, but many real-world archives- * write UTF-8 or other encodings without setting that flag.- * Recover the original raw bytes and re-decode with the detected encoding.+ * Resolves an entry's name from what fflate decoded plus what the archive actually recorded.+ *+ * fflate hands names back already decoded, choosing UTF-8 or Latin-1 by the language encoding flag —+ * which it never exposes. A flagged name is therefore already correct and is passed through untouched;+ * re-deriving bytes from it would truncate every character above U+00FF (a curly apostrophe in a note+ * title becoming a control character, and the entry then matching nothing in `!!!meta.json`).+ *+ * Only an unflagged name is ambiguous — many real-world archives write UTF-8, or a legacy codepage,+ * without setting the flag — so those are re-decoded from their raw bytes with the detected encoding.*/-function decodeZipFileName(name: string, encoding?: string): string {- const bytes = recoverRawBytes(name);+function decodeZipFileName(name: string, info: FileNameInfo | undefined, encoding?: string): string {+ // A name missing from the central directory (a duplicate entry, say) keeps fflate's reading.+ if (!info || info.isUtf8Flagged) {+ return name;+ }+try {- return new TextDecoder(encoding || "utf-8", { fatal: true }).decode(bytes);+ return new TextDecoder(encoding || "utf-8", { fatal: true }).decode(info.rawBytes);} catch {if (encoding && encoding !== "utf-8") {// Encoding detection was wrong for this entry, try UTF-8try {- return new TextDecoder("utf-8", { fatal: true }).decode(bytes);+ return new TextDecoder("utf-8", { fatal: true }).decode(info.rawBytes);} catch {return name;}@@ -163,6 +175,88 @@ function decodeZipFileName(name: string, encoding?: string): string {}}+const CENTRAL_HEADER_SIGNATURE = 0x02014b50;+const END_OF_CENTRAL_DIRECTORY_SIGNATURE = 0x06054b50;+const CENTRAL_HEADER_LENGTH = 46;+const END_OF_CENTRAL_DIRECTORY_LENGTH = 22;+/** General purpose bit 11: the file name and comment are UTF-8. */+const UTF8_FLAG = 0x800;++/**+ * Reads the archive's central directory for the two facts fflate discards — each entry's raw name bytes+ * and its language encoding flag — keyed by the string fflate produces for that entry, which is the only+ * handle the callers have on it.+ *+ * This also replaces what used to be a second full `unzip()` pass done purely to sample file names: the+ * central directory carries them verbatim, so no entry has to be inflated to read one.+ */+function readCentralDirectory(buffer: Uint8Array): Map<string, FileNameInfo> {+ const entries = new Map<string, FileNameInfo>();+ if (buffer.byteLength < END_OF_CENTRAL_DIRECTORY_LENGTH) {+ throw new Error("Truncated ZIP: no end-of-central-directory record.");+ }++ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);++ // The end-of-central-directory record is last, but a trailing comment of up to 64 KiB may follow it.+ let eocd = -1;+ const earliest = Math.max(0, buffer.byteLength - END_OF_CENTRAL_DIRECTORY_LENGTH - 0xffff);+ for (let i = buffer.byteLength - END_OF_CENTRAL_DIRECTORY_LENGTH; i >= earliest; i--) {+ if (view.getUint32(i, true) === END_OF_CENTRAL_DIRECTORY_SIGNATURE) {+ eocd = i;+ break;+ }+ }+ if (eocd < 0) {+ throw new Error("Truncated ZIP: no end-of-central-directory record.");+ }++ // Walk the directory by header rather than by the recorded entry count, which saturates at 65535+ // (and is then only recoverable from a ZIP64 record). A ZIP64 offset saturates to 0xFFFFFFFF, which+ // lands past `end` and simply yields no entries — every name then keeps fflate's own decoding.+ let offset = view.getUint32(eocd + 16, true);+ const end = Math.min(buffer.byteLength, offset + view.getUint32(eocd + 12, true));++ while (offset + CENTRAL_HEADER_LENGTH <= end && view.getUint32(offset, true) === CENTRAL_HEADER_SIGNATURE) {+ const isUtf8Flagged = !!(view.getUint16(offset + 8, true) & UTF8_FLAG);+ const nameLength = view.getUint16(offset + 28, true);+ const extraLength = view.getUint16(offset + 30, true);+ const commentLength = view.getUint16(offset + 32, true);+ const nameStart = offset + CENTRAL_HEADER_LENGTH;++ if (nameStart + nameLength > end) {+ break;+ }++ const rawBytes = buffer.subarray(nameStart, nameStart + nameLength);+ entries.set(decodeAsFflateDoes(rawBytes, isUtf8Flagged), { rawBytes, isUtf8Flagged });++ offset = nameStart + nameLength + extraLength + commentLength;+ }++ return entries;+}++/**+ * Reproduces the string fflate hands back for an entry, so a central directory record can be matched to+ * it: UTF-8 when the archive flags the name as such, otherwise one character per byte.+ *+ * The Latin-1 branch cannot use `TextDecoder`, whose "latin1"/"iso-8859-1" labels are aliases of+ * windows-1252 and so map 0x80-0x9F to different code points than the plain byte-to-char widening+ * fflate performs.+ */+function decodeAsFflateDoes(rawBytes: Uint8Array, isUtf8Flagged: boolean): string {+ if (isUtf8Flagged) {+ return new TextDecoder("utf-8").decode(rawBytes);+ }++ let name = "";+ for (const byte of rawBytes) {+ name += String.fromCharCode(byte);+ }+ return name;+}+/** Common CJK encodings to try when filenames aren't valid UTF-8. */const CANDIDATE_ENCODINGS = ["gbk", "shift_jis", "euc-kr", "big5"];diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.tsindex 0265f6e5de..22e15423d8 100644--- a/packages/trilium-core/src/services/import/zip.spec.ts+++ b/packages/trilium-core/src/services/import/zip.spec.ts@@ -739,6 +739,48 @@ describe("processNoteContent", () => {await expect(testImportBuffer(zipBuffer, "import-name-collision-nested")).rejects.toThrow("Missing parent note ID.");});+ it("imports a note whose file name carries a character outside Latin-1", async () => {+ // Entry names come from note titles, so a curly apostrophe (U+2019) is routine. A provider that+ // mangles it makes the path miss its !!!meta.json entry, at which point the importer falls back+ // to path-based parentage and aborts on the folder it can no longer place the note under.+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "curlyFolder1",+ title: "Map",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Map.html",+ dirFileName: "Map",+ attributes: [],+ attachments: [],+ children: [{+ noteId: "curlyChild01",+ title: "Private Murnahan’s Holotape",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Private Murnahan’s Holotape.html",+ attributes: [],+ attachments: []+ }]+ }]+ };++ const zipBuffer = Buffer.from(zipSync({+ "!!!meta.json": strToU8(JSON.stringify(metaFile)),+ "Map.html": strToU8("<p>map</p>"),+ "Map/Private Murnahan’s Holotape.html": strToU8("<p>holotape</p>")+ }));++ const { rootNote } = await testImportBuffer(zipBuffer, "import-non-latin1-name");+ const folder = rootNote.getChildNotes().find((n) => n.title === "Map");++ expect(folder?.getChildNotes().map((n) => n.title)).toEqual(["Private Murnahan’s Holotape"]);+ });+it("restores a cloned note whose clone entry precedes its primary", async () => {// An export writes a clone as a stub entry carrying the same noteId as the primary. When the// stub is read first, its branch materialises a type-less skeleton note in becca; the primary