Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: reject ZIP members with unsafe asset names in the ChatGPT importer (#5652)
Adam Eivy1e33bc1c0441
diff --git a/server/services/chatgptZipImport.js b/server/services/chatgptZipImport.jsindex 079959476b..b81d00ec4f 100644--- a/server/services/chatgptZipImport.js+++ b/server/services/chatgptZipImport.js@@ -31,8 +31,10 @@import { createReadStream, createWriteStream } from 'fs';import { rename, unlink } from 'fs/promises';+import { join } from 'path';import { Writable } from 'stream';import { PATHS, getMimeType, ensureDir } from '../lib/fileUtils.js';+import { isTopLevelEntryName } from '../lib/pathSafety.js';import { parseZip, collectZipEntry, MAX_ZIP_MEMBER_BYTES } from '../lib/zipStream.js';import { parseExport, importConversations, assetPointerId } from './chatgptImport.js';import { ServerError } from '../lib/errorHandler.js';@@ -102,7 +104,35 @@ const IS_ASSET_NAME_MAP = (path) => /(?:^|\/)conversation_asset_file_names\.json// A `.dat` member's asset id is its basename without extension. Conversations// reference assets as `file-service://file-XXX` / `sediment://file_HASH`, both// of which `assetPointerId()` reduces to that same bare id.-const datAssetId = (path) => path.replace(/^.*\//, '').replace(/\.dat$/i, '');+//+// Splits on BOTH separators so the id is always a real basename on every+// platform: a hostile archive can name a member `a\..\..\evil.dat`, and a+// forward-slash-only strip would leave the backslashes in the id — on Windows+// `${assetDir}/${id}` would then escape the asset dir (Zip Slip).+const datAssetId = (path) => path.split(/[\\/]/).pop().replace(/\.dat$/i, '');++// A `.dat` member is extractable only when BOTH its ZIP-spec name and the asset+// id it reduces to are plain filenames.+//+// The ZIP spec mandates `/` as the only separator, so everything after the last+// `/` is one filename — a `\` or `..` surviving there means a hostile or+// malformed member, not a nested directory, and it is skipped rather than+// silently normalized into an extracted file. The second half catches ids that+// degenerate once `.dat` is dropped (`.dat` -> ``, `..dat` -> `.`), which would+// otherwise write a `.png` / `..png` dotfile into the served dir.+//+// `zipStream.js` also sanitizes separators and `.`/`..` components as it decodes+// each header, so a traversal has to defeat two independent layers to land. This+// one is the layer that matters here: the parser's sanitizing is its own private+// policy, while the consumer is what actually opens the file, and keeping the+// check at the write site means a future faithful-reader refactor of the parser+// cannot silently reintroduce the escape.+const isSafeDatMember = (path) =>+ isTopLevelEntryName(path.replace(/^.*\//, '')) && isTopLevelEntryName(datAssetId(path));++// Single-sourced so both guards below log identically. Deliberately carries NO+// member path — the name is untrusted third-party text.+const UNSAFE_MEMBER_WARNING = '⚠️ ChatGPT import: skipped a ZIP member with an unsafe asset name';// Stream a `.dat` entry straight to `filePath`, holding only the leading// `SNIFF_BYTES` so the asset's real extension can be sniffed without buffering@@ -206,8 +236,18 @@ export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportA// bytes to sniff the extension. Peak RAM is one chunk regardless of// asset size, so there is no aggregate ceiling and a multi-GB export// imports without OOM risk. Renamed to its final served name below.+ // Refuse any member whose name isn't a plain filename BEFORE the temp+ // file is opened. Skip the member rather than failing the whole+ // import: one malformed member in a multi-GB export shouldn't cost the+ // user the entire ingest, and a conversation referencing it simply+ // renders without its asset (the resolver already returns null).+ if (!isSafeDatMember(path)) {+ console.warn(UNSAFE_MEMBER_WARNING);+ entry.autodrain();+ return;+ }const assetId = datAssetId(path);- const tempPath = `${assetDir}/${assetId}.part`;+ const tempPath = join(assetDir, `${assetId}.part`);tempPaths.add(tempPath);inFlight.push(streamAssetToFile(entry, tempPath, MAX_MEMBER_BYTES).then((sniffedExt) => { pendingAssets.set(assetId, { datPath: path, tempPath, sniffedExt }); })@@ -250,7 +290,16 @@ export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportAconst friendlyName = assetNameMap[`${assetId}.dat`] || assetNameMap[datPath] || null;const ext = sniffedExt || extFromName(friendlyName) || '.bin';const fileName = `${assetId}${ext}`;- const filePath = `${assetDir}/${fileName}`;+ // Defense in depth: `assetId` was already vetted above, but `ext` comes+ // from `extFromName`/the sniffer — re-check the composed name so a future+ // change there can't reintroduce a traversal.+ if (!isTopLevelEntryName(fileName)) {+ console.warn(UNSAFE_MEMBER_WARNING);+ // eslint-disable-next-line no-await-in-loop -- same sequential loop+ await unlink(tempPath).catch(() => {});+ continue;+ }+ const filePath = join(assetDir, fileName);// eslint-disable-next-line no-await-in-loop -- sequential rename keeps peak// disk/IO bounded; an export has a few hundred assets, not millions.await rename(tempPath, filePath);@@ -359,4 +408,4 @@ export async function importChatgptZip(zipPath, { tags, skipEmpty } = {}) {};}-export const __test = { sniffExtension, extFromName, datAssetId, makeAssetResolver, cleanupExtractedAssets };+export const __test = { sniffExtension, extFromName, datAssetId, isSafeDatMember, makeAssetResolver, cleanupExtractedAssets };diff --git a/server/services/chatgptZipImport.test.js b/server/services/chatgptZipImport.test.jsindex 1e8e6ffb89..6178df94fe 100644--- a/server/services/chatgptZipImport.test.js+++ b/server/services/chatgptZipImport.test.js@@ -72,6 +72,31 @@ describe('chatgptZipImport service', () => {expect(datAssetId('file-ABC123.dat')).toBe('file-ABC123');expect(datAssetId('nested/dir/file_DEADBEEF.dat')).toBe('file_DEADBEEF');});+ it('splits on backslashes too, so a Windows-style member reduces to a basename', () => {+ expect(datAssetId('a\\..\\..\\evil.dat')).toBe('evil');+ expect(datAssetId('nested\\dir\\file-ABC.dat')).toBe('file-ABC');+ });+ });++ describe('isSafeDatMember', () => {+ it('accepts plain and forward-slash-nested member names', async () => {+ const { isSafeDatMember } = (await import('./chatgptZipImport.js')).__test;+ expect(isSafeDatMember('file-ABC.dat')).toBe(true);+ expect(isSafeDatMember('chat/files/file-abc.dat')).toBe(true);+ });+ it('rejects backslash separators, NUL, and empty/dot ids', async () => {+ const { isSafeDatMember } = (await import('./chatgptZipImport.js')).__test;+ // A `\` is NOT a ZIP separator, so a name carrying one is malformed or+ // hostile — refused rather than normalized into an extracted file.+ expect(isSafeDatMember('a\\..\\..\\evil.dat')).toBe(false);+ expect(isSafeDatMember('files/..\\evil.dat')).toBe(false);+ expect(isSafeDatMember('bad\u0000name.dat')).toBe(false);+ expect(isSafeDatMember('.dat')).toBe(false); // id becomes ''+ expect(isSafeDatMember('..dat')).toBe(false); // id becomes '.'+ // Forward-slash components ARE directories: the basename is what's used,+ // so traversal components reduce away harmlessly.+ expect(isSafeDatMember('../../evil.dat')).toBe(true);+ });});describe('extFromName (fallback extension allowlist)', () => {@@ -172,6 +197,73 @@ describe('chatgptZipImport service', () => {expect(written).toEqual([]); // no <id>.part temp left behind});+ it('writes nothing outside the asset dir for a member whose name carries backslashes', async () => {+ // `a\..\..\evil.dat` is the classic Zip Slip shape. Two independent+ // layers stop it: `zipStream.js` sanitizes separators/traversal on the way+ // out of the parser, and `isSafeDatMember` refuses anything that still+ // isn't a plain filename before the temp file is opened. This pins the+ // end-to-end outcome — no write lands outside `assetDir` on any platform,+ // and the rest of the import still succeeds.+ const assetDir = join(TMP, 'nest', 'assets');+ const zipPath = await writeZip([+ ['conversations-000.json', JSON.stringify([{ id: 'c1', title: 'A', mapping: {} }])],+ ['a\\..\\..\\evil.dat', PNG],+ ['file-OK.dat', JPEG],+ ]);+ const { conversationFiles, assets } = await extractChatgptZip(zipPath, { assetDir });++ expect(conversationFiles.length).toBe(1);+ expect(assets.get('file-OK').file).toBe('file-OK.jpg');+ // Nothing escaped into a sibling or parent directory.+ expect((await readdir(join(TMP, 'nest'))).sort()).toEqual(['assets']);+ expect((await readdir(TMP)).sort()).toEqual(['export.zip', 'nest']);+ // Every extracted file sits directly inside the asset dir.+ for (const name of await readdir(assetDir)) {+ expect(name.includes('/')).toBe(false);+ expect(name.includes('\\')).toBe(false);+ }+ });++ it('skips a .dat member whose name contains a NUL instead of failing the whole import', async () => {+ // A NUL survives the parser's sanitizer, and `createWriteStream` on such a+ // path errors — which used to reject the ENTIRE import. The member is now+ // skipped and the rest of the export still lands.+ const assetDir = join(TMP, 'assets');+ const zipPath = await writeZip([+ ['conversations-000.json', JSON.stringify([{ id: 'c1', title: 'A', mapping: {} }])],+ ['bad\u0000name.dat', PNG],+ ['file-OK.dat', JPEG],+ ]);+ const { conversationFiles, stats } = await extractChatgptZip(zipPath, { assetDir });+ expect(conversationFiles.length).toBe(1);+ expect(stats.assetCount).toBe(1);+ expect(await readdir(assetDir)).toEqual(['file-OK.jpg']);+ });++ it('skips .dat members whose id degenerates to "" or "." rather than writing a dotfile', async () => {+ const assetDir = join(TMP, 'assets');+ const zipPath = await writeZip([+ ['conversations-000.json', JSON.stringify([{ id: 'c1', title: 'A', mapping: {} }])],+ ['..dat', PNG], // id '.'+ ['.dat', PNG], // id ''+ ]);+ const { stats } = await extractChatgptZip(zipPath, { assetDir });+ expect(stats.assetCount).toBe(0);+ expect(await readdir(assetDir)).toEqual([]); // no `..png` / `.png` dotfiles+ });++ it('still extracts a normally-nested member such as chat/files/file-abc.dat', async () => {+ const assetDir = join(TMP, 'assets');+ const zipPath = await writeZip([+ ['conversations-000.json', JSON.stringify([{ id: 'c1', title: 'A', mapping: {} }])],+ ['chat/files/file-abc.dat', PNG],+ ]);+ const { assets, stats } = await extractChatgptZip(zipPath, { assetDir });+ expect(stats.assetCount).toBe(1);+ expect(assets.get('file-abc').file).toBe('file-abc.png');+ expect(await readdir(assetDir)).toEqual(['file-abc.png']);+ });+it('cleans up already-written assets and throws a 400 when a conversation shard is corrupt JSON', async () => {const zipPath = await writeZip([['conversations-000.json', '[{ "id": "c1", "title": "A", "mapping": {} '], // truncated → JSON.parse throws