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

simplify: clean up zipStream, multipart, and scaffold

Adam Eivy925bb8e52189
diff --git a/server/lib/multipart.js b/server/lib/multipart.js
index a844467da5..61642bc5e6 100644
--- a/server/lib/multipart.js
+++ b/server/lib/multipart.js
@@ -27,14 +27,17 @@ 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 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 streaming = false; // true once past headers, writing file bytes
let done = false;
- const headerChunks = []; // accumulates chunks until headers are parsed
+
+ // Header accumulation: keep prior chunks + a spillover window to detect \r\n\r\n across boundaries
+ const headerChunks = [];
+ let headerSpill = Buffer.alloc(0); // last (HEADER_END.length - 1) bytes from previous chunk
const fail = (err) => {
if (!done) { done = true; if (ws) ws.destroy(); next(err); }
@@ -45,7 +48,6 @@ function parseStream(stream, boundary, fieldName, maxSize, fileFilter, next) {
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)`));
@@ -76,13 +78,21 @@ function parseStream(stream, boundary, fieldName, maxSize, fileFilter, next) {
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;
+ // Search for \r\n\r\n only in the window of spillover + new chunk (O(n) per chunk)
+ const window = headerSpill.length ? Buffer.concat([headerSpill, chunk]) : chunk;
+ const hEnd = window.indexOf(HEADER_END);
+ if (hEnd === -1) {
+ headerChunks.push(chunk);
+ // Keep last (HEADER_END.length - 1) bytes as spillover for next chunk
+ headerSpill = window.length >= HEADER_END.length
+ ? window.slice(window.length - (HEADER_END.length - 1))
+ : window;
+ return;
+ }
- // Parse Content-Disposition and Content-Type from headers
- const headerStr = combined.slice(0, hEnd).toString('utf-8');
+ // Headers found — reconstruct full header block from prior chunks + window up to hEnd
+ const fullHeader = Buffer.concat([...headerChunks, window.slice(0, hEnd)]);
+ const headerStr = fullHeader.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}"`));
@@ -99,11 +109,11 @@ function parseStream(stream, boundary, fieldName, maxSize, fileFilter, next) {
if (!fr.accept) return fail(new Error('File type not allowed'));
}
- filePath = join(tmpdir(), `upload-${Date.now()}-${randomUUID()}${ext}`);
+ filePath = join(tmpdir(), `upload-${randomUUID()}${ext}`);
ws = createWriteStream(filePath);
ws.on('error', fail);
streaming = true;
- writeChunk(combined.slice(hEnd + HEADER_END.length));
+ writeChunk(window.slice(hEnd + HEADER_END.length));
});
stream.on('end', () => {
diff --git a/server/lib/zipStream.js b/server/lib/zipStream.js
index b74a341cb3..90c5eec391 100644
--- a/server/lib/zipStream.js
+++ b/server/lib/zipStream.js
@@ -28,7 +28,6 @@ const LOCAL_HEADER_SIZE = 30; // fixed portion (before variable-length name + ex
export function parseZip() {
const emitter = new EventEmitter();
- const chunks = [];
let buf = Buffer.alloc(0);
let closed = false;
@@ -48,7 +47,7 @@ export function parseZip() {
let state = 'HEADER'; // HEADER | ENTRY | SKIP_CENTRAL
let currentEntry = null;
- let entryBytesRemaining = 0; // compressed size remaining to push to entry stream
+ let entryBytesRemaining = 0; // compressed size remaining; only used when !dataDescriptor
function processBuffer() {
while (true) {
@@ -86,7 +85,6 @@ export function parseZip() {
buf = buf.slice(headerSize);
const passThrough = new PassThrough();
- const entryEmitter = new EventEmitter();
let piped = false;
const entry = {
@@ -114,11 +112,9 @@ export function parseZip() {
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
+ currentEntry = { passThrough, method, name, dataDescriptor: true };
} else {
- currentEntry = { passThrough, method, name, dataDescriptor: false, compSize };
+ currentEntry = { passThrough, method, name, dataDescriptor: false };
entryBytesRemaining = compSize;
}
state = 'ENTRY';
@@ -128,27 +124,21 @@ export function parseZip() {
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]);
-
+ // Unknown compressed size — scan for data descriptor or next local/central header
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
+ // Some ZIPs omit the descriptor signature — boundary is next local/central header
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)
+ // Flush safe bytes (keep last 16 for boundary overlap)
const safe = buf.length - 16;
if (safe > 0) {
currentEntry.passThrough.write(buf.slice(0, safe));
@@ -157,7 +147,6 @@ export function parseZip() {
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);
@@ -183,11 +172,10 @@ export function parseZip() {
}
}
- // 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);
+ // Delegate EventEmitter interface to emitter so .pipe() syntax works
+ for (const m of ['on', 'once', 'off', 'emit', 'addListener', 'removeListener', 'removeAllListeners', 'listenerCount']) {
+ sink[m] = emitter[m].bind(emitter);
+ }
return sink;
}
diff --git a/server/routes/scaffold.js b/server/routes/scaffold.js
index 724a04af52..35165b1720 100644
--- a/server/routes/scaffold.js
+++ b/server/routes/scaffold.js
@@ -15,6 +15,15 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const TEMPLATES_DIR = join(__dirname, '../../templates');
+// Inline CORS middleware snippet for generated projects (no cors package dependency)
+const CORS_SNIPPET = `app.use((req, res, next) => {
+ res.set('Access-Control-Allow-Origin', '*');
+ res.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
+ res.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');
+ if (req.method === 'OPTIONS') return res.sendStatus(204);
+ next();
+});`;
+
const router = Router();
// GET /api/directories - Browse directories for directory picker
@@ -299,13 +308,7 @@ async function scaffoldApp(req, res) {
const app = express();
const PORT = process.env.PORT || ${apiPort || 3001};
-app.use((req, res, next) => {
- res.set('Access-Control-Allow-Origin', '*');
- res.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
- res.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');
- if (req.method === 'OPTIONS') return res.sendStatus(204);
- next();
-});
+${CORS_SNIPPET}
app.use(express.json());
app.get('/api/health', (req, res) => {
@@ -352,13 +355,7 @@ app.listen(PORT, '0.0.0.0', () => {
const app = express();
const PORT = process.env.PORT || ${apiPort || 3000};
-app.use((req, res, next) => {
- res.set('Access-Control-Allow-Origin', '*');
- res.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
- res.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');
- if (req.method === 'OPTIONS') return res.sendStatus(204);
- next();
-});
+${CORS_SNIPPET}
app.use(express.json());
app.get('/api/health', (req, res) => {
@@ -1009,13 +1006,7 @@ const io = new Server(httpServer, {
const PORT = process.env.PORT || ${apiPort || 3001};
-app.use((req, res, next) => {
- res.set('Access-Control-Allow-Origin', '*');
- res.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
- res.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');
- if (req.method === 'OPTIONS') return res.sendStatus(204);
- next();
-});
+${CORS_SNIPPET}
app.use(express.json());
// Initialize AI Toolkit with routes for providers, runs, and prompts