Skip to content

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

fix([issue-1532]): consume clinical_records ZIP entries via streaming, not entry.on()

[._.]/ Adam Eivy6346f009fdb7
diff --git a/server/lib/README.md b/server/lib/README.md
index 8f201630c9..770eca0950 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -114,7 +114,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `multipart.js` | Streaming multipart/form-data parser. |
| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. |
| `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |
-| `zipStream.js` | Streaming ZIP parser (`parseZip`, unzipper-style); `extractZipEntryToBuffer(path, match)` cracks one member out to a Buffer. |
+| `zipStream.js` | Streaming ZIP parser (`parseZip`, unzipper-style); `collectZipEntry(entry, maxBytes?)` buffers one `parseZip` entry into a Buffer (size-capped); `extractZipEntryToBuffer(path, match)` cracks one member out to a Buffer. |
| `zipWriter.js` | Minimal ZIP writer — `createZip(entries)` builds a stored (uncompressed) archive Buffer that round-trips through `parseZip`; `crc32(buf)` is the dependency-free checksum it uses. |
| `assetHash.js` | Cross-transport SHA-256 cache for `data/images/*` — persists hashes in the asset's `.metadata.json` sidecar so the share-bucket exporter and the federated peer-sync push pipeline reuse the same value. `sidecarGenParamsHash` canonically hashes a sidecar's gen-params (excludes the machine-local `sha256` cache block) for cross-machine sidecar-convergence comparisons. |
diff --git a/server/lib/zipStream.js b/server/lib/zipStream.js
index bda24083ec..08c9fe22ba 100644
--- a/server/lib/zipStream.js
+++ b/server/lib/zipStream.js
@@ -200,6 +200,38 @@ export function parseZip() {
return sink;
}
+/**
+ * Collect a single `parseZip()` entry's decompressed bytes into one Buffer.
+ *
+ * `parseZip()` entries are NOT readable streams — they expose only `.pipe(dest)`
+ * / `.autodrain()`, so the EventEmitter idiom `entry.on('data'/'end')` throws
+ * `entry.on is not a function`. Pipe the entry into a collecting Writable and
+ * resolve with the concatenated buffer instead. When `maxBytes` is finite the
+ * collect rejects once the member exceeds it, rather than buffering an unbounded
+ * amount into memory.
+ *
+ * Call this synchronously inside the `entry` handler (entries auto-drain on the
+ * next tick if nothing attaches a pipe/drain), and gather the returned promises
+ * so the parser's `close` handler can `Promise.all` them before settling.
+ */
+export function collectZipEntry(entry, maxBytes = Infinity) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let size = 0;
+ const sink = new Writable({
+ write(chunk, _enc, cb) {
+ size += chunk.length;
+ if (size > maxBytes) { cb(new Error(`ZIP member exceeds ${maxBytes} byte limit`)); return; }
+ chunks.push(chunk);
+ cb();
+ }
+ });
+ sink.on('finish', () => resolve(Buffer.concat(chunks)));
+ sink.on('error', reject);
+ entry.pipe(sink);
+ });
+}
+
/**
* Extract the first entry whose path satisfies `match` (a predicate or a
* substring) from a zip on disk, resolving to its decompressed Buffer (or null
diff --git a/server/lib/zipStream.test.js b/server/lib/zipStream.test.js
index 0a460216a6..0115623b97 100644
--- a/server/lib/zipStream.test.js
+++ b/server/lib/zipStream.test.js
@@ -4,7 +4,7 @@ import { deflateRawSync } from 'zlib';
import { writeFile, rm, mkdtemp } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
-import { parseZip, extractZipEntryToBuffer } from './zipStream.js';
+import { parseZip, extractZipEntryToBuffer, collectZipEntry } from './zipStream.js';
const LOCAL_SIG = 0x04034b50;
const CENTRAL_SIG = 0x02014b50;
@@ -176,6 +176,80 @@ describe('parseZip', () => {
});
});
+describe('collectZipEntry', () => {
+ it('collects a stored entry into one Buffer', async () => {
+ const data = Buffer.from('clinical record json payload');
+ const zip = Buffer.concat([buildEntry('clinical_records/a.json', data), buildEocd()]);
+ const out = await new Promise((resolve, reject) => {
+ const parser = parseZip();
+ let read;
+ parser.on('entry', (entry) => { read = collectZipEntry(entry); });
+ parser.on('close', () => read.then(resolve, reject));
+ parser.on('error', reject);
+ Readable.from([zip]).pipe(parser);
+ });
+ expect(out.toString()).toBe('clinical record json payload');
+ });
+
+ it('round-trips a deflated entry', async () => {
+ const original = Buffer.from('{"resourceType":"Observation","value":42}');
+ const zip = Buffer.concat([
+ buildEntry('clinical_records/obs.json', deflateRawSync(original), { method: 8 }),
+ buildEocd(),
+ ]);
+ const out = await new Promise((resolve, reject) => {
+ const parser = parseZip();
+ let read;
+ parser.on('entry', (entry) => { read = collectZipEntry(entry); });
+ parser.on('close', () => read.then(resolve, reject));
+ parser.on('error', reject);
+ Readable.from([zip]).pipe(parser);
+ });
+ expect(out.toString()).toBe(original.toString());
+ });
+
+ it('rejects when the member exceeds maxBytes', async () => {
+ const data = Buffer.alloc(64, 0x41);
+ const zip = Buffer.concat([buildEntry('big.json', data), buildEocd()]);
+ const collected = new Promise((resolve, reject) => {
+ const parser = parseZip();
+ let read;
+ parser.on('entry', (entry) => { read = collectZipEntry(entry, 16); });
+ parser.on('close', () => read.then(resolve, reject));
+ parser.on('error', reject);
+ Readable.from([zip]).pipe(parser);
+ });
+ await expect(collected).rejects.toThrow(/exceeds 16 byte limit/);
+ });
+
+ it('collects multiple JSON members alongside a drained member (appleHealth pattern)', async () => {
+ // Mirrors server/routes/appleHealth.js: drain export.xml, collect every
+ // clinical_records/*.json into buffers, await them all on 'close'.
+ const zip = Buffer.concat([
+ buildEntry('apple_health_export/export.xml', Buffer.from('<HealthData/>')),
+ buildEntry('clinical_records/r1.json', deflateRawSync(Buffer.from('{"id":1}')), { method: 8 }),
+ buildEntry('clinical_records/r2.json', Buffer.from('{"id":2}')),
+ buildEocd(),
+ ]);
+ const jsons = await new Promise((resolve, reject) => {
+ const reads = [];
+ const collected = [];
+ const parser = parseZip();
+ parser.on('entry', (entry) => {
+ if (entry.path.includes('clinical_records/') && entry.path.endsWith('.json')) {
+ reads.push(collectZipEntry(entry).then((buf) => collected.push(buf.toString('utf-8'))));
+ } else {
+ entry.autodrain();
+ }
+ });
+ parser.on('close', () => Promise.all(reads).then(() => resolve(collected), reject));
+ parser.on('error', reject);
+ Readable.from([zip]).pipe(parser);
+ });
+ expect(jsons.sort()).toEqual(['{"id":1}', '{"id":2}']);
+ });
+});
+
describe('extractZipEntryToBuffer', () => {
let dir;
let zipPath;
diff --git a/server/routes/appleHealth.js b/server/routes/appleHealth.js
index 83ece0a5ec..463641461e 100644
--- a/server/routes/appleHealth.js
+++ b/server/routes/appleHealth.js
@@ -3,7 +3,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { createReadStream, createWriteStream, promises as fs } from 'fs';
import { uploadSingle } from '../lib/multipart.js';
-import { parseZip } from '../lib/zipStream.js';
+import { parseZip, collectZipEntry } from '../lib/zipStream.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { healthIngestSchema } from '../lib/appleHealthValidation.js';
@@ -23,6 +23,11 @@ import {
const XML_WRITE_POLL_INTERVAL_MS = 50;
const XML_WRITE_TIMEOUT_MS = 5000;
+// Per-member cap when buffering a clinical-record JSON into memory. Real records
+// are ~1-5KB each; the generous ceiling just guards against a pathological
+// member exhausting memory (mirrors chatgptZipImport's MAX_MEMBER_BYTES).
+const MAX_CLINICAL_RECORD_BYTES = 100 * 1024 * 1024;
+
const isZip = (file) =>
file.mimetype === 'application/zip' ||
file.mimetype === 'application/x-zip-compressed' ||
@@ -117,6 +122,10 @@ router.post('/import/xml', uploadXml, asyncHandler(async (req, res) => {
const xmlPath = join(tmpdir(), `apple-health-${Date.now()}.xml`);
let foundXml = false;
let xmlWriteFinished = false;
+ // Each clinical-record collect is async (entries stream through an inflate
+ // pipeline), so track them and await all before resolving — otherwise
+ // 'close' can fire and drop records whose buffers haven't finished.
+ const clinicalReads = [];
await new Promise((resolve, reject) => {
let settled = false;
@@ -132,20 +141,28 @@ router.post('/import/xml', uploadXml, asyncHandler(async (req, res) => {
.on('finish', () => { xmlWriteFinished = true; })
.on('error', settle(reject));
} else if (entry.path.includes('clinical_records/') && entry.path.endsWith('.json')) {
- // Buffer clinical record JSON files (~1-5KB each)
- const chunks = [];
- entry.on('data', (chunk) => chunks.push(chunk));
- entry.on('end', () => clinicalJsons.push(Buffer.concat(chunks).toString('utf-8')));
+ // Buffer clinical record JSON files (~1-5KB each). parseZip() entries
+ // aren't EventEmitters (no entry.on('data'/'end') — that throws), so
+ // pipe into a collecting Writable via the shared helper and track the
+ // read so 'close' can await it.
+ clinicalReads.push(
+ collectZipEntry(entry, MAX_CLINICAL_RECORD_BYTES)
+ .then((buf) => { clinicalJsons.push(buf.toString('utf-8')); })
+ .catch(settle(reject))
+ );
} else {
entry.autodrain();
}
})
.on('close', () => {
if (!foundXml) return settle(reject)(new ServerError('ZIP does not contain export.xml', { status: 400, code: 'BAD_REQUEST' }));
- // Wait briefly for XML write stream to finish if close fires first
- if (xmlWriteFinished) return settle(resolve)();
- const check = setInterval(() => { if (xmlWriteFinished) { clearInterval(check); settle(resolve)(); } }, XML_WRITE_POLL_INTERVAL_MS);
- setTimeout(() => { clearInterval(check); settle(resolve)(); }, XML_WRITE_TIMEOUT_MS);
+ // Resolve once the XML write stream has flushed AND every clinical
+ // record collect has finished. XML completion is signaled via the
+ // polled flag; the clinical collects are awaited as promises.
+ const finalize = () => Promise.all(clinicalReads).then(settle(resolve));
+ if (xmlWriteFinished) return finalize();
+ const check = setInterval(() => { if (xmlWriteFinished) { clearInterval(check); finalize(); } }, XML_WRITE_POLL_INTERVAL_MS);
+ setTimeout(() => { clearInterval(check); finalize(); }, XML_WRITE_TIMEOUT_MS);
})
.on('error', settle(reject));
});
diff --git a/server/services/chatgptZipImport.js b/server/services/chatgptZipImport.js
index d87ee2a536..01a49a6a3d 100644
--- a/server/services/chatgptZipImport.js
+++ b/server/services/chatgptZipImport.js
@@ -33,7 +33,7 @@ import { createReadStream, createWriteStream } from 'fs';
import { mkdir, rename, unlink } from 'fs/promises';
import { Writable } from 'stream';
import { PATHS, getMimeType } from '../lib/fileUtils.js';
-import { parseZip } from '../lib/zipStream.js';
+import { parseZip, collectZipEntry } from '../lib/zipStream.js';
import { parseExport, importConversations, assetPointerId } from './chatgptImport.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -105,23 +105,9 @@ const IS_ASSET_NAME_MAP = (path) => /(?:^|\/)conversation_asset_file_names\.json
const datAssetId = (path) => path.replace(/^.*\//, '').replace(/\.dat$/i, '');
// `parseZip` entries aren't readable streams — they expose `.pipe(dest)` /
-// `.autodrain()`. Pipe the entry into a size-capped collecting Writable and
-// resolve with the concatenated buffer.
-const collect = (entry, max) => new Promise((resolve, reject) => {
- const chunks = [];
- let size = 0;
- const sink = new Writable({
- write(chunk, _enc, cb) {
- size += chunk.length;
- if (size > max) { cb(new Error(`ZIP member exceeds ${max} byte limit`)); return; }
- chunks.push(chunk);
- cb();
- }
- });
- sink.on('finish', () => resolve(Buffer.concat(chunks)));
- sink.on('error', reject);
- entry.pipe(sink);
-});
+// `.autodrain()`, so buffering one into memory goes through the shared,
+// size-capped `collectZipEntry` helper (see lib/zipStream.js).
+const collect = collectZipEntry;
// Stream a `.dat` entry straight to `filePath`, holding only the leading
// `SNIFF_BYTES` so the asset's real extension can be sniffed without buffering