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AAC,eAAS,2BAA2B,OAAO,OAAO,IAElE,GAAG,SAAS,IACT,GAAI,GAAwB,eAAf,EAAM,KAEf,OADA,QAAQ,MAAM,MAAM,IAAI,wBAAwB,OAAO,2HAChD,QAAQ,KAAK,GAExB,QAAQ,MAAM,MAAM,IAAI,iGACxB,OAAO,MAAM,GACb,QAAQ,KAAK,EAAE","file":"/npm/cors-backdoor@1.0.6/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.37.0.\n * Original file: /npm/cors-backdoor@1.0.6/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","#! /usr/bin/env node\nconst program = require('commander');\nconst express = require('express');\nconst pino = require('pino');\nconst chalk = require('chalk');\nconst merge = require('lodash/merge');\nconst packageJson = require('./package');\nconst request = require('request');\nconst path = require('path');\nconst os = require('os');\n\n\n/**\n * Helper to get a list of available external network interfaces\n * to generate a list of URLs for the proxy server\n * @returns {Array<string>} A list of available local external network interfaces\n */\nfunction getLocalExternalInterfaces() {\n    const interfaces = os.networkInterfaces();\n    return Object.keys(interfaces).reduce((acc, key) => {\n        return acc.concat(interfaces[key].filter(({family}) => family.toLowerCase() === 'ipv4'));\n    }, []);\n}\n\n/**\n * @typedef HeaderOverrides\n * A key-value map where the key is the header name and the value determines the header value that will be used.\n * If the value is a string, the string value will be used for the header specified by the key.\n * If the value is undefined, the header is removed entirely\n * If the value is a function, the function is invoked for every request and it's return value will be used similar to\n * the rules above. The function will be passed the Express req object as it's first argument\n * @type Object\n */\n\n/**\n * @typedef Configuration\n * @type Object\n * @property {string} host - The host to proxy\n * @property {Number} [port] - The port to run the proxy server on\n * @property {string} [baseUrl] - The base URL to use for the proxied requests\n * @property {HeaderOverrides} [headers] - The header overrides Object\n * @property {Object} [debug] - The options to pass to pino\n */\n\n/**\n * Default configuration\n * @type {Configuration}\n */\nconst defaultConfig = {\n    baseUrl: '/',\n    port: 1234,\n    headers: {\n        'Access-Control-Allow-Origin': '*',\n        'Access-Control-Allow-Headers': function (req) {\n            return req.headers['access-control-request-headers'];\n        },\n        'X-Powered-By': 'cors-backdoor'\n    },\n    debug: {\n        name: 'cors-backdoor',\n        level: 'trace',\n        prettyPrint: false\n    }\n};\n\n// Parse the parameters\nprogram\n    .version(packageJson.version)\n    .option('-t, --target [target]', 'The URL to proxy')\n    .option('-p, --port [port]', 'The port to use. Defaults to 1234')\n    .option('-b, --base-url [baseUrl]')\n    .option('-c, --config [configPath]', 'A path to a JSON config file for advanced configuration')\n    .parse(process.argv);\n\nlet externalConfig = {};\n\nif (program.config) {\n    // Attempt to load external config if the config option is used\n    try {\n        externalConfig = require(path.resolve(process.cwd(), program.config));\n        console.log(chalk`\\n{gray Loaded config file} ✅ `);\n    } catch (e) {\n        console.error(chalk.red('Failed to load the specified external configuration file. ❌\\nResorting to default configuration'), e);\n    }\n}\n\n// Extract options parsed from the command line\nconst {target: cmdTarget, port: cmdPort, baseUrl: cmdBaseUrl} = program;\n\n// Create merged configuration: defaultConfig < cmdConfig < externalConfig\nconst config = merge({}, defaultConfig, {\n    target: cmdTarget,\n    port: cmdPort,\n    baseUrl: cmdBaseUrl\n}, externalConfig);\n\n// Use target, port, baseUrl from merged config\nlet {target, port, baseUrl} = config;\n\n// Create Logger Instance\nconst logger = pino(config.debug);\n\nif (!target) {\n    console.error(chalk.red('Missing `target` parameter. Aborting'));\n    process.exit(1);\n}\n\n// Normalise target URL - remove trailing slash\ntarget = target.replace(/\\/$/, '');\n\n\n// Create Express App\nconst proxy = express();\n\n// Middleware to add in res helper to override headers\nproxy.use((req, res, next) => {\n    res.applyHeaderOverrides = () => {\n\n        Object.keys(config.headers).forEach(key => {\n\n                // Normalise value to an array if it;s not already one\n                const values = Array.isArray(config.headers[key]) ? config.headers[key] : [config.headers[key]];\n\n                // Combine array values into a single comma separated list\n                const combinedValue = values\n                // If the item is a function, call it passing req as a parameter and use it's return value for the header value.\n                    .map(value => (typeof value === 'function' ? value(req, res) : value))\n                    // Remove any `undefined` values\n                    .filter(value => value !== undefined)\n                    // Join by `,`\n                    .join(',');\n\n                if (combinedValue) {\n                    // There is a valid value, set the header `key` to `combinedValue`\n                    res.setHeader(key, combinedValue);\n                } else {\n                    // No valid value was found. Remove the header\n                    res.removeHeader(key);\n                }\n            }\n        );\n\n        return res;\n    };\n    next();\n});\n\n// Respond to OPTIONS requests with a 200\nproxy.use((req, res, next) => {\n    if (req.method.toLowerCase() === 'options') {\n        return res.status(200).applyHeaderOverrides().send('');\n    }\n    next();\n});\n\n// Proxy other requests to target/baseURl\nproxy.use(`${baseUrl}`, (req, res) => {\n    const {method, path, originalUrl, body, headers} = req;\n\n    // Build target URL\n    const targetUrl = `${target}${req.url}`;\n\n    // Trace request information\n    logger.trace({\n        req: {method, path, originalUrl, body, headers},\n        targetUrl\n    }, 'Proxy Request: %s %s', method, originalUrl);\n\n    // Create a request stream to the target and pipe the request to it\n    const requestStream = req.pipe(request(targetUrl));\n\n    // Pipe the results of the request to the target to the response\n    const responseStream = requestStream.pipe(res);\n\n    // Apply the header overrides when the response stream is available\n    requestStream.on('response', res.applyHeaderOverrides);\n\n    // Report any errors from the request stream\n    requestStream.on('error', e => logger.error(e));\n\n    // Report any errors from the response stream\n    responseStream.on('error', e => logger.error(e));\n\n    // Log debug message when proxy is complete\n    responseStream.on('finish', () => logger.debug('Proxy Complete: %s %s', method, originalUrl));\n});\n\n// Start proxy server on the port derived from the merged config\nproxy.listen(config.port, () => {\n        console.log(chalk`\\n{green Backdoor to} {yellowBright ${target}} {green initialised on port} {yellowBright ${port}} 🐙`);\n        console.log(chalk`\\n{green Available Backdoor Interfaces:}`);\n        [{address: 'localhost'}, ...getLocalExternalInterfaces()]\n            .forEach(({address}) => console.log(chalk`\\n\\t🚪 {yellowBright http://${address}:${port}${baseUrl}}`));\n        console.log(`\\n`);\n        logger.info({config}, `Proxy server running on ${config.port}`);\n    })\n    .on('error', error => {\n        if (error && error.code === 'EADDRINUSE') {\n            console.error(chalk.red(`EADDRINUSE: The port ${config.port} is busy. Please release the port and try again or start cors-backdoor on a different port using the --port option`));\n            return process.exit(0);\n        }\n        console.error(chalk.red(`Unknown error: More details in the dump below. Please check your configuration and try again`));\n        logger.error(error);\n        process.exit(1);\n    });"]}