// Copyright (c) 2014 Max Ogden and other contributors. // Licensed under the BSD-2-Clause License. See LICENSE. const {createWriteStream, promises: fs} = require('node:fs'); const path = require('node:path'); const {pipeline} = require('node:stream/promises'); const {promisify} = require('node:util'); const getStream = require('get-stream'); const yauzl = require('yauzl'); const openZip = promisify(yauzl.open); function assertContained(dir, destination) { const relative = path.relative(dir, destination); if ( relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative) ) { throw new Error(`Out of bound path "${destination}"`); } } async function lstatIfExists(destination) { try { return await fs.lstat(destination); } catch (error) { if (error.code !== 'ENOENT') { throw error; } } } // Resolve existing and dangling links component by component. Only leading ".." // segments are allowed so lexical and link-following resolution cannot disagree. async function canonicalPath(base, filename, links = {count: 0}) { if (filename.includes('\0') || /^[a-z]:($|[^\\/])/i.test(filename)) { throw new Error(`Invalid path "${filename}"`); } if (path.win32.isAbsolute(filename) && !path.isAbsolute(filename)) { throw new Error(`Out of bound path "${filename}"`); } let current = base; if (path.isAbsolute(filename)) { const root = path.parse(filename).root; current = path.resolve(root); filename = filename.slice(root.length); } const components = filename.split( process.platform === 'win32' ? /[\\/]/ : '/', ); let hasOrdinaryComponent = false; for (const component of components) { if (!component || component === '.') { continue; } if (component === '..') { if (hasOrdinaryComponent) { throw new Error(`Ambiguous path "${filename}"`); } current = path.dirname(current); continue; } hasOrdinaryComponent = true; const next = path.join(current, component); const existing = await lstatIfExists(next); if (existing?.isSymbolicLink()) { if (++links.count > 40) { throw new Error(`Too many symbolic links in "${filename}"`); } current = await canonicalPath(current, await fs.readlink(next), links); } else { current = existing ? await fs.realpath(next) : next; } } return current; } class Extractor { constructor(zipPath, opts) { this.zipPath = zipPath; this.opts = opts; this.canceled = false; } async extract() { this.zipfile = await openZip(this.zipPath, {lazyEntries: true}); return new Promise((resolve, reject) => { const fail = error => { this.canceled = true; this.readStream?.destroy(error); this.zipfile.close(); reject(error); }; this.zipfile.on('error', fail); this.zipfile.on('close', () => { if (!this.canceled) { resolve(); } }); this.zipfile.on('entry', async entry => { if (this.canceled) { return; } try { if (!entry.fileName.startsWith('__MACOSX/')) { await this.extractEntry(entry); } if (!this.canceled) { this.zipfile.readEntry(); } } catch (error) { fail(error); } }); this.zipfile.readEntry(); }); } async extractEntry(entry) { if (this.opts.onEntry) { this.opts.onEntry(entry, this.zipfile); } // Validate again after onEntry, which receives the mutable yauzl entry. const invalid = yauzl.validateFileName(entry.fileName); if (invalid || entry.fileName.includes('\0')) { throw new Error(invalid || 'Invalid null byte in entry path'); } const dest = path.resolve(this.opts.dir, entry.fileName); assertContained(this.opts.dir, dest); const mode = (entry.externalFileAttributes >> 16) & 0xffff; const symlink = (mode & 0o170000) === 0o120000; const isDir = (mode & 0o170000) === 0o040000 || entry.fileName.endsWith('/') || (entry.versionMadeBy >> 8 === 0 && entry.externalFileAttributes === 16); const procMode = this.getExtractedMode(mode, isDir) & 0o777; const destDir = isDir ? dest : path.dirname(dest); if (!isDir && !symlink) { const existing = await lstatIfExists(dest); if (existing?.isSymbolicLink()) { throw new Error( `Refusing to overwrite symbolic link "${dest}" while processing file ${entry.fileName}`, ); } } const parent = await canonicalPath( this.opts.dir, path.relative(this.opts.dir, destDir), ); assertContained(this.opts.dir, parent); let link; if (symlink && !isDir) { const readStream = await this.openReadStream(entry); try { link = await getStream(readStream); } finally { this.readStream = undefined; } assertContained(this.opts.dir, path.resolve(parent, link)); assertContained(this.opts.dir, await canonicalPath(parent, link)); } // All containment checks precede mutations; callers must prevent concurrent // filesystem changes during extraction (these checks are not race-proof). if (this.canceled) { return; } await fs.mkdir(destDir, { recursive: true, ...(isDir ? {mode: procMode} : {}), }); if (isDir || this.canceled) { return; } if (symlink) { await fs.symlink(link, dest); } else { const readStream = await this.openReadStream(entry); try { await pipeline(readStream, createWriteStream(dest, {mode: procMode})); } finally { this.readStream = undefined; } } } async openReadStream(entry) { this.readStream = await promisify( this.zipfile.openReadStream.bind(this.zipfile), )(entry); if (this.canceled) { this.readStream.destroy(); throw new Error('Extraction canceled'); } return this.readStream; } getExtractedMode(entryMode, isDir) { if (entryMode !== 0) { return entryMode; } const fallback = isDir ? this.opts.defaultDirMode : this.opts.defaultFileMode; return parseInt(fallback, 10) || (isDir ? 0o755 : 0o644); } } module.exports = async function (zipPath, opts) { if (!path.isAbsolute(opts.dir)) { throw new Error('Target directory is expected to be absolute'); } await fs.mkdir(opts.dir, {recursive: true}); const dir = await fs.realpath(opts.dir); return new Extractor(zipPath, {...opts, dir}).extract(); };