From 305ae6a35e1e25f8566308568b0c612fad378a22 Mon Sep 17 00:00:00 2001 From: Rim Date: Sat, 12 Apr 2025 02:57:05 -0400 Subject: [PATCH] chore: add rate limiting --- app.js | 303 ++++++- node_modules/.package-lock.json | 130 +++ .../@fastify/busboy/deps/dicer/lib/Dicer.js | 213 +++++ .../busboy/deps/dicer/lib/HeaderParser.js | 100 +++ .../busboy/deps/dicer/lib/PartStream.js | 13 + .../@fastify/busboy/deps/dicer/lib/dicer.d.ts | 164 ++++ .../@fastify/busboy/deps/streamsearch/sbmh.js | 228 +++++ node_modules/@fastify/busboy/lib/main.d.ts | 196 ++++ node_modules/@fastify/busboy/lib/main.js | 85 ++ .../@fastify/busboy/lib/types/multipart.js | 306 +++++++ .../@fastify/busboy/lib/types/urlencoded.js | 190 ++++ .../@fastify/busboy/lib/utils/Decoder.js | 54 ++ .../@fastify/busboy/lib/utils/basename.js | 14 + .../@fastify/busboy/lib/utils/decodeText.js | 114 +++ .../@fastify/busboy/lib/utils/getLimit.js | 16 + .../@fastify/busboy/lib/utils/parseParams.js | 196 ++++ node_modules/@fastify/busboy/package.json | 86 ++ .../express-rate-limit/dist/index.cjs | 838 ++++++++++++++++++ .../express-rate-limit/dist/index.d.cts | 584 ++++++++++++ .../express-rate-limit/dist/index.d.mts | 584 ++++++++++++ .../express-rate-limit/dist/index.d.ts | 584 ++++++++++++ .../express-rate-limit/dist/index.mjs | 809 +++++++++++++++++ node_modules/express-rate-limit/package.json | 133 +++ node_modules/express-rate-limit/tsconfig.json | 8 + node_modules/express-session/index.js | 693 +++++++++++++++ .../node_modules/cookie-signature/index.js | 51 ++ .../cookie-signature/package.json | 18 + .../node_modules/cookie/index.js | 335 +++++++ .../node_modules/cookie/package.json | 44 + node_modules/express-session/package.json | 47 + .../express-session/session/cookie.js | 152 ++++ .../express-session/session/memory.js | 187 ++++ .../express-session/session/session.js | 143 +++ node_modules/express-session/session/store.js | 102 +++ node_modules/on-headers/index.js | 132 +++ node_modules/on-headers/package.json | 42 + node_modules/random-bytes/index.js | 101 +++ node_modules/random-bytes/package.json | 36 + node_modules/uid-safe/index.js | 107 +++ node_modules/uid-safe/package.json | 46 + package-lock.json | 118 +++ package.json | 3 + src/css/styles.css | 16 + src/js/backend-min.js | 381 ++++++++ src/js/backend.js | 10 +- src/js/frontend.js | 85 ++ src/js/index.d.ts | 5 + src/js/index.js | 49 + src/js/index.ts | 58 ++ src/js/test.js | 41 + token.txt | 1 + 51 files changed, 8903 insertions(+), 48 deletions(-) create mode 100644 node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js create mode 100644 node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js create mode 100644 node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js create mode 100644 node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts create mode 100644 node_modules/@fastify/busboy/deps/streamsearch/sbmh.js create mode 100644 node_modules/@fastify/busboy/lib/main.d.ts create mode 100644 node_modules/@fastify/busboy/lib/main.js create mode 100644 node_modules/@fastify/busboy/lib/types/multipart.js create mode 100644 node_modules/@fastify/busboy/lib/types/urlencoded.js create mode 100644 node_modules/@fastify/busboy/lib/utils/Decoder.js create mode 100644 node_modules/@fastify/busboy/lib/utils/basename.js create mode 100644 node_modules/@fastify/busboy/lib/utils/decodeText.js create mode 100644 node_modules/@fastify/busboy/lib/utils/getLimit.js create mode 100644 node_modules/@fastify/busboy/lib/utils/parseParams.js create mode 100644 node_modules/@fastify/busboy/package.json create mode 100644 node_modules/express-rate-limit/dist/index.cjs create mode 100644 node_modules/express-rate-limit/dist/index.d.cts create mode 100644 node_modules/express-rate-limit/dist/index.d.mts create mode 100644 node_modules/express-rate-limit/dist/index.d.ts create mode 100644 node_modules/express-rate-limit/dist/index.mjs create mode 100644 node_modules/express-rate-limit/package.json create mode 100644 node_modules/express-rate-limit/tsconfig.json create mode 100644 node_modules/express-session/index.js create mode 100644 node_modules/express-session/node_modules/cookie-signature/index.js create mode 100644 node_modules/express-session/node_modules/cookie-signature/package.json create mode 100644 node_modules/express-session/node_modules/cookie/index.js create mode 100644 node_modules/express-session/node_modules/cookie/package.json create mode 100644 node_modules/express-session/package.json create mode 100644 node_modules/express-session/session/cookie.js create mode 100644 node_modules/express-session/session/memory.js create mode 100644 node_modules/express-session/session/session.js create mode 100644 node_modules/express-session/session/store.js create mode 100644 node_modules/on-headers/index.js create mode 100644 node_modules/on-headers/package.json create mode 100644 node_modules/random-bytes/index.js create mode 100644 node_modules/random-bytes/package.json create mode 100644 node_modules/uid-safe/index.js create mode 100644 node_modules/uid-safe/package.json create mode 100644 src/js/backend-min.js create mode 100644 src/js/test.js create mode 100644 token.txt diff --git a/app.js b/app.js index 9262b47..466682d 100644 --- a/app.js +++ b/app.js @@ -1,4 +1,5 @@ const express = require('express'); +const rateLimit = require('express-rate-limit'); const path = require('path'); const bodyParser = require('body-parser'); const API = require('./src/js/index.js'); @@ -11,7 +12,7 @@ require('./src/js/utils.js'); app.set('trust proxy', true); // Middleware -app.use(bodyParser.json({ limit: '10mb' })); +// app.use(bodyParser.json({ limit: '10mb' })); app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' })); app.use(express.static(__dirname)); app.use(express.static(path.join(__dirname, 'public'))); @@ -29,6 +30,153 @@ app.use( const fs = require('fs'); +let DEFAULT_SSO_TOKEN = ''; + +// Try to read the token from a file +try { + const tokenPath = path.join(__dirname, 'token.txt'); + if (fs.existsSync(tokenPath)) { + DEFAULT_SSO_TOKEN = fs.readFileSync(tokenPath, 'utf8').trim(); + logger.info('Default SSO token loaded successfully from token.txt'); + } else { + logger.warn('token.txt not found, demo mode may not function correctly'); + } +} catch (error) { + logger.error('Error loading token file:', { error: error.message }); +} + +setInterval(() => demoModeRequestTracker.cleanupExpiredEntries(), 3600000); // Clean up every hour + +// Configure rate limiting for demo mode +const demoModeRequestTracker = { + requests: new Map(), + maxRequestsPerHour: 5, // Adjust as needed + resetInterval: 60 * 60 * 1000, // 1 hour in milliseconds + + isLimited: function (ip) { + const now = Date.now(); + const userRequests = this.requests.get(ip) || { + count: 0, + resetTime: now + this.resetInterval, + }; + + // Reset counter if the reset time has passed + if (now > userRequests.resetTime) { + userRequests.count = 0; + userRequests.resetTime = now + this.resetInterval; + } + + return userRequests.count >= this.maxRequestsPerHour; + }, + + incrementCounter: function (ip) { + const now = Date.now(); + const userRequests = this.requests.get(ip) || { + count: 0, + resetTime: now + this.resetInterval, + }; + + // Reset counter if the reset time has passed + if (now > userRequests.resetTime) { + userRequests.count = 1; // Start with 1 for this request + userRequests.resetTime = now + this.resetInterval; + } else { + userRequests.count++; + } + + this.requests.set(ip, userRequests); + return userRequests.count; + }, + + cleanupExpiredEntries: function () { + const now = Date.now(); + for (const [ip, data] of this.requests.entries()) { + if (now > data.resetTime) { + // Either remove entries completely or reset them to 0 + this.requests.delete(ip); + } + } + }, +}; + +// Demo mode middleware +const demoModeMiddleware = (req, res, next) => { + // Skip non-API routes + if (!req.path.startsWith('/api/')) { + return next(); + } + + // Get client IP for tracking + // const clientIP = req.headers['x-forwarded-for'] || req.ip || req.connection.remoteAddress; + const clientIP = + req.headers['cf-connecting-ip'] || + req.headers['x-forwarded-for']?.split(',')[0] || + req.ip || + req.connection.remoteAddress; + + // Check if demo mode is active + if (DEFAULT_SSO_TOKEN) { + // For API endpoints, check rate limit in demo mode + if (demoModeRequestTracker.isLimited(clientIP)) { + const userRequests = demoModeRequestTracker.requests.get(clientIP); + const resetTimeMs = userRequests.resetTime - Date.now(); + + // Format time as HH:MM:SS + const hours = Math.floor(resetTimeMs / (60 * 60 * 1000)); + const minutes = Math.floor( + (resetTimeMs % (60 * 60 * 1000)) / (60 * 1000) + ); + const seconds = Math.floor((resetTimeMs % (60 * 1000)) / 1000); + const timeFormat = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; + + logger.warn(`Demo mode rate limit exceeded for IP: ${clientIP}`); + return res.status(429).json({ + status: 'error', + message: `Please try again in ${timeFormat} or use your own SSO token.`, + timestamp: global.Utils.toIsoString(new Date()), + }); + } + + // Increment the counter + // const count = demoModeRequestTracker.incrementCounter(clientIP); + // logger.debug(`Demo mode request count for ${clientIP}: ${count}`); + } + + next(); +}; + +function incrementDemoCounter(req, ssoToken) { + if (ssoToken === DEFAULT_SSO_TOKEN) { + const clientIP = + req.headers['cf-connecting-ip'] || + req.headers['x-forwarded-for']?.split(',')[0] || + req.ip || + req.connection.remoteAddress; + + const count = demoModeRequestTracker.incrementCounter(clientIP); + logger.debug(`Demo mode request count for ${clientIP}: ${count}`); + } +} + +app.use(demoModeMiddleware); +app.use((req, res, next) => { + if (req.query.demo === 'true' || req.query.demo === '1') { + // Enable demo mode for this session if it's not already enabled + if (!req.session) { + req.session = {}; + } + req.session.forceDemoMode = true; + logger.info('Demo mode enabled via URL parameter'); + } else if (req.query.demo === 'false' || req.query.demo === '0') { + // Disable demo mode for this session + if (req.session) { + req.session.forceDemoMode = false; + } + logger.info('Demo mode disabled via URL parameter'); + } + next(); +}); + // Initialize key replacements let keyReplacements = {}; @@ -224,15 +372,19 @@ app.post('/api/stats', async (req, res) => { ); try { - const { - username, - ssoToken, - platform, - game, - apiCall, - sanitize, - replaceKeys, - } = req.body; + let { username, ssoToken, platform, game, apiCall, sanitize, replaceKeys } = + req.body; + + if (!ssoToken && DEFAULT_SSO_TOKEN) { + ssoToken = DEFAULT_SSO_TOKEN; + logger.info('Using default SSO token for demo mode'); + } else if (!ssoToken && !DEFAULT_SSO_TOKEN) { + return res.status(200).json({ + status: 'error', + message: 'SSO Token is required as demo mode is not active', + timestamp: global.Utils.toIsoString(new Date()), + }); + } /* logger.debug( @@ -247,10 +399,6 @@ app.post('/api/stats', async (req, res) => { logger.debug(`Processing Options - Sanitize: ${sanitize}, Replace Keys: ${replaceKeys}`); logger.debug("====================="); */ - if (!ssoToken) { - return res.status(400).json({ error: 'SSO Token is required' }); - } - // For mapList, username is not required if (apiCall !== 'mapList' && !username) { return res.status(400).json({ error: 'Username is required' }); @@ -435,6 +583,8 @@ app.post('/api/stats', async (req, res) => { const { sanitize, replaceKeys } = req.body; + incrementDemoCounter(req, ssoToken); + return res.json({ // status: "success", data: processJsonOutput(data, { sanitize, replaceKeys }), @@ -475,7 +625,7 @@ app.post('/api/matches', async (req, res) => { ); try { - const { username, ssoToken, platform, game, sanitize, replaceKeys } = + let { username, ssoToken, platform, game, sanitize, replaceKeys } = req.body; /* @@ -490,10 +640,19 @@ app.post('/api/matches', async (req, res) => { logger.debug(`Processing Options - Sanitize: ${sanitize}, Replace Keys: ${replaceKeys}`); logger.debug("========================"); */ - if (!username || !ssoToken) { - return res - .status(400) - .json({ error: 'Username and SSO Token are required' }); + if (!username) { + return res.status(400).json({ error: 'Username is required' }); + } + + if (!ssoToken && DEFAULT_SSO_TOKEN) { + ssoToken = DEFAULT_SSO_TOKEN; + logger.info('Using default SSO token for demo mode'); + } else if (!ssoToken && !DEFAULT_SSO_TOKEN) { + return res.status(200).json({ + status: 'error', + message: 'SSO Token is required as demo mode is not active', + timestamp: global.Utils.toIsoString(new Date()), + }); } try { @@ -584,6 +743,8 @@ app.post('/api/matches', async (req, res) => { const { sanitize, replaceKeys } = req.body; + incrementDemoCounter(req, ssoToken); + return res.json({ // status: "success", data: processJsonOutput(data, { sanitize, replaceKeys }), @@ -621,9 +782,7 @@ app.post('/api/matchInfo', async (req, res) => { ); try { - const { matchId, ssoToken, platform, game, sanitize, replaceKeys } = - req.body; - const mode = 'mp'; + let { matchId, ssoToken, platform, game, sanitize, replaceKeys } = req.body; /* logger.debug( @@ -637,10 +796,19 @@ app.post('/api/matchInfo', async (req, res) => { logger.debug(`Processing Options - Sanitize: ${sanitize}, Replace Keys: ${replaceKeys}`); logger.debug("=========================="); */ - if (!matchId || !ssoToken) { - return res - .status(400) - .json({ error: 'Match ID and SSO Token are required' }); + if (!matchId) { + return res.status(400).json({ error: 'Match ID is required' }); + } + + if (!ssoToken && DEFAULT_SSO_TOKEN) { + ssoToken = DEFAULT_SSO_TOKEN; + logger.info('Using default SSO token for demo mode'); + } else if (!ssoToken && !DEFAULT_SSO_TOKEN) { + return res.status(200).json({ + status: 'error', + message: 'SSO Token is required as demo mode is not active', + timestamp: global.Utils.toIsoString(new Date()), + }); } try { @@ -717,6 +885,8 @@ app.post('/api/matchInfo', async (req, res) => { const { sanitize, replaceKeys } = req.body; + incrementDemoCounter(req, ssoToken); + return res.json({ // status: "success", data: processJsonOutput(data, { sanitize, replaceKeys }), @@ -754,7 +924,7 @@ app.post('/api/user', async (req, res) => { ); try { - const { username, ssoToken, platform, userCall, sanitize, replaceKeys } = + let { username, ssoToken, platform, userCall, sanitize, replaceKeys } = req.body; /* @@ -769,10 +939,6 @@ app.post('/api/user', async (req, res) => { logger.debug(`Processing Options - Sanitize: ${sanitize}, Replace Keys: ${replaceKeys}`); logger.debug("========================="); */ - if (!ssoToken) { - return res.status(400).json({ error: 'SSO Token is required' }); - } - // For eventFeed and identities, username is not required if ( !username && @@ -785,6 +951,17 @@ app.post('/api/user', async (req, res) => { .json({ error: 'Username is required for this API call' }); } + if (!ssoToken && DEFAULT_SSO_TOKEN) { + ssoToken = DEFAULT_SSO_TOKEN; + logger.info('Using default SSO token for demo mode'); + } else if (!ssoToken && !DEFAULT_SSO_TOKEN) { + return res.status(200).json({ + status: 'error', + message: 'SSO Token is required as demo mode is not active', + timestamp: global.Utils.toIsoString(new Date()), + }); + } + try { await ensureLogin(ssoToken); } catch (loginError) { @@ -850,6 +1027,8 @@ app.post('/api/user', async (req, res) => { const { sanitize, replaceKeys } = req.body; + incrementDemoCounter(req, ssoToken); + return res.json({ // status: "success", data: processJsonOutput(data, { sanitize, replaceKeys }), @@ -886,23 +1065,33 @@ app.post('/api/search', async (req, res) => { ); try { - const { username, ssoToken, platform, sanitize, replaceKeys } = req.body; + let { username, ssoToken, platform, sanitize, replaceKeys } = req.body; /* logger.debug( - `Request details - Username to search: ${username}, Platform: ${platform}` + `Request details - Match ID: ${matchId}, Platform: ${platform}, Game: ${game}` ); - logger.debug("=== SEARCH REQUEST ==="); - logger.debug(`Search Term: ${username}`); + logger.debug("=== MATCH INFO REQUEST ==="); + logger.debug(`Match ID: ${matchId}`); logger.debug(`Platform: ${platform}`); + logger.debug(`Game: ${game}`); logger.debug(`Processing Options - Sanitize: ${sanitize}, Replace Keys: ${replaceKeys}`); - logger.debug("======================"); */ + logger.debug("=========================="); */ - if (!username || !ssoToken) { - return res - .status(400) - .json({ error: 'Username and SSO Token are required' }); + if (!username) { + return res.status(400).json({ error: 'Username is required' }); + } + + if (!ssoToken && DEFAULT_SSO_TOKEN) { + ssoToken = DEFAULT_SSO_TOKEN; + logger.info('Using default SSO token for demo mode'); + } else if (!ssoToken && !DEFAULT_SSO_TOKEN) { + return res.status(200).json({ + status: 'error', + message: 'SSO Token is required as demo mode is not active', + timestamp: global.Utils.toIsoString(new Date()), + }); } try { @@ -935,6 +1124,8 @@ app.post('/api/search', async (req, res) => { const { sanitize, replaceKeys } = req.body; + incrementDemoCounter(req, ssoToken); + return res.json({ // status: "success", data: processJsonOutput(data, { sanitize, replaceKeys }), @@ -957,7 +1148,10 @@ app.post('/api/search', async (req, res) => { // Improved logging endpoint app.post('/api/log', (req, res) => { const clientIP = - req.headers['x-forwarded-for'] || req.ip || req.connection.remoteAddress; + req.headers['cf-connecting-ip'] || + req.headers['x-forwarded-for']?.split(',')[0] || + req.ip || + req.connection.remoteAddress; const userAgent = req.headers['user-agent']; const referer = req.headers['referer']; const origin = req.headers['origin']; @@ -1028,9 +1222,32 @@ function storeLogInDatabase(logData) { } */ -// Basic health check endpoint app.get('/health', (req, res) => { - res.json({ status: 'ok', timestamp: global.Utils.toIsoString(new Date()) }); + // Check if demo mode is forced via URL parameter + const forceDemoMode = req.session && req.session.forceDemoMode === true; + + const isDemoMode = !!DEFAULT_SSO_TOKEN || forceDemoMode; + res.json({ + status: 'ok', + timestamp: global.Utils.toIsoString(new Date()), + demoMode: isDemoMode, + requestsRemaining: + isDemoMode ? + demoModeRequestTracker.maxRequestsPerHour - + (demoModeRequestTracker.requests.get(req.ip)?.count || 0) + : null, + }); +}); + +app.get('/demo', (req, res) => { + // Set a cookie or session variable to enable demo mode + if (!req.session) { + req.session = {}; + } + req.session.forceDemoMode = true; + + // Redirect to the main app + res.redirect('/'); }); // Serve the main HTML file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index e9c8eb3..db58e60 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -62,6 +62,15 @@ "node": ">=6.9.0" } }, + "node_modules/@fastify/busboy": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", + "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -508,6 +517,33 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/call-of-duty-api": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/call-of-duty-api/-/call-of-duty-api-4.1.0.tgz", + "integrity": "sha512-f5DJ6gQru6f406QVBZkkXOv0gUzFu0hykdkyKRa2Am6iWwGRVzcBK7rq+xHpNI6oTq3EFfw0T70kb38rZaezNA==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0", + "undici": "^5.12.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Lierrmm" + } + }, + "node_modules/call-of-duty-api/node_modules/undici": { + "version": "5.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.29.0.tgz", + "integrity": "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==", + "license": "MIT", + "dependencies": { + "@fastify/busboy": "^2.0.0" + }, + "engines": { + "node": ">=14.0" + } + }, "node_modules/camel-case": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/camel-case/-/camel-case-3.0.0.tgz", @@ -987,6 +1023,55 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-rate-limit": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.0.tgz", + "integrity": "sha512-eB5zbQh5h+VenMPM3fh+nw1YExi5nMr6HUCR62ELSP11huvxm/Uir1H1QEyTkk5QX6A58pX6NmaTMceKZ0Eodg==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": "^4.11 || 5 || ^5.0.0-beta.1" + } + }, + "node_modules/express-session": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.18.1.tgz", + "integrity": "sha512-a5mtTqEaZvBCL9A9aqkrtfz+3SMDhOVUnjafjo+s7A9Txkq+SVX2DLvSp1Zrv4uCXa3lMSK3viWnh9Gg07PBUA==", + "license": "MIT", + "dependencies": { + "cookie": "0.7.2", + "cookie-signature": "1.0.7", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.0.2", + "parseurl": "~1.3.3", + "safe-buffer": "5.2.1", + "uid-safe": "~2.1.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/express-session/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express-session/node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, "node_modules/express/node_modules/body-parser": { "version": "1.20.3", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", @@ -1869,6 +1954,15 @@ "node": ">= 0.8" } }, + "node_modules/on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -2045,6 +2139,21 @@ "node": ">=10" } }, + "node_modules/prettier": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.3.tgz", + "integrity": "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==", + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", @@ -2116,6 +2225,15 @@ ], "license": "MIT" }, + "node_modules/random-bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", + "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", @@ -2849,6 +2967,18 @@ "node": ">=0.8.0" } }, + "node_modules/uid-safe": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", + "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", + "license": "MIT", + "dependencies": { + "random-bytes": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/undici": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/undici/-/undici-7.6.0.tgz", diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js b/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js new file mode 100644 index 0000000..3c8c081 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js @@ -0,0 +1,213 @@ +'use strict' + +const WritableStream = require('node:stream').Writable +const inherits = require('node:util').inherits + +const StreamSearch = require('../../streamsearch/sbmh') + +const PartStream = require('./PartStream') +const HeaderParser = require('./HeaderParser') + +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} + +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } + + this._headerFirst = cfg.headerFirst + + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false + + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) +} +inherits(Dicer, WritableStream) + +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return + } + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + } + } else { WritableStream.prototype.emit.apply(this, arguments) } +} + +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } + + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } + } + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } + + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } + + this._bparser.push(data) + + if (this._pause) { this._cb = cb } else { cb() } +} + +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} + +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) +} + +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() + } +} + +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true + + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes + } else { + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break + } + } + if (this._dashes === 2) { + if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } + } + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() + } + if (this._isPreamble && this.listenerCount('preamble') !== 0) { + this.emit('preamble', this._part) + } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { + this.emit('part', this._part) + } else { + this._ignore() + } + if (!this._isPreamble) { this._inHeader = true } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } + } + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() + } + } + }) + } + } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } +} + +Dicer.prototype._unpause = function () { + if (!this._pause) { return } + + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} + +module.exports = Dicer diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js b/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js new file mode 100644 index 0000000..65f667b --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js @@ -0,0 +1,100 @@ +'use strict' + +const EventEmitter = require('node:events').EventEmitter +const inherits = require('node:util').inherits +const getLimit = require('../../../lib/utils/getLimit') + +const StreamSearch = require('../../streamsearch/sbmh') + +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex + +function HeaderParser (cfg) { + EventEmitter.call(this) + + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } + + self.buffer += data.toString('binary', start, end) + } + if (isMatch) { self._finish() } + }) +} +inherits(HeaderParser, EventEmitter) + +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } +} + +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() +} + +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) +} + +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } + + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue + } + } + + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return + } + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } + } +} + +module.exports = HeaderParser diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js b/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js new file mode 100644 index 0000000..c91da1c --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js @@ -0,0 +1,13 @@ +'use strict' + +const inherits = require('node:util').inherits +const ReadableStream = require('node:stream').Readable + +function PartStream (opts) { + ReadableStream.call(this, opts) +} +inherits(PartStream, ReadableStream) + +PartStream.prototype._read = function (n) {} + +module.exports = PartStream diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts b/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts new file mode 100644 index 0000000..3c5b896 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts @@ -0,0 +1,164 @@ +// Type definitions for dicer 0.2 +// Project: https://github.com/mscdex/dicer +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +/// + +import stream = require("stream"); + +// tslint:disable:unified-signatures + +/** + * A very fast streaming multipart parser for node.js. + * Dicer is a WritableStream + * + * Dicer (special) events: + * - on('finish', ()) - Emitted when all parts have been parsed and the Dicer instance has been ended. + * - on('part', (stream: PartStream)) - Emitted when a new part has been found. + * - on('preamble', (stream: PartStream)) - Emitted for preamble if you should happen to need it (can usually be ignored). + * - on('trailer', (data: Buffer)) - Emitted when trailing data was found after the terminating boundary (as with the preamble, this can usually be ignored too). + */ +export class Dicer extends stream.Writable { + /** + * Creates and returns a new Dicer instance with the following valid config settings: + * + * @param config The configuration to use + */ + constructor(config: Dicer.Config); + /** + * Sets the boundary to use for parsing and performs some initialization needed for parsing. + * You should only need to use this if you set headerFirst to true in the constructor and are parsing the boundary from the preamble header. + * + * @param boundary The boundary to use + */ + setBoundary(boundary: string): void; + addListener(event: "finish", listener: () => void): this; + addListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "trailer", listener: (data: Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "part", listener: (stream: Dicer.PartStream) => void): this; + on(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + on(event: "trailer", listener: (data: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "part", listener: (stream: Dicer.PartStream) => void): this; + once(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + once(event: "trailer", listener: (data: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "trailer", listener: (data: Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "trailer", listener: (data: Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "trailer", listener: (data: Buffer) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pipe", listener: (src: stream.Readable) => void): this; + removeListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; +} + +declare namespace Dicer { + interface Config { + /** + * This is the boundary used to detect the beginning of a new part. + */ + boundary?: string | undefined; + /** + * If true, preamble header parsing will be performed first. + */ + headerFirst?: boolean | undefined; + /** + * The maximum number of header key=>value pairs to parse Default: 2000 (same as node's http). + */ + maxHeaderPairs?: number | undefined; + } + + /** + * PartStream is a _ReadableStream_ + * + * PartStream (special) events: + * - on('header', (header: object)) - An object containing the header for this particular part. Each property value is an array of one or more string values. + */ + interface PartStream extends stream.Readable { + addListener(event: "header", listener: (header: object) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "header", listener: (header: object) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "header", listener: (header: object) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "header", listener: (header: object) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "header", listener: (header: object) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "header", listener: (header: object) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + } +} \ No newline at end of file diff --git a/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js b/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js new file mode 100644 index 0000000..b90c0e8 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js @@ -0,0 +1,228 @@ +'use strict' + +/** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ +const EventEmitter = require('node:events').EventEmitter +const inherits = require('node:util').inherits + +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } + + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } + + const needleLength = needle.length + + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } + + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + + this.maxMatches = Infinity + this.matches = 0 + + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 + + this._lookbehind = Buffer.alloc(needleLength) + + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i + } +} +inherits(SBMH, EventEmitter) + +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} + +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') + } + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r +} + +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1) + + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) + + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch] + } + + // No match. + + if (pos < 0) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + } + + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } + + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff + + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len + + this._bufpos = len + return len + } + } + + pos += (pos >= 0) * this._bufpos + + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos) + ++this.matches + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } + + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos < len && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos + } + + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } + + this._bufpos = len + return len +} + +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} + +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true +} + +module.exports = SBMH diff --git a/node_modules/@fastify/busboy/lib/main.d.ts b/node_modules/@fastify/busboy/lib/main.d.ts new file mode 100644 index 0000000..91b6448 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/main.d.ts @@ -0,0 +1,196 @@ +// Definitions by: Jacob Baskin +// BendingBender +// Igor Savin + +/// + +import * as http from 'http'; +import { Readable, Writable } from 'stream'; +export { Dicer } from "../deps/dicer/lib/dicer"; + +export const Busboy: BusboyConstructor; +export default Busboy; + +export interface BusboyConfig { + /** + * These are the HTTP headers of the incoming request, which are used by individual parsers. + */ + headers: BusboyHeaders; + /** + * `highWaterMark` to use for this Busboy instance. + * @default WritableStream default. + */ + highWaterMark?: number | undefined; + /** + * highWaterMark to use for file streams. + * @default ReadableStream default. + */ + fileHwm?: number | undefined; + /** + * Default character set to use when one isn't defined. + * @default 'utf8' + */ + defCharset?: string | undefined; + /** + * Detect if a Part is a file. + * + * By default a file is detected if contentType + * is application/octet-stream or fileName is not + * undefined. + * + * Modify this to handle e.g. Blobs. + */ + isPartAFile?: (fieldName: string | undefined, contentType: string | undefined, fileName: string | undefined) => boolean; + /** + * If paths in the multipart 'filename' field shall be preserved. + * @default false + */ + preservePath?: boolean | undefined; + /** + * Various limits on incoming data. + */ + limits?: + | { + /** + * Max field name size (in bytes) + * @default 100 bytes + */ + fieldNameSize?: number | undefined; + /** + * Max field value size (in bytes) + * @default 1MB + */ + fieldSize?: number | undefined; + /** + * Max number of non-file fields + * @default Infinity + */ + fields?: number | undefined; + /** + * For multipart forms, the max file size (in bytes) + * @default Infinity + */ + fileSize?: number | undefined; + /** + * For multipart forms, the max number of file fields + * @default Infinity + */ + files?: number | undefined; + /** + * For multipart forms, the max number of parts (fields + files) + * @default Infinity + */ + parts?: number | undefined; + /** + * For multipart forms, the max number of header key=>value pairs to parse + * @default 2000 + */ + headerPairs?: number | undefined; + + /** + * For multipart forms, the max size of a header part + * @default 81920 + */ + headerSize?: number | undefined; + } + | undefined; +} + +export type BusboyHeaders = { 'content-type': string } & http.IncomingHttpHeaders; + +export interface BusboyFileStream extends + Readable { + + truncated: boolean; + + /** + * The number of bytes that have been read so far. + */ + bytesRead: number; +} + +export interface Busboy extends Writable { + addListener(event: Event, listener: BusboyEvents[Event]): this; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + on(event: Event, listener: BusboyEvents[Event]): this; + + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: Event, listener: BusboyEvents[Event]): this; + + once(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: Event, listener: BusboyEvents[Event]): this; + + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: Event, listener: BusboyEvents[Event]): this; + + off(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: Event, listener: BusboyEvents[Event]): this; + + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: Event, listener: BusboyEvents[Event]): this; + + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; +} + +export interface BusboyEvents { + /** + * Emitted for each new file form field found. + * + * * Note: if you listen for this event, you should always handle the `stream` no matter if you care about the + * file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents), + * otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any** + * incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically + * and safely discarded (these discarded files do still count towards `files` and `parts` limits). + * * If a configured file size limit was reached, `stream` will both have a boolean property `truncated` + * (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens. + * + * @param listener.transferEncoding Contains the 'Content-Transfer-Encoding' value for the file stream. + * @param listener.mimeType Contains the 'Content-Type' value for the file stream. + */ + file: ( + fieldname: string, + stream: BusboyFileStream, + filename: string, + transferEncoding: string, + mimeType: string, + ) => void; + /** + * Emitted for each new non-file field found. + */ + field: ( + fieldname: string, + value: string, + fieldnameTruncated: boolean, + valueTruncated: boolean, + transferEncoding: string, + mimeType: string, + ) => void; + finish: () => void; + /** + * Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted. + */ + partsLimit: () => void; + /** + * Emitted when specified `files` limit has been reached. No more 'file' events will be emitted. + */ + filesLimit: () => void; + /** + * Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted. + */ + fieldsLimit: () => void; + error: (error: unknown) => void; +} + +export interface BusboyConstructor { + (options: BusboyConfig): Busboy; + + new(options: BusboyConfig): Busboy; +} + diff --git a/node_modules/@fastify/busboy/lib/main.js b/node_modules/@fastify/busboy/lib/main.js new file mode 100644 index 0000000..8794beb --- /dev/null +++ b/node_modules/@fastify/busboy/lib/main.js @@ -0,0 +1,85 @@ +'use strict' + +const WritableStream = require('node:stream').Writable +const { inherits } = require('node:util') +const Dicer = require('../deps/dicer/lib/Dicer') + +const MultipartParser = require('./types/multipart') +const UrlencodedParser = require('./types/urlencoded') +const parseParams = require('./utils/parseParams') + +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } + + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } + + const { + headers, + ...streamOptions + } = opts + + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) + + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) + +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return + } + this._finished = true + } + WritableStream.prototype.emit.apply(this, arguments) +} + +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) + + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + } + + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') +} + +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} + +module.exports = Busboy +module.exports.default = Busboy +module.exports.Busboy = Busboy + +module.exports.Dicer = Dicer diff --git a/node_modules/@fastify/busboy/lib/types/multipart.js b/node_modules/@fastify/busboy/lib/types/multipart.js new file mode 100644 index 0000000..d691eca --- /dev/null +++ b/node_modules/@fastify/busboy/lib/types/multipart.js @@ -0,0 +1,306 @@ +'use strict' + +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams + +const { Readable } = require('node:stream') +const { inherits } = require('node:util') + +const Dicer = require('../../deps/dicer/lib/Dicer') + +const parseParams = require('../utils/parseParams') +const decodeText = require('../utils/decodeText') +const basename = require('../utils/basename') +const getLimit = require('../utils/getLimit') + +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i + +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } + + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break + } + } + + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) + + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false + + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } + + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) + } + + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') + } + + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 + + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } + } + } + + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } + + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } + } + } else { return skipPart(part) } + + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } + + let onData, + onEnd + + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } + + ++nfiles + + if (boy.listenerCount('file') === 0) { + self.parser._ignore() + return + } + + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + } + boy.emit('file', fieldname, file, filename, encoding, contype) + + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } + + file.bytesRead = nsize + } + + onEnd = function () { + curFile = undefined + file.push(null) + } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) + } + + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part + + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } + } + + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() + } + } + + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false + + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} + +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb + } +} + +Multipart.prototype.end = function () { + const self = this + + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } +} + +function skipPart (part) { + part.resume() +} + +function FileStream (opts) { + Readable.call(this, opts) + + this.bytesRead = 0 + + this.truncated = false +} + +inherits(FileStream, Readable) + +FileStream.prototype._read = function (n) {} + +module.exports = Multipart diff --git a/node_modules/@fastify/busboy/lib/types/urlencoded.js b/node_modules/@fastify/busboy/lib/types/urlencoded.js new file mode 100644 index 0000000..6f5f784 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/types/urlencoded.js @@ -0,0 +1,190 @@ +'use strict' + +const Decoder = require('../utils/Decoder') +const decodeText = require('../utils/decodeText') +const getLimit = require('../utils/getLimit') + +const RE_CHARSET = /^charset$/i + +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy + + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) + + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break + } + } + + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } + + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false +} + +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') + } + return cb() + } + + let idxeq; let idxamp; let i; let p = 0; const len = data.length + + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' + + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() + + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) + } + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true + } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len + } + } else { + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } + } + + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len + } + } + } + cb() +} + +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } + + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + } + this.boy._done = true + this.boy.emit('finish') +} + +module.exports = UrlEncoded diff --git a/node_modules/@fastify/busboy/lib/utils/Decoder.js b/node_modules/@fastify/busboy/lib/utils/Decoder.js new file mode 100644 index 0000000..7917678 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/Decoder.js @@ -0,0 +1,54 @@ +'use strict' + +const RE_PLUS = /\+/g + +const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +] + +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined + } + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p + } + } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res +} +Decoder.prototype.reset = function () { + this.buffer = undefined +} + +module.exports = Decoder diff --git a/node_modules/@fastify/busboy/lib/utils/basename.js b/node_modules/@fastify/busboy/lib/utils/basename.js new file mode 100644 index 0000000..db58819 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/basename.js @@ -0,0 +1,14 @@ +'use strict' + +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) + } + } + return (path === '..' || path === '.' ? '' : path) +} diff --git a/node_modules/@fastify/busboy/lib/utils/decodeText.js b/node_modules/@fastify/busboy/lib/utils/decodeText.js new file mode 100644 index 0000000..eac7d35 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/decodeText.js @@ -0,0 +1,114 @@ +'use strict' + +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) + +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue + } + return decoders.other.bind(charset) + } + } +} + +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.utf8Slice(0, data.length) + }, + + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + return data + } + return data.latin1Slice(0, data.length) + }, + + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.ucs2Slice(0, data.length) + }, + + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.base64Slice(0, data.length) + }, + + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} + } + return typeof data === 'string' + ? data + : data.toString() + } +} + +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) + } + return text +} + +module.exports = decodeText diff --git a/node_modules/@fastify/busboy/lib/utils/getLimit.js b/node_modules/@fastify/busboy/lib/utils/getLimit.js new file mode 100644 index 0000000..cb64fd6 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/getLimit.js @@ -0,0 +1,16 @@ +'use strict' + +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] +} diff --git a/node_modules/@fastify/busboy/lib/utils/parseParams.js b/node_modules/@fastify/busboy/lib/utils/parseParams.js new file mode 100644 index 0000000..1698e62 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/parseParams.js @@ -0,0 +1,196 @@ +/* eslint-disable object-property-newline */ +'use strict' + +const decodeText = require('./decodeText') + +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g + +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} + +function encodedReplacer (match) { + return EncodedLookup[match] +} + +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 + +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } + } + tmp += char + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } + + return res +} + +module.exports = parseParams diff --git a/node_modules/@fastify/busboy/package.json b/node_modules/@fastify/busboy/package.json new file mode 100644 index 0000000..83693ac --- /dev/null +++ b/node_modules/@fastify/busboy/package.json @@ -0,0 +1,86 @@ +{ + "name": "@fastify/busboy", + "version": "2.1.1", + "private": false, + "author": "Brian White ", + "contributors": [ + { + "name": "Igor Savin", + "email": "kibertoad@gmail.com", + "url": "https://github.com/kibertoad" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com", + "url": "https://github.com/uzlopak" + } + ], + "description": "A streaming parser for HTML form data for node.js", + "main": "lib/main", + "type": "commonjs", + "types": "lib/main.d.ts", + "scripts": { + "bench:busboy": "cd benchmarks && npm install && npm run benchmark-fastify", + "bench:dicer": "node bench/dicer/dicer-bench-multipart-parser.js", + "coveralls": "nyc report --reporter=lcov", + "lint": "npm run lint:standard", + "lint:everything": "npm run lint && npm run test:types", + "lint:fix": "standard --fix", + "lint:standard": "standard --verbose | snazzy", + "test:mocha": "tap", + "test:types": "tsd", + "test:coverage": "nyc npm run test", + "test": "npm run test:mocha" + }, + "engines": { + "node": ">=14" + }, + "devDependencies": { + "@types/node": "^20.1.0", + "busboy": "^1.0.0", + "photofinish": "^1.8.0", + "snazzy": "^9.0.0", + "standard": "^17.0.0", + "tap": "^16.3.8", + "tinybench": "^2.5.1", + "tsd": "^0.30.0", + "typescript": "^5.0.2" + }, + "keywords": [ + "uploads", + "forms", + "multipart", + "form-data" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/busboy.git" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "esModuleInterop": false, + "module": "commonjs", + "target": "ES2017" + } + }, + "standard": { + "globals": [ + "describe", + "it" + ], + "ignore": [ + "bench" + ] + }, + "files": [ + "README.md", + "LICENSE", + "lib/*", + "deps/encoding/*", + "deps/dicer/lib", + "deps/streamsearch/", + "deps/dicer/LICENSE" + ] +} diff --git a/node_modules/express-rate-limit/dist/index.cjs b/node_modules/express-rate-limit/dist/index.cjs new file mode 100644 index 0000000..36d5e1b --- /dev/null +++ b/node_modules/express-rate-limit/dist/index.cjs @@ -0,0 +1,838 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// source/index.ts +var source_exports = {}; +__export(source_exports, { + MemoryStore: () => MemoryStore, + default: () => lib_default, + rateLimit: () => lib_default +}); +module.exports = __toCommonJS(source_exports); + +// source/headers.ts +var import_node_buffer = require("buffer"); +var import_node_crypto = require("crypto"); +var SUPPORTED_DRAFT_VERSIONS = ["draft-6", "draft-7", "draft-8"]; +var getResetSeconds = (resetTime, windowMs) => { + let resetSeconds = void 0; + if (resetTime) { + const deltaSeconds = Math.ceil((resetTime.getTime() - Date.now()) / 1e3); + resetSeconds = Math.max(0, deltaSeconds); + } else if (windowMs) { + resetSeconds = Math.ceil(windowMs / 1e3); + } + return resetSeconds; +}; +var getPartitionKey = (key) => { + const hash = (0, import_node_crypto.createHash)("sha256"); + hash.update(key); + const partitionKey = hash.digest("hex").slice(0, 12); + return import_node_buffer.Buffer.from(partitionKey).toString("base64"); +}; +var setLegacyHeaders = (response, info) => { + if (response.headersSent) + return; + response.setHeader("X-RateLimit-Limit", info.limit.toString()); + response.setHeader("X-RateLimit-Remaining", info.remaining.toString()); + if (info.resetTime instanceof Date) { + response.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString()); + response.setHeader( + "X-RateLimit-Reset", + Math.ceil(info.resetTime.getTime() / 1e3).toString() + ); + } +}; +var setDraft6Headers = (response, info, windowMs) => { + if (response.headersSent) + return; + const windowSeconds = Math.ceil(windowMs / 1e3); + const resetSeconds = getResetSeconds(info.resetTime); + response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`); + response.setHeader("RateLimit-Limit", info.limit.toString()); + response.setHeader("RateLimit-Remaining", info.remaining.toString()); + if (resetSeconds) + response.setHeader("RateLimit-Reset", resetSeconds.toString()); +}; +var setDraft7Headers = (response, info, windowMs) => { + if (response.headersSent) + return; + const windowSeconds = Math.ceil(windowMs / 1e3); + const resetSeconds = getResetSeconds(info.resetTime, windowMs); + response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`); + response.setHeader( + "RateLimit", + `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}` + ); +}; +var setDraft8Headers = (response, info, windowMs, name, key) => { + if (response.headersSent) + return; + const windowSeconds = Math.ceil(windowMs / 1e3); + const resetSeconds = getResetSeconds(info.resetTime, windowMs); + const partitionKey = getPartitionKey(key); + const policy = `q=${info.limit}; w=${windowSeconds}; pk=:${partitionKey}:`; + const header = `r=${info.remaining}; t=${resetSeconds}`; + response.append("RateLimit-Policy", `"${name}"; ${policy}`); + response.append("RateLimit", `"${name}"; ${header}`); +}; +var setRetryAfterHeader = (response, info, windowMs) => { + if (response.headersSent) + return; + const resetSeconds = getResetSeconds(info.resetTime, windowMs); + response.setHeader("Retry-After", resetSeconds.toString()); +}; + +// source/validations.ts +var import_node_net = require("net"); +var ValidationError = class extends Error { + /** + * The code must be a string, in snake case and all capital, that starts with + * the substring `ERR_ERL_`. + * + * The message must be a string, starting with an uppercase character, + * describing the issue in detail. + */ + constructor(code, message) { + const url = `https://express-rate-limit.github.io/${code}/`; + super(`${message} See ${url} for more information.`); + this.name = this.constructor.name; + this.code = code; + this.help = url; + } +}; +var ChangeWarning = class extends ValidationError { +}; +var usedStores = /* @__PURE__ */ new Set(); +var singleCountKeys = /* @__PURE__ */ new WeakMap(); +var validations = { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + enabled: { + default: true + }, + // Should be EnabledValidations type, but that's a circular reference + disable() { + for (const k of Object.keys(this.enabled)) + this.enabled[k] = false; + }, + /** + * Checks whether the IP address is valid, and that it does not have a port + * number in it. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address. + * + * @param ip {string | undefined} - The IP address provided by Express as request.ip. + * + * @returns {void} + */ + ip(ip) { + if (ip === void 0) { + throw new ValidationError( + "ERR_ERL_UNDEFINED_IP_ADDRESS", + `An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.` + ); + } + if (!(0, import_node_net.isIP)(ip)) { + throw new ValidationError( + "ERR_ERL_INVALID_IP_ADDRESS", + `An invalid 'request.ip' (${ip}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.` + ); + } + }, + /** + * Makes sure the trust proxy setting is not set to `true`. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + trustProxy(request) { + if (request.app.get("trust proxy") === true) { + throw new ValidationError( + "ERR_ERL_PERMISSIVE_TRUST_PROXY", + `The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.` + ); + } + }, + /** + * Makes sure the trust proxy setting is set in case the `X-Forwarded-For` + * header is present. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + xForwardedForHeader(request) { + if (request.headers["x-forwarded-for"] && request.app.get("trust proxy") === false) { + throw new ValidationError( + "ERR_ERL_UNEXPECTED_X_FORWARDED_FOR", + `The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.` + ); + } + }, + /** + * Ensures totalHits value from store is a positive integer. + * + * @param hits {any} - The `totalHits` returned by the store. + */ + positiveHits(hits) { + if (typeof hits !== "number" || hits < 1 || hits !== Math.round(hits)) { + throw new ValidationError( + "ERR_ERL_INVALID_HITS", + `The totalHits value returned from the store must be a positive integer, got ${hits}` + ); + } + }, + /** + * Ensures a single store instance is not used with multiple express-rate-limit instances + */ + unsharedStore(store) { + if (usedStores.has(store)) { + const maybeUniquePrefix = store?.localKeys ? "" : " (with a unique prefix)"; + throw new ValidationError( + "ERR_ERL_STORE_REUSE", + `A Store instance must not be shared across multiple rate limiters. Create a new instance of ${store.constructor.name}${maybeUniquePrefix} for each limiter instead.` + ); + } + usedStores.add(store); + }, + /** + * Ensures a given key is incremented only once per request. + * + * @param request {Request} - The Express request object. + * @param store {Store} - The store class. + * @param key {string} - The key used to store the client's hit count. + * + * @returns {void} + */ + singleCount(request, store, key) { + let storeKeys = singleCountKeys.get(request); + if (!storeKeys) { + storeKeys = /* @__PURE__ */ new Map(); + singleCountKeys.set(request, storeKeys); + } + const storeKey = store.localKeys ? store : store.constructor.name; + let keys = storeKeys.get(storeKey); + if (!keys) { + keys = []; + storeKeys.set(storeKey, keys); + } + const prefixedKey = `${store.prefix ?? ""}${key}`; + if (keys.includes(prefixedKey)) { + throw new ValidationError( + "ERR_ERL_DOUBLE_COUNT", + `The hit count for ${key} was incremented more than once for a single request.` + ); + } + keys.push(prefixedKey); + }, + /** + * Warns the user that the behaviour for `max: 0` / `limit: 0` is + * changing in the next major release. + * + * @param limit {number} - The maximum number of hits per client. + * + * @returns {void} + */ + limit(limit) { + if (limit === 0) { + throw new ChangeWarning( + "WRN_ERL_MAX_ZERO", + `Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7` + ); + } + }, + /** + * Warns the user that the `draft_polli_ratelimit_headers` option is deprecated + * and will be removed in the next major release. + * + * @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers. + * + * @returns {void} + */ + draftPolliHeaders(draft_polli_ratelimit_headers) { + if (draft_polli_ratelimit_headers) { + throw new ChangeWarning( + "WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS", + `The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.` + ); + } + }, + /** + * Warns the user that the `onLimitReached` option is deprecated and + * will be removed in the next major release. + * + * @param onLimitReached {any | undefined} - The maximum number of hits per client. + * + * @returns {void} + */ + onLimitReached(onLimitReached) { + if (onLimitReached) { + throw new ChangeWarning( + "WRN_ERL_DEPRECATED_ON_LIMIT_REACHED", + `The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7.` + ); + } + }, + /** + * Warns the user when an invalid/unsupported version of the draft spec is passed. + * + * @param version {any | undefined} - The version passed by the user. + * + * @returns {void} + */ + headersDraftVersion(version) { + if (typeof version !== "string" || !SUPPORTED_DRAFT_VERSIONS.includes(version)) { + const versionString = SUPPORTED_DRAFT_VERSIONS.join(", "); + throw new ValidationError( + "ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION", + `standardHeaders: only the following versions of the IETF draft specification are supported: ${versionString}.` + ); + } + }, + /** + * Warns the user when the selected headers option requires a reset time but + * the store does not provide one. + * + * @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset. + * + * @returns {void} + */ + headersResetTime(resetTime) { + if (!resetTime) { + throw new ValidationError( + "ERR_ERL_HEADERS_NO_RESET", + `standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.` + ); + } + }, + /** + * Checks the options.validate setting to ensure that only recognized + * validations are enabled or disabled. + * + * If any unrecognized values are found, an error is logged that + * includes the list of supported vaidations. + */ + validationsConfig() { + const supportedValidations = Object.keys(this).filter( + (k) => !["enabled", "disable"].includes(k) + ); + supportedValidations.push("default"); + for (const key of Object.keys(this.enabled)) { + if (!supportedValidations.includes(key)) { + throw new ValidationError( + "ERR_ERL_UNKNOWN_VALIDATION", + `options.validate.${key} is not recognized. Supported validate options are: ${supportedValidations.join( + ", " + )}.` + ); + } + } + }, + /** + * Checks to see if the instance was created inside of a request handler, + * which would prevent it from working correctly, with the default memory + * store (or any other store with localKeys.) + */ + creationStack(store) { + const { stack } = new Error( + "express-rate-limit validation check (set options.validate.creationStack=false to disable)" + ); + if (stack?.includes("Layer.handle [as handle_request]")) { + if (!store.localKeys) { + throw new ValidationError( + "ERR_ERL_CREATED_IN_REQUEST_HANDLER", + "express-rate-limit instance should *usually* be created at app initialization, not when responding to a request." + ); + } + throw new ValidationError( + "ERR_ERL_CREATED_IN_REQUEST_HANDLER", + `express-rate-limit instance should be created at app initialization, not when responding to a request.` + ); + } + } +}; +var getValidations = (_enabled) => { + let enabled; + if (typeof _enabled === "boolean") { + enabled = { + default: _enabled + }; + } else { + enabled = { + default: true, + ..._enabled + }; + } + const wrappedValidations = { + enabled + }; + for (const [name, validation] of Object.entries(validations)) { + if (typeof validation === "function") + wrappedValidations[name] = (...args) => { + if (!(enabled[name] ?? enabled.default)) { + return; + } + try { + ; + validation.apply( + wrappedValidations, + args + ); + } catch (error) { + if (error instanceof ChangeWarning) + console.warn(error); + else + console.error(error); + } + }; + } + return wrappedValidations; +}; + +// source/memory-store.ts +var MemoryStore = class { + constructor() { + /** + * These two maps store usage (requests) and reset time by key (for example, IP + * addresses or API keys). + * + * They are split into two to avoid having to iterate through the entire set to + * determine which ones need reset. Instead, `Client`s are moved from `previous` + * to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients + * left in `previous`, i.e., those that have not made any recent requests, are + * known to be expired and can be deleted in bulk. + */ + this.previous = /* @__PURE__ */ new Map(); + this.current = /* @__PURE__ */ new Map(); + /** + * Confirmation that the keys incremented in once instance of MemoryStore + * cannot affect other instances. + */ + this.localKeys = true; + } + /** + * Method that initializes the store. + * + * @param options {Options} - The options used to setup the middleware. + */ + init(options) { + this.windowMs = options.windowMs; + if (this.interval) + clearInterval(this.interval); + this.interval = setInterval(() => { + this.clearExpired(); + }, this.windowMs); + if (this.interval.unref) + this.interval.unref(); + } + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client. + * + * @public + */ + async get(key) { + return this.current.get(key) ?? this.previous.get(key); + } + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + * + * @public + */ + async increment(key) { + const client = this.getClient(key); + const now = Date.now(); + if (client.resetTime.getTime() <= now) { + this.resetClient(client, now); + } + client.totalHits++; + return client; + } + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + async decrement(key) { + const client = this.getClient(key); + if (client.totalHits > 0) + client.totalHits--; + } + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + async resetKey(key) { + this.current.delete(key); + this.previous.delete(key); + } + /** + * Method to reset everyone's hit counter. + * + * @public + */ + async resetAll() { + this.current.clear(); + this.previous.clear(); + } + /** + * Method to stop the timer (if currently running) and prevent any memory + * leaks. + * + * @public + */ + shutdown() { + clearInterval(this.interval); + void this.resetAll(); + } + /** + * Recycles a client by setting its hit count to zero, and reset time to + * `windowMs` milliseconds from now. + * + * NOT to be confused with `#resetKey()`, which removes a client from both the + * `current` and `previous` maps. + * + * @param client {Client} - The client to recycle. + * @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client. + * + * @return {Client} - The modified client that was passed in, to allow for chaining. + */ + resetClient(client, now = Date.now()) { + client.totalHits = 0; + client.resetTime.setTime(now + this.windowMs); + return client; + } + /** + * Retrieves or creates a client, given a key. Also ensures that the client being + * returned is in the `current` map. + * + * @param key {string} - The key under which the client is (or is to be) stored. + * + * @returns {Client} - The requested client. + */ + getClient(key) { + if (this.current.has(key)) + return this.current.get(key); + let client; + if (this.previous.has(key)) { + client = this.previous.get(key); + this.previous.delete(key); + } else { + client = { totalHits: 0, resetTime: /* @__PURE__ */ new Date() }; + this.resetClient(client); + } + this.current.set(key, client); + return client; + } + /** + * Move current clients to previous, create a new map for current. + * + * This function is called every `windowMs`. + */ + clearExpired() { + this.previous = this.current; + this.current = /* @__PURE__ */ new Map(); + } +}; + +// source/lib.ts +var isLegacyStore = (store) => ( + // Check that `incr` exists but `increment` does not - store authors might want + // to keep both around for backwards compatibility. + typeof store.incr === "function" && typeof store.increment !== "function" +); +var promisifyStore = (passedStore) => { + if (!isLegacyStore(passedStore)) { + return passedStore; + } + const legacyStore = passedStore; + class PromisifiedStore { + async increment(key) { + return new Promise((resolve, reject) => { + legacyStore.incr( + key, + (error, totalHits, resetTime) => { + if (error) + reject(error); + resolve({ totalHits, resetTime }); + } + ); + }); + } + async decrement(key) { + return legacyStore.decrement(key); + } + async resetKey(key) { + return legacyStore.resetKey(key); + } + /* istanbul ignore next */ + async resetAll() { + if (typeof legacyStore.resetAll === "function") + return legacyStore.resetAll(); + } + } + return new PromisifiedStore(); +}; +var getOptionsFromConfig = (config) => { + const { validations: validations2, ...directlyPassableEntries } = config; + return { + ...directlyPassableEntries, + validate: validations2.enabled + }; +}; +var omitUndefinedOptions = (passedOptions) => { + const omittedOptions = {}; + for (const k of Object.keys(passedOptions)) { + const key = k; + if (passedOptions[key] !== void 0) { + omittedOptions[key] = passedOptions[key]; + } + } + return omittedOptions; +}; +var parseOptions = (passedOptions) => { + const notUndefinedOptions = omitUndefinedOptions(passedOptions); + const validations2 = getValidations(notUndefinedOptions?.validate ?? true); + validations2.validationsConfig(); + validations2.draftPolliHeaders( + // @ts-expect-error see the note above. + notUndefinedOptions.draft_polli_ratelimit_headers + ); + validations2.onLimitReached(notUndefinedOptions.onLimitReached); + let standardHeaders = notUndefinedOptions.standardHeaders ?? false; + if (standardHeaders === true) + standardHeaders = "draft-6"; + const config = { + windowMs: 60 * 1e3, + limit: passedOptions.max ?? 5, + // `max` is deprecated, but support it anyways. + message: "Too many requests, please try again later.", + statusCode: 429, + legacyHeaders: passedOptions.headers ?? true, + identifier(request, _response) { + let duration = ""; + const property = config.requestPropertyName; + const { limit } = request[property]; + const seconds = config.windowMs / 1e3; + const minutes = config.windowMs / (1e3 * 60); + const hours = config.windowMs / (1e3 * 60 * 60); + const days = config.windowMs / (1e3 * 60 * 60 * 24); + if (seconds < 60) + duration = `${seconds}sec`; + else if (minutes < 60) + duration = `${minutes}min`; + else if (hours < 24) + duration = `${hours}hr${hours > 1 ? "s" : ""}`; + else + duration = `${days}day${days > 1 ? "s" : ""}`; + return `${limit}-in-${duration}`; + }, + requestPropertyName: "rateLimit", + skipFailedRequests: false, + skipSuccessfulRequests: false, + requestWasSuccessful: (_request, response) => response.statusCode < 400, + skip: (_request, _response) => false, + keyGenerator(request, _response) { + validations2.ip(request.ip); + validations2.trustProxy(request); + validations2.xForwardedForHeader(request); + return request.ip; + }, + async handler(request, response, _next, _optionsUsed) { + response.status(config.statusCode); + const message = typeof config.message === "function" ? await config.message( + request, + response + ) : config.message; + if (!response.writableEnded) { + response.send(message); + } + }, + passOnStoreError: false, + // Allow the default options to be overriden by the passed options. + ...notUndefinedOptions, + // `standardHeaders` is resolved into a draft version above, use that. + standardHeaders, + // Note that this field is declared after the user's options are spread in, + // so that this field doesn't get overriden with an un-promisified store! + store: promisifyStore(notUndefinedOptions.store ?? new MemoryStore()), + // Print an error to the console if a few known misconfigurations are detected. + validations: validations2 + }; + if (typeof config.store.increment !== "function" || typeof config.store.decrement !== "function" || typeof config.store.resetKey !== "function" || config.store.resetAll !== void 0 && typeof config.store.resetAll !== "function" || config.store.init !== void 0 && typeof config.store.init !== "function") { + throw new TypeError( + "An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface." + ); + } + return config; +}; +var handleAsyncErrors = (fn) => async (request, response, next) => { + try { + await Promise.resolve(fn(request, response, next)).catch(next); + } catch (error) { + next(error); + } +}; +var rateLimit = (passedOptions) => { + const config = parseOptions(passedOptions ?? {}); + const options = getOptionsFromConfig(config); + config.validations.creationStack(config.store); + config.validations.unsharedStore(config.store); + if (typeof config.store.init === "function") + config.store.init(options); + const middleware = handleAsyncErrors( + async (request, response, next) => { + const skip = await config.skip(request, response); + if (skip) { + next(); + return; + } + const augmentedRequest = request; + const key = await config.keyGenerator(request, response); + let totalHits = 0; + let resetTime; + try { + const incrementResult = await config.store.increment(key); + totalHits = incrementResult.totalHits; + resetTime = incrementResult.resetTime; + } catch (error) { + if (config.passOnStoreError) { + console.error( + "express-rate-limit: error from store, allowing request without rate-limiting.", + error + ); + next(); + return; + } + throw error; + } + config.validations.positiveHits(totalHits); + config.validations.singleCount(request, config.store, key); + const retrieveLimit = typeof config.limit === "function" ? config.limit(request, response) : config.limit; + const limit = await retrieveLimit; + config.validations.limit(limit); + const info = { + limit, + used: totalHits, + remaining: Math.max(limit - totalHits, 0), + resetTime + }; + Object.defineProperty(info, "current", { + configurable: false, + enumerable: false, + value: totalHits + }); + augmentedRequest[config.requestPropertyName] = info; + if (config.legacyHeaders && !response.headersSent) { + setLegacyHeaders(response, info); + } + if (config.standardHeaders && !response.headersSent) { + switch (config.standardHeaders) { + case "draft-6": { + setDraft6Headers(response, info, config.windowMs); + break; + } + case "draft-7": { + config.validations.headersResetTime(info.resetTime); + setDraft7Headers(response, info, config.windowMs); + break; + } + case "draft-8": { + const retrieveName = typeof config.identifier === "function" ? config.identifier(request, response) : config.identifier; + const name = await retrieveName; + config.validations.headersResetTime(info.resetTime); + setDraft8Headers(response, info, config.windowMs, name, key); + break; + } + default: { + config.validations.headersDraftVersion(config.standardHeaders); + break; + } + } + } + if (config.skipFailedRequests || config.skipSuccessfulRequests) { + let decremented = false; + const decrementKey = async () => { + if (!decremented) { + await config.store.decrement(key); + decremented = true; + } + }; + if (config.skipFailedRequests) { + response.on("finish", async () => { + if (!await config.requestWasSuccessful(request, response)) + await decrementKey(); + }); + response.on("close", async () => { + if (!response.writableEnded) + await decrementKey(); + }); + response.on("error", async () => { + await decrementKey(); + }); + } + if (config.skipSuccessfulRequests) { + response.on("finish", async () => { + if (await config.requestWasSuccessful(request, response)) + await decrementKey(); + }); + } + } + config.validations.disable(); + if (totalHits > limit) { + if (config.legacyHeaders || config.standardHeaders) { + setRetryAfterHeader(response, info, config.windowMs); + } + config.handler(request, response, next, options); + return; + } + next(); + } + ); + const getThrowFn = () => { + throw new Error("The current store does not support the get/getKey method"); + }; + middleware.resetKey = config.store.resetKey.bind(config.store); + middleware.getKey = typeof config.store.get === "function" ? config.store.get.bind(config.store) : getThrowFn; + return middleware; +}; +var lib_default = rateLimit; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + MemoryStore, + rateLimit +}); +module.exports = rateLimit; module.exports.default = rateLimit; module.exports.rateLimit = rateLimit; module.exports.MemoryStore = MemoryStore; diff --git a/node_modules/express-rate-limit/dist/index.d.cts b/node_modules/express-rate-limit/dist/index.d.cts new file mode 100644 index 0000000..62fe123 --- /dev/null +++ b/node_modules/express-rate-limit/dist/index.d.cts @@ -0,0 +1,584 @@ +// Generated by dts-bundle-generator v8.0.1 + +import { NextFunction, Request, RequestHandler, Response } from 'express'; + +declare const validations: { + enabled: { + [key: string]: boolean; + }; + disable(): void; + /** + * Checks whether the IP address is valid, and that it does not have a port + * number in it. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address. + * + * @param ip {string | undefined} - The IP address provided by Express as request.ip. + * + * @returns {void} + */ + ip(ip: string | undefined): void; + /** + * Makes sure the trust proxy setting is not set to `true`. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + trustProxy(request: Request): void; + /** + * Makes sure the trust proxy setting is set in case the `X-Forwarded-For` + * header is present. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + xForwardedForHeader(request: Request): void; + /** + * Ensures totalHits value from store is a positive integer. + * + * @param hits {any} - The `totalHits` returned by the store. + */ + positiveHits(hits: any): void; + /** + * Ensures a single store instance is not used with multiple express-rate-limit instances + */ + unsharedStore(store: Store): void; + /** + * Ensures a given key is incremented only once per request. + * + * @param request {Request} - The Express request object. + * @param store {Store} - The store class. + * @param key {string} - The key used to store the client's hit count. + * + * @returns {void} + */ + singleCount(request: Request, store: Store, key: string): void; + /** + * Warns the user that the behaviour for `max: 0` / `limit: 0` is + * changing in the next major release. + * + * @param limit {number} - The maximum number of hits per client. + * + * @returns {void} + */ + limit(limit: number): void; + /** + * Warns the user that the `draft_polli_ratelimit_headers` option is deprecated + * and will be removed in the next major release. + * + * @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers. + * + * @returns {void} + */ + draftPolliHeaders(draft_polli_ratelimit_headers?: any): void; + /** + * Warns the user that the `onLimitReached` option is deprecated and + * will be removed in the next major release. + * + * @param onLimitReached {any | undefined} - The maximum number of hits per client. + * + * @returns {void} + */ + onLimitReached(onLimitReached?: any): void; + /** + * Warns the user when an invalid/unsupported version of the draft spec is passed. + * + * @param version {any | undefined} - The version passed by the user. + * + * @returns {void} + */ + headersDraftVersion(version?: any): void; + /** + * Warns the user when the selected headers option requires a reset time but + * the store does not provide one. + * + * @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset. + * + * @returns {void} + */ + headersResetTime(resetTime?: Date): void; + /** + * Checks the options.validate setting to ensure that only recognized + * validations are enabled or disabled. + * + * If any unrecognized values are found, an error is logged that + * includes the list of supported vaidations. + */ + validationsConfig(): void; + /** + * Checks to see if the instance was created inside of a request handler, + * which would prevent it from working correctly, with the default memory + * store (or any other store with localKeys.) + */ + creationStack(store: Store): void; +}; +export type Validations = typeof validations; +declare const SUPPORTED_DRAFT_VERSIONS: string[]; +/** + * Callback that fires when a client's hit counter is incremented. + * + * @param error {Error | undefined} - The error that occurred, if any. + * @param totalHits {number} - The number of hits for that client so far. + * @param resetTime {Date | undefined} - The time when the counter resets. + */ +export type IncrementCallback = (error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void; +/** + * Method (in the form of middleware) to generate/retrieve a value based on the + * incoming request. + * + * @param request {Request} - The Express request object. + * @param response {Response} - The Express response object. + * + * @returns {T} - The value needed. + */ +export type ValueDeterminingMiddleware = (request: Request, response: Response) => T | Promise; +/** + * Express request handler that sends back a response when a client is + * rate-limited. + * + * @param request {Request} - The Express request object. + * @param response {Response} - The Express response object. + * @param next {NextFunction} - The Express `next` function, can be called to skip responding. + * @param optionsUsed {Options} - The options used to set up the middleware. + */ +export type RateLimitExceededEventHandler = (request: Request, response: Response, next: NextFunction, optionsUsed: Options) => void; +/** + * Event callback that is triggered on a client's first request that exceeds the limit + * but not for subsequent requests. May be used for logging, etc. Should *not* + * send a response. + * + * @param request {Request} - The Express request object. + * @param response {Response} - The Express response object. + * @param optionsUsed {Options} - The options used to set up the middleware. + */ +export type RateLimitReachedEventHandler = (request: Request, response: Response, optionsUsed: Options) => void; +/** + * Data returned from the `Store` when a client's hit counter is incremented. + * + * @property totalHits {number} - The number of hits for that client so far. + * @property resetTime {Date | undefined} - The time when the counter resets. + */ +export type ClientRateLimitInfo = { + totalHits: number; + resetTime: Date | undefined; +}; +export type IncrementResponse = ClientRateLimitInfo; +/** + * A modified Express request handler with the rate limit functions. + */ +export type RateLimitRequestHandler = RequestHandler & { + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + resetKey: (key: string) => void; + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + */ + getKey: (key: string) => Promise | ClientRateLimitInfo | undefined; +}; +/** + * An interface that all hit counter stores must implement. + * + * @deprecated 6.x - Implement the `Store` interface instead. + */ +export type LegacyStore = { + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * @param callback {IncrementCallback} - The callback to call once the counter is incremented. + */ + incr: (key: string, callback: IncrementCallback) => void; + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + decrement: (key: string) => void; + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + resetKey: (key: string) => void; + /** + * Method to reset everyone's hit counter. + */ + resetAll?: () => void; +}; +/** + * An interface that all hit counter stores must implement. + */ +export type Store = { + /** + * Method that initializes the store, and has access to the options passed to + * the middleware too. + * + * @param options {Options} - The options used to setup the middleware. + */ + init?: (options: Options) => void; + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + */ + get?: (key: string) => Promise | ClientRateLimitInfo | undefined; + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @returns {IncrementResponse | undefined} - The number of hits and reset time for that client. + */ + increment: (key: string) => Promise | IncrementResponse; + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + decrement: (key: string) => Promise | void; + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + resetKey: (key: string) => Promise | void; + /** + * Method to reset everyone's hit counter. + */ + resetAll?: () => Promise | void; + /** + * Method to shutdown the store, stop timers, and release all resources. + */ + shutdown?: () => Promise | void; + /** + * Flag to indicate that keys incremented in one instance of this store can + * not affect other instances. Typically false if a database is used, true for + * MemoryStore. + * + * Used to help detect double-counting misconfigurations. + */ + localKeys?: boolean; + /** + * Optional value that the store prepends to keys + * + * Used by the double-count check to avoid false-positives when a key is counted twice, but with different prefixes + */ + prefix?: string; +}; +export type DraftHeadersVersion = (typeof SUPPORTED_DRAFT_VERSIONS)[number]; +/** + * Validate configuration object for enabling or disabling specific validations. + * + * The keys must also be keys in the validations object, except `enable`, `disable`, + * and `default`. + */ +export type EnabledValidations = { + [key in keyof Omit | "default"]?: boolean; +}; +/** + * The configuration options for the rate limiter. + */ +export type Options = { + /** + * How long we should remember the requests. + * + * Defaults to `60000` ms (= 1 minute). + */ + windowMs: number; + /** + * The maximum number of connections to allow during the `window` before + * rate limiting the client. + * + * Can be the limit itself as a number or express middleware that parses + * the request and then figures out the limit. + * + * Defaults to `5`. + */ + limit: number | ValueDeterminingMiddleware; + /** + * The response body to send back when a client is rate limited. + * + * Defaults to `'Too many requests, please try again later.'` + */ + message: any | ValueDeterminingMiddleware; + /** + * The HTTP status code to send back when a client is rate limited. + * + * Defaults to `HTTP 429 Too Many Requests` (RFC 6585). + */ + statusCode: number; + /** + * Whether to send `X-RateLimit-*` headers with the rate limit and the number + * of requests. + * + * Defaults to `true` (for backward compatibility). + */ + legacyHeaders: boolean; + /** + * Whether to enable support for the standardized rate limit headers (`RateLimit-*`). + * + * Defaults to `false` (for backward compatibility, but its use is recommended). + */ + standardHeaders: boolean | DraftHeadersVersion; + /** + * The name used to identify the quota policy in the `RateLimit` headers as per + * the 8th draft of the IETF specification. + * + * Defaults to `{limit}-in-{window}`. + */ + identifier: string | ValueDeterminingMiddleware; + /** + * The name of the property on the request object to store the rate limit info. + * + * Defaults to `rateLimit`. + */ + requestPropertyName: string; + /** + * If `true`, the library will (by default) skip all requests that have a 4XX + * or 5XX status. + * + * Defaults to `false`. + */ + skipFailedRequests: boolean; + /** + * If `true`, the library will (by default) skip all requests that have a + * status code less than 400. + * + * Defaults to `false`. + */ + skipSuccessfulRequests: boolean; + /** + * Method to generate custom identifiers for clients. + * + * By default, the client's IP address is used. + */ + keyGenerator: ValueDeterminingMiddleware; + /** + * Express request handler that sends back a response when a client is + * rate-limited. + * + * By default, sends back the `statusCode` and `message` set via the options. + */ + handler: RateLimitExceededEventHandler; + /** + * Method (in the form of middleware) to determine whether or not this request + * counts towards a client's quota. + * + * By default, skips no requests. + */ + skip: ValueDeterminingMiddleware; + /** + * Method to determine whether or not the request counts as 'succesful'. Used + * when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true. + * + * By default, requests with a response status code less than 400 are considered + * successful. + */ + requestWasSuccessful: ValueDeterminingMiddleware; + /** + * The `Store` to use to store the hit count for each client. + * + * By default, the built-in `MemoryStore` will be used. + */ + store: Store | LegacyStore; + /** + * The list of validation checks that should run. + */ + validate: boolean | EnabledValidations; + /** + * Whether to send `X-RateLimit-*` headers with the rate limit and the number + * of requests. + * + * @deprecated 6.x - This option was renamed to `legacyHeaders`. + */ + headers?: boolean; + /** + * The maximum number of connections to allow during the `window` before + * rate limiting the client. + * + * Can be the limit itself as a number or express middleware that parses + * the request and then figures out the limit. + * + * @deprecated 7.x - This option was renamed to `limit`. However, it will not + * be removed from the library in the foreseeable future. + */ + max?: number | ValueDeterminingMiddleware; + /** + * If the Store generates an error, allow the request to pass. + */ + passOnStoreError: boolean; +}; +/** + * The extended request object that includes information about the client's + * rate limit. + */ +export type AugmentedRequest = Request & { + [key: string]: RateLimitInfo; +}; +/** + * The rate limit related information for each client included in the + * Express request object. + */ +export type RateLimitInfo = { + limit: number; + used: number; + remaining: number; + resetTime: Date | undefined; +}; +/** + * + * Create an instance of IP rate-limiting middleware for Express. + * + * @param passedOptions {Options} - Options to configure the rate limiter. + * + * @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration. + * + * @public + */ +export declare const rateLimit: (passedOptions?: Partial) => RateLimitRequestHandler; +/** + * The record that stores information about a client - namely, how many times + * they have hit the endpoint, and when their hit count resets. + * + * Similar to `ClientRateLimitInfo`, except `resetTime` is a compulsory field. + */ +export type Client = { + totalHits: number; + resetTime: Date; +}; +/** + * A `Store` that stores the hit count for each client in memory. + * + * @public + */ +export declare class MemoryStore implements Store { + /** + * The duration of time before which all hit counts are reset (in milliseconds). + */ + windowMs: number; + /** + * These two maps store usage (requests) and reset time by key (for example, IP + * addresses or API keys). + * + * They are split into two to avoid having to iterate through the entire set to + * determine which ones need reset. Instead, `Client`s are moved from `previous` + * to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients + * left in `previous`, i.e., those that have not made any recent requests, are + * known to be expired and can be deleted in bulk. + */ + previous: Map; + current: Map; + /** + * A reference to the active timer. + */ + interval?: NodeJS.Timeout; + /** + * Confirmation that the keys incremented in once instance of MemoryStore + * cannot affect other instances. + */ + localKeys: boolean; + /** + * Method that initializes the store. + * + * @param options {Options} - The options used to setup the middleware. + */ + init(options: Options): void; + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client. + * + * @public + */ + get(key: string): Promise; + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + * + * @public + */ + increment(key: string): Promise; + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + decrement(key: string): Promise; + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + resetKey(key: string): Promise; + /** + * Method to reset everyone's hit counter. + * + * @public + */ + resetAll(): Promise; + /** + * Method to stop the timer (if currently running) and prevent any memory + * leaks. + * + * @public + */ + shutdown(): void; + /** + * Recycles a client by setting its hit count to zero, and reset time to + * `windowMs` milliseconds from now. + * + * NOT to be confused with `#resetKey()`, which removes a client from both the + * `current` and `previous` maps. + * + * @param client {Client} - The client to recycle. + * @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client. + * + * @return {Client} - The modified client that was passed in, to allow for chaining. + */ + private resetClient; + /** + * Retrieves or creates a client, given a key. Also ensures that the client being + * returned is in the `current` map. + * + * @param key {string} - The key under which the client is (or is to be) stored. + * + * @returns {Client} - The requested client. + */ + private getClient; + /** + * Move current clients to previous, create a new map for current. + * + * This function is called every `windowMs`. + */ + private clearExpired; +} + +export { + rateLimit as default, +}; + +export {}; diff --git a/node_modules/express-rate-limit/dist/index.d.mts b/node_modules/express-rate-limit/dist/index.d.mts new file mode 100644 index 0000000..62fe123 --- /dev/null +++ b/node_modules/express-rate-limit/dist/index.d.mts @@ -0,0 +1,584 @@ +// Generated by dts-bundle-generator v8.0.1 + +import { NextFunction, Request, RequestHandler, Response } from 'express'; + +declare const validations: { + enabled: { + [key: string]: boolean; + }; + disable(): void; + /** + * Checks whether the IP address is valid, and that it does not have a port + * number in it. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address. + * + * @param ip {string | undefined} - The IP address provided by Express as request.ip. + * + * @returns {void} + */ + ip(ip: string | undefined): void; + /** + * Makes sure the trust proxy setting is not set to `true`. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + trustProxy(request: Request): void; + /** + * Makes sure the trust proxy setting is set in case the `X-Forwarded-For` + * header is present. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + xForwardedForHeader(request: Request): void; + /** + * Ensures totalHits value from store is a positive integer. + * + * @param hits {any} - The `totalHits` returned by the store. + */ + positiveHits(hits: any): void; + /** + * Ensures a single store instance is not used with multiple express-rate-limit instances + */ + unsharedStore(store: Store): void; + /** + * Ensures a given key is incremented only once per request. + * + * @param request {Request} - The Express request object. + * @param store {Store} - The store class. + * @param key {string} - The key used to store the client's hit count. + * + * @returns {void} + */ + singleCount(request: Request, store: Store, key: string): void; + /** + * Warns the user that the behaviour for `max: 0` / `limit: 0` is + * changing in the next major release. + * + * @param limit {number} - The maximum number of hits per client. + * + * @returns {void} + */ + limit(limit: number): void; + /** + * Warns the user that the `draft_polli_ratelimit_headers` option is deprecated + * and will be removed in the next major release. + * + * @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers. + * + * @returns {void} + */ + draftPolliHeaders(draft_polli_ratelimit_headers?: any): void; + /** + * Warns the user that the `onLimitReached` option is deprecated and + * will be removed in the next major release. + * + * @param onLimitReached {any | undefined} - The maximum number of hits per client. + * + * @returns {void} + */ + onLimitReached(onLimitReached?: any): void; + /** + * Warns the user when an invalid/unsupported version of the draft spec is passed. + * + * @param version {any | undefined} - The version passed by the user. + * + * @returns {void} + */ + headersDraftVersion(version?: any): void; + /** + * Warns the user when the selected headers option requires a reset time but + * the store does not provide one. + * + * @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset. + * + * @returns {void} + */ + headersResetTime(resetTime?: Date): void; + /** + * Checks the options.validate setting to ensure that only recognized + * validations are enabled or disabled. + * + * If any unrecognized values are found, an error is logged that + * includes the list of supported vaidations. + */ + validationsConfig(): void; + /** + * Checks to see if the instance was created inside of a request handler, + * which would prevent it from working correctly, with the default memory + * store (or any other store with localKeys.) + */ + creationStack(store: Store): void; +}; +export type Validations = typeof validations; +declare const SUPPORTED_DRAFT_VERSIONS: string[]; +/** + * Callback that fires when a client's hit counter is incremented. + * + * @param error {Error | undefined} - The error that occurred, if any. + * @param totalHits {number} - The number of hits for that client so far. + * @param resetTime {Date | undefined} - The time when the counter resets. + */ +export type IncrementCallback = (error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void; +/** + * Method (in the form of middleware) to generate/retrieve a value based on the + * incoming request. + * + * @param request {Request} - The Express request object. + * @param response {Response} - The Express response object. + * + * @returns {T} - The value needed. + */ +export type ValueDeterminingMiddleware = (request: Request, response: Response) => T | Promise; +/** + * Express request handler that sends back a response when a client is + * rate-limited. + * + * @param request {Request} - The Express request object. + * @param response {Response} - The Express response object. + * @param next {NextFunction} - The Express `next` function, can be called to skip responding. + * @param optionsUsed {Options} - The options used to set up the middleware. + */ +export type RateLimitExceededEventHandler = (request: Request, response: Response, next: NextFunction, optionsUsed: Options) => void; +/** + * Event callback that is triggered on a client's first request that exceeds the limit + * but not for subsequent requests. May be used for logging, etc. Should *not* + * send a response. + * + * @param request {Request} - The Express request object. + * @param response {Response} - The Express response object. + * @param optionsUsed {Options} - The options used to set up the middleware. + */ +export type RateLimitReachedEventHandler = (request: Request, response: Response, optionsUsed: Options) => void; +/** + * Data returned from the `Store` when a client's hit counter is incremented. + * + * @property totalHits {number} - The number of hits for that client so far. + * @property resetTime {Date | undefined} - The time when the counter resets. + */ +export type ClientRateLimitInfo = { + totalHits: number; + resetTime: Date | undefined; +}; +export type IncrementResponse = ClientRateLimitInfo; +/** + * A modified Express request handler with the rate limit functions. + */ +export type RateLimitRequestHandler = RequestHandler & { + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + resetKey: (key: string) => void; + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + */ + getKey: (key: string) => Promise | ClientRateLimitInfo | undefined; +}; +/** + * An interface that all hit counter stores must implement. + * + * @deprecated 6.x - Implement the `Store` interface instead. + */ +export type LegacyStore = { + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * @param callback {IncrementCallback} - The callback to call once the counter is incremented. + */ + incr: (key: string, callback: IncrementCallback) => void; + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + decrement: (key: string) => void; + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + resetKey: (key: string) => void; + /** + * Method to reset everyone's hit counter. + */ + resetAll?: () => void; +}; +/** + * An interface that all hit counter stores must implement. + */ +export type Store = { + /** + * Method that initializes the store, and has access to the options passed to + * the middleware too. + * + * @param options {Options} - The options used to setup the middleware. + */ + init?: (options: Options) => void; + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + */ + get?: (key: string) => Promise | ClientRateLimitInfo | undefined; + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @returns {IncrementResponse | undefined} - The number of hits and reset time for that client. + */ + increment: (key: string) => Promise | IncrementResponse; + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + decrement: (key: string) => Promise | void; + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + resetKey: (key: string) => Promise | void; + /** + * Method to reset everyone's hit counter. + */ + resetAll?: () => Promise | void; + /** + * Method to shutdown the store, stop timers, and release all resources. + */ + shutdown?: () => Promise | void; + /** + * Flag to indicate that keys incremented in one instance of this store can + * not affect other instances. Typically false if a database is used, true for + * MemoryStore. + * + * Used to help detect double-counting misconfigurations. + */ + localKeys?: boolean; + /** + * Optional value that the store prepends to keys + * + * Used by the double-count check to avoid false-positives when a key is counted twice, but with different prefixes + */ + prefix?: string; +}; +export type DraftHeadersVersion = (typeof SUPPORTED_DRAFT_VERSIONS)[number]; +/** + * Validate configuration object for enabling or disabling specific validations. + * + * The keys must also be keys in the validations object, except `enable`, `disable`, + * and `default`. + */ +export type EnabledValidations = { + [key in keyof Omit | "default"]?: boolean; +}; +/** + * The configuration options for the rate limiter. + */ +export type Options = { + /** + * How long we should remember the requests. + * + * Defaults to `60000` ms (= 1 minute). + */ + windowMs: number; + /** + * The maximum number of connections to allow during the `window` before + * rate limiting the client. + * + * Can be the limit itself as a number or express middleware that parses + * the request and then figures out the limit. + * + * Defaults to `5`. + */ + limit: number | ValueDeterminingMiddleware; + /** + * The response body to send back when a client is rate limited. + * + * Defaults to `'Too many requests, please try again later.'` + */ + message: any | ValueDeterminingMiddleware; + /** + * The HTTP status code to send back when a client is rate limited. + * + * Defaults to `HTTP 429 Too Many Requests` (RFC 6585). + */ + statusCode: number; + /** + * Whether to send `X-RateLimit-*` headers with the rate limit and the number + * of requests. + * + * Defaults to `true` (for backward compatibility). + */ + legacyHeaders: boolean; + /** + * Whether to enable support for the standardized rate limit headers (`RateLimit-*`). + * + * Defaults to `false` (for backward compatibility, but its use is recommended). + */ + standardHeaders: boolean | DraftHeadersVersion; + /** + * The name used to identify the quota policy in the `RateLimit` headers as per + * the 8th draft of the IETF specification. + * + * Defaults to `{limit}-in-{window}`. + */ + identifier: string | ValueDeterminingMiddleware; + /** + * The name of the property on the request object to store the rate limit info. + * + * Defaults to `rateLimit`. + */ + requestPropertyName: string; + /** + * If `true`, the library will (by default) skip all requests that have a 4XX + * or 5XX status. + * + * Defaults to `false`. + */ + skipFailedRequests: boolean; + /** + * If `true`, the library will (by default) skip all requests that have a + * status code less than 400. + * + * Defaults to `false`. + */ + skipSuccessfulRequests: boolean; + /** + * Method to generate custom identifiers for clients. + * + * By default, the client's IP address is used. + */ + keyGenerator: ValueDeterminingMiddleware; + /** + * Express request handler that sends back a response when a client is + * rate-limited. + * + * By default, sends back the `statusCode` and `message` set via the options. + */ + handler: RateLimitExceededEventHandler; + /** + * Method (in the form of middleware) to determine whether or not this request + * counts towards a client's quota. + * + * By default, skips no requests. + */ + skip: ValueDeterminingMiddleware; + /** + * Method to determine whether or not the request counts as 'succesful'. Used + * when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true. + * + * By default, requests with a response status code less than 400 are considered + * successful. + */ + requestWasSuccessful: ValueDeterminingMiddleware; + /** + * The `Store` to use to store the hit count for each client. + * + * By default, the built-in `MemoryStore` will be used. + */ + store: Store | LegacyStore; + /** + * The list of validation checks that should run. + */ + validate: boolean | EnabledValidations; + /** + * Whether to send `X-RateLimit-*` headers with the rate limit and the number + * of requests. + * + * @deprecated 6.x - This option was renamed to `legacyHeaders`. + */ + headers?: boolean; + /** + * The maximum number of connections to allow during the `window` before + * rate limiting the client. + * + * Can be the limit itself as a number or express middleware that parses + * the request and then figures out the limit. + * + * @deprecated 7.x - This option was renamed to `limit`. However, it will not + * be removed from the library in the foreseeable future. + */ + max?: number | ValueDeterminingMiddleware; + /** + * If the Store generates an error, allow the request to pass. + */ + passOnStoreError: boolean; +}; +/** + * The extended request object that includes information about the client's + * rate limit. + */ +export type AugmentedRequest = Request & { + [key: string]: RateLimitInfo; +}; +/** + * The rate limit related information for each client included in the + * Express request object. + */ +export type RateLimitInfo = { + limit: number; + used: number; + remaining: number; + resetTime: Date | undefined; +}; +/** + * + * Create an instance of IP rate-limiting middleware for Express. + * + * @param passedOptions {Options} - Options to configure the rate limiter. + * + * @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration. + * + * @public + */ +export declare const rateLimit: (passedOptions?: Partial) => RateLimitRequestHandler; +/** + * The record that stores information about a client - namely, how many times + * they have hit the endpoint, and when their hit count resets. + * + * Similar to `ClientRateLimitInfo`, except `resetTime` is a compulsory field. + */ +export type Client = { + totalHits: number; + resetTime: Date; +}; +/** + * A `Store` that stores the hit count for each client in memory. + * + * @public + */ +export declare class MemoryStore implements Store { + /** + * The duration of time before which all hit counts are reset (in milliseconds). + */ + windowMs: number; + /** + * These two maps store usage (requests) and reset time by key (for example, IP + * addresses or API keys). + * + * They are split into two to avoid having to iterate through the entire set to + * determine which ones need reset. Instead, `Client`s are moved from `previous` + * to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients + * left in `previous`, i.e., those that have not made any recent requests, are + * known to be expired and can be deleted in bulk. + */ + previous: Map; + current: Map; + /** + * A reference to the active timer. + */ + interval?: NodeJS.Timeout; + /** + * Confirmation that the keys incremented in once instance of MemoryStore + * cannot affect other instances. + */ + localKeys: boolean; + /** + * Method that initializes the store. + * + * @param options {Options} - The options used to setup the middleware. + */ + init(options: Options): void; + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client. + * + * @public + */ + get(key: string): Promise; + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + * + * @public + */ + increment(key: string): Promise; + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + decrement(key: string): Promise; + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + resetKey(key: string): Promise; + /** + * Method to reset everyone's hit counter. + * + * @public + */ + resetAll(): Promise; + /** + * Method to stop the timer (if currently running) and prevent any memory + * leaks. + * + * @public + */ + shutdown(): void; + /** + * Recycles a client by setting its hit count to zero, and reset time to + * `windowMs` milliseconds from now. + * + * NOT to be confused with `#resetKey()`, which removes a client from both the + * `current` and `previous` maps. + * + * @param client {Client} - The client to recycle. + * @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client. + * + * @return {Client} - The modified client that was passed in, to allow for chaining. + */ + private resetClient; + /** + * Retrieves or creates a client, given a key. Also ensures that the client being + * returned is in the `current` map. + * + * @param key {string} - The key under which the client is (or is to be) stored. + * + * @returns {Client} - The requested client. + */ + private getClient; + /** + * Move current clients to previous, create a new map for current. + * + * This function is called every `windowMs`. + */ + private clearExpired; +} + +export { + rateLimit as default, +}; + +export {}; diff --git a/node_modules/express-rate-limit/dist/index.d.ts b/node_modules/express-rate-limit/dist/index.d.ts new file mode 100644 index 0000000..62fe123 --- /dev/null +++ b/node_modules/express-rate-limit/dist/index.d.ts @@ -0,0 +1,584 @@ +// Generated by dts-bundle-generator v8.0.1 + +import { NextFunction, Request, RequestHandler, Response } from 'express'; + +declare const validations: { + enabled: { + [key: string]: boolean; + }; + disable(): void; + /** + * Checks whether the IP address is valid, and that it does not have a port + * number in it. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address. + * + * @param ip {string | undefined} - The IP address provided by Express as request.ip. + * + * @returns {void} + */ + ip(ip: string | undefined): void; + /** + * Makes sure the trust proxy setting is not set to `true`. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + trustProxy(request: Request): void; + /** + * Makes sure the trust proxy setting is set in case the `X-Forwarded-For` + * header is present. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + xForwardedForHeader(request: Request): void; + /** + * Ensures totalHits value from store is a positive integer. + * + * @param hits {any} - The `totalHits` returned by the store. + */ + positiveHits(hits: any): void; + /** + * Ensures a single store instance is not used with multiple express-rate-limit instances + */ + unsharedStore(store: Store): void; + /** + * Ensures a given key is incremented only once per request. + * + * @param request {Request} - The Express request object. + * @param store {Store} - The store class. + * @param key {string} - The key used to store the client's hit count. + * + * @returns {void} + */ + singleCount(request: Request, store: Store, key: string): void; + /** + * Warns the user that the behaviour for `max: 0` / `limit: 0` is + * changing in the next major release. + * + * @param limit {number} - The maximum number of hits per client. + * + * @returns {void} + */ + limit(limit: number): void; + /** + * Warns the user that the `draft_polli_ratelimit_headers` option is deprecated + * and will be removed in the next major release. + * + * @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers. + * + * @returns {void} + */ + draftPolliHeaders(draft_polli_ratelimit_headers?: any): void; + /** + * Warns the user that the `onLimitReached` option is deprecated and + * will be removed in the next major release. + * + * @param onLimitReached {any | undefined} - The maximum number of hits per client. + * + * @returns {void} + */ + onLimitReached(onLimitReached?: any): void; + /** + * Warns the user when an invalid/unsupported version of the draft spec is passed. + * + * @param version {any | undefined} - The version passed by the user. + * + * @returns {void} + */ + headersDraftVersion(version?: any): void; + /** + * Warns the user when the selected headers option requires a reset time but + * the store does not provide one. + * + * @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset. + * + * @returns {void} + */ + headersResetTime(resetTime?: Date): void; + /** + * Checks the options.validate setting to ensure that only recognized + * validations are enabled or disabled. + * + * If any unrecognized values are found, an error is logged that + * includes the list of supported vaidations. + */ + validationsConfig(): void; + /** + * Checks to see if the instance was created inside of a request handler, + * which would prevent it from working correctly, with the default memory + * store (or any other store with localKeys.) + */ + creationStack(store: Store): void; +}; +export type Validations = typeof validations; +declare const SUPPORTED_DRAFT_VERSIONS: string[]; +/** + * Callback that fires when a client's hit counter is incremented. + * + * @param error {Error | undefined} - The error that occurred, if any. + * @param totalHits {number} - The number of hits for that client so far. + * @param resetTime {Date | undefined} - The time when the counter resets. + */ +export type IncrementCallback = (error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void; +/** + * Method (in the form of middleware) to generate/retrieve a value based on the + * incoming request. + * + * @param request {Request} - The Express request object. + * @param response {Response} - The Express response object. + * + * @returns {T} - The value needed. + */ +export type ValueDeterminingMiddleware = (request: Request, response: Response) => T | Promise; +/** + * Express request handler that sends back a response when a client is + * rate-limited. + * + * @param request {Request} - The Express request object. + * @param response {Response} - The Express response object. + * @param next {NextFunction} - The Express `next` function, can be called to skip responding. + * @param optionsUsed {Options} - The options used to set up the middleware. + */ +export type RateLimitExceededEventHandler = (request: Request, response: Response, next: NextFunction, optionsUsed: Options) => void; +/** + * Event callback that is triggered on a client's first request that exceeds the limit + * but not for subsequent requests. May be used for logging, etc. Should *not* + * send a response. + * + * @param request {Request} - The Express request object. + * @param response {Response} - The Express response object. + * @param optionsUsed {Options} - The options used to set up the middleware. + */ +export type RateLimitReachedEventHandler = (request: Request, response: Response, optionsUsed: Options) => void; +/** + * Data returned from the `Store` when a client's hit counter is incremented. + * + * @property totalHits {number} - The number of hits for that client so far. + * @property resetTime {Date | undefined} - The time when the counter resets. + */ +export type ClientRateLimitInfo = { + totalHits: number; + resetTime: Date | undefined; +}; +export type IncrementResponse = ClientRateLimitInfo; +/** + * A modified Express request handler with the rate limit functions. + */ +export type RateLimitRequestHandler = RequestHandler & { + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + resetKey: (key: string) => void; + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + */ + getKey: (key: string) => Promise | ClientRateLimitInfo | undefined; +}; +/** + * An interface that all hit counter stores must implement. + * + * @deprecated 6.x - Implement the `Store` interface instead. + */ +export type LegacyStore = { + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * @param callback {IncrementCallback} - The callback to call once the counter is incremented. + */ + incr: (key: string, callback: IncrementCallback) => void; + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + decrement: (key: string) => void; + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + resetKey: (key: string) => void; + /** + * Method to reset everyone's hit counter. + */ + resetAll?: () => void; +}; +/** + * An interface that all hit counter stores must implement. + */ +export type Store = { + /** + * Method that initializes the store, and has access to the options passed to + * the middleware too. + * + * @param options {Options} - The options used to setup the middleware. + */ + init?: (options: Options) => void; + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + */ + get?: (key: string) => Promise | ClientRateLimitInfo | undefined; + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @returns {IncrementResponse | undefined} - The number of hits and reset time for that client. + */ + increment: (key: string) => Promise | IncrementResponse; + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + decrement: (key: string) => Promise | void; + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + */ + resetKey: (key: string) => Promise | void; + /** + * Method to reset everyone's hit counter. + */ + resetAll?: () => Promise | void; + /** + * Method to shutdown the store, stop timers, and release all resources. + */ + shutdown?: () => Promise | void; + /** + * Flag to indicate that keys incremented in one instance of this store can + * not affect other instances. Typically false if a database is used, true for + * MemoryStore. + * + * Used to help detect double-counting misconfigurations. + */ + localKeys?: boolean; + /** + * Optional value that the store prepends to keys + * + * Used by the double-count check to avoid false-positives when a key is counted twice, but with different prefixes + */ + prefix?: string; +}; +export type DraftHeadersVersion = (typeof SUPPORTED_DRAFT_VERSIONS)[number]; +/** + * Validate configuration object for enabling or disabling specific validations. + * + * The keys must also be keys in the validations object, except `enable`, `disable`, + * and `default`. + */ +export type EnabledValidations = { + [key in keyof Omit | "default"]?: boolean; +}; +/** + * The configuration options for the rate limiter. + */ +export type Options = { + /** + * How long we should remember the requests. + * + * Defaults to `60000` ms (= 1 minute). + */ + windowMs: number; + /** + * The maximum number of connections to allow during the `window` before + * rate limiting the client. + * + * Can be the limit itself as a number or express middleware that parses + * the request and then figures out the limit. + * + * Defaults to `5`. + */ + limit: number | ValueDeterminingMiddleware; + /** + * The response body to send back when a client is rate limited. + * + * Defaults to `'Too many requests, please try again later.'` + */ + message: any | ValueDeterminingMiddleware; + /** + * The HTTP status code to send back when a client is rate limited. + * + * Defaults to `HTTP 429 Too Many Requests` (RFC 6585). + */ + statusCode: number; + /** + * Whether to send `X-RateLimit-*` headers with the rate limit and the number + * of requests. + * + * Defaults to `true` (for backward compatibility). + */ + legacyHeaders: boolean; + /** + * Whether to enable support for the standardized rate limit headers (`RateLimit-*`). + * + * Defaults to `false` (for backward compatibility, but its use is recommended). + */ + standardHeaders: boolean | DraftHeadersVersion; + /** + * The name used to identify the quota policy in the `RateLimit` headers as per + * the 8th draft of the IETF specification. + * + * Defaults to `{limit}-in-{window}`. + */ + identifier: string | ValueDeterminingMiddleware; + /** + * The name of the property on the request object to store the rate limit info. + * + * Defaults to `rateLimit`. + */ + requestPropertyName: string; + /** + * If `true`, the library will (by default) skip all requests that have a 4XX + * or 5XX status. + * + * Defaults to `false`. + */ + skipFailedRequests: boolean; + /** + * If `true`, the library will (by default) skip all requests that have a + * status code less than 400. + * + * Defaults to `false`. + */ + skipSuccessfulRequests: boolean; + /** + * Method to generate custom identifiers for clients. + * + * By default, the client's IP address is used. + */ + keyGenerator: ValueDeterminingMiddleware; + /** + * Express request handler that sends back a response when a client is + * rate-limited. + * + * By default, sends back the `statusCode` and `message` set via the options. + */ + handler: RateLimitExceededEventHandler; + /** + * Method (in the form of middleware) to determine whether or not this request + * counts towards a client's quota. + * + * By default, skips no requests. + */ + skip: ValueDeterminingMiddleware; + /** + * Method to determine whether or not the request counts as 'succesful'. Used + * when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true. + * + * By default, requests with a response status code less than 400 are considered + * successful. + */ + requestWasSuccessful: ValueDeterminingMiddleware; + /** + * The `Store` to use to store the hit count for each client. + * + * By default, the built-in `MemoryStore` will be used. + */ + store: Store | LegacyStore; + /** + * The list of validation checks that should run. + */ + validate: boolean | EnabledValidations; + /** + * Whether to send `X-RateLimit-*` headers with the rate limit and the number + * of requests. + * + * @deprecated 6.x - This option was renamed to `legacyHeaders`. + */ + headers?: boolean; + /** + * The maximum number of connections to allow during the `window` before + * rate limiting the client. + * + * Can be the limit itself as a number or express middleware that parses + * the request and then figures out the limit. + * + * @deprecated 7.x - This option was renamed to `limit`. However, it will not + * be removed from the library in the foreseeable future. + */ + max?: number | ValueDeterminingMiddleware; + /** + * If the Store generates an error, allow the request to pass. + */ + passOnStoreError: boolean; +}; +/** + * The extended request object that includes information about the client's + * rate limit. + */ +export type AugmentedRequest = Request & { + [key: string]: RateLimitInfo; +}; +/** + * The rate limit related information for each client included in the + * Express request object. + */ +export type RateLimitInfo = { + limit: number; + used: number; + remaining: number; + resetTime: Date | undefined; +}; +/** + * + * Create an instance of IP rate-limiting middleware for Express. + * + * @param passedOptions {Options} - Options to configure the rate limiter. + * + * @returns {RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration. + * + * @public + */ +export declare const rateLimit: (passedOptions?: Partial) => RateLimitRequestHandler; +/** + * The record that stores information about a client - namely, how many times + * they have hit the endpoint, and when their hit count resets. + * + * Similar to `ClientRateLimitInfo`, except `resetTime` is a compulsory field. + */ +export type Client = { + totalHits: number; + resetTime: Date; +}; +/** + * A `Store` that stores the hit count for each client in memory. + * + * @public + */ +export declare class MemoryStore implements Store { + /** + * The duration of time before which all hit counts are reset (in milliseconds). + */ + windowMs: number; + /** + * These two maps store usage (requests) and reset time by key (for example, IP + * addresses or API keys). + * + * They are split into two to avoid having to iterate through the entire set to + * determine which ones need reset. Instead, `Client`s are moved from `previous` + * to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients + * left in `previous`, i.e., those that have not made any recent requests, are + * known to be expired and can be deleted in bulk. + */ + previous: Map; + current: Map; + /** + * A reference to the active timer. + */ + interval?: NodeJS.Timeout; + /** + * Confirmation that the keys incremented in once instance of MemoryStore + * cannot affect other instances. + */ + localKeys: boolean; + /** + * Method that initializes the store. + * + * @param options {Options} - The options used to setup the middleware. + */ + init(options: Options): void; + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client. + * + * @public + */ + get(key: string): Promise; + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + * + * @public + */ + increment(key: string): Promise; + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + decrement(key: string): Promise; + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + resetKey(key: string): Promise; + /** + * Method to reset everyone's hit counter. + * + * @public + */ + resetAll(): Promise; + /** + * Method to stop the timer (if currently running) and prevent any memory + * leaks. + * + * @public + */ + shutdown(): void; + /** + * Recycles a client by setting its hit count to zero, and reset time to + * `windowMs` milliseconds from now. + * + * NOT to be confused with `#resetKey()`, which removes a client from both the + * `current` and `previous` maps. + * + * @param client {Client} - The client to recycle. + * @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client. + * + * @return {Client} - The modified client that was passed in, to allow for chaining. + */ + private resetClient; + /** + * Retrieves or creates a client, given a key. Also ensures that the client being + * returned is in the `current` map. + * + * @param key {string} - The key under which the client is (or is to be) stored. + * + * @returns {Client} - The requested client. + */ + private getClient; + /** + * Move current clients to previous, create a new map for current. + * + * This function is called every `windowMs`. + */ + private clearExpired; +} + +export { + rateLimit as default, +}; + +export {}; diff --git a/node_modules/express-rate-limit/dist/index.mjs b/node_modules/express-rate-limit/dist/index.mjs new file mode 100644 index 0000000..f8b70ce --- /dev/null +++ b/node_modules/express-rate-limit/dist/index.mjs @@ -0,0 +1,809 @@ +// source/headers.ts +import { Buffer } from "buffer"; +import { createHash } from "crypto"; +var SUPPORTED_DRAFT_VERSIONS = ["draft-6", "draft-7", "draft-8"]; +var getResetSeconds = (resetTime, windowMs) => { + let resetSeconds = void 0; + if (resetTime) { + const deltaSeconds = Math.ceil((resetTime.getTime() - Date.now()) / 1e3); + resetSeconds = Math.max(0, deltaSeconds); + } else if (windowMs) { + resetSeconds = Math.ceil(windowMs / 1e3); + } + return resetSeconds; +}; +var getPartitionKey = (key) => { + const hash = createHash("sha256"); + hash.update(key); + const partitionKey = hash.digest("hex").slice(0, 12); + return Buffer.from(partitionKey).toString("base64"); +}; +var setLegacyHeaders = (response, info) => { + if (response.headersSent) + return; + response.setHeader("X-RateLimit-Limit", info.limit.toString()); + response.setHeader("X-RateLimit-Remaining", info.remaining.toString()); + if (info.resetTime instanceof Date) { + response.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString()); + response.setHeader( + "X-RateLimit-Reset", + Math.ceil(info.resetTime.getTime() / 1e3).toString() + ); + } +}; +var setDraft6Headers = (response, info, windowMs) => { + if (response.headersSent) + return; + const windowSeconds = Math.ceil(windowMs / 1e3); + const resetSeconds = getResetSeconds(info.resetTime); + response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`); + response.setHeader("RateLimit-Limit", info.limit.toString()); + response.setHeader("RateLimit-Remaining", info.remaining.toString()); + if (resetSeconds) + response.setHeader("RateLimit-Reset", resetSeconds.toString()); +}; +var setDraft7Headers = (response, info, windowMs) => { + if (response.headersSent) + return; + const windowSeconds = Math.ceil(windowMs / 1e3); + const resetSeconds = getResetSeconds(info.resetTime, windowMs); + response.setHeader("RateLimit-Policy", `${info.limit};w=${windowSeconds}`); + response.setHeader( + "RateLimit", + `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}` + ); +}; +var setDraft8Headers = (response, info, windowMs, name, key) => { + if (response.headersSent) + return; + const windowSeconds = Math.ceil(windowMs / 1e3); + const resetSeconds = getResetSeconds(info.resetTime, windowMs); + const partitionKey = getPartitionKey(key); + const policy = `q=${info.limit}; w=${windowSeconds}; pk=:${partitionKey}:`; + const header = `r=${info.remaining}; t=${resetSeconds}`; + response.append("RateLimit-Policy", `"${name}"; ${policy}`); + response.append("RateLimit", `"${name}"; ${header}`); +}; +var setRetryAfterHeader = (response, info, windowMs) => { + if (response.headersSent) + return; + const resetSeconds = getResetSeconds(info.resetTime, windowMs); + response.setHeader("Retry-After", resetSeconds.toString()); +}; + +// source/validations.ts +import { isIP } from "net"; +var ValidationError = class extends Error { + /** + * The code must be a string, in snake case and all capital, that starts with + * the substring `ERR_ERL_`. + * + * The message must be a string, starting with an uppercase character, + * describing the issue in detail. + */ + constructor(code, message) { + const url = `https://express-rate-limit.github.io/${code}/`; + super(`${message} See ${url} for more information.`); + this.name = this.constructor.name; + this.code = code; + this.help = url; + } +}; +var ChangeWarning = class extends ValidationError { +}; +var usedStores = /* @__PURE__ */ new Set(); +var singleCountKeys = /* @__PURE__ */ new WeakMap(); +var validations = { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + enabled: { + default: true + }, + // Should be EnabledValidations type, but that's a circular reference + disable() { + for (const k of Object.keys(this.enabled)) + this.enabled[k] = false; + }, + /** + * Checks whether the IP address is valid, and that it does not have a port + * number in it. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_invalid_ip_address. + * + * @param ip {string | undefined} - The IP address provided by Express as request.ip. + * + * @returns {void} + */ + ip(ip) { + if (ip === void 0) { + throw new ValidationError( + "ERR_ERL_UNDEFINED_IP_ADDRESS", + `An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.` + ); + } + if (!isIP(ip)) { + throw new ValidationError( + "ERR_ERL_INVALID_IP_ADDRESS", + `An invalid 'request.ip' (${ip}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.` + ); + } + }, + /** + * Makes sure the trust proxy setting is not set to `true`. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_permissive_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + trustProxy(request) { + if (request.app.get("trust proxy") === true) { + throw new ValidationError( + "ERR_ERL_PERMISSIVE_TRUST_PROXY", + `The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.` + ); + } + }, + /** + * Makes sure the trust proxy setting is set in case the `X-Forwarded-For` + * header is present. + * + * See https://github.com/express-rate-limit/express-rate-limit/wiki/Error-Codes#err_erl_unset_trust_proxy. + * + * @param request {Request} - The Express request object. + * + * @returns {void} + */ + xForwardedForHeader(request) { + if (request.headers["x-forwarded-for"] && request.app.get("trust proxy") === false) { + throw new ValidationError( + "ERR_ERL_UNEXPECTED_X_FORWARDED_FOR", + `The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.` + ); + } + }, + /** + * Ensures totalHits value from store is a positive integer. + * + * @param hits {any} - The `totalHits` returned by the store. + */ + positiveHits(hits) { + if (typeof hits !== "number" || hits < 1 || hits !== Math.round(hits)) { + throw new ValidationError( + "ERR_ERL_INVALID_HITS", + `The totalHits value returned from the store must be a positive integer, got ${hits}` + ); + } + }, + /** + * Ensures a single store instance is not used with multiple express-rate-limit instances + */ + unsharedStore(store) { + if (usedStores.has(store)) { + const maybeUniquePrefix = store?.localKeys ? "" : " (with a unique prefix)"; + throw new ValidationError( + "ERR_ERL_STORE_REUSE", + `A Store instance must not be shared across multiple rate limiters. Create a new instance of ${store.constructor.name}${maybeUniquePrefix} for each limiter instead.` + ); + } + usedStores.add(store); + }, + /** + * Ensures a given key is incremented only once per request. + * + * @param request {Request} - The Express request object. + * @param store {Store} - The store class. + * @param key {string} - The key used to store the client's hit count. + * + * @returns {void} + */ + singleCount(request, store, key) { + let storeKeys = singleCountKeys.get(request); + if (!storeKeys) { + storeKeys = /* @__PURE__ */ new Map(); + singleCountKeys.set(request, storeKeys); + } + const storeKey = store.localKeys ? store : store.constructor.name; + let keys = storeKeys.get(storeKey); + if (!keys) { + keys = []; + storeKeys.set(storeKey, keys); + } + const prefixedKey = `${store.prefix ?? ""}${key}`; + if (keys.includes(prefixedKey)) { + throw new ValidationError( + "ERR_ERL_DOUBLE_COUNT", + `The hit count for ${key} was incremented more than once for a single request.` + ); + } + keys.push(prefixedKey); + }, + /** + * Warns the user that the behaviour for `max: 0` / `limit: 0` is + * changing in the next major release. + * + * @param limit {number} - The maximum number of hits per client. + * + * @returns {void} + */ + limit(limit) { + if (limit === 0) { + throw new ChangeWarning( + "WRN_ERL_MAX_ZERO", + `Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7` + ); + } + }, + /** + * Warns the user that the `draft_polli_ratelimit_headers` option is deprecated + * and will be removed in the next major release. + * + * @param draft_polli_ratelimit_headers {any | undefined} - The now-deprecated setting that was used to enable standard headers. + * + * @returns {void} + */ + draftPolliHeaders(draft_polli_ratelimit_headers) { + if (draft_polli_ratelimit_headers) { + throw new ChangeWarning( + "WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS", + `The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.` + ); + } + }, + /** + * Warns the user that the `onLimitReached` option is deprecated and + * will be removed in the next major release. + * + * @param onLimitReached {any | undefined} - The maximum number of hits per client. + * + * @returns {void} + */ + onLimitReached(onLimitReached) { + if (onLimitReached) { + throw new ChangeWarning( + "WRN_ERL_DEPRECATED_ON_LIMIT_REACHED", + `The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7.` + ); + } + }, + /** + * Warns the user when an invalid/unsupported version of the draft spec is passed. + * + * @param version {any | undefined} - The version passed by the user. + * + * @returns {void} + */ + headersDraftVersion(version) { + if (typeof version !== "string" || !SUPPORTED_DRAFT_VERSIONS.includes(version)) { + const versionString = SUPPORTED_DRAFT_VERSIONS.join(", "); + throw new ValidationError( + "ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION", + `standardHeaders: only the following versions of the IETF draft specification are supported: ${versionString}.` + ); + } + }, + /** + * Warns the user when the selected headers option requires a reset time but + * the store does not provide one. + * + * @param resetTime {Date | undefined} - The timestamp when the client's hit count will be reset. + * + * @returns {void} + */ + headersResetTime(resetTime) { + if (!resetTime) { + throw new ValidationError( + "ERR_ERL_HEADERS_NO_RESET", + `standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.` + ); + } + }, + /** + * Checks the options.validate setting to ensure that only recognized + * validations are enabled or disabled. + * + * If any unrecognized values are found, an error is logged that + * includes the list of supported vaidations. + */ + validationsConfig() { + const supportedValidations = Object.keys(this).filter( + (k) => !["enabled", "disable"].includes(k) + ); + supportedValidations.push("default"); + for (const key of Object.keys(this.enabled)) { + if (!supportedValidations.includes(key)) { + throw new ValidationError( + "ERR_ERL_UNKNOWN_VALIDATION", + `options.validate.${key} is not recognized. Supported validate options are: ${supportedValidations.join( + ", " + )}.` + ); + } + } + }, + /** + * Checks to see if the instance was created inside of a request handler, + * which would prevent it from working correctly, with the default memory + * store (or any other store with localKeys.) + */ + creationStack(store) { + const { stack } = new Error( + "express-rate-limit validation check (set options.validate.creationStack=false to disable)" + ); + if (stack?.includes("Layer.handle [as handle_request]")) { + if (!store.localKeys) { + throw new ValidationError( + "ERR_ERL_CREATED_IN_REQUEST_HANDLER", + "express-rate-limit instance should *usually* be created at app initialization, not when responding to a request." + ); + } + throw new ValidationError( + "ERR_ERL_CREATED_IN_REQUEST_HANDLER", + `express-rate-limit instance should be created at app initialization, not when responding to a request.` + ); + } + } +}; +var getValidations = (_enabled) => { + let enabled; + if (typeof _enabled === "boolean") { + enabled = { + default: _enabled + }; + } else { + enabled = { + default: true, + ..._enabled + }; + } + const wrappedValidations = { + enabled + }; + for (const [name, validation] of Object.entries(validations)) { + if (typeof validation === "function") + wrappedValidations[name] = (...args) => { + if (!(enabled[name] ?? enabled.default)) { + return; + } + try { + ; + validation.apply( + wrappedValidations, + args + ); + } catch (error) { + if (error instanceof ChangeWarning) + console.warn(error); + else + console.error(error); + } + }; + } + return wrappedValidations; +}; + +// source/memory-store.ts +var MemoryStore = class { + constructor() { + /** + * These two maps store usage (requests) and reset time by key (for example, IP + * addresses or API keys). + * + * They are split into two to avoid having to iterate through the entire set to + * determine which ones need reset. Instead, `Client`s are moved from `previous` + * to `current` as they hit the endpoint. Once `windowMs` has elapsed, all clients + * left in `previous`, i.e., those that have not made any recent requests, are + * known to be expired and can be deleted in bulk. + */ + this.previous = /* @__PURE__ */ new Map(); + this.current = /* @__PURE__ */ new Map(); + /** + * Confirmation that the keys incremented in once instance of MemoryStore + * cannot affect other instances. + */ + this.localKeys = true; + } + /** + * Method that initializes the store. + * + * @param options {Options} - The options used to setup the middleware. + */ + init(options) { + this.windowMs = options.windowMs; + if (this.interval) + clearInterval(this.interval); + this.interval = setInterval(() => { + this.clearExpired(); + }, this.windowMs); + if (this.interval.unref) + this.interval.unref(); + } + /** + * Method to fetch a client's hit count and reset time. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo | undefined} - The number of hits and reset time for that client. + * + * @public + */ + async get(key) { + return this.current.get(key) ?? this.previous.get(key); + } + /** + * Method to increment a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. + * + * @public + */ + async increment(key) { + const client = this.getClient(key); + const now = Date.now(); + if (client.resetTime.getTime() <= now) { + this.resetClient(client, now); + } + client.totalHits++; + return client; + } + /** + * Method to decrement a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + async decrement(key) { + const client = this.getClient(key); + if (client.totalHits > 0) + client.totalHits--; + } + /** + * Method to reset a client's hit counter. + * + * @param key {string} - The identifier for a client. + * + * @public + */ + async resetKey(key) { + this.current.delete(key); + this.previous.delete(key); + } + /** + * Method to reset everyone's hit counter. + * + * @public + */ + async resetAll() { + this.current.clear(); + this.previous.clear(); + } + /** + * Method to stop the timer (if currently running) and prevent any memory + * leaks. + * + * @public + */ + shutdown() { + clearInterval(this.interval); + void this.resetAll(); + } + /** + * Recycles a client by setting its hit count to zero, and reset time to + * `windowMs` milliseconds from now. + * + * NOT to be confused with `#resetKey()`, which removes a client from both the + * `current` and `previous` maps. + * + * @param client {Client} - The client to recycle. + * @param now {number} - The current time, to which the `windowMs` is added to get the `resetTime` for the client. + * + * @return {Client} - The modified client that was passed in, to allow for chaining. + */ + resetClient(client, now = Date.now()) { + client.totalHits = 0; + client.resetTime.setTime(now + this.windowMs); + return client; + } + /** + * Retrieves or creates a client, given a key. Also ensures that the client being + * returned is in the `current` map. + * + * @param key {string} - The key under which the client is (or is to be) stored. + * + * @returns {Client} - The requested client. + */ + getClient(key) { + if (this.current.has(key)) + return this.current.get(key); + let client; + if (this.previous.has(key)) { + client = this.previous.get(key); + this.previous.delete(key); + } else { + client = { totalHits: 0, resetTime: /* @__PURE__ */ new Date() }; + this.resetClient(client); + } + this.current.set(key, client); + return client; + } + /** + * Move current clients to previous, create a new map for current. + * + * This function is called every `windowMs`. + */ + clearExpired() { + this.previous = this.current; + this.current = /* @__PURE__ */ new Map(); + } +}; + +// source/lib.ts +var isLegacyStore = (store) => ( + // Check that `incr` exists but `increment` does not - store authors might want + // to keep both around for backwards compatibility. + typeof store.incr === "function" && typeof store.increment !== "function" +); +var promisifyStore = (passedStore) => { + if (!isLegacyStore(passedStore)) { + return passedStore; + } + const legacyStore = passedStore; + class PromisifiedStore { + async increment(key) { + return new Promise((resolve, reject) => { + legacyStore.incr( + key, + (error, totalHits, resetTime) => { + if (error) + reject(error); + resolve({ totalHits, resetTime }); + } + ); + }); + } + async decrement(key) { + return legacyStore.decrement(key); + } + async resetKey(key) { + return legacyStore.resetKey(key); + } + /* istanbul ignore next */ + async resetAll() { + if (typeof legacyStore.resetAll === "function") + return legacyStore.resetAll(); + } + } + return new PromisifiedStore(); +}; +var getOptionsFromConfig = (config) => { + const { validations: validations2, ...directlyPassableEntries } = config; + return { + ...directlyPassableEntries, + validate: validations2.enabled + }; +}; +var omitUndefinedOptions = (passedOptions) => { + const omittedOptions = {}; + for (const k of Object.keys(passedOptions)) { + const key = k; + if (passedOptions[key] !== void 0) { + omittedOptions[key] = passedOptions[key]; + } + } + return omittedOptions; +}; +var parseOptions = (passedOptions) => { + const notUndefinedOptions = omitUndefinedOptions(passedOptions); + const validations2 = getValidations(notUndefinedOptions?.validate ?? true); + validations2.validationsConfig(); + validations2.draftPolliHeaders( + // @ts-expect-error see the note above. + notUndefinedOptions.draft_polli_ratelimit_headers + ); + validations2.onLimitReached(notUndefinedOptions.onLimitReached); + let standardHeaders = notUndefinedOptions.standardHeaders ?? false; + if (standardHeaders === true) + standardHeaders = "draft-6"; + const config = { + windowMs: 60 * 1e3, + limit: passedOptions.max ?? 5, + // `max` is deprecated, but support it anyways. + message: "Too many requests, please try again later.", + statusCode: 429, + legacyHeaders: passedOptions.headers ?? true, + identifier(request, _response) { + let duration = ""; + const property = config.requestPropertyName; + const { limit } = request[property]; + const seconds = config.windowMs / 1e3; + const minutes = config.windowMs / (1e3 * 60); + const hours = config.windowMs / (1e3 * 60 * 60); + const days = config.windowMs / (1e3 * 60 * 60 * 24); + if (seconds < 60) + duration = `${seconds}sec`; + else if (minutes < 60) + duration = `${minutes}min`; + else if (hours < 24) + duration = `${hours}hr${hours > 1 ? "s" : ""}`; + else + duration = `${days}day${days > 1 ? "s" : ""}`; + return `${limit}-in-${duration}`; + }, + requestPropertyName: "rateLimit", + skipFailedRequests: false, + skipSuccessfulRequests: false, + requestWasSuccessful: (_request, response) => response.statusCode < 400, + skip: (_request, _response) => false, + keyGenerator(request, _response) { + validations2.ip(request.ip); + validations2.trustProxy(request); + validations2.xForwardedForHeader(request); + return request.ip; + }, + async handler(request, response, _next, _optionsUsed) { + response.status(config.statusCode); + const message = typeof config.message === "function" ? await config.message( + request, + response + ) : config.message; + if (!response.writableEnded) { + response.send(message); + } + }, + passOnStoreError: false, + // Allow the default options to be overriden by the passed options. + ...notUndefinedOptions, + // `standardHeaders` is resolved into a draft version above, use that. + standardHeaders, + // Note that this field is declared after the user's options are spread in, + // so that this field doesn't get overriden with an un-promisified store! + store: promisifyStore(notUndefinedOptions.store ?? new MemoryStore()), + // Print an error to the console if a few known misconfigurations are detected. + validations: validations2 + }; + if (typeof config.store.increment !== "function" || typeof config.store.decrement !== "function" || typeof config.store.resetKey !== "function" || config.store.resetAll !== void 0 && typeof config.store.resetAll !== "function" || config.store.init !== void 0 && typeof config.store.init !== "function") { + throw new TypeError( + "An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface." + ); + } + return config; +}; +var handleAsyncErrors = (fn) => async (request, response, next) => { + try { + await Promise.resolve(fn(request, response, next)).catch(next); + } catch (error) { + next(error); + } +}; +var rateLimit = (passedOptions) => { + const config = parseOptions(passedOptions ?? {}); + const options = getOptionsFromConfig(config); + config.validations.creationStack(config.store); + config.validations.unsharedStore(config.store); + if (typeof config.store.init === "function") + config.store.init(options); + const middleware = handleAsyncErrors( + async (request, response, next) => { + const skip = await config.skip(request, response); + if (skip) { + next(); + return; + } + const augmentedRequest = request; + const key = await config.keyGenerator(request, response); + let totalHits = 0; + let resetTime; + try { + const incrementResult = await config.store.increment(key); + totalHits = incrementResult.totalHits; + resetTime = incrementResult.resetTime; + } catch (error) { + if (config.passOnStoreError) { + console.error( + "express-rate-limit: error from store, allowing request without rate-limiting.", + error + ); + next(); + return; + } + throw error; + } + config.validations.positiveHits(totalHits); + config.validations.singleCount(request, config.store, key); + const retrieveLimit = typeof config.limit === "function" ? config.limit(request, response) : config.limit; + const limit = await retrieveLimit; + config.validations.limit(limit); + const info = { + limit, + used: totalHits, + remaining: Math.max(limit - totalHits, 0), + resetTime + }; + Object.defineProperty(info, "current", { + configurable: false, + enumerable: false, + value: totalHits + }); + augmentedRequest[config.requestPropertyName] = info; + if (config.legacyHeaders && !response.headersSent) { + setLegacyHeaders(response, info); + } + if (config.standardHeaders && !response.headersSent) { + switch (config.standardHeaders) { + case "draft-6": { + setDraft6Headers(response, info, config.windowMs); + break; + } + case "draft-7": { + config.validations.headersResetTime(info.resetTime); + setDraft7Headers(response, info, config.windowMs); + break; + } + case "draft-8": { + const retrieveName = typeof config.identifier === "function" ? config.identifier(request, response) : config.identifier; + const name = await retrieveName; + config.validations.headersResetTime(info.resetTime); + setDraft8Headers(response, info, config.windowMs, name, key); + break; + } + default: { + config.validations.headersDraftVersion(config.standardHeaders); + break; + } + } + } + if (config.skipFailedRequests || config.skipSuccessfulRequests) { + let decremented = false; + const decrementKey = async () => { + if (!decremented) { + await config.store.decrement(key); + decremented = true; + } + }; + if (config.skipFailedRequests) { + response.on("finish", async () => { + if (!await config.requestWasSuccessful(request, response)) + await decrementKey(); + }); + response.on("close", async () => { + if (!response.writableEnded) + await decrementKey(); + }); + response.on("error", async () => { + await decrementKey(); + }); + } + if (config.skipSuccessfulRequests) { + response.on("finish", async () => { + if (await config.requestWasSuccessful(request, response)) + await decrementKey(); + }); + } + } + config.validations.disable(); + if (totalHits > limit) { + if (config.legacyHeaders || config.standardHeaders) { + setRetryAfterHeader(response, info, config.windowMs); + } + config.handler(request, response, next, options); + return; + } + next(); + } + ); + const getThrowFn = () => { + throw new Error("The current store does not support the get/getKey method"); + }; + middleware.resetKey = config.store.resetKey.bind(config.store); + middleware.getKey = typeof config.store.get === "function" ? config.store.get.bind(config.store) : getThrowFn; + return middleware; +}; +var lib_default = rateLimit; +export { + MemoryStore, + lib_default as default, + lib_default as rateLimit +}; diff --git a/node_modules/express-rate-limit/package.json b/node_modules/express-rate-limit/package.json new file mode 100644 index 0000000..1783725 --- /dev/null +++ b/node_modules/express-rate-limit/package.json @@ -0,0 +1,133 @@ +{ + "name": "express-rate-limit", + "version": "7.5.0", + "description": "Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.", + "author": { + "name": "Nathan Friedly", + "url": "http://nfriedly.com/" + }, + "license": "MIT", + "homepage": "https://github.com/express-rate-limit/express-rate-limit", + "repository": { + "type": "git", + "url": "git+https://github.com/express-rate-limit/express-rate-limit.git" + }, + "funding": "https://github.com/sponsors/express-rate-limit", + "keywords": [ + "express-rate-limit", + "express", + "rate", + "limit", + "ratelimit", + "rate-limit", + "middleware", + "ip", + "auth", + "authorization", + "security", + "brute", + "force", + "bruteforce", + "brute-force", + "attack" + ], + "type": "module", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "files": [ + "dist/", + "tsconfig.json" + ], + "engines": { + "node": ">= 16" + }, + "scripts": { + "clean": "del-cli dist/ coverage/ *.log *.tmp *.bak *.tgz", + "build:cjs": "esbuild --platform=node --bundle --target=es2022 --format=cjs --outfile=dist/index.cjs --footer:js=\"module.exports = rateLimit; module.exports.default = rateLimit; module.exports.rateLimit = rateLimit; module.exports.MemoryStore = MemoryStore;\" source/index.ts", + "build:esm": "esbuild --platform=node --bundle --target=es2022 --format=esm --outfile=dist/index.mjs source/index.ts", + "build:types": "dts-bundle-generator --out-file=dist/index.d.ts source/index.ts && cp dist/index.d.ts dist/index.d.cts && cp dist/index.d.ts dist/index.d.mts", + "compile": "run-s clean build:*", + "docs": "cd docs && mintlify dev", + "lint:code": "xo", + "lint:rest": "prettier --check .", + "lint": "run-s lint:*", + "format:code": "xo --fix", + "format:rest": "prettier --write .", + "format": "run-s format:*", + "test:lib": "jest", + "test:ext": "cd test/external/ && bash run-all-tests", + "test": "run-s lint test:lib", + "pre-commit": "lint-staged", + "prepare": "run-s compile && husky install config/husky" + }, + "peerDependencies": { + "express": "^4.11 || 5 || ^5.0.0-beta.1" + }, + "devDependencies": { + "@express-rate-limit/prettier": "1.1.1", + "@express-rate-limit/tsconfig": "1.0.2", + "@jest/globals": "29.7.0", + "@types/express": "4.17.20", + "@types/jest": "29.5.6", + "@types/node": "20.8.7", + "@types/supertest": "2.0.15", + "del-cli": "5.1.0", + "dts-bundle-generator": "8.0.1", + "esbuild": "0.19.5", + "express": "4.21.1", + "husky": "8.0.3", + "jest": "29.7.0", + "lint-staged": "15.0.2", + "mintlify": "4.0.63", + "npm-run-all": "4.1.5", + "ratelimit-header-parser": "0.1.0", + "supertest": "6.3.3", + "ts-jest": "29.1.1", + "ts-node": "10.9.1", + "typescript": "5.2.2", + "xo": "0.56.0" + }, + "xo": { + "prettier": true, + "rules": { + "@typescript-eslint/no-empty-function": 0, + "@typescript-eslint/no-dynamic-delete": 0, + "@typescript-eslint/no-confusing-void-expression": 0, + "@typescript-eslint/consistent-indexed-object-style": [ + "error", + "index-signature" + ], + "n/no-unsupported-features/es-syntax": 0 + }, + "overrides": [ + { + "files": "test/library/*.ts", + "rules": { + "@typescript-eslint/no-unsafe-argument": 0, + "@typescript-eslint/no-unsafe-assignment": 0 + } + } + ], + "ignore": [ + "test/external" + ] + }, + "prettier": "@express-rate-limit/prettier", + "lint-staged": { + "{source,test}/**/*.ts": "xo --fix", + "**/*.{json,yaml,md}": "prettier --write " + } +} diff --git a/node_modules/express-rate-limit/tsconfig.json b/node_modules/express-rate-limit/tsconfig.json new file mode 100644 index 0000000..52b6ff1 --- /dev/null +++ b/node_modules/express-rate-limit/tsconfig.json @@ -0,0 +1,8 @@ +{ + "include": ["source/"], + "exclude": ["node_modules/"], + "extends": "@express-rate-limit/tsconfig", + "compilerOptions": { + "target": "ES2020" + } +} diff --git a/node_modules/express-session/index.js b/node_modules/express-session/index.js new file mode 100644 index 0000000..d41b237 --- /dev/null +++ b/node_modules/express-session/index.js @@ -0,0 +1,693 @@ +/*! + * express-session + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('safe-buffer').Buffer +var cookie = require('cookie'); +var crypto = require('crypto') +var debug = require('debug')('express-session'); +var deprecate = require('depd')('express-session'); +var onHeaders = require('on-headers') +var parseUrl = require('parseurl'); +var signature = require('cookie-signature') +var uid = require('uid-safe').sync + +var Cookie = require('./session/cookie') +var MemoryStore = require('./session/memory') +var Session = require('./session/session') +var Store = require('./session/store') + +// environment + +var env = process.env.NODE_ENV; + +/** + * Expose the middleware. + */ + +exports = module.exports = session; + +/** + * Expose constructors. + */ + +exports.Store = Store; +exports.Cookie = Cookie; +exports.Session = Session; +exports.MemoryStore = MemoryStore; + +/** + * Warning message for `MemoryStore` usage in production. + * @private + */ + +var warning = 'Warning: connect.session() MemoryStore is not\n' + + 'designed for a production environment, as it will leak\n' + + 'memory, and will not scale past a single process.'; + +/** + * Node.js 0.8+ async implementation. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Setup session store with the given `options`. + * + * @param {Object} [options] + * @param {Object} [options.cookie] Options for cookie + * @param {Function} [options.genid] + * @param {String} [options.name=connect.sid] Session ID cookie name + * @param {Boolean} [options.proxy] + * @param {Boolean} [options.resave] Resave unmodified sessions back to the store + * @param {Boolean} [options.rolling] Enable/disable rolling session expiration + * @param {Boolean} [options.saveUninitialized] Save uninitialized sessions to the store + * @param {String|Array} [options.secret] Secret for signing session ID + * @param {Object} [options.store=MemoryStore] Session store + * @param {String} [options.unset] + * @return {Function} middleware + * @public + */ + +function session(options) { + var opts = options || {} + + // get the cookie options + var cookieOptions = opts.cookie || {} + + // get the session id generate function + var generateId = opts.genid || generateSessionId + + // get the session cookie name + var name = opts.name || opts.key || 'connect.sid' + + // get the session store + var store = opts.store || new MemoryStore() + + // get the trust proxy setting + var trustProxy = opts.proxy + + // get the resave session option + var resaveSession = opts.resave; + + // get the rolling session option + var rollingSessions = Boolean(opts.rolling) + + // get the save uninitialized session option + var saveUninitializedSession = opts.saveUninitialized + + // get the cookie signing secret + var secret = opts.secret + + if (typeof generateId !== 'function') { + throw new TypeError('genid option must be a function'); + } + + if (resaveSession === undefined) { + deprecate('undefined resave option; provide resave option'); + resaveSession = true; + } + + if (saveUninitializedSession === undefined) { + deprecate('undefined saveUninitialized option; provide saveUninitialized option'); + saveUninitializedSession = true; + } + + if (opts.unset && opts.unset !== 'destroy' && opts.unset !== 'keep') { + throw new TypeError('unset option must be "destroy" or "keep"'); + } + + // TODO: switch to "destroy" on next major + var unsetDestroy = opts.unset === 'destroy' + + if (Array.isArray(secret) && secret.length === 0) { + throw new TypeError('secret option array must contain one or more strings'); + } + + if (secret && !Array.isArray(secret)) { + secret = [secret]; + } + + if (!secret) { + deprecate('req.secret; provide secret option'); + } + + // notify user that this store is not + // meant for a production environment + /* istanbul ignore next: not tested */ + if (env === 'production' && store instanceof MemoryStore) { + console.warn(warning); + } + + // generates the new session + store.generate = function(req){ + req.sessionID = generateId(req); + req.session = new Session(req); + req.session.cookie = new Cookie(cookieOptions); + + if (cookieOptions.secure === 'auto') { + req.session.cookie.secure = issecure(req, trustProxy); + } + }; + + var storeImplementsTouch = typeof store.touch === 'function'; + + // register event listeners for the store to track readiness + var storeReady = true + store.on('disconnect', function ondisconnect() { + storeReady = false + }) + store.on('connect', function onconnect() { + storeReady = true + }) + + return function session(req, res, next) { + // self-awareness + if (req.session) { + next() + return + } + + // Handle connection as if there is no session if + // the store has temporarily disconnected etc + if (!storeReady) { + debug('store is disconnected') + next() + return + } + + // pathname mismatch + var originalPath = parseUrl.original(req).pathname || '/' + if (originalPath.indexOf(cookieOptions.path || '/') !== 0) { + debug('pathname mismatch') + next() + return + } + + // ensure a secret is available or bail + if (!secret && !req.secret) { + next(new Error('secret option required for sessions')); + return; + } + + // backwards compatibility for signed cookies + // req.secret is passed from the cookie parser middleware + var secrets = secret || [req.secret]; + + var originalHash; + var originalId; + var savedHash; + var touched = false + + // expose store + req.sessionStore = store; + + // get the session ID from the cookie + var cookieId = req.sessionID = getcookie(req, name, secrets); + + // set-cookie + onHeaders(res, function(){ + if (!req.session) { + debug('no session'); + return; + } + + if (!shouldSetCookie(req)) { + return; + } + + // only send secure cookies via https + if (req.session.cookie.secure && !issecure(req, trustProxy)) { + debug('not secured'); + return; + } + + if (!touched) { + // touch session + req.session.touch() + touched = true + } + + // set cookie + try { + setcookie(res, name, req.sessionID, secrets[0], req.session.cookie.data) + } catch (err) { + defer(next, err) + } + }); + + // proxy end() to commit the session + var _end = res.end; + var _write = res.write; + var ended = false; + res.end = function end(chunk, encoding) { + if (ended) { + return false; + } + + ended = true; + + var ret; + var sync = true; + + function writeend() { + if (sync) { + ret = _end.call(res, chunk, encoding); + sync = false; + return; + } + + _end.call(res); + } + + function writetop() { + if (!sync) { + return ret; + } + + if (!res._header) { + res._implicitHeader() + } + + if (chunk == null) { + ret = true; + return ret; + } + + var contentLength = Number(res.getHeader('Content-Length')); + + if (!isNaN(contentLength) && contentLength > 0) { + // measure chunk + chunk = !Buffer.isBuffer(chunk) + ? Buffer.from(chunk, encoding) + : chunk; + encoding = undefined; + + if (chunk.length !== 0) { + debug('split response'); + ret = _write.call(res, chunk.slice(0, chunk.length - 1)); + chunk = chunk.slice(chunk.length - 1, chunk.length); + return ret; + } + } + + ret = _write.call(res, chunk, encoding); + sync = false; + + return ret; + } + + if (shouldDestroy(req)) { + // destroy session + debug('destroying'); + store.destroy(req.sessionID, function ondestroy(err) { + if (err) { + defer(next, err); + } + + debug('destroyed'); + writeend(); + }); + + return writetop(); + } + + // no session to save + if (!req.session) { + debug('no session'); + return _end.call(res, chunk, encoding); + } + + if (!touched) { + // touch session + req.session.touch() + touched = true + } + + if (shouldSave(req)) { + req.session.save(function onsave(err) { + if (err) { + defer(next, err); + } + + writeend(); + }); + + return writetop(); + } else if (storeImplementsTouch && shouldTouch(req)) { + // store implements touch method + debug('touching'); + store.touch(req.sessionID, req.session, function ontouch(err) { + if (err) { + defer(next, err); + } + + debug('touched'); + writeend(); + }); + + return writetop(); + } + + return _end.call(res, chunk, encoding); + }; + + // generate the session + function generate() { + store.generate(req); + originalId = req.sessionID; + originalHash = hash(req.session); + wrapmethods(req.session); + } + + // inflate the session + function inflate (req, sess) { + store.createSession(req, sess) + originalId = req.sessionID + originalHash = hash(sess) + + if (!resaveSession) { + savedHash = originalHash + } + + wrapmethods(req.session) + } + + function rewrapmethods (sess, callback) { + return function () { + if (req.session !== sess) { + wrapmethods(req.session) + } + + callback.apply(this, arguments) + } + } + + // wrap session methods + function wrapmethods(sess) { + var _reload = sess.reload + var _save = sess.save; + + function reload(callback) { + debug('reloading %s', this.id) + _reload.call(this, rewrapmethods(this, callback)) + } + + function save() { + debug('saving %s', this.id); + savedHash = hash(this); + _save.apply(this, arguments); + } + + Object.defineProperty(sess, 'reload', { + configurable: true, + enumerable: false, + value: reload, + writable: true + }) + + Object.defineProperty(sess, 'save', { + configurable: true, + enumerable: false, + value: save, + writable: true + }); + } + + // check if session has been modified + function isModified(sess) { + return originalId !== sess.id || originalHash !== hash(sess); + } + + // check if session has been saved + function isSaved(sess) { + return originalId === sess.id && savedHash === hash(sess); + } + + // determine if session should be destroyed + function shouldDestroy(req) { + return req.sessionID && unsetDestroy && req.session == null; + } + + // determine if session should be saved to store + function shouldSave(req) { + // cannot set cookie without a session ID + if (typeof req.sessionID !== 'string') { + debug('session ignored because of bogus req.sessionID %o', req.sessionID); + return false; + } + + return !saveUninitializedSession && !savedHash && cookieId !== req.sessionID + ? isModified(req.session) + : !isSaved(req.session) + } + + // determine if session should be touched + function shouldTouch(req) { + // cannot set cookie without a session ID + if (typeof req.sessionID !== 'string') { + debug('session ignored because of bogus req.sessionID %o', req.sessionID); + return false; + } + + return cookieId === req.sessionID && !shouldSave(req); + } + + // determine if cookie should be set on response + function shouldSetCookie(req) { + // cannot set cookie without a session ID + if (typeof req.sessionID !== 'string') { + return false; + } + + return cookieId !== req.sessionID + ? saveUninitializedSession || isModified(req.session) + : rollingSessions || req.session.cookie.expires != null && isModified(req.session); + } + + // generate a session if the browser doesn't send a sessionID + if (!req.sessionID) { + debug('no SID sent, generating session'); + generate(); + next(); + return; + } + + // generate the session object + debug('fetching %s', req.sessionID); + store.get(req.sessionID, function(err, sess){ + // error handling + if (err && err.code !== 'ENOENT') { + debug('error %j', err); + next(err) + return + } + + try { + if (err || !sess) { + debug('no session found') + generate() + } else { + debug('session found') + inflate(req, sess) + } + } catch (e) { + next(e) + return + } + + next() + }); + }; +}; + +/** + * Generate a session ID for a new session. + * + * @return {String} + * @private + */ + +function generateSessionId(sess) { + return uid(24); +} + +/** + * Get the session ID cookie from request. + * + * @return {string} + * @private + */ + +function getcookie(req, name, secrets) { + var header = req.headers.cookie; + var raw; + var val; + + // read from cookie header + if (header) { + var cookies = cookie.parse(header); + + raw = cookies[name]; + + if (raw) { + if (raw.substr(0, 2) === 's:') { + val = unsigncookie(raw.slice(2), secrets); + + if (val === false) { + debug('cookie signature invalid'); + val = undefined; + } + } else { + debug('cookie unsigned') + } + } + } + + // back-compat read from cookieParser() signedCookies data + if (!val && req.signedCookies) { + val = req.signedCookies[name]; + + if (val) { + deprecate('cookie should be available in req.headers.cookie'); + } + } + + // back-compat read from cookieParser() cookies data + if (!val && req.cookies) { + raw = req.cookies[name]; + + if (raw) { + if (raw.substr(0, 2) === 's:') { + val = unsigncookie(raw.slice(2), secrets); + + if (val) { + deprecate('cookie should be available in req.headers.cookie'); + } + + if (val === false) { + debug('cookie signature invalid'); + val = undefined; + } + } else { + debug('cookie unsigned') + } + } + } + + return val; +} + +/** + * Hash the given `sess` object omitting changes to `.cookie`. + * + * @param {Object} sess + * @return {String} + * @private + */ + +function hash(sess) { + // serialize + var str = JSON.stringify(sess, function (key, val) { + // ignore sess.cookie property + if (this === sess && key === 'cookie') { + return + } + + return val + }) + + // hash + return crypto + .createHash('sha1') + .update(str, 'utf8') + .digest('hex') +} + +/** + * Determine if request is secure. + * + * @param {Object} req + * @param {Boolean} [trustProxy] + * @return {Boolean} + * @private + */ + +function issecure(req, trustProxy) { + // socket is https server + if (req.connection && req.connection.encrypted) { + return true; + } + + // do not trust proxy + if (trustProxy === false) { + return false; + } + + // no explicit trust; try req.secure from express + if (trustProxy !== true) { + return req.secure === true + } + + // read the proto from x-forwarded-proto header + var header = req.headers['x-forwarded-proto'] || ''; + var index = header.indexOf(','); + var proto = index !== -1 + ? header.substr(0, index).toLowerCase().trim() + : header.toLowerCase().trim() + + return proto === 'https'; +} + +/** + * Set cookie on response. + * + * @private + */ + +function setcookie(res, name, val, secret, options) { + var signed = 's:' + signature.sign(val, secret); + var data = cookie.serialize(name, signed, options); + + debug('set-cookie %s', data); + + var prev = res.getHeader('Set-Cookie') || [] + var header = Array.isArray(prev) ? prev.concat(data) : [prev, data]; + + res.setHeader('Set-Cookie', header) +} + +/** + * Verify and decode the given `val` with `secrets`. + * + * @param {String} val + * @param {Array} secrets + * @returns {String|Boolean} + * @private + */ +function unsigncookie(val, secrets) { + for (var i = 0; i < secrets.length; i++) { + var result = signature.unsign(val, secrets[i]); + + if (result !== false) { + return result; + } + } + + return false; +} diff --git a/node_modules/express-session/node_modules/cookie-signature/index.js b/node_modules/express-session/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..336d487 --- /dev/null +++ b/node_modules/express-session/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String|NodeJS.ArrayBufferView|crypto.KeyObject} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' !== typeof val) throw new TypeError("Cookie value must be provided as a string."); + if (null == secret) throw new TypeError("Secret key must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String|NodeJS.ArrayBufferView|crypto.KeyObject} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' !== typeof val) throw new TypeError("Signed cookie string must be provided."); + if (null == secret) throw new TypeError("Secret key must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/node_modules/express-session/node_modules/cookie-signature/package.json b/node_modules/express-session/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..738487b --- /dev/null +++ b/node_modules/express-session/node_modules/cookie-signature/package.json @@ -0,0 +1,18 @@ +{ + "name": "cookie-signature", + "version": "1.0.7", + "description": "Sign and unsign cookies", + "keywords": ["cookie", "sign", "unsign"], + "author": "TJ Holowaychuk ", + "license": "MIT", + "repository": { "type": "git", "url": "https://github.com/visionmedia/node-cookie-signature.git"}, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "main": "index" +} \ No newline at end of file diff --git a/node_modules/express-session/node_modules/cookie/index.js b/node_modules/express-session/node_modules/cookie/index.js new file mode 100644 index 0000000..acd5acd --- /dev/null +++ b/node_modules/express-session/node_modules/cookie/index.js @@ -0,0 +1,335 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var __toString = Object.prototype.toString +var __hasOwnProperty = Object.prototype.hasOwnProperty + +/** + * RegExp to match cookie-name in RFC 6265 sec 4.1.1 + * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2 + * which has been replaced by the token definition in RFC 7230 appendix B. + * + * cookie-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / + * "*" / "+" / "-" / "." / "^" / "_" / + * "`" / "|" / "~" / DIGIT / ALPHA + */ + +var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** + * RegExp to match cookie-value in RFC 6265 sec 4.1.1 + * + * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + * ; US-ASCII characters excluding CTLs, + * ; whitespace DQUOTE, comma, semicolon, + * ; and backslash + */ + +var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/; + +/** + * RegExp to match domain-value in RFC 6265 sec 4.1.1 + * + * domain-value = + * ; defined in [RFC1034], Section 3.5, as + * ; enhanced by [RFC1123], Section 2.1 + * =