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
depfree: replace multer and unzipper with owned streaming implementations
Adam Eivyb8436214dee0
diff --git a/PLAN.md b/PLAN.mdindex 604f396c86..455b9021a7 100644--- a/PLAN.md+++ b/PLAN.md@@ -85,9 +85,9 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]- [ ] **`uuid`** — Add `server/lib/uuid.js` (`export const uuidv4 = () => crypto.randomUUID()`), update 40 import paths. Trivial. ~5 lines.- [x] **`cors`** — Replaced `cors()` in scaffold.js generated templates with inline CORS middleware; removed `cors` from generated package.json deps. PortOS itself already used inline headers. Note: package remains in lock file via socket.io.- [x] **`axios`** — Wrote `server/lib/httpClient.js` (fetch-based client factory, `AbortSignal.timeout`, self-signed TLS via `https.Agent`). Updated `services/jira.js`, `services/datadog.js`, `services/datadog.test.js`. Token-expiry interceptor inlined in jira.js.-- [ ] **`multer`** — Write `server/lib/multipart.js` (stream multipart to disk, size limit, MIME filter, req.file compatible). Update `routes/appleHealth.js`. ~65 lines.+- [x] **`multer`** — Wrote `server/lib/multipart.js` (streaming multipart parser, no memory buffering, size limit, MIME filter, req.file compatible). Updated `routes/appleHealth.js`.- [ ] **`node-telegram-bot-api`** — Write `server/lib/telegramClient.js` (fetch-based Telegram Bot API wrapper: polling loop with offset, `getMe`, `sendMessage`, `editMessageText`, `answerCallbackQuery`, `stopPolling`, regex handler dispatch). Update `services/telegram.js`. ~110 lines.-- [ ] **`unzipper`** — Write `server/lib/zipStream.js` (streaming ZIP parser: local file header reader, `zlib.createInflateRaw` decompressor, entry event emitter with `{ path, pipe, autodrain }`). Update `routes/appleHealth.js`. ~175 lines. **Note:** This is the most complex replacement — consider validating with apple health data before committing.+- [x] **`unzipper`** — Wrote `server/lib/zipStream.js` (streaming ZIP parser: local file header reader, `zlib.createInflateRaw` decompressor, entry emitter with `{ path, pipe, autodrain }`). Updated `routes/appleHealth.js`. **Note:** validate with real Apple Health ZIP before production use.- [ ] **`supertest`** — Write `server/tests/testHelper.js` (HTTP server lifecycle, fetch-based `request(app)` factory returning `.get/.post/.put/.delete` with `.send/.set`). Update 9 test files. ~45 lines.- [ ] **`geist`** — Copy font files to `client/public/fonts/`. Update CSS `url()` paths in `client/src/index.css`. Remove package. ~0 logic lines.- [ ] **`fflate`** (direct usage) — Replace `unzipSync` + `strFromU8` in `GenomeTab.jsx` with native `DecompressionStream` API (browser). Note: package stays in lock file via @react-three/drei.diff --git a/server/lib/multipart.js b/server/lib/multipart.jsnew file mode 100644index 0000000000..a844467da5--- /dev/null+++ b/server/lib/multipart.js@@ -0,0 +1,114 @@+/**+ * Streaming multipart/form-data parser — multer.diskStorage() replacement.+ * Streams file content directly to disk; never buffers entire body in memory.+ *+ * Returns an Express middleware for a single file field.+ * Populates req.file with { path, originalname, mimetype, size }.+ */++import { createWriteStream } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { randomUUID } from 'crypto';++export function uploadSingle(fieldName, { limits = {}, fileFilter } = {}) {+ const maxSize = limits.fileSize ?? Infinity;++ return (req, res, next) => {+ const ct = req.headers['content-type'] || '';+ if (!ct.startsWith('multipart/form-data')) return next(new Error('Expected multipart/form-data'));+ const bm = ct.match(/boundary=([^\s;]+)/);+ if (!bm) return next(new Error('Missing multipart boundary'));+ parseStream(req, bm[1], fieldName, maxSize, fileFilter, next);+ };+}++function parseStream(stream, boundary, fieldName, maxSize, fileFilter, next) {+ const END_MARKER = Buffer.from('\r\n--' + boundary);+ const HEADER_END = Buffer.from('\r\n\r\n');++ let buf = Buffer.alloc(0); // lookahead buffer while streaming file content+ let ws = null; // WriteStream for current file+ let filePath = null;+ let fileMeta = null;+ let fileSize = 0;+ let streaming = false; // true once past headers, writing file bytes+ let done = false;+ const headerChunks = []; // accumulates chunks until headers are parsed++ const fail = (err) => {+ if (!done) { done = true; if (ws) ws.destroy(); next(err); }+ };++ const writeChunk = (chunk) => {+ if (done) return;+ const combined = buf.length ? Buffer.concat([buf, chunk]) : chunk;+ const idx = combined.indexOf(END_MARKER);+ if (idx !== -1) {+ // End of file content found+ const tail = combined.slice(0, idx);+ fileSize += tail.length;+ if (fileSize > maxSize) return fail(new Error(`File too large (max ${maxSize} bytes)`));+ ws.end(tail);+ ws.once('finish', () => {+ if (!done) {+ done = true;+ stream.file = { path: filePath, ...fileMeta, size: fileSize };+ next();+ }+ });+ buf = Buffer.alloc(0);+ } else {+ // Keep last END_MARKER.length-1 bytes buffered (boundary may span chunks)+ const safe = combined.length - (END_MARKER.length - 1);+ if (safe > 0) {+ fileSize += safe;+ if (fileSize > maxSize) return fail(new Error(`File too large (max ${maxSize} bytes)`));+ ws.write(combined.slice(0, safe));+ buf = combined.slice(safe);+ } else {+ buf = combined;+ }+ }+ };++ stream.on('data', (chunk) => {+ if (done) return;+ if (streaming) return writeChunk(chunk);++ headerChunks.push(chunk);+ const combined = Buffer.concat(headerChunks);+ const hEnd = combined.indexOf(HEADER_END);+ if (hEnd === -1) return;++ // Parse Content-Disposition and Content-Type from headers+ const headerStr = combined.slice(0, hEnd).toString('utf-8');+ const dispMatch = headerStr.match(/Content-Disposition:[^\r\n]*name="([^"]+)"[^\r\n]*filename="([^"]+)"/i);+ if (!dispMatch || dispMatch[1] !== fieldName) return fail(new Error(`Expected field "${fieldName}"`));++ const originalname = dispMatch[2];+ const mimeMatch = headerStr.match(/Content-Type:\s*([^\r\n]+)/i);+ const mimetype = mimeMatch ? mimeMatch[1].trim() : 'application/octet-stream';+ const ext = originalname.match(/\.[^.]+$/)?.[0] || '';+ fileMeta = { originalname, mimetype };++ if (fileFilter) {+ let fr = null;+ fileFilter(null, fileMeta, (err, accept) => { fr = { err, accept }; });+ if (fr.err) return fail(fr.err);+ if (!fr.accept) return fail(new Error('File type not allowed'));+ }++ filePath = join(tmpdir(), `upload-${Date.now()}-${randomUUID()}${ext}`);+ ws = createWriteStream(filePath);+ ws.on('error', fail);+ streaming = true;+ writeChunk(combined.slice(hEnd + HEADER_END.length));+ });++ stream.on('end', () => {+ if (!done && !streaming) { stream.file = undefined; next(); }+ });++ stream.on('error', fail);+}diff --git a/server/lib/zipStream.js b/server/lib/zipStream.jsnew file mode 100644index 0000000000..b74a341cb3--- /dev/null+++ b/server/lib/zipStream.js@@ -0,0 +1,193 @@+/**+ * Streaming ZIP parser — unzipper.Parse replacement.+ *+ * Usage (mirrors unzipper):+ * createReadStream(path).pipe(parseZip())+ * .on('entry', entry => { entry.path; entry.pipe(ws); entry.autodrain(); })+ * .on('close', () => {})+ * .on('error', err => {})+ *+ * Supports DEFLATE (method 8) and stored (method 0) entries.+ * Central directory is not used — entries are read sequentially from the stream.+ */++import { createInflateRaw } from 'zlib';+import { EventEmitter } from 'events';+import { PassThrough, Writable } from 'stream';++// Local file header signature: PK\x03\x04+const LOCAL_SIG = 0x04034b50;+// Data descriptor signature: PK\x07\x08+const DATA_DESC_SIG = 0x08074b50;+// Central directory signature: PK\x01\x02+const CENTRAL_SIG = 0x02014b50;+// End of central directory: PK\x05\x06+const EOCD_SIG = 0x06054b50;++const LOCAL_HEADER_SIZE = 30; // fixed portion (before variable-length name + extra)++export function parseZip() {+ const emitter = new EventEmitter();+ const chunks = [];+ let buf = Buffer.alloc(0);+ let closed = false;++ const sink = new Writable({+ write(chunk, _, cb) {+ buf = buf.length ? Buffer.concat([buf, chunk]) : chunk;+ processBuffer();+ cb();+ },+ final(cb) {+ if (!closed) { closed = true; emitter.emit('close'); }+ cb();+ }+ });++ sink.on('error', err => emitter.emit('error', err));++ let state = 'HEADER'; // HEADER | ENTRY | SKIP_CENTRAL+ let currentEntry = null;+ let entryBytesRemaining = 0; // compressed size remaining to push to entry stream++ function processBuffer() {+ while (true) {+ if (state === 'SKIP_CENTRAL') return; // done with entries++ if (state === 'HEADER') {+ if (buf.length < 4) return;+ const sig = buf.readUInt32LE(0);++ if (sig === CENTRAL_SIG || sig === EOCD_SIG) {+ state = 'SKIP_CENTRAL';+ return;+ }++ if (sig !== LOCAL_SIG) {+ // Skip one byte and retry (handles padding)+ buf = buf.slice(1);+ continue;+ }++ if (buf.length < LOCAL_HEADER_SIZE) return; // wait for more data++ const flags = buf.readUInt16LE(6);+ const method = buf.readUInt16LE(8);+ const compSize = buf.readUInt32LE(18);+ const nameLen = buf.readUInt16LE(26);+ const extraLen = buf.readUInt16LE(28);+ const headerSize = LOCAL_HEADER_SIZE + nameLen + extraLen;++ if (buf.length < headerSize) return;++ const name = buf.slice(30, 30 + nameLen).toString('utf-8');+ const dataDescriptor = (flags & 0x0008) !== 0; // bit 3: sizes in data descriptor++ buf = buf.slice(headerSize);++ const passThrough = new PassThrough();+ const entryEmitter = new EventEmitter();+ let piped = false;++ const entry = {+ path: name,+ pipe(dest) {+ piped = true;+ if (method === 8) {+ passThrough.pipe(createInflateRaw()).pipe(dest);+ } else {+ passThrough.pipe(dest);+ }+ return dest;+ },+ autodrain() {+ piped = true;+ passThrough.resume(); // discard+ }+ };++ // Give consumer a tick to attach pipe/autodrain+ process.nextTick(() => {+ if (!piped) entry.autodrain();+ });++ emitter.emit('entry', entry);++ if (dataDescriptor) {+ // Unknown compressed size — read until data descriptor signature+ currentEntry = { passThrough, method, name, dataDescriptor: true, compSize: 0 };+ entryBytesRemaining = -1; // signal: scan mode+ } else {+ currentEntry = { passThrough, method, name, dataDescriptor: false, compSize };+ entryBytesRemaining = compSize;+ }+ state = 'ENTRY';+ }++ if (state === 'ENTRY') {+ if (!currentEntry) { state = 'HEADER'; continue; }++ if (currentEntry.dataDescriptor) {+ // Scan for data descriptor: PK\x07\x08 or PK\x07\x08 without sig+ // Data descriptor is 12 or 16 bytes (with/without sig)+ // Strategy: find end of compressed data by looking for next local header or descriptor+ const descSig = Buffer.from([0x50, 0x4b, 0x07, 0x08]);+ const localSig = Buffer.from([0x50, 0x4b, 0x03, 0x04]);+ const centralSig = Buffer.from([0x50, 0x4b, 0x01, 0x02]);++ let found = -1;+ let descLen = 0;+ for (let i = 0; i <= buf.length - 4; i++) {+ if (buf.readUInt32LE(i) === DATA_DESC_SIG) {+ found = i; descLen = 16; break;+ }+ // Some ZIPs omit the descriptor signature — look for next local/central+ if (i > 0 && (buf.readUInt32LE(i) === LOCAL_SIG || buf.readUInt32LE(i) === CENTRAL_SIG || buf.readUInt32LE(i) === EOCD_SIG)) {+ found = i; descLen = 0; break;+ }+ }++ if (found === -1) {+ // Flush safe bytes to entry stream (keep last 16 bytes for boundary detection)+ const safe = buf.length - 16;+ if (safe > 0) {+ currentEntry.passThrough.write(buf.slice(0, safe));+ buf = buf.slice(safe);+ }+ return;+ }++ // Push all bytes up to the descriptor to the entry+ currentEntry.passThrough.write(buf.slice(0, found));+ currentEntry.passThrough.end();+ buf = buf.slice(found + descLen);+ currentEntry = null;+ state = 'HEADER';++ } else {+ if (buf.length === 0) return;+ const take = Math.min(entryBytesRemaining, buf.length);+ currentEntry.passThrough.write(buf.slice(0, take));+ buf = buf.slice(take);+ entryBytesRemaining -= take;++ if (entryBytesRemaining === 0) {+ currentEntry.passThrough.end();+ currentEntry = null;+ state = 'HEADER';+ } else {+ return; // need more data+ }+ }+ }+ }+ }++ // Allow .pipe() syntax: readStream.pipe(parseZip())+ sink.on = emitter.on.bind(emitter);+ sink.once = emitter.once.bind(emitter);+ sink.emit = emitter.emit.bind(emitter);+ sink.removeListener = emitter.removeListener.bind(emitter);++ return sink;+}diff --git a/server/routes/appleHealth.js b/server/routes/appleHealth.jsindex b8b93d51aa..109cbd0d31 100644--- a/server/routes/appleHealth.js+++ b/server/routes/appleHealth.js@@ -2,8 +2,8 @@ import { Router } from 'express';import { tmpdir } from 'os';import { join } from 'path';import { createReadStream, createWriteStream, promises as fs } from 'fs';-import multer from 'multer';-import { Parse as unzipParse } from 'unzipper';+import { uploadSingle } from '../lib/multipart.js';+import { parseZip } from '../lib/zipStream.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { healthIngestSchema } from '../lib/appleHealthValidation.js';@@ -29,14 +29,7 @@ const isXml = (file) =>file.mimetype === 'application/xml' ||file.originalname.endsWith('.xml');-const upload = multer({- storage: multer.diskStorage({- destination: (req, file, cb) => cb(null, tmpdir()),- filename: (req, file, cb) => {- const ext = isZip(file) ? '.zip' : '.xml';- cb(null, `apple-health-${Date.now()}${ext}`);- }- }),+const uploadXml = uploadSingle('file', {limits: { fileSize: 2 * 1024 * 1024 * 1024 }, // 2GB maxfileFilter: (req, file, cb) => {if (isXml(file) || isZip(file)) {@@ -107,8 +100,8 @@ router.get('/correlation', asyncHandler(async (req, res) => {}));// POST /api/health/import/xml-// Accepts Apple Health export.xml or ZIP via multipart upload (multer diskStorage — no OOM on 500MB+)-router.post('/import/xml', upload.single('file'), asyncHandler(async (req, res) => {+// Accepts Apple Health export.xml or ZIP via multipart upload (streaming — no OOM on 500MB+)+router.post('/import/xml', uploadXml, asyncHandler(async (req, res) => {const io = req.app.get('io');let filePath = req.file?.path;if (!filePath) throw new ServerError('No file uploaded', { status: 400, code: 'BAD_REQUEST' });@@ -126,7 +119,7 @@ router.post('/import/xml', upload.single('file'), asyncHandler(async (req, res)const settle = (fn) => (...args) => { if (!settled) { settled = true; fn(...args); } };createReadStream(filePath)- .pipe(unzipParse())+ .pipe(parseZip()).on('entry', (entry) => {if (entry.path === 'apple_health_export/export.xml' || entry.path === 'export.xml') {foundXml = true;