index.cjs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var fs = require('node:fs');
  4. var crypto = require('node:crypto');
  5. var node_events = require('node:events');
  6. var os = require('node:os');
  7. var path = require('node:path');
  8. var fsPromises = require('node:fs/promises');
  9. var node_string_decoder = require('node:string_decoder');
  10. var hexoid = require('hexoid');
  11. var once = require('once');
  12. var dezalgo = require('dezalgo');
  13. var node_stream = require('node:stream');
  14. /* eslint-disable no-underscore-dangle */
  15. class PersistentFile extends node_events.EventEmitter {
  16. constructor({ filepath, newFilename, originalFilename, mimetype, hashAlgorithm }) {
  17. super();
  18. this.lastModifiedDate = null;
  19. Object.assign(this, { filepath, newFilename, originalFilename, mimetype, hashAlgorithm });
  20. this.size = 0;
  21. this._writeStream = null;
  22. if (typeof this.hashAlgorithm === 'string') {
  23. this.hash = crypto.createHash(this.hashAlgorithm);
  24. } else {
  25. this.hash = null;
  26. }
  27. }
  28. open() {
  29. this._writeStream = fs.createWriteStream(this.filepath);
  30. this._writeStream.on('error', (err) => {
  31. this.emit('error', err);
  32. });
  33. }
  34. toJSON() {
  35. const json = {
  36. size: this.size,
  37. filepath: this.filepath,
  38. newFilename: this.newFilename,
  39. mimetype: this.mimetype,
  40. mtime: this.lastModifiedDate,
  41. length: this.length,
  42. originalFilename: this.originalFilename,
  43. };
  44. if (this.hash && this.hash !== '') {
  45. json.hash = this.hash;
  46. }
  47. return json;
  48. }
  49. toString() {
  50. return `PersistentFile: ${this.newFilename}, Original: ${this.originalFilename}, Path: ${this.filepath}`;
  51. }
  52. write(buffer, cb) {
  53. if (this.hash) {
  54. this.hash.update(buffer);
  55. }
  56. if (this._writeStream.closed) {
  57. cb();
  58. return;
  59. }
  60. this._writeStream.write(buffer, () => {
  61. this.lastModifiedDate = new Date();
  62. this.size += buffer.length;
  63. this.emit('progress', this.size);
  64. cb();
  65. });
  66. }
  67. end(cb) {
  68. if (this.hash) {
  69. this.hash = this.hash.digest('hex');
  70. }
  71. this._writeStream.end(() => {
  72. this.emit('end');
  73. cb();
  74. });
  75. }
  76. destroy() {
  77. this._writeStream.destroy();
  78. const filepath = this.filepath;
  79. setTimeout(function () {
  80. fs.unlink(filepath, () => {});
  81. }, 1);
  82. }
  83. }
  84. /* eslint-disable no-underscore-dangle */
  85. class VolatileFile extends node_events.EventEmitter {
  86. constructor({ filepath, newFilename, originalFilename, mimetype, hashAlgorithm, createFileWriteStream }) {
  87. super();
  88. this.lastModifiedDate = null;
  89. Object.assign(this, { filepath, newFilename, originalFilename, mimetype, hashAlgorithm, createFileWriteStream });
  90. this.size = 0;
  91. this._writeStream = null;
  92. if (typeof this.hashAlgorithm === 'string') {
  93. this.hash = crypto.createHash(this.hashAlgorithm);
  94. } else {
  95. this.hash = null;
  96. }
  97. }
  98. open() {
  99. this._writeStream = this.createFileWriteStream(this);
  100. this._writeStream.on('error', (err) => {
  101. this.emit('error', err);
  102. });
  103. }
  104. destroy() {
  105. this._writeStream.destroy();
  106. }
  107. toJSON() {
  108. const json = {
  109. size: this.size,
  110. newFilename: this.newFilename,
  111. length: this.length,
  112. originalFilename: this.originalFilename,
  113. mimetype: this.mimetype,
  114. };
  115. if (this.hash && this.hash !== '') {
  116. json.hash = this.hash;
  117. }
  118. return json;
  119. }
  120. toString() {
  121. return `VolatileFile: ${this.originalFilename}`;
  122. }
  123. write(buffer, cb) {
  124. if (this.hash) {
  125. this.hash.update(buffer);
  126. }
  127. if (this._writeStream.closed || this._writeStream.destroyed) {
  128. cb();
  129. return;
  130. }
  131. this._writeStream.write(buffer, () => {
  132. this.size += buffer.length;
  133. this.emit('progress', this.size);
  134. cb();
  135. });
  136. }
  137. end(cb) {
  138. if (this.hash) {
  139. this.hash = this.hash.digest('hex');
  140. }
  141. this._writeStream.end(() => {
  142. this.emit('end');
  143. cb();
  144. });
  145. }
  146. }
  147. class OctetStreamParser extends node_stream.PassThrough {
  148. constructor(options = {}) {
  149. super();
  150. this.globalOptions = { ...options };
  151. }
  152. }
  153. /* eslint-disable no-underscore-dangle */
  154. const octetStreamType = 'octet-stream';
  155. // the `options` is also available through the `options` / `formidable.options`
  156. async function plugin$3(formidable, options) {
  157. // the `this` context is always formidable, as the first argument of a plugin
  158. // but this allows us to customize/test each plugin
  159. /* istanbul ignore next */
  160. const self = this || formidable;
  161. if (/octet-stream/i.test(self.headers['content-type'])) {
  162. await init$2.call(self, self, options);
  163. }
  164. return self;
  165. }
  166. // Note that it's a good practice (but it's up to you) to use the `this.options` instead
  167. // of the passed `options` (second) param, because when you decide
  168. // to test the plugin you can pass custom `this` context to it (and so `this.options`)
  169. async function init$2(_self, _opts) {
  170. this.type = octetStreamType;
  171. const originalFilename = this.headers['x-file-name'];
  172. const mimetype = this.headers['content-type'];
  173. const thisPart = {
  174. originalFilename,
  175. mimetype,
  176. };
  177. const newFilename = this._getNewName(thisPart);
  178. const filepath = this._joinDirectoryName(newFilename);
  179. const file = await this._newFile({
  180. newFilename,
  181. filepath,
  182. originalFilename,
  183. mimetype,
  184. });
  185. this.emit('fileBegin', originalFilename, file);
  186. file.open();
  187. this.openedFiles.push(file);
  188. this._flushing += 1;
  189. this._parser = new OctetStreamParser(this.options);
  190. // Keep track of writes that haven't finished so we don't emit the file before it's done being written
  191. let outstandingWrites = 0;
  192. this._parser.on('data', (buffer) => {
  193. this.pause();
  194. outstandingWrites += 1;
  195. file.write(buffer, () => {
  196. outstandingWrites -= 1;
  197. this.resume();
  198. if (this.ended) {
  199. this._parser.emit('doneWritingFile');
  200. }
  201. });
  202. });
  203. this._parser.on('end', () => {
  204. this._flushing -= 1;
  205. this.ended = true;
  206. const done = () => {
  207. file.end(() => {
  208. this.emit('file', 'file', file);
  209. this._maybeEnd();
  210. });
  211. };
  212. if (outstandingWrites === 0) {
  213. done();
  214. } else {
  215. this._parser.once('doneWritingFile', done);
  216. }
  217. });
  218. return this;
  219. }
  220. /* eslint-disable no-underscore-dangle */
  221. // This is a buffering parser, have a look at StreamingQuerystring.js for a streaming parser
  222. class QuerystringParser extends node_stream.Transform {
  223. constructor(options = {}) {
  224. super({ readableObjectMode: true });
  225. this.globalOptions = { ...options };
  226. this.buffer = '';
  227. this.bufferLength = 0;
  228. }
  229. _transform(buffer, encoding, callback) {
  230. this.buffer += buffer.toString('ascii');
  231. this.bufferLength = this.buffer.length;
  232. callback();
  233. }
  234. _flush(callback) {
  235. const fields = new URLSearchParams(this.buffer);
  236. for (const [key, value] of fields) {
  237. this.push({
  238. key,
  239. value,
  240. });
  241. }
  242. this.buffer = '';
  243. callback();
  244. }
  245. }
  246. /* eslint-disable no-underscore-dangle */
  247. const querystringType = 'urlencoded';
  248. // the `options` is also available through the `this.options` / `formidable.options`
  249. function plugin$2(formidable, options) {
  250. // the `this` context is always formidable, as the first argument of a plugin
  251. // but this allows us to customize/test each plugin
  252. /* istanbul ignore next */
  253. const self = this || formidable;
  254. if (/urlencoded/i.test(self.headers['content-type'])) {
  255. init$1.call(self, self, options);
  256. }
  257. return self;
  258. }
  259. // Note that it's a good practice (but it's up to you) to use the `this.options` instead
  260. // of the passed `options` (second) param, because when you decide
  261. // to test the plugin you can pass custom `this` context to it (and so `this.options`)
  262. function init$1(_self, _opts) {
  263. this.type = querystringType;
  264. const parser = new QuerystringParser(this.options);
  265. parser.on('data', ({ key, value }) => {
  266. this.emit('field', key, value);
  267. });
  268. parser.once('end', () => {
  269. this.ended = true;
  270. this._maybeEnd();
  271. });
  272. this._parser = parser;
  273. return this;
  274. }
  275. const missingPlugin = 1000;
  276. const pluginFunction = 1001;
  277. const aborted = 1002;
  278. const noParser = 1003;
  279. const uninitializedParser = 1004;
  280. const filenameNotString = 1005;
  281. const maxFieldsSizeExceeded = 1006;
  282. const maxFieldsExceeded = 1007;
  283. const smallerThanMinFileSize = 1008;
  284. const biggerThanTotalMaxFileSize = 1009;
  285. const noEmptyFiles = 1010;
  286. const missingContentType = 1011;
  287. const malformedMultipart = 1012;
  288. const missingMultipartBoundary = 1013;
  289. const unknownTransferEncoding = 1014;
  290. const maxFilesExceeded = 1015;
  291. const biggerThanMaxFileSize = 1016;
  292. const pluginFailed = 1017;
  293. const cannotCreateDir = 1018;
  294. const FormidableError = class extends Error {
  295. constructor(message, internalCode, httpCode = 500) {
  296. super(message);
  297. this.code = internalCode;
  298. this.httpCode = httpCode;
  299. }
  300. };
  301. var FormidableError$1 = /*#__PURE__*/Object.freeze({
  302. __proto__: null,
  303. aborted: aborted,
  304. biggerThanMaxFileSize: biggerThanMaxFileSize,
  305. biggerThanTotalMaxFileSize: biggerThanTotalMaxFileSize,
  306. cannotCreateDir: cannotCreateDir,
  307. default: FormidableError,
  308. filenameNotString: filenameNotString,
  309. malformedMultipart: malformedMultipart,
  310. maxFieldsExceeded: maxFieldsExceeded,
  311. maxFieldsSizeExceeded: maxFieldsSizeExceeded,
  312. maxFilesExceeded: maxFilesExceeded,
  313. missingContentType: missingContentType,
  314. missingMultipartBoundary: missingMultipartBoundary,
  315. missingPlugin: missingPlugin,
  316. noEmptyFiles: noEmptyFiles,
  317. noParser: noParser,
  318. pluginFailed: pluginFailed,
  319. pluginFunction: pluginFunction,
  320. smallerThanMinFileSize: smallerThanMinFileSize,
  321. uninitializedParser: uninitializedParser,
  322. unknownTransferEncoding: unknownTransferEncoding
  323. });
  324. /* eslint-disable no-fallthrough */
  325. /* eslint-disable no-bitwise */
  326. /* eslint-disable no-plusplus */
  327. /* eslint-disable no-underscore-dangle */
  328. let s = 0;
  329. const STATE = {
  330. PARSER_UNINITIALIZED: s++,
  331. START: s++,
  332. START_BOUNDARY: s++,
  333. HEADER_FIELD_START: s++,
  334. HEADER_FIELD: s++,
  335. HEADER_VALUE_START: s++,
  336. HEADER_VALUE: s++,
  337. HEADER_VALUE_ALMOST_DONE: s++,
  338. HEADERS_ALMOST_DONE: s++,
  339. PART_DATA_START: s++,
  340. PART_DATA: s++,
  341. PART_END: s++,
  342. END: s++,
  343. };
  344. let f = 1;
  345. const FBOUNDARY = { PART_BOUNDARY: f, LAST_BOUNDARY: (f *= 2) };
  346. const LF = 10;
  347. const CR = 13;
  348. const SPACE = 32;
  349. const HYPHEN = 45;
  350. const COLON = 58;
  351. const A = 97;
  352. const Z = 122;
  353. function lower(c) {
  354. return c | 0x20;
  355. }
  356. const STATES = {};
  357. Object.keys(STATE).forEach((stateName) => {
  358. STATES[stateName] = STATE[stateName];
  359. });
  360. class MultipartParser extends node_stream.Transform {
  361. constructor(options = {}) {
  362. super({ readableObjectMode: true });
  363. this.boundary = null;
  364. this.boundaryChars = null;
  365. this.lookbehind = null;
  366. this.bufferLength = 0;
  367. this.state = STATE.PARSER_UNINITIALIZED;
  368. this.globalOptions = { ...options };
  369. this.index = null;
  370. this.flags = 0;
  371. }
  372. _endUnexpected() {
  373. return new FormidableError(
  374. `MultipartParser.end(): stream ended unexpectedly: ${this.explain()}`,
  375. malformedMultipart,
  376. 400,
  377. );
  378. }
  379. _flush(done) {
  380. if (
  381. (this.state === STATE.HEADER_FIELD_START && this.index === 0) ||
  382. (this.state === STATE.PART_DATA && this.index === this.boundary.length)
  383. ) {
  384. this._handleCallback('partEnd');
  385. this._handleCallback('end');
  386. done();
  387. } else if (this.state !== STATE.END) {
  388. done(this._endUnexpected());
  389. } else {
  390. done();
  391. }
  392. }
  393. initWithBoundary(str) {
  394. this.boundary = Buffer.from(`\r\n--${str}`);
  395. this.lookbehind = Buffer.alloc(this.boundary.length + 8);
  396. this.state = STATE.START;
  397. this.boundaryChars = {};
  398. for (let i = 0; i < this.boundary.length; i++) {
  399. this.boundaryChars[this.boundary[i]] = true;
  400. }
  401. }
  402. // eslint-disable-next-line max-params
  403. _handleCallback(name, buf, start, end) {
  404. if (start !== undefined && start === end) {
  405. return;
  406. }
  407. this.push({ name, buffer: buf, start, end });
  408. }
  409. // eslint-disable-next-line max-statements
  410. _transform(buffer, _, done) {
  411. let i = 0;
  412. let prevIndex = this.index;
  413. let { index, state, flags } = this;
  414. const { lookbehind, boundary, boundaryChars } = this;
  415. const boundaryLength = boundary.length;
  416. const boundaryEnd = boundaryLength - 1;
  417. this.bufferLength = buffer.length;
  418. let c = null;
  419. let cl = null;
  420. const setMark = (name, idx) => {
  421. this[`${name}Mark`] = typeof idx === 'number' ? idx : i;
  422. };
  423. const clearMarkSymbol = (name) => {
  424. delete this[`${name}Mark`];
  425. };
  426. const dataCallback = (name, shouldClear) => {
  427. const markSymbol = `${name}Mark`;
  428. if (!(markSymbol in this)) {
  429. return;
  430. }
  431. if (!shouldClear) {
  432. this._handleCallback(name, buffer, this[markSymbol], buffer.length);
  433. setMark(name, 0);
  434. } else {
  435. this._handleCallback(name, buffer, this[markSymbol], i);
  436. clearMarkSymbol(name);
  437. }
  438. };
  439. for (i = 0; i < this.bufferLength; i++) {
  440. c = buffer[i];
  441. switch (state) {
  442. case STATE.PARSER_UNINITIALIZED:
  443. done(this._endUnexpected());
  444. return;
  445. case STATE.START:
  446. index = 0;
  447. state = STATE.START_BOUNDARY;
  448. case STATE.START_BOUNDARY:
  449. if (index === boundary.length - 2) {
  450. if (c === HYPHEN) {
  451. flags |= FBOUNDARY.LAST_BOUNDARY;
  452. } else if (c !== CR) {
  453. done(this._endUnexpected());
  454. return;
  455. }
  456. index++;
  457. break;
  458. } else if (index - 1 === boundary.length - 2) {
  459. if (flags & FBOUNDARY.LAST_BOUNDARY && c === HYPHEN) {
  460. this._handleCallback('end');
  461. state = STATE.END;
  462. flags = 0;
  463. } else if (!(flags & FBOUNDARY.LAST_BOUNDARY) && c === LF) {
  464. index = 0;
  465. this._handleCallback('partBegin');
  466. state = STATE.HEADER_FIELD_START;
  467. } else {
  468. done(this._endUnexpected());
  469. return;
  470. }
  471. break;
  472. }
  473. if (c !== boundary[index + 2]) {
  474. index = -2;
  475. }
  476. if (c === boundary[index + 2]) {
  477. index++;
  478. }
  479. break;
  480. case STATE.HEADER_FIELD_START:
  481. state = STATE.HEADER_FIELD;
  482. setMark('headerField');
  483. index = 0;
  484. case STATE.HEADER_FIELD:
  485. if (c === CR) {
  486. clearMarkSymbol('headerField');
  487. state = STATE.HEADERS_ALMOST_DONE;
  488. break;
  489. }
  490. index++;
  491. if (c === HYPHEN) {
  492. break;
  493. }
  494. if (c === COLON) {
  495. if (index === 1) {
  496. // empty header field
  497. done(this._endUnexpected());
  498. return;
  499. }
  500. dataCallback('headerField', true);
  501. state = STATE.HEADER_VALUE_START;
  502. break;
  503. }
  504. cl = lower(c);
  505. if (cl < A || cl > Z) {
  506. done(this._endUnexpected());
  507. return;
  508. }
  509. break;
  510. case STATE.HEADER_VALUE_START:
  511. if (c === SPACE) {
  512. break;
  513. }
  514. setMark('headerValue');
  515. state = STATE.HEADER_VALUE;
  516. case STATE.HEADER_VALUE:
  517. if (c === CR) {
  518. dataCallback('headerValue', true);
  519. this._handleCallback('headerEnd');
  520. state = STATE.HEADER_VALUE_ALMOST_DONE;
  521. }
  522. break;
  523. case STATE.HEADER_VALUE_ALMOST_DONE:
  524. if (c !== LF) {
  525. done(this._endUnexpected());
  526. return;
  527. }
  528. state = STATE.HEADER_FIELD_START;
  529. break;
  530. case STATE.HEADERS_ALMOST_DONE:
  531. if (c !== LF) {
  532. done(this._endUnexpected());
  533. return;
  534. }
  535. this._handleCallback('headersEnd');
  536. state = STATE.PART_DATA_START;
  537. break;
  538. case STATE.PART_DATA_START:
  539. state = STATE.PART_DATA;
  540. setMark('partData');
  541. case STATE.PART_DATA:
  542. prevIndex = index;
  543. if (index === 0) {
  544. // boyer-moore derived algorithm to safely skip non-boundary data
  545. i += boundaryEnd;
  546. while (i < this.bufferLength && !(buffer[i] in boundaryChars)) {
  547. i += boundaryLength;
  548. }
  549. i -= boundaryEnd;
  550. c = buffer[i];
  551. }
  552. if (index < boundary.length) {
  553. if (boundary[index] === c) {
  554. if (index === 0) {
  555. dataCallback('partData', true);
  556. }
  557. index++;
  558. } else {
  559. index = 0;
  560. }
  561. } else if (index === boundary.length) {
  562. index++;
  563. if (c === CR) {
  564. // CR = part boundary
  565. flags |= FBOUNDARY.PART_BOUNDARY;
  566. } else if (c === HYPHEN) {
  567. // HYPHEN = end boundary
  568. flags |= FBOUNDARY.LAST_BOUNDARY;
  569. } else {
  570. index = 0;
  571. }
  572. } else if (index - 1 === boundary.length) {
  573. if (flags & FBOUNDARY.PART_BOUNDARY) {
  574. index = 0;
  575. if (c === LF) {
  576. // unset the PART_BOUNDARY flag
  577. flags &= ~FBOUNDARY.PART_BOUNDARY;
  578. this._handleCallback('partEnd');
  579. this._handleCallback('partBegin');
  580. state = STATE.HEADER_FIELD_START;
  581. break;
  582. }
  583. } else if (flags & FBOUNDARY.LAST_BOUNDARY) {
  584. if (c === HYPHEN) {
  585. this._handleCallback('partEnd');
  586. this._handleCallback('end');
  587. state = STATE.END;
  588. flags = 0;
  589. } else {
  590. index = 0;
  591. }
  592. } else {
  593. index = 0;
  594. }
  595. }
  596. if (index > 0) {
  597. // when matching a possible boundary, keep a lookbehind reference
  598. // in case it turns out to be a false lead
  599. lookbehind[index - 1] = c;
  600. } else if (prevIndex > 0) {
  601. // if our boundary turned out to be rubbish, the captured lookbehind
  602. // belongs to partData
  603. this._handleCallback('partData', lookbehind, 0, prevIndex);
  604. prevIndex = 0;
  605. setMark('partData');
  606. // reconsider the current character even so it interrupted the sequence
  607. // it could be the beginning of a new sequence
  608. i--;
  609. }
  610. break;
  611. case STATE.END:
  612. break;
  613. default:
  614. done(this._endUnexpected());
  615. return;
  616. }
  617. }
  618. dataCallback('headerField');
  619. dataCallback('headerValue');
  620. dataCallback('partData');
  621. this.index = index;
  622. this.state = state;
  623. this.flags = flags;
  624. done();
  625. return this.bufferLength;
  626. }
  627. explain() {
  628. return `state = ${MultipartParser.stateToString(this.state)}`;
  629. }
  630. }
  631. // eslint-disable-next-line consistent-return
  632. MultipartParser.stateToString = (stateNumber) => {
  633. // eslint-disable-next-line no-restricted-syntax, guard-for-in
  634. for (const stateName in STATE) {
  635. const number = STATE[stateName];
  636. if (number === stateNumber) return stateName;
  637. }
  638. };
  639. var MultipartParser$1 = Object.assign(MultipartParser, { STATES });
  640. /* eslint-disable no-underscore-dangle */
  641. const multipartType = 'multipart';
  642. // the `options` is also available through the `options` / `formidable.options`
  643. function plugin$1(formidable, options) {
  644. // the `this` context is always formidable, as the first argument of a plugin
  645. // but this allows us to customize/test each plugin
  646. /* istanbul ignore next */
  647. const self = this || formidable;
  648. // NOTE: we (currently) support both multipart/form-data and multipart/related
  649. const multipart = /multipart/i.test(self.headers['content-type']);
  650. if (multipart) {
  651. const m = self.headers['content-type'].match(
  652. /boundary=(?:"([^"]+)"|([^;]+))/i,
  653. );
  654. if (m) {
  655. const initMultipart = createInitMultipart(m[1] || m[2]);
  656. initMultipart.call(self, self, options); // lgtm [js/superfluous-trailing-arguments]
  657. } else {
  658. const err = new FormidableError(
  659. 'bad content-type header, no multipart boundary',
  660. missingMultipartBoundary,
  661. 400,
  662. );
  663. self._error(err);
  664. }
  665. }
  666. return self;
  667. }
  668. // Note that it's a good practice (but it's up to you) to use the `this.options` instead
  669. // of the passed `options` (second) param, because when you decide
  670. // to test the plugin you can pass custom `this` context to it (and so `this.options`)
  671. function createInitMultipart(boundary) {
  672. return function initMultipart() {
  673. this.type = multipartType;
  674. const parser = new MultipartParser$1(this.options);
  675. let headerField;
  676. let headerValue;
  677. let part;
  678. parser.initWithBoundary(boundary);
  679. // eslint-disable-next-line max-statements, consistent-return
  680. parser.on('data', async ({ name, buffer, start, end }) => {
  681. if (name === 'partBegin') {
  682. part = new node_stream.Stream();
  683. part.readable = true;
  684. part.headers = {};
  685. part.name = null;
  686. part.originalFilename = null;
  687. part.mimetype = null;
  688. part.transferEncoding = this.options.encoding;
  689. part.transferBuffer = '';
  690. headerField = '';
  691. headerValue = '';
  692. } else if (name === 'headerField') {
  693. headerField += buffer.toString(this.options.encoding, start, end);
  694. } else if (name === 'headerValue') {
  695. headerValue += buffer.toString(this.options.encoding, start, end);
  696. } else if (name === 'headerEnd') {
  697. headerField = headerField.toLowerCase();
  698. part.headers[headerField] = headerValue;
  699. // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
  700. const m = headerValue.match(
  701. // eslint-disable-next-line no-useless-escape
  702. /\bname=("([^"]*)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))/i,
  703. );
  704. if (headerField === 'content-disposition') {
  705. if (m) {
  706. part.name = m[2] || m[3] || '';
  707. }
  708. part.originalFilename = this._getFileName(headerValue);
  709. } else if (headerField === 'content-type') {
  710. part.mimetype = headerValue;
  711. } else if (headerField === 'content-transfer-encoding') {
  712. part.transferEncoding = headerValue.toLowerCase();
  713. }
  714. headerField = '';
  715. headerValue = '';
  716. } else if (name === 'headersEnd') {
  717. switch (part.transferEncoding) {
  718. case 'binary':
  719. case '7bit':
  720. case '8bit':
  721. case 'utf-8': {
  722. const dataPropagation = (ctx) => {
  723. if (ctx.name === 'partData') {
  724. part.emit('data', ctx.buffer.slice(ctx.start, ctx.end));
  725. }
  726. };
  727. const dataStopPropagation = (ctx) => {
  728. if (ctx.name === 'partEnd') {
  729. part.emit('end');
  730. parser.off('data', dataPropagation);
  731. parser.off('data', dataStopPropagation);
  732. }
  733. };
  734. parser.on('data', dataPropagation);
  735. parser.on('data', dataStopPropagation);
  736. break;
  737. }
  738. case 'base64': {
  739. const dataPropagation = (ctx) => {
  740. if (ctx.name === 'partData') {
  741. part.transferBuffer += ctx.buffer
  742. .slice(ctx.start, ctx.end)
  743. .toString('ascii');
  744. /*
  745. four bytes (chars) in base64 converts to three bytes in binary
  746. encoding. So we should always work with a number of bytes that
  747. can be divided by 4, it will result in a number of bytes that
  748. can be divided vy 3.
  749. */
  750. const offset = parseInt(part.transferBuffer.length / 4, 10) * 4;
  751. part.emit(
  752. 'data',
  753. Buffer.from(
  754. part.transferBuffer.substring(0, offset),
  755. 'base64',
  756. ),
  757. );
  758. part.transferBuffer = part.transferBuffer.substring(offset);
  759. }
  760. };
  761. const dataStopPropagation = (ctx) => {
  762. if (ctx.name === 'partEnd') {
  763. part.emit('data', Buffer.from(part.transferBuffer, 'base64'));
  764. part.emit('end');
  765. parser.off('data', dataPropagation);
  766. parser.off('data', dataStopPropagation);
  767. }
  768. };
  769. parser.on('data', dataPropagation);
  770. parser.on('data', dataStopPropagation);
  771. break;
  772. }
  773. default:
  774. return this._error(
  775. new FormidableError(
  776. 'unknown transfer-encoding',
  777. unknownTransferEncoding,
  778. 501,
  779. ),
  780. );
  781. }
  782. this._parser.pause();
  783. await this.onPart(part);
  784. this._parser.resume();
  785. } else if (name === 'end') {
  786. this.ended = true;
  787. this._maybeEnd();
  788. }
  789. });
  790. this._parser = parser;
  791. };
  792. }
  793. /* eslint-disable no-underscore-dangle */
  794. class JSONParser extends node_stream.Transform {
  795. constructor(options = {}) {
  796. super({ readableObjectMode: true });
  797. this.chunks = [];
  798. this.globalOptions = { ...options };
  799. }
  800. _transform(chunk, encoding, callback) {
  801. this.chunks.push(String(chunk)); // todo consider using a string decoder
  802. callback();
  803. }
  804. _flush(callback) {
  805. try {
  806. const fields = JSON.parse(this.chunks.join(''));
  807. this.push(fields);
  808. } catch (e) {
  809. callback(e);
  810. return;
  811. }
  812. this.chunks = null;
  813. callback();
  814. }
  815. }
  816. /* eslint-disable no-underscore-dangle */
  817. const jsonType = 'json';
  818. // the `options` is also available through the `this.options` / `formidable.options`
  819. function plugin(formidable, options) {
  820. // the `this` context is always formidable, as the first argument of a plugin
  821. // but this allows us to customize/test each plugin
  822. /* istanbul ignore next */
  823. const self = this || formidable;
  824. if (/json/i.test(self.headers['content-type'])) {
  825. init.call(self, self, options);
  826. }
  827. return self;
  828. }
  829. // Note that it's a good practice (but it's up to you) to use the `this.options` instead
  830. // of the passed `options` (second) param, because when you decide
  831. // to test the plugin you can pass custom `this` context to it (and so `this.options`)
  832. function init(_self, _opts) {
  833. this.type = jsonType;
  834. const parser = new JSONParser(this.options);
  835. parser.on('data', (fields) => {
  836. this.fields = fields;
  837. });
  838. parser.once('end', () => {
  839. this.ended = true;
  840. this._maybeEnd();
  841. });
  842. this._parser = parser;
  843. }
  844. /* eslint-disable no-underscore-dangle */
  845. class DummyParser extends node_stream.Transform {
  846. constructor(incomingForm, options = {}) {
  847. super();
  848. this.globalOptions = { ...options };
  849. this.incomingForm = incomingForm;
  850. }
  851. _flush(callback) {
  852. this.incomingForm.ended = true;
  853. this.incomingForm._maybeEnd();
  854. callback();
  855. }
  856. }
  857. /* eslint-disable class-methods-use-this */
  858. /* eslint-disable no-underscore-dangle */
  859. const toHexoId = hexoid.hexoid(25);
  860. const DEFAULT_OPTIONS = {
  861. maxFields: 1000,
  862. maxFieldsSize: 20 * 1024 * 1024,
  863. maxFiles: Infinity,
  864. maxFileSize: 200 * 1024 * 1024,
  865. maxTotalFileSize: undefined,
  866. minFileSize: 1,
  867. allowEmptyFiles: false,
  868. createDirsFromUploads: false,
  869. keepExtensions: false,
  870. encoding: 'utf-8',
  871. hashAlgorithm: false,
  872. uploadDir: os.tmpdir(),
  873. enabledPlugins: [plugin$3, plugin$2, plugin$1, plugin],
  874. fileWriteStreamHandler: null,
  875. defaultInvalidName: 'invalid-name',
  876. filter(_part) {
  877. return true;
  878. },
  879. filename: undefined,
  880. };
  881. function hasOwnProp(obj, key) {
  882. return Object.prototype.hasOwnProperty.call(obj, key);
  883. }
  884. const decorateForceSequential = function (promiseCreator) {
  885. /* forces a function that returns a promise to be sequential
  886. useful for fs for example */
  887. let lastPromise = Promise.resolve();
  888. return async function (...x) {
  889. const promiseWeAreWaitingFor = lastPromise;
  890. let currentPromise;
  891. let callback;
  892. // we need to change lastPromise before await anything,
  893. // otherwise 2 calls might wait the same thing
  894. lastPromise = new Promise(function (resolve) {
  895. callback = resolve;
  896. });
  897. await promiseWeAreWaitingFor;
  898. currentPromise = promiseCreator(...x);
  899. currentPromise.then(callback).catch(callback);
  900. return currentPromise;
  901. };
  902. };
  903. const createNecessaryDirectoriesAsync = decorateForceSequential(function (filePath) {
  904. const directoryname = path.dirname(filePath);
  905. return fsPromises.mkdir(directoryname, { recursive: true });
  906. });
  907. const invalidExtensionChar = (c) => {
  908. const code = c.charCodeAt(0);
  909. return !(
  910. code === 46 || // .
  911. (code >= 48 && code <= 57) ||
  912. (code >= 65 && code <= 90) ||
  913. (code >= 97 && code <= 122)
  914. );
  915. };
  916. class IncomingForm extends node_events.EventEmitter {
  917. constructor(options = {}) {
  918. super();
  919. this.options = { ...DEFAULT_OPTIONS, ...options };
  920. if (!this.options.maxTotalFileSize) {
  921. this.options.maxTotalFileSize = this.options.maxFileSize;
  922. }
  923. const dir = path.resolve(
  924. this.options.uploadDir || this.options.uploaddir || os.tmpdir(),
  925. );
  926. this.uploaddir = dir;
  927. this.uploadDir = dir;
  928. // initialize with null
  929. [
  930. 'error',
  931. 'headers',
  932. 'type',
  933. 'bytesExpected',
  934. 'bytesReceived',
  935. '_parser',
  936. 'req',
  937. ].forEach((key) => {
  938. this[key] = null;
  939. });
  940. this._setUpRename();
  941. this._flushing = 0;
  942. this._fieldsSize = 0;
  943. this._totalFileSize = 0;
  944. this._plugins = [];
  945. this.openedFiles = [];
  946. this.options.enabledPlugins = []
  947. .concat(this.options.enabledPlugins)
  948. .filter(Boolean);
  949. if (this.options.enabledPlugins.length === 0) {
  950. throw new FormidableError(
  951. 'expect at least 1 enabled builtin plugin, see options.enabledPlugins',
  952. missingPlugin,
  953. );
  954. }
  955. this.options.enabledPlugins.forEach((plugin) => {
  956. this.use(plugin);
  957. });
  958. this._setUpMaxFields();
  959. this._setUpMaxFiles();
  960. this.ended = undefined;
  961. this.type = undefined;
  962. }
  963. use(plugin) {
  964. if (typeof plugin !== 'function') {
  965. throw new FormidableError(
  966. '.use: expect `plugin` to be a function',
  967. pluginFunction,
  968. );
  969. }
  970. this._plugins.push(plugin.bind(this));
  971. return this;
  972. }
  973. pause () {
  974. try {
  975. this.req.pause();
  976. } catch (err) {
  977. // the stream was destroyed
  978. if (!this.ended) {
  979. // before it was completed, crash & burn
  980. this._error(err);
  981. }
  982. return false;
  983. }
  984. return true;
  985. }
  986. resume () {
  987. try {
  988. this.req.resume();
  989. } catch (err) {
  990. // the stream was destroyed
  991. if (!this.ended) {
  992. // before it was completed, crash & burn
  993. this._error(err);
  994. }
  995. return false;
  996. }
  997. return true;
  998. }
  999. // returns a promise if no callback is provided
  1000. async parse(req, cb) {
  1001. this.req = req;
  1002. let promise;
  1003. // Setup callback first, so we don't miss anything from data events emitted immediately.
  1004. if (!cb) {
  1005. let resolveRef;
  1006. let rejectRef;
  1007. promise = new Promise((resolve, reject) => {
  1008. resolveRef = resolve;
  1009. rejectRef = reject;
  1010. });
  1011. cb = (err, fields, files) => {
  1012. if (err) {
  1013. rejectRef(err);
  1014. } else {
  1015. resolveRef([fields, files]);
  1016. }
  1017. };
  1018. }
  1019. const callback = once(dezalgo(cb));
  1020. this.fields = {};
  1021. const files = {};
  1022. this.on('field', (name, value) => {
  1023. if (this.type === 'multipart' || this.type === 'urlencoded') {
  1024. if (!hasOwnProp(this.fields, name)) {
  1025. this.fields[name] = [value];
  1026. } else {
  1027. this.fields[name].push(value);
  1028. }
  1029. } else {
  1030. this.fields[name] = value;
  1031. }
  1032. });
  1033. this.on('file', (name, file) => {
  1034. if (!hasOwnProp(files, name)) {
  1035. files[name] = [file];
  1036. } else {
  1037. files[name].push(file);
  1038. }
  1039. });
  1040. this.on('error', (err) => {
  1041. callback(err, this.fields, files);
  1042. });
  1043. this.on('end', () => {
  1044. callback(null, this.fields, files);
  1045. });
  1046. // Parse headers and setup the parser, ready to start listening for data.
  1047. await this.writeHeaders(req.headers);
  1048. // Start listening for data.
  1049. req
  1050. .on('error', (err) => {
  1051. this._error(err);
  1052. })
  1053. .on('aborted', () => {
  1054. this.emit('aborted');
  1055. this._error(new FormidableError('Request aborted', aborted));
  1056. })
  1057. .on('data', (buffer) => {
  1058. try {
  1059. this.write(buffer);
  1060. } catch (err) {
  1061. this._error(err);
  1062. }
  1063. })
  1064. .on('end', () => {
  1065. if (this.error) {
  1066. return;
  1067. }
  1068. if (this._parser) {
  1069. this._parser.end();
  1070. }
  1071. });
  1072. if (promise) {
  1073. return promise;
  1074. }
  1075. return this;
  1076. }
  1077. async writeHeaders(headers) {
  1078. this.headers = headers;
  1079. this._parseContentLength();
  1080. await this._parseContentType();
  1081. if (!this._parser) {
  1082. this._error(
  1083. new FormidableError(
  1084. 'no parser found',
  1085. noParser,
  1086. 415, // Unsupported Media Type
  1087. ),
  1088. );
  1089. return;
  1090. }
  1091. this._parser.once('error', (error) => {
  1092. this._error(error);
  1093. });
  1094. }
  1095. write(buffer) {
  1096. if (this.error) {
  1097. return null;
  1098. }
  1099. if (!this._parser) {
  1100. this._error(
  1101. new FormidableError('uninitialized parser', uninitializedParser),
  1102. );
  1103. return null;
  1104. }
  1105. this.bytesReceived += buffer.length;
  1106. this.emit('progress', this.bytesReceived, this.bytesExpected);
  1107. this._parser.write(buffer);
  1108. return this.bytesReceived;
  1109. }
  1110. onPart(part) {
  1111. // this method can be overwritten by the user
  1112. return this._handlePart(part);
  1113. }
  1114. async _handlePart(part) {
  1115. if (part.originalFilename && typeof part.originalFilename !== 'string') {
  1116. this._error(
  1117. new FormidableError(
  1118. `the part.originalFilename should be string when it exists`,
  1119. filenameNotString,
  1120. ),
  1121. );
  1122. return;
  1123. }
  1124. // This MUST check exactly for undefined. You can not change it to !part.originalFilename.
  1125. // todo: uncomment when switch tests to Jest
  1126. // console.log(part);
  1127. // ? NOTE(@tunnckocore): no it can be any falsey value, it most probably depends on what's returned
  1128. // from somewhere else. Where recently I changed the return statements
  1129. // and such thing because code style
  1130. // ? NOTE(@tunnckocore): or even better, if there is no mimetype, then it's for sure a field
  1131. // ? NOTE(@tunnckocore): originalFilename is an empty string when a field?
  1132. if (!part.mimetype) {
  1133. let value = '';
  1134. const decoder = new node_string_decoder.StringDecoder(
  1135. part.transferEncoding || this.options.encoding,
  1136. );
  1137. part.on('data', (buffer) => {
  1138. this._fieldsSize += buffer.length;
  1139. if (this._fieldsSize > this.options.maxFieldsSize) {
  1140. this._error(
  1141. new FormidableError(
  1142. `options.maxFieldsSize (${this.options.maxFieldsSize} bytes) exceeded, received ${this._fieldsSize} bytes of field data`,
  1143. maxFieldsSizeExceeded,
  1144. 413, // Payload Too Large
  1145. ),
  1146. );
  1147. return;
  1148. }
  1149. value += decoder.write(buffer);
  1150. });
  1151. part.on('end', () => {
  1152. this.emit('field', part.name, value);
  1153. });
  1154. return;
  1155. }
  1156. if (!this.options.filter(part)) {
  1157. return;
  1158. }
  1159. this._flushing += 1;
  1160. let fileSize = 0;
  1161. const newFilename = this._getNewName(part);
  1162. const filepath = this._joinDirectoryName(newFilename);
  1163. const file = await this._newFile({
  1164. newFilename,
  1165. filepath,
  1166. originalFilename: part.originalFilename,
  1167. mimetype: part.mimetype,
  1168. });
  1169. file.on('error', (err) => {
  1170. this._error(err);
  1171. });
  1172. this.emit('fileBegin', part.name, file);
  1173. file.open();
  1174. this.openedFiles.push(file);
  1175. part.on('data', (buffer) => {
  1176. this._totalFileSize += buffer.length;
  1177. fileSize += buffer.length;
  1178. if (this._totalFileSize > this.options.maxTotalFileSize) {
  1179. this._error(
  1180. new FormidableError(
  1181. `options.maxTotalFileSize (${this.options.maxTotalFileSize} bytes) exceeded, received ${this._totalFileSize} bytes of file data`,
  1182. biggerThanTotalMaxFileSize,
  1183. 413,
  1184. ),
  1185. );
  1186. return;
  1187. }
  1188. if (buffer.length === 0) {
  1189. return;
  1190. }
  1191. this.pause();
  1192. file.write(buffer, () => {
  1193. this.resume();
  1194. });
  1195. });
  1196. part.on('end', () => {
  1197. if (!this.options.allowEmptyFiles && fileSize === 0) {
  1198. this._error(
  1199. new FormidableError(
  1200. `options.allowEmptyFiles is false, file size should be greater than 0`,
  1201. noEmptyFiles,
  1202. 400,
  1203. ),
  1204. );
  1205. return;
  1206. }
  1207. if (fileSize < this.options.minFileSize) {
  1208. this._error(
  1209. new FormidableError(
  1210. `options.minFileSize (${this.options.minFileSize} bytes) inferior, received ${fileSize} bytes of file data`,
  1211. smallerThanMinFileSize,
  1212. 400,
  1213. ),
  1214. );
  1215. return;
  1216. }
  1217. if (fileSize > this.options.maxFileSize) {
  1218. this._error(
  1219. new FormidableError(
  1220. `options.maxFileSize (${this.options.maxFileSize} bytes), received ${fileSize} bytes of file data`,
  1221. biggerThanMaxFileSize,
  1222. 413,
  1223. ),
  1224. );
  1225. return;
  1226. }
  1227. file.end(() => {
  1228. this._flushing -= 1;
  1229. this.emit('file', part.name, file);
  1230. this._maybeEnd();
  1231. });
  1232. });
  1233. }
  1234. // eslint-disable-next-line max-statements
  1235. async _parseContentType() {
  1236. if (this.bytesExpected === 0) {
  1237. this._parser = new DummyParser(this, this.options);
  1238. return;
  1239. }
  1240. if (!this.headers['content-type']) {
  1241. this._error(
  1242. new FormidableError(
  1243. 'bad content-type header, no content-type',
  1244. missingContentType,
  1245. 400,
  1246. ),
  1247. );
  1248. return;
  1249. }
  1250. new DummyParser(this, this.options);
  1251. const results = [];
  1252. await Promise.all(this._plugins.map(async (plugin, idx) => {
  1253. let pluginReturn = null;
  1254. try {
  1255. pluginReturn = await plugin(this, this.options) || this;
  1256. } catch (err) {
  1257. // directly throw from the `form.parse` method;
  1258. // there is no other better way, except a handle through options
  1259. const error = new FormidableError(
  1260. `plugin on index ${idx} failed with: ${err.message}`,
  1261. pluginFailed,
  1262. 500,
  1263. );
  1264. error.idx = idx;
  1265. throw error;
  1266. }
  1267. Object.assign(this, pluginReturn);
  1268. // todo: use Set/Map and pass plugin name instead of the `idx` index
  1269. this.emit('plugin', idx, pluginReturn);
  1270. }));
  1271. this.emit('pluginsResults', results);
  1272. }
  1273. _error(err, eventName = 'error') {
  1274. if (this.error || this.ended) {
  1275. return;
  1276. }
  1277. this.req = null;
  1278. this.error = err;
  1279. this.emit(eventName, err);
  1280. this.openedFiles.forEach((file) => {
  1281. file.destroy();
  1282. });
  1283. }
  1284. _parseContentLength() {
  1285. this.bytesReceived = 0;
  1286. if (this.headers['content-length']) {
  1287. this.bytesExpected = parseInt(this.headers['content-length'], 10);
  1288. } else if (this.headers['transfer-encoding'] === undefined) {
  1289. this.bytesExpected = 0;
  1290. }
  1291. if (this.bytesExpected !== null) {
  1292. this.emit('progress', this.bytesReceived, this.bytesExpected);
  1293. }
  1294. }
  1295. _newParser() {
  1296. return new MultipartParser$1(this.options);
  1297. }
  1298. async _newFile({ filepath, originalFilename, mimetype, newFilename }) {
  1299. if (this.options.fileWriteStreamHandler) {
  1300. return new VolatileFile({
  1301. newFilename,
  1302. filepath,
  1303. originalFilename,
  1304. mimetype,
  1305. createFileWriteStream: this.options.fileWriteStreamHandler,
  1306. hashAlgorithm: this.options.hashAlgorithm,
  1307. });
  1308. }
  1309. if (this.options.createDirsFromUploads) {
  1310. try {
  1311. await createNecessaryDirectoriesAsync(filepath);
  1312. } catch (errorCreatingDir) {
  1313. this._error(new FormidableError(
  1314. `cannot create directory`,
  1315. cannotCreateDir,
  1316. 409,
  1317. ));
  1318. }
  1319. }
  1320. return new PersistentFile({
  1321. newFilename,
  1322. filepath,
  1323. originalFilename,
  1324. mimetype,
  1325. hashAlgorithm: this.options.hashAlgorithm,
  1326. });
  1327. }
  1328. _getFileName(headerValue) {
  1329. // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
  1330. const m = headerValue.match(
  1331. /\bfilename=("(.*?)"|([^()<>{}[\]@,;:"?=\s/\t]+))($|;\s)/i,
  1332. );
  1333. if (!m) return null;
  1334. const match = m[2] || m[3] || '';
  1335. let originalFilename = match.substr(match.lastIndexOf('\\') + 1);
  1336. originalFilename = originalFilename.replace(/%22/g, '"');
  1337. originalFilename = originalFilename.replace(/&#([\d]{4});/g, (_, code) =>
  1338. String.fromCharCode(code),
  1339. );
  1340. return originalFilename;
  1341. }
  1342. // able to get composed extension with multiple dots
  1343. // "a.b.c" -> ".b.c"
  1344. // as opposed to path.extname -> ".c"
  1345. _getExtension(str) {
  1346. if (!str) {
  1347. return '';
  1348. }
  1349. const basename = path.basename(str);
  1350. const firstDot = basename.indexOf('.');
  1351. const lastDot = basename.lastIndexOf('.');
  1352. let rawExtname = path.extname(basename);
  1353. if (firstDot !== lastDot) {
  1354. rawExtname = basename.slice(firstDot);
  1355. }
  1356. let filtered;
  1357. const firstInvalidIndex = Array.from(rawExtname).findIndex(invalidExtensionChar);
  1358. if (firstInvalidIndex === -1) {
  1359. filtered = rawExtname;
  1360. } else {
  1361. filtered = rawExtname.substring(0, firstInvalidIndex);
  1362. }
  1363. if (filtered === '.') {
  1364. return '';
  1365. }
  1366. return filtered;
  1367. }
  1368. _joinDirectoryName(name) {
  1369. const newPath = path.join(this.uploadDir, name);
  1370. // prevent directory traversal attacks
  1371. if (!newPath.startsWith(this.uploadDir)) {
  1372. return path.join(this.uploadDir, this.options.defaultInvalidName);
  1373. }
  1374. return newPath;
  1375. }
  1376. _setUpRename() {
  1377. const hasRename = typeof this.options.filename === 'function';
  1378. if (hasRename) {
  1379. this._getNewName = (part) => {
  1380. let ext = '';
  1381. let name = this.options.defaultInvalidName;
  1382. if (part.originalFilename) {
  1383. // can be null
  1384. ({ ext, name } = path.parse(part.originalFilename));
  1385. if (this.options.keepExtensions !== true) {
  1386. ext = '';
  1387. }
  1388. }
  1389. return this.options.filename.call(this, name, ext, part, this);
  1390. };
  1391. } else {
  1392. this._getNewName = (part) => {
  1393. const name = toHexoId();
  1394. if (part && this.options.keepExtensions) {
  1395. const originalFilename =
  1396. typeof part === 'string' ? part : part.originalFilename;
  1397. return `${name}${this._getExtension(originalFilename)}`;
  1398. }
  1399. return name;
  1400. };
  1401. }
  1402. }
  1403. _setUpMaxFields() {
  1404. if (this.options.maxFields !== Infinity) {
  1405. let fieldsCount = 0;
  1406. this.on('field', () => {
  1407. fieldsCount += 1;
  1408. if (fieldsCount > this.options.maxFields) {
  1409. this._error(
  1410. new FormidableError(
  1411. `options.maxFields (${this.options.maxFields}) exceeded`,
  1412. maxFieldsExceeded,
  1413. 413,
  1414. ),
  1415. );
  1416. }
  1417. });
  1418. }
  1419. }
  1420. _setUpMaxFiles() {
  1421. if (this.options.maxFiles !== Infinity) {
  1422. let fileCount = 0;
  1423. this.on('fileBegin', () => {
  1424. fileCount += 1;
  1425. if (fileCount > this.options.maxFiles) {
  1426. this._error(
  1427. new FormidableError(
  1428. `options.maxFiles (${this.options.maxFiles}) exceeded`,
  1429. maxFilesExceeded,
  1430. 413,
  1431. ),
  1432. );
  1433. }
  1434. });
  1435. }
  1436. }
  1437. _maybeEnd() {
  1438. if (!this.ended || this._flushing || this.error) {
  1439. return;
  1440. }
  1441. this.req = null;
  1442. this.emit('end');
  1443. }
  1444. }
  1445. // make it available without requiring the `new` keyword
  1446. // if you want it access `const formidable.IncomingForm` as v1
  1447. const formidable = (...args) => new IncomingForm(...args);
  1448. const {enabledPlugins} = DEFAULT_OPTIONS;
  1449. exports.DummyParser = DummyParser;
  1450. exports.File = PersistentFile;
  1451. exports.Formidable = IncomingForm;
  1452. exports.IncomingForm = IncomingForm;
  1453. exports.JSONParser = JSONParser;
  1454. exports.MultipartParser = MultipartParser$1;
  1455. exports.OctetStreamParser = OctetStreamParser;
  1456. exports.OctetstreamParser = OctetStreamParser;
  1457. exports.PersistentFile = PersistentFile;
  1458. exports.QueryStringParser = QuerystringParser;
  1459. exports.QuerystringParser = QuerystringParser;
  1460. exports.VolatileFile = VolatileFile;
  1461. exports.default = formidable;
  1462. exports.defaultOptions = DEFAULT_OPTIONS;
  1463. exports.enabledPlugins = enabledPlugins;
  1464. exports.errors = FormidableError$1;
  1465. exports.formidable = formidable;
  1466. exports.json = plugin;
  1467. exports.multipart = plugin$1;
  1468. exports.octetstream = plugin$3;
  1469. exports.querystring = plugin$2;