Repository: garygrossgarten/github-action-scp Branch: master Commit: ed477632dd30 Files: 17 Total size: 2.2 MB Directory structure: gitextract_06o2uh5w/ ├── .github/ │ └── workflows/ │ └── scp-example-workflow.yml ├── .gitignore ├── .node-version ├── .prettierignore ├── .prettierrc.json ├── LICENSE ├── action.yml ├── dist/ │ ├── build/ │ │ └── Release/ │ │ └── cpufeatures.node │ ├── index.js │ └── lib/ │ └── protocol/ │ └── crypto/ │ └── build/ │ └── Release/ │ └── sshcrypto.node ├── lib/ │ ├── index.js │ └── keyboard.js ├── package.json ├── readme.md ├── src/ │ ├── index.ts │ └── keyboard.ts └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/scp-example-workflow.yml ================================================ name: scp copy folder to remote via SSH on: push: branches: ['master'] workflow_dispatch: jobs: build: runs-on: ubuntu-latest env: CI: true LOCAL: test steps: - name: checkout uses: actions/checkout@v6 - name: setup demo run: | mkdir test touch test/oof.txt touch test/.dot.txt - name: Copy folder content recursively to remote uses: ./ with: local: test remote: scp/directory host: ${{ secrets.HOST }} username: ${{ secrets.SSH_USER }} privateKey: ${{ secrets.PRIVATE_KEY}} - name: Copy folder content recursively to remote (clean directory) uses: ./ with: local: test remote: scp/directory host: ${{ secrets.HOST }} username: ${{ secrets.SSH_USER }} privateKey: ${{ secrets.PRIVATE_KEY}} rmRemote: true dotfiles: true - name: Copy folder content recursively to remote (atomic put) uses: ./ with: local: test remote: scp/atomic host: ${{ secrets.HOST }} username: ${{ secrets.SSH_USER }} privateKey: ${{ secrets.PRIVATE_KEY}} rmRemote: true dotfiles: true atomicPut: true - name: Copy single file to remote uses: ./ with: local: test/oof.txt remote: scp/single/readme.md host: ${{ secrets.HOST }} username: ${{ secrets.SSH_USER }} privateKey: ${{ secrets.PRIVATE_KEY}} - name: Copy dotfile to remote uses: ./ with: local: test/.dot.txt remote: scp/single/.dot.txt host: ${{ secrets.HOST }} username: ${{ secrets.SSH_USER }} privateKey: ${{ secrets.PRIVATE_KEY}} dotfiles: true - name: Copy with user/pw uses: ./ with: local: test/oof.txt remote: scp/user/pw/oof.txt host: ${{ secrets.HOST }} username: ${{ secrets.SSH_USER }} password: ${{ secrets.PASSWORD }} - name: With ENV uses: ./ with: local: ${{ env.LOCAL }} remote: scp/directory host: ${{ secrets.HOST }} username: ${{ secrets.SSH_USER }} privateKey: ${{ secrets.PRIVATE_KEY}} rmRemote: true dotfiles: true ================================================ FILE: .gitignore ================================================ node_modules .env ================================================ FILE: .node-version ================================================ 24.14.0 ================================================ FILE: .prettierignore ================================================ dist/ lib/ node_modules/ ================================================ FILE: .prettierrc.json ================================================ { "printWidth": 80, "tabWidth": 2, "useTabs": false, "semi": true, "singleQuote": true, "trailingComma": "none", "bracketSpacing": false, "arrowParens": "avoid", "parser": "typescript" } ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 fivethree 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. ================================================ FILE: action.yml ================================================ name: Copy via ssh author: garygrossgarten description: Github Action to copy a folder to a remote server using SSH inputs: local: description: "Path to the local folder you want to copy." required: true remote: description: "Path on the remote server to copy to." required: true dotfiles: description: "Determines if files with leading dot (.) on folder copy is included" required: false default: false rmRemote: description: "If it is a directory, remote files in it will be deleted before the copy is started." required: false concurrency: description: "Number of concurrent file transfers." required: false default: 1 recursive: description: "Wether copy of directory should be recursive" required: false default: true verbose: description: "Log status of every file copy" required: false default: true host: description: "Hostname or IP address of the server." required: false default: "localhost" username: description: "Username for authentication." required: false port: description: "Port number of the server." required: false default: "22" privateKey: description: "File Location or string that contains a private key for either key-based or hostbased user authentication (OpenSSH format)" required: false password: description: "Password for password-based user authentication." required: false passphrase: description: "For an encrypted private key, this is the passphrase used to decrypt it." required: false tryKeyboard: description: "Try keyboard-interactive user authentication if primary user authentication method fails." required: false atomicPut: description: "Upload files to temporary file first, then rename once upload completed" required: false default: false runs: using: "node24" main: "dist/index.js" branding: color: "purple" icon: "copy" ================================================ FILE: dist/index.js ================================================ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 1188: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const core = __importStar(__nccwpck_require__(7484)); const node_ssh_1 = __nccwpck_require__(1227); const path_1 = __importDefault(__nccwpck_require__(6928)); const ssh2_streams_1 = __nccwpck_require__(4440); const fs_1 = __importDefault(__nccwpck_require__(9896)); const keyboard_1 = __nccwpck_require__(7615); const path_2 = __importDefault(__nccwpck_require__(6928)); function run() { return __awaiter(this, void 0, void 0, function* () { const host = core.getInput('host') || 'localhost'; const username = core.getInput('username'); const port = +core.getInput('port') || 22; const privateKey = core.getInput('privateKey'); const password = core.getInput('password'); const passphrase = core.getInput('passphrase'); const tryKeyboard = !!core.getInput('tryKeyboard'); const verbose = !!core.getInput('verbose') || true; const recursive = !!core.getInput('recursive') || true; const concurrency = +core.getInput('concurrency') || 1; const local = core.getInput('local'); const dotfiles = !!core.getInput('dotfiles') || true; const remote = core.getInput('remote'); const rmRemote = !!core.getInput('rmRemote') || false; const atomicPut = core.getInput('atomicPut'); if (atomicPut) { // patch SFTPStream to atomically rename files const originalFastPut = ssh2_streams_1.SFTPStream.prototype.fastPut; ssh2_streams_1.SFTPStream.prototype.fastPut = function (localPath, remotePath, opts, cb) { const parsedPath = path_2.default.posix.parse(remotePath); parsedPath.base = '.' + parsedPath.base; const tmpRemotePath = path_2.default.posix.format(parsedPath); const that = this; originalFastPut.apply(this, [ localPath, tmpRemotePath, opts, function (error, result) { if (error) { cb(error, result); } else { that.ext_openssh_rename(tmpRemotePath, remotePath, cb); } } ]); }; } try { const ssh = yield connect(host, username, port, privateKey, password, passphrase, tryKeyboard); yield scp(ssh, local, remote, dotfiles, concurrency, verbose, recursive, rmRemote); ssh.dispose(); } catch (err) { core.setFailed(err); } }); } function connect() { return __awaiter(this, arguments, void 0, function* (host = 'localhost', username, port = 22, privateKey, password, passphrase, tryKeyboard) { const ssh = new node_ssh_1.NodeSSH(); console.log(`Establishing a SSH connection to ${host}.`); try { const config = { host: host, port: port, username: username, password: password, passphrase: passphrase, tryKeyboard: tryKeyboard, onKeyboardInteractive: tryKeyboard ? (0, keyboard_1.keyboardFunction)(password) : null }; if (privateKey) { console.log('using provided private key'); config.privateKey = privateKey; } yield ssh.connect(config); console.log(`🤝 Connected to ${host}.`); } catch (err) { console.error(`⚠️ The GitHub Action couldn't connect to ${host}.`, err); core.setFailed(err.message); } return ssh; }); } function scp(ssh_1, local_1, remote_1) { return __awaiter(this, arguments, void 0, function* (ssh, local, remote, dotfiles = false, concurrency, verbose = true, recursive = true, rmRemote = false) { console.log(`Starting scp Action: ${local} to ${remote}`); try { if (isDirectory(local)) { if (rmRemote) { yield cleanDirectory(ssh, remote); } yield putDirectory(ssh, local, remote, dotfiles, concurrency, verbose, recursive); } else { yield putFile(ssh, local, remote, verbose); } ssh.dispose(); console.log('✅ scp Action finished.'); } catch (err) { console.error(`⚠️ An error happened:(.`, err.message, err.stack); ssh.dispose(); process.abort(); core.setFailed(err.message); } }); } function putDirectory(ssh_1, local_1, remote_1) { return __awaiter(this, arguments, void 0, function* (ssh, local, remote, dotfiles = false, concurrency = 3, verbose = false, recursive = true) { const failed = []; const successful = []; const status = yield ssh.putDirectory(local, remote, { recursive: recursive, concurrency: concurrency, validate: (path) => !path_1.default.basename(path).startsWith('.') || dotfiles, tick: function (localPath, remotePath, error) { if (error) { if (verbose) { console.log(`❕copy failed for ${localPath}.`); } failed.push({ local: localPath, remote: remotePath }); } else { if (verbose) { console.log(`✔ successfully copied ${localPath}.`); } successful.push({ local: localPath, remote: remotePath }); } } }); console.log(`The copy of directory ${local} was ${status ? 'successful' : 'unsuccessful'}.`); if (failed.length > 0) { console.log('failed transfers', failed.join(', ')); yield putMany(failed, (failed) => __awaiter(this, void 0, void 0, function* () { console.log(`Retrying to copy ${failed.local} to ${failed.remote}.`); yield putFile(ssh, failed.local, failed.remote, true); })); } }); } function cleanDirectory(ssh_1, remote_1) { return __awaiter(this, arguments, void 0, function* (ssh, remote, verbose = true) { try { yield ssh.execCommand(`rm -rf ${remote}/*`); if (verbose) { console.log(`✔ Successfully deleted all files of ${remote}.`); } } catch (error) { console.error(`⚠️ An error happened:(.`, error.message, error.stack); ssh.dispose(); core.setFailed(error.message); } }); } function putFile(ssh_1, local_1, remote_1) { return __awaiter(this, arguments, void 0, function* (ssh, local, remote, verbose = true) { try { yield ssh.putFile(local, remote); if (verbose) { console.log(`✔ Successfully copied file ${local} to remote ${remote}.`); } } catch (error) { console.error(`⚠️ An error happened:(.`, error.message, error.stack); ssh.dispose(); core.setFailed(error.message); } }); } function isDirectory(path) { return fs_1.default.existsSync(path) && fs_1.default.lstatSync(path).isDirectory(); } function putMany(array, asyncFunction) { return __awaiter(this, void 0, void 0, function* () { for (const el of array) { yield asyncFunction(el); } }); } process.on('uncaughtException', (err) => { if (err['code'] !== 'ECONNRESET') throw err; }); run(); /***/ }), /***/ 7615: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.keyboardFunction = void 0; const keyboardFunction = password => (name, instructions, instructionsLang, prompts, finish) => { if (prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password')) { finish([password]); } }; exports.keyboardFunction = keyboardFunction; /***/ }), /***/ 4914: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issueCommand = issueCommand; exports.issue = issue; const os = __importStar(__nccwpck_require__(857)); const utils_1 = __nccwpck_require__(302); /** * Issues a command to the GitHub Actions runner * * @param command - The command name to issue * @param properties - Additional properties for the command (key-value pairs) * @param message - The message to include with the command * @remarks * This function outputs a specially formatted string to stdout that the Actions * runner interprets as a command. These commands can control workflow behavior, * set outputs, create annotations, mask values, and more. * * Command Format: * ::name key=value,key=value::message * * @example * ```typescript * // Issue a warning annotation * issueCommand('warning', {}, 'This is a warning message'); * // Output: ::warning::This is a warning message * * // Set an environment variable * issueCommand('set-env', { name: 'MY_VAR' }, 'some value'); * // Output: ::set-env name=MY_VAR::some value * * // Add a secret mask * issueCommand('add-mask', {}, 'secretValue123'); * // Output: ::add-mask::secretValue123 * ``` * * @internal * This is an internal utility function that powers the public API functions * such as setSecret, warning, error, and exportVariable. */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + os.EOL); } function issue(name, message = '') { issueCommand(name, {}, message); } const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } function escapeData(s) { return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map /***/ }), /***/ 7484: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.ExitCode = void 0; exports.exportVariable = exportVariable; exports.setSecret = setSecret; exports.addPath = addPath; exports.getInput = getInput; exports.getMultilineInput = getMultilineInput; exports.getBooleanInput = getBooleanInput; exports.setOutput = setOutput; exports.setCommandEcho = setCommandEcho; exports.setFailed = setFailed; exports.isDebug = isDebug; exports.debug = debug; exports.error = error; exports.warning = warning; exports.notice = notice; exports.info = info; exports.startGroup = startGroup; exports.endGroup = endGroup; exports.group = group; exports.saveState = saveState; exports.getState = getState; exports.getIDToken = getIDToken; const command_1 = __nccwpck_require__(4914); const file_command_1 = __nccwpck_require__(4753); const utils_1 = __nccwpck_require__(302); const os = __importStar(__nccwpck_require__(857)); const path = __importStar(__nccwpck_require__(6928)); const oidc_utils_1 = __nccwpck_require__(5306); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode || (exports.ExitCode = ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { const convertedVal = (0, utils_1.toCommandValue)(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); } (0, command_1.issueCommand)('set-env', { name }, convertedVal); } /** * Registers a secret which will get masked from logs * * @param secret - Value of the secret to be masked * @remarks * This function instructs the Actions runner to mask the specified value in any * logs produced during the workflow run. Once registered, the secret value will * be replaced with asterisks (***) whenever it appears in console output, logs, * or error messages. * * This is useful for protecting sensitive information such as: * - API keys * - Access tokens * - Authentication credentials * - URL parameters containing signatures (SAS tokens) * * Note that masking only affects future logs; any previous appearances of the * secret in logs before calling this function will remain unmasked. * * @example * ```typescript * // Register an API token as a secret * const apiToken = "abc123xyz456"; * setSecret(apiToken); * * // Now any logs containing this value will show *** instead * console.log(`Using token: ${apiToken}`); // Outputs: "Using token: ***" * ``` */ function setSecret(secret) { (0, command_1.issueCommand)('add-mask', {}, secret); } /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { (0, file_command_1.issueFileCommand)('PATH', inputPath); } else { (0, command_1.issueCommand)('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } /** * Gets the value of an input. * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. * Returns an empty string if the value is not defined. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } if (options && options.trimWhitespace === false) { return val; } return val.trim(); } /** * Gets the values of an multiline input. Each value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string[] * */ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); if (options && options.trimWhitespace === false) { return inputs; } return inputs.map(input => input.trim()); } /** * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. * Support boolean input list: `true | True | TRUE | false | False | FALSE` . * The return value is also in boolean type. * ref: https://yaml.org/spec/1.2/spec.html#id2804923 * * @param name name of the input to get * @param options optional. See InputOptions. * @returns boolean */ function getBooleanInput(name, options) { const trueValue = ['true', 'True', 'TRUE']; const falseValue = ['false', 'False', 'FALSE']; const val = getInput(name, options); if (trueValue.includes(val)) return true; if (falseValue.includes(val)) return false; throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { const filePath = process.env['GITHUB_OUTPUT'] || ''; if (filePath) { return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); } process.stdout.write(os.EOL); (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); } /** * Enables or disables the echoing of commands into stdout for the rest of the step. * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. * */ function setCommandEcho(enabled) { (0, command_1.issue)('echo', enabled ? 'on' : 'off'); } //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } /** * Writes debug message to user log * @param message debug message */ function debug(message) { (0, command_1.issueCommand)('debug', {}, message); } /** * Adds an error issue * @param message error issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function error(message, properties = {}) { (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } /** * Adds a warning issue * @param message warning issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function warning(message, properties = {}) { (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } /** * Adds a notice issue * @param message notice issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function notice(message, properties = {}) { (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { (0, command_1.issue)('group', name); } /** * End an output group. */ function endGroup() { (0, command_1.issue)('endgroup'); } /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { const filePath = process.env['GITHUB_STATE'] || ''; if (filePath) { return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); } (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); } /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } function getIDToken(aud) { return __awaiter(this, void 0, void 0, function* () { return yield oidc_utils_1.OidcClient.getIDToken(aud); }); } /** * Summary exports */ var summary_1 = __nccwpck_require__(1847); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ var summary_2 = __nccwpck_require__(1847); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports */ var path_utils_1 = __nccwpck_require__(1976); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); /** * Platform utilities exports */ exports.platform = __importStar(__nccwpck_require__(8968)); //# sourceMappingURL=core.js.map /***/ }), /***/ 4753: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issueFileCommand = issueFileCommand; exports.prepareKeyValueMessage = prepareKeyValueMessage; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const crypto = __importStar(__nccwpck_require__(6982)); const fs = __importStar(__nccwpck_require__(9896)); const os = __importStar(__nccwpck_require__(857)); const utils_1 = __nccwpck_require__(302); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { encoding: 'utf8' }); } function prepareKeyValueMessage(key, value) { const delimiter = `ghadelimiter_${crypto.randomUUID()}`; const convertedValue = (0, utils_1.toCommandValue)(value); // These should realistically never happen, but just in case someone finds a // way to exploit uuid generation let's not allow keys or values that contain // the delimiter. if (key.includes(delimiter)) { throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); } if (convertedValue.includes(delimiter)) { throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); } return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; } //# sourceMappingURL=file-command.js.map /***/ }), /***/ 5306: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; const http_client_1 = __nccwpck_require__(4844); const auth_1 = __nccwpck_require__(4552); const core_1 = __nccwpck_require__(7484); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { allowRetries: allowRetry, maxRetries: maxRetry }; return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); } static getRequestToken() { const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; if (!token) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); } return token; } static getIDTokenUrl() { const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; if (!runtimeUrl) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); } return runtimeUrl; } static getCall(id_token_url) { return __awaiter(this, void 0, void 0, function* () { var _a; const httpclient = OidcClient.createHttpClient(); const res = yield httpclient .getJson(id_token_url) .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { throw new Error('Response json body do not have ID Token field'); } return id_token; }); } static getIDToken(audience) { return __awaiter(this, void 0, void 0, function* () { try { // New ID Token is requested from action service let id_token_url = OidcClient.getIDTokenUrl(); if (audience) { const encodedAudience = encodeURIComponent(audience); id_token_url = `${id_token_url}&audience=${encodedAudience}`; } (0, core_1.debug)(`ID token url is ${id_token_url}`); const id_token = yield OidcClient.getCall(id_token_url); (0, core_1.setSecret)(id_token); return id_token; } catch (error) { throw new Error(`Error message: ${error.message}`); } }); } } exports.OidcClient = OidcClient; //# sourceMappingURL=oidc-utils.js.map /***/ }), /***/ 1976: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toPosixPath = toPosixPath; exports.toWin32Path = toWin32Path; exports.toPlatformPath = toPlatformPath; const path = __importStar(__nccwpck_require__(6928)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. * * @param pth. Path to transform. * @return string Posix path. */ function toPosixPath(pth) { return pth.replace(/[\\]/g, '/'); } /** * toWin32Path converts the given path to the win32 form. On Linux, / will be * replaced with \\. * * @param pth. Path to transform. * @return string Win32 path. */ function toWin32Path(pth) { return pth.replace(/[/]/g, '\\'); } /** * toPlatformPath converts the given path to a platform-specific path. It does * this by replacing instances of / and \ with the platform-specific path * separator. * * @param pth The path to platformize. * @return string The platform-specific path. */ function toPlatformPath(pth) { return pth.replace(/[/\\]/g, path.sep); } //# sourceMappingURL=path-utils.js.map /***/ }), /***/ 8968: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; exports.getDetails = getDetails; const os_1 = __importDefault(__nccwpck_require__(857)); const exec = __importStar(__nccwpck_require__(5236)); const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { silent: true }); const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { silent: true }); return { name: name.trim(), version: version.trim() }; }); const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { var _a, _b, _c, _d; const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { silent: true }); const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; return { name, version }; }); const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { silent: true }); const [name, version] = stdout.trim().split('\n'); return { name, version }; }); exports.platform = os_1.default.platform(); exports.arch = os_1.default.arch(); exports.isWindows = exports.platform === 'win32'; exports.isMacOS = exports.platform === 'darwin'; exports.isLinux = exports.platform === 'linux'; function getDetails() { return __awaiter(this, void 0, void 0, function* () { return Object.assign(Object.assign({}, (yield (exports.isWindows ? getWindowsInfo() : exports.isMacOS ? getMacOsInfo() : getLinuxInfo()))), { platform: exports.platform, arch: exports.arch, isWindows: exports.isWindows, isMacOS: exports.isMacOS, isLinux: exports.isLinux }); }); } //# sourceMappingURL=platform.js.map /***/ }), /***/ 1847: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; const os_1 = __nccwpck_require__(857); const fs_1 = __nccwpck_require__(9896); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; class Summary { constructor() { this._buffer = ''; } /** * Finds the summary file path from the environment, rejects if env var is not found or file does not exist * Also checks r/w permissions. * * @returns step summary file path */ filePath() { return __awaiter(this, void 0, void 0, function* () { if (this._filePath) { return this._filePath; } const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; if (!pathFromEnv) { throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); } try { yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); } catch (_a) { throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); } this._filePath = pathFromEnv; return this._filePath; }); } /** * Wraps content in an HTML tag, adding any HTML attributes * * @param {string} tag HTML tag to wrap * @param {string | null} content content within the tag * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add * * @returns {string} content wrapped in HTML element */ wrap(tag, content, attrs = {}) { const htmlAttrs = Object.entries(attrs) .map(([key, value]) => ` ${key}="${value}"`) .join(''); if (!content) { return `<${tag}${htmlAttrs}>`; } return `<${tag}${htmlAttrs}>${content}`; } /** * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. * * @param {SummaryWriteOptions} [options] (optional) options for write operation * * @returns {Promise} summary instance */ write(options) { return __awaiter(this, void 0, void 0, function* () { const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); const filePath = yield this.filePath(); const writeFunc = overwrite ? writeFile : appendFile; yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); return this.emptyBuffer(); }); } /** * Clears the summary buffer and wipes the summary file * * @returns {Summary} summary instance */ clear() { return __awaiter(this, void 0, void 0, function* () { return this.emptyBuffer().write({ overwrite: true }); }); } /** * Returns the current summary buffer as a string * * @returns {string} string of summary buffer */ stringify() { return this._buffer; } /** * If the summary buffer is empty * * @returns {boolen} true if the buffer is empty */ isEmptyBuffer() { return this._buffer.length === 0; } /** * Resets the summary buffer without writing to summary file * * @returns {Summary} summary instance */ emptyBuffer() { this._buffer = ''; return this; } /** * Adds raw text to the summary buffer * * @param {string} text content to add * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) * * @returns {Summary} summary instance */ addRaw(text, addEOL = false) { this._buffer += text; return addEOL ? this.addEOL() : this; } /** * Adds the operating system-specific end-of-line marker to the buffer * * @returns {Summary} summary instance */ addEOL() { return this.addRaw(os_1.EOL); } /** * Adds an HTML codeblock to the summary buffer * * @param {string} code content to render within fenced code block * @param {string} lang (optional) language to syntax highlight code * * @returns {Summary} summary instance */ addCodeBlock(code, lang) { const attrs = Object.assign({}, (lang && { lang })); const element = this.wrap('pre', this.wrap('code', code), attrs); return this.addRaw(element).addEOL(); } /** * Adds an HTML list to the summary buffer * * @param {string[]} items list of items to render * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) * * @returns {Summary} summary instance */ addList(items, ordered = false) { const tag = ordered ? 'ol' : 'ul'; const listItems = items.map(item => this.wrap('li', item)).join(''); const element = this.wrap(tag, listItems); return this.addRaw(element).addEOL(); } /** * Adds an HTML table to the summary buffer * * @param {SummaryTableCell[]} rows table rows * * @returns {Summary} summary instance */ addTable(rows) { const tableBody = rows .map(row => { const cells = row .map(cell => { if (typeof cell === 'string') { return this.wrap('td', cell); } const { header, data, colspan, rowspan } = cell; const tag = header ? 'th' : 'td'; const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); return this.wrap(tag, data, attrs); }) .join(''); return this.wrap('tr', cells); }) .join(''); const element = this.wrap('table', tableBody); return this.addRaw(element).addEOL(); } /** * Adds a collapsable HTML details element to the summary buffer * * @param {string} label text for the closed state * @param {string} content collapsable content * * @returns {Summary} summary instance */ addDetails(label, content) { const element = this.wrap('details', this.wrap('summary', label) + content); return this.addRaw(element).addEOL(); } /** * Adds an HTML image tag to the summary buffer * * @param {string} src path to the image you to embed * @param {string} alt text description of the image * @param {SummaryImageOptions} options (optional) addition image attributes * * @returns {Summary} summary instance */ addImage(src, alt, options) { const { width, height } = options || {}; const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); return this.addRaw(element).addEOL(); } /** * Adds an HTML section heading element * * @param {string} text heading text * @param {number | string} [level=1] (optional) the heading level, default: 1 * * @returns {Summary} summary instance */ addHeading(text, level) { const tag = `h${level}`; const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) ? tag : 'h1'; const element = this.wrap(allowedTag, text); return this.addRaw(element).addEOL(); } /** * Adds an HTML thematic break (
) to the summary buffer * * @returns {Summary} summary instance */ addSeparator() { const element = this.wrap('hr', null); return this.addRaw(element).addEOL(); } /** * Adds an HTML line break (
) to the summary buffer * * @returns {Summary} summary instance */ addBreak() { const element = this.wrap('br', null); return this.addRaw(element).addEOL(); } /** * Adds an HTML blockquote to the summary buffer * * @param {string} text quote text * @param {string} cite (optional) citation url * * @returns {Summary} summary instance */ addQuote(text, cite) { const attrs = Object.assign({}, (cite && { cite })); const element = this.wrap('blockquote', text, attrs); return this.addRaw(element).addEOL(); } /** * Adds an HTML anchor tag to the summary buffer * * @param {string} text link text/content * @param {string} href hyperlink * * @returns {Summary} summary instance */ addLink(text, href) { const element = this.wrap('a', text, { href }); return this.addRaw(element).addEOL(); } } const _summary = new Summary(); /** * @deprecated use `core.summary` */ exports.markdownSummary = _summary; exports.summary = _summary; //# sourceMappingURL=summary.js.map /***/ }), /***/ 302: /***/ ((__unused_webpack_module, exports) => { "use strict"; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toCommandValue = toCommandValue; exports.toCommandProperties = toCommandProperties; /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string */ function toCommandValue(input) { if (input === null || input === undefined) { return ''; } else if (typeof input === 'string' || input instanceof String) { return input; } return JSON.stringify(input); } /** * * @param annotationProperties * @returns The command properties to send with the actual annotation command * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 */ function toCommandProperties(annotationProperties) { if (!Object.keys(annotationProperties).length) { return {}; } return { title: annotationProperties.title, file: annotationProperties.file, line: annotationProperties.startLine, endLine: annotationProperties.endLine, col: annotationProperties.startColumn, endColumn: annotationProperties.endColumn }; } //# sourceMappingURL=utils.js.map /***/ }), /***/ 5236: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.exec = exec; exports.getExecOutput = getExecOutput; const string_decoder_1 = __nccwpck_require__(3193); const tr = __importStar(__nccwpck_require__(6665)); /** * Exec a command. * Output will be streamed to the live console. * Returns promise with return code * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise exit code */ function exec(commandLine, args, options) { return __awaiter(this, void 0, void 0, function* () { const commandArgs = tr.argStringToArray(commandLine); if (commandArgs.length === 0) { throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } // Path to tool to execute should be first arg const toolPath = commandArgs[0]; args = commandArgs.slice(1).concat(args || []); const runner = new tr.ToolRunner(toolPath, args, options); return runner.exec(); }); } /** * Exec a command and get the output. * Output will be streamed to the live console. * Returns promise with the exit code and collected stdout and stderr * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise exit code, stdout, and stderr */ function getExecOutput(commandLine, args, options) { return __awaiter(this, void 0, void 0, function* () { var _a, _b; let stdout = ''; let stderr = ''; //Using string decoder covers the case where a mult-byte character is split const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; const stdErrListener = (data) => { stderr += stderrDecoder.write(data); if (originalStdErrListener) { originalStdErrListener(data); } }; const stdOutListener = (data) => { stdout += stdoutDecoder.write(data); if (originalStdoutListener) { originalStdoutListener(data); } }; const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); //flush any remaining characters stdout += stdoutDecoder.end(); stderr += stderrDecoder.end(); return { exitCode, stdout, stderr }; }); } //# sourceMappingURL=exec.js.map /***/ }), /***/ 6665: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolRunner = void 0; exports.argStringToArray = argStringToArray; const os = __importStar(__nccwpck_require__(857)); const events = __importStar(__nccwpck_require__(4434)); const child = __importStar(__nccwpck_require__(5317)); const path = __importStar(__nccwpck_require__(6928)); const io = __importStar(__nccwpck_require__(4994)); const ioUtil = __importStar(__nccwpck_require__(5207)); const timers_1 = __nccwpck_require__(3557); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ class ToolRunner extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(os.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } return s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); return ''; } } _getSpawnFileName() { if (IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse.split('').reverse().join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // 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. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse.split('').reverse().join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return __awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes('/') || (IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); } const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); let stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } let errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } errbuffer = this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); if (this.options.input) { if (!cp.stdin) { throw new Error('child process missing stdin'); } cp.stdin.end(this.options.input); } })); }); } } exports.ToolRunner = ToolRunner; /** * Convert an arg string to an array of args. Handles escaping * * @param argString string of arguments * @returns string[] array of arguments */ function argStringToArray(argString) { const args = []; let inQuotes = false; let escaped = false; let arg = ''; function append(c) { // we only escape double quotes. if (escaped && c !== '"') { arg += '\\'; } arg += c; escaped = false; } for (let i = 0; i < argString.length; i++) { const c = argString.charAt(i); if (c === '"') { if (!escaped) { inQuotes = !inQuotes; } else { append(c); } continue; } if (c === '\\' && escaped) { append(c); continue; } if (c === '\\' && inQuotes) { escaped = true; continue; } if (c === ' ' && !inQuotes) { if (arg.length > 0) { args.push(arg); arg = ''; } continue; } append(c); } if (arg.length > 0) { args.push(arg.trim()); } return args; } class ExecState extends events.EventEmitter { constructor(options, toolPath) { super(); this.processClosed = false; // tracks whether the process has exited and stdio is closed this.processError = ''; this.processExitCode = 0; this.processExited = false; // tracks whether the process has exited this.processStderr = false; // tracks whether stderr was written to this.delay = 10000; // 10 seconds this.done = false; this.timeout = null; if (!toolPath) { throw new Error('toolPath must not be empty'); } this.options = options; this.toolPath = toolPath; if (options.delay) { this.delay = options.delay; } } CheckComplete() { if (this.done) { return; } if (this.processClosed) { this._setResult(); } else if (this.processExited) { this.timeout = (0, timers_1.setTimeout)(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { this.emit('debug', message); } _setResult() { // determine whether there is an error let error; if (this.processExited) { if (this.processError) { error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } else if (this.processStderr && this.options.failOnStdErr) { error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } } // clear the timeout if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.done = true; this.emit('done', error, this.processExitCode); } static HandleTimeout(state) { if (state.done) { return; } if (!state.processClosed && state.processExited) { const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; state._debug(message); } state._setResult(); } } //# sourceMappingURL=toolrunner.js.map /***/ }), /***/ 4552: /***/ (function(__unused_webpack_module, exports) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; class BasicCredentialHandler { constructor(username, password) { this.username = username; this.password = password; } prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.BasicCredentialHandler = BasicCredentialHandler; class BearerCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Bearer ${this.token}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.BearerCredentialHandler = BearerCredentialHandler; class PersonalAccessTokenCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; //# sourceMappingURL=auth.js.map /***/ }), /***/ 4844: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.HttpClientResponse = exports.HttpClientError = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; exports.getProxyUrl = getProxyUrl; exports.isHttps = isHttps; const http = __importStar(__nccwpck_require__(8611)); const https = __importStar(__nccwpck_require__(5692)); const pm = __importStar(__nccwpck_require__(4988)); const tunnel = __importStar(__nccwpck_require__(770)); const undici_1 = __nccwpck_require__(6752); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes || (exports.HttpCodes = HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers || (exports.Headers = Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ]; const HttpResponseRetryCodes = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientError extends Error { constructor(message, statusCode) { super(message); this.name = 'HttpClientError'; this.statusCode = statusCode; Object.setPrototypeOf(this, HttpClientError.prototype); } } exports.HttpClientError = HttpClientError; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { let output = Buffer.alloc(0); this.message.on('data', (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on('end', () => { resolve(output.toString()); }); })); }); } readBodyBuffer() { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { const chunks = []; this.message.on('data', (chunk) => { chunks.push(chunk); }); this.message.on('end', () => { resolve(Buffer.concat(chunks)); }); })); }); } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { const parsedUrl = new URL(requestUrl); return parsedUrl.protocol === 'https:'; } class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = this._getUserAgentWithOrchestrationId(userAgent); this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); }); } get(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('GET', requestUrl, null, additionalHeaders || {}); }); } del(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); }); } post(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('POST', requestUrl, data, additionalHeaders || {}); }); } patch(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); }); } put(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PUT', requestUrl, data, additionalHeaders || {}); }); } head(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); }); } sendStream(verb, requestUrl, stream, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request(verb, requestUrl, stream, additionalHeaders); }); } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ getJson(requestUrl_1) { return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); const res = yield this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } postJson(requestUrl_1, obj_1) { return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); const res = yield this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } putJson(requestUrl_1, obj_1) { return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); const res = yield this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } patchJson(requestUrl_1, obj_1) { return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); const res = yield this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ request(verb, requestUrl, data, headers) { return __awaiter(this, void 0, void 0, function* () { if (this._disposed) { throw new Error('Client has already been disposed.'); } const parsedUrl = new URL(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; let numTries = 0; let response; do { response = yield this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (const handler of this.handlers) { if (handler.canHandleAuthentication(response)) { authenticationHandler = handler; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } const parsedRedirectUrl = new URL(redirectUrl); if (parsedUrl.protocol === 'https:' && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); } // we need to finish reading the response before reassigning response // which will leak the open socket. yield response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (const header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header]; } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = yield this.requestRaw(info, data); redirectsRemaining--; } if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { yield response.readBody(); yield this._performExponentialBackoff(numTries); } } while (numTries < maxTries); return response; }); } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { function callbackForResult(err, res) { if (err) { reject(err); } else if (!res) { // If `err` is not passed, then `res` must be passed. reject(new Error('Unknown error')); } else { resolve(res); } } this.requestRawWithCallback(info, data, callbackForResult); }); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { if (typeof data === 'string') { if (!info.options.headers) { info.options.headers = {}; } info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; function handleResult(err, res) { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } } const req = info.httpModule.request(info.options, (msg) => { const res = new HttpClientResponse(msg); handleResult(undefined, res); }); let socket; req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end(); } handleResult(new Error(`Request timeout: ${info.options.path}`)); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); } if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } getAgentDispatcher(serverUrl) { const parsedUrl = new URL(serverUrl); const proxyUrl = pm.getProxyUrl(parsedUrl); const useProxy = proxyUrl && proxyUrl.hostname; if (!useProxy) { return; } return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { for (const handler of this.handlers) { handler.prepareRequest(info.options); } } return info; } _mergeHeaders(headers) { if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } return lowercaseKeys(headers || {}); } /** * Gets an existing header value or returns a default. * Handles converting number header values to strings since HTTP headers must be strings. * Note: This returns string | string[] since some headers can have multiple values. * For headers that must always be a single string (like Content-Type), use the * specialized _getExistingOrDefaultContentTypeHeader method instead. */ _getExistingOrDefaultHeader(additionalHeaders, header, _default) { let clientHeader; if (this.requestOptions && this.requestOptions.headers) { const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; if (headerValue) { clientHeader = typeof headerValue === 'number' ? headerValue.toString() : headerValue; } } const additionalValue = additionalHeaders[header]; if (additionalValue !== undefined) { return typeof additionalValue === 'number' ? additionalValue.toString() : additionalValue; } if (clientHeader !== undefined) { return clientHeader; } return _default; } /** * Specialized version of _getExistingOrDefaultHeader for Content-Type header. * Always returns a single string (not an array) since Content-Type should be a single value. * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). */ _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { let clientHeader; if (this.requestOptions && this.requestOptions.headers) { const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; if (headerValue) { if (typeof headerValue === 'number') { clientHeader = String(headerValue); } else if (Array.isArray(headerValue)) { clientHeader = headerValue.join(', '); } else { clientHeader = headerValue; } } } const additionalValue = additionalHeaders[Headers.ContentType]; // Return the first non-undefined value, converting numbers or arrays to strings if necessary if (additionalValue !== undefined) { if (typeof additionalValue === 'number') { return String(additionalValue); } else if (Array.isArray(additionalValue)) { return additionalValue.join(', '); } else { return additionalValue; } } if (clientHeader !== undefined) { return clientHeader; } return _default; } _getAgent(parsedUrl) { let agent; const proxyUrl = pm.getProxyUrl(parsedUrl); const useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. if (proxyUrl && proxyUrl.hostname) { const agentOptions = { maxSockets, keepAlive: this._keepAlive, proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` })), { host: proxyUrl.hostname, port: proxyUrl.port }) }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if tunneling agent isn't assigned create a new agent if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } return agent; } _getProxyAgentDispatcher(parsedUrl, proxyUrl) { let proxyAgent; if (this._keepAlive) { proxyAgent = this._proxyAgentDispatcher; } // if agent is already assigned use that agent. if (proxyAgent) { return proxyAgent; } const usingSsl = parsedUrl.protocol === 'https:'; proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` }))); this._proxyAgentDispatcher = proxyAgent; if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { rejectUnauthorized: false }); } return proxyAgent; } _getUserAgentWithOrchestrationId(userAgent) { const baseUserAgent = userAgent || 'actions/http-client'; const orchId = process.env['ACTIONS_ORCHESTRATION_ID']; if (orchId) { // Sanitize the orchestration ID to ensure it contains only valid characters // Valid characters: 0-9, a-z, _, -, . const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_'); return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; } return baseUserAgent; } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); }); } _processResponse(res, options) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { const statusCode = res.message.statusCode || 0; const response = { statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode === HttpCodes.NotFound) { resolve(response); } // get the result from the body function dateTimeDeserializer(key, value) { if (typeof value === 'string') { const a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } let obj; let contents; try { contents = yield res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, dateTimeDeserializer); } else { obj = JSON.parse(contents); } response.result = obj; } response.headers = res.message.headers; } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg; // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message; } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents; } else { msg = `Failed request: (${statusCode})`; } const err = new HttpClientError(msg, statusCode); err.result = response.result; reject(err); } else { resolve(response); } })); }); } } exports.HttpClient = HttpClient; const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); //# sourceMappingURL=index.js.map /***/ }), /***/ 4988: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getProxyUrl = getProxyUrl; exports.checkBypass = checkBypass; function getProxyUrl(reqUrl) { const usingSsl = reqUrl.protocol === 'https:'; if (checkBypass(reqUrl)) { return undefined; } const proxyVar = (() => { if (usingSsl) { return process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { return process.env['http_proxy'] || process.env['HTTP_PROXY']; } })(); if (proxyVar) { try { return new DecodedURL(proxyVar); } catch (_a) { if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) return new DecodedURL(`http://${proxyVar}`); } } else { return undefined; } } function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } const reqHost = reqUrl.hostname; if (isLoopbackAddress(reqHost)) { return true; } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } // Determine the request port let reqPort; if (reqUrl.port) { reqPort = Number(reqUrl.port); } else if (reqUrl.protocol === 'http:') { reqPort = 80; } else if (reqUrl.protocol === 'https:') { reqPort = 443; } // Format the request hostname and hostname with port const upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (const upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { if (upperNoProxyItem === '*' || upperReqHosts.some(x => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || (upperNoProxyItem.startsWith('.') && x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } function isLoopbackAddress(host) { const hostLower = host.toLowerCase(); return (hostLower === 'localhost' || hostLower.startsWith('127.') || hostLower.startsWith('[::1]') || hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } class DecodedURL extends URL { constructor(url, base) { super(url, base); this._decodedUsername = decodeURIComponent(super.username); this._decodedPassword = decodeURIComponent(super.password); } get username() { return this._decodedUsername; } get password() { return this._decodedPassword; } } //# sourceMappingURL=proxy.js.map /***/ }), /***/ 5207: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; exports.readlink = readlink; exports.exists = exists; exports.isDirectory = isDirectory; exports.isRooted = isRooted; exports.tryGetExecutablePath = tryGetExecutablePath; exports.getCmdPath = getCmdPath; const fs = __importStar(__nccwpck_require__(9896)); const path = __importStar(__nccwpck_require__(6928)); _a = fs.promises // export const {open} = 'fs' , exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; // export const {open} = 'fs' exports.IS_WINDOWS = process.platform === 'win32'; /** * Custom implementation of readlink to ensure Windows junctions * maintain trailing backslash for backward compatibility with Node.js < 24 * * In Node.js 20, Windows junctions (directory symlinks) always returned paths * with trailing backslashes. Node.js 24 removed this behavior, which breaks * code that relied on this format for path operations. * * This implementation restores the Node 20 behavior by adding a trailing * backslash to all junction results on Windows. */ function readlink(fsPath) { return __awaiter(this, void 0, void 0, function* () { const result = yield fs.promises.readlink(fsPath); // On Windows, restore Node 20 behavior: add trailing backslash to all results // since junctions on Windows are always directory links if (exports.IS_WINDOWS && !result.endsWith('\\')) { return `${result}\\`; } return result; }); } // See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 exports.UV_FS_O_EXLOCK = 0x10000000; exports.READONLY = fs.constants.O_RDONLY; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { yield (0, exports.stat)(fsPath); } catch (err) { if (err.code === 'ENOENT') { return false; } throw err; } return true; }); } function isDirectory(fsPath_1) { return __awaiter(this, arguments, void 0, function* (fsPath, useStat = false) { const stats = useStat ? yield (0, exports.stat)(fsPath) : yield (0, exports.lstat)(fsPath); return stats.isDirectory(); }); } /** * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ function isRooted(p) { p = normalizeSeparators(p); if (!p) { throw new Error('isRooted() parameter "p" cannot be empty'); } if (exports.IS_WINDOWS) { return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello ); // e.g. C: or C:\hello } return p.startsWith('/'); } /** * Best effort attempt to determine whether a file exists and is executable. * @param filePath file path to check * @param extensions additional file extensions to try * @return if file exists and is executable, returns the file path. otherwise empty string. */ function tryGetExecutablePath(filePath, extensions) { return __awaiter(this, void 0, void 0, function* () { let stats = undefined; try { // test file exists stats = yield (0, exports.stat)(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // on Windows, test for valid extension const upperExt = path.extname(filePath).toUpperCase(); if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { return filePath; } } else { if (isUnixExecutable(stats)) { return filePath; } } } // try each extension const originalFilePath = filePath; for (const extension of extensions) { filePath = originalFilePath + extension; stats = undefined; try { stats = yield (0, exports.stat)(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // preserve the case of the actual file (since an extension was appended) try { const directory = path.dirname(filePath); const upperName = path.basename(filePath).toUpperCase(); for (const actualName of yield (0, exports.readdir)(directory)) { if (upperName === actualName.toUpperCase()) { filePath = path.join(directory, actualName); break; } } } catch (err) { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); } return filePath; } else { if (isUnixExecutable(stats)) { return filePath; } } } } return ''; }); } function normalizeSeparators(p) { p = p || ''; if (exports.IS_WINDOWS) { // convert slashes on Windows p = p.replace(/\//g, '\\'); // remove redundant slashes return p.replace(/\\\\+/g, '\\'); } // remove redundant slashes return p.replace(/\/\/+/g, '/'); } // on Mac/Linux, test the execute bit // R W X R W X R W X // 256 128 64 32 16 8 4 2 1 function isUnixExecutable(stats) { return ((stats.mode & 1) > 0 || ((stats.mode & 8) > 0 && process.getgid !== undefined && stats.gid === process.getgid()) || ((stats.mode & 64) > 0 && process.getuid !== undefined && stats.uid === process.getuid())); } // Get the path of cmd.exe in windows function getCmdPath() { var _a; return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; } //# sourceMappingURL=io-util.js.map /***/ }), /***/ 4994: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.cp = cp; exports.mv = mv; exports.rmRF = rmRF; exports.mkdirP = mkdirP; exports.which = which; exports.findInPath = findInPath; const assert_1 = __nccwpck_require__(2613); const path = __importStar(__nccwpck_require__(6928)); const ioUtil = __importStar(__nccwpck_require__(5207)); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js * * @param source source path * @param dest destination path * @param options optional. See CopyOptions. */ function cp(source_1, dest_1) { return __awaiter(this, arguments, void 0, function* (source, dest, options = {}) { const { force, recursive, copySourceDirectory } = readCopyOptions(options); const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; // Dest is an existing file, but not forcing if (destStat && destStat.isFile() && !force) { return; } // If dest is an existing directory, should copy inside. const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path.join(dest, path.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } const sourceStat = yield ioUtil.stat(source); if (sourceStat.isDirectory()) { if (!recursive) { throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); } else { yield cpDirRecursive(source, newDest, 0, force); } } else { if (path.relative(source, newDest) === '') { // a file cannot be copied to itself throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile(source, newDest, force); } }); } /** * Moves a path. * * @param source source path * @param dest destination path * @param options optional. See MoveOptions. */ function mv(source_1, dest_1) { return __awaiter(this, arguments, void 0, function* (source, dest, options = {}) { if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { // If dest is directory copy src into dest dest = path.join(dest, path.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { if (options.force == null || options.force) { yield rmRF(dest); } else { throw new Error('Destination already exists'); } } } yield mkdirP(path.dirname(dest)); yield ioUtil.rename(source, dest); }); } /** * Remove a path recursively with force * * @param inputPath path to remove */ function rmRF(inputPath) { return __awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { // Check for invalid characters // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file if (/[*"<>|]/.test(inputPath)) { throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); } } try { // note if path does not exist, error is silent yield ioUtil.rm(inputPath, { force: true, maxRetries: 3, recursive: true, retryDelay: 300 }); } catch (err) { throw new Error(`File was unable to be removed ${err}`); } }); } /** * Make a directory. Creates the full path with folders in between * Will throw if it fails * * @param fsPath path to create * @returns Promise */ function mkdirP(fsPath) { return __awaiter(this, void 0, void 0, function* () { (0, assert_1.ok)(fsPath, 'a path argument must be provided'); yield ioUtil.mkdir(fsPath, { recursive: true }); }); } /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, it will throw. * * @param tool name of the tool * @param check whether to check if tool exists * @returns Promise path to tool */ function which(tool, check) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // recursive when check=true if (check) { const result = yield which(tool, false); if (!result) { if (ioUtil.IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); } else { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } return result; } const matches = yield findInPath(tool); if (matches && matches.length > 0) { return matches[0]; } return ''; }); } /** * Returns a list of all occurrences of the given tool on the system path. * * @returns Promise the paths of the tool */ function findInPath(tool) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // build the list of extensions to try const extensions = []; if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { for (const extension of process.env['PATHEXT'].split(path.delimiter)) { if (extension) { extensions.push(extension); } } } // if it's rooted, return it if exists. otherwise return empty. if (ioUtil.isRooted(tool)) { const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); if (filePath) { return [filePath]; } return []; } // if any path separators, return empty if (tool.includes(path.sep)) { return []; } // build the list of directories // // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, // it feels like we should not do this. Checking the current directory seems like more of a use // case of a shell, and the which() function exposed by the toolkit should strive for consistency // across platforms. const directories = []; if (process.env.PATH) { for (const p of process.env.PATH.split(path.delimiter)) { if (p) { directories.push(p); } } } // find all matches const matches = []; for (const directory of directories) { const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); if (filePath) { matches.push(filePath); } } return matches; }); } function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); const copySourceDirectory = options.copySourceDirectory == null ? true : Boolean(options.copySourceDirectory); return { force, recursive, copySourceDirectory }; } function cpDirRecursive(sourceDir, destDir, currentDepth, force) { return __awaiter(this, void 0, void 0, function* () { // Ensure there is not a run away recursive copy if (currentDepth >= 255) return; currentDepth++; yield mkdirP(destDir); const files = yield ioUtil.readdir(sourceDir); for (const fileName of files) { const srcFile = `${sourceDir}/${fileName}`; const destFile = `${destDir}/${fileName}`; const srcFileStat = yield ioUtil.lstat(srcFile); if (srcFileStat.isDirectory()) { // Recurse yield cpDirRecursive(srcFile, destFile, currentDepth, force); } else { yield copyFile(srcFile, destFile, force); } } // Change the mode for the newly created directory yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); }); } // Buffered file copy function copyFile(srcFile, destFile, force) { return __awaiter(this, void 0, void 0, function* () { if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { // unlink/re-link it try { yield ioUtil.lstat(destFile); yield ioUtil.unlink(destFile); } catch (e) { // Try to override file permission if (e.code === 'EPERM') { yield ioUtil.chmod(destFile, '0666'); yield ioUtil.unlink(destFile); } // other errors = it doesn't exist, no work to do } // Copy over symlink const symlinkFull = yield ioUtil.readlink(srcFile); yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } else if (!(yield ioUtil.exists(destFile)) || force) { yield ioUtil.copyFile(srcFile, destFile); } }); } //# sourceMappingURL=io.js.map /***/ }), /***/ 6656: /***/ ((module) => { // Copyright 2011 Mark Cavage All rights reserved. module.exports = { newInvalidAsn1Error: function (msg) { var e = new Error(); e.name = 'InvalidAsn1Error'; e.message = msg || ''; return e; } }; /***/ }), /***/ 7703: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var errors = __nccwpck_require__(6656); var types = __nccwpck_require__(254); var Reader = __nccwpck_require__(1996); var Writer = __nccwpck_require__(9816); // --- Exports module.exports = { Reader: Reader, Writer: Writer }; for (var t in types) { if (types.hasOwnProperty(t)) module.exports[t] = types[t]; } for (var e in errors) { if (errors.hasOwnProperty(e)) module.exports[e] = errors[e]; } /***/ }), /***/ 1996: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var assert = __nccwpck_require__(2613); var Buffer = (__nccwpck_require__(2803).Buffer); var ASN1 = __nccwpck_require__(254); var errors = __nccwpck_require__(6656); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; // --- API function Reader(data) { if (!data || !Buffer.isBuffer(data)) throw new TypeError('data must be a node Buffer'); this._buf = data; this._size = data.length; // These hold the "current" state this._len = 0; this._offset = 0; } Object.defineProperty(Reader.prototype, 'length', { enumerable: true, get: function () { return (this._len); } }); Object.defineProperty(Reader.prototype, 'offset', { enumerable: true, get: function () { return (this._offset); } }); Object.defineProperty(Reader.prototype, 'remain', { get: function () { return (this._size - this._offset); } }); Object.defineProperty(Reader.prototype, 'buffer', { get: function () { return (this._buf.slice(this._offset)); } }); /** * Reads a single byte and advances offset; you can pass in `true` to make this * a "peek" operation (i.e., get the byte, but don't advance the offset). * * @param {Boolean} peek true means don't move offset. * @return {Number} the next byte, null if not enough data. */ Reader.prototype.readByte = function (peek) { if (this._size - this._offset < 1) return null; var b = this._buf[this._offset] & 0xff; if (!peek) this._offset += 1; return b; }; Reader.prototype.peek = function () { return this.readByte(true); }; /** * Reads a (potentially) variable length off the BER buffer. This call is * not really meant to be called directly, as callers have to manipulate * the internal buffer afterwards. * * As a result of this call, you can call `Reader.length`, until the * next thing called that does a readLength. * * @return {Number} the amount of offset to advance the buffer. * @throws {InvalidAsn1Error} on bad ASN.1 */ Reader.prototype.readLength = function (offset) { if (offset === undefined) offset = this._offset; if (offset >= this._size) return null; var lenB = this._buf[offset++] & 0xff; if (lenB === null) return null; if ((lenB & 0x80) === 0x80) { lenB &= 0x7f; if (lenB === 0) throw newInvalidAsn1Error('Indefinite length not supported'); if (lenB > 4) throw newInvalidAsn1Error('encoding too long'); if (this._size - offset < lenB) return null; this._len = 0; for (var i = 0; i < lenB; i++) this._len = (this._len << 8) + (this._buf[offset++] & 0xff); } else { // Wasn't a variable length this._len = lenB; } return offset; }; /** * Parses the next sequence in this BER buffer. * * To get the length of the sequence, call `Reader.length`. * * @return {Number} the sequence's tag. */ Reader.prototype.readSequence = function (tag) { var seq = this.peek(); if (seq === null) return null; if (tag !== undefined && tag !== seq) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + seq.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; this._offset = o; return seq; }; Reader.prototype.readInt = function () { return this._readTag(ASN1.Integer); }; Reader.prototype.readBoolean = function () { return (this._readTag(ASN1.Boolean) === 0 ? false : true); }; Reader.prototype.readEnumeration = function () { return this._readTag(ASN1.Enumeration); }; Reader.prototype.readString = function (tag, retbuf) { if (!tag) tag = ASN1.OctetString; var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > this._size - o) return null; this._offset = o; if (this.length === 0) return retbuf ? Buffer.alloc(0) : ''; var str = this._buf.slice(this._offset, this._offset + this.length); this._offset += this.length; return retbuf ? str : str.toString('utf8'); }; Reader.prototype.readOID = function (tag) { if (!tag) tag = ASN1.OID; var b = this.readString(tag, true); if (b === null) return null; var values = []; var value = 0; for (var i = 0; i < b.length; i++) { var byte = b[i] & 0xff; value <<= 7; value += byte & 0x7f; if ((byte & 0x80) === 0) { values.push(value); value = 0; } } value = values.shift(); values.unshift(value % 40); values.unshift((value / 40) >> 0); return values.join('.'); }; Reader.prototype._readTag = function (tag) { assert.ok(tag !== undefined); var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > 4) throw newInvalidAsn1Error('Integer too long: ' + this.length); if (this.length > this._size - o) return null; this._offset = o; var fb = this._buf[this._offset]; var value = 0; for (var i = 0; i < this.length; i++) { value <<= 8; value |= (this._buf[this._offset++] & 0xff); } if ((fb & 0x80) === 0x80 && i !== 4) value -= (1 << (i * 8)); return value >> 0; }; // --- Exported API module.exports = Reader; /***/ }), /***/ 254: /***/ ((module) => { // Copyright 2011 Mark Cavage All rights reserved. module.exports = { EOC: 0, Boolean: 1, Integer: 2, BitString: 3, OctetString: 4, Null: 5, OID: 6, ObjectDescriptor: 7, External: 8, Real: 9, // float Enumeration: 10, PDV: 11, Utf8String: 12, RelativeOID: 13, Sequence: 16, Set: 17, NumericString: 18, PrintableString: 19, T61String: 20, VideotexString: 21, IA5String: 22, UTCTime: 23, GeneralizedTime: 24, GraphicString: 25, VisibleString: 26, GeneralString: 28, UniversalString: 29, CharacterString: 30, BMPString: 31, Constructor: 32, Context: 128 }; /***/ }), /***/ 9816: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var assert = __nccwpck_require__(2613); var Buffer = (__nccwpck_require__(2803).Buffer); var ASN1 = __nccwpck_require__(254); var errors = __nccwpck_require__(6656); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; var DEFAULT_OPTS = { size: 1024, growthFactor: 8 }; // --- Helpers function merge(from, to) { assert.ok(from); assert.equal(typeof (from), 'object'); assert.ok(to); assert.equal(typeof (to), 'object'); var keys = Object.getOwnPropertyNames(from); keys.forEach(function (key) { if (to[key]) return; var value = Object.getOwnPropertyDescriptor(from, key); Object.defineProperty(to, key, value); }); return to; } // --- API function Writer(options) { options = merge(DEFAULT_OPTS, options || {}); this._buf = Buffer.alloc(options.size || 1024); this._size = this._buf.length; this._offset = 0; this._options = options; // A list of offsets in the buffer where we need to insert // sequence tag/len pairs. this._seq = []; } Object.defineProperty(Writer.prototype, 'buffer', { get: function () { if (this._seq.length) throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); return (this._buf.slice(0, this._offset)); } }); Writer.prototype.writeByte = function (b) { if (typeof (b) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(1); this._buf[this._offset++] = b; }; Writer.prototype.writeInt = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Integer; var sz = 4; while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && (sz > 1)) { sz--; i <<= 8; } if (sz > 4) throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); this._ensure(2 + sz); this._buf[this._offset++] = tag; this._buf[this._offset++] = sz; while (sz-- > 0) { this._buf[this._offset++] = ((i & 0xff000000) >>> 24); i <<= 8; } }; Writer.prototype.writeNull = function () { this.writeByte(ASN1.Null); this.writeByte(0x00); }; Writer.prototype.writeEnumeration = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Enumeration; return this.writeInt(i, tag); }; Writer.prototype.writeBoolean = function (b, tag) { if (typeof (b) !== 'boolean') throw new TypeError('argument must be a Boolean'); if (typeof (tag) !== 'number') tag = ASN1.Boolean; this._ensure(3); this._buf[this._offset++] = tag; this._buf[this._offset++] = 0x01; this._buf[this._offset++] = b ? 0xff : 0x00; }; Writer.prototype.writeString = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); if (typeof (tag) !== 'number') tag = ASN1.OctetString; var len = Buffer.byteLength(s); this.writeByte(tag); this.writeLength(len); if (len) { this._ensure(len); this._buf.write(s, this._offset); this._offset += len; } }; Writer.prototype.writeBuffer = function (buf, tag) { if (typeof (tag) !== 'number') throw new TypeError('tag must be a number'); if (!Buffer.isBuffer(buf)) throw new TypeError('argument must be a buffer'); this.writeByte(tag); this.writeLength(buf.length); this._ensure(buf.length); buf.copy(this._buf, this._offset, 0, buf.length); this._offset += buf.length; }; Writer.prototype.writeStringArray = function (strings) { if ((!strings instanceof Array)) throw new TypeError('argument must be an Array[String]'); var self = this; strings.forEach(function (s) { self.writeString(s); }); }; // This is really to solve DER cases, but whatever for now Writer.prototype.writeOID = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string'); if (typeof (tag) !== 'number') tag = ASN1.OID; if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) throw new Error('argument is not a valid OID string'); function encodeOctet(bytes, octet) { if (octet < 128) { bytes.push(octet); } else if (octet < 16384) { bytes.push((octet >>> 7) | 0x80); bytes.push(octet & 0x7F); } else if (octet < 2097152) { bytes.push((octet >>> 14) | 0x80); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else if (octet < 268435456) { bytes.push((octet >>> 21) | 0x80); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else { bytes.push(((octet >>> 28) | 0x80) & 0xFF); bytes.push(((octet >>> 21) | 0x80) & 0xFF); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } } var tmp = s.split('.'); var bytes = []; bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); tmp.slice(2).forEach(function (b) { encodeOctet(bytes, parseInt(b, 10)); }); var self = this; this._ensure(2 + bytes.length); this.writeByte(tag); this.writeLength(bytes.length); bytes.forEach(function (b) { self.writeByte(b); }); }; Writer.prototype.writeLength = function (len) { if (typeof (len) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(4); if (len <= 0x7f) { this._buf[this._offset++] = len; } else if (len <= 0xff) { this._buf[this._offset++] = 0x81; this._buf[this._offset++] = len; } else if (len <= 0xffff) { this._buf[this._offset++] = 0x82; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else if (len <= 0xffffff) { this._buf[this._offset++] = 0x83; this._buf[this._offset++] = len >> 16; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else { throw newInvalidAsn1Error('Length too long (> 4 bytes)'); } }; Writer.prototype.startSequence = function (tag) { if (typeof (tag) !== 'number') tag = ASN1.Sequence | ASN1.Constructor; this.writeByte(tag); this._seq.push(this._offset); this._ensure(3); this._offset += 3; }; Writer.prototype.endSequence = function () { var seq = this._seq.pop(); var start = seq + 3; var len = this._offset - start; if (len <= 0x7f) { this._shift(start, len, -2); this._buf[seq] = len; } else if (len <= 0xff) { this._shift(start, len, -1); this._buf[seq] = 0x81; this._buf[seq + 1] = len; } else if (len <= 0xffff) { this._buf[seq] = 0x82; this._buf[seq + 1] = len >> 8; this._buf[seq + 2] = len; } else if (len <= 0xffffff) { this._shift(start, len, 1); this._buf[seq] = 0x83; this._buf[seq + 1] = len >> 16; this._buf[seq + 2] = len >> 8; this._buf[seq + 3] = len; } else { throw newInvalidAsn1Error('Sequence too long'); } }; Writer.prototype._shift = function (start, len, shift) { assert.ok(start !== undefined); assert.ok(len !== undefined); assert.ok(shift); this._buf.copy(this._buf, start + shift, start, start + len); this._offset += shift; }; Writer.prototype._ensure = function (len) { assert.ok(len); if (this._size - this._offset < len) { var sz = this._size * this._options.growthFactor; if (sz - this._offset < len) sz += len; var buf = Buffer.alloc(sz); this._buf.copy(buf, 0, 0, this._offset); this._buf = buf; this._size = sz; } }; // --- Exported API module.exports = Writer; /***/ }), /***/ 9837: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2011 Mark Cavage All rights reserved. // If you have no idea what ASN.1 or BER is, see this: // ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc var Ber = __nccwpck_require__(7703); // --- Exported API module.exports = { Ber: Ber, BerReader: Ber.Reader, BerWriter: Ber.Writer }; /***/ }), /***/ 686: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var crypto_hash_sha512 = (__nccwpck_require__(668).lowlevel).crypto_hash; /* * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a * result, it retains the original copyright and license. The two files are * under slightly different (but compatible) licenses, and are here combined in * one file. * * Credit for the actual porting work goes to: * Devi Mandiri */ /* * The Blowfish portions are under the following license: * * Blowfish block cipher for OpenBSD * Copyright 1997 Niels Provos * All rights reserved. * * Implementation advice by David Mazieres . * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * The bcrypt_pbkdf portions are under the following license: * * Copyright (c) 2013 Ted Unangst * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Performance improvements (Javascript-specific): * * Copyright 2016, Joyent Inc * Author: Alex Wilson * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Ported from OpenBSD bcrypt_pbkdf.c v1.9 var BLF_J = 0; var Blowfish = function() { this.S = [ new Uint32Array([ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), new Uint32Array([ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), new Uint32Array([ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), new Uint32Array([ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) ]; this.P = new Uint32Array([ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b]); }; function F(S, x8, i) { return (((S[0][x8[i+3]] + S[1][x8[i+2]]) ^ S[2][x8[i+1]]) + S[3][x8[i]]); }; Blowfish.prototype.encipher = function(x, x8) { if (x8 === undefined) { x8 = new Uint8Array(x.buffer); if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); } x[0] ^= this.P[0]; for (var i = 1; i < 16; i += 2) { x[1] ^= F(this.S, x8, 0) ^ this.P[i]; x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; } var t = x[0]; x[0] = x[1] ^ this.P[17]; x[1] = t; }; Blowfish.prototype.decipher = function(x) { var x8 = new Uint8Array(x.buffer); if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); x[0] ^= this.P[17]; for (var i = 16; i > 0; i -= 2) { x[1] ^= F(this.S, x8, 0) ^ this.P[i]; x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; } var t = x[0]; x[0] = x[1] ^ this.P[0]; x[1] = t; }; function stream2word(data, databytes){ var i, temp = 0; for (i = 0; i < 4; i++, BLF_J++) { if (BLF_J >= databytes) BLF_J = 0; temp = (temp << 8) | data[BLF_J]; } return temp; }; Blowfish.prototype.expand0state = function(key, keybytes) { var d = new Uint32Array(2), i, k; var d8 = new Uint8Array(d.buffer); for (i = 0, BLF_J = 0; i < 18; i++) { this.P[i] ^= stream2word(key, keybytes); } BLF_J = 0; for (i = 0; i < 18; i += 2) { this.encipher(d, d8); this.P[i] = d[0]; this.P[i+1] = d[1]; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { this.encipher(d, d8); this.S[i][k] = d[0]; this.S[i][k+1] = d[1]; } } }; Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { var d = new Uint32Array(2), i, k; for (i = 0, BLF_J = 0; i < 18; i++) { this.P[i] ^= stream2word(key, keybytes); } for (i = 0, BLF_J = 0; i < 18; i += 2) { d[0] ^= stream2word(data, databytes); d[1] ^= stream2word(data, databytes); this.encipher(d); this.P[i] = d[0]; this.P[i+1] = d[1]; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { d[0] ^= stream2word(data, databytes); d[1] ^= stream2word(data, databytes); this.encipher(d); this.S[i][k] = d[0]; this.S[i][k+1] = d[1]; } } BLF_J = 0; }; Blowfish.prototype.enc = function(data, blocks) { for (var i = 0; i < blocks; i++) { this.encipher(data.subarray(i*2)); } }; Blowfish.prototype.dec = function(data, blocks) { for (var i = 0; i < blocks; i++) { this.decipher(data.subarray(i*2)); } }; var BCRYPT_BLOCKS = 8, BCRYPT_HASHSIZE = 32; function bcrypt_hash(sha2pass, sha2salt, out) { var state = new Blowfish(), cdata = new Uint32Array(BCRYPT_BLOCKS), i, ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, 105,116,101]); //"OxychromaticBlowfishSwatDynamite" state.expandstate(sha2salt, 64, sha2pass, 64); for (i = 0; i < 64; i++) { state.expand0state(sha2salt, 64); state.expand0state(sha2pass, 64); } for (i = 0; i < BCRYPT_BLOCKS; i++) cdata[i] = stream2word(ciphertext, ciphertext.byteLength); for (i = 0; i < 64; i++) state.enc(cdata, cdata.byteLength / 8); for (i = 0; i < BCRYPT_BLOCKS; i++) { out[4*i+3] = cdata[i] >>> 24; out[4*i+2] = cdata[i] >>> 16; out[4*i+1] = cdata[i] >>> 8; out[4*i+0] = cdata[i]; } }; function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { var sha2pass = new Uint8Array(64), sha2salt = new Uint8Array(64), out = new Uint8Array(BCRYPT_HASHSIZE), tmpout = new Uint8Array(BCRYPT_HASHSIZE), countsalt = new Uint8Array(saltlen+4), i, j, amt, stride, dest, count, origkeylen = keylen; if (rounds < 1) return -1; if (passlen === 0 || saltlen === 0 || keylen === 0 || keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) return -1; stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); amt = Math.floor((keylen + stride - 1) / stride); for (i = 0; i < saltlen; i++) countsalt[i] = salt[i]; crypto_hash_sha512(sha2pass, pass, passlen); for (count = 1; keylen > 0; count++) { countsalt[saltlen+0] = count >>> 24; countsalt[saltlen+1] = count >>> 16; countsalt[saltlen+2] = count >>> 8; countsalt[saltlen+3] = count; crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); bcrypt_hash(sha2pass, sha2salt, tmpout); for (i = out.byteLength; i--;) out[i] = tmpout[i]; for (i = 1; i < rounds; i++) { crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); bcrypt_hash(sha2pass, sha2salt, tmpout); for (j = 0; j < out.byteLength; j++) out[j] ^= tmpout[j]; } amt = Math.min(amt, keylen); for (i = 0; i < amt; i++) { dest = i * stride + (count - 1); if (dest >= origkeylen) break; key[dest] = out[i]; } keylen -= i; } return 0; }; module.exports = { BLOCKS: BCRYPT_BLOCKS, HASHSIZE: BCRYPT_HASHSIZE, hash: bcrypt_hash, pbkdf: bcrypt_pbkdf }; /***/ }), /***/ 4982: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const binding = __nccwpck_require__(5243); module.exports = binding.getCPUInfo; /***/ }), /***/ 6543: /***/ ((module) => { "use strict"; const isStream = stream => stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; isStream.writable = stream => isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; isStream.readable = stream => isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; isStream.duplex = stream => isStream.writable(stream) && isStream.readable(stream); isStream.transform = stream => isStream.duplex(stream) && typeof stream._transform === 'function'; module.exports = isStream; /***/ }), /***/ 6512: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const fs = __nccwpck_require__(9896); const path = __nccwpck_require__(6928); const {promisify} = __nccwpck_require__(9023); const semver = __nccwpck_require__(9318); const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0'); // https://github.com/nodejs/node/issues/8987 // https://github.com/libuv/libuv/pull/1088 const checkPath = pth => { if (process.platform === 'win32') { const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')); if (pathHasInvalidWinCharacters) { const error = new Error(`Path contains invalid characters: ${pth}`); error.code = 'EINVAL'; throw error; } } }; const processOptions = options => { // https://github.com/sindresorhus/make-dir/issues/18 const defaults = { mode: 0o777, fs }; return { ...defaults, ...options }; }; const permissionError = pth => { // This replicates the exception of `fs.mkdir` with native the // `recusive` option when run on an invalid drive under Windows. const error = new Error(`operation not permitted, mkdir '${pth}'`); error.code = 'EPERM'; error.errno = -4048; error.path = pth; error.syscall = 'mkdir'; return error; }; const makeDir = async (input, options) => { checkPath(input); options = processOptions(options); const mkdir = promisify(options.fs.mkdir); const stat = promisify(options.fs.stat); if (useNativeRecursiveOption && options.fs.mkdir === fs.mkdir) { const pth = path.resolve(input); await mkdir(pth, { mode: options.mode, recursive: true }); return pth; } const make = async pth => { try { await mkdir(pth, options.mode); return pth; } catch (error) { if (error.code === 'EPERM') { throw error; } if (error.code === 'ENOENT') { if (path.dirname(pth) === pth) { throw permissionError(pth); } if (error.message.includes('null bytes')) { throw error; } await make(path.dirname(pth)); return make(pth); } try { const stats = await stat(pth); if (!stats.isDirectory()) { throw new Error('The path is not a directory'); } } catch (_) { throw error; } return pth; } }; return make(path.resolve(input)); }; module.exports = makeDir; module.exports.sync = (input, options) => { checkPath(input); options = processOptions(options); if (useNativeRecursiveOption && options.fs.mkdirSync === fs.mkdirSync) { const pth = path.resolve(input); fs.mkdirSync(pth, { mode: options.mode, recursive: true }); return pth; } const make = pth => { try { options.fs.mkdirSync(pth, options.mode); } catch (error) { if (error.code === 'EPERM') { throw error; } if (error.code === 'ENOENT') { if (path.dirname(pth) === pth) { throw permissionError(pth); } if (error.message.includes('null bytes')) { throw error; } make(path.dirname(pth)); return make(pth); } try { if (!options.fs.statSync(pth).isDirectory()) { throw new Error('The path is not a directory'); } } catch (_) { throw error; } } return pth; }; return make(path.resolve(input)); }; /***/ }), /***/ 2803: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(181) var Buffer = buffer.Buffer var safer = {} var key for (key in buffer) { if (!buffer.hasOwnProperty(key)) continue if (key === 'SlowBuffer' || key === 'Buffer') continue safer[key] = buffer[key] } var Safer = safer.Buffer = {} for (key in Buffer) { if (!Buffer.hasOwnProperty(key)) continue if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue Safer[key] = Buffer[key] } safer.Buffer.prototype = Buffer.prototype if (!Safer.from || Safer.from === Uint8Array.from) { Safer.from = function (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) } if (value && typeof value.length === 'undefined') { throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) } return Buffer(value, encodingOrOffset, length) } } if (!Safer.alloc) { Safer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) } if (size < 0 || size >= 2 * (1 << 30)) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } var buf = Buffer(size) if (!fill || fill.length === 0) { buf.fill(0) } else if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } return buf } } if (!safer.kStringMaxLength) { try { safer.kStringMaxLength = process.binding('buffer').kStringMaxLength } catch (e) { // we can't determine kStringMaxLength in environments where process.binding // is unsupported, so let's not set it } } if (!safer.constants) { safer.constants = { MAX_LENGTH: safer.kMaxLength } if (safer.kStringMaxLength) { safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength } } module.exports = safer /***/ }), /***/ 9318: /***/ ((module, exports) => { exports = module.exports = SemVer var debug /* istanbul ignore next */ if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { debug = function () { var args = Array.prototype.slice.call(arguments, 0) args.unshift('SEMVER') console.log.apply(console, args) } } else { debug = function () {} } // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0' var MAX_LENGTH = 256 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16 // The actual regexps go on exports.re var re = exports.re = [] var src = exports.src = [] var t = exports.tokens = {} var R = 0 function tok (n) { t[n] = R++ } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. tok('NUMERICIDENTIFIER') src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' tok('NUMERICIDENTIFIERLOOSE') src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. tok('NONNUMERICIDENTIFIER') src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' // ## Main Version // Three dot-separated numeric identifiers. tok('MAINVERSION') src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')' tok('MAINVERSIONLOOSE') src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. tok('PRERELEASEIDENTIFIER') src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' tok('PRERELEASEIDENTIFIERLOOSE') src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + '|' + src[t.NONNUMERICIDENTIFIER] + ')' // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. tok('PRERELEASE') src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' tok('PRERELEASELOOSE') src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. tok('BUILDIDENTIFIER') src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. tok('BUILD') src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. tok('FULL') tok('FULLPLAIN') src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + src[t.PRERELEASE] + '?' + src[t.BUILD] + '?' src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. tok('LOOSEPLAIN') src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + '?' + src[t.BUILD] + '?' tok('LOOSE') src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' tok('GTLT') src[t.GTLT] = '((?:<|>)?=?)' // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. tok('XRANGEIDENTIFIERLOOSE') src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' tok('XRANGEIDENTIFIER') src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' tok('XRANGEPLAIN') src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:' + src[t.PRERELEASE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGEPLAINLOOSE') src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[t.PRERELEASELOOSE] + ')?' + src[t.BUILD] + '?' + ')?)?' tok('XRANGE') src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' tok('XRANGELOOSE') src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' // Coercion. // Extract anything that could conceivably be a part of a valid semver tok('COERCE') src[t.COERCE] = '(^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])' tok('COERCERTL') re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') // Tilde ranges. // Meaning is "reasonably at or greater than" tok('LONETILDE') src[t.LONETILDE] = '(?:~>?)' tok('TILDETRIM') src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') var tildeTrimReplace = '$1~' tok('TILDE') src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' tok('TILDELOOSE') src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' // Caret ranges. // Meaning is "at least and backwards compatible with" tok('LONECARET') src[t.LONECARET] = '(?:\\^)' tok('CARETTRIM') src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') var caretTrimReplace = '$1^' tok('CARET') src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' tok('CARETLOOSE') src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' // A simple gt/lt/eq thing, or just "" to indicate "any version" tok('COMPARATORLOOSE') src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' tok('COMPARATOR') src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` tok('COMPARATORTRIM') src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' // this one has to use the /g flag re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') var comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. tok('HYPHENRANGE') src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAIN] + ')' + '\\s*$' tok('HYPHENRANGELOOSE') src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s*$' // Star ranges basically just allow anything at all. tok('STAR') src[t.STAR] = '(<|>)?=?\\s*\\*' // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]) if (!re[i]) { re[i] = new RegExp(src[i]) } } exports.parse = parse function parse (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } var r = options.loose ? re[t.LOOSE] : re[t.FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } exports.valid = valid function valid (version, options) { var v = parse(version, options) return v ? v.version : null } exports.clean = clean function clean (version, options) { var s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } exports.SemVer = SemVer function SemVer (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { if (version.loose === options.loose) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version) } if (version.length > MAX_LENGTH) { throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } if (!(this instanceof SemVer)) { return new SemVer(version, options) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError('Invalid Version: ' + version) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map(function (id) { if (/^[0-9]+$/.test(id)) { var num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } SemVer.prototype.format = function () { this.version = this.major + '.' + this.minor + '.' + this.patch if (this.prerelease.length) { this.version += '-' + this.prerelease.join('.') } return this.version } SemVer.prototype.toString = function () { return this.version } SemVer.prototype.compare = function (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return this.compareMain(other) || this.comparePre(other) } SemVer.prototype.compareMain = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) } SemVer.prototype.comparePre = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } var i = 0 do { var a = this.prerelease[i] var b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } SemVer.prototype.compareBuild = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } var i = 0 do { var a = this.build[i] var b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function (release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier) this.inc('pre', identifier) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier) } this.inc('pre', identifier) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0] } else { var i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything this.prerelease.push(0) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0] } } else { this.prerelease = [identifier, 0] } } break default: throw new Error('invalid increment argument: ' + release) } this.format() this.raw = this.version return this } exports.inc = inc function inc (version, release, loose, identifier) { if (typeof (loose) === 'string') { identifier = loose loose = undefined } try { return new SemVer(version, loose).inc(release, identifier).version } catch (er) { return null } } exports.diff = diff function diff (version1, version2) { if (eq(version1, version2)) { return null } else { var v1 = parse(version1) var v2 = parse(version2) var prefix = '' if (v1.prerelease.length || v2.prerelease.length) { prefix = 'pre' var defaultResult = 'prerelease' } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } exports.compareIdentifiers = compareIdentifiers var numeric = /^[0-9]+$/ function compareIdentifiers (a, b) { var anum = numeric.test(a) var bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } exports.rcompareIdentifiers = rcompareIdentifiers function rcompareIdentifiers (a, b) { return compareIdentifiers(b, a) } exports.major = major function major (a, loose) { return new SemVer(a, loose).major } exports.minor = minor function minor (a, loose) { return new SemVer(a, loose).minor } exports.patch = patch function patch (a, loose) { return new SemVer(a, loose).patch } exports.compare = compare function compare (a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)) } exports.compareLoose = compareLoose function compareLoose (a, b) { return compare(a, b, true) } exports.compareBuild = compareBuild function compareBuild (a, b, loose) { var versionA = new SemVer(a, loose) var versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } exports.rcompare = rcompare function rcompare (a, b, loose) { return compare(b, a, loose) } exports.sort = sort function sort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(a, b, loose) }) } exports.rsort = rsort function rsort (list, loose) { return list.sort(function (a, b) { return exports.compareBuild(b, a, loose) }) } exports.gt = gt function gt (a, b, loose) { return compare(a, b, loose) > 0 } exports.lt = lt function lt (a, b, loose) { return compare(a, b, loose) < 0 } exports.eq = eq function eq (a, b, loose) { return compare(a, b, loose) === 0 } exports.neq = neq function neq (a, b, loose) { return compare(a, b, loose) !== 0 } exports.gte = gte function gte (a, b, loose) { return compare(a, b, loose) >= 0 } exports.lte = lte function lte (a, b, loose) { return compare(a, b, loose) <= 0 } exports.cmp = cmp function cmp (a, op, b, loose) { switch (op) { case '===': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a === b case '!==': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError('Invalid operator: ' + op) } } exports.Comparator = Comparator function Comparator (comp, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } if (!(this instanceof Comparator)) { return new Comparator(comp, options) } debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } var ANY = {} Comparator.prototype.parse = function (comp) { var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var m = comp.match(r) if (!m) { throw new TypeError('Invalid comparator: ' + comp) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } Comparator.prototype.toString = function () { return this.value } Comparator.prototype.test = function (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } Comparator.prototype.intersects = function (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } var rangeTmp if (this.operator === '') { if (this.value === '') { return true } rangeTmp = new Range(comp.value, options) return satisfies(this.value, rangeTmp, options) } else if (comp.operator === '') { if (comp.value === '') { return true } rangeTmp = new Range(this.value, options) return satisfies(comp.semver, rangeTmp, options) } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') var sameSemVer = this.semver.version === comp.semver.version var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')) var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')) return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } exports.Range = Range function Range (range, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (range instanceof Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { return new Range(range.value, options) } if (!(this instanceof Range)) { return new Range(range, options) } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First, split based on boolean or || this.raw = range this.set = range.split(/\s*\|\|\s*/).map(function (range) { return this.parseRange(range.trim()) }, this).filter(function (c) { // throw out any that are not relevant for whatever reason return c.length }) if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + range) } this.format() } Range.prototype.format = function () { this.range = this.set.map(function (comps) { return comps.join(' ').trim() }).join('||').trim() return this.range } Range.prototype.toString = function () { return this.range } Range.prototype.parseRange = function (range) { var loose = this.options.loose range = range.trim() // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, re[t.COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) // normalize spaces range = range.split(/\s+/).join(' ') // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] var set = range.split(' ').map(function (comp) { return parseComparator(comp, this.options) }, this).join(' ').split(/\s+/) if (this.options.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function (comp) { return !!comp.match(compRe) }) } set = set.map(function (comp) { return new Comparator(comp, this.options) }, this) return set } Range.prototype.intersects = function (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some(function (thisComparators) { return ( isSatisfiable(thisComparators, options) && range.set.some(function (rangeComparators) { return ( isSatisfiable(rangeComparators, options) && thisComparators.every(function (thisComparator) { return rangeComparators.every(function (rangeComparator) { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // take a set of comparators and determine whether there // exists a version which can satisfy it function isSatisfiable (comparators, options) { var result = true var remainingComparators = comparators.slice() var testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every(function (otherComparator) { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // Mostly just for testing and legacy API reasons exports.toComparators = toComparators function toComparators (range, options) { return new Range(range, options).set.map(function (comp) { return comp.map(function (c) { return c.value }).join(' ').trim().split(' ') }) } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator (comp, options) { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } function isX (id) { return !id || id.toLowerCase() === 'x' || id === '*' } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceTilde(comp, options) }).join(' ') } function replaceTilde (comp, options) { var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, function (_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else if (pr) { debug('replaceTilde pr', pr) ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } else { // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceCaret(comp, options) }).join(' ') } function replaceCaret (comp, options) { debug('caret', comp, options) var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] return comp.replace(r, function (_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { if (M === '0') { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else { ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0' } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0' } } debug('caret return', ret) return ret }) } function replaceXRanges (comp, options) { debug('replaceXRanges', comp, options) return comp.split(/\s+/).map(function (comp) { return replaceXRange(comp, options) }).join(' ') } function replaceXRange (comp, options) { comp = comp.trim() var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, function (ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr) var xM = isX(M) var xm = xM || isX(m) var xp = xm || isX(p) var anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 // >1.2.3 => >= 1.2.4 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } ret = gtlt + M + '.' + m + '.' + p + pr } else if (xm) { ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr } else if (xp) { ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars (comp, options) { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re[t.STAR], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) { from = '' } else if (isX(fm)) { from = '>=' + fM + '.0.0' } else if (isX(fp)) { from = '>=' + fM + '.' + fm + '.0' } else { from = '>=' + from } if (isX(tM)) { to = '' } else if (isX(tm)) { to = '<' + (+tM + 1) + '.0.0' } else if (isX(tp)) { to = '<' + tM + '.' + (+tm + 1) + '.0' } else if (tpr) { to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr } else { to = '<=' + to } return (from + ' ' + to).trim() } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } function testSet (set, version, options) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === ANY) { continue } if (set[i].semver.prerelease.length > 0) { var allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } exports.satisfies = satisfies function satisfies (version, range, options) { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } exports.maxSatisfying = maxSatisfying function maxSatisfying (versions, range, options) { var max = null var maxSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } exports.minSatisfying = minSatisfying function minSatisfying (versions, range, options) { var min = null var minSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } exports.minVersion = minVersion function minVersion (range, loose) { range = new Range(range, loose) var minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] comparators.forEach(function (comparator) { // Clone to avoid manipulating the comparator's semver object. var compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!minver || gt(minver, compver)) { minver = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error('Unexpected operation: ' + comparator.operator) } }) } if (minver && range.test(minver)) { return minver } return null } exports.validRange = validRange function validRange (range, options) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr function ltr (version, range, options) { return outside(version, range, '<', options) } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr function gtr (version, range, options) { return outside(version, range, '>', options) } exports.outside = outside function outside (version, range, hilo, options) { version = new SemVer(version, options) range = new Range(range, options) var gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisifes the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] var high = null var low = null comparators.forEach(function (comparator) { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } exports.prerelease = prerelease function prerelease (version, options) { var parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } exports.intersects = intersects function intersects (r1, r2, options) { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } exports.coerce = coerce function coerce (version, options) { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} var match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. var next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options) } /***/ }), /***/ 4646: /***/ ((module) => { module.exports = shellescape; // return a shell compatible format function shellescape(a) { var ret = []; a.forEach(function(s) { if (!/^[A-Za-z0-9_\/-]+$/.test(s)) { s = "'"+s.replace(/'/g,"'\\''")+"'"; s = s.replace(/^(?:'')+/g, '') // unduplicate single-quote at the beginning .replace(/\\'''/g, "\\'" ); // remove non-escaped single-quote if there are enclosed between 2 escaped } ret.push(s); }); return ret.join(' '); } /***/ }), /***/ 4440: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = { SFTPStream: __nccwpck_require__(507), SSH2Stream: __nccwpck_require__(8494), utils: __nccwpck_require__(2557), constants: __nccwpck_require__(4169) }; /***/ }), /***/ 4288: /***/ ((module) => { module.exports = { readUInt32BE: function readUInt32BE(buf, offset) { return buf[offset++] * 16777216 + buf[offset++] * 65536 + buf[offset++] * 256 + buf[offset]; }, writeUInt32BE: function writeUInt32BE(buf, value, offset) { buf[offset++] = (value >>> 24); buf[offset++] = (value >>> 16); buf[offset++] = (value >>> 8); buf[offset++] = value; return offset; }, writeUInt32LE: function writeUInt32LE(buf, value, offset) { buf[offset++] = value; buf[offset++] = (value >>> 8); buf[offset++] = (value >>> 16); buf[offset++] = (value >>> 24); return offset; } }; /***/ }), /***/ 4169: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var i; var keys; var len; var crypto = __nccwpck_require__(6982); var eddsaSupported = (function() { if (typeof crypto.sign === 'function' && typeof crypto.verify === 'function') { var key = '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; var data = Buffer.from('a'); var sig; var verified; try { sig = crypto.sign(null, data, key); verified = crypto.verify(null, data, key, sig); } catch (ex) {} return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); } return false; })(); var curve25519Supported = (typeof crypto.diffieHellman === 'function' && typeof crypto.generateKeyPairSync === 'function' && typeof crypto.createPublicKey === 'function'); var MESSAGE = exports.MESSAGE = { // Transport layer protocol -- generic (1-19) DISCONNECT: 1, IGNORE: 2, UNIMPLEMENTED: 3, DEBUG: 4, SERVICE_REQUEST: 5, SERVICE_ACCEPT: 6, // Transport layer protocol -- algorithm negotiation (20-29) KEXINIT: 20, NEWKEYS: 21, // Transport layer protocol -- key exchange method-specific (30-49) // User auth protocol -- generic (50-59) USERAUTH_REQUEST: 50, USERAUTH_FAILURE: 51, USERAUTH_SUCCESS: 52, USERAUTH_BANNER: 53, // User auth protocol -- user auth method-specific (60-79) // Connection protocol -- generic (80-89) GLOBAL_REQUEST: 80, REQUEST_SUCCESS: 81, REQUEST_FAILURE: 82, // Connection protocol -- channel-related (90-127) CHANNEL_OPEN: 90, CHANNEL_OPEN_CONFIRMATION: 91, CHANNEL_OPEN_FAILURE: 92, CHANNEL_WINDOW_ADJUST: 93, CHANNEL_DATA: 94, CHANNEL_EXTENDED_DATA: 95, CHANNEL_EOF: 96, CHANNEL_CLOSE: 97, CHANNEL_REQUEST: 98, CHANNEL_SUCCESS: 99, CHANNEL_FAILURE: 100 // Reserved for client protocols (128-191) // Local extensions (192-155) }; for (i = 0, keys = Object.keys(MESSAGE), len = keys.length; i < len; ++i) MESSAGE[MESSAGE[keys[i]]] = keys[i]; // context-specific message codes: MESSAGE.KEXDH_INIT = 30; MESSAGE.KEXDH_REPLY = 31; MESSAGE.KEXDH_GEX_REQUEST = 34; MESSAGE.KEXDH_GEX_GROUP = 31; MESSAGE.KEXDH_GEX_INIT = 32; MESSAGE.KEXDH_GEX_REPLY = 33; MESSAGE.KEXECDH_INIT = 30; // included here for completeness MESSAGE.KEXECDH_REPLY = 31; // included here for completeness MESSAGE.USERAUTH_PASSWD_CHANGEREQ = 60; MESSAGE.USERAUTH_PK_OK = 60; MESSAGE.USERAUTH_INFO_REQUEST = 60; MESSAGE.USERAUTH_INFO_RESPONSE = 61; var DYNAMIC_KEXDH_MESSAGE = exports.DYNAMIC_KEXDH_MESSAGE = {}; DYNAMIC_KEXDH_MESSAGE[MESSAGE.KEXDH_GEX_GROUP] = 'KEXDH_GEX_GROUP'; DYNAMIC_KEXDH_MESSAGE[MESSAGE.KEXDH_GEX_REPLY] = 'KEXDH_GEX_REPLY'; var KEXDH_MESSAGE = exports.KEXDH_MESSAGE = {}; KEXDH_MESSAGE[MESSAGE.KEXDH_INIT] = 'KEXDH_INIT'; KEXDH_MESSAGE[MESSAGE.KEXDH_REPLY] = 'KEXDH_REPLY'; var DISCONNECT_REASON = exports.DISCONNECT_REASON = { HOST_NOT_ALLOWED_TO_CONNECT: 1, PROTOCOL_ERROR: 2, KEY_EXCHANGE_FAILED: 3, RESERVED: 4, MAC_ERROR: 5, COMPRESSION_ERROR: 6, SERVICE_NOT_AVAILABLE: 7, PROTOCOL_VERSION_NOT_SUPPORTED: 8, HOST_KEY_NOT_VERIFIABLE: 9, CONNECTION_LOST: 10, BY_APPLICATION: 11, TOO_MANY_CONNECTIONS: 12, AUTH_CANCELED_BY_USER: 13, NO_MORE_AUTH_METHODS_AVAILABLE: 14, ILLEGAL_USER_NAME: 15 }; for (i = 0, keys = Object.keys(DISCONNECT_REASON), len = keys.length; i < len; ++i) { DISCONNECT_REASON[DISCONNECT_REASON[keys[i]]] = keys[i]; } var CHANNEL_OPEN_FAILURE = exports.CHANNEL_OPEN_FAILURE = { ADMINISTRATIVELY_PROHIBITED: 1, CONNECT_FAILED: 2, UNKNOWN_CHANNEL_TYPE: 3, RESOURCE_SHORTAGE: 4 }; for (i = 0, keys = Object.keys(CHANNEL_OPEN_FAILURE), len = keys.length; i < len; ++i) { CHANNEL_OPEN_FAILURE[CHANNEL_OPEN_FAILURE[keys[i]]] = keys[i]; } var TERMINAL_MODE = exports.TERMINAL_MODE = { TTY_OP_END: 0, // Indicates end of options. VINTR: 1, // Interrupt character; 255 if none. Similarly for the // other characters. Not all of these characters are // supported on all systems. VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX // systems). VERASE: 3, // Erase the character to left of the cursor. VKILL: 4, // Kill the current input line. VEOF: 5, // End-of-file character (sends EOF from the terminal). VEOL: 6, // End-of-line character in addition to carriage return // and/or linefeed. VEOL2: 7, // Additional end-of-line character. VSTART: 8, // Continues paused output (normally control-Q). VSTOP: 9, // Pauses output (normally control-S). VSUSP: 10, // Suspends the current program. VDSUSP: 11, // Another suspend character. VREPRINT: 12, // Reprints the current input line. VWERASE: 13, // Erases a word left of cursor. VLNEXT: 14, // Enter the next character typed literally, even if it // is a special character VFLUSH: 15, // Character to flush output. VSWTCH: 16, // Switch to a different shell layer. VSTATUS: 17, // Prints system status line (load, command, pid, etc). VDISCARD: 18, // Toggles the flushing of terminal output. IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 // if this flag is FALSE, and 1 if it is TRUE. PARMRK: 31, // Mark parity and framing errors. INPCK: 32, // Enable checking of parity errors. ISTRIP: 33, // Strip 8th bit off characters. INLCR: 34, // Map NL into CR on input. IGNCR: 35, // Ignore CR on input. ICRNL: 36, // Map CR to NL on input. IUCLC: 37, // Translate uppercase characters to lowercase. IXON: 38, // Enable output flow control. IXANY: 39, // Any char will restart after stop. IXOFF: 40, // Enable input flow control. IMAXBEL: 41, // Ring bell on input queue full. ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. ICANON: 51, // Canonicalize input lines. XCASE: 52, // Enable input and output of uppercase characters by // preceding their lowercase equivalents with "\". ECHO: 53, // Enable echoing. ECHOE: 54, // Visually erase chars. ECHOK: 55, // Kill character discards current line. ECHONL: 56, // Echo NL even if ECHO is off. NOFLSH: 57, // Don't flush after interrupt. TOSTOP: 58, // Stop background jobs from output. IEXTEN: 59, // Enable extensions. ECHOCTL: 60, // Echo control characters as ^(Char). ECHOKE: 61, // Visual erase for line kill. PENDIN: 62, // Retype pending input. OPOST: 70, // Enable output processing. OLCUC: 71, // Convert lowercase to uppercase. ONLCR: 72, // Map NL to CR-NL. OCRNL: 73, // Translate carriage return to newline (output). ONOCR: 74, // Translate newline to carriage return-newline // (output). ONLRET: 75, // Newline performs a carriage return (output). CS7: 90, // 7 bit mode. CS8: 91, // 8 bit mode. PARENB: 92, // Parity enable. PARODD: 93, // Odd parity, else even. TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. TTY_OP_OSPEED: 129 // Specifies the output baud rate in bits per second. }; for (i = 0, keys = Object.keys(TERMINAL_MODE), len = keys.length; i < len; ++i) TERMINAL_MODE[TERMINAL_MODE[keys[i]]] = keys[i]; var CHANNEL_EXTENDED_DATATYPE = exports.CHANNEL_EXTENDED_DATATYPE = { STDERR: 1 }; for (i = 0, keys = Object.keys(CHANNEL_EXTENDED_DATATYPE), len = keys.length; i < len; ++i) { CHANNEL_EXTENDED_DATATYPE[CHANNEL_EXTENDED_DATATYPE[keys[i]]] = keys[i]; } exports.SIGNALS = ['ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', 'USR2', 'KILL', 'PIPE']; var DEFAULT_KEX = [ // https://tools.ietf.org/html/rfc5656#section-10.1 'ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', // https://tools.ietf.org/html/rfc4419#section-4 'diffie-hellman-group-exchange-sha256', 'diffie-hellman-group14-sha256', 'diffie-hellman-group16-sha512', 'diffie-hellman-group18-sha512', 'diffie-hellman-group14-sha1', // REQUIRED ]; if (curve25519Supported) { DEFAULT_KEX.unshift('curve25519-sha256'); DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); } var SUPPORTED_KEX = [ // https://tools.ietf.org/html/rfc4419#section-4 'diffie-hellman-group-exchange-sha1', 'diffie-hellman-group1-sha1' // REQUIRED ]; var KEX_BUF = Buffer.from(DEFAULT_KEX.join(','), 'ascii'); SUPPORTED_KEX = DEFAULT_KEX.concat(SUPPORTED_KEX); var DEFAULT_SERVER_HOST_KEY = [ 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521', 'ssh-rsa', ]; if (eddsaSupported) DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); var SUPPORTED_SERVER_HOST_KEY = [ 'ssh-dss' ]; var SERVER_HOST_KEY_BUF = Buffer.from(DEFAULT_SERVER_HOST_KEY.join(','), 'ascii'); SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat( SUPPORTED_SERVER_HOST_KEY ); var DEFAULT_CIPHER = [ // http://tools.ietf.org/html/rfc4344#section-4 'aes128-ctr', 'aes192-ctr', 'aes256-ctr', // http://tools.ietf.org/html/rfc5647 'aes128-gcm', 'aes128-gcm@openssh.com', 'aes256-gcm', 'aes256-gcm@openssh.com' ]; var SUPPORTED_CIPHER = [ 'aes256-cbc', 'aes192-cbc', 'aes128-cbc', 'blowfish-cbc', '3des-cbc', // http://tools.ietf.org/html/rfc4345#section-4: 'arcfour256', 'arcfour128', 'cast128-cbc', 'arcfour' ]; var CIPHER_BUF = Buffer.from(DEFAULT_CIPHER.join(','), 'ascii'); SUPPORTED_CIPHER = DEFAULT_CIPHER.concat(SUPPORTED_CIPHER); var DEFAULT_HMAC = [ 'hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1', ]; var SUPPORTED_HMAC = [ 'hmac-md5', 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 'hmac-ripemd160', 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 'hmac-md5-96' // first 96 bits of HMAC-MD5 ]; var HMAC_BUF = Buffer.from(DEFAULT_HMAC.join(','), 'ascii'); SUPPORTED_HMAC = DEFAULT_HMAC.concat(SUPPORTED_HMAC); var DEFAULT_COMPRESS = [ 'none', 'zlib@openssh.com', // ZLIB (LZ77) compression, except // compression/decompression does not start until after // successful user authentication 'zlib' // ZLIB (LZ77) compression ]; var SUPPORTED_COMPRESS = []; var COMPRESS_BUF = Buffer.from(DEFAULT_COMPRESS.join(','), 'ascii'); SUPPORTED_COMPRESS = DEFAULT_COMPRESS.concat(SUPPORTED_COMPRESS); function makeCipherInfo(blockLen, keyLen, ivLen, authLen, discardLen, stream) { return { blockLen: blockLen, keyLen: keyLen, ivLen: ivLen === 0 ? blockLen : ivLen, authLen: authLen, discardLen: discardLen, stream: stream, }; } exports.CIPHER_INFO = { 'aes128-gcm': makeCipherInfo(16, 16, 12, 16, 0, false), 'aes256-gcm': makeCipherInfo(16, 32, 12, 16, 0, false), 'aes128-gcm@openssh.com': makeCipherInfo(16, 16, 12, 16, 0, false), 'aes256-gcm@openssh.com': makeCipherInfo(16, 32, 12, 16, 0, false), 'aes128-cbc': makeCipherInfo(16, 16, 0, 0, 0, false), 'aes192-cbc': makeCipherInfo(16, 24, 0, 0, 0, false), 'aes256-cbc': makeCipherInfo(16, 32, 0, 0, 0, false), 'rijndael-cbc@lysator.liu.se': makeCipherInfo(16, 32, 0, 0, 0, false), '3des-cbc': makeCipherInfo(8, 24, 0, 0, 0, false), 'blowfish-cbc': makeCipherInfo(8, 16, 0, 0, 0, false), 'idea-cbc': makeCipherInfo(8, 16, 0, 0, 0, false), 'cast128-cbc': makeCipherInfo(8, 16, 0, 0, 0, false), 'camellia128-cbc': makeCipherInfo(16, 16, 0, 0, 0, false), 'camellia192-cbc': makeCipherInfo(16, 24, 0, 0, 0, false), 'camellia256-cbc': makeCipherInfo(16, 32, 0, 0, 0, false), 'camellia128-cbc@openssh.com': makeCipherInfo(16, 16, 0, 0, 0, false), 'camellia192-cbc@openssh.com': makeCipherInfo(16, 24, 0, 0, 0, false), 'camellia256-cbc@openssh.com': makeCipherInfo(16, 32, 0, 0, 0, false), 'aes128-ctr': makeCipherInfo(16, 16, 0, 0, 0, false), 'aes192-ctr': makeCipherInfo(16, 24, 0, 0, 0, false), 'aes256-ctr': makeCipherInfo(16, 32, 0, 0, 0, false), '3des-ctr': makeCipherInfo(8, 24, 0, 0, 0, false), 'blowfish-ctr': makeCipherInfo(8, 16, 0, 0, 0, false), 'cast128-ctr': makeCipherInfo(8, 16, 0, 0, 0, false), 'camellia128-ctr': makeCipherInfo(16, 16, 0, 0, 0, false), 'camellia192-ctr': makeCipherInfo(16, 24, 0, 0, 0, false), 'camellia256-ctr': makeCipherInfo(16, 32, 0, 0, 0, false), 'camellia128-ctr@openssh.com': makeCipherInfo(16, 16, 0, 0, 0, false), 'camellia192-ctr@openssh.com': makeCipherInfo(16, 24, 0, 0, 0, false), 'camellia256-ctr@openssh.com': makeCipherInfo(16, 32, 0, 0, 0, false), /* The "arcfour128" algorithm is the RC4 cipher, as described in [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream generated by the cipher MUST be discarded, and the first byte of the first encrypted packet MUST be encrypted using the 1537th byte of keystream. -- http://tools.ietf.org/html/rfc4345#section-4 */ 'arcfour': makeCipherInfo(8, 16, 0, 0, 1536, true), 'arcfour128': makeCipherInfo(8, 16, 0, 0, 1536, true), 'arcfour256': makeCipherInfo(8, 32, 0, 0, 1536, true), 'arcfour512': makeCipherInfo(8, 64, 0, 0, 1536, true), }; function makeHMACInfo(len, actualLen) { return { len: len, actualLen: actualLen }; } exports.HMAC_INFO = { 'hmac-md5': makeHMACInfo(16, 16), 'hmac-md5-96': makeHMACInfo(16, 12), 'hmac-ripemd160': makeHMACInfo(20, 20), 'hmac-sha1': makeHMACInfo(20, 20), 'hmac-sha1-96': makeHMACInfo(20, 12), 'hmac-sha2-256': makeHMACInfo(32, 32), 'hmac-sha2-256-96': makeHMACInfo(32, 12), 'hmac-sha2-512': makeHMACInfo(64, 64), 'hmac-sha2-512-96': makeHMACInfo(64, 12), }; exports.ALGORITHMS = { KEX: DEFAULT_KEX, KEX_BUF: KEX_BUF, SUPPORTED_KEX: SUPPORTED_KEX, SERVER_HOST_KEY: DEFAULT_SERVER_HOST_KEY, SERVER_HOST_KEY_BUF: SERVER_HOST_KEY_BUF, SUPPORTED_SERVER_HOST_KEY: SUPPORTED_SERVER_HOST_KEY, CIPHER: DEFAULT_CIPHER, CIPHER_BUF: CIPHER_BUF, SUPPORTED_CIPHER: SUPPORTED_CIPHER, HMAC: DEFAULT_HMAC, HMAC_BUF: HMAC_BUF, SUPPORTED_HMAC: SUPPORTED_HMAC, COMPRESS: DEFAULT_COMPRESS, COMPRESS_BUF: COMPRESS_BUF, SUPPORTED_COMPRESS: SUPPORTED_COMPRESS }; exports.SSH_TO_OPENSSL = { // ECDH key exchange 'ecdh-sha2-nistp256': 'prime256v1', // OpenSSL's name for 'secp256r1' 'ecdh-sha2-nistp384': 'secp384r1', 'ecdh-sha2-nistp521': 'secp521r1', // Ciphers 'aes128-gcm': 'aes-128-gcm', 'aes256-gcm': 'aes-256-gcm', 'aes128-gcm@openssh.com': 'aes-128-gcm', 'aes256-gcm@openssh.com': 'aes-256-gcm', '3des-cbc': 'des-ede3-cbc', 'blowfish-cbc': 'bf-cbc', 'aes256-cbc': 'aes-256-cbc', 'aes192-cbc': 'aes-192-cbc', 'aes128-cbc': 'aes-128-cbc', 'idea-cbc': 'idea-cbc', 'cast128-cbc': 'cast-cbc', 'rijndael-cbc@lysator.liu.se': 'aes-256-cbc', 'arcfour128': 'rc4', 'arcfour256': 'rc4', 'arcfour512': 'rc4', 'arcfour': 'rc4', 'camellia128-cbc': 'camellia-128-cbc', 'camellia192-cbc': 'camellia-192-cbc', 'camellia256-cbc': 'camellia-256-cbc', 'camellia128-cbc@openssh.com': 'camellia-128-cbc', 'camellia192-cbc@openssh.com': 'camellia-192-cbc', 'camellia256-cbc@openssh.com': 'camellia-256-cbc', '3des-ctr': 'des-ede3', 'blowfish-ctr': 'bf-ecb', 'aes256-ctr': 'aes-256-ctr', 'aes192-ctr': 'aes-192-ctr', 'aes128-ctr': 'aes-128-ctr', 'cast128-ctr': 'cast5-ecb', 'camellia128-ctr': 'camellia-128-ecb', 'camellia192-ctr': 'camellia-192-ecb', 'camellia256-ctr': 'camellia-256-ecb', 'camellia128-ctr@openssh.com': 'camellia-128-ecb', 'camellia192-ctr@openssh.com': 'camellia-192-ecb', 'camellia256-ctr@openssh.com': 'camellia-256-ecb', // HMAC 'hmac-sha1-96': 'sha1', 'hmac-sha1': 'sha1', 'hmac-sha2-256': 'sha256', 'hmac-sha2-256-96': 'sha256', 'hmac-sha2-512': 'sha512', 'hmac-sha2-512-96': 'sha512', 'hmac-md5-96': 'md5', 'hmac-md5': 'md5', 'hmac-ripemd160': 'ripemd160' }; var BUGS = exports.BUGS = { BAD_DHGEX: 1, OLD_EXIT: 2, DYN_RPORT_BUG: 4 }; exports.BUGGY_IMPLS = [ [ 'Cisco-1.25', BUGS.BAD_DHGEX ], [ /^[0-9.]+$/, BUGS.OLD_EXIT ], // old SSH.com implementations [ /^OpenSSH_5\.\d+/, BUGS.DYN_RPORT_BUG ] ]; exports.EDDSA_SUPPORTED = eddsaSupported; exports.CURVE25519_SUPPORTED = curve25519Supported; /***/ }), /***/ 4441: /***/ ((module) => { // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // Set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } BigInteger.prototype.am = am3; dbits = 28; BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+this.DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); } else this[this.t-1] |= x<= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1< 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this[i]&((1<>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return (this.s<0)?-r:r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1< 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005-2009 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // Version 1.2: square() API, isProbablePrime fix // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this[1]&((1<<(32-this.DB))-1))<>24; } // (public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } // (protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } // (protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1< 0) { if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this[i]&((1<>(p+=this.DB-8); } else { d = (this[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r[i] = op(this[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this[i] != 0) return i*this.DB+lbit(this[i]); if(this.s < 0) return this.t*this.DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this^2 function bnSquare() { var r = nbi(); this.squareTo(r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1< 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // JSBN-specific extension BigInteger.prototype.square = bnSquare; // Expose the Barrett function BigInteger.prototype.Barrett = Barrett // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) module.exports = BigInteger; /***/ }), /***/ 7044: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // TODO: // * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` // * handle multi-line header values (OpenSSH)? // * more thorough validation? var crypto = __nccwpck_require__(6982); var cryptoSign = crypto.sign; var cryptoVerify = crypto.verify; var createSign = crypto.createSign; var createVerify = crypto.createVerify; var createDecipheriv = crypto.createDecipheriv; var createHash = crypto.createHash; var createHmac = crypto.createHmac; var supportedOpenSSLCiphers = crypto.getCiphers(); var utils; var Ber = (__nccwpck_require__(9837).Ber); var bcrypt_pbkdf = (__nccwpck_require__(686).pbkdf); var bufferHelpers = __nccwpck_require__(4288); var readUInt32BE = bufferHelpers.readUInt32BE; var writeUInt32BE = bufferHelpers.writeUInt32BE; var constants = __nccwpck_require__(4169); var SUPPORTED_CIPHER = constants.ALGORITHMS.SUPPORTED_CIPHER; var CIPHER_INFO = constants.CIPHER_INFO; var SSH_TO_OPENSSL = constants.SSH_TO_OPENSSL; var EDDSA_SUPPORTED = constants.EDDSA_SUPPORTED; var SYM_HASH_ALGO = Symbol('Hash Algorithm'); var SYM_PRIV_PEM = Symbol('Private key PEM'); var SYM_PUB_PEM = Symbol('Public key PEM'); var SYM_PUB_SSH = Symbol('Public key SSH'); var SYM_DECRYPTED = Symbol('Decrypted Key'); // Create OpenSSL cipher name -> SSH cipher name conversion table var CIPHER_INFO_OPENSSL = Object.create(null); (function() { var keys = Object.keys(CIPHER_INFO); for (var i = 0; i < keys.length; ++i) { var cipherName = SSH_TO_OPENSSL[keys[i]]; if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) continue; CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; } })(); var trimStart = (function() { if (typeof String.prototype.trimStart === 'function') { return function trimStart(str) { return str.trimStart(); }; } return function trimStart(str) { var start = 0; for (var i = 0; i < str.length; ++i) { switch (str.charCodeAt(i)) { case 32: // ' ' case 9: // '\t' case 13: // '\r' case 10: // '\n' case 12: // '\f' ++start; continue; } break; } if (start === 0) return str; return str.slice(start); }; })(); function makePEM(type, data) { data = data.toString('base64'); return '-----BEGIN ' + type + ' KEY-----\n' + data.replace(/.{64}/g, '$&\n') + (data.length % 64 ? '\n' : '') + '-----END ' + type + ' KEY-----'; } function combineBuffers(buf1, buf2) { var result = Buffer.allocUnsafe(buf1.length + buf2.length); buf1.copy(result, 0); buf2.copy(result, buf1.length); return result; } function skipFields(buf, nfields) { var bufLen = buf.length; var pos = (buf._pos || 0); for (var i = 0; i < nfields; ++i) { var left = (bufLen - pos); if (pos >= bufLen || left < 4) return false; var len = readUInt32BE(buf, pos); if (left < 4 + len) return false; pos += 4 + len; } buf._pos = pos; return true; } function genOpenSSLRSAPub(n, e) { var asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption // algorithm parameters (RSA has none) asnWriter.writeNull(); asnWriter.endSequence(); // subjectPublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); asnWriter.startSequence(); asnWriter.writeBuffer(n, Ber.Integer); asnWriter.writeBuffer(e, Ber.Integer); asnWriter.endSequence(); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHRSAPub(n, e) { var publicKey = Buffer.allocUnsafe(4 + 7 // "ssh-rsa" + 4 + n.length + 4 + e.length); writeUInt32BE(publicKey, 7, 0); publicKey.write('ssh-rsa', 4, 7, 'ascii'); var i = 4 + 7; writeUInt32BE(publicKey, e.length, i); e.copy(publicKey, i += 4); writeUInt32BE(publicKey, n.length, i += e.length); n.copy(publicKey, i + 4); return publicKey; } var genOpenSSLRSAPriv = (function() { function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { var asnWriter = new Ber.Writer(); asnWriter.startSequence(); asnWriter.writeInt(0x00, Ber.Integer); asnWriter.writeBuffer(n, Ber.Integer); asnWriter.writeBuffer(e, Ber.Integer); asnWriter.writeBuffer(d, Ber.Integer); asnWriter.writeBuffer(p, Ber.Integer); asnWriter.writeBuffer(q, Ber.Integer); asnWriter.writeBuffer(dmp1, Ber.Integer); asnWriter.writeBuffer(dmq1, Ber.Integer); asnWriter.writeBuffer(iqmp, Ber.Integer); asnWriter.endSequence(); return asnWriter.buffer; } function bigIntFromBuffer(buf) { return BigInt('0x' + buf.toString('hex')); } function bigIntToBuffer(bn) { var hex = bn.toString(16); if ((hex.length & 1) !== 0) { hex = '0' + hex; } else { var sigbit = hex.charCodeAt(0); // BER/DER integers require leading zero byte to denote a positive value // when first byte >= 0x80 if (sigbit === 56 || (sigbit >= 97 && sigbit <= 102)) hex = '00' + hex; } return Buffer.from(hex, 'hex'); } // Feature detect native BigInt availability and use it when possible try { var code = [ 'return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) {', ' var bn_d = bigIntFromBuffer(d);', ' var dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n));', ' var dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n));', ' return makePEM(\'RSA PRIVATE\', ' + 'genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp));', '};' ].join('\n'); return new Function( 'bigIntFromBuffer, bigIntToBuffer, makePEM, genRSAASN1Buf', code )(bigIntFromBuffer, bigIntToBuffer, makePEM, genRSAASN1Buf); } catch (ex) { return (function() { var BigInteger = __nccwpck_require__(4441); return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { var pbi = new BigInteger(p, 256); var qbi = new BigInteger(q, 256); var dbi = new BigInteger(d, 256); var dmp1bi = dbi.mod(pbi.subtract(BigInteger.ONE)); var dmq1bi = dbi.mod(qbi.subtract(BigInteger.ONE)); var dmp1 = Buffer.from(dmp1bi.toByteArray()); var dmq1 = Buffer.from(dmq1bi.toByteArray()); return makePEM('RSA PRIVATE', genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); }; })(); } })(); function genOpenSSLDSAPub(p, q, g, y) { var asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa // algorithm parameters asnWriter.startSequence(); asnWriter.writeBuffer(p, Ber.Integer); asnWriter.writeBuffer(q, Ber.Integer); asnWriter.writeBuffer(g, Ber.Integer); asnWriter.endSequence(); asnWriter.endSequence(); // subjectPublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); asnWriter.writeBuffer(y, Ber.Integer); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHDSAPub(p, q, g, y) { var publicKey = Buffer.allocUnsafe(4 + 7 // ssh-dss + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length); writeUInt32BE(publicKey, 7, 0); publicKey.write('ssh-dss', 4, 7, 'ascii'); var i = 4 + 7; writeUInt32BE(publicKey, p.length, i); p.copy(publicKey, i += 4); writeUInt32BE(publicKey, q.length, i += p.length); q.copy(publicKey, i += 4); writeUInt32BE(publicKey, g.length, i += q.length); g.copy(publicKey, i += 4); writeUInt32BE(publicKey, y.length, i += g.length); y.copy(publicKey, i + 4); return publicKey; } function genOpenSSLDSAPriv(p, q, g, y, x) { var asnWriter = new Ber.Writer(); asnWriter.startSequence(); asnWriter.writeInt(0x00, Ber.Integer); asnWriter.writeBuffer(p, Ber.Integer); asnWriter.writeBuffer(q, Ber.Integer); asnWriter.writeBuffer(g, Ber.Integer); asnWriter.writeBuffer(y, Ber.Integer); asnWriter.writeBuffer(x, Ber.Integer); asnWriter.endSequence(); return makePEM('DSA PRIVATE', asnWriter.buffer); } function genOpenSSLEdPub(pub) { var asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.3.101.112'); // id-Ed25519 asnWriter.endSequence(); // PublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(pub.length); pub.copy(asnWriter._buf, asnWriter._offset, 0, pub.length); asnWriter._offset += pub.length; asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHEdPub(pub) { var publicKey = Buffer.allocUnsafe(4 + 11 // ssh-ed25519 + 4 + pub.length); writeUInt32BE(publicKey, 11, 0); publicKey.write('ssh-ed25519', 4, 11, 'ascii'); writeUInt32BE(publicKey, pub.length, 15); pub.copy(publicKey, 19); return publicKey; } function genOpenSSLEdPriv(priv) { var asnWriter = new Ber.Writer(); asnWriter.startSequence(); // version asnWriter.writeInt(0x00, Ber.Integer); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.3.101.112'); // id-Ed25519 asnWriter.endSequence(); // PrivateKey asnWriter.startSequence(Ber.OctetString); asnWriter.writeBuffer(priv, Ber.OctetString); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PRIVATE', asnWriter.buffer); } function genOpenSSLECDSAPub(oid, Q) { var asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey // algorithm parameters (namedCurve) asnWriter.writeOID(oid); asnWriter.endSequence(); // subjectPublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(Q.length); Q.copy(asnWriter._buf, asnWriter._offset, 0, Q.length); asnWriter._offset += Q.length; // end hack asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHECDSAPub(oid, Q) { var curveName; switch (oid) { case '1.2.840.10045.3.1.7': // prime256v1/secp256r1 curveName = 'nistp256'; break; case '1.3.132.0.34': // secp384r1 curveName = 'nistp384'; break; case '1.3.132.0.35': // secp521r1 curveName = 'nistp521'; break; default: return; } var publicKey = Buffer.allocUnsafe(4 + 19 // ecdsa-sha2- + 4 + 8 // + 4 + Q.length); writeUInt32BE(publicKey, 19, 0); publicKey.write('ecdsa-sha2-' + curveName, 4, 19, 'ascii'); writeUInt32BE(publicKey, 8, 23); publicKey.write(curveName, 27, 8, 'ascii'); writeUInt32BE(publicKey, Q.length, 35); Q.copy(publicKey, 39); return publicKey; } function genOpenSSLECDSAPriv(oid, pub, priv) { var asnWriter = new Ber.Writer(); asnWriter.startSequence(); // version asnWriter.writeInt(0x01, Ber.Integer); // privateKey asnWriter.writeBuffer(priv, Ber.OctetString); // parameters (optional) asnWriter.startSequence(0xA0); asnWriter.writeOID(oid); asnWriter.endSequence(); // publicKey (optional) asnWriter.startSequence(0xA1); asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(pub.length); pub.copy(asnWriter._buf, asnWriter._offset, 0, pub.length); asnWriter._offset += pub.length; // end hack asnWriter.endSequence(); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('EC PRIVATE', asnWriter.buffer); } function genOpenSSLECDSAPubFromPriv(curveName, priv) { var tempECDH = crypto.createECDH(curveName); tempECDH.setPrivateKey(priv); return tempECDH.getPublicKey(); } var baseKeySign = (function() { if (typeof cryptoSign === 'function') { return function sign(data) { var pem = this[SYM_PRIV_PEM]; if (pem === null) return new Error('No private key available'); try { return cryptoSign(this[SYM_HASH_ALGO], data, pem); } catch (ex) { return ex; } }; } else { function trySign(signature, privKey) { try { return signature.sign(privKey); } catch (ex) { return ex; } } return function sign(data) { var pem = this[SYM_PRIV_PEM]; if (pem === null) return new Error('No private key available'); var signature = createSign(this[SYM_HASH_ALGO]); signature.update(data); return trySign(signature, pem); }; } })(); var baseKeyVerify = (function() { if (typeof cryptoVerify === 'function') { return function verify(data, signature) { var pem = this[SYM_PUB_PEM]; if (pem === null) return new Error('No public key available'); try { return cryptoVerify(this[SYM_HASH_ALGO], data, pem, signature); } catch (ex) { return ex; } }; } else { function tryVerify(verifier, pubKey, signature) { try { return verifier.verify(pubKey, signature); } catch (ex) { return ex; } } return function verify(data, signature) { var pem = this[SYM_PUB_PEM]; if (pem === null) return new Error('No public key available'); var verifier = createVerify(this[SYM_HASH_ALGO]); verifier.update(data); return tryVerify(verifier, pem, signature); }; } })(); var BaseKey = { sign: baseKeySign, verify: baseKeyVerify, getPrivatePEM: function getPrivatePEM() { return this[SYM_PRIV_PEM]; }, getPublicPEM: function getPublicPEM() { return this[SYM_PUB_PEM]; }, getPublicSSH: function getPublicSSH() { return this[SYM_PUB_SSH]; }, }; function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; } OpenSSH_Private.prototype = BaseKey; (function() { var regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; OpenSSH_Private.parse = function(str, passphrase) { var m = regexp.exec(str); if (m === null) return null; var ret; var data = Buffer.from(m[1], 'base64'); if (data.length < 31) // magic (+ magic null term.) + minimum field lengths return new Error('Malformed OpenSSH private key'); var magic = data.toString('ascii', 0, 15); if (magic !== 'openssh-key-v1\0') return new Error('Unsupported OpenSSH key magic: ' + magic); // avoid cyclic require by requiring on first use if (!utils) utils = __nccwpck_require__(2557); var cipherName = utils.readString(data, 15, 'ascii'); if (cipherName === false) return new Error('Malformed OpenSSH private key'); if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) return new Error('Unsupported cipher for OpenSSH key: ' + cipherName); var kdfName = utils.readString(data, data._pos, 'ascii'); if (kdfName === false) return new Error('Malformed OpenSSH private key'); if (kdfName !== 'none') { if (cipherName === 'none') return new Error('Malformed OpenSSH private key'); if (kdfName !== 'bcrypt') return new Error('Unsupported kdf name for OpenSSH key: ' + kdfName); if (!passphrase) { return new Error( 'Encrypted private OpenSSH key detected, but no passphrase given' ); } } else if (cipherName !== 'none') { return new Error('Malformed OpenSSH private key'); } var encInfo; var cipherKey; var cipherIV; if (cipherName !== 'none') encInfo = CIPHER_INFO[cipherName]; var kdfOptions = utils.readString(data, data._pos); if (kdfOptions === false) return new Error('Malformed OpenSSH private key'); if (kdfOptions.length) { switch (kdfName) { case 'none': return new Error('Malformed OpenSSH private key'); case 'bcrypt': /* string salt uint32 rounds */ var salt = utils.readString(kdfOptions, 0); if (salt === false || kdfOptions._pos + 4 > kdfOptions.length) return new Error('Malformed OpenSSH private key'); var rounds = readUInt32BE(kdfOptions, kdfOptions._pos); var gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); var r = bcrypt_pbkdf(passphrase, passphrase.length, salt, salt.length, gen, gen.length, rounds); if (r !== 0) return new Error('Failed to generate information to decrypt key'); cipherKey = gen.slice(0, encInfo.keyLen); cipherIV = gen.slice(encInfo.keyLen); break; } } else if (kdfName !== 'none') { return new Error('Malformed OpenSSH private key'); } var keyCount = utils.readInt(data, data._pos); if (keyCount === false) return new Error('Malformed OpenSSH private key'); data._pos += 4; if (keyCount > 0) { // TODO: place sensible limit on max `keyCount` // Read public keys first for (var i = 0; i < keyCount; ++i) { var pubData = utils.readString(data, data._pos); if (pubData === false) return new Error('Malformed OpenSSH private key'); var type = utils.readString(pubData, 0, 'ascii'); if (type === false) return new Error('Malformed OpenSSH private key'); } var privBlob = utils.readString(data, data._pos); if (privBlob === false) return new Error('Malformed OpenSSH private key'); if (cipherKey !== undefined) { // encrypted private key(s) if (privBlob.length < encInfo.blockLen || (privBlob.length % encInfo.blockLen) !== 0) { return new Error('Malformed OpenSSH private key'); } try { var options = { authTagLength: encInfo.authLen }; var decipher = createDecipheriv(SSH_TO_OPENSSL[cipherName], cipherKey, cipherIV, options); if (encInfo.authLen > 0) { if (data.length - data._pos < encInfo.authLen) return new Error('Malformed OpenSSH private key'); decipher.setAuthTag( data.slice(data._pos, data._pos += encInfo.authLen) ); } privBlob = combineBuffers(decipher.update(privBlob), decipher.final()); } catch (ex) { return ex; } } // Nothing should we follow the private key(s), except a possible // authentication tag for relevant ciphers if (data._pos !== data.length) return new Error('Malformed OpenSSH private key'); ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); } else { ret = []; } return ret; }; function parseOpenSSHPrivKeys(data, nkeys, decrypted) { var keys = []; /* uint32 checkint uint32 checkint string privatekey1 string comment1 string privatekey2 string comment2 ... string privatekeyN string commentN char 1 char 2 char 3 ... char padlen % 255 */ if (data.length < 8) return new Error('Malformed OpenSSH private key'); var check1 = readUInt32BE(data, 0); var check2 = readUInt32BE(data, 4); if (check1 !== check2) { if (decrypted) return new Error('OpenSSH key integrity check failed -- bad passphrase?'); return new Error('OpenSSH key integrity check failed'); } data._pos = 8; var i; var oid; for (i = 0; i < nkeys; ++i) { var algo = undefined; var privPEM = undefined; var pubPEM = undefined; var pubSSH = undefined; // The OpenSSH documentation for the key format actually lies, the entirety // of the private key content is not contained with a string field, it's // actually the literal contents of the private key, so to be able to find // the end of the key data you need to know the layout/format of each key // type ... var type = utils.readString(data, data._pos, 'ascii'); if (type === false) return new Error('Malformed OpenSSH private key'); switch (type) { case 'ssh-rsa': /* string n -- public string e -- public string d -- private string iqmp -- private string p -- private string q -- private */ var n = utils.readString(data, data._pos); if (n === false) return new Error('Malformed OpenSSH private key'); var e = utils.readString(data, data._pos); if (e === false) return new Error('Malformed OpenSSH private key'); var d = utils.readString(data, data._pos); if (d === false) return new Error('Malformed OpenSSH private key'); var iqmp = utils.readString(data, data._pos); if (iqmp === false) return new Error('Malformed OpenSSH private key'); var p = utils.readString(data, data._pos); if (p === false) return new Error('Malformed OpenSSH private key'); var q = utils.readString(data, data._pos); if (q === false) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); algo = 'sha1'; break; case 'ssh-dss': /* string p -- public string q -- public string g -- public string y -- public string x -- private */ var p = utils.readString(data, data._pos); if (p === false) return new Error('Malformed OpenSSH private key'); var q = utils.readString(data, data._pos); if (q === false) return new Error('Malformed OpenSSH private key'); var g = utils.readString(data, data._pos); if (g === false) return new Error('Malformed OpenSSH private key'); var y = utils.readString(data, data._pos); if (y === false) return new Error('Malformed OpenSSH private key'); var x = utils.readString(data, data._pos); if (x === false) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); privPEM = genOpenSSLDSAPriv(p, q, g, y, x); algo = 'sha1'; break; case 'ssh-ed25519': if (!EDDSA_SUPPORTED) return new Error('Unsupported OpenSSH private key type: ' + type); /* * string public key * string private key + public key */ var edpub = utils.readString(data, data._pos); if (edpub === false || edpub.length !== 32) return new Error('Malformed OpenSSH private key'); var edpriv = utils.readString(data, data._pos); if (edpriv === false || edpriv.length !== 64) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLEdPub(edpub); pubSSH = genOpenSSHEdPub(edpub); privPEM = genOpenSSLEdPriv(edpriv.slice(0, 32)); algo = null; break; case 'ecdsa-sha2-nistp256': algo = 'sha256'; oid = '1.2.840.10045.3.1.7'; case 'ecdsa-sha2-nistp384': if (algo === undefined) { algo = 'sha384'; oid = '1.3.132.0.34'; } case 'ecdsa-sha2-nistp521': if (algo === undefined) { algo = 'sha512'; oid = '1.3.132.0.35'; } /* string curve name string Q -- public string d -- private */ // TODO: validate curve name against type if (!skipFields(data, 1)) // Skip curve name return new Error('Malformed OpenSSH private key'); var ecpub = utils.readString(data, data._pos); if (ecpub === false) return new Error('Malformed OpenSSH private key'); var ecpriv = utils.readString(data, data._pos); if (ecpriv === false) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLECDSAPub(oid, ecpub); pubSSH = genOpenSSHECDSAPub(oid, ecpub); privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); break; default: return new Error('Unsupported OpenSSH private key type: ' + type); } var privComment = utils.readString(data, data._pos, 'utf8'); if (privComment === false) return new Error('Malformed OpenSSH private key'); keys.push( new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, decrypted) ); } var cnt = 0; for (i = data._pos; i < data.length; ++i) { if (data[i] !== (++cnt % 255)) return new Error('Malformed OpenSSH private key'); } return keys; } })(); function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; } OpenSSH_Old_Private.prototype = BaseKey; (function() { var regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; OpenSSH_Old_Private.parse = function(str, passphrase) { var m = regexp.exec(str); if (m === null) return null; var privBlob = Buffer.from(m[3], 'base64'); var headers = m[2]; var decrypted = false; if (headers !== undefined) { // encrypted key headers = headers.split(/\r\n|\n/g); for (var i = 0; i < headers.length; ++i) { var header = headers[i]; var sepIdx = header.indexOf(':'); if (header.slice(0, sepIdx) === 'DEK-Info') { var val = header.slice(sepIdx + 2); sepIdx = val.indexOf(','); if (sepIdx === -1) continue; var cipherName = val.slice(0, sepIdx).toLowerCase(); if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { return new Error( 'Cipher (' + cipherName + ') not supported for encrypted OpenSSH private key' ); } var encInfo = CIPHER_INFO_OPENSSL[cipherName]; if (!encInfo) { return new Error( 'Cipher (' + cipherName + ') not supported for encrypted OpenSSH private key' ); } var cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); if (cipherIV.length !== encInfo.ivLen) return new Error('Malformed encrypted OpenSSH private key'); if (!passphrase) { return new Error( 'Encrypted OpenSSH private key detected, but no passphrase given' ); } var cipherKey = createHash('md5') .update(passphrase) .update(cipherIV.slice(0, 8)) .digest(); while (cipherKey.length < encInfo.keyLen) { cipherKey = combineBuffers( cipherKey, (createHash('md5') .update(cipherKey) .update(passphrase) .update(cipherIV) .digest()).slice(0, 8) ); } if (cipherKey.length > encInfo.keyLen) cipherKey = cipherKey.slice(0, encInfo.keyLen); try { var decipher = createDecipheriv(cipherName, cipherKey, cipherIV); decipher.setAutoPadding(false); privBlob = combineBuffers(decipher.update(privBlob), decipher.final()); decrypted = true; } catch (ex) { return ex; } } } } var type; var privPEM; var pubPEM; var pubSSH; var algo; var reader; var errMsg = 'Malformed OpenSSH private key'; if (decrypted) errMsg += '. Bad passphrase?'; switch (m[1]) { case 'RSA': type = 'ssh-rsa'; privPEM = makePEM('RSA PRIVATE', privBlob); try { reader = new Ber.Reader(privBlob); reader.readSequence(); reader.readInt(); // skip version var n = reader.readString(Ber.Integer, true); if (n === null) return new Error(errMsg); var e = reader.readString(Ber.Integer, true); if (e === null) return new Error(errMsg); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); } catch (ex) { return new Error(errMsg); } algo = 'sha1'; break; case 'DSA': type = 'ssh-dss'; privPEM = makePEM('DSA PRIVATE', privBlob); try { reader = new Ber.Reader(privBlob); reader.readSequence(); reader.readInt(); // skip version var p = reader.readString(Ber.Integer, true); if (p === null) return new Error(errMsg); var q = reader.readString(Ber.Integer, true); if (q === null) return new Error(errMsg); var g = reader.readString(Ber.Integer, true); if (g === null) return new Error(errMsg); var y = reader.readString(Ber.Integer, true); if (y === null) return new Error(errMsg); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); } catch (ex) { return new Error(errMsg); } algo = 'sha1'; break; case 'EC': var ecSSLName; var ecPriv; try { reader = new Ber.Reader(privBlob); reader.readSequence(); reader.readInt(); // skip version ecPriv = reader.readString(Ber.OctetString, true); reader.readByte(); // Skip "complex" context type byte var offset = reader.readLength(); // Skip context length if (offset !== null) { reader._offset = offset; var oid = reader.readOID(); if (oid === null) return new Error(errMsg); switch (oid) { case '1.2.840.10045.3.1.7': // prime256v1/secp256r1 ecSSLName = 'prime256v1'; type = 'ecdsa-sha2-nistp256'; algo = 'sha256'; break; case '1.3.132.0.34': // secp384r1 ecSSLName = 'secp384r1'; type = 'ecdsa-sha2-nistp384'; algo = 'sha384'; break; case '1.3.132.0.35': // secp521r1 ecSSLName = 'secp521r1'; type = 'ecdsa-sha2-nistp521'; algo = 'sha512'; break; default: return new Error('Unsupported private key EC OID: ' + oid); } } else { return new Error(errMsg); } } catch (ex) { return new Error(errMsg); } privPEM = makePEM('EC PRIVATE', privBlob); var pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); pubPEM = genOpenSSLECDSAPub(oid, pubBlob); pubSSH = genOpenSSHECDSAPub(oid, pubBlob); break; } return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, decrypted); }; })(); function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; } PPK_Private.prototype = BaseKey; (function() { var EMPTY_PASSPHRASE = Buffer.alloc(0); var PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); var PPK_PP1 = Buffer.from([0, 0, 0, 0]); var PPK_PP2 = Buffer.from([0, 0, 0, 1]); var regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; PPK_Private.parse = function(str, passphrase) { var m = regexp.exec(str); if (m === null) return null; // m[1] = key type // m[2] = encryption type // m[3] = comment // m[4] = base64-encoded public key data: // for "ssh-rsa": // string "ssh-rsa" // mpint e (public exponent) // mpint n (modulus) // for "ssh-dss": // string "ssh-dss" // mpint p (modulus) // mpint q (prime) // mpint g (base number) // mpint y (public key parameter: g^x mod p) // m[5] = base64-encoded private key data: // for "ssh-rsa": // mpint d (private exponent) // mpint p (prime 1) // mpint q (prime 2) // mpint iqmp ([inverse of q] mod p) // for "ssh-dss": // mpint x (private key parameter) // m[6] = SHA1 HMAC over: // string name of algorithm ("ssh-dss", "ssh-rsa") // string encryption type // string comment // string public key data // string private-plaintext (including the final padding) var cipherName = m[2]; var encrypted = (cipherName !== 'none'); if (encrypted && !passphrase) { return new Error( 'Encrypted PPK private key detected, but no passphrase given' ); } var privBlob = Buffer.from(m[5], 'base64'); if (encrypted) { var encInfo = CIPHER_INFO[cipherName]; var cipherKey = combineBuffers( createHash('sha1').update(PPK_PP1).update(passphrase).digest(), createHash('sha1').update(PPK_PP2).update(passphrase).digest() ); if (cipherKey.length > encInfo.keyLen) cipherKey = cipherKey.slice(0, encInfo.keyLen); try { var decipher = createDecipheriv(SSH_TO_OPENSSL[cipherName], cipherKey, PPK_IV); decipher.setAutoPadding(false); privBlob = combineBuffers(decipher.update(privBlob), decipher.final()); decrypted = true; } catch (ex) { return ex; } } var type = m[1]; var comment = m[3]; var pubBlob = Buffer.from(m[4], 'base64'); var mac = m[6]; var typeLen = type.length; var cipherNameLen = cipherName.length; var commentLen = Buffer.byteLength(comment); var pubLen = pubBlob.length; var privLen = privBlob.length; var macData = Buffer.allocUnsafe(4 + typeLen + 4 + cipherNameLen + 4 + commentLen + 4 + pubLen + 4 + privLen); var p = 0; writeUInt32BE(macData, typeLen, p); macData.write(type, p += 4, typeLen, 'ascii'); writeUInt32BE(macData, cipherNameLen, p += typeLen); macData.write(cipherName, p += 4, cipherNameLen, 'ascii'); writeUInt32BE(macData, commentLen, p += cipherNameLen); macData.write(comment, p += 4, commentLen, 'utf8'); writeUInt32BE(macData, pubLen, p += commentLen); pubBlob.copy(macData, p += 4); writeUInt32BE(macData, privLen, p += pubLen); privBlob.copy(macData, p + 4); if (!passphrase) passphrase = EMPTY_PASSPHRASE; var calcMAC = createHmac('sha1', createHash('sha1') .update('putty-private-key-file-mac-key') .update(passphrase) .digest()) .update(macData) .digest('hex'); if (calcMAC !== mac) { if (encrypted) { return new Error( 'PPK private key integrity check failed -- bad passphrase?' ); } else { return new Error('PPK private key integrity check failed'); } } // avoid cyclic require by requiring on first use if (!utils) utils = __nccwpck_require__(2557); var pubPEM; var pubSSH; var privPEM; pubBlob._pos = 0; skipFields(pubBlob, 1); // skip (duplicate) key type switch (type) { case 'ssh-rsa': var e = utils.readString(pubBlob, pubBlob._pos); if (e === false) return new Error('Malformed PPK public key'); var n = utils.readString(pubBlob, pubBlob._pos); if (n === false) return new Error('Malformed PPK public key'); var d = utils.readString(privBlob, 0); if (d === false) return new Error('Malformed PPK private key'); var p = utils.readString(privBlob, privBlob._pos); if (p === false) return new Error('Malformed PPK private key'); var q = utils.readString(privBlob, privBlob._pos); if (q === false) return new Error('Malformed PPK private key'); var iqmp = utils.readString(privBlob, privBlob._pos); if (iqmp === false) return new Error('Malformed PPK private key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); break; case 'ssh-dss': var p = utils.readString(pubBlob, pubBlob._pos); if (p === false) return new Error('Malformed PPK public key'); var q = utils.readString(pubBlob, pubBlob._pos); if (q === false) return new Error('Malformed PPK public key'); var g = utils.readString(pubBlob, pubBlob._pos); if (g === false) return new Error('Malformed PPK public key'); var y = utils.readString(pubBlob, pubBlob._pos); if (y === false) return new Error('Malformed PPK public key'); var x = utils.readString(privBlob, 0); if (x === false) return new Error('Malformed PPK private key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); privPEM = genOpenSSLDSAPriv(p, q, g, y, x); break; } return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', encrypted); }; })(); function parseDER(data, baseType, comment, fullType) { // avoid cyclic require by requiring on first use if (!utils) utils = __nccwpck_require__(2557); var algo; var pubPEM = null; var pubSSH = null; switch (baseType) { case 'ssh-rsa': var e = utils.readString(data, data._pos); if (e === false) return new Error('Malformed OpenSSH public key'); var n = utils.readString(data, data._pos); if (n === false) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); algo = 'sha1'; break; case 'ssh-dss': var p = utils.readString(data, data._pos); if (p === false) return new Error('Malformed OpenSSH public key'); var q = utils.readString(data, data._pos); if (q === false) return new Error('Malformed OpenSSH public key'); var g = utils.readString(data, data._pos); if (g === false) return new Error('Malformed OpenSSH public key'); var y = utils.readString(data, data._pos); if (y === false) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); algo = 'sha1'; break; case 'ssh-ed25519': var edpub = utils.readString(data, data._pos); if (edpub === false || edpub.length !== 32) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLEdPub(edpub); pubSSH = genOpenSSHEdPub(edpub); algo = null; break; case 'ecdsa-sha2-nistp256': algo = 'sha256'; oid = '1.2.840.10045.3.1.7'; case 'ecdsa-sha2-nistp384': if (algo === undefined) { algo = 'sha384'; oid = '1.3.132.0.34'; } case 'ecdsa-sha2-nistp521': if (algo === undefined) { algo = 'sha512'; oid = '1.3.132.0.35'; } // TODO: validate curve name against type if (!skipFields(data, 1)) // Skip curve name return new Error('Malformed OpenSSH public key'); var ecpub = utils.readString(data, data._pos); if (ecpub === false) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLECDSAPub(oid, ecpub); pubSSH = genOpenSSHECDSAPub(oid, ecpub); break; default: return new Error('Unsupported OpenSSH public key type: ' + baseType); } return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); } function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = null; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = false; } OpenSSH_Public.prototype = BaseKey; (function() { var regexp; if (EDDSA_SUPPORTED) regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z\/+=]+)(?:$|\s+([\S].*)?)$/; else regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z\/+=]+)(?:$|\s+([\S].*)?)$/; OpenSSH_Public.parse = function(str) { var m = regexp.exec(str); if (m === null) return null; // m[1] = full type // m[2] = base type // m[3] = base64-encoded public key // m[4] = comment // avoid cyclic require by requiring on first use if (!utils) utils = __nccwpck_require__(2557); var fullType = m[1]; var baseType = m[2]; var data = Buffer.from(m[3], 'base64'); var comment = (m[4] || ''); var type = utils.readString(data, data._pos, 'ascii'); if (type === false || type.indexOf(baseType) !== 0) return new Error('Malformed OpenSSH public key'); return parseDER(data, baseType, comment, fullType); }; })(); function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = null; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = false; } RFC4716_Public.prototype = BaseKey; (function() { var regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r\n|\n)((?:(?:[\x21-\x7E]+?):(?:(?:.*?\\\r?\n)*.*)(?:\r\n|\n))*)((?:[A-Z0-9a-z\/+=]+(?:\r\n|\n))+)---- END SSH2 PUBLIC KEY ----$/; var RE_HEADER = /^([\x21-\x7E]+?):((?:.*?\\\r?\n)*.*)$/gm; var RE_HEADER_ENDS = /\\\r?\n/g; RFC4716_Public.parse = function(str) { var m = regexp.exec(str); if (m === null) return null; // m[1] = header(s) // m[2] = base64-encoded public key var headers = m[1]; var data = Buffer.from(m[2], 'base64'); var comment = ''; if (headers !== undefined) { while (m = RE_HEADER.exec(headers)) { if (m[1].toLowerCase() === 'comment') { comment = trimStart(m[2].replace(RE_HEADER_ENDS, '')); if (comment.length > 1 && comment.charCodeAt(0) === 34/*'"'*/ && comment.charCodeAt(comment.length - 1) === 34/*'"'*/) { comment = comment.slice(1, -1); } } } } // avoid cyclic require by requiring on first use if (!utils) utils = __nccwpck_require__(2557); var type = utils.readString(data, 0, 'ascii'); if (type === false) return new Error('Malformed RFC4716 public key'); var pubPEM = null; var pubSSH = null; switch (type) { case 'ssh-rsa': var e = utils.readString(data, data._pos); if (e === false) return new Error('Malformed RFC4716 public key'); var n = utils.readString(data, data._pos); if (n === false) return new Error('Malformed RFC4716 public key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); break; case 'ssh-dss': var p = utils.readString(data, data._pos); if (p === false) return new Error('Malformed RFC4716 public key'); var q = utils.readString(data, data._pos); if (q === false) return new Error('Malformed RFC4716 public key'); var g = utils.readString(data, data._pos); if (g === false) return new Error('Malformed RFC4716 public key'); var y = utils.readString(data, data._pos); if (y === false) return new Error('Malformed RFC4716 public key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); break; default: return new Error('Malformed RFC4716 public key'); } return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); }; })(); module.exports = { parseDERKey: function parseDERKey(data, type) { return parseDER(data, type, '', type); }, parseKey: function parseKey(data, passphrase) { if (Buffer.isBuffer(data)) data = data.toString('utf8').trim(); else if (typeof data !== 'string') return new Error('Key data must be a Buffer or string'); else data = data.trim(); // intentional != if (passphrase != undefined) { if (typeof passphrase === 'string') passphrase = Buffer.from(passphrase); else if (!Buffer.isBuffer(passphrase)) return new Error('Passphrase must be a string or Buffer when supplied'); } var ret; // Private keys if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) return ret; if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) return ret; if ((ret = PPK_Private.parse(data, passphrase)) !== null) return ret; // Public keys if ((ret = OpenSSH_Public.parse(data)) !== null) return ret; if ((ret = RFC4716_Public.parse(data)) !== null) return ret; return new Error('Unsupported key format'); } } /***/ }), /***/ 1839: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var inspect = (__nccwpck_require__(9023).inspect); function assert(value, message) { if (!value) throw new ERR_INTERNAL_ASSERTION(message); } assert.fail = function fail(message) { throw new ERR_INTERNAL_ASSERTION(message); }; // Only use this for integers! Decimal numbers do not work with this function. function addNumericalSeparator(val) { var res = ''; var i = val.length; var start = val[0] === '-' ? 1 : 0; for (; i >= start + 4; i -= 3) res = `_${val.slice(i - 3, i)}${res}`; return `${val.slice(0, i)}${res}`; } function oneOf(expected, thing) { assert(typeof thing === 'string', '`thing` has to be of type string'); if (Array.isArray(expected)) { var len = expected.length; assert(len > 0, 'At least one expected value needs to be specified'); expected = expected.map((i) => String(i)); if (len > 2) { return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; } else if (len === 2) { return `one of ${thing} ${expected[0]} or ${expected[1]}`; } else { return `of ${thing} ${expected[0]}`; } } else { return `of ${thing} ${String(expected)}`; } } exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { constructor(message) { super(); Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); var suffix = 'This is caused by either a bug in ssh2-streams ' + 'or incorrect usage of ssh2-streams internals.\n' + 'Please open an issue with this stack trace at ' + 'https://github.com/mscdex/ssh2-streams/issues\n'; this.message = (message === undefined ? suffix : `${message}\n${suffix}`); } }; var MAX_32BIT_INT = Math.pow(2, 32); var MAX_32BIT_BIGINT = (function() { try { return new Function('return 2n ** 32n')(); } catch (ex) {} })(); exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { constructor(str, range, input, replaceDefaultBoolean) { super(); Error.captureStackTrace(this, ERR_OUT_OF_RANGE); assert(range, 'Missing "range" argument'); var msg = (replaceDefaultBoolean ? str : `The value of "${str}" is out of range.`); var received; if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { received = addNumericalSeparator(String(input)); } else if (typeof input === 'bigint') { received = String(input); if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) received = addNumericalSeparator(received); received += 'n'; } else { received = inspect(input); } msg += ` It must be ${range}. Received ${received}`; this.message = msg; } }; exports.ERR_INVALID_ARG_TYPE = class ERR_INVALID_ARG_TYPE extends TypeError { constructor(name, expected, actual) { super(); Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); assert(typeof name === 'string', `'name' must be a string`); // determiner: 'must be' or 'must not be' var determiner; if (typeof expected === 'string' && expected.startsWith('not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } var msg; if (name.endsWith(' argument')) { // For cases like 'first argument' msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { var type = (name.includes('.') ? 'property' : 'argument'); msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } msg += `. Received type ${typeof actual}`; this.message = msg; } }; exports.validateNumber = function validateNumber(value, name) { if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value); }; // ============================================================================= // Following code is only needed to support node v6.x .... // Undocumented cb() API, needed for core, not for public API exports.destroyImpl = function destroy(err, cb) { const readableDestroyed = this._readableState && this._readableState.destroyed; const writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err) { if (!this._writableState) { process.nextTick(emitErrorNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; process.nextTick(emitErrorNT, this, err); } } return this; } // We set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // If this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, (err) => { if (!cb && err) { if (!this._writableState) { process.nextTick(emitErrorAndCloseNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; process.nextTick(emitErrorAndCloseNT, this, err); } else { process.nextTick(emitCloseNT, this); } } else if (cb) { process.nextTick(emitCloseNT, this); cb(err); } else { process.nextTick(emitCloseNT, this); } }); return this; }; function emitErrorAndCloseNT(self, err) { emitErrorNT(self, err); emitCloseNT(self); } function emitCloseNT(self) { if (self._writableState && !self._writableState.emitClose) return; if (self._readableState && !self._readableState.emitClose) return; self.emit('close'); } // ============================================================================= /***/ }), /***/ 507: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // TODO: support EXTENDED request packets var TransformStream = (__nccwpck_require__(2203).Transform); var ReadableStream = (__nccwpck_require__(2203).Readable); var WritableStream = (__nccwpck_require__(2203).Writable); var constants = (__nccwpck_require__(9896).constants) || process.binding('constants'); var util = __nccwpck_require__(9023); var inherits = util.inherits; var isDate = util.isDate; var listenerCount = (__nccwpck_require__(4434).EventEmitter).listenerCount; var fs = __nccwpck_require__(9896); var readString = (__nccwpck_require__(2557).readString); var readInt = (__nccwpck_require__(2557).readInt); var readUInt32BE = (__nccwpck_require__(4288).readUInt32BE); var writeUInt32BE = (__nccwpck_require__(4288).writeUInt32BE); var ATTR = { SIZE: 0x00000001, UIDGID: 0x00000002, PERMISSIONS: 0x00000004, ACMODTIME: 0x00000008, EXTENDED: 0x80000000 }; var STATUS_CODE = { OK: 0, EOF: 1, NO_SUCH_FILE: 2, PERMISSION_DENIED: 3, FAILURE: 4, BAD_MESSAGE: 5, NO_CONNECTION: 6, CONNECTION_LOST: 7, OP_UNSUPPORTED: 8 }; Object.keys(STATUS_CODE).forEach(function(key) { STATUS_CODE[STATUS_CODE[key]] = key; }); var STATUS_CODE_STR = { 0: 'No error', 1: 'End of file', 2: 'No such file or directory', 3: 'Permission denied', 4: 'Failure', 5: 'Bad message', 6: 'No connection', 7: 'Connection lost', 8: 'Operation unsupported' }; SFTPStream.STATUS_CODE = STATUS_CODE; var REQUEST = { INIT: 1, OPEN: 3, CLOSE: 4, READ: 5, WRITE: 6, LSTAT: 7, FSTAT: 8, SETSTAT: 9, FSETSTAT: 10, OPENDIR: 11, READDIR: 12, REMOVE: 13, MKDIR: 14, RMDIR: 15, REALPATH: 16, STAT: 17, RENAME: 18, READLINK: 19, SYMLINK: 20, EXTENDED: 200 }; Object.keys(REQUEST).forEach(function(key) { REQUEST[REQUEST[key]] = key; }); var RESPONSE = { VERSION: 2, STATUS: 101, HANDLE: 102, DATA: 103, NAME: 104, ATTRS: 105, EXTENDED: 201 }; Object.keys(RESPONSE).forEach(function(key) { RESPONSE[RESPONSE[key]] = key; }); var OPEN_MODE = { READ: 0x00000001, WRITE: 0x00000002, APPEND: 0x00000004, CREAT: 0x00000008, TRUNC: 0x00000010, EXCL: 0x00000020 }; SFTPStream.OPEN_MODE = OPEN_MODE; var MAX_PKT_LEN = 34000; var MAX_REQID = Math.pow(2, 32) - 1; var CLIENT_VERSION_BUFFER = Buffer.from([0, 0, 0, 5 /* length */, REQUEST.INIT, 0, 0, 0, 3 /* version */]); var SERVER_VERSION_BUFFER = Buffer.from([0, 0, 0, 5 /* length */, RESPONSE.VERSION, 0, 0, 0, 3 /* version */]); /* http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02: The maximum size of a packet is in practice determined by the client (the maximum size of read or write requests that it sends, plus a few bytes of packet overhead). All servers SHOULD support packets of at least 34000 bytes (where the packet size refers to the full length, including the header above). This should allow for reads and writes of at most 32768 bytes. OpenSSH caps this to 256kb instead of the ~34kb as mentioned in the sftpv3 spec. */ var RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; var OPENSSH_MAX_DATA_LEN = (256 * 1024) - (2 * 1024)/*account for header data*/; function DEBUG_NOOP(msg) {} function SFTPStream(cfg, remoteIdentRaw) { if (typeof cfg === 'string' && !remoteIdentRaw) { remoteIdentRaw = cfg; cfg = undefined; } if (typeof cfg !== 'object' || !cfg) cfg = {}; TransformStream.call(this, { highWaterMark: (typeof cfg.highWaterMark === 'number' ? cfg.highWaterMark : 32 * 1024) }); this.debug = (typeof cfg.debug === 'function' ? cfg.debug : DEBUG_NOOP); this.server = (cfg.server ? true : false); this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); this._needContinue = false; this._state = { // common status: 'packet_header', writeReqid: -1, pktLeft: undefined, pktHdrBuf: Buffer.allocUnsafe(9), // room for pktLen + pktType + req id pktBuf: undefined, pktType: undefined, version: undefined, extensions: {}, // client maxDataLen: (this._isOpenSSH ? OPENSSH_MAX_DATA_LEN : 32768), requests: {} }; var self = this; this.on('end', function() { self.readable = false; }).on('finish', onFinish) .on('prefinish', onFinish); function onFinish() { self.writable = false; self._cleanup(false); } if (!this.server) this.push(CLIENT_VERSION_BUFFER); } inherits(SFTPStream, TransformStream); SFTPStream.prototype.__read = TransformStream.prototype._read; SFTPStream.prototype._read = function(n) { if (this._needContinue) { this._needContinue = false; this.emit('continue'); } return this.__read(n); }; SFTPStream.prototype.__push = TransformStream.prototype.push; SFTPStream.prototype.push = function(chunk, encoding) { if (!this.readable) return false; if (chunk === null) this.readable = false; var ret = this.__push(chunk, encoding); this._needContinue = (ret === false); return ret; }; SFTPStream.prototype._cleanup = function(callback) { var state = this._state; state.pktBuf = undefined; // give GC something to do var requests = state.requests; var keys = Object.keys(requests); var len = keys.length; if (len) { if (this.readable) { var err = new Error('SFTP session ended early'); for (var i = 0, cb; i < len; ++i) (cb = requests[keys[i]].cb) && cb(err); } state.requests = {}; } if (this.readable) this.push(null); if (!this._readableState.endEmitted && !this._readableState.flowing) { // Ugh! this.resume(); } if (callback !== false) { this.debug('DEBUG[SFTP]: Parser: Malformed packet'); callback && callback(new Error('Malformed packet')); } }; SFTPStream.prototype._transform = function(chunk, encoding, callback) { var state = this._state; var server = this.server; var status = state.status; var pktType = state.pktType; var pktBuf = state.pktBuf; var pktLeft = state.pktLeft; var version = state.version; var pktHdrBuf = state.pktHdrBuf; var requests = state.requests; var debug = this.debug; var chunkLen = chunk.length; var chunkPos = 0; var buffer; var chunkLeft; var id; while (true) { if (status === 'discard') { chunkLeft = (chunkLen - chunkPos); if (pktLeft <= chunkLeft) { chunkPos += pktLeft; pktLeft = 0; status = 'packet_header'; buffer = pktBuf = undefined; } else { pktLeft -= chunkLeft; break; } } else if (pktBuf !== undefined) { chunkLeft = (chunkLen - chunkPos); if (pktLeft <= chunkLeft) { chunk.copy(pktBuf, pktBuf.length - pktLeft, chunkPos, chunkPos + pktLeft); chunkPos += pktLeft; pktLeft = 0; buffer = pktBuf; pktBuf = undefined; continue; } else { chunk.copy(pktBuf, pktBuf.length - pktLeft, chunkPos); pktLeft -= chunkLeft; break; } } else if (status === 'packet_header') { if (!buffer) { pktLeft = 5; pktBuf = pktHdrBuf; } else { // here we read the right-most 5 bytes from buffer (pktHdrBuf) pktLeft = readUInt32BE(buffer, 4) - 1; // account for type byte pktType = buffer[8]; if (server) { if (version === undefined && pktType !== REQUEST.INIT) { debug('DEBUG[SFTP]: Parser: Unexpected packet before init'); this._cleanup(false); return callback(new Error('Unexpected packet before init')); } else if (version !== undefined && pktType === REQUEST.INIT) { debug('DEBUG[SFTP]: Parser: Unexpected duplicate init'); status = 'bad_pkt'; } else if (pktLeft > MAX_PKT_LEN) { var msg = 'Packet length (' + pktLeft + ') exceeds max length (' + MAX_PKT_LEN + ')'; debug('DEBUG[SFTP]: Parser: ' + msg); this._cleanup(false); return callback(new Error(msg)); } else if (pktType === REQUEST.EXTENDED) { status = 'bad_pkt'; } else if (REQUEST[pktType] === undefined) { debug('DEBUG[SFTP]: Parser: Unsupported packet type: ' + pktType); status = 'discard'; } } else if (version === undefined && pktType !== RESPONSE.VERSION) { debug('DEBUG[SFTP]: Parser: Unexpected packet before version'); this._cleanup(false); return callback(new Error('Unexpected packet before version')); } else if (version !== undefined && pktType === RESPONSE.VERSION) { debug('DEBUG[SFTP]: Parser: Unexpected duplicate version'); status = 'bad_pkt'; } else if (RESPONSE[pktType] === undefined) { status = 'discard'; } if (status === 'bad_pkt') { // Copy original packet info to left of pktHdrBuf writeUInt32BE(pktHdrBuf, pktLeft + 1, 0); pktHdrBuf[4] = pktType; pktLeft = 4; pktBuf = pktHdrBuf; } else { pktBuf = Buffer.allocUnsafe(pktLeft); status = 'payload'; } } } else if (status === 'payload') { if (pktType === RESPONSE.VERSION || pktType === REQUEST.INIT) { /* uint32 version */ version = state.version = readInt(buffer, 0, this, callback); if (version === false) return; if (version < 3) { this._cleanup(false); return callback(new Error('Incompatible SFTP version: ' + version)); } else if (server) this.push(SERVER_VERSION_BUFFER); var buflen = buffer.length; var extname; var extdata; buffer._pos = 4; while (buffer._pos < buflen) { extname = readString(buffer, buffer._pos, 'ascii', this, callback); if (extname === false) return; extdata = readString(buffer, buffer._pos, 'ascii', this, callback); if (extdata === false) return; if (state.extensions[extname]) state.extensions[extname].push(extdata); else state.extensions[extname] = [ extdata ]; } this.emit('ready'); } else { /* All other packets (client and server) begin with a (client) request id: uint32 id */ id = readInt(buffer, 0, this, callback); if (id === false) return; var filename; var attrs; var handle; var data; if (!server) { var req = requests[id]; var cb = req && req.cb; debug('DEBUG[SFTP]: Parser: Response: ' + RESPONSE[pktType]); if (req && cb) { if (pktType === RESPONSE.STATUS) { /* uint32 error/status code string error message (ISO-10646 UTF-8) string language tag */ var code = readInt(buffer, 4, this, callback); if (code === false) return; if (code === STATUS_CODE.OK) { cb(); } else { // We borrow OpenSSH behavior here, specifically we make the // message and language fields optional, despite the // specification requiring them (even if they are empty). This // helps to avoid problems with buggy implementations that do // not fully conform to the SFTP(v3) specification. var msg; var lang = ''; if (buffer.length >= 12) { msg = readString(buffer, 8, 'utf8', this, callback); if (msg === false) return; if ((buffer._pos + 4) < buffer.length) { lang = readString(buffer, buffer._pos, 'ascii', this, callback); if (lang === false) return; } } var err = new Error(msg || STATUS_CODE_STR[code] || 'Unknown status'); err.code = code; err.lang = lang; cb(err); } } else if (pktType === RESPONSE.HANDLE) { /* string handle */ handle = readString(buffer, 4, this, callback); if (handle === false) return; cb(undefined, handle); } else if (pktType === RESPONSE.DATA) { /* string data */ if (req.buffer) { // we have already pre-allocated space to store the data var dataLen = readInt(buffer, 4, this, callback); if (dataLen === false) return; var reqBufLen = req.buffer.length; if (dataLen > reqBufLen) { // truncate response data to fit expected size writeUInt32BE(buffer, reqBufLen, 4); } data = readString(buffer, 4, req.buffer, this, callback); if (data === false) return; cb(undefined, data, dataLen); } else { data = readString(buffer, 4, this, callback); if (data === false) return; cb(undefined, data); } } else if (pktType === RESPONSE.NAME) { /* uint32 count repeats count times: string filename string longname ATTRS attrs */ var namesLen = readInt(buffer, 4, this, callback); if (namesLen === false) return; var names = [], longname; buffer._pos = 8; for (var i = 0; i < namesLen; ++i) { // we are going to assume UTF-8 for filenames despite the SFTPv3 // spec not specifying an encoding because the specs for newer // versions of the protocol all explicitly specify UTF-8 for // filenames filename = readString(buffer, buffer._pos, 'utf8', this, callback); if (filename === false) return; // `longname` only exists in SFTPv3 and since it typically will // contain the filename, we assume it is also UTF-8 longname = readString(buffer, buffer._pos, 'utf8', this, callback); if (longname === false) return; attrs = readAttrs(buffer, buffer._pos, this, callback); if (attrs === false) return; names.push({ filename: filename, longname: longname, attrs: attrs }); } cb(undefined, names); } else if (pktType === RESPONSE.ATTRS) { /* ATTRS attrs */ attrs = readAttrs(buffer, 4, this, callback); if (attrs === false) return; cb(undefined, attrs); } else if (pktType === RESPONSE.EXTENDED) { if (req.extended) { switch (req.extended) { case 'statvfs@openssh.com': case 'fstatvfs@openssh.com': /* uint64 f_bsize // file system block size uint64 f_frsize // fundamental fs block size uint64 f_blocks // number of blocks (unit f_frsize) uint64 f_bfree // free blocks in file system uint64 f_bavail // free blocks for non-root uint64 f_files // total file inodes uint64 f_ffree // free file inodes uint64 f_favail // free file inodes for to non-root uint64 f_fsid // file system id uint64 f_flag // bit mask of f_flag values uint64 f_namemax // maximum filename length */ var stats = { f_bsize: undefined, f_frsize: undefined, f_blocks: undefined, f_bfree: undefined, f_bavail: undefined, f_files: undefined, f_ffree: undefined, f_favail: undefined, f_sid: undefined, f_flag: undefined, f_namemax: undefined }; stats.f_bsize = readUInt64BE(buffer, 4, this, callback); if (stats.f_bsize === false) return; stats.f_frsize = readUInt64BE(buffer, 12, this, callback); if (stats.f_frsize === false) return; stats.f_blocks = readUInt64BE(buffer, 20, this, callback); if (stats.f_blocks === false) return; stats.f_bfree = readUInt64BE(buffer, 28, this, callback); if (stats.f_bfree === false) return; stats.f_bavail = readUInt64BE(buffer, 36, this, callback); if (stats.f_bavail === false) return; stats.f_files = readUInt64BE(buffer, 44, this, callback); if (stats.f_files === false) return; stats.f_ffree = readUInt64BE(buffer, 52, this, callback); if (stats.f_ffree === false) return; stats.f_favail = readUInt64BE(buffer, 60, this, callback); if (stats.f_favail === false) return; stats.f_sid = readUInt64BE(buffer, 68, this, callback); if (stats.f_sid === false) return; stats.f_flag = readUInt64BE(buffer, 76, this, callback); if (stats.f_flag === false) return; stats.f_namemax = readUInt64BE(buffer, 84, this, callback); if (stats.f_namemax === false) return; cb(undefined, stats); break; } } // XXX: at least provide the raw buffer data to the callback in // case of unexpected extended response? cb(); } } if (req) delete requests[id]; } else { // server var evName = REQUEST[pktType]; var offset; var path; debug('DEBUG[SFTP]: Parser: Request: ' + evName); if (listenerCount(this, evName)) { if (pktType === REQUEST.OPEN) { /* string filename uint32 pflags ATTRS attrs */ filename = readString(buffer, 4, 'utf8', this, callback); if (filename === false) return; var pflags = readInt(buffer, buffer._pos, this, callback); if (pflags === false) return; attrs = readAttrs(buffer, buffer._pos + 4, this, callback); if (attrs === false) return; this.emit(evName, id, filename, pflags, attrs); } else if (pktType === REQUEST.CLOSE || pktType === REQUEST.FSTAT || pktType === REQUEST.READDIR) { /* string handle */ handle = readString(buffer, 4, this, callback); if (handle === false) return; this.emit(evName, id, handle); } else if (pktType === REQUEST.READ) { /* string handle uint64 offset uint32 len */ handle = readString(buffer, 4, this, callback); if (handle === false) return; offset = readUInt64BE(buffer, buffer._pos, this, callback); if (offset === false) return; var len = readInt(buffer, buffer._pos, this, callback); if (len === false) return; this.emit(evName, id, handle, offset, len); } else if (pktType === REQUEST.WRITE) { /* string handle uint64 offset string data */ handle = readString(buffer, 4, this, callback); if (handle === false) return; offset = readUInt64BE(buffer, buffer._pos, this, callback); if (offset === false) return; data = readString(buffer, buffer._pos, this, callback); if (data === false) return; this.emit(evName, id, handle, offset, data); } else if (pktType === REQUEST.LSTAT || pktType === REQUEST.STAT || pktType === REQUEST.OPENDIR || pktType === REQUEST.REMOVE || pktType === REQUEST.RMDIR || pktType === REQUEST.REALPATH || pktType === REQUEST.READLINK) { /* string path */ path = readString(buffer, 4, 'utf8', this, callback); if (path === false) return; this.emit(evName, id, path); } else if (pktType === REQUEST.SETSTAT || pktType === REQUEST.MKDIR) { /* string path ATTRS attrs */ path = readString(buffer, 4, 'utf8', this, callback); if (path === false) return; attrs = readAttrs(buffer, buffer._pos, this, callback); if (attrs === false) return; this.emit(evName, id, path, attrs); } else if (pktType === REQUEST.FSETSTAT) { /* string handle ATTRS attrs */ handle = readString(buffer, 4, this, callback); if (handle === false) return; attrs = readAttrs(buffer, buffer._pos, this, callback); if (attrs === false) return; this.emit(evName, id, handle, attrs); } else if (pktType === REQUEST.RENAME || pktType === REQUEST.SYMLINK) { /* RENAME: string oldpath string newpath SYMLINK: string linkpath string targetpath */ var str1; var str2; str1 = readString(buffer, 4, 'utf8', this, callback); if (str1 === false) return; str2 = readString(buffer, buffer._pos, 'utf8', this, callback); if (str2 === false) return; if (pktType === REQUEST.SYMLINK && this._isOpenSSH) { // OpenSSH has linkpath and targetpath positions switched this.emit(evName, id, str2, str1); } else this.emit(evName, id, str1, str2); } } else { // automatically reject request if no handler for request type this.status(id, STATUS_CODE.OP_UNSUPPORTED); } } } // prepare for next packet status = 'packet_header'; buffer = pktBuf = undefined; } else if (status === 'bad_pkt') { if (server && buffer[4] !== REQUEST.INIT) { var errCode = (buffer[4] === REQUEST.EXTENDED ? STATUS_CODE.OP_UNSUPPORTED : STATUS_CODE.FAILURE); // no request id for init/version packets, so we have no way to send a // status response, so we just close up shop ... if (buffer[4] === REQUEST.INIT || buffer[4] === RESPONSE.VERSION) return this._cleanup(callback); id = readInt(buffer, 5, this, callback); if (id === false) return; this.status(id, errCode); } // by this point we have already read the type byte and the id bytes, so // we subtract those from the number of bytes to skip pktLeft = readUInt32BE(buffer, 0) - 5; status = 'discard'; } if (chunkPos >= chunkLen) break; } state.status = status; state.pktType = pktType; state.pktBuf = pktBuf; state.pktLeft = pktLeft; state.version = version; callback(); }; // client SFTPStream.prototype.createReadStream = function(path, options) { if (this.server) throw new Error('Client-only method called in server mode'); return new ReadStream(this, path, options); }; SFTPStream.prototype.createWriteStream = function(path, options) { if (this.server) throw new Error('Client-only method called in server mode'); return new WriteStream(this, path, options); }; SFTPStream.prototype.open = function(path, flags_, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; if (typeof attrs === 'function') { cb = attrs; attrs = undefined; } var flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); if (flags === null) throw new Error('Unknown flags string: ' + flags_); var attrFlags = 0; var attrBytes = 0; if (typeof attrs === 'string' || typeof attrs === 'number') { attrs = { mode: attrs }; } if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); attrFlags = attrs.flags; attrBytes = attrs.nbytes; attrs = attrs.bytes; } /* uint32 id string filename uint32 pflags ATTRS attrs */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen + 4 + 4 + attrBytes); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.OPEN; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathlen, p); buf.write(path, p += 4, pathlen, 'utf8'); writeUInt32BE(buf, flags, p += pathlen); writeUInt32BE(buf, attrFlags, p += 4); if (attrs && attrFlags) { p += 4; for (var i = 0, len = attrs.length; i < len; ++i) for (var j = 0, len2 = attrs[i].length; j < len2; ++j) buf[p++] = attrs[i][j]; } state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing OPEN'); return this.push(buf); }; SFTPStream.prototype.close = function(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); else if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); var state = this._state; /* uint32 id string handle */ var handlelen = handle.length; var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handlelen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.CLOSE; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handlelen, p); handle.copy(buf, p += 4); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing CLOSE'); return this.push(buf); }; SFTPStream.prototype.readData = function(handle, buf, off, len, position, cb) { if (this.server) throw new Error('Client-only method called in server mode'); else if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); else if (!Buffer.isBuffer(buf)) throw new Error('buffer is not a Buffer'); else if (off >= buf.length) throw new Error('offset is out of bounds'); else if (off + len > buf.length) throw new Error('length extends beyond buffer'); else if (position === null) throw new Error('null position currently unsupported'); var state = this._state; /* uint32 id string handle uint64 offset uint32 len */ var handlelen = handle.length; var p = 9; var pos = position; var out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handlelen + 8 + 4); writeUInt32BE(out, out.length - 4, 0); out[4] = REQUEST.READ; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(out, reqid, 5); writeUInt32BE(out, handlelen, p); handle.copy(out, p += 4); p += handlelen; for (var i = 7; i >= 0; --i) { out[p + i] = pos & 0xFF; pos /= 256; } writeUInt32BE(out, len, p += 8); state.requests[reqid] = { cb: function(err, data, nb) { if (err) { if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) return cb(err); } else if (nb > len) { return cb(new Error('Received more data than requested')); } cb(undefined, nb || 0, data, position); }, buffer: buf.slice(off, off + len) }; this.debug('DEBUG[SFTP]: Outgoing: Writing READ'); return this.push(out); }; SFTPStream.prototype.writeData = function(handle, buf, off, len, position, cb) { if (this.server) throw new Error('Client-only method called in server mode'); else if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); else if (!Buffer.isBuffer(buf)) throw new Error('buffer is not a Buffer'); else if (off > buf.length) throw new Error('offset is out of bounds'); else if (off + len > buf.length) throw new Error('length extends beyond buffer'); else if (position === null) throw new Error('null position currently unsupported'); var self = this; var state = this._state; if (!len) { cb && process.nextTick(function() { cb(undefined, 0); }); return; } var overflow = (len > state.maxDataLen ? len - state.maxDataLen : 0); var origPosition = position; if (overflow) len = state.maxDataLen; /* uint32 id string handle uint64 offset string data */ var handlelen = handle.length; var p = 9; var out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handlelen + 8 + 4 + len); writeUInt32BE(out, out.length - 4, 0); out[4] = REQUEST.WRITE; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(out, reqid, 5); writeUInt32BE(out, handlelen, p); handle.copy(out, p += 4); p += handlelen; for (var i = 7; i >= 0; --i) { out[p + i] = position & 0xFF; position /= 256; } writeUInt32BE(out, len, p += 8); buf.copy(out, p += 4, off, off + len); state.requests[reqid] = { cb: function(err) { if (err) cb && cb(err); else if (overflow) { self.writeData(handle, buf, off + len, overflow, origPosition + len, cb); } else cb && cb(undefined, off + len); } }; this.debug('DEBUG[SFTP]: Outgoing: Writing WRITE'); return this.push(out); }; function tryCreateBuffer(size) { try { return Buffer.allocUnsafe(size); } catch (ex) { return ex; } } function fastXfer(src, dst, srcPath, dstPath, opts, cb) { var concurrency = 64; var chunkSize = 32768; //var preserve = false; var onstep; var mode; var fileSize; if (typeof opts === 'function') { cb = opts; } else if (typeof opts === 'object' && opts !== null) { if (typeof opts.concurrency === 'number' && opts.concurrency > 0 && !isNaN(opts.concurrency)) concurrency = opts.concurrency; if (typeof opts.chunkSize === 'number' && opts.chunkSize > 0 && !isNaN(opts.chunkSize)) chunkSize = opts.chunkSize; if (typeof opts.fileSize === 'number' && opts.fileSize > 0 && !isNaN(opts.fileSize)) fileSize = opts.fileSize; if (typeof opts.step === 'function') onstep = opts.step; //preserve = (opts.preserve ? true : false); if (typeof opts.mode === 'string' || typeof opts.mode === 'number') mode = modeNum(opts.mode); } // internal state variables var fsize; var pdst = 0; var total = 0; var hadError = false; var srcHandle; var dstHandle; var readbuf; var bufsize = chunkSize * concurrency; function onerror(err) { if (hadError) return; hadError = true; var left = 0; var cbfinal; if (srcHandle || dstHandle) { cbfinal = function() { if (--left === 0) cb(err); }; if (srcHandle && (src === fs || src.writable)) ++left; if (dstHandle && (dst === fs || dst.writable)) ++left; if (srcHandle && (src === fs || src.writable)) src.close(srcHandle, cbfinal); if (dstHandle && (dst === fs || dst.writable)) dst.close(dstHandle, cbfinal); } else cb(err); } src.open(srcPath, 'r', function(err, sourceHandle) { if (err) return onerror(err); srcHandle = sourceHandle; if (fileSize === undefined) src.fstat(srcHandle, tryStat); else tryStat(null, { size: fileSize }); function tryStat(err, attrs) { if (err) { if (src !== fs) { // Try stat() for sftp servers that may not support fstat() for // whatever reason src.stat(srcPath, function(err_, attrs_) { if (err_) return onerror(err); tryStat(null, attrs_); }); return; } return onerror(err); } fsize = attrs.size; dst.open(dstPath, 'w', function(err, destHandle) { if (err) return onerror(err); dstHandle = destHandle; if (fsize <= 0) return onerror(); // Use less memory where possible while (bufsize > fsize) { if (concurrency === 1) { bufsize = fsize; break; } bufsize -= chunkSize; --concurrency; } readbuf = tryCreateBuffer(bufsize); if (readbuf instanceof Error) return onerror(readbuf); if (mode !== undefined) { dst.fchmod(dstHandle, mode, function tryAgain(err) { if (err) { // Try chmod() for sftp servers that may not support fchmod() for // whatever reason dst.chmod(dstPath, mode, function(err_) { tryAgain(); }); return; } startReads(); }); } else { startReads(); } function onread(err, nb, data, dstpos, datapos, origChunkLen) { if (err) return onerror(err); datapos = datapos || 0; if (src === fs) dst.writeData(dstHandle, readbuf, datapos, nb, dstpos, writeCb); else dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); function writeCb(err) { if (err) return onerror(err); total += nb; onstep && onstep(total, nb, fsize); if (nb < origChunkLen) return singleRead(datapos, dstpos + nb, origChunkLen - nb); if (total === fsize) { dst.close(dstHandle, function(err) { dstHandle = undefined; if (err) return onerror(err); src.close(srcHandle, function(err) { srcHandle = undefined; if (err) return onerror(err); cb(); }); }); return; } if (pdst >= fsize) return; var chunk = (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); singleRead(datapos, pdst, chunk); pdst += chunk; } } function makeCb(psrc, pdst, chunk) { return function(err, nb, data) { onread(err, nb, data, pdst, psrc, chunk); }; } function singleRead(psrc, pdst, chunk) { if (src === fs) { src.read(srcHandle, readbuf, psrc, chunk, pdst, makeCb(psrc, pdst, chunk)); } else { src.readData(srcHandle, readbuf, psrc, chunk, pdst, makeCb(psrc, pdst, chunk)); } } function startReads() { var reads = 0; var psrc = 0; while (pdst < fsize && reads < concurrency) { var chunk = (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); singleRead(psrc, pdst, chunk); psrc += chunk; pdst += chunk; ++reads; } } }); } }); } SFTPStream.prototype.fastGet = function(remotePath, localPath, opts, cb) { if (this.server) throw new Error('Client-only method called in server mode'); fastXfer(this, fs, remotePath, localPath, opts, cb); }; SFTPStream.prototype.fastPut = function(localPath, remotePath, opts, cb) { if (this.server) throw new Error('Client-only method called in server mode'); fastXfer(fs, this, localPath, remotePath, opts, cb); }; SFTPStream.prototype.readFile = function(path, options, callback_) { if (this.server) throw new Error('Client-only method called in server mode'); var callback; if (typeof callback_ === 'function') { callback = callback_; } else if (typeof options === 'function') { callback = options; options = undefined; } var self = this; if (typeof options === 'string') options = { encoding: options, flag: 'r' }; else if (!options) options = { encoding: null, flag: 'r' }; else if (typeof options !== 'object') throw new TypeError('Bad arguments'); var encoding = options.encoding; if (encoding && !Buffer.isEncoding(encoding)) throw new Error('Unknown encoding: ' + encoding); // first, stat the file, so we know the size. var size; var buffer; // single buffer with file data var buffers; // list for when size is unknown var pos = 0; var handle; // SFTPv3 does not support using -1 for read position, so we have to track // read position manually var bytesRead = 0; var flag = options.flag || 'r'; this.open(path, flag, 438 /*=0666*/, function(er, handle_) { if (er) return callback && callback(er); handle = handle_; self.fstat(handle, function tryStat(er, st) { if (er) { // Try stat() for sftp servers that may not support fstat() for // whatever reason self.stat(path, function(er_, st_) { if (er_) { return self.close(handle, function() { callback && callback(er); }); } tryStat(null, st_); }); return; } size = st.size || 0; if (size === 0) { // the kernel lies about many files. // Go ahead and try to read some bytes. buffers = []; return read(); } buffer = Buffer.allocUnsafe(size); read(); }); }); function read() { if (size === 0) { buffer = Buffer.allocUnsafe(8192); self.readData(handle, buffer, 0, 8192, bytesRead, afterRead); } else { self.readData(handle, buffer, pos, size - pos, bytesRead, afterRead); } } function afterRead(er, nbytes) { var eof; if (er) { eof = (er.code === STATUS_CODE.EOF); if (!eof) { return self.close(handle, function() { return callback && callback(er); }); } } else { eof = false; } if (eof || (size === 0 && nbytes === 0)) return close(); bytesRead += nbytes; pos += nbytes; if (size !== 0) { if (pos === size) close(); else read(); } else { // unknown size, just read until we don't get bytes. buffers.push(buffer.slice(0, nbytes)); read(); } } afterRead._wantEOFError = true; function close() { self.close(handle, function(er) { if (size === 0) { // collected the data into the buffers list. buffer = Buffer.concat(buffers, pos); } else if (pos < size) { buffer = buffer.slice(0, pos); } if (encoding) buffer = buffer.toString(encoding); return callback && callback(er, buffer); }); } }; function writeAll(self, handle, buffer, offset, length, position, callback_) { var callback = (typeof callback_ === 'function' ? callback_ : undefined); self.writeData(handle, buffer, offset, length, position, function(writeErr, written) { if (writeErr) { return self.close(handle, function() { callback && callback(writeErr); }); } if (written === length) self.close(handle, callback); else { offset += written; length -= written; position += written; writeAll(self, handle, buffer, offset, length, position, callback); } }); } SFTPStream.prototype.writeFile = function(path, data, options, callback_) { if (this.server) throw new Error('Client-only method called in server mode'); var callback; if (typeof callback_ === 'function') { callback = callback_; } else if (typeof options === 'function') { callback = options; options = undefined; } var self = this; if (typeof options === 'string') options = { encoding: options, mode: 438, flag: 'w' }; else if (!options) options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; else if (typeof options !== 'object') throw new TypeError('Bad arguments'); if (options.encoding && !Buffer.isEncoding(options.encoding)) throw new Error('Unknown encoding: ' + options.encoding); var flag = options.flag || 'w'; this.open(path, flag, options.mode, function(openErr, handle) { if (openErr) callback && callback(openErr); else { var buffer = (Buffer.isBuffer(data) ? data : Buffer.from('' + data, options.encoding || 'utf8')); var position = (/a/.test(flag) ? null : 0); // SFTPv3 does not support the notion of 'current position' // (null position), so we just attempt to append to the end of the file // instead if (position === null) { self.fstat(handle, function tryStat(er, st) { if (er) { // Try stat() for sftp servers that may not support fstat() for // whatever reason self.stat(path, function(er_, st_) { if (er_) { return self.close(handle, function() { callback && callback(er); }); } tryStat(null, st_); }); return; } writeAll(self, handle, buffer, 0, buffer.length, st.size, callback); }); return; } writeAll(self, handle, buffer, 0, buffer.length, position, callback); } }); }; SFTPStream.prototype.appendFile = function(path, data, options, callback_) { if (this.server) throw new Error('Client-only method called in server mode'); var callback; if (typeof callback_ === 'function') { callback = callback_; } else if (typeof options === 'function') { callback = options; options = undefined; } if (typeof options === 'string') options = { encoding: options, mode: 438, flag: 'a' }; else if (!options) options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; else if (typeof options !== 'object') throw new TypeError('Bad arguments'); if (!options.flag) options = util._extend({ flag: 'a' }, options); this.writeFile(path, data, options, callback); }; SFTPStream.prototype.exists = function(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); this.stat(path, function(err) { cb && cb(err ? false : true); }); }; SFTPStream.prototype.unlink = function(filename, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; /* uint32 id string filename */ var fnamelen = Buffer.byteLength(filename); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnamelen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.REMOVE; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, fnamelen, p); buf.write(filename, p += 4, fnamelen, 'utf8'); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing REMOVE'); return this.push(buf); }; SFTPStream.prototype.rename = function(oldPath, newPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; /* uint32 id string oldpath string newpath */ var oldlen = Buffer.byteLength(oldPath); var newlen = Buffer.byteLength(newPath); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldlen + 4 + newlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.RENAME; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, oldlen, p); buf.write(oldPath, p += 4, oldlen, 'utf8'); writeUInt32BE(buf, newlen, p += oldlen); buf.write(newPath, p += 4, newlen, 'utf8'); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing RENAME'); return this.push(buf); }; SFTPStream.prototype.mkdir = function(path, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var flags = 0; var attrBytes = 0; var state = this._state; if (typeof attrs === 'function') { cb = attrs; attrs = undefined; } if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrBytes = attrs.nbytes; attrs = attrs.bytes; } /* uint32 id string path ATTRS attrs */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen + 4 + attrBytes); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.MKDIR; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathlen, p); buf.write(path, p += 4, pathlen, 'utf8'); writeUInt32BE(buf, flags, p += pathlen); if (flags) { p += 4; for (var i = 0, len = attrs.length; i < len; ++i) for (var j = 0, len2 = attrs[i].length; j < len2; ++j) buf[p++] = attrs[i][j]; } state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing MKDIR'); return this.push(buf); }; SFTPStream.prototype.rmdir = function(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; /* uint32 id string path */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.RMDIR; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathlen, p); buf.write(path, p += 4, pathlen, 'utf8'); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing RMDIR'); return this.push(buf); }; SFTPStream.prototype.readdir = function(where, opts, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; var doFilter; if (typeof opts === 'function') { cb = opts; opts = {}; } if (typeof opts !== 'object' || opts === null) opts = {}; doFilter = (opts && opts.full ? false : true); if (!Buffer.isBuffer(where) && typeof where !== 'string') throw new Error('missing directory handle or path'); if (typeof where === 'string') { var self = this; var entries = []; var e = 0; return this.opendir(where, function reread(err, handle) { if (err) return cb(err); self.readdir(handle, opts, function(err, list) { var eof = (err && err.code === STATUS_CODE.EOF); if (err && !eof) { return self.close(handle, function() { cb(err); }); } else if (eof) { return self.close(handle, function(err) { if (err) return cb(err); cb(undefined, entries); }); } for (var i = 0, len = list.length; i < len; ++i, ++e) entries[e] = list[i]; reread(undefined, handle); }); }); } /* uint32 id string handle */ var handlelen = where.length; var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handlelen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.READDIR; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handlelen, p); where.copy(buf, p += 4); state.requests[reqid] = { cb: (doFilter ? function(err, list) { if (err) return cb(err); for (var i = list.length - 1; i >= 0; --i) { if (list[i].filename === '.' || list[i].filename === '..') list.splice(i, 1); } cb(undefined, list); } : cb) }; this.debug('DEBUG[SFTP]: Outgoing: Writing READDIR'); return this.push(buf); }; SFTPStream.prototype.fstat = function(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); else if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); var state = this._state; /* uint32 id string handle */ var handlelen = handle.length; var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handlelen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.FSTAT; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handlelen, p); handle.copy(buf, p += 4); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing FSTAT'); return this.push(buf); }; SFTPStream.prototype.stat = function(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; /* uint32 id string path */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.STAT; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathlen, p); buf.write(path, p += 4, pathlen, 'utf8'); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing STAT'); return this.push(buf); }; SFTPStream.prototype.lstat = function(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; /* uint32 id string path */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.LSTAT; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathlen, p); buf.write(path, p += 4, pathlen, 'utf8'); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing LSTAT'); return this.push(buf); }; SFTPStream.prototype.opendir = function(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; /* uint32 id string path */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.OPENDIR; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathlen, p); buf.write(path, p += 4, pathlen, 'utf8'); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing OPENDIR'); return this.push(buf); }; SFTPStream.prototype.setstat = function(path, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var flags = 0; var attrBytes = 0; var state = this._state; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrBytes = attrs.nbytes; attrs = attrs.bytes; } else if (typeof attrs === 'function') cb = attrs; /* uint32 id string path ATTRS attrs */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen + 4 + attrBytes); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.SETSTAT; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathlen, p); buf.write(path, p += 4, pathlen, 'utf8'); writeUInt32BE(buf, flags, p += pathlen); if (flags) { p += 4; for (var i = 0, len = attrs.length; i < len; ++i) for (var j = 0, len2 = attrs[i].length; j < len2; ++j) buf[p++] = attrs[i][j]; } state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing SETSTAT'); return this.push(buf); }; SFTPStream.prototype.fsetstat = function(handle, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); else if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); var flags = 0; var attrBytes = 0; var state = this._state; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrBytes = attrs.nbytes; attrs = attrs.bytes; } else if (typeof attrs === 'function') cb = attrs; /* uint32 id string handle ATTRS attrs */ var handlelen = handle.length; var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handlelen + 4 + attrBytes); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.FSETSTAT; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handlelen, p); handle.copy(buf, p += 4); writeUInt32BE(buf, flags, p += handlelen); if (flags) { p += 4; for (var i = 0, len = attrs.length; i < len; ++i) for (var j = 0, len2 = attrs[i].length; j < len2; ++j) buf[p++] = attrs[i][j]; } state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing FSETSTAT'); return this.push(buf); }; SFTPStream.prototype.futimes = function(handle, atime, mtime, cb) { return this.fsetstat(handle, { atime: toUnixTimestamp(atime), mtime: toUnixTimestamp(mtime) }, cb); }; SFTPStream.prototype.utimes = function(path, atime, mtime, cb) { return this.setstat(path, { atime: toUnixTimestamp(atime), mtime: toUnixTimestamp(mtime) }, cb); }; SFTPStream.prototype.fchown = function(handle, uid, gid, cb) { return this.fsetstat(handle, { uid: uid, gid: gid }, cb); }; SFTPStream.prototype.chown = function(path, uid, gid, cb) { return this.setstat(path, { uid: uid, gid: gid }, cb); }; SFTPStream.prototype.fchmod = function(handle, mode, cb) { return this.fsetstat(handle, { mode: mode }, cb); }; SFTPStream.prototype.chmod = function(path, mode, cb) { return this.setstat(path, { mode: mode }, cb); }; SFTPStream.prototype.readlink = function(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; /* uint32 id string path */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.READLINK; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathlen, p); buf.write(path, p += 4, pathlen, 'utf8'); state.requests[reqid] = { cb: function(err, names) { if (err) return cb(err); else if (!names || !names.length) return cb(new Error('Response missing link info')); cb(undefined, names[0].filename); } }; this.debug('DEBUG[SFTP]: Outgoing: Writing READLINK'); return this.push(buf); }; SFTPStream.prototype.symlink = function(targetPath, linkPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; /* uint32 id string linkpath string targetpath */ var linklen = Buffer.byteLength(linkPath); var targetlen = Buffer.byteLength(targetPath); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linklen + 4 + targetlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.SYMLINK; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); if (this._isOpenSSH) { // OpenSSH has linkpath and targetpath positions switched writeUInt32BE(buf, targetlen, p); buf.write(targetPath, p += 4, targetlen, 'utf8'); writeUInt32BE(buf, linklen, p += targetlen); buf.write(linkPath, p += 4, linklen, 'utf8'); } else { writeUInt32BE(buf, linklen, p); buf.write(linkPath, p += 4, linklen, 'utf8'); writeUInt32BE(buf, targetlen, p += linklen); buf.write(targetPath, p += 4, targetlen, 'utf8'); } state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing SYMLINK'); return this.push(buf); }; SFTPStream.prototype.realpath = function(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); var state = this._state; /* uint32 id string path */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.REALPATH; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathlen, p); buf.write(path, p += 4, pathlen, 'utf8'); state.requests[reqid] = { cb: function(err, names) { if (err) return cb(err); else if (!names || !names.length) return cb(new Error('Response missing path info')); cb(undefined, names[0].filename); } }; this.debug('DEBUG[SFTP]: Outgoing: Writing REALPATH'); return this.push(buf); }; // extended requests SFTPStream.prototype.ext_openssh_rename = function(oldPath, newPath, cb) { var state = this._state; if (this.server) throw new Error('Client-only method called in server mode'); else if (!state.extensions['posix-rename@openssh.com'] || state.extensions['posix-rename@openssh.com'].indexOf('1') === -1) throw new Error('Server does not support this extended request'); /* uint32 id string "posix-rename@openssh.com" string oldpath string newpath */ var oldlen = Buffer.byteLength(oldPath); var newlen = Buffer.byteLength(newPath); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldlen + 4 + newlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 24, p); buf.write('posix-rename@openssh.com', p += 4, 24, 'ascii'); writeUInt32BE(buf, oldlen, p += 24); buf.write(oldPath, p += 4, oldlen, 'utf8'); writeUInt32BE(buf, newlen, p += oldlen); buf.write(newPath, p += 4, newlen, 'utf8'); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing posix-rename@openssh.com'); return this.push(buf); }; SFTPStream.prototype.ext_openssh_statvfs = function(path, cb) { var state = this._state; if (this.server) throw new Error('Client-only method called in server mode'); else if (!state.extensions['statvfs@openssh.com'] || state.extensions['statvfs@openssh.com'].indexOf('2') === -1) throw new Error('Server does not support this extended request'); /* uint32 id string "statvfs@openssh.com" string path */ var pathlen = Buffer.byteLength(path); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 19, p); buf.write('statvfs@openssh.com', p += 4, 19, 'ascii'); writeUInt32BE(buf, pathlen, p += 19); buf.write(path, p += 4, pathlen, 'utf8'); state.requests[reqid] = { extended: 'statvfs@openssh.com', cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing statvfs@openssh.com'); return this.push(buf); }; SFTPStream.prototype.ext_openssh_fstatvfs = function(handle, cb) { var state = this._state; if (this.server) throw new Error('Client-only method called in server mode'); else if (!state.extensions['fstatvfs@openssh.com'] || state.extensions['fstatvfs@openssh.com'].indexOf('2') === -1) throw new Error('Server does not support this extended request'); else if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string "fstatvfs@openssh.com" string handle */ var handlelen = handle.length; var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handlelen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 20, p); buf.write('fstatvfs@openssh.com', p += 4, 20, 'ascii'); writeUInt32BE(buf, handlelen, p += 20); buf.write(handle, p += 4, handlelen, 'utf8'); state.requests[reqid] = { extended: 'fstatvfs@openssh.com', cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing fstatvfs@openssh.com'); return this.push(buf); }; SFTPStream.prototype.ext_openssh_hardlink = function(oldPath, newPath, cb) { var state = this._state; if (this.server) throw new Error('Client-only method called in server mode'); else if (!state.extensions['hardlink@openssh.com'] || state.extensions['hardlink@openssh.com'].indexOf('1') === -1) throw new Error('Server does not support this extended request'); /* uint32 id string "hardlink@openssh.com" string oldpath string newpath */ var oldlen = Buffer.byteLength(oldPath); var newlen = Buffer.byteLength(newPath); var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldlen + 4 + newlen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 20, p); buf.write('hardlink@openssh.com', p += 4, 20, 'ascii'); writeUInt32BE(buf, oldlen, p += 20); buf.write(oldPath, p += 4, oldlen, 'utf8'); writeUInt32BE(buf, newlen, p += oldlen); buf.write(newPath, p += 4, newlen, 'utf8'); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing hardlink@openssh.com'); return this.push(buf); }; SFTPStream.prototype.ext_openssh_fsync = function(handle, cb) { var state = this._state; if (this.server) throw new Error('Client-only method called in server mode'); else if (!state.extensions['fsync@openssh.com'] || state.extensions['fsync@openssh.com'].indexOf('1') === -1) throw new Error('Server does not support this extended request'); else if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string "fsync@openssh.com" string handle */ var handlelen = handle.length; var p = 9; var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handlelen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 17, p); buf.write('fsync@openssh.com', p += 4, 17, 'ascii'); writeUInt32BE(buf, handlelen, p += 17); buf.write(handle, p += 4, handlelen, 'utf8'); state.requests[reqid] = { cb: cb }; this.debug('DEBUG[SFTP]: Outgoing: Writing fsync@openssh.com'); return this.push(buf); }; // server SFTPStream.prototype.status = function(id, code, message, lang) { if (!this.server) throw new Error('Server-only method called in client mode'); if (!STATUS_CODE[code] || typeof code !== 'number') throw new Error('Bad status code: ' + code); message || (message = ''); lang || (lang = ''); var msgLen = Buffer.byteLength(message); var langLen = Buffer.byteLength(lang); var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4 + langLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.STATUS; writeUInt32BE(buf, id, 5); writeUInt32BE(buf, code, 9); writeUInt32BE(buf, msgLen, 13); if (msgLen) buf.write(message, 17, msgLen, 'utf8'); writeUInt32BE(buf, langLen, 17 + msgLen); if (langLen) buf.write(lang, 17 + msgLen + 4, langLen, 'ascii'); this.debug('DEBUG[SFTP]: Outgoing: Writing STATUS'); return this.push(buf); }; SFTPStream.prototype.handle = function(id, handle) { if (!this.server) throw new Error('Server-only method called in client mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); var handleLen = handle.length; if (handleLen > 256) throw new Error('handle too large (> 256 bytes)'); var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.HANDLE; writeUInt32BE(buf, id, 5); writeUInt32BE(buf, handleLen, 9); if (handleLen) handle.copy(buf, 13); this.debug('DEBUG[SFTP]: Outgoing: Writing HANDLE'); return this.push(buf); }; SFTPStream.prototype.data = function(id, data, encoding) { if (!this.server) throw new Error('Server-only method called in client mode'); var isBuffer = Buffer.isBuffer(data); if (!isBuffer && typeof data !== 'string') throw new Error('data is not a Buffer or string'); if (!isBuffer) encoding || (encoding = 'utf8'); var dataLen = (isBuffer ? data.length : Buffer.byteLength(data, encoding)); var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.DATA; writeUInt32BE(buf, id, 5); writeUInt32BE(buf, dataLen, 9); if (dataLen) { if (isBuffer) data.copy(buf, 13); else buf.write(data, 13, dataLen, encoding); } this.debug('DEBUG[SFTP]: Outgoing: Writing DATA'); return this.push(buf); }; SFTPStream.prototype.name = function(id, names) { if (!this.server) throw new Error('Server-only method called in client mode'); if (!Array.isArray(names)) { if (typeof names !== 'object' || names === null) throw new Error('names is not an object or array'); names = [ names ]; } var count = names.length; var namesLen = 0; var nameAttrs; var attrs = []; var name; var filename; var longname; var attr; var len; var len2; var buf; var p; var i; var j; var k; for (i = 0; i < count; ++i) { name = names[i]; filename = (!name || !name.filename || typeof name.filename !== 'string' ? '' : name.filename); namesLen += 4 + Buffer.byteLength(filename); longname = (!name || !name.longname || typeof name.longname !== 'string' ? '' : name.longname); namesLen += 4 + Buffer.byteLength(longname); if (typeof name.attrs === 'object' && name.attrs !== null) { nameAttrs = attrsToBytes(name.attrs); namesLen += 4 + nameAttrs.nbytes; attrs.push(nameAttrs); } else { namesLen += 4; attrs.push(null); } } buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.NAME; writeUInt32BE(buf, id, 5); writeUInt32BE(buf, count, 9); p = 13; for (i = 0; i < count; ++i) { name = names[i]; filename = (!name || !name.filename || typeof name.filename !== 'string' ? '' : name.filename); len = Buffer.byteLength(filename); writeUInt32BE(buf, len, p); p += 4; if (len) { buf.write(filename, p, len, 'utf8'); p += len; } longname = (!name || !name.longname || typeof name.longname !== 'string' ? '' : name.longname); len = Buffer.byteLength(longname); writeUInt32BE(buf, len, p); p += 4; if (len) { buf.write(longname, p, len, 'utf8'); p += len; } attr = attrs[i]; if (attr) { writeUInt32BE(buf, attr.flags, p); p += 4; if (attr.flags && attr.bytes) { var bytes = attr.bytes; for (j = 0, len = bytes.length; j < len; ++j) for (k = 0, len2 = bytes[j].length; k < len2; ++k) buf[p++] = bytes[j][k]; } } else { writeUInt32BE(buf, 0, p); p += 4; } } this.debug('DEBUG[SFTP]: Outgoing: Writing NAME'); return this.push(buf); }; SFTPStream.prototype.attrs = function(id, attrs) { if (!this.server) throw new Error('Server-only method called in client mode'); if (typeof attrs !== 'object' || attrs === null) throw new Error('attrs is not an object'); var info = attrsToBytes(attrs); var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + info.nbytes); var p = 13; writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.ATTRS; writeUInt32BE(buf, id, 5); writeUInt32BE(buf, info.flags, 9); if (info.flags && info.bytes) { var bytes = info.bytes; for (var j = 0, len = bytes.length; j < len; ++j) for (var k = 0, len2 = bytes[j].length; k < len2; ++k) buf[p++] = bytes[j][k]; } this.debug('DEBUG[SFTP]: Outgoing: Writing ATTRS'); return this.push(buf); }; function readAttrs(buf, p, stream, callback) { /* uint32 flags uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS uint32 atime present only if flag SSH_FILEXFER_ACMODTIME uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED string extended_type string extended_data ... more extended data (extended_type - extended_data pairs), so that number of pairs equals extended_count */ var flags = readUInt32BE(buf, p); var attrs = new Stats(); p += 4; if (flags & ATTR.SIZE) { var size = readUInt64BE(buf, p, stream, callback); if (size === false) return false; attrs.size = size; p += 8; } if (flags & ATTR.UIDGID) { var uid; var gid; uid = readInt(buf, p, this, callback); if (uid === false) return false; attrs.uid = uid; p += 4; gid = readInt(buf, p, this, callback); if (gid === false) return false; attrs.gid = gid; p += 4; } if (flags & ATTR.PERMISSIONS) { var mode = readInt(buf, p, this, callback); if (mode === false) return false; attrs.mode = mode; // backwards compatibility attrs.permissions = mode; p += 4; } if (flags & ATTR.ACMODTIME) { var atime; var mtime; atime = readInt(buf, p, this, callback); if (atime === false) return false; attrs.atime = atime; p += 4; mtime = readInt(buf, p, this, callback); if (mtime === false) return false; attrs.mtime = mtime; p += 4; } if (flags & ATTR.EXTENDED) { // TODO: read/parse extended data var extcount = readInt(buf, p, this, callback); if (extcount === false) return false; p += 4; for (var i = 0, len; i < extcount; ++i) { len = readInt(buf, p, this, callback); if (len === false) return false; p += 4 + len; } } buf._pos = p; return attrs; } function readUInt64BE(buffer, p, stream, callback) { if ((buffer.length - p) < 8) { stream && stream._cleanup(callback); return false; } var val = 0; for (var len = p + 8; p < len; ++p) { val *= 256; val += buffer[p]; } buffer._pos = p; return val; } function attrsToBytes(attrs) { var flags = 0; var attrBytes = 0; var ret = []; var i = 0; if (typeof attrs !== 'object' || attrs === null) return { flags: flags, nbytes: attrBytes, bytes: ret }; if (typeof attrs.size === 'number') { flags |= ATTR.SIZE; attrBytes += 8; var sizeBytes = new Array(8); var val = attrs.size; for (i = 7; i >= 0; --i) { sizeBytes[i] = val & 0xFF; val /= 256; } ret.push(sizeBytes); } if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { flags |= ATTR.UIDGID; attrBytes += 8; ret.push([(attrs.uid >> 24) & 0xFF, (attrs.uid >> 16) & 0xFF, (attrs.uid >> 8) & 0xFF, attrs.uid & 0xFF]); ret.push([(attrs.gid >> 24) & 0xFF, (attrs.gid >> 16) & 0xFF, (attrs.gid >> 8) & 0xFF, attrs.gid & 0xFF]); } if (typeof attrs.permissions === 'number' || typeof attrs.permissions === 'string' || typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { var mode = modeNum(attrs.mode || attrs.permissions); flags |= ATTR.PERMISSIONS; attrBytes += 4; ret.push([(mode >> 24) & 0xFF, (mode >> 16) & 0xFF, (mode >> 8) & 0xFF, mode & 0xFF]); } if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { var atime = toUnixTimestamp(attrs.atime); var mtime = toUnixTimestamp(attrs.mtime); flags |= ATTR.ACMODTIME; attrBytes += 8; ret.push([(atime >> 24) & 0xFF, (atime >> 16) & 0xFF, (atime >> 8) & 0xFF, atime & 0xFF]); ret.push([(mtime >> 24) & 0xFF, (mtime >> 16) & 0xFF, (mtime >> 8) & 0xFF, mtime & 0xFF]); } // TODO: extended attributes return { flags: flags, nbytes: attrBytes, bytes: ret }; } function toUnixTimestamp(time) { if (typeof time === 'number' && !isNaN(time)) return time; else if (isDate(time)) return parseInt(time.getTime() / 1000, 10); throw new Error('Cannot parse time: ' + time); } function modeNum(mode) { if (typeof mode === 'number' && !isNaN(mode)) return mode; else if (typeof mode === 'string') return modeNum(parseInt(mode, 8)); throw new Error('Cannot parse mode: ' + mode); } var stringFlagMap = { 'r': OPEN_MODE.READ, 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL }; var stringFlagMapKeys = Object.keys(stringFlagMap); function stringToFlags(str) { var flags = stringFlagMap[str]; if (flags !== undefined) return flags; return null; } SFTPStream.stringToFlags = stringToFlags; function flagsToString(flags) { for (var i = 0; i < stringFlagMapKeys.length; ++i) { var key = stringFlagMapKeys[i]; if (stringFlagMap[key] === flags) return key; } return null; } SFTPStream.flagsToString = flagsToString; function Stats(initial) { this.mode = (initial && initial.mode); this.permissions = this.mode; // backwards compatiblity this.uid = (initial && initial.uid); this.gid = (initial && initial.gid); this.size = (initial && initial.size); this.atime = (initial && initial.atime); this.mtime = (initial && initial.mtime); } Stats.prototype._checkModeProperty = function(property) { return ((this.mode & constants.S_IFMT) === property); }; Stats.prototype.isDirectory = function() { return this._checkModeProperty(constants.S_IFDIR); }; Stats.prototype.isFile = function() { return this._checkModeProperty(constants.S_IFREG); }; Stats.prototype.isBlockDevice = function() { return this._checkModeProperty(constants.S_IFBLK); }; Stats.prototype.isCharacterDevice = function() { return this._checkModeProperty(constants.S_IFCHR); }; Stats.prototype.isSymbolicLink = function() { return this._checkModeProperty(constants.S_IFLNK); }; Stats.prototype.isFIFO = function() { return this._checkModeProperty(constants.S_IFIFO); }; Stats.prototype.isSocket = function() { return this._checkModeProperty(constants.S_IFSOCK); }; SFTPStream.Stats = Stats; // ============================================================================= // ReadStream/WriteStream-related var fsCompat = __nccwpck_require__(1839); var validateNumber = fsCompat.validateNumber; var destroyImpl = fsCompat.destroyImpl; var ERR_OUT_OF_RANGE = fsCompat.ERR_OUT_OF_RANGE; var ERR_INVALID_ARG_TYPE = fsCompat.ERR_INVALID_ARG_TYPE; var kMinPoolSpace = 128; var pool; // It can happen that we expect to read a large chunk of data, and reserve // a large chunk of the pool accordingly, but the read() call only filled // a portion of it. If a concurrently executing read() then uses the same pool, // the "reserved" portion cannot be used, so we allow it to be re-used as a // new pool later. var poolFragments = []; function allocNewPool(poolSize) { if (poolFragments.length > 0) pool = poolFragments.pop(); else pool = Buffer.allocUnsafe(poolSize); pool.used = 0; } // Check the `this.start` and `this.end` of stream. function checkPosition(pos, name) { if (!Number.isSafeInteger(pos)) { validateNumber(pos, name); if (!Number.isInteger(pos)) throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); } if (pos < 0) throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); } function roundUpToMultipleOf8(n) { return (n + 7) & ~7; // Align to 8 byte boundary. } function ReadStream(sftp, path, options) { if (options === undefined) options = {}; else if (typeof options === 'string') options = { encoding: options }; else if (options === null || typeof options !== 'object') throw new TypeError('"options" argument must be a string or an object'); else options = Object.create(options); // A little bit bigger buffer and water marks by default if (options.highWaterMark === undefined) options.highWaterMark = 64 * 1024; // For backwards compat do not emit close on destroy. options.emitClose = false; ReadableStream.call(this, options); this.path = path; this.flags = options.flags === undefined ? 'r' : options.flags; this.mode = options.mode === undefined ? 0o666 : options.mode; this.start = options.start; this.end = options.end; this.autoClose = options.autoClose === undefined ? true : options.autoClose; this.pos = 0; this.bytesRead = 0; this.closed = false; this.handle = options.handle === undefined ? null : options.handle; this.sftp = sftp; this._opening = false; if (this.start !== undefined) { checkPosition(this.start, 'start'); this.pos = this.start; } if (this.end === undefined) { this.end = Infinity; } else if (this.end !== Infinity) { checkPosition(this.end, 'end'); if (this.start !== undefined && this.start > this.end) { throw new ERR_OUT_OF_RANGE( 'start', `<= "end" (here: ${this.end})`, this.start ); } } this.on('end', function() { if (this.autoClose) this.destroy(); }); if (!Buffer.isBuffer(this.handle)) this.open(); } inherits(ReadStream, ReadableStream); ReadStream.prototype.open = function() { if (this._opening) return; this._opening = true; this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { this._opening = false; if (er) { this.emit('error', er); if (this.autoClose) this.destroy(); return; } this.handle = handle; this.emit('open', handle); this.emit('ready'); // start the flow of data. this.read(); }); }; ReadStream.prototype._read = function(n) { if (!Buffer.isBuffer(this.handle)) { return this.once('open', function() { this._read(n); }); } // XXX: safe to remove this? if (this.destroyed) return; if (!pool || pool.length - pool.used < kMinPoolSpace) { // discard the old pool. allocNewPool(this.readableHighWaterMark || this._readableState.highWaterMark); } // Grab another reference to the pool in the case that while we're // in the thread pool another read() finishes up the pool, and // allocates a new one. var thisPool = pool; var toRead = Math.min(pool.length - pool.used, n); var start = pool.used; if (this.end !== undefined) toRead = Math.min(this.end - this.pos + 1, toRead); // Already read everything we were supposed to read! // treat as EOF. if (toRead <= 0) return this.push(null); // the actual read. this.sftp.readData(this.handle, pool, pool.used, toRead, this.pos, (er, bytesRead) => { if (er) { this.emit('error', er); if (this.autoClose) this.destroy(); return; } var b = null; // Now that we know how much data we have actually read, re-wind the // 'used' field if we can, and otherwise allow the remainder of our // reservation to be used as a new pool later. if (start + toRead === thisPool.used && thisPool === pool) { var newUsed = thisPool.used + bytesRead - toRead; thisPool.used = roundUpToMultipleOf8(newUsed); } else { // Round down to the next lowest multiple of 8 to ensure the new pool // fragment start and end positions are aligned to an 8 byte boundary. var alignedEnd = (start + toRead) & ~7; var alignedStart = roundUpToMultipleOf8(start + bytesRead); if (alignedEnd - alignedStart >= kMinPoolSpace) poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); } if (bytesRead > 0) { this.bytesRead += bytesRead; b = thisPool.slice(start, start + bytesRead); } // Move the pool positions, and internal position for reading. this.pos += bytesRead; this.push(b); }); pool.used = roundUpToMultipleOf8(pool.used + toRead); }; if (typeof ReadableStream.prototype.destroy !== 'function') ReadStream.prototype.destroy = destroyImpl; ReadStream.prototype._destroy = function(err, cb) { if (this._opening && !Buffer.isBuffer(this.handle)) { this.once('open', closeStream.bind(null, this, cb, err)); return; } closeStream(this, cb, err); this.handle = null; this._opening = false; }; function closeStream(stream, cb, err) { if (!stream.handle) return onclose(); stream.sftp.close(stream.handle, onclose); function onclose(er) { er = er || err; cb(er); stream.closed = true; if (!er) stream.emit('close'); } } ReadStream.prototype.close = function(cb) { this.destroy(null, cb); }; Object.defineProperty(ReadStream.prototype, 'pending', { get() { return this.handle === null; }, configurable: true }); function WriteStream(sftp, path, options) { if (options === undefined) options = {}; else if (typeof options === 'string') options = { encoding: options }; else if (options === null || typeof options !== 'object') throw new TypeError('"options" argument must be a string or an object'); else options = Object.create(options); // For backwards compat do not emit close on destroy. options.emitClose = false; WritableStream.call(this, options); this.path = path; this.flags = options.flags === undefined ? 'w' : options.flags; this.mode = options.mode === undefined ? 0o666 : options.mode; this.start = options.start; this.autoClose = options.autoClose === undefined ? true : options.autoClose; this.pos = 0; this.bytesWritten = 0; this.closed = false; this.handle = options.handle === undefined ? null : options.handle; this.sftp = sftp; this._opening = false; if (this.start !== undefined) { checkPosition(this.start, 'start'); this.pos = this.start; } if (options.encoding) this.setDefaultEncoding(options.encoding); // Node v6.x only this.on('finish', function() { if (this._writableState.finalCalled) return; if (this.autoClose) this.destroy(); }); if (!Buffer.isBuffer(this.handle)) this.open(); } inherits(WriteStream, WritableStream); WriteStream.prototype._final = function(cb) { if (this.autoClose) this.destroy(); cb(); }; WriteStream.prototype.open = function() { if (this._opening) return; this._opening = true; this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { this._opening = false; if (er) { this.emit('error', er); if (this.autoClose) this.destroy(); return; } this.handle = handle; var tryAgain = (err) => { if (err) { // Try chmod() for sftp servers that may not support fchmod() for // whatever reason this.sftp.chmod(this.path, this.mode, (err_) => { tryAgain(); }); return; } // SFTPv3 requires absolute offsets, no matter the open flag used if (this.flags[0] === 'a') { var tryStat = (err, st) => { if (err) { // Try stat() for sftp servers that may not support fstat() for // whatever reason this.sftp.stat(this.path, (err_, st_) => { if (err_) { this.destroy(); this.emit('error', err); return; } tryStat(null, st_); }); return; } this.pos = st.size; this.emit('open', handle); this.emit('ready'); }; this.sftp.fstat(handle, tryStat); return; } this.emit('open', handle); this.emit('ready'); }; this.sftp.fchmod(handle, this.mode, tryAgain); }); }; WriteStream.prototype._write = function(data, encoding, cb) { if (!Buffer.isBuffer(data)) { const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); return this.emit('error', err); } if (!Buffer.isBuffer(this.handle)) { return this.once('open', function() { this._write(data, encoding, cb); }); } this.sftp.writeData(this.handle, data, 0, data.length, this.pos, (er, bytes) => { if (er) { if (this.autoClose) this.destroy(); return cb(er); } this.bytesWritten += bytes; cb(); }); this.pos += data.length; }; WriteStream.prototype._writev = function(data, cb) { if (!Buffer.isBuffer(this.handle)) { return this.once('open', function() { this._writev(data, cb); }); } var sftp = this.sftp; var handle = this.handle; var writesLeft = data.length; var onwrite = (er, bytes) => { if (er) { this.destroy(); return cb(er); } this.bytesWritten += bytes; if (--writesLeft === 0) cb(); }; // TODO: try to combine chunks to reduce number of requests to the server for (var i = 0; i < data.length; ++i) { var chunk = data[i].chunk; sftp.writeData(handle, chunk, 0, chunk.length, this.pos, onwrite); this.pos += chunk.length; } }; if (typeof WritableStream.prototype.destroy !== 'function') WriteStream.prototype.destroy = ReadStream.prototype.destroy; WriteStream.prototype._destroy = ReadStream.prototype._destroy; WriteStream.prototype.close = function(cb) { if (cb) { if (this.closed) { process.nextTick(cb); return; } else { this.on('close', cb); } } // If we are not autoClosing, we should call // destroy on 'finish'. if (!this.autoClose) this.on('finish', this.destroy.bind(this)); this.end(); }; // There is no shutdown() for files. WriteStream.prototype.destroySoon = WriteStream.prototype.end; Object.defineProperty(WriteStream.prototype, 'pending', { get() { return this.handle === null; }, configurable: true }); module.exports = SFTPStream; /***/ }), /***/ 8494: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // TODO: * Automatic re-key every (configurable) n bytes or length of time // - RFC suggests every 1GB of transmitted data or 1 hour, whichever // comes sooner // * Filter control codes from strings // (as per http://tools.ietf.org/html/rfc4251#section-9.2) var crypto = __nccwpck_require__(6982); var zlib = __nccwpck_require__(3106); var TransformStream = (__nccwpck_require__(2203).Transform); var inherits = (__nccwpck_require__(9023).inherits); var inspect = (__nccwpck_require__(9023).inspect); var StreamSearch = __nccwpck_require__(9026); var Ber = (__nccwpck_require__(9837).Ber); var readUInt32BE = (__nccwpck_require__(4288).readUInt32BE); var writeUInt32BE = (__nccwpck_require__(4288).writeUInt32BE); var consts = __nccwpck_require__(4169); var utils = __nccwpck_require__(2557); var iv_inc = utils.iv_inc; var readString = utils.readString; var readInt = utils.readInt; var DSASigBERToBare = utils.DSASigBERToBare; var ECDSASigASN1ToSSH = utils.ECDSASigASN1ToSSH; var sigSSHToASN1 = utils.sigSSHToASN1; var parseDERKey = (__nccwpck_require__(7044).parseDERKey); var CIPHER_INFO = consts.CIPHER_INFO; var HMAC_INFO = consts.HMAC_INFO; var MESSAGE = consts.MESSAGE; var DYNAMIC_KEXDH_MESSAGE = consts.DYNAMIC_KEXDH_MESSAGE; var KEXDH_MESSAGE = consts.KEXDH_MESSAGE; var ALGORITHMS = consts.ALGORITHMS; var DISCONNECT_REASON = consts.DISCONNECT_REASON; var CHANNEL_OPEN_FAILURE = consts.CHANNEL_OPEN_FAILURE; var SSH_TO_OPENSSL = consts.SSH_TO_OPENSSL; var TERMINAL_MODE = consts.TERMINAL_MODE; var SIGNALS = consts.SIGNALS; var EDDSA_SUPPORTED = consts.EDDSA_SUPPORTED; var CURVE25519_SUPPORTED = consts.CURVE25519_SUPPORTED; var BUGS = consts.BUGS; var BUGGY_IMPLS = consts.BUGGY_IMPLS; var BUGGY_IMPLS_LEN = BUGGY_IMPLS.length; var MODULE_VER = (__nccwpck_require__(6914)/* .version */ .rE); var I = 0; var IN_INIT = I++; var IN_GREETING = I++; var IN_HEADER = I++; var IN_PACKETBEFORE = I++; var IN_PACKET = I++; var IN_PACKETDATA = I++; var IN_PACKETDATAVERIFY = I++; var IN_PACKETDATAAFTER = I++; var OUT_INIT = I++; var OUT_READY = I++; var OUT_REKEYING = I++; var MAX_SEQNO = 4294967295; var MAX_PACKET_SIZE = 35000; var MAX_PACKETS_REKEYING = 50; var EXP_TYPE_HEADER = 0; var EXP_TYPE_LF = 1; var EXP_TYPE_BYTES = 2; // Waits until n bytes have been seen var Z_PARTIAL_FLUSH = zlib.Z_PARTIAL_FLUSH; var ZLIB_OPTS = { flush: Z_PARTIAL_FLUSH }; var RE_NULL = /\x00/g; var IDENT_PREFIX_BUFFER = Buffer.from('SSH-'); var EMPTY_BUFFER = Buffer.allocUnsafe(0); var HMAC_COMPUTE = Buffer.allocUnsafe(9); var PING_PACKET = Buffer.from([ MESSAGE.GLOBAL_REQUEST, // "keepalive@openssh.com" 0, 0, 0, 21, 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, 115, 104, 46, 99, 111, 109, // Request a reply 1 ]); var NEWKEYS_PACKET = Buffer.from([MESSAGE.NEWKEYS]); var USERAUTH_SUCCESS_PACKET = Buffer.from([MESSAGE.USERAUTH_SUCCESS]); var REQUEST_SUCCESS_PACKET = Buffer.from([MESSAGE.REQUEST_SUCCESS]); var REQUEST_FAILURE_PACKET = Buffer.from([MESSAGE.REQUEST_FAILURE]); var NO_TERMINAL_MODES_BUFFER = Buffer.from([TERMINAL_MODE.TTY_OP_END]); var KEXDH_GEX_REQ_PACKET = Buffer.from([ MESSAGE.KEXDH_GEX_REQUEST, // Minimal size in bits of an acceptable group 0, 0, 4, 0, // 1024, modp2 // Preferred size in bits of the group the server will send 0, 0, 16, 0, // 4096, modp16 // Maximal size in bits of an acceptable group 0, 0, 32, 0 // 8192, modp18 ]); function DEBUG_NOOP(msg) {} function SSH2Stream(cfg) { if (typeof cfg !== 'object' || cfg === null) cfg = {}; TransformStream.call(this, { highWaterMark: (typeof cfg.highWaterMark === 'number' ? cfg.highWaterMark : 32 * 1024) }); this._needContinue = false; this.bytesSent = this.bytesReceived = 0; this.debug = (typeof cfg.debug === 'function' ? cfg.debug : DEBUG_NOOP); this.server = (cfg.server === true); this.maxPacketSize = (typeof cfg.maxPacketSize === 'number' ? cfg.maxPacketSize : MAX_PACKET_SIZE); // Bitmap that indicates any bugs the remote side has. This is determined // by the reported software version. this.remoteBugs = 0; if (this.server) { // TODO: Remove when we support group exchange for server implementation this.remoteBugs = BUGS.BAD_DHGEX; } this.readable = true; var self = this; var hostKeys = cfg.hostKeys; if (this.server && (typeof hostKeys !== 'object' || hostKeys === null)) throw new Error('hostKeys must be an object keyed on host key type'); this.config = { // Server hostKeys: hostKeys, // All keys supported by server // Client/Server ident: 'SSH-2.0-' + (cfg.ident || ('ssh2js' + MODULE_VER + (this.server ? 'srv' : ''))), algorithms: { kex: ALGORITHMS.KEX, kexBuf: ALGORITHMS.KEX_BUF, serverHostKey: ALGORITHMS.SERVER_HOST_KEY, serverHostKeyBuf: ALGORITHMS.SERVER_HOST_KEY_BUF, cipher: ALGORITHMS.CIPHER, cipherBuf: ALGORITHMS.CIPHER_BUF, hmac: ALGORITHMS.HMAC, hmacBuf: ALGORITHMS.HMAC_BUF, compress: ALGORITHMS.COMPRESS, compressBuf: ALGORITHMS.COMPRESS_BUF } }; // RFC 4253 states the identification string must not contain NULL this.config.ident.replace(RE_NULL, ''); if (this.config.ident.length + 2 /* Account for "\r\n" */ > 255) throw new Error('ident too long'); if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { var algos = cfg.algorithms; if (Array.isArray(algos.kex) && algos.kex.length > 0) { this.config.algorithms.kex = algos.kex; if (!Buffer.isBuffer(algos.kexBuf)) algos.kexBuf = Buffer.from(algos.kex.join(','), 'ascii'); this.config.algorithms.kexBuf = algos.kexBuf; } if (Array.isArray(algos.serverHostKey) && algos.serverHostKey.length > 0) { this.config.algorithms.serverHostKey = algos.serverHostKey; if (!Buffer.isBuffer(algos.serverHostKeyBuf)) { algos.serverHostKeyBuf = Buffer.from(algos.serverHostKey.join(','), 'ascii'); } this.config.algorithms.serverHostKeyBuf = algos.serverHostKeyBuf; } if (Array.isArray(algos.cipher) && algos.cipher.length > 0) { this.config.algorithms.cipher = algos.cipher; if (!Buffer.isBuffer(algos.cipherBuf)) algos.cipherBuf = Buffer.from(algos.cipher.join(','), 'ascii'); this.config.algorithms.cipherBuf = algos.cipherBuf; } if (Array.isArray(algos.hmac) && algos.hmac.length > 0) { this.config.algorithms.hmac = algos.hmac; if (!Buffer.isBuffer(algos.hmacBuf)) algos.hmacBuf = Buffer.from(algos.hmac.join(','), 'ascii'); this.config.algorithms.hmacBuf = algos.hmacBuf; } if (Array.isArray(algos.compress) && algos.compress.length > 0) { this.config.algorithms.compress = algos.compress; if (!Buffer.isBuffer(algos.compressBuf)) algos.compressBuf = Buffer.from(algos.compress.join(','), 'ascii'); this.config.algorithms.compressBuf = algos.compressBuf; } } this.reset(true); // Common events this.on('end', function() { // Let GC collect any Buffers we were previously storing self.readable = false; self._state = undefined; self.reset(); self._state.outgoing.bufSeqno = undefined; }); this.on('DISCONNECT', function(reason, code, desc, lang) { onDISCONNECT(self, reason, code, desc, lang); }); this.on('KEXINIT', function(init, firstFollows) { onKEXINIT(self, init, firstFollows); }); this.on('NEWKEYS', function() { onNEWKEYS(self); }); if (this.server) { // Server-specific events this.on('KEXDH_INIT', function(e) { onKEXDH_INIT(self, e); }); } else { // Client-specific events this.on('KEXDH_REPLY', function(info) { onKEXDH_REPLY(self, info); }) .on('KEXDH_GEX_GROUP', function(prime, gen) { onKEXDH_GEX_GROUP(self, prime, gen); }); } if (this.server) { // Greeting displayed before the ssh identification string is sent, this is // usually ignored by most clients if (typeof cfg.greeting === 'string' && cfg.greeting.length) { if (cfg.greeting.slice(-2) === '\r\n') this.push(cfg.greeting); else this.push(cfg.greeting + '\r\n'); } // Banner shown after the handshake completes, but before user // authentication begins if (typeof cfg.banner === 'string' && cfg.banner.length) { if (cfg.banner.slice(-2) === '\r\n') this.banner = cfg.banner; else this.banner = cfg.banner + '\r\n'; } } this.debug('DEBUG: Local ident: ' + inspect(this.config.ident)); this.push(this.config.ident + '\r\n'); this._state.incoming.expectedPacket = 'KEXINIT'; } inherits(SSH2Stream, TransformStream); SSH2Stream.prototype.__read = TransformStream.prototype._read; SSH2Stream.prototype._read = function(n) { if (this._needContinue) { this._needContinue = false; this.emit('continue'); } return this.__read(n); }; SSH2Stream.prototype.__push = TransformStream.prototype.push; SSH2Stream.prototype.push = function(chunk, encoding) { var ret = this.__push(chunk, encoding); this._needContinue = (ret === false); return ret; }; SSH2Stream.prototype._cleanup = function(callback) { this.reset(); this.debug('DEBUG: Parser: Malformed packet'); callback && callback(new Error('Malformed packet')); }; SSH2Stream.prototype._transform = function(chunk, encoding, callback, decomp) { var skipDecrypt = false; var decryptAuthMode = false; var state = this._state; var instate = state.incoming; var outstate = state.outgoing; var expect = instate.expect; var decrypt = instate.decrypt; var decompress = instate.decompress; var chlen = chunk.length; var chleft = 0; var debug = this.debug; var self = this; var i = 0; var p = i; var blockLen; var buffer; var buf; var r; this.bytesReceived += chlen; while (true) { if (expect.type !== undefined) { if (i >= chlen) break; if (expect.type === EXP_TYPE_BYTES) { chleft = (chlen - i); var pktLeft = (expect.buf.length - expect.ptr); if (pktLeft <= chleft) { chunk.copy(expect.buf, expect.ptr, i, i + pktLeft); i += pktLeft; buffer = expect.buf; expect.buf = undefined; expect.ptr = 0; expect.type = undefined; } else { chunk.copy(expect.buf, expect.ptr, i); expect.ptr += chleft; i += chleft; } continue; } else if (expect.type === EXP_TYPE_HEADER) { i += instate.search.push(chunk); if (expect.type !== undefined) continue; } else if (expect.type === EXP_TYPE_LF) { if (++expect.ptr + 4 /* Account for "SSH-" */ > 255) { this.reset(); debug('DEBUG: Parser: Identification string exceeded 255 characters'); return callback(new Error('Max identification string size exceeded')); } if (chunk[i] === 0x0A) { expect.type = undefined; if (p < i) { if (expect.buf === undefined) expect.buf = chunk.toString('ascii', p, i); else expect.buf += chunk.toString('ascii', p, i); } buffer = expect.buf; expect.buf = undefined; ++i; } else { if (++i === chlen && p < i) { if (expect.buf === undefined) expect.buf = chunk.toString('ascii', p, i); else expect.buf += chunk.toString('ascii', p, i); } continue; } } } if (instate.status === IN_INIT) { if (!this.readable) return callback(); if (this.server) { // Retrieve what should be the start of the protocol version exchange if (!buffer) { debug('DEBUG: Parser: IN_INIT (waiting for identification begin)'); expectData(this, EXP_TYPE_BYTES, 4); } else { if (buffer[0] === 0x53 // S && buffer[1] === 0x53 // S && buffer[2] === 0x48 // H && buffer[3] === 0x2D) { // - instate.status = IN_GREETING; debug('DEBUG: Parser: IN_INIT (waiting for rest of identification)'); } else { this.reset(); debug('DEBUG: Parser: Bad identification start'); return callback(new Error('Bad identification start')); } } } else { debug('DEBUG: Parser: IN_INIT'); // Retrieve any bytes that may come before the protocol version exchange var ss = instate.search = new StreamSearch(IDENT_PREFIX_BUFFER); ss.on('info', function onInfo(matched, data, start, end) { if (data) { if (instate.greeting === undefined) instate.greeting = data.toString('binary', start, end); else instate.greeting += data.toString('binary', start, end); } if (matched) { expect.type = undefined; instate.search.removeListener('info', onInfo); } }); ss.maxMatches = 1; expectData(this, EXP_TYPE_HEADER); instate.status = IN_GREETING; } } else if (instate.status === IN_GREETING) { debug('DEBUG: Parser: IN_GREETING'); instate.search = undefined; // Retrieve the identification bytes after the "SSH-" header p = i; expectData(this, EXP_TYPE_LF); instate.status = IN_HEADER; } else if (instate.status === IN_HEADER) { debug('DEBUG: Parser: IN_HEADER'); if (buffer.charCodeAt(buffer.length - 1) === 13) buffer = buffer.slice(0, -1); var idxDash = buffer.indexOf('-'); var idxSpace = buffer.indexOf(' '); var header = { // RFC says greeting SHOULD be utf8 greeting: instate.greeting, identRaw: 'SSH-' + buffer, versions: { protocol: buffer.substr(0, idxDash), software: (idxSpace === -1 ? buffer.substring(idxDash + 1) : buffer.substring(idxDash + 1, idxSpace)) }, comments: (idxSpace > -1 ? buffer.substring(idxSpace + 1) : undefined) }; instate.greeting = undefined; if (header.versions.protocol !== '1.99' && header.versions.protocol !== '2.0') { this.reset(); debug('DEBUG: Parser: protocol version not supported: ' + header.versions.protocol); return callback(new Error('Protocol version not supported')); } else this.emit('header', header); if (instate.status === IN_INIT) { // We reset from an event handler, possibly due to an unsupported SSH // protocol version? return; } var identRaw = header.identRaw; var software = header.versions.software; this.debug('DEBUG: Remote ident: ' + inspect(identRaw)); for (var j = 0, rule; j < BUGGY_IMPLS_LEN; ++j) { rule = BUGGY_IMPLS[j]; if (typeof rule[0] === 'string') { if (software === rule[0]) this.remoteBugs |= rule[1]; } else if (rule[0].test(software)) this.remoteBugs |= rule[1]; } instate.identRaw = identRaw; // Adjust bytesReceived first otherwise it will have an incorrectly larger // total when we call back into this function after completing KEXINIT this.bytesReceived -= (chlen - i); KEXINIT(this, function() { if (i === chlen) callback(); else self._transform(chunk.slice(i), encoding, callback); }); instate.status = IN_PACKETBEFORE; return; } else if (instate.status === IN_PACKETBEFORE) { blockLen = (decrypt.instance ? decrypt.info.blockLen : 8); debug('DEBUG: Parser: IN_PACKETBEFORE (expecting ' + blockLen + ')'); // Wait for the right number of bytes so we can determine the incoming // packet length expectData(this, EXP_TYPE_BYTES, blockLen, decrypt.buf); instate.status = IN_PACKET; } else if (instate.status === IN_PACKET) { debug('DEBUG: Parser: IN_PACKET'); if (decrypt.instance) { decryptAuthMode = (decrypt.info.authLen > 0); if (!decryptAuthMode) buffer = decryptData(this, buffer); blockLen = decrypt.info.blockLen; } else { decryptAuthMode = false; blockLen = 8; } r = readInt(buffer, 0, this, callback); if (r === false) return; var hmacInfo = instate.hmac.info; var macSize; if (hmacInfo) macSize = hmacInfo.actualLen; else macSize = 0; var fullPacketLen = r + 4 + macSize; var maxPayloadLen = this.maxPacketSize; if (decompress.instance) { // Account for compressed payloads // This formula is taken from dropbear which derives it from zlib's // documentation. Explanation from dropbear: /* For exact details see http://www.zlib.net/zlib_tech.html * 5 bytes per 16kB block, plus 6 bytes for the stream. * We might allocate 5 unnecessary bytes here if it's an * exact multiple. */ maxPayloadLen += (((this.maxPacketSize / 16384) + 1) * 5 + 6); } if (r > maxPayloadLen // TODO: Change 16 to "MAX(16, decrypt.info.blockLen)" when/if SSH2 // adopts 512-bit ciphers || fullPacketLen < (16 + macSize) || ((r + (decryptAuthMode ? 0 : 4)) % blockLen) !== 0) { this.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); debug('DEBUG: Parser: Bad packet length (' + fullPacketLen + ')'); return callback(new Error('Bad packet length')); } instate.pktLen = r; var remainLen = instate.pktLen + 4 - blockLen; if (decryptAuthMode) { decrypt.instance.setAAD(buffer.slice(0, 4)); debug('DEBUG: Parser: pktLen:' + instate.pktLen + ',remainLen:' + remainLen); } else { instate.padLen = buffer[4]; debug('DEBUG: Parser: pktLen:' + instate.pktLen + ',padLen:' + instate.padLen + ',remainLen:' + remainLen); } if (remainLen > 0) { if (decryptAuthMode) instate.pktExtra = buffer.slice(4); else instate.pktExtra = buffer.slice(5); // Grab the rest of the packet expectData(this, EXP_TYPE_BYTES, remainLen); instate.status = IN_PACKETDATA; } else if (remainLen < 0) instate.status = IN_PACKETBEFORE; else { // Entire message fit into one block skipDecrypt = true; instate.status = IN_PACKETDATA; continue; } } else if (instate.status === IN_PACKETDATA) { debug('DEBUG: Parser: IN_PACKETDATA'); if (decrypt.instance) { decryptAuthMode = (decrypt.info.authLen > 0); if (!skipDecrypt) { if (!decryptAuthMode) buffer = decryptData(this, buffer); } else { skipDecrypt = false; } } else { decryptAuthMode = false; skipDecrypt = false; } var padStart = instate.pktLen - instate.padLen - 1; // TODO: Allocate a Buffer once that is slightly larger than maxPacketSize // (to accommodate for packet length field and MAC) and re-use that // instead if (instate.pktExtra) { buf = Buffer.allocUnsafe(instate.pktExtra.length + buffer.length); instate.pktExtra.copy(buf); buffer.copy(buf, instate.pktExtra.length); instate.payload = buf.slice(0, padStart); } else { // Entire message fit into one block if (decryptAuthMode) buf = buffer.slice(4); else buf = buffer.slice(5); instate.payload = buffer.slice(5, 5 + padStart); } if (instate.hmac.info !== undefined) { // Wait for hmac hash var inHMACSize = decrypt.info.authLen || instate.hmac.info.actualLen; debug('DEBUG: Parser: HMAC size:' + inHMACSize); expectData(this, EXP_TYPE_BYTES, inHMACSize, instate.hmac.buf); instate.status = IN_PACKETDATAVERIFY; instate.packet = buf; } else instate.status = IN_PACKETDATAAFTER; instate.pktExtra = undefined; buf = undefined; } else if (instate.status === IN_PACKETDATAVERIFY) { debug('DEBUG: Parser: IN_PACKETDATAVERIFY'); // Verify packet data integrity if (hmacVerify(this, buffer)) { debug('DEBUG: Parser: IN_PACKETDATAVERIFY (Valid HMAC)'); instate.status = IN_PACKETDATAAFTER; instate.packet = undefined; } else { this.reset(); debug('DEBUG: Parser: IN_PACKETDATAVERIFY (Invalid HMAC)'); return callback(new Error('Invalid HMAC')); } } else if (instate.status === IN_PACKETDATAAFTER) { if (decompress.instance) { if (!decomp) { debug('DEBUG: Parser: Decompressing'); decompress.instance.write(instate.payload); var decompBuf = []; var decompBufLen = 0; decompress.instance.on('readable', function() { var buf; while (buf = this.read()) { decompBuf.push(buf); decompBufLen += buf.length; } }).flush(Z_PARTIAL_FLUSH, function() { decompress.instance.removeAllListeners('readable'); if (decompBuf.length === 1) instate.payload = decompBuf[0]; else instate.payload = Buffer.concat(decompBuf, decompBufLen); decompBuf = null; var nextSlice; if (i === chlen) nextSlice = EMPTY_BUFFER; // Avoid slicing a zero-length buffer else nextSlice = chunk.slice(i); self._transform(nextSlice, encoding, callback, true); }); return; } else { // Make sure we reset this after this first time in the loop, // otherwise we could end up trying to interpret as-is another // compressed packet that is within the same chunk decomp = false; } } this.emit('packet'); var ptype = instate.payload[0]; if (debug !== DEBUG_NOOP) { var msgPacket = 'DEBUG: Parser: IN_PACKETDATAAFTER, packet: '; var authMethod = state.authsQueue[0]; var msgPktType = null; if (outstate.status === OUT_REKEYING && !(ptype <= 4 || (ptype >= 20 && ptype <= 49))) msgPacket += '(enqueued) '; if (ptype === MESSAGE.KEXDH_INIT) { switch (state.kex.type) { case 'group': msgPktType = 'KEXDH_INIT'; break; case 'groupex': msgPktType = 'KEXDH_GEX_REQUEST'; break; default: msgPktType = 'KEXECDH_INIT'; } } else if (ptype === MESSAGE.KEXDH_REPLY) { switch (state.kex.type) { case 'group': msgPktType = 'KEXDH_REPLY'; break; case 'groupex': msgPktType = 'KEXDH_GEX_GROUP'; break; default: msgPktType = 'KEXECDH_REPLY'; } } else if (ptype === MESSAGE.KEXDH_GEX_GROUP) { msgPktType = 'KEXDH_GEX_GROUP'; } else if (ptype === MESSAGE.KEXDH_GEX_REPLY) { msgPktType = 'KEXDH_GEX_REPLY'; } else if (ptype === 60) { if (authMethod === 'password') msgPktType = 'USERAUTH_PASSWD_CHANGEREQ'; else if (authMethod === 'keyboard-interactive') msgPktType = 'USERAUTH_INFO_REQUEST'; else if (authMethod === 'publickey') msgPktType = 'USERAUTH_PK_OK'; else msgPktType = 'UNKNOWN PACKET 60'; } else if (ptype === 61) { if (authMethod === 'keyboard-interactive') msgPktType = 'USERAUTH_INFO_RESPONSE'; else msgPktType = 'UNKNOWN PACKET 61'; } if (msgPktType === null) msgPktType = MESSAGE[ptype]; // Don't write debug output for messages we custom make in parsePacket() if (ptype !== MESSAGE.CHANNEL_OPEN && ptype !== MESSAGE.CHANNEL_REQUEST && ptype !== MESSAGE.CHANNEL_SUCCESS && ptype !== MESSAGE.CHANNEL_FAILURE && ptype !== MESSAGE.CHANNEL_EOF && ptype !== MESSAGE.CHANNEL_CLOSE && ptype !== MESSAGE.CHANNEL_DATA && ptype !== MESSAGE.CHANNEL_EXTENDED_DATA && ptype !== MESSAGE.CHANNEL_WINDOW_ADJUST && ptype !== MESSAGE.DISCONNECT && ptype !== MESSAGE.USERAUTH_REQUEST && ptype !== MESSAGE.GLOBAL_REQUEST) debug(msgPacket + msgPktType); } // Only parse packet if we are not re-keying or the packet is not a // transport layer packet needed for re-keying if (outstate.status === OUT_READY || ptype <= 4 || (ptype >= 20 && ptype <= 49)) { if (parsePacket(this, callback) === false) return; if (instate.status === IN_INIT) { // We were reset due to some error/disagreement ? return; } } else if (outstate.status === OUT_REKEYING) { if (instate.rekeyQueue.length === MAX_PACKETS_REKEYING) { debug('DEBUG: Parser: Max incoming re-key queue length reached'); this.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); return callback( new Error('Incoming re-key queue length limit reached') ); } // Make sure to record the sequence number in case we need it later on // when we drain the queue (e.g. unknown packet) var seqno = instate.seqno; if (++instate.seqno > MAX_SEQNO) instate.seqno = 0; instate.rekeyQueue.push([seqno, instate.payload]); } instate.status = IN_PACKETBEFORE; instate.payload = undefined; } if (buffer !== undefined) buffer = undefined; } callback(); }; SSH2Stream.prototype.reset = function(noend) { if (this._state) { var state = this._state; state.incoming.status = IN_INIT; state.outgoing.status = OUT_INIT; } else { this._state = { authsQueue: [], hostkeyFormat: undefined, kex: undefined, incoming: { status: IN_INIT, expectedPacket: undefined, search: undefined, greeting: undefined, seqno: 0, pktLen: undefined, padLen: undefined, pktExtra: undefined, payload: undefined, packet: undefined, kexinit: undefined, identRaw: undefined, rekeyQueue: [], ignoreNext: false, expect: { amount: undefined, type: undefined, ptr: 0, buf: undefined }, decrypt: { instance: false, info: undefined, iv: undefined, key: undefined, buf: undefined, type: undefined }, hmac: { info: undefined, key: undefined, buf: undefined, type: false }, decompress: { instance: false, type: false } }, outgoing: { status: OUT_INIT, seqno: 0, bufSeqno: Buffer.allocUnsafe(4), rekeyQueue: [], kexinit: undefined, kexsecret: undefined, pubkey: undefined, exchangeHash: undefined, sessionId: undefined, sentNEWKEYS: false, encrypt: { instance: false, info: undefined, iv: undefined, key: undefined, type: undefined }, hmac: { info: undefined, key: undefined, buf: undefined, type: false }, compress: { instance: false, type: false, queue: null } } }; } if (!noend) { if (this.readable) this.push(null); } }; // Common methods // Global SSH2Stream.prototype.disconnect = function(reason) { /* byte SSH_MSG_DISCONNECT uint32 reason code string description in ISO-10646 UTF-8 encoding string language tag */ var buf = Buffer.alloc(1 + 4 + 4 + 4); buf[0] = MESSAGE.DISCONNECT; if (DISCONNECT_REASON[reason] === undefined) reason = DISCONNECT_REASON.BY_APPLICATION; writeUInt32BE(buf, reason, 1); this.debug('DEBUG: Outgoing: Writing DISCONNECT (' + DISCONNECT_REASON[reason] + ')'); send(this, buf); this.reset(); return false; }; SSH2Stream.prototype.ping = function() { this.debug('DEBUG: Outgoing: Writing ping (GLOBAL_REQUEST: keepalive@openssh.com)'); return send(this, PING_PACKET); }; SSH2Stream.prototype.rekey = function() { var status = this._state.outgoing.status; if (status === OUT_REKEYING) throw new Error('A re-key is already in progress'); else if (status !== OUT_READY) throw new Error('Cannot re-key yet'); this.debug('DEBUG: Outgoing: Starting re-key'); return KEXINIT(this); }; // 'ssh-connection' service-specific SSH2Stream.prototype.requestSuccess = function(data) { var buf; if (Buffer.isBuffer(data)) { buf = Buffer.allocUnsafe(1 + data.length); buf[0] = MESSAGE.REQUEST_SUCCESS; data.copy(buf, 1); } else buf = REQUEST_SUCCESS_PACKET; this.debug('DEBUG: Outgoing: Writing REQUEST_SUCCESS'); return send(this, buf); }; SSH2Stream.prototype.requestFailure = function() { this.debug('DEBUG: Outgoing: Writing REQUEST_FAILURE'); return send(this, REQUEST_FAILURE_PACKET); }; SSH2Stream.prototype.channelSuccess = function(chan) { // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4); buf[0] = MESSAGE.CHANNEL_SUCCESS; writeUInt32BE(buf, chan, 1); this.debug('DEBUG: Outgoing: Writing CHANNEL_SUCCESS (' + chan + ')'); return send(this, buf); }; SSH2Stream.prototype.channelFailure = function(chan) { // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4); buf[0] = MESSAGE.CHANNEL_FAILURE; writeUInt32BE(buf, chan, 1); this.debug('DEBUG: Outgoing: Writing CHANNEL_FAILURE (' + chan + ')'); return send(this, buf); }; SSH2Stream.prototype.channelEOF = function(chan) { // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4); buf[0] = MESSAGE.CHANNEL_EOF; writeUInt32BE(buf, chan, 1); this.debug('DEBUG: Outgoing: Writing CHANNEL_EOF (' + chan + ')'); return send(this, buf); }; SSH2Stream.prototype.channelClose = function(chan) { // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4); buf[0] = MESSAGE.CHANNEL_CLOSE; writeUInt32BE(buf, chan, 1); this.debug('DEBUG: Outgoing: Writing CHANNEL_CLOSE (' + chan + ')'); return send(this, buf); }; SSH2Stream.prototype.channelWindowAdjust = function(chan, amount) { // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4 + 4); buf[0] = MESSAGE.CHANNEL_WINDOW_ADJUST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, amount, 5); this.debug('DEBUG: Outgoing: Writing CHANNEL_WINDOW_ADJUST (' + chan + ', ' + amount + ')'); return send(this, buf); }; SSH2Stream.prototype.channelData = function(chan, data) { var dataIsBuffer = Buffer.isBuffer(data); var dataLen = (dataIsBuffer ? data.length : Buffer.byteLength(data)); var buf = Buffer.allocUnsafe(1 + 4 + 4 + dataLen); buf[0] = MESSAGE.CHANNEL_DATA; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, dataLen, 5); if (dataIsBuffer) data.copy(buf, 9); else buf.write(data, 9, dataLen, 'utf8'); this.debug('DEBUG: Outgoing: Writing CHANNEL_DATA (' + chan + ')'); return send(this, buf); }; SSH2Stream.prototype.channelExtData = function(chan, data, type) { var dataIsBuffer = Buffer.isBuffer(data); var dataLen = (dataIsBuffer ? data.length : Buffer.byteLength(data)); var buf = Buffer.allocUnsafe(1 + 4 + 4 + 4 + dataLen); buf[0] = MESSAGE.CHANNEL_EXTENDED_DATA; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, type, 5); writeUInt32BE(buf, dataLen, 9); if (dataIsBuffer) data.copy(buf, 13); else buf.write(data, 13, dataLen, 'utf8'); this.debug('DEBUG: Outgoing: Writing CHANNEL_EXTENDED_DATA (' + chan + ')'); return send(this, buf); }; SSH2Stream.prototype.channelOpenConfirm = function(remoteChan, localChan, initWindow, maxPacket) { var buf = Buffer.allocUnsafe(1 + 4 + 4 + 4 + 4); buf[0] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; writeUInt32BE(buf, remoteChan, 1); writeUInt32BE(buf, localChan, 5); writeUInt32BE(buf, initWindow, 9); writeUInt32BE(buf, maxPacket, 13); this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN_CONFIRMATION (r:' + remoteChan + ', l:' + localChan + ')'); return send(this, buf); }; SSH2Stream.prototype.channelOpenFail = function(remoteChan, reason, desc, lang) { if (typeof desc !== 'string') desc = ''; if (typeof lang !== 'string') lang = ''; var descLen = Buffer.byteLength(desc); var langLen = Buffer.byteLength(lang); var p = 9; var buf = Buffer.allocUnsafe(1 + 4 + 4 + 4 + descLen + 4 + langLen); buf[0] = MESSAGE.CHANNEL_OPEN_FAILURE; writeUInt32BE(buf, remoteChan, 1); writeUInt32BE(buf, reason, 5); writeUInt32BE(buf, descLen, p); p += 4; if (descLen) { buf.write(desc, p, descLen, 'utf8'); p += descLen; } writeUInt32BE(buf, langLen, p); if (langLen) buf.write(lang, p += 4, langLen, 'ascii'); this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN_FAILURE (' + remoteChan + ')'); return send(this, buf); }; // Client-specific methods // Global SSH2Stream.prototype.service = function(svcName) { if (this.server) throw new Error('Client-only method called in server mode'); var svcNameLen = Buffer.byteLength(svcName); var buf = Buffer.allocUnsafe(1 + 4 + svcNameLen); buf[0] = MESSAGE.SERVICE_REQUEST; writeUInt32BE(buf, svcNameLen, 1); buf.write(svcName, 5, svcNameLen, 'ascii'); this.debug('DEBUG: Outgoing: Writing SERVICE_REQUEST (' + svcName + ')'); return send(this, buf); }; // 'ssh-connection' service-specific SSH2Stream.prototype.tcpipForward = function(bindAddr, bindPort, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); var addrlen = Buffer.byteLength(bindAddr); var buf = Buffer.allocUnsafe(1 + 4 + 13 + 1 + 4 + addrlen + 4); buf[0] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(buf, 13, 1); buf.write('tcpip-forward', 5, 13, 'ascii'); buf[18] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(buf, addrlen, 19); buf.write(bindAddr, 23, addrlen, 'ascii'); writeUInt32BE(buf, bindPort, 23 + addrlen); this.debug('DEBUG: Outgoing: Writing GLOBAL_REQUEST (tcpip-forward)'); return send(this, buf); }; SSH2Stream.prototype.cancelTcpipForward = function(bindAddr, bindPort, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); var addrlen = Buffer.byteLength(bindAddr); var buf = Buffer.allocUnsafe(1 + 4 + 20 + 1 + 4 + addrlen + 4); buf[0] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(buf, 20, 1); buf.write('cancel-tcpip-forward', 5, 20, 'ascii'); buf[25] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(buf, addrlen, 26); buf.write(bindAddr, 30, addrlen, 'ascii'); writeUInt32BE(buf, bindPort, 30 + addrlen); this.debug('DEBUG: Outgoing: Writing GLOBAL_REQUEST (cancel-tcpip-forward)'); return send(this, buf); }; SSH2Stream.prototype.openssh_streamLocalForward = function(socketPath, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); var pathlen = Buffer.byteLength(socketPath); var buf = Buffer.allocUnsafe(1 + 4 + 31 + 1 + 4 + pathlen); buf[0] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(buf, 31, 1); buf.write('streamlocal-forward@openssh.com', 5, 31, 'ascii'); buf[36] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(buf, pathlen, 37); buf.write(socketPath, 41, pathlen, 'utf8'); this.debug('DEBUG: Outgoing: Writing GLOBAL_REQUEST (streamlocal-forward@openssh.com)'); return send(this, buf); }; SSH2Stream.prototype.openssh_cancelStreamLocalForward = function(socketPath, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); var pathlen = Buffer.byteLength(socketPath); var buf = Buffer.allocUnsafe(1 + 4 + 38 + 1 + 4 + pathlen); buf[0] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(buf, 38, 1); buf.write('cancel-streamlocal-forward@openssh.com', 5, 38, 'ascii'); buf[43] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(buf, pathlen, 44); buf.write(socketPath, 48, pathlen, 'utf8'); this.debug('DEBUG: Outgoing: Writing GLOBAL_REQUEST (cancel-streamlocal-forward@openssh.com)'); return send(this, buf); }; SSH2Stream.prototype.directTcpip = function(chan, initWindow, maxPacket, cfg) { if (this.server) throw new Error('Client-only method called in server mode'); var srclen = Buffer.byteLength(cfg.srcIP); var dstlen = Buffer.byteLength(cfg.dstIP); var p = 29; var buf = Buffer.allocUnsafe(1 + 4 + 12 + 4 + 4 + 4 + 4 + srclen + 4 + 4 + dstlen + 4); buf[0] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(buf, 12, 1); buf.write('direct-tcpip', 5, 12, 'ascii'); writeUInt32BE(buf, chan, 17); writeUInt32BE(buf, initWindow, 21); writeUInt32BE(buf, maxPacket, 25); writeUInt32BE(buf, dstlen, p); buf.write(cfg.dstIP, p += 4, dstlen, 'ascii'); writeUInt32BE(buf, cfg.dstPort, p += dstlen); writeUInt32BE(buf, srclen, p += 4); buf.write(cfg.srcIP, p += 4, srclen, 'ascii'); writeUInt32BE(buf, cfg.srcPort, p += srclen); this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN (' + chan + ', direct-tcpip)'); return send(this, buf); }; SSH2Stream.prototype.openssh_directStreamLocal = function(chan, initWindow, maxPacket, cfg) { if (this.server) throw new Error('Client-only method called in server mode'); var pathlen = Buffer.byteLength(cfg.socketPath); var p = 47; var buf = Buffer.allocUnsafe(1 + 4 + 30 + 4 + 4 + 4 + 4 + pathlen + 4 + 4); buf[0] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(buf, 30, 1); buf.write('direct-streamlocal@openssh.com', 5, 30, 'ascii'); writeUInt32BE(buf, chan, 35); writeUInt32BE(buf, initWindow, 39); writeUInt32BE(buf, maxPacket, 43); writeUInt32BE(buf, pathlen, p); buf.write(cfg.socketPath, p += 4, pathlen, 'utf8'); // reserved fields (string and uint32) buf.fill(0, buf.length - 8); this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN (' + chan + ', direct-streamlocal@openssh.com)'); return send(this, buf); }; SSH2Stream.prototype.openssh_noMoreSessions = function(wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); var buf = Buffer.allocUnsafe(1 + 4 + 28 + 1); buf[0] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(buf, 28, 1); buf.write('no-more-sessions@openssh.com', 5, 28, 'ascii'); buf[33] = (wantReply === undefined || wantReply === true ? 1 : 0); this.debug('DEBUG: Outgoing: Writing GLOBAL_REQUEST (no-more-sessions@openssh.com)'); return send(this, buf); }; SSH2Stream.prototype.session = function(chan, initWindow, maxPacket) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4 + 7 + 4 + 4 + 4); buf[0] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(buf, 7, 1); buf.write('session', 5, 7, 'ascii'); writeUInt32BE(buf, chan, 12); writeUInt32BE(buf, initWindow, 16); writeUInt32BE(buf, maxPacket, 20); this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN (' + chan + ', session)'); return send(this, buf); }; SSH2Stream.prototype.windowChange = function(chan, rows, cols, height, width) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 13, 5); buf.write('window-change', 9, 13, 'ascii'); buf[22] = 0; writeUInt32BE(buf, cols, 23); writeUInt32BE(buf, rows, 27); writeUInt32BE(buf, width, 31); writeUInt32BE(buf, height, 35); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', window-change)'); return send(this, buf); }; SSH2Stream.prototype.pty = function(chan, rows, cols, height, width, term, modes, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space if (!term || !term.length) term = 'vt100'; if (modes && !Buffer.isBuffer(modes) && !Array.isArray(modes) && typeof modes === 'object') modes = modesToBytes(modes); if (!modes || !modes.length) modes = NO_TERMINAL_MODES_BUFFER; var termLen = term.length; var modesLen = modes.length; var p = 21; var buf = Buffer.allocUnsafe(1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 7, 5); buf.write('pty-req', 9, 7, 'ascii'); buf[16] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(buf, termLen, 17); buf.write(term, 21, termLen, 'utf8'); writeUInt32BE(buf, cols, p += termLen); writeUInt32BE(buf, rows, p += 4); writeUInt32BE(buf, width, p += 4); writeUInt32BE(buf, height, p += 4); writeUInt32BE(buf, modesLen, p += 4); p += 4; if (Array.isArray(modes)) { for (var i = 0; i < modesLen; ++i) buf[p++] = modes[i]; } else if (Buffer.isBuffer(modes)) { modes.copy(buf, p); } this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', pty-req)'); return send(this, buf); }; SSH2Stream.prototype.shell = function(chan, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4 + 4 + 5 + 1); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 5, 5); buf.write('shell', 9, 5, 'ascii'); buf[14] = (wantReply === undefined || wantReply === true ? 1 : 0); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', shell)'); return send(this, buf); }; SSH2Stream.prototype.exec = function(chan, cmd, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space var cmdlen = (Buffer.isBuffer(cmd) ? cmd.length : Buffer.byteLength(cmd)); var buf = Buffer.allocUnsafe(1 + 4 + 4 + 4 + 1 + 4 + cmdlen); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 4, 5); buf.write('exec', 9, 4, 'ascii'); buf[13] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(buf, cmdlen, 14); if (Buffer.isBuffer(cmd)) cmd.copy(buf, 18); else buf.write(cmd, 18, cmdlen, 'utf8'); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', exec)'); return send(this, buf); }; SSH2Stream.prototype.signal = function(chan, signal) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space signal = signal.toUpperCase(); if (signal.slice(0, 3) === 'SIG') signal = signal.substring(3); if (SIGNALS.indexOf(signal) === -1) throw new Error('Invalid signal: ' + signal); var signalLen = signal.length; var buf = Buffer.allocUnsafe(1 + 4 + 4 + 6 + 1 + 4 + signalLen); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 6, 5); buf.write('signal', 9, 6, 'ascii'); buf[15] = 0; writeUInt32BE(buf, signalLen, 16); buf.write(signal, 20, signalLen, 'ascii'); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', signal)'); return send(this, buf); }; SSH2Stream.prototype.env = function(chan, key, val, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space var keyLen = Buffer.byteLength(key); var valLen = (Buffer.isBuffer(val) ? val.length : Buffer.byteLength(val)); var buf = Buffer.allocUnsafe(1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 3, 5); buf.write('env', 9, 3, 'ascii'); buf[12] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(buf, keyLen, 13); buf.write(key, 17, keyLen, 'ascii'); writeUInt32BE(buf, valLen, 17 + keyLen); if (Buffer.isBuffer(val)) val.copy(buf, 17 + keyLen + 4); else buf.write(val, 17 + keyLen + 4, valLen, 'utf8'); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', env)'); return send(this, buf); }; SSH2Stream.prototype.x11Forward = function(chan, cfg, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space var protolen = Buffer.byteLength(cfg.protocol); var cookielen = Buffer.byteLength(cfg.cookie); var buf = Buffer.allocUnsafe(1 + 4 + 4 + 7 + 1 + 1 + 4 + protolen + 4 + cookielen + 4); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 7, 5); buf.write('x11-req', 9, 7, 'ascii'); buf[16] = (wantReply === undefined || wantReply === true ? 1 : 0); buf[17] = (cfg.single ? 1 : 0); writeUInt32BE(buf, protolen, 18); var bp = 22; if (Buffer.isBuffer(cfg.protocol)) cfg.protocol.copy(buf, bp); else buf.write(cfg.protocol, bp, protolen, 'utf8'); bp += protolen; writeUInt32BE(buf, cookielen, bp); bp += 4; if (Buffer.isBuffer(cfg.cookie)) cfg.cookie.copy(buf, bp); else buf.write(cfg.cookie, bp, cookielen, 'binary'); bp += cookielen; writeUInt32BE(buf, (cfg.screen || 0), bp); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', x11-req)'); return send(this, buf); }; SSH2Stream.prototype.subsystem = function(chan, name, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space var nameLen = Buffer.byteLength(name); var buf = Buffer.allocUnsafe(1 + 4 + 4 + 9 + 1 + 4 + nameLen); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 9, 5); buf.write('subsystem', 9, 9, 'ascii'); buf[18] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(buf, nameLen, 19); buf.write(name, 23, nameLen, 'ascii'); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', subsystem: ' + name + ')'); return send(this, buf); }; SSH2Stream.prototype.openssh_agentForward = function(chan, wantReply) { if (this.server) throw new Error('Client-only method called in server mode'); // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4 + 4 + 26 + 1); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 26, 5); buf.write('auth-agent-req@openssh.com', 9, 26, 'ascii'); buf[35] = (wantReply === undefined || wantReply === true ? 1 : 0); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', auth-agent-req@openssh.com)'); return send(this, buf); }; // 'ssh-userauth' service-specific SSH2Stream.prototype.authPassword = function(username, password) { if (this.server) throw new Error('Client-only method called in server mode'); var userLen = Buffer.byteLength(username); var passLen = Buffer.byteLength(password); var p = 0; var buf = Buffer.allocUnsafe(1 + 4 + userLen + 4 + 14 // "ssh-connection" + 4 + 8 // "password" + 1 + 4 + passLen); buf[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(buf, userLen, ++p); buf.write(username, p += 4, userLen, 'utf8'); writeUInt32BE(buf, 14, p += userLen); buf.write('ssh-connection', p += 4, 14, 'ascii'); writeUInt32BE(buf, 8, p += 14); buf.write('password', p += 4, 8, 'ascii'); buf[p += 8] = 0; writeUInt32BE(buf, passLen, ++p); buf.write(password, p += 4, passLen, 'utf8'); this._state.authsQueue.push('password'); this.debug('DEBUG: Outgoing: Writing USERAUTH_REQUEST (password)'); return send(this, buf); }; SSH2Stream.prototype.authPK = function(username, pubKey, cbSign) { if (this.server) throw new Error('Client-only method called in server mode'); var self = this; var outstate = this._state.outgoing; var keyType; if (typeof pubKey.getPublicSSH === 'function') { keyType = pubKey.type; pubKey = pubKey.getPublicSSH(); } else { keyType = pubKey.toString('ascii', 4, 4 + readUInt32BE(pubKey, 0)); } var userLen = Buffer.byteLength(username); var algoLen = Buffer.byteLength(keyType); var pubKeyLen = pubKey.length; var sesLen = outstate.sessionId.length; var p = 0; var buf = Buffer.allocUnsafe((cbSign ? 4 + sesLen : 0) + 1 + 4 + userLen + 4 + 14 // "ssh-connection" + 4 + 9 // "publickey" + 1 + 4 + algoLen + 4 + pubKeyLen ); if (cbSign) { writeUInt32BE(buf, sesLen, p); outstate.sessionId.copy(buf, p += 4); buf[p += sesLen] = MESSAGE.USERAUTH_REQUEST; } else { buf[p] = MESSAGE.USERAUTH_REQUEST; } writeUInt32BE(buf, userLen, ++p); buf.write(username, p += 4, userLen, 'utf8'); writeUInt32BE(buf, 14, p += userLen); buf.write('ssh-connection', p += 4, 14, 'ascii'); writeUInt32BE(buf, 9, p += 14); buf.write('publickey', p += 4, 9, 'ascii'); buf[p += 9] = (cbSign ? 1 : 0); writeUInt32BE(buf, algoLen, ++p); buf.write(keyType, p += 4, algoLen, 'ascii'); writeUInt32BE(buf, pubKeyLen, p += algoLen); pubKey.copy(buf, p += 4); if (!cbSign) { this._state.authsQueue.push('publickey'); this.debug('DEBUG: Outgoing: Writing USERAUTH_REQUEST (publickey -- check)'); return send(this, buf); } cbSign(buf, function(signature) { signature = convertSignature(signature, keyType); if (signature === false) throw new Error('Error while converting handshake signature'); var sigLen = signature.length; var sigbuf = Buffer.allocUnsafe(1 + 4 + userLen + 4 + 14 // "ssh-connection" + 4 + 9 // "publickey" + 1 + 4 + algoLen + 4 + pubKeyLen + 4 // 4 + algoLen + 4 + sigLen + 4 + algoLen + 4 + sigLen); p = 0; sigbuf[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(sigbuf, userLen, ++p); sigbuf.write(username, p += 4, userLen, 'utf8'); writeUInt32BE(sigbuf, 14, p += userLen); sigbuf.write('ssh-connection', p += 4, 14, 'ascii'); writeUInt32BE(sigbuf, 9, p += 14); sigbuf.write('publickey', p += 4, 9, 'ascii'); sigbuf[p += 9] = 1; writeUInt32BE(sigbuf, algoLen, ++p); sigbuf.write(keyType, p += 4, algoLen, 'ascii'); writeUInt32BE(sigbuf, pubKeyLen, p += algoLen); pubKey.copy(sigbuf, p += 4); writeUInt32BE(sigbuf, 4 + algoLen + 4 + sigLen, p += pubKeyLen); writeUInt32BE(sigbuf, algoLen, p += 4); sigbuf.write(keyType, p += 4, algoLen, 'ascii'); writeUInt32BE(sigbuf, sigLen, p += algoLen); signature.copy(sigbuf, p += 4); // Servers shouldn't send packet type 60 in response to signed publickey // attempts, but if they do, interpret as type 60. self._state.authsQueue.push('publickey'); self.debug('DEBUG: Outgoing: Writing USERAUTH_REQUEST (publickey)'); return send(self, sigbuf); }); return true; }; SSH2Stream.prototype.authHostbased = function(username, pubKey, hostname, userlocal, cbSign) { // TODO: Make DRY by sharing similar code with authPK() if (this.server) throw new Error('Client-only method called in server mode'); var self = this; var outstate = this._state.outgoing; var keyType; if (typeof pubKey.getPublicSSH === 'function') { keyType = pubKey.type; pubKey = pubKey.getPublicSSH(); } else { keyType = pubKey.toString('ascii', 4, 4 + readUInt32BE(pubKey, 0)); } var userLen = Buffer.byteLength(username); var algoLen = Buffer.byteLength(keyType); var pubKeyLen = pubKey.length; var sesLen = outstate.sessionId.length; var hostnameLen = Buffer.byteLength(hostname); var userlocalLen = Buffer.byteLength(userlocal); var p = 0; var buf = Buffer.allocUnsafe(4 + sesLen + 1 + 4 + userLen + 4 + 14 // "ssh-connection" + 4 + 9 // "hostbased" + 4 + algoLen + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen ); writeUInt32BE(buf, sesLen, p); outstate.sessionId.copy(buf, p += 4); buf[p += sesLen] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(buf, userLen, ++p); buf.write(username, p += 4, userLen, 'utf8'); writeUInt32BE(buf, 14, p += userLen); buf.write('ssh-connection', p += 4, 14, 'ascii'); writeUInt32BE(buf, 9, p += 14); buf.write('hostbased', p += 4, 9, 'ascii'); writeUInt32BE(buf, algoLen, p += 9); buf.write(keyType, p += 4, algoLen, 'ascii'); writeUInt32BE(buf, pubKeyLen, p += algoLen); pubKey.copy(buf, p += 4); writeUInt32BE(buf, hostnameLen, p += pubKeyLen); buf.write(hostname, p += 4, hostnameLen, 'ascii'); writeUInt32BE(buf, userlocalLen, p += hostnameLen); buf.write(userlocal, p += 4, userlocalLen, 'utf8'); cbSign(buf, function(signature) { signature = convertSignature(signature, keyType); if (signature === false) throw new Error('Error while converting handshake signature'); var sigLen = signature.length; var sigbuf = Buffer.allocUnsafe((buf.length - sesLen) + sigLen); buf.copy(sigbuf, 0, 4 + sesLen); writeUInt32BE(sigbuf, sigLen, sigbuf.length - sigLen - 4); signature.copy(sigbuf, sigbuf.length - sigLen); self._state.authsQueue.push('hostbased'); self.debug('DEBUG: Outgoing: Writing USERAUTH_REQUEST (hostbased)'); return send(self, sigbuf); }); return true; }; SSH2Stream.prototype.authKeyboard = function(username) { if (this.server) throw new Error('Client-only method called in server mode'); var userLen = Buffer.byteLength(username); var p = 0; var buf = Buffer.allocUnsafe(1 + 4 + userLen + 4 + 14 // "ssh-connection" + 4 + 20 // "keyboard-interactive" + 4 // no language set + 4 // no submethods ); buf[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(buf, userLen, ++p); buf.write(username, p += 4, userLen, 'utf8'); writeUInt32BE(buf, 14, p += userLen); buf.write('ssh-connection', p += 4, 14, 'ascii'); writeUInt32BE(buf, 20, p += 14); buf.write('keyboard-interactive', p += 4, 20, 'ascii'); writeUInt32BE(buf, 0, p += 20); writeUInt32BE(buf, 0, p += 4); this._state.authsQueue.push('keyboard-interactive'); this.debug('DEBUG: Outgoing: Writing USERAUTH_REQUEST (keyboard-interactive)'); return send(this, buf); }; SSH2Stream.prototype.authNone = function(username) { if (this.server) throw new Error('Client-only method called in server mode'); var userLen = Buffer.byteLength(username); var p = 0; var buf = Buffer.allocUnsafe(1 + 4 + userLen + 4 + 14 // "ssh-connection" + 4 + 4 // "none" ); buf[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(buf, userLen, ++p); buf.write(username, p += 4, userLen, 'utf8'); writeUInt32BE(buf, 14, p += userLen); buf.write('ssh-connection', p += 4, 14, 'ascii'); writeUInt32BE(buf, 4, p += 14); buf.write('none', p += 4, 4, 'ascii'); this._state.authsQueue.push('none'); this.debug('DEBUG: Outgoing: Writing USERAUTH_REQUEST (none)'); return send(this, buf); }; SSH2Stream.prototype.authInfoRes = function(responses) { if (this.server) throw new Error('Client-only method called in server mode'); var responsesLen = 0; var p = 0; var resLen; var len; var i; if (responses) { for (i = 0, len = responses.length; i < len; ++i) responsesLen += 4 + Buffer.byteLength(responses[i]); } var buf = Buffer.allocUnsafe(1 + 4 + responsesLen); buf[p++] = MESSAGE.USERAUTH_INFO_RESPONSE; writeUInt32BE(buf, responses ? responses.length : 0, p); if (responses) { p += 4; for (i = 0, len = responses.length; i < len; ++i) { resLen = Buffer.byteLength(responses[i]); writeUInt32BE(buf, resLen, p); p += 4; if (resLen) { buf.write(responses[i], p, resLen, 'utf8'); p += resLen; } } } this.debug('DEBUG: Outgoing: Writing USERAUTH_INFO_RESPONSE'); return send(this, buf); }; // Server-specific methods // Global SSH2Stream.prototype.serviceAccept = function(svcName) { if (!this.server) throw new Error('Server-only method called in client mode'); var svcNameLen = svcName.length; var buf = Buffer.allocUnsafe(1 + 4 + svcNameLen); buf[0] = MESSAGE.SERVICE_ACCEPT; writeUInt32BE(buf, svcNameLen, 1); buf.write(svcName, 5, svcNameLen, 'ascii'); this.debug('DEBUG: Outgoing: Writing SERVICE_ACCEPT (' + svcName + ')'); send(this, buf); if (this.server && this.banner && svcName === 'ssh-userauth') { /* byte SSH_MSG_USERAUTH_BANNER string message in ISO-10646 UTF-8 encoding string language tag */ var bannerLen = Buffer.byteLength(this.banner); var packetLen = 1 + 4 + bannerLen + 4; var packet = Buffer.allocUnsafe(packetLen); packet[0] = MESSAGE.USERAUTH_BANNER; writeUInt32BE(packet, bannerLen, 1); packet.write(this.banner, 5, bannerLen, 'utf8'); packet.fill(0, packetLen - 4); // Empty language tag this.debug('DEBUG: Outgoing: Writing USERAUTH_BANNER'); send(this, packet); this.banner = undefined; // Prevent banner from being displayed again } }; // 'ssh-connection' service-specific SSH2Stream.prototype.forwardedTcpip = function(chan, initWindow, maxPacket, cfg) { if (!this.server) throw new Error('Server-only method called in client mode'); var boundAddrLen = Buffer.byteLength(cfg.boundAddr); var remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); var p = 36 + boundAddrLen; var buf = Buffer.allocUnsafe(1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4); buf[0] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(buf, 15, 1); buf.write('forwarded-tcpip', 5, 15, 'ascii'); writeUInt32BE(buf, chan, 20); writeUInt32BE(buf, initWindow, 24); writeUInt32BE(buf, maxPacket, 28); writeUInt32BE(buf, boundAddrLen, 32); buf.write(cfg.boundAddr, 36, boundAddrLen, 'ascii'); writeUInt32BE(buf, cfg.boundPort, p); writeUInt32BE(buf, remoteAddrLen, p += 4); buf.write(cfg.remoteAddr, p += 4, remoteAddrLen, 'ascii'); writeUInt32BE(buf, cfg.remotePort, p += remoteAddrLen); this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN (' + chan + ', forwarded-tcpip)'); return send(this, buf); }; SSH2Stream.prototype.x11 = function(chan, initWindow, maxPacket, cfg) { if (!this.server) throw new Error('Server-only method called in client mode'); var addrLen = Buffer.byteLength(cfg.originAddr); var p = 24 + addrLen; var buf = Buffer.allocUnsafe(1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4); buf[0] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(buf, 3, 1); buf.write('x11', 5, 3, 'ascii'); writeUInt32BE(buf, chan, 8); writeUInt32BE(buf, initWindow, 12); writeUInt32BE(buf, maxPacket, 16); writeUInt32BE(buf, addrLen, 20); buf.write(cfg.originAddr, 24, addrLen, 'ascii'); writeUInt32BE(buf, cfg.originPort, p); this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN (' + chan + ', x11)'); return send(this, buf); }; SSH2Stream.prototype.openssh_authAgent = function(chan, initWindow, maxPacket) { if (!this.server) throw new Error('Server-only method called in client mode'); var buf = Buffer.allocUnsafe(1 + 4 + 22 + 4 + 4 + 4); buf[0] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(buf, 22, 1); buf.write('auth-agent@openssh.com', 5, 22, 'ascii'); writeUInt32BE(buf, chan, 27); writeUInt32BE(buf, initWindow, 31); writeUInt32BE(buf, maxPacket, 35); this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN (' + chan + ', auth-agent@openssh.com)'); return send(this, buf); }; SSH2Stream.prototype.openssh_forwardedStreamLocal = function(chan, initWindow, maxPacket, cfg) { if (!this.server) throw new Error('Server-only method called in client mode'); var pathlen = Buffer.byteLength(cfg.socketPath); var buf = Buffer.allocUnsafe(1 + 4 + 33 + 4 + 4 + 4 + 4 + pathlen + 4); buf[0] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(buf, 33, 1); buf.write('forwarded-streamlocal@openssh.com', 5, 33, 'ascii'); writeUInt32BE(buf, chan, 38); writeUInt32BE(buf, initWindow, 42); writeUInt32BE(buf, maxPacket, 46); writeUInt32BE(buf, pathlen, 50); buf.write(cfg.socketPath, 54, pathlen, 'utf8'); writeUInt32BE(buf, 0, 54 + pathlen); this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN (' + chan + ', forwarded-streamlocal@openssh.com)'); return send(this, buf); }; SSH2Stream.prototype.exitStatus = function(chan, status) { if (!this.server) throw new Error('Server-only method called in client mode'); // Does not consume window space var buf = Buffer.allocUnsafe(1 + 4 + 4 + 11 + 1 + 4); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 11, 5); buf.write('exit-status', 9, 11, 'ascii'); buf[20] = 0; writeUInt32BE(buf, status, 21); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', exit-status)'); return send(this, buf); }; SSH2Stream.prototype.exitSignal = function(chan, name, coreDumped, msg) { if (!this.server) throw new Error('Server-only method called in client mode'); // Does not consume window space var nameLen = Buffer.byteLength(name); var msgLen = (msg ? Buffer.byteLength(msg) : 0); var p = 25 + nameLen; var buf = Buffer.allocUnsafe(1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4); buf[0] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(buf, chan, 1); writeUInt32BE(buf, 11, 5); buf.write('exit-signal', 9, 11, 'ascii'); buf[20] = 0; writeUInt32BE(buf, nameLen, 21); buf.write(name, 25, nameLen, 'utf8'); buf[p++] = (coreDumped ? 1 : 0); writeUInt32BE(buf, msgLen, p); p += 4; if (msgLen) { buf.write(msg, p, msgLen, 'utf8'); p += msgLen; } writeUInt32BE(buf, 0, p); this.debug('DEBUG: Outgoing: Writing CHANNEL_REQUEST (' + chan + ', exit-signal)'); return send(this, buf); }; // 'ssh-userauth' service-specific SSH2Stream.prototype.authFailure = function(authMethods, isPartial) { if (!this.server) throw new Error('Server-only method called in client mode'); var authsQueue = this._state.authsQueue; if (!authsQueue.length) throw new Error('No auth in progress'); var methods; if (typeof authMethods === 'boolean') { isPartial = authMethods; authMethods = undefined; } if (authMethods) { methods = []; for (var i = 0, len = authMethods.length; i < len; ++i) { if (authMethods[i].toLowerCase() === 'none') continue; methods.push(authMethods[i]); } methods = methods.join(','); } else methods = ''; var methodsLen = methods.length; var buf = Buffer.allocUnsafe(1 + 4 + methodsLen + 1); buf[0] = MESSAGE.USERAUTH_FAILURE; writeUInt32BE(buf, methodsLen, 1); buf.write(methods, 5, methodsLen, 'ascii'); buf[5 + methodsLen] = (isPartial === true ? 1 : 0); this._state.authsQueue.shift(); this.debug('DEBUG: Outgoing: Writing USERAUTH_FAILURE'); return send(this, buf); }; SSH2Stream.prototype.authSuccess = function() { if (!this.server) throw new Error('Server-only method called in client mode'); var authsQueue = this._state.authsQueue; if (!authsQueue.length) throw new Error('No auth in progress'); var state = this._state; var outstate = state.outgoing; var instate = state.incoming; state.authsQueue.shift(); this.debug('DEBUG: Outgoing: Writing USERAUTH_SUCCESS'); var ret = send(this, USERAUTH_SUCCESS_PACKET); if (outstate.compress.type === 'zlib@openssh.com') { outstate.compress.instance = zlib.createDeflate(ZLIB_OPTS); outstate.compress.queue = []; } if (instate.decompress.type === 'zlib@openssh.com') instate.decompress.instance = zlib.createInflate(ZLIB_OPTS); return ret; }; SSH2Stream.prototype.authPKOK = function(keyAlgo, key) { if (!this.server) throw new Error('Server-only method called in client mode'); var authsQueue = this._state.authsQueue; if (!authsQueue.length || authsQueue[0] !== 'publickey') throw new Error('"publickey" auth not in progress'); var keyAlgoLen = keyAlgo.length; var keyLen = key.length; var buf = Buffer.allocUnsafe(1 + 4 + keyAlgoLen + 4 + keyLen); buf[0] = MESSAGE.USERAUTH_PK_OK; writeUInt32BE(buf, keyAlgoLen, 1); buf.write(keyAlgo, 5, keyAlgoLen, 'ascii'); writeUInt32BE(buf, keyLen, 5 + keyAlgoLen); key.copy(buf, 5 + keyAlgoLen + 4); this._state.authsQueue.shift(); this.debug('DEBUG: Outgoing: Writing USERAUTH_PK_OK'); return send(this, buf); }; SSH2Stream.prototype.authPasswdChg = function(prompt, lang) { if (!this.server) throw new Error('Server-only method called in client mode'); var promptLen = Buffer.byteLength(prompt); var langLen = lang ? lang.length : 0; var p = 0; var buf = Buffer.allocUnsafe(1 + 4 + promptLen + 4 + langLen); buf[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; writeUInt32BE(buf, promptLen, ++p); buf.write(prompt, p += 4, promptLen, 'utf8'); writeUInt32BE(buf, langLen, p += promptLen); if (langLen) buf.write(lang, p += 4, langLen, 'ascii'); this.debug('DEBUG: Outgoing: Writing USERAUTH_PASSWD_CHANGEREQ'); return send(this, buf); }; SSH2Stream.prototype.authInfoReq = function(name, instructions, prompts) { if (!this.server) throw new Error('Server-only method called in client mode'); var promptsLen = 0; var nameLen = name ? Buffer.byteLength(name) : 0; var instrLen = instructions ? Buffer.byteLength(instructions) : 0; var p = 0; var promptLen; var prompt; var len; var i; for (i = 0, len = prompts.length; i < len; ++i) promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; var buf = Buffer.allocUnsafe(1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen); buf[p++] = MESSAGE.USERAUTH_INFO_REQUEST; writeUInt32BE(buf, nameLen, p); p += 4; if (name) { buf.write(name, p, nameLen, 'utf8'); p += nameLen; } writeUInt32BE(buf, instrLen, p); p += 4; if (instructions) { buf.write(instructions, p, instrLen, 'utf8'); p += instrLen; } writeUInt32BE(buf, 0, p); p += 4; writeUInt32BE(buf, prompts.length, p); p += 4; for (i = 0, len = prompts.length; i < len; ++i) { prompt = prompts[i]; promptLen = Buffer.byteLength(prompt.prompt); writeUInt32BE(buf, promptLen, p); p += 4; if (promptLen) { buf.write(prompt.prompt, p, promptLen, 'utf8'); p += promptLen; } buf[p++] = (prompt.echo ? 1 : 0); } this.debug('DEBUG: Outgoing: Writing USERAUTH_INFO_REQUEST'); return send(this, buf); }; // Shared incoming/parser functions function onDISCONNECT(self, reason, code, desc, lang) { // Client/Server if (code !== DISCONNECT_REASON.BY_APPLICATION) { var err = new Error(desc || reason); err.code = code; self.emit('error', err); } self.reset(); } function onKEXINIT(self, init, firstFollows) { // Client/Server var state = self._state; var outstate = state.outgoing; if (outstate.status === OUT_READY) { self.debug('DEBUG: Received re-key request'); outstate.status = OUT_REKEYING; outstate.kexinit = undefined; KEXINIT(self, check); } else { check(); } function check() { if (check_KEXINIT(self, init, firstFollows) === true) { if (!self.server) { if (state.kex.type === 'groupex') KEXDH_GEX_REQ(self); else KEXDH_INIT(self); } else { state.incoming.expectedPacket = state.kex.pktInit; } } } } function check_KEXINIT(self, init, firstFollows) { var state = self._state; var instate = state.incoming; var outstate = state.outgoing; var debug = self.debug; var serverList; var clientList; var val; var len; var i; debug('DEBUG: Comparing KEXINITs ...'); var algos = self.config.algorithms; var kexList = algos.kex; if (self.remoteBugs & BUGS.BAD_DHGEX) { var copied = false; for (var j = kexList.length - 1; j >= 0; --j) { if (kexList[j].indexOf('group-exchange') !== -1) { if (!copied) { kexList = kexList.slice(); copied = true; } kexList.splice(j, 1); } } } debug('DEBUG: (local) KEX algorithms: ' + kexList); debug('DEBUG: (remote) KEX algorithms: ' + init.algorithms.kex); if (self.server) { serverList = kexList; clientList = init.algorithms.kex; } else { serverList = init.algorithms.kex; clientList = kexList; } // Check for agreeable key exchange algorithm for (i = 0, len = clientList.length; i < len && serverList.indexOf(clientList[i]) === -1; ++i); if (i === len) { // No suitable match found! debug('DEBUG: No matching key exchange algorithm'); var err = new Error('Handshake failed: no matching key exchange algorithm'); err.level = 'handshake'; self.emit('error', err); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } var kex_algorithm = clientList[i]; debug('DEBUG: KEX algorithm: ' + kex_algorithm); if (firstFollows && (!init.algorithms.kex.length || kex_algorithm !== init.algorithms.kex[0])) { // Ignore next incoming packet, it was a wrong first guess at KEX algorithm instate.ignoreNext = true; } debug('DEBUG: (local) Host key formats: ' + algos.serverHostKey); debug('DEBUG: (remote) Host key formats: ' + init.algorithms.srvHostKey); if (self.server) { serverList = algos.serverHostKey; clientList = init.algorithms.srvHostKey; } else { serverList = init.algorithms.srvHostKey; clientList = algos.serverHostKey; } // Check for agreeable server host key format for (i = 0, len = clientList.length; i < len && serverList.indexOf(clientList[i]) === -1; ++i); if (i === len) { // No suitable match found! debug('DEBUG: No matching host key format'); var err = new Error('Handshake failed: no matching host key format'); err.level = 'handshake'; self.emit('error', err); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } state.hostkeyFormat = clientList[i]; debug('DEBUG: Host key format: ' + state.hostkeyFormat); debug('DEBUG: (local) Client->Server ciphers: ' + algos.cipher); debug('DEBUG: (remote) Client->Server ciphers: ' + init.algorithms.cs.encrypt); if (self.server) { serverList = algos.cipher; clientList = init.algorithms.cs.encrypt; } else { serverList = init.algorithms.cs.encrypt; clientList = algos.cipher; } // Check for agreeable client->server cipher for (i = 0, len = clientList.length; i < len && serverList.indexOf(clientList[i]) === -1; ++i); if (i === len) { // No suitable match found! debug('DEBUG: No matching Client->Server cipher'); var err = new Error('Handshake failed: no matching client->server cipher'); err.level = 'handshake'; self.emit('error', err); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } if (self.server) val = instate.decrypt.type = clientList[i]; else val = outstate.encrypt.type = clientList[i]; debug('DEBUG: Client->Server Cipher: ' + val); debug('DEBUG: (local) Server->Client ciphers: ' + algos.cipher); debug('DEBUG: (remote) Server->Client ciphers: ' + (init.algorithms.sc.encrypt)); if (self.server) { serverList = algos.cipher; clientList = init.algorithms.sc.encrypt; } else { serverList = init.algorithms.sc.encrypt; clientList = algos.cipher; } // Check for agreeable server->client cipher for (i = 0, len = clientList.length; i < len && serverList.indexOf(clientList[i]) === -1; ++i); if (i === len) { // No suitable match found! debug('DEBUG: No matching Server->Client cipher'); var err = new Error('Handshake failed: no matching server->client cipher'); err.level = 'handshake'; self.emit('error', err); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } if (self.server) val = outstate.encrypt.type = clientList[i]; else val = instate.decrypt.type = clientList[i]; debug('DEBUG: Server->Client Cipher: ' + val); debug('DEBUG: (local) Client->Server HMAC algorithms: ' + algos.hmac); debug('DEBUG: (remote) Client->Server HMAC algorithms: ' + init.algorithms.cs.mac); if (self.server) { serverList = algos.hmac; clientList = init.algorithms.cs.mac; } else { serverList = init.algorithms.cs.mac; clientList = algos.hmac; } // Check for agreeable client->server hmac algorithm for (i = 0, len = clientList.length; i < len && serverList.indexOf(clientList[i]) === -1; ++i); if (i === len) { // No suitable match found! debug('DEBUG: No matching Client->Server HMAC algorithm'); var err = new Error('Handshake failed: no matching client->server HMAC'); err.level = 'handshake'; self.emit('error', err); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } if (self.server) val = instate.hmac.type = clientList[i]; else val = outstate.hmac.type = clientList[i]; debug('DEBUG: Client->Server HMAC algorithm: ' + val); debug('DEBUG: (local) Server->Client HMAC algorithms: ' + algos.hmac); debug('DEBUG: (remote) Server->Client HMAC algorithms: ' + init.algorithms.sc.mac); if (self.server) { serverList = algos.hmac; clientList = init.algorithms.sc.mac; } else { serverList = init.algorithms.sc.mac; clientList = algos.hmac; } // Check for agreeable server->client hmac algorithm for (i = 0, len = clientList.length; i < len && serverList.indexOf(clientList[i]) === -1; ++i); if (i === len) { // No suitable match found! debug('DEBUG: No matching Server->Client HMAC algorithm'); var err = new Error('Handshake failed: no matching server->client HMAC'); err.level = 'handshake'; self.emit('error', err); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } if (self.server) val = outstate.hmac.type = clientList[i]; else val = instate.hmac.type = clientList[i]; debug('DEBUG: Server->Client HMAC algorithm: ' + val); debug('DEBUG: (local) Client->Server compression algorithms: ' + algos.compress); debug('DEBUG: (remote) Client->Server compression algorithms: ' + init.algorithms.cs.compress); if (self.server) { serverList = algos.compress; clientList = init.algorithms.cs.compress; } else { serverList = init.algorithms.cs.compress; clientList = algos.compress; } // Check for agreeable client->server compression algorithm for (i = 0, len = clientList.length; i < len && serverList.indexOf(clientList[i]) === -1; ++i); if (i === len) { // No suitable match found! debug('DEBUG: No matching Client->Server compression algorithm'); var err = new Error('Handshake failed: no matching client->server ' + 'compression algorithm'); err.level = 'handshake'; self.emit('error', err); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } if (self.server) val = instate.decompress.type = clientList[i]; else val = outstate.compress.type = clientList[i]; debug('DEBUG: Client->Server compression algorithm: ' + val); debug('DEBUG: (local) Server->Client compression algorithms: ' + algos.compress); debug('DEBUG: (remote) Server->Client compression algorithms: ' + init.algorithms.sc.compress); if (self.server) { serverList = algos.compress; clientList = init.algorithms.sc.compress; } else { serverList = init.algorithms.sc.compress; clientList = algos.compress; } // Check for agreeable server->client compression algorithm for (i = 0, len = clientList.length; i < len && serverList.indexOf(clientList[i]) === -1; ++i); if (i === len) { // No suitable match found! debug('DEBUG: No matching Server->Client compression algorithm'); var err = new Error('Handshake failed: no matching server->client ' + 'compression algorithm'); err.level = 'handshake'; self.emit('error', err); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } if (self.server) val = outstate.compress.type = clientList[i]; else val = instate.decompress.type = clientList[i]; debug('DEBUG: Server->Client compression algorithm: ' + val); state.kex = new KeyExchange(kex_algorithm); state.kex.generateKeys(); outstate.pubkey = state.kex.getPublicKey(); return true; } function onKEXDH_GEX_GROUP(self, prime, gen) { var state = self._state; var outstate = state.outgoing; state.kex.setDHParams(prime, gen); state.kex.generateKeys(); outstate.pubkey = state.kex.getPublicKey(); KEXDH_INIT(self); } function onKEXDH_INIT(self, e) { // Server KEXDH_REPLY(self, e); } function onKEXDH_REPLY(self, info, verifiedHost) { // Client var state = self._state; var instate = state.incoming; var outstate = state.outgoing; var debug = self.debug; var len; var i; if (verifiedHost === undefined) { instate.expectedPacket = 'NEWKEYS'; outstate.sentNEWKEYS = false; debug('DEBUG: Checking host key format'); // Ensure all host key formats agree var hostkey_format = readString(info.hostkey, 0, 'ascii', self); if (hostkey_format === false) return false; if (info.hostkey_format !== state.hostkeyFormat || info.hostkey_format !== hostkey_format) { // Expected and actual server host key format do not match! debug('DEBUG: Host key format mismatch'); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); self.reset(); var err = new Error('Handshake failed: host key format mismatch'); err.level = 'handshake'; self.emit('error', err); return false; } debug('DEBUG: Checking signature format'); // Ensure signature formats agree var sig_format = readString(info.sig, 0, 'ascii', self); if (sig_format === false) return false; if (info.sig_format !== sig_format) { debug('DEBUG: Signature format mismatch'); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); self.reset(); var err = new Error('Handshake failed: signature format mismatch'); err.level = 'handshake'; self.emit('error', err); return false; } } // Verify the host fingerprint first if needed if (outstate.status === OUT_INIT) { if (verifiedHost === undefined) { debug('DEBUG: Verifying host fingerprint'); var sync = true; var emitted = self.emit('fingerprint', info.hostkey, function(permitted) { // Prevent multiple calls to this callback if (verifiedHost !== undefined) return; verifiedHost = !!permitted; if (!sync) { // Continue execution by re-entry onKEXDH_REPLY(self, info, verifiedHost); } }); sync = false; // Support async calling of verification callback if (emitted && verifiedHost === undefined) return; } if (verifiedHost === undefined) debug('DEBUG: Host accepted by default (no verification)'); else if (verifiedHost === true) debug('DEBUG: Host accepted (verified)'); else { debug('DEBUG: Host denied via fingerprint verification'); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); self.reset(); var err = new Error('Handshake failed: ' + 'host fingerprint verification failed'); err.level = 'handshake'; self.emit('error', err); return false; } } info.pubkey = state.kex.convertPublicKey(info.pubkey); info.secret = state.kex.computeSecret(info.pubkey); if (info.secret instanceof Error) { info.secret.message = 'Error while computing DH secret (' + state.kex.type + '): ' + info.secret.message; info.secret.level = 'handshake'; self.emit('error', info.secret); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } var hash = crypto.createHash(state.kex.hash); var len_ident = Buffer.byteLength(self.config.ident); var len_sident = Buffer.byteLength(instate.identRaw); var len_init = outstate.kexinit.length; var len_sinit = instate.kexinit.length; var len_hostkey = info.hostkey.length; var len_pubkey = outstate.pubkey.length; var len_spubkey = info.pubkey.length; var len_secret = info.secret.length; var exchangeBufLen = len_ident + len_sident + len_init + len_sinit + len_hostkey + len_pubkey + len_spubkey + len_secret + (4 * 8); // Length fields for above values // Group exchange-related var len_gex_prime; var len_gex_gen; var gex_prime; var gex_gen; var dhParams = state.kex.getDHParams(); if (dhParams) { gex_prime = dhParams.prime; gex_gen = dhParams.generator; len_gex_prime = gex_prime.length; len_gex_gen = gex_gen.length; exchangeBufLen += (4 * 3); // min, n, max values exchangeBufLen += (4 * 2); // prime, generator length fields exchangeBufLen += len_gex_prime; exchangeBufLen += len_gex_gen; } var bp = 0; var exchangeBuf = Buffer.allocUnsafe(exchangeBufLen); writeUInt32BE(exchangeBuf, len_ident, bp); bp += 4; exchangeBuf.write(self.config.ident, bp, 'utf8'); // V_C bp += len_ident; writeUInt32BE(exchangeBuf, len_sident, bp); bp += 4; exchangeBuf.write(instate.identRaw, bp, 'utf8'); // V_S bp += len_sident; writeUInt32BE(exchangeBuf, len_init, bp); bp += 4; outstate.kexinit.copy(exchangeBuf, bp); // I_C bp += len_init; outstate.kexinit = undefined; writeUInt32BE(exchangeBuf, len_sinit, bp); bp += 4; instate.kexinit.copy(exchangeBuf, bp); // I_S bp += len_sinit; instate.kexinit = undefined; writeUInt32BE(exchangeBuf, len_hostkey, bp); bp += 4; info.hostkey.copy(exchangeBuf, bp); // K_S bp += len_hostkey; if (dhParams) { KEXDH_GEX_REQ_PACKET.slice(1).copy(exchangeBuf, bp); // min, n, max bp += (4 * 3); // Skip over bytes just copied writeUInt32BE(exchangeBuf, len_gex_prime, bp); bp += 4; gex_prime.copy(exchangeBuf, bp); // p bp += len_gex_prime; writeUInt32BE(exchangeBuf, len_gex_gen, bp); bp += 4; gex_gen.copy(exchangeBuf, bp); // g bp += len_gex_gen; } writeUInt32BE(exchangeBuf, len_pubkey, bp); bp += 4; outstate.pubkey.copy(exchangeBuf, bp); // e bp += len_pubkey; writeUInt32BE(exchangeBuf, len_spubkey, bp); bp += 4; info.pubkey.copy(exchangeBuf, bp); // f bp += len_spubkey; writeUInt32BE(exchangeBuf, len_secret, bp); bp += 4; info.secret.copy(exchangeBuf, bp); // K outstate.exchangeHash = hash.update(exchangeBuf).digest(); // H var rawsig = readString(info.sig, info.sig._pos, self); // s if (rawsig === false || !(rawsig = sigSSHToASN1(rawsig, info.sig_format, self))) { return false; } var hostPubKey = parseDERKey(info.hostkey, info.sig_format); if (hostPubKey instanceof Error) return false; debug('DEBUG: Verifying signature'); if (hostPubKey.verify(outstate.exchangeHash, rawsig) !== true) { debug('DEBUG: Signature verification failed'); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); self.reset(); var err = new Error('Handshake failed: signature verification failed'); err.level = 'handshake'; self.emit('error', err); return false; } if (outstate.sessionId === undefined) outstate.sessionId = outstate.exchangeHash; outstate.kexsecret = info.secret; debug('DEBUG: Outgoing: Writing NEWKEYS'); if (outstate.status === OUT_REKEYING) send(self, NEWKEYS_PACKET, undefined, true); else send(self, NEWKEYS_PACKET); outstate.sentNEWKEYS = true; if (verifiedHost !== undefined && instate.expectedPacket === undefined) { // We received NEWKEYS while we were waiting for the fingerprint // verification callback to be called. In this case we have to re-execute // onNEWKEYS to finish the handshake. onNEWKEYS(self); } } function onNEWKEYS(self) { // Client/Server var state = self._state; var outstate = state.outgoing; var instate = state.incoming; instate.expectedPacket = undefined; if (!outstate.sentNEWKEYS) return; var len = outstate.kexsecret.length; var outCipherInfo = outstate.encrypt.info = CIPHER_INFO[outstate.encrypt.type]; var p = 0; var dhHashAlgo = state.kex.hash; var secret = Buffer.allocUnsafe(4 + len); var iv; var key; // Whenever the client sends a new authentication request, it is enqueued // here. Once the request is resolved (success, fail, or PK_OK), // dequeue. Whatever is at the front of the queue determines how we // interpret packet type 60. state.authsQueue = []; writeUInt32BE(secret, len, p); p += 4; outstate.kexsecret.copy(secret, p); outstate.kexsecret = undefined; if (!outCipherInfo.stream) { iv = crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(!self.server ? 'A' : 'B', 'ascii') .update(outstate.sessionId) .digest(); while (iv.length < outCipherInfo.ivLen) { iv = Buffer.concat([iv, crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(iv) .digest()]); } if (iv.length > outCipherInfo.ivLen) iv = iv.slice(0, outCipherInfo.ivLen); } else { iv = EMPTY_BUFFER; // Streaming ciphers don't use an IV upfront } key = crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(!self.server ? 'C' : 'D', 'ascii') .update(outstate.sessionId) .digest(); while (key.length < outCipherInfo.keyLen) { key = Buffer.concat([key, crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(key) .digest()]); } if (key.length > outCipherInfo.keyLen) key = key.slice(0, outCipherInfo.keyLen); if (outCipherInfo.authLen > 0) { outstate.encrypt.iv = iv; outstate.encrypt.key = key; outstate.encrypt.instance = true; } else { var cipherAlgo = SSH_TO_OPENSSL[outstate.encrypt.type]; outstate.encrypt.instance = crypto.createCipheriv(cipherAlgo, key, iv); outstate.encrypt.instance.setAutoPadding(false); } // And now for decrypting ... var inCipherInfo = instate.decrypt.info = CIPHER_INFO[instate.decrypt.type]; if (!inCipherInfo.stream) { iv = crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(!self.server ? 'B' : 'A', 'ascii') .update(outstate.sessionId) .digest(); while (iv.length < inCipherInfo.ivLen) { iv = Buffer.concat([iv, crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(iv) .digest()]); } if (iv.length > inCipherInfo.ivLen) iv = iv.slice(0, inCipherInfo.ivLen); } else { iv = EMPTY_BUFFER; // Streaming ciphers don't use an IV upfront } // Create a reusable buffer for decryption purposes instate.decrypt.buf = Buffer.allocUnsafe(inCipherInfo.blockLen); key = crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(!self.server ? 'D' : 'C', 'ascii') .update(outstate.sessionId) .digest(); while (key.length < inCipherInfo.keyLen) { key = Buffer.concat([key, crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(key) .digest()]); } if (key.length > inCipherInfo.keyLen) key = key.slice(0, inCipherInfo.keyLen); var decipherAlgo = SSH_TO_OPENSSL[instate.decrypt.type]; instate.decrypt.instance = crypto.createDecipheriv(decipherAlgo, key, iv); instate.decrypt.instance.setAutoPadding(false); instate.decrypt.iv = iv; instate.decrypt.key = key; var emptyBuf; if (outCipherInfo.discardLen > 0) { emptyBuf = Buffer.alloc(outCipherInfo.discardLen); outstate.encrypt.instance.update(emptyBuf); } if (inCipherInfo.discardLen > 0) { if (!emptyBuf || emptyBuf.length !== inCipherInfo.discardLen) emptyBuf = Buffer.alloc(outCipherInfo.discardLen); instate.decrypt.instance.update(emptyBuf); } var outHMACInfo = outstate.hmac.info = HMAC_INFO[outstate.hmac.type]; var inHMACInfo = instate.hmac.info = HMAC_INFO[instate.hmac.type]; if (outCipherInfo.authLen === 0) { key = crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(!self.server ? 'E' : 'F', 'ascii') .update(outstate.sessionId) .digest(); while (key.length < outHMACInfo.len) { key = Buffer.concat([key, crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(key) .digest()]); } if (key.length > outHMACInfo.len) key = key.slice(0, outHMACInfo.len); outstate.hmac.key = key; } else { outstate.hmac.key = undefined; } if (inCipherInfo.authLen === 0) { key = crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(!self.server ? 'F' : 'E', 'ascii') .update(outstate.sessionId) .digest(); while (key.length < inHMACInfo.len) { key = Buffer.concat([key, crypto.createHash(dhHashAlgo) .update(secret) .update(outstate.exchangeHash) .update(key) .digest()]); } if (key.length > inHMACInfo.len) key = key.slice(0, inHMACInfo.len); instate.hmac.key = key; } else { instate.hmac.key = undefined; } // Create a reusable buffer for message verification purposes var inHMACSize = inCipherInfo.authLen || instate.hmac.info.actualLen; if (!instate.hmac.buf || instate.hmac.buf.length !== inHMACSize) { instate.hmac.buf = Buffer.allocUnsafe(inHMACSize); } outstate.exchangeHash = undefined; if (outstate.compress.type === 'zlib') { outstate.compress.instance = zlib.createDeflate(ZLIB_OPTS); outstate.compress.queue = []; } else if (outstate.compress.type === 'none') { outstate.compress.instance = false; outstate.compress.queue = null; } if (instate.decompress.type === 'zlib') instate.decompress.instance = zlib.createInflate(ZLIB_OPTS); else if (instate.decompress.type === 'none') instate.decompress.instance = false; self.bytesSent = self.bytesReceived = 0; if (outstate.status === OUT_REKEYING) { outstate.status = OUT_READY; // Empty our outbound buffer of any data we tried to send during the // re-keying process var queue = outstate.rekeyQueue; var qlen = queue.length; var q = 0; outstate.rekeyQueue = []; for (; q < qlen; ++q) { if (Buffer.isBuffer(queue[q])) send(self, queue[q]); else send(self, queue[q][0], queue[q][1]); } // Now empty our inbound buffer of any non-transport layer packets we // received during the re-keying process queue = instate.rekeyQueue; qlen = queue.length; q = 0; instate.rekeyQueue = []; var curSeqno = instate.seqno; for (; q < qlen; ++q) { instate.seqno = queue[q][0]; instate.payload = queue[q][1]; if (parsePacket(self) === false) return; if (instate.status === IN_INIT) { // We were reset due to some error/disagreement ? return; } } instate.seqno = curSeqno; } else { outstate.status = OUT_READY; if (instate.status === IN_PACKET) { // Explicitly update incoming packet parser status in order to get the // correct decipher, hmac, etc. states. // We only get here if the host fingerprint callback was called // asynchronously and the incoming packet parser is still expecting an // unencrypted packet, etc. self.debug('DEBUG: Parser: IN_PACKETBEFORE (update) (expecting ' + inCipherInfo.blockLen + ')'); // Wait for the right number of bytes so we can determine the incoming // packet length expectData(self, EXP_TYPE_BYTES, inCipherInfo.blockLen, instate.decrypt.buf); } self.emit('ready'); } } function getPacketType(self, pktType) { var kex = self._state.kex; if (kex) { // Disambiguate switch (pktType) { case 30: return kex.pktInit; case 31: switch (kex.type) { case 'group': return 'KEXDH_REPLY'; case 'groupex': return 'KEXDH_GEX_GROUP'; default: return 'KEXECDH_REPLY'; } break; case 33: if (kex.type === 'groupex') return 'KEXDH_GEX_REPLY'; } } return MESSAGE[pktType]; } function parsePacket(self, callback) { var instate = self._state.incoming; var outstate = self._state.outgoing; var payload = instate.payload; var seqno = instate.seqno; var serviceName; var lang; var message; var info; var chan; var data; var srcIP; var srcPort; var sender; var window; var packetSize; var recipient; var description; var socketPath; if (++instate.seqno > MAX_SEQNO) instate.seqno = 0; if (instate.ignoreNext) { self.debug('DEBUG: Parser: Packet ignored'); instate.ignoreNext = false; return; } var type = payload[0]; if (type === undefined) return false; // If we receive a packet during handshake that is not the expected packet // and it is not one of: DISCONNECT, IGNORE, UNIMPLEMENTED, or DEBUG, then we // close the stream if (outstate.status !== OUT_READY && getPacketType(self, type) !== instate.expectedPacket && type < 1 && type > 4) { self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, expected: ' + instate.expectedPacket + ' but got: ' + getPacketType(self, type)); // XXX: Potential issue where the module user decides to initiate a rekey // via KEXINIT() (which sets `expectedPacket`) after receiving a packet // and there is still another packet already waiting to be parsed at the // time the KEXINIT is written. this will cause an unexpected disconnect... self.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); var err = new Error('Received unexpected packet'); err.level = 'protocol'; self.emit('error', err); return false; } if (type === MESSAGE.CHANNEL_DATA) { /* byte SSH_MSG_CHANNEL_DATA uint32 recipient channel string data */ chan = readInt(payload, 1, self, callback); if (chan === false) return false; // TODO: MAX_CHAN_DATA_LEN here should really be dependent upon the // channel's packet size. The ssh2 module uses 32KB, so we'll hard // code this for now ... data = readString(payload, 5, self, callback, 32768); if (data === false) return false; self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: CHANNEL_DATA (' + chan + ')'); self.emit('CHANNEL_DATA:' + chan, data); } else if (type === MESSAGE.CHANNEL_EXTENDED_DATA) { /* byte SSH_MSG_CHANNEL_EXTENDED_DATA uint32 recipient channel uint32 data_type_code string data */ chan = readInt(payload, 1, self, callback); if (chan === false) return false; var dataType = readInt(payload, 5, self, callback); if (dataType === false) return false; data = readString(payload, 9, self, callback); if (data === false) return false; self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: ' + 'CHANNEL_EXTENDED_DATA (' + chan + ')'); self.emit('CHANNEL_EXTENDED_DATA:' + chan, dataType, data); } else if (type === MESSAGE.CHANNEL_WINDOW_ADJUST) { /* byte SSH_MSG_CHANNEL_WINDOW_ADJUST uint32 recipient channel uint32 bytes to add */ chan = readInt(payload, 1, self, callback); if (chan === false) return false; var bytesToAdd = readInt(payload, 5, self, callback); if (bytesToAdd === false) return false; self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: ' + 'CHANNEL_WINDOW_ADJUST (' + chan + ', ' + bytesToAdd + ')'); self.emit('CHANNEL_WINDOW_ADJUST:' + chan, bytesToAdd); } else if (type === MESSAGE.CHANNEL_SUCCESS) { /* byte SSH_MSG_CHANNEL_SUCCESS uint32 recipient channel */ chan = readInt(payload, 1, self, callback); if (chan === false) return false; self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: CHANNEL_SUCCESS (' + chan + ')'); self.emit('CHANNEL_SUCCESS:' + chan); } else if (type === MESSAGE.CHANNEL_FAILURE) { /* byte SSH_MSG_CHANNEL_FAILURE uint32 recipient channel */ chan = readInt(payload, 1, self, callback); if (chan === false) return false; self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: CHANNEL_FAILURE (' + chan + ')'); self.emit('CHANNEL_FAILURE:' + chan); } else if (type === MESSAGE.CHANNEL_EOF) { /* byte SSH_MSG_CHANNEL_EOF uint32 recipient channel */ chan = readInt(payload, 1, self, callback); if (chan === false) return false; self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: CHANNEL_EOF (' + chan + ')'); self.emit('CHANNEL_EOF:' + chan); } else if (type === MESSAGE.CHANNEL_OPEN) { /* byte SSH_MSG_CHANNEL_OPEN string channel type in US-ASCII only uint32 sender channel uint32 initial window size uint32 maximum packet size .... channel type specific data follows */ var chanType = readString(payload, 1, 'ascii', self, callback); if (chanType === false) return false; sender = readInt(payload, payload._pos, self, callback); if (sender === false) return false; window = readInt(payload, payload._pos += 4, self, callback); if (window === false) return false; packetSize = readInt(payload, payload._pos += 4, self, callback); if (packetSize === false) return false; var channel; self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: CHANNEL_OPEN (' + sender + ', ' + chanType + ')'); if (chanType === 'forwarded-tcpip' // Server->Client || chanType === 'direct-tcpip') { // Client->Server /* string address that was connected / host to connect uint32 port that was connected / port to connect string originator IP address uint32 originator port */ var destIP = readString(payload, payload._pos += 4, 'ascii', self, callback); if (destIP === false) return false; var destPort = readInt(payload, payload._pos, self, callback); if (destPort === false) return false; srcIP = readString(payload, payload._pos += 4, 'ascii', self, callback); if (srcIP === false) return false; srcPort = readInt(payload, payload._pos, self, callback); if (srcPort === false) return false; channel = { type: chanType, sender: sender, window: window, packetSize: packetSize, data: { destIP: destIP, destPort: destPort, srcIP: srcIP, srcPort: srcPort } }; } else if (// Server->Client chanType === 'forwarded-streamlocal@openssh.com' // Client->Server || chanType === 'direct-streamlocal@openssh.com') { /* string socket path string reserved for future use */ socketPath = readString(payload, payload._pos += 4, 'utf8', self, callback); if (socketPath === false) return false; channel = { type: chanType, sender: sender, window: window, packetSize: packetSize, data: { socketPath: socketPath, } }; } else if (chanType === 'x11') { // Server->Client /* string originator address (e.g., "192.168.7.38") uint32 originator port */ srcIP = readString(payload, payload._pos += 4, 'ascii', self, callback); if (srcIP === false) return false; srcPort = readInt(payload, payload._pos, self, callback); if (srcPort === false) return false; channel = { type: chanType, sender: sender, window: window, packetSize: packetSize, data: { srcIP: srcIP, srcPort: srcPort } }; } else { // 'session' (Client->Server), 'auth-agent@openssh.com' (Server->Client) channel = { type: chanType, sender: sender, window: window, packetSize: packetSize, data: {} }; } self.emit('CHANNEL_OPEN', channel); } else if (type === MESSAGE.CHANNEL_OPEN_CONFIRMATION) { /* byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION uint32 recipient channel uint32 sender channel uint32 initial window size uint32 maximum packet size .... channel type specific data follows */ // "The 'recipient channel' is the channel number given in the // original open request, and 'sender channel' is the channel number // allocated by the other side." recipient = readInt(payload, 1, self, callback); if (recipient === false) return false; sender = readInt(payload, 5, self, callback); if (sender === false) return false; window = readInt(payload, 9, self, callback); if (window === false) return false; packetSize = readInt(payload, 13, self, callback); if (packetSize === false) return false; info = { recipient: recipient, sender: sender, window: window, packetSize: packetSize }; if (payload.length > 17) info.data = payload.slice(17); self.emit('CHANNEL_OPEN_CONFIRMATION:' + info.recipient, info); } else if (type === MESSAGE.CHANNEL_OPEN_FAILURE) { /* byte SSH_MSG_CHANNEL_OPEN_FAILURE uint32 recipient channel uint32 reason code string description in ISO-10646 UTF-8 encoding string language tag */ recipient = readInt(payload, 1, self, callback); if (recipient === false) return false; var reasonCode = readInt(payload, 5, self, callback); if (reasonCode === false) return false; description = readString(payload, 9, 'utf8', self, callback); if (description === false) return false; lang = readString(payload, payload._pos, 'utf8', self, callback); if (lang === false) return false; payload._pos = 9; info = { recipient: recipient, reasonCode: reasonCode, reason: CHANNEL_OPEN_FAILURE[reasonCode], description: description, lang: lang }; self.emit('CHANNEL_OPEN_FAILURE:' + info.recipient, info); } else if (type === MESSAGE.CHANNEL_CLOSE) { /* byte SSH_MSG_CHANNEL_CLOSE uint32 recipient channel */ chan = readInt(payload, 1, self, callback); if (chan === false) return false; self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: CHANNEL_CLOSE (' + chan + ')'); self.emit('CHANNEL_CLOSE:' + chan); } else if (type === MESSAGE.IGNORE) { /* byte SSH_MSG_IGNORE string data */ } else if (type === MESSAGE.DISCONNECT) { /* byte SSH_MSG_DISCONNECT uint32 reason code string description in ISO-10646 UTF-8 encoding string language tag */ var reason = readInt(payload, 1, self, callback); if (reason === false) return false; var reasonText = DISCONNECT_REASON[reason]; description = readString(payload, 5, 'utf8', self, callback); if (description === false) return false; if (payload._pos < payload.length) lang = readString(payload, payload._pos, 'ascii', self, callback); self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: DISCONNECT (' + reasonText + ')'); self.emit('DISCONNECT', reasonText, reason, description, lang); } else if (type === MESSAGE.DEBUG) { /* byte SSH_MSG_DEBUG boolean always_display string message in ISO-10646 UTF-8 encoding string language tag */ message = readString(payload, 2, 'utf8', self, callback); if (message === false) return false; lang = readString(payload, payload._pos, 'ascii', self, callback); if (lang === false) return false; self.emit('DEBUG', message, lang); } else if (type === MESSAGE.NEWKEYS) { /* byte SSH_MSG_NEW_KEYS */ self.emit('NEWKEYS'); } else if (type === MESSAGE.SERVICE_REQUEST) { /* byte SSH_MSG_SERVICE_REQUEST string service name */ serviceName = readString(payload, 1, 'ascii', self, callback); if (serviceName === false) return false; self.emit('SERVICE_REQUEST', serviceName); } else if (type === MESSAGE.SERVICE_ACCEPT) { /* byte SSH_MSG_SERVICE_ACCEPT string service name */ serviceName = readString(payload, 1, 'ascii', self, callback); if (serviceName === false) return false; self.emit('SERVICE_ACCEPT', serviceName); } else if (type === MESSAGE.USERAUTH_REQUEST) { /* byte SSH_MSG_USERAUTH_REQUEST string user name in ISO-10646 UTF-8 encoding [RFC3629] string service name in US-ASCII string method name in US-ASCII .... method specific fields */ var username = readString(payload, 1, 'utf8', self, callback); if (username === false) return false; var svcName = readString(payload, payload._pos, 'ascii', self, callback); if (svcName === false) return false; var method = readString(payload, payload._pos, 'ascii', self, callback); if (method === false) return false; var methodData; var methodDesc; if (method === 'password') { methodData = readString(payload, payload._pos + 1, 'utf8', self, callback); if (methodData === false) return false; } else if (method === 'publickey' || method === 'hostbased') { var pkSigned; var keyAlgo; var key; var signature; var blob; var hostname; var userlocal; if (method === 'publickey') { pkSigned = payload[payload._pos++]; if (pkSigned === undefined) return false; pkSigned = (pkSigned !== 0); } keyAlgo = readString(payload, payload._pos, 'ascii', self, callback); if (keyAlgo === false) return false; key = readString(payload, payload._pos, self, callback); if (key === false) return false; if (pkSigned || method === 'hostbased') { if (method === 'hostbased') { hostname = readString(payload, payload._pos, 'ascii', self, callback); if (hostname === false) return false; userlocal = readString(payload, payload._pos, 'utf8', self, callback); if (userlocal === false) return false; } var blobEnd = payload._pos; signature = readString(payload, blobEnd, self, callback); if (signature === false) return false; if (signature.length > (4 + keyAlgo.length + 4) && signature.toString('ascii', 4, 4 + keyAlgo.length) === keyAlgo) { // Skip algoLen + algo + sigLen signature = signature.slice(4 + keyAlgo.length + 4); } signature = sigSSHToASN1(signature, keyAlgo, self, callback); if (signature === false) return false; blob = Buffer.allocUnsafe(4 + outstate.sessionId.length + blobEnd); writeUInt32BE(blob, outstate.sessionId.length, 0); outstate.sessionId.copy(blob, 4); payload.copy(blob, 4 + outstate.sessionId.length, 0, blobEnd); } else { methodDesc = 'publickey -- check'; } methodData = { keyAlgo: keyAlgo, key: key, signature: signature, blob: blob, localHostname: hostname, localUsername: userlocal }; } else if (method === 'keyboard-interactive') { // Skip language, it's deprecated var skipLen = readInt(payload, payload._pos, self, callback); if (skipLen === false) return false; methodData = readString(payload, payload._pos + 4 + skipLen, 'utf8', self, callback); if (methodData === false) return false; } else if (method !== 'none') methodData = payload.slice(payload._pos); if (methodDesc === undefined) methodDesc = method; self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: USERAUTH_REQUEST (' + methodDesc + ')'); self._state.authsQueue.push(method); self.emit('USERAUTH_REQUEST', username, svcName, method, methodData); } else if (type === MESSAGE.USERAUTH_SUCCESS) { /* byte SSH_MSG_USERAUTH_SUCCESS */ if (outstate.compress.type === 'zlib@openssh.com') { outstate.compress.instance = zlib.createDeflate(ZLIB_OPTS); outstate.compress.queue = []; } if (instate.decompress.type === 'zlib@openssh.com') instate.decompress.instance = zlib.createInflate(ZLIB_OPTS); self._state.authsQueue.shift(); self.emit('USERAUTH_SUCCESS'); } else if (type === MESSAGE.USERAUTH_FAILURE) { /* byte SSH_MSG_USERAUTH_FAILURE name-list authentications that can continue boolean partial success */ var auths = readString(payload, 1, 'ascii', self, callback); if (auths === false) return false; var partSuccess = payload[payload._pos]; if (partSuccess === undefined) return false; partSuccess = (partSuccess !== 0); auths = auths.split(','); self._state.authsQueue.shift(); self.emit('USERAUTH_FAILURE', auths, partSuccess); } else if (type === MESSAGE.USERAUTH_BANNER) { /* byte SSH_MSG_USERAUTH_BANNER string message in ISO-10646 UTF-8 encoding string language tag */ message = readString(payload, 1, 'utf8', self, callback); if (message === false) return false; lang = readString(payload, payload._pos, 'utf8', self, callback); if (lang === false) return false; self.emit('USERAUTH_BANNER', message, lang); } else if (type === MESSAGE.GLOBAL_REQUEST) { /* byte SSH_MSG_GLOBAL_REQUEST string request name in US-ASCII only boolean want reply .... request-specific data follows */ var request = readString(payload, 1, 'ascii', self, callback); if (request === false) { self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: GLOBAL_REQUEST'); return false; } self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: GLOBAL_REQUEST (' + request + ')'); var wantReply = payload[payload._pos++]; if (wantReply === undefined) return false; wantReply = (wantReply !== 0); var reqData; if (request === 'tcpip-forward' || request === 'cancel-tcpip-forward') { var bindAddr = readString(payload, payload._pos, 'ascii', self, callback); if (bindAddr === false) return false; var bindPort = readInt(payload, payload._pos, self, callback); if (bindPort === false) return false; reqData = { bindAddr: bindAddr, bindPort: bindPort }; } else if (request === 'streamlocal-forward@openssh.com' || request === 'cancel-streamlocal-forward@openssh.com') { socketPath = readString(payload, payload._pos, 'utf8', self, callback); if (socketPath === false) return false; reqData = { socketPath: socketPath }; } else if (request === 'no-more-sessions@openssh.com') { // No data } else { reqData = payload.slice(payload._pos); } self.emit('GLOBAL_REQUEST', request, wantReply, reqData); } else if (type === MESSAGE.REQUEST_SUCCESS) { /* byte SSH_MSG_REQUEST_SUCCESS .... response specific data */ if (payload.length > 1) self.emit('REQUEST_SUCCESS', payload.slice(1)); else self.emit('REQUEST_SUCCESS'); } else if (type === MESSAGE.REQUEST_FAILURE) { /* byte SSH_MSG_REQUEST_FAILURE */ self.emit('REQUEST_FAILURE'); } else if (type === MESSAGE.UNIMPLEMENTED) { /* byte SSH_MSG_UNIMPLEMENTED uint32 packet sequence number of rejected message */ // TODO } else if (type === MESSAGE.KEXINIT) return parse_KEXINIT(self, callback); else if (type === MESSAGE.CHANNEL_REQUEST) return parse_CHANNEL_REQUEST(self, callback); else if (type >= 30 && type <= 49) // Key exchange method-specific messages return parse_KEX(self, type, callback); else if (type >= 60 && type <= 70) // User auth context-specific messages return parse_USERAUTH(self, type, callback); else { // Unknown packet type var unimpl = Buffer.allocUnsafe(1 + 4); unimpl[0] = MESSAGE.UNIMPLEMENTED; writeUInt32BE(unimpl, seqno, 1); send(self, unimpl); } } function parse_KEXINIT(self, callback) { var instate = self._state.incoming; var payload = instate.payload; /* byte SSH_MSG_KEXINIT byte[16] cookie (random bytes) name-list kex_algorithms name-list server_host_key_algorithms name-list encryption_algorithms_client_to_server name-list encryption_algorithms_server_to_client name-list mac_algorithms_client_to_server name-list mac_algorithms_server_to_client name-list compression_algorithms_client_to_server name-list compression_algorithms_server_to_client name-list languages_client_to_server name-list languages_server_to_client boolean first_kex_packet_follows uint32 0 (reserved for future extension) */ var init = { algorithms: { kex: undefined, srvHostKey: undefined, cs: { encrypt: undefined, mac: undefined, compress: undefined }, sc: { encrypt: undefined, mac: undefined, compress: undefined } }, languages: { cs: undefined, sc: undefined } }; var val; val = readList(payload, 17, self, callback); if (val === false) return false; init.algorithms.kex = val; val = readList(payload, payload._pos, self, callback); if (val === false) return false; init.algorithms.srvHostKey = val; val = readList(payload, payload._pos, self, callback); if (val === false) return false; init.algorithms.cs.encrypt = val; val = readList(payload, payload._pos, self, callback); if (val === false) return false; init.algorithms.sc.encrypt = val; val = readList(payload, payload._pos, self, callback); if (val === false) return false; init.algorithms.cs.mac = val; val = readList(payload, payload._pos, self, callback); if (val === false) return false; init.algorithms.sc.mac = val; val = readList(payload, payload._pos, self, callback); if (val === false) return false; init.algorithms.cs.compress = val; val = readList(payload, payload._pos, self, callback); if (val === false) return false; init.algorithms.sc.compress = val; val = readList(payload, payload._pos, self, callback); if (val === false) return false; init.languages.cs = val; val = readList(payload, payload._pos, self, callback); if (val === false) return false; init.languages.sc = val; var firstFollows = (payload._pos < payload.length && payload[payload._pos] === 1); instate.kexinit = payload; self.emit('KEXINIT', init, firstFollows); } function parse_KEX(self, type, callback) { var state = self._state; var instate = state.incoming; var payload = instate.payload; if (state.outgoing.status === OUT_READY || getPacketType(self, type) !== instate.expectedPacket) { self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, expected: ' + instate.expectedPacket + ' but got: ' + getPacketType(self, type)); self.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); var err = new Error('Received unexpected packet'); err.level = 'protocol'; self.emit('error', err); return false; } if (state.kex.type === 'groupex') { // Dynamic group exchange-related if (self.server) { // TODO: Support group exchange server-side self.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); var err = new Error('DH group exchange not supported by server'); err.level = 'handshake'; self.emit('error', err); return false; } else { if (type === MESSAGE.KEXDH_GEX_GROUP) { /* byte SSH_MSG_KEX_DH_GEX_GROUP mpint p, safe prime mpint g, generator for subgroup in GF(p) */ var prime = readString(payload, 1, self, callback); if (prime === false) return false; var gen = readString(payload, payload._pos, self, callback); if (gen === false) return false; self.emit('KEXDH_GEX_GROUP', prime, gen); } else if (type === MESSAGE.KEXDH_GEX_REPLY) return parse_KEXDH_REPLY(self, callback); } } else { // Static group or ECDH-related if (type === MESSAGE.KEXDH_INIT) { /* byte SSH_MSG_KEXDH_INIT mpint e */ var e = readString(payload, 1, self, callback); if (e === false) return false; self.emit('KEXDH_INIT', e); } else if (type === MESSAGE.KEXDH_REPLY) return parse_KEXDH_REPLY(self, callback); } } function parse_KEXDH_REPLY(self, callback) { var payload = self._state.incoming.payload; /* byte SSH_MSG_KEXDH_REPLY / SSH_MSG_KEX_DH_GEX_REPLY / SSH_MSG_KEX_ECDH_REPLY string server public host key and certificates (K_S) mpint f string signature of H */ var hostkey = readString(payload, 1, self, callback); if (hostkey === false) return false; var pubkey = readString(payload, payload._pos, self, callback); if (pubkey === false) return false; var sig = readString(payload, payload._pos, self, callback); if (sig === false) return false; var info = { hostkey: hostkey, hostkey_format: undefined, pubkey: pubkey, sig: sig, sig_format: undefined }; var hostkey_format = readString(hostkey, 0, 'ascii', self, callback); if (hostkey_format === false) return false; info.hostkey_format = hostkey_format; var sig_format = readString(sig, 0, 'ascii', self, callback); if (sig_format === false) return false; info.sig_format = sig_format; self.emit('KEXDH_REPLY', info); } function parse_USERAUTH(self, type, callback) { var state = self._state; var authMethod = state.authsQueue[0]; var payload = state.incoming.payload; var message; var lang; var text; if (authMethod === 'password') { if (type === MESSAGE.USERAUTH_PASSWD_CHANGEREQ) { /* byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ string prompt in ISO-10646 UTF-8 encoding string language tag */ message = readString(payload, 1, 'utf8', self, callback); if (message === false) return false; lang = readString(payload, payload._pos, 'utf8', self, callback); if (lang === false) return false; self.emit('USERAUTH_PASSWD_CHANGEREQ', message, lang); } } else if (authMethod === 'keyboard-interactive') { if (type === MESSAGE.USERAUTH_INFO_REQUEST) { /* byte SSH_MSG_USERAUTH_INFO_REQUEST string name (ISO-10646 UTF-8) string instruction (ISO-10646 UTF-8) string language tag -- MAY be empty int num-prompts string prompt[1] (ISO-10646 UTF-8) boolean echo[1] ... string prompt[num-prompts] (ISO-10646 UTF-8) boolean echo[num-prompts] */ var name; var instr; var nprompts; name = readString(payload, 1, 'utf8', self, callback); if (name === false) return false; instr = readString(payload, payload._pos, 'utf8', self, callback); if (instr === false) return false; lang = readString(payload, payload._pos, 'utf8', self, callback); if (lang === false) return false; nprompts = readInt(payload, payload._pos, self, callback); if (nprompts === false) return false; payload._pos += 4; var prompts = []; for (var prompt = 0; prompt < nprompts; ++prompt) { text = readString(payload, payload._pos, 'utf8', self, callback); if (text === false) return false; var echo = payload[payload._pos++]; if (echo === undefined) return false; echo = (echo !== 0); prompts.push({ prompt: text, echo: echo }); } self.emit('USERAUTH_INFO_REQUEST', name, instr, lang, prompts); } else if (type === MESSAGE.USERAUTH_INFO_RESPONSE) { /* byte SSH_MSG_USERAUTH_INFO_RESPONSE int num-responses string response[1] (ISO-10646 UTF-8) ... string response[num-responses] (ISO-10646 UTF-8) */ var nresponses = readInt(payload, 1, self, callback); if (nresponses === false) return false; payload._pos = 5; var responses = []; for (var response = 0; response < nresponses; ++response) { text = readString(payload, payload._pos, 'utf8', self, callback); if (text === false) return false; responses.push(text); } self.emit('USERAUTH_INFO_RESPONSE', responses); } } else if (authMethod === 'publickey') { if (type === MESSAGE.USERAUTH_PK_OK) { /* byte SSH_MSG_USERAUTH_PK_OK string public key algorithm name from the request string public key blob from the request */ var authsQueue = self._state.authsQueue; if (!authsQueue.length || authsQueue[0] !== 'publickey') return; authsQueue.shift(); self.emit('USERAUTH_PK_OK'); // XXX: Parse public key info? client currently can ignore it because // there is only one outstanding auth request at any given time, so it // knows which key was OK'd } } else if (authMethod !== undefined) { // Invalid packet for this auth type self.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); var err = new Error('Invalid authentication method: ' + authMethod); err.level = 'protocol'; self.emit('error', err); } } function parse_CHANNEL_REQUEST(self, callback) { var payload = self._state.incoming.payload; var info; var cols; var rows; var width; var height; var wantReply; var signal; var recipient = readInt(payload, 1, self, callback); if (recipient === false) return false; var request = readString(payload, 5, 'ascii', self, callback); if (request === false) return false; if (request === 'exit-status') { // Server->Client /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "exit-status" boolean FALSE uint32 exit_status */ var code = readInt(payload, ++payload._pos, self, callback); if (code === false) return false; info = { recipient: recipient, request: request, wantReply: false, code: code }; } else if (request === 'exit-signal') { // Server->Client /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "exit-signal" boolean FALSE string signal name (without the "SIG" prefix) boolean core dumped string error message in ISO-10646 UTF-8 encoding string language tag */ var coredump; if (!(self.remoteBugs & BUGS.OLD_EXIT)) { signal = readString(payload, ++payload._pos, 'ascii', self, callback); if (signal === false) return false; coredump = payload[payload._pos++]; if (coredump === undefined) return false; coredump = (coredump !== 0); } else { /* Instead of `signal name` and `core dumped`, we have just: uint32 signal number */ signal = readInt(payload, ++payload._pos, self, callback); if (signal === false) return false; switch (signal) { case 1: signal = 'HUP'; break; case 2: signal = 'INT'; break; case 3: signal = 'QUIT'; break; case 6: signal = 'ABRT'; break; case 9: signal = 'KILL'; break; case 14: signal = 'ALRM'; break; case 15: signal = 'TERM'; break; default: // Unknown or OS-specific signal = 'UNKNOWN (' + signal + ')'; } coredump = false; } var description = readString(payload, payload._pos, 'utf8', self, callback); if (description === false) return false; var lang = readString(payload, payload._pos, 'utf8', self, callback); if (lang === false) return false; info = { recipient: recipient, request: request, wantReply: false, signal: signal, coredump: coredump, description: description, lang: lang }; } else if (request === 'pty-req') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "pty-req" boolean want_reply string TERM environment variable value (e.g., vt100) uint32 terminal width, characters (e.g., 80) uint32 terminal height, rows (e.g., 24) uint32 terminal width, pixels (e.g., 640) uint32 terminal height, pixels (e.g., 480) string encoded terminal modes */ wantReply = payload[payload._pos++]; if (wantReply === undefined) return false; wantReply = (wantReply !== 0); var term = readString(payload, payload._pos, 'ascii', self, callback); if (term === false) return false; cols = readInt(payload, payload._pos, self, callback); if (cols === false) return false; rows = readInt(payload, payload._pos += 4, self, callback); if (rows === false) return false; width = readInt(payload, payload._pos += 4, self, callback); if (width === false) return false; height = readInt(payload, payload._pos += 4, self, callback); if (height === false) return false; var modes = readString(payload, payload._pos += 4, self, callback); if (modes === false) return false; modes = bytesToModes(modes); info = { recipient: recipient, request: request, wantReply: wantReply, term: term, cols: cols, rows: rows, width: width, height: height, modes: modes }; } else if (request === 'window-change') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "window-change" boolean FALSE uint32 terminal width, columns uint32 terminal height, rows uint32 terminal width, pixels uint32 terminal height, pixels */ cols = readInt(payload, ++payload._pos, self, callback); if (cols === false) return false; rows = readInt(payload, payload._pos += 4, self, callback); if (rows === false) return false; width = readInt(payload, payload._pos += 4, self, callback); if (width === false) return false; height = readInt(payload, payload._pos += 4, self, callback); if (height === false) return false; info = { recipient: recipient, request: request, wantReply: false, cols: cols, rows: rows, width: width, height: height }; } else if (request === 'x11-req') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "x11-req" boolean want reply boolean single connection string x11 authentication protocol string x11 authentication cookie uint32 x11 screen number */ wantReply = payload[payload._pos++]; if (wantReply === undefined) return false; wantReply = (wantReply !== 0); var single = payload[payload._pos++]; if (single === undefined) return false; single = (single !== 0); var protocol = readString(payload, payload._pos, 'ascii', self, callback); if (protocol === false) return false; var cookie = readString(payload, payload._pos, 'binary', self, callback); if (cookie === false) return false; var screen = readInt(payload, payload._pos, self, callback); if (screen === false) return false; info = { recipient: recipient, request: request, wantReply: wantReply, single: single, protocol: protocol, cookie: cookie, screen: screen }; } else if (request === 'env') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "env" boolean want reply string variable name string variable value */ wantReply = payload[payload._pos++]; if (wantReply === undefined) return false; wantReply = (wantReply !== 0); var key = readString(payload, payload._pos, 'utf8', self, callback); if (key === false) return false; var val = readString(payload, payload._pos, 'utf8', self, callback); if (val === false) return false; info = { recipient: recipient, request: request, wantReply: wantReply, key: key, val: val }; } else if (request === 'shell') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "shell" boolean want reply */ wantReply = payload[payload._pos]; if (wantReply === undefined) return false; wantReply = (wantReply !== 0); info = { recipient: recipient, request: request, wantReply: wantReply }; } else if (request === 'exec') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "exec" boolean want reply string command */ wantReply = payload[payload._pos++]; if (wantReply === undefined) return false; wantReply = (wantReply !== 0); var command = readString(payload, payload._pos, 'utf8', self, callback); if (command === false) return false; info = { recipient: recipient, request: request, wantReply: wantReply, command: command }; } else if (request === 'subsystem') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "subsystem" boolean want reply string subsystem name */ wantReply = payload[payload._pos++]; if (wantReply === undefined) return false; wantReply = (wantReply !== 0); var subsystem = readString(payload, payload._pos, 'utf8', self, callback); if (subsystem === false) return false; info = { recipient: recipient, request: request, wantReply: wantReply, subsystem: subsystem }; } else if (request === 'signal') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "signal" boolean FALSE string signal name (without the "SIG" prefix) */ signal = readString(payload, ++payload._pos, 'ascii', self, callback); if (signal === false) return false; info = { recipient: recipient, request: request, wantReply: false, signal: 'SIG' + signal }; } else if (request === 'xon-xoff') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "xon-xoff" boolean FALSE boolean client can do */ var clientControl = payload[++payload._pos]; if (clientControl === undefined) return false; clientControl = (clientControl !== 0); info = { recipient: recipient, request: request, wantReply: false, clientControl: clientControl }; } else if (request === 'auth-agent-req@openssh.com') { // Client->Server /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string "auth-agent-req@openssh.com" boolean want reply */ wantReply = payload[payload._pos]; if (wantReply === undefined) return false; wantReply = (wantReply !== 0); info = { recipient: recipient, request: request, wantReply: wantReply }; } else { // Unknown request type wantReply = payload[payload._pos]; if (wantReply === undefined) return false; wantReply = (wantReply !== 0); info = { recipient: recipient, request: request, wantReply: wantReply }; } self.debug('DEBUG: Parser: IN_PACKETDATAAFTER, packet: CHANNEL_REQUEST (' + recipient + ', ' + request + ')'); self.emit('CHANNEL_REQUEST:' + recipient, info); } function hmacVerify(self, data) { var instate = self._state.incoming; var hmac = instate.hmac; self.debug('DEBUG: Parser: Verifying MAC'); if (instate.decrypt.info.authLen > 0) { var decrypt = instate.decrypt; var instance = decrypt.instance; instance.setAuthTag(data); var payload = instance.update(instate.packet); instate.payload = payload.slice(1, instate.packet.length - payload[0]); iv_inc(decrypt.iv); decrypt.instance = crypto.createDecipheriv( SSH_TO_OPENSSL[decrypt.type], decrypt.key, decrypt.iv ); decrypt.instance.setAutoPadding(false); return true; } else { var calcHmac = crypto.createHmac(SSH_TO_OPENSSL[hmac.type], hmac.key); writeUInt32BE(HMAC_COMPUTE, instate.seqno, 0); writeUInt32BE(HMAC_COMPUTE, instate.pktLen, 4); HMAC_COMPUTE[8] = instate.padLen; calcHmac.update(HMAC_COMPUTE); calcHmac.update(instate.packet); var mac = calcHmac.digest(); if (mac.length > instate.hmac.info.actualLen) mac = mac.slice(0, instate.hmac.info.actualLen); return timingSafeEqual(mac, data); } } function decryptData(self, data) { var instance = self._state.incoming.decrypt.instance; self.debug('DEBUG: Parser: Decrypting'); return instance.update(data); } function expectData(self, type, amount, buffer) { var expect = self._state.incoming.expect; expect.amount = amount; expect.type = type; expect.ptr = 0; if (buffer) expect.buf = buffer; else if (amount) expect.buf = Buffer.allocUnsafe(amount); } function readList(buffer, start, stream, callback) { var list = readString(buffer, start, 'ascii', stream, callback); return (list !== false ? (list.length ? list.split(',') : []) : false); } function bytesToModes(buffer) { var modes = {}; for (var i = 0, len = buffer.length, opcode; i < len; i += 5) { opcode = buffer[i]; if (opcode === TERMINAL_MODE.TTY_OP_END || TERMINAL_MODE[opcode] === undefined || i + 5 > len) break; modes[TERMINAL_MODE[opcode]] = readUInt32BE(buffer, i + 1); } return modes; } function modesToBytes(modes) { var RE_IS_NUM = /^\d+$/; var keys = Object.keys(modes); var b = 0; var bytes = []; for (var i = 0, len = keys.length, key, opcode, val; i < len; ++i) { key = keys[i]; opcode = TERMINAL_MODE[key]; if (opcode && !RE_IS_NUM.test(key) && typeof modes[key] === 'number' && key !== 'TTY_OP_END') { val = modes[key]; bytes[b++] = opcode; bytes[b++] = (val >>> 24) & 0xFF; bytes[b++] = (val >>> 16) & 0xFF; bytes[b++] = (val >>> 8) & 0xFF; bytes[b++] = val & 0xFF; } } bytes[b] = TERMINAL_MODE.TTY_OP_END; return bytes; } // Shared outgoing functions function KEXINIT(self, cb) { // Client/Server randBytes(16, function(myCookie) { /* byte SSH_MSG_KEXINIT byte[16] cookie (random bytes) name-list kex_algorithms name-list server_host_key_algorithms name-list encryption_algorithms_client_to_server name-list encryption_algorithms_server_to_client name-list mac_algorithms_client_to_server name-list mac_algorithms_server_to_client name-list compression_algorithms_client_to_server name-list compression_algorithms_server_to_client name-list languages_client_to_server name-list languages_server_to_client boolean first_kex_packet_follows uint32 0 (reserved for future extension) */ var algos = self.config.algorithms; var kexBuf = algos.kexBuf; if (self.remoteBugs & BUGS.BAD_DHGEX) { var copied = false; var kexList = algos.kex; for (var j = kexList.length - 1; j >= 0; --j) { if (kexList[j].indexOf('group-exchange') !== -1) { if (!copied) { kexList = kexList.slice(); copied = true; } kexList.splice(j, 1); } } if (copied) kexBuf = Buffer.from(kexList.join(',')); } var hostKeyBuf = algos.serverHostKeyBuf; var kexInitSize = 1 + 16 + 4 + kexBuf.length + 4 + hostKeyBuf.length + (2 * (4 + algos.cipherBuf.length)) + (2 * (4 + algos.hmacBuf.length)) + (2 * (4 + algos.compressBuf.length)) + (2 * (4 /* languages skipped */)) + 1 + 4; var buf = Buffer.allocUnsafe(kexInitSize); var p = 17; buf[0] = MESSAGE.KEXINIT; if (myCookie !== false) myCookie.copy(buf, 1); writeUInt32BE(buf, kexBuf.length, p); p += 4; kexBuf.copy(buf, p); p += kexBuf.length; writeUInt32BE(buf, hostKeyBuf.length, p); p += 4; hostKeyBuf.copy(buf, p); p += hostKeyBuf.length; writeUInt32BE(buf, algos.cipherBuf.length, p); p += 4; algos.cipherBuf.copy(buf, p); p += algos.cipherBuf.length; writeUInt32BE(buf, algos.cipherBuf.length, p); p += 4; algos.cipherBuf.copy(buf, p); p += algos.cipherBuf.length; writeUInt32BE(buf, algos.hmacBuf.length, p); p += 4; algos.hmacBuf.copy(buf, p); p += algos.hmacBuf.length; writeUInt32BE(buf, algos.hmacBuf.length, p); p += 4; algos.hmacBuf.copy(buf, p); p += algos.hmacBuf.length; writeUInt32BE(buf, algos.compressBuf.length, p); p += 4; algos.compressBuf.copy(buf, p); p += algos.compressBuf.length; writeUInt32BE(buf, algos.compressBuf.length, p); p += 4; algos.compressBuf.copy(buf, p); p += algos.compressBuf.length; // Skip language lists, first_kex_packet_follows, and reserved bytes buf.fill(0, buf.length - 13); self.debug('DEBUG: Outgoing: Writing KEXINIT'); self._state.incoming.expectedPacket = 'KEXINIT'; var outstate = self._state.outgoing; outstate.kexinit = buf; if (outstate.status === OUT_READY) { // We are the one starting the rekeying process ... outstate.status = OUT_REKEYING; } send(self, buf, cb, true); }); return true; } function KEXDH_INIT(self) { // Client var state = self._state; var outstate = state.outgoing; var buf = Buffer.allocUnsafe(1 + 4 + outstate.pubkey.length); state.incoming.expectedPacket = state.kex.pktReply; if (state.kex.type === 'groupex') { buf[0] = MESSAGE.KEXDH_GEX_INIT; self.debug('DEBUG: Outgoing: Writing KEXDH_GEX_INIT'); } else { buf[0] = MESSAGE.KEXDH_INIT; if (state.kex.type === 'group') self.debug('DEBUG: Outgoing: Writing KEXDH_INIT'); else self.debug('DEBUG: Outgoing: Writing KEXECDH_INIT'); } writeUInt32BE(buf, outstate.pubkey.length, 1); outstate.pubkey.copy(buf, 5); return send(self, buf, undefined, true); } function KEXDH_REPLY(self, e) { // Server var state = self._state; var outstate = state.outgoing; var instate = state.incoming; var curHostKey = self.config.hostKeys[state.hostkeyFormat]; if (Array.isArray(curHostKey)) curHostKey = curHostKey[0]; var hostkey = curHostKey.getPublicSSH(); var hostkeyAlgo = curHostKey.type; // e === client DH public key e = state.kex.convertPublicKey(e); var secret = state.kex.computeSecret(e); if (secret instanceof Error) { secret.message = 'Error while computing DH secret (' + state.kex.type + '): ' + secret.message; secret.level = 'handshake'; self.emit('error', secret); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } var hash = crypto.createHash(state.kex.hash); var len_ident = Buffer.byteLength(instate.identRaw); var len_sident = Buffer.byteLength(self.config.ident); var len_init = instate.kexinit.length; var len_sinit = outstate.kexinit.length; var len_hostkey = hostkey.length; var len_pubkey = e.length; var len_spubkey = outstate.pubkey.length; var len_secret = secret.length; var exchangeBufLen = len_ident + len_sident + len_init + len_sinit + len_hostkey + len_pubkey + len_spubkey + len_secret + (4 * 8); // Length fields for above values // Group exchange-related var len_gex_prime; var len_gex_gen; var gex_prime; var gex_gen; var dhParams = state.kex.getDHParams(); if (dhParams) { gex_prime = dhParams.prime; gex_gen = dhParams.generator; len_gex_prime = gex_prime.length; len_gex_gen = gex_gen.length; exchangeBufLen += (4 * 3); // min, n, max values exchangeBufLen += (4 * 2); // prime, generator length fields exchangeBufLen += len_gex_prime; exchangeBufLen += len_gex_gen; } var bp = 0; var exchangeBuf = Buffer.allocUnsafe(exchangeBufLen); writeUInt32BE(exchangeBuf, len_ident, bp); bp += 4; exchangeBuf.write(instate.identRaw, bp, 'utf8'); // V_C bp += len_ident; writeUInt32BE(exchangeBuf, len_sident, bp); bp += 4; exchangeBuf.write(self.config.ident, bp, 'utf8'); // V_S bp += len_sident; writeUInt32BE(exchangeBuf, len_init, bp); bp += 4; instate.kexinit.copy(exchangeBuf, bp); // I_C bp += len_init; instate.kexinit = undefined; writeUInt32BE(exchangeBuf, len_sinit, bp); bp += 4; outstate.kexinit.copy(exchangeBuf, bp); // I_S bp += len_sinit; outstate.kexinit = undefined; writeUInt32BE(exchangeBuf, len_hostkey, bp); bp += 4; hostkey.copy(exchangeBuf, bp); // K_S bp += len_hostkey; if (dhParams) { KEXDH_GEX_REQ_PACKET.slice(1).copy(exchangeBuf, bp); // min, n, max bp += (4 * 3); // Skip over bytes just copied writeUInt32BE(exchangeBuf, len_gex_prime, bp); bp += 4; gex_prime.copy(exchangeBuf, bp); // p bp += len_gex_prime; writeUInt32BE(exchangeBuf, len_gex_gen, bp); bp += 4; gex_gen.copy(exchangeBuf, bp); // g bp += len_gex_gen; } writeUInt32BE(exchangeBuf, len_pubkey, bp); bp += 4; e.copy(exchangeBuf, bp); // e bp += len_pubkey; writeUInt32BE(exchangeBuf, len_spubkey, bp); bp += 4; outstate.pubkey.copy(exchangeBuf, bp); // f bp += len_spubkey; writeUInt32BE(exchangeBuf, len_secret, bp); bp += 4; secret.copy(exchangeBuf, bp); // K outstate.exchangeHash = hash.update(exchangeBuf).digest(); // H if (outstate.sessionId === undefined) outstate.sessionId = outstate.exchangeHash; outstate.kexsecret = secret; var signature = curHostKey.sign(outstate.exchangeHash); if (signature instanceof Error) { signature.message = 'Error while signing data with host key (' + hostkeyAlgo + '): ' + signature.message; signature.level = 'handshake'; self.emit('error', signature); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } signature = convertSignature(signature, hostkeyAlgo); if (signature === false) { signature.message = 'Error while converting handshake signature'; signature.level = 'handshake'; self.emit('error', signature); self.disconnect(DISCONNECT_REASON.KEY_EXCHANGE_FAILED); return false; } /* byte SSH_MSG_KEXDH_REPLY string server public host key and certificates (K_S) mpint f string signature of H */ var siglen = 4 + hostkeyAlgo.length + 4 + signature.length; var buf = Buffer.allocUnsafe(1 + 4 + len_hostkey + 4 + len_spubkey + 4 + siglen); bp = 0; buf[bp] = MESSAGE[state.kex.pktReply]; ++bp; writeUInt32BE(buf, len_hostkey, bp); bp += 4; hostkey.copy(buf, bp); // K_S bp += len_hostkey; writeUInt32BE(buf, len_spubkey, bp); bp += 4; outstate.pubkey.copy(buf, bp); // f bp += len_spubkey; writeUInt32BE(buf, siglen, bp); bp += 4; writeUInt32BE(buf, hostkeyAlgo.length, bp); bp += 4; buf.write(hostkeyAlgo, bp, hostkeyAlgo.length, 'ascii'); bp += hostkeyAlgo.length; writeUInt32BE(buf, signature.length, bp); bp += 4; signature.copy(buf, bp); state.incoming.expectedPacket = 'NEWKEYS'; self.debug('DEBUG: Outgoing: Writing ' + state.kex.pktReply); send(self, buf, undefined, true); outstate.sentNEWKEYS = true; self.debug('DEBUG: Outgoing: Writing NEWKEYS'); return send(self, NEWKEYS_PACKET, undefined, true); } function KEXDH_GEX_REQ(self) { // Client self._state.incoming.expectedPacket = 'KEXDH_GEX_GROUP'; self.debug('DEBUG: Outgoing: Writing KEXDH_GEX_REQUEST'); return send(self, KEXDH_GEX_REQ_PACKET, undefined, true); } function compressPayload(self, payload, cb) { var compress = self._state.outgoing.compress.instance; compress.write(payload); compress.flush(Z_PARTIAL_FLUSH, compressFlushCb.bind(self, cb)); } function compressFlushCb(cb) { if (this._readableState.ended || this._writableState.ended) return; send_(this, this._state.outgoing.compress.instance.read(), cb); var queue = this._state.outgoing.compress.queue; queue.shift(); if (queue.length > 0) compressPayload(this, queue[0][0], queue[0][1]); } function send(self, payload, cb, bypass) { var state = self._state; if (!state) return false; var outstate = state.outgoing; if (outstate.status === OUT_REKEYING && !bypass) { if (typeof cb === 'function') outstate.rekeyQueue.push([payload, cb]); else outstate.rekeyQueue.push(payload); return false; } else if (self._readableState.ended || self._writableState.ended) { return false; } if (outstate.compress.instance) { // This queue nonsense only exists because of a change made in node v10.12.0 // that changed flushing behavior, which now coalesces multiple writes to a // single flush, which does not work for us. var queue = outstate.compress.queue; queue.push([payload, cb]); if (queue.length === 1) compressPayload(self, queue[0][0], queue[0][1]); return true; } else { return send_(self, payload, cb); } } function send_(self, payload, cb) { // TODO: Implement length checks var state = self._state; var outstate = state.outgoing; var encrypt = outstate.encrypt; var hmac = outstate.hmac; var pktLen; var padLen; var buf; var mac; var ret; pktLen = payload.length + 9; if (encrypt.instance !== false) { if (encrypt.info.authLen > 0) { var ptlen = 1 + payload.length + 4/* Must have at least 4 bytes padding*/; while ((ptlen % encrypt.info.blockLen) !== 0) ++ptlen; padLen = ptlen - 1 - payload.length; pktLen = 4 + ptlen; } else { var blockLen = encrypt.info.blockLen; pktLen += ((blockLen - 1) * pktLen) % blockLen; padLen = pktLen - payload.length - 5; } } else { pktLen += (7 * pktLen) % 8; padLen = pktLen - payload.length - 5; } buf = Buffer.allocUnsafe(pktLen); writeUInt32BE(buf, pktLen - 4, 0); buf[4] = padLen; payload.copy(buf, 5); copyRandPadBytes(buf, 5 + payload.length, padLen); if (hmac.type !== false && hmac.key) { mac = crypto.createHmac(SSH_TO_OPENSSL[hmac.type], hmac.key); writeUInt32BE(outstate.bufSeqno, outstate.seqno, 0); mac.update(outstate.bufSeqno); mac.update(buf); mac = mac.digest(); if (mac.length > hmac.info.actualLen) mac = mac.slice(0, hmac.info.actualLen); } var nb = 0; var encData; if (encrypt.instance !== false) { if (encrypt.info.authLen > 0) { var encrypter = crypto.createCipheriv(SSH_TO_OPENSSL[encrypt.type], encrypt.key, encrypt.iv); encrypter.setAutoPadding(false); var lenbuf = buf.slice(0, 4); encrypter.setAAD(lenbuf); self.push(lenbuf); nb += lenbuf; encData = encrypter.update(buf.slice(4)); self.push(encData); nb += encData.length; var final = encrypter.final(); if (final.length) { self.push(final); nb += final.length; } var authTag = encrypter.getAuthTag(); ret = self.push(authTag); nb += authTag.length; iv_inc(encrypt.iv); } else { encData = encrypt.instance.update(buf); self.push(encData); nb += encData.length; ret = self.push(mac); nb += mac.length; } } else { ret = self.push(buf); nb = buf.length; } self.bytesSent += nb; if (++outstate.seqno > MAX_SEQNO) outstate.seqno = 0; cb && cb(); return ret; } var copyRandPadBytes = (function() { if (typeof crypto.randomFillSync === 'function') { return crypto.randomFillSync; } else { return function copyRandPadBytes(buf, offset, count) { var padBytes = crypto.randomBytes(count); padBytes.copy(buf, offset); }; } })(); function randBytes(n, cb) { crypto.randomBytes(n, function retry(err, buf) { if (err) return crypto.randomBytes(n, retry); cb && cb(buf); }); } function convertSignature(signature, keyType) { switch (keyType) { case 'ssh-dss': return DSASigBERToBare(signature); case 'ecdsa-sha2-nistp256': case 'ecdsa-sha2-nistp384': case 'ecdsa-sha2-nistp521': return ECDSASigASN1ToSSH(signature); } return signature; } var timingSafeEqual = (function() { if (typeof crypto.timingSafeEqual === 'function') { return function timingSafeEquals(a, b) { if (a.length !== b.length) { crypto.timingSafeEqual(a, a); return false; } else { return crypto.timingSafeEqual(a, b); } }; } else { return function timingSafeEquals(a, b) { var val; if (a.length === b.length) { val = 0; } else { val = 1; b = a; } for (var i = 0, len = a.length; i < len; ++i) val |= (a[i] ^ b[i]); return (val === 0); } } })(); function KeyExchange(algo, options) { switch (algo) { case 'curve25519-sha256': case 'curve25519-sha256@libssh.org': if (!CURVE25519_SUPPORTED) break; this.type = '25519'; this.hash = 'sha256'; this.pktInit = 'KEXECDH_INIT'; this.pktReply = 'KEXECDH_REPLY'; return; case 'ecdh-sha2-nistp256': this.type = 'ecdh'; this.name = 'prime256v1'; this.hash = 'sha256'; this.pktInit = 'KEXECDH_INIT'; this.pktReply = 'KEXECDH_REPLY'; return; case 'ecdh-sha2-nistp384': this.type = 'ecdh'; this.name = 'secp384r1'; this.hash = 'sha384'; this.pktInit = 'KEXECDH_INIT'; this.pktReply = 'KEXECDH_REPLY'; return; case 'ecdh-sha2-nistp521': this.type = 'ecdh'; this.name = 'secp521r1'; this.hash = 'sha512'; this.pktInit = 'KEXECDH_INIT'; this.pktReply = 'KEXECDH_REPLY'; return; case 'diffie-hellman-group1-sha1': this.type = 'group'; this.name = 'modp2'; this.hash = 'sha1'; this.pktInit = 'KEXDH_INIT'; this.pktReply = 'KEXDH_REPLY'; return; case 'diffie-hellman-group14-sha1': this.type = 'group'; this.name = 'modp14'; this.hash = 'sha1'; this.pktInit = 'KEXDH_INIT'; this.pktReply = 'KEXDH_REPLY'; return; case 'diffie-hellman-group14-sha256': this.type = 'group'; this.name = 'modp14'; this.hash = 'sha256'; this.pktInit = 'KEXDH_INIT'; this.pktReply = 'KEXDH_REPLY'; return; case 'diffie-hellman-group16-sha512': this.type = 'group'; this.name = 'modp16'; this.hash = 'sha512'; this.pktInit = 'KEXDH_INIT'; this.pktReply = 'KEXDH_REPLY'; return; case 'diffie-hellman-group18-sha512': this.type = 'group'; this.name = 'modp18'; this.hash = 'sha512'; this.pktInit = 'KEXDH_INIT'; this.pktReply = 'KEXDH_REPLY'; return; case 'diffie-hellman-group-exchange-sha1': this.type = 'groupex'; this.hash = 'sha1'; this.pktInit = 'KEXDH_GEX_REQ'; this.pktReply = 'KEXDH_GEX_REPLY'; this._prime = null; this._generator = null; return; case 'diffie-hellman-group-exchange-sha256': this.type = 'groupex'; this.hash = 'sha256'; this.pktInit = 'KEXDH_GEX_REQ'; this.pktReply = 'KEXDH_GEX_REPLY'; this._prime = null; this._generator = null; return; } throw new Error('Unsupported key exchange algorithm: ' + algo); } KeyExchange.prototype.setDHParams = function(prime, generator) { if (this.type === 'groupex') { if (!Buffer.isBuffer(prime)) throw new Error('Invalid prime value'); if (!Buffer.isBuffer(generator)) throw new Error('Invalid generator value'); this._prime = prime; this._generator = generator; } }; KeyExchange.prototype.getDHParams = function() { if (this.type === 'groupex' && this._kex) { return { prime: convertToMpint(this._kex.getPrime()), generator: convertToMpint(this._kex.getGenerator()), }; } }; KeyExchange.prototype.generateKeys = function() { switch (this.type) { case '25519': if (!this._keys) this._keys = crypto.generateKeyPairSync('x25519'); break; case 'ecdh': if (!this._kex) { this._kex = crypto.createECDH(this.name); this._public = this._kex.generateKeys(); } break; case 'group': case 'groupex': if (!this._kex) { if (this.name) this._kex = crypto.createDiffieHellmanGroup(this.name); else if (this._prime && this._generator) this._kex = crypto.createDiffieHellman(this._prime, this._generator); if (this._kex) this._public = this._kex.generateKeys(); } break; } }; KeyExchange.prototype.getPublicKey = function() { this.generateKeys(); var key; switch (this.type) { case '25519': key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); return key.slice(-32); // HACK: avoids parsing DER/BER header case 'ecdh': case 'group': case 'groupex': key = this._public; break; } if (key) return this.convertPublicKey(key); }; KeyExchange.prototype.convertPublicKey = function(key) { var newKey; var idx = 0; var len = key.length; while (key[idx] === 0x00) { ++idx; --len; } switch (this.type) { case '25519': if (key.length === 32) return key; break; default: if (key[idx] & 0x80) { newKey = Buffer.allocUnsafe(1 + len); newKey[0] = 0; key.copy(newKey, 1, idx); return newKey; } } if (len !== key.length) { newKey = Buffer.allocUnsafe(len); key.copy(newKey, 0, idx); key = newKey; } return key; }; KeyExchange.prototype.computeSecret = function(otherPublicKey) { this.generateKeys(); switch (this.type) { case '25519': try { var asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.3.101.110'); // id-X25519 asnWriter.endSequence(); // PublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(otherPublicKey.length); otherPublicKey.copy(asnWriter._buf, asnWriter._offset, 0, otherPublicKey.length); asnWriter._offset += otherPublicKey.length; asnWriter.endSequence(); asnWriter.endSequence(); return convertToMpint(crypto.diffieHellman({ privateKey: this._keys.privateKey, publicKey: crypto.createPublicKey({ key: asnWriter.buffer, type: 'spki', format: 'der', }), })); } catch (ex) { return ex; } break; case 'ecdh': case 'group': case 'groupex': try { return convertToMpint(this._kex.computeSecret(otherPublicKey)); } catch (ex) { return ex; } } }; function convertToMpint(buf) { var idx = 0; var length = buf.length; while (buf[idx] === 0x00) { ++idx; --length; } var newBuf; if (buf[idx] & 0x80) { newBuf = Buffer.allocUnsafe(1 + length); newBuf[0] = 0; buf.copy(newBuf, 1, idx); buf = newBuf; } else if (length !== buf.length) { newBuf = Buffer.allocUnsafe(length); buf.copy(newBuf, 0, idx); buf = newBuf; } return buf; } module.exports = SSH2Stream; module.exports._send = send; /***/ }), /***/ 2557: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var Ber = (__nccwpck_require__(9837).Ber); var readUInt32BE = (__nccwpck_require__(4288).readUInt32BE); var writeUInt32BE = (__nccwpck_require__(4288).writeUInt32BE); // XXX the value of 2400 from dropbear is only for certain strings, not all // strings. for example the list strings used during handshakes var MAX_STRING_LEN = Infinity;//2400; // taken from dropbear module.exports = { iv_inc: iv_inc, readInt: readInt, readString: readString, parseKey: (__nccwpck_require__(7044).parseKey), sigSSHToASN1: sigSSHToASN1, DSASigBERToBare: DSASigBERToBare, ECDSASigASN1ToSSH: ECDSASigASN1ToSSH }; function iv_inc(iv) { var n = 12; var c = 0; do { --n; c = iv[n]; if (c === 255) iv[n] = 0; else { iv[n] = ++c; return; } } while (n > 4); } function readInt(buffer, start, stream, cb) { var bufferLen = buffer.length; if (start < 0 || start >= bufferLen || (bufferLen - start) < 4) { stream && stream._cleanup(cb); return false; } return readUInt32BE(buffer, start); } function DSASigBERToBare(signature) { if (signature.length <= 40) return signature; // This is a quick and dirty way to get from BER encoded r and s that // OpenSSL gives us, to just the bare values back to back (40 bytes // total) like OpenSSH (and possibly others) are expecting var asnReader = new Ber.Reader(signature); asnReader.readSequence(); var r = asnReader.readString(Ber.Integer, true); var s = asnReader.readString(Ber.Integer, true); var rOffset = 0; var sOffset = 0; if (r.length < 20) { var rNew = Buffer.allocUnsafe(20); r.copy(rNew, 1); r = rNew; r[0] = 0; } if (s.length < 20) { var sNew = Buffer.allocUnsafe(20); s.copy(sNew, 1); s = sNew; s[0] = 0; } if (r.length > 20 && r[0] === 0x00) rOffset = 1; if (s.length > 20 && s[0] === 0x00) sOffset = 1; var newSig = Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); r.copy(newSig, 0, rOffset); s.copy(newSig, r.length - rOffset, sOffset); return newSig; } function ECDSASigASN1ToSSH(signature) { if (signature[0] === 0x00) return signature; // Convert SSH signature parameters to ASN.1 BER values for OpenSSL var asnReader = new Ber.Reader(signature); asnReader.readSequence(); var r = asnReader.readString(Ber.Integer, true); var s = asnReader.readString(Ber.Integer, true); if (r === null || s === null) return false; var newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); writeUInt32BE(newSig, r.length, 0); r.copy(newSig, 4); writeUInt32BE(newSig, s.length, 4 + r.length); s.copy(newSig, 4 + 4 + r.length); return newSig; } function sigSSHToASN1(sig, type, self, callback) { var asnWriter; switch (type) { case 'ssh-dss': if (sig.length > 40) return sig; // Change bare signature r and s values to ASN.1 BER values for OpenSSL asnWriter = new Ber.Writer(); asnWriter.startSequence(); var r = sig.slice(0, 20); var s = sig.slice(20); if (r[0] & 0x80) { var rNew = Buffer.allocUnsafe(21); rNew[0] = 0x00; r.copy(rNew, 1); r = rNew; } else if (r[0] === 0x00 && !(r[1] & 0x80)) { r = r.slice(1); } if (s[0] & 0x80) { var sNew = Buffer.allocUnsafe(21); sNew[0] = 0x00; s.copy(sNew, 1); s = sNew; } else if (s[0] === 0x00 && !(s[1] & 0x80)) { s = s.slice(1); } asnWriter.writeBuffer(r, Ber.Integer); asnWriter.writeBuffer(s, Ber.Integer); asnWriter.endSequence(); return asnWriter.buffer; case 'ecdsa-sha2-nistp256': case 'ecdsa-sha2-nistp384': case 'ecdsa-sha2-nistp521': var r = readString(sig, 0, self, callback); if (r === false) return false; var s = readString(sig, sig._pos, self, callback); if (s === false) return false; asnWriter = new Ber.Writer(); asnWriter.startSequence(); asnWriter.writeBuffer(r, Ber.Integer); asnWriter.writeBuffer(s, Ber.Integer); asnWriter.endSequence(); return asnWriter.buffer; default: return sig; } } function readString(buffer, start, encoding, stream, cb, maxLen) { if (encoding && !Buffer.isBuffer(encoding) && typeof encoding !== 'string') { if (typeof cb === 'number') maxLen = cb; cb = stream; stream = encoding; encoding = undefined; } start || (start = 0); var bufferLen = buffer.length; var left = (bufferLen - start); var len; var end; if (start < 0 || start >= bufferLen || left < 4) { stream && stream._cleanup(cb); return false; } len = readUInt32BE(buffer, start); if (len > (maxLen || MAX_STRING_LEN) || left < (4 + len)) { stream && stream._cleanup(cb); return false; } start += 4; end = start + len; buffer._pos = end; if (encoding) { if (Buffer.isBuffer(encoding)) { buffer.copy(encoding, 0, start, end); return encoding; } else { return buffer.toString(encoding, start, end); } } else { return buffer.slice(start, end); } } /***/ }), /***/ 5683: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Duplex: DuplexStream, Readable: ReadableStream, Writable: WritableStream, } = __nccwpck_require__(2203); const { CHANNEL_EXTENDED_DATATYPE: { STDERR }, } = __nccwpck_require__(4020); const { bufferSlice } = __nccwpck_require__(2184); const PACKET_SIZE = 32 * 1024; const MAX_WINDOW = 2 * 1024 * 1024; const WINDOW_THRESHOLD = MAX_WINDOW / 2; class ClientStderr extends ReadableStream { constructor(channel, streamOpts) { super(streamOpts); this._channel = channel; } _read(n) { if (this._channel._waitChanDrain) { this._channel._waitChanDrain = false; if (this._channel.incoming.window <= WINDOW_THRESHOLD) windowAdjust(this._channel); } } } class ServerStderr extends WritableStream { constructor(channel) { super({ highWaterMark: MAX_WINDOW }); this._channel = channel; } _write(data, encoding, cb) { const channel = this._channel; const protocol = channel._client._protocol; const outgoing = channel.outgoing; const packetSize = outgoing.packetSize; const id = outgoing.id; let window = outgoing.window; const len = data.length; let p = 0; if (outgoing.state !== 'open') return; while (len - p > 0 && window > 0) { let sliceLen = len - p; if (sliceLen > window) sliceLen = window; if (sliceLen > packetSize) sliceLen = packetSize; if (p === 0 && sliceLen === len) protocol.channelExtData(id, data, STDERR); else protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); p += sliceLen; window -= sliceLen; } outgoing.window = window; if (len - p > 0) { if (window === 0) channel._waitWindow = true; if (p > 0) channel._chunkErr = bufferSlice(data, p, len); else channel._chunkErr = data; channel._chunkcbErr = cb; return; } cb(); } } class Channel extends DuplexStream { constructor(client, info, opts) { const streamOpts = { highWaterMark: MAX_WINDOW, allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), emitClose: false, }; super(streamOpts); this.allowHalfOpen = streamOpts.allowHalfOpen; const server = !!(opts && opts.server); this.server = server; this.type = info.type; this.subtype = undefined; /* incoming and outgoing contain these properties: { id: undefined, window: undefined, packetSize: undefined, state: 'closed' } */ this.incoming = info.incoming; this.outgoing = info.outgoing; this._callbacks = []; this._client = client; this._hasX11 = false; this._exit = { code: undefined, signal: undefined, dump: undefined, desc: undefined, }; this.stdin = this.stdout = this; if (server) this.stderr = new ServerStderr(this); else this.stderr = new ClientStderr(this, streamOpts); // Outgoing data this._waitWindow = false; // SSH-level backpressure // Incoming data this._waitChanDrain = false; // Channel Readable side backpressure this._chunk = undefined; this._chunkcb = undefined; this._chunkErr = undefined; this._chunkcbErr = undefined; this.on('finish', onFinish) .on('prefinish', onFinish); // For node v0.11+ this.on('end', onEnd).on('close', onEnd); } _read(n) { if (this._waitChanDrain) { this._waitChanDrain = false; if (this.incoming.window <= WINDOW_THRESHOLD) windowAdjust(this); } } _write(data, encoding, cb) { const protocol = this._client._protocol; const outgoing = this.outgoing; const packetSize = outgoing.packetSize; const id = outgoing.id; let window = outgoing.window; const len = data.length; let p = 0; if (outgoing.state !== 'open') return; while (len - p > 0 && window > 0) { let sliceLen = len - p; if (sliceLen > window) sliceLen = window; if (sliceLen > packetSize) sliceLen = packetSize; if (p === 0 && sliceLen === len) protocol.channelData(id, data); else protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); p += sliceLen; window -= sliceLen; } outgoing.window = window; if (len - p > 0) { if (window === 0) this._waitWindow = true; if (p > 0) this._chunk = bufferSlice(data, p, len); else this._chunk = data; this._chunkcb = cb; return; } cb(); } eof() { if (this.outgoing.state === 'open') { this.outgoing.state = 'eof'; this._client._protocol.channelEOF(this.outgoing.id); } } close() { if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { this.outgoing.state = 'closing'; this._client._protocol.channelClose(this.outgoing.id); } } destroy() { this.end(); this.close(); return this; } // Session type-specific methods ============================================= setWindow(rows, cols, height, width) { if (this.server) throw new Error('Client-only method called in server mode'); if (this.type === 'session' && (this.subtype === 'shell' || this.subtype === 'exec') && this.writable && this.outgoing.state === 'open') { this._client._protocol.windowChange(this.outgoing.id, rows, cols, height, width); } } signal(signalName) { if (this.server) throw new Error('Client-only method called in server mode'); if (this.type === 'session' && this.writable && this.outgoing.state === 'open') { this._client._protocol.signal(this.outgoing.id, signalName); } } exit(statusOrSignal, coreDumped, msg) { if (!this.server) throw new Error('Server-only method called in client mode'); if (this.type === 'session' && this.writable && this.outgoing.state === 'open') { if (typeof statusOrSignal === 'number') { this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); } else { this._client._protocol.exitSignal(this.outgoing.id, statusOrSignal, coreDumped, msg); } } } } function onFinish() { this.eof(); if (this.server || !this.allowHalfOpen) this.close(); this.writable = false; } function onEnd() { this.readable = false; } function windowAdjust(self) { if (self.outgoing.state === 'closed') return; const amt = MAX_WINDOW - self.incoming.window; if (amt <= 0) return; self.incoming.window += amt; self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); } module.exports = { Channel, MAX_WINDOW, PACKET_SIZE, windowAdjust, WINDOW_THRESHOLD, }; /***/ }), /***/ 3849: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Socket } = __nccwpck_require__(9278); const { Duplex } = __nccwpck_require__(2203); const { resolve } = __nccwpck_require__(6928); const { readFile } = __nccwpck_require__(9896); const { execFile, spawn } = __nccwpck_require__(5317); const { isParsedKey, parseKey } = __nccwpck_require__(1789); const { makeBufferParser, readUInt32BE, writeUInt32BE, writeUInt32LE, } = __nccwpck_require__(2184); function once(cb) { let called = false; return (...args) => { if (called) return; called = true; cb(...args); }; } function concat(buf1, buf2) { const combined = Buffer.allocUnsafe(buf1.length + buf2.length); buf1.copy(combined, 0); buf2.copy(combined, buf1.length); return combined; } function noop() {} const EMPTY_BUF = Buffer.alloc(0); const binaryParser = makeBufferParser(); class BaseAgent { getIdentities(cb) { cb(new Error('Missing getIdentities() implementation')); } sign(pubKey, data, options, cb) { if (typeof options === 'function') cb = options; cb(new Error('Missing sign() implementation')); } } class OpenSSHAgent extends BaseAgent { constructor(socketPath) { super(); this.socketPath = socketPath; } getStream(cb) { cb = once(cb); const sock = new Socket(); sock.on('connect', () => { cb(null, sock); }); sock.on('close', onFail) .on('end', onFail) .on('error', onFail); sock.connect(this.socketPath); function onFail() { try { sock.destroy(); } catch {} cb(new Error('Failed to connect to agent')); } } getIdentities(cb) { cb = once(cb); this.getStream((err, stream) => { function onFail(err) { if (stream) { try { stream.destroy(); } catch {} } if (!err) err = new Error('Failed to retrieve identities from agent'); cb(err); } if (err) return onFail(err); const protocol = new AgentProtocol(true); protocol.on('error', onFail); protocol.pipe(stream).pipe(protocol); stream.on('close', onFail) .on('end', onFail) .on('error', onFail); protocol.getIdentities((err, keys) => { if (err) return onFail(err); try { stream.destroy(); } catch {} cb(null, keys); }); }); } sign(pubKey, data, options, cb) { if (typeof options === 'function') { cb = options; options = undefined; } else if (typeof options !== 'object' || options === null) { options = undefined; } cb = once(cb); this.getStream((err, stream) => { function onFail(err) { if (stream) { try { stream.destroy(); } catch {} } if (!err) err = new Error('Failed to sign data with agent'); cb(err); } if (err) return onFail(err); const protocol = new AgentProtocol(true); protocol.on('error', onFail); protocol.pipe(stream).pipe(protocol); stream.on('close', onFail) .on('end', onFail) .on('error', onFail); protocol.sign(pubKey, data, options, (err, sig) => { if (err) return onFail(err); try { stream.destroy(); } catch {} cb(null, sig); }); }); } } const PageantAgent = (() => { const RET_ERR_BADARGS = 10; const RET_ERR_UNAVAILABLE = 11; const RET_ERR_NOMAP = 12; const RET_ERR_BINSTDIN = 13; const RET_ERR_BINSTDOUT = 14; const RET_ERR_BADLEN = 15; const EXEPATH = __nccwpck_require__.ab + "pagent.exe"; const ERROR = { [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), [RET_ERR_BADLEN]: new Error('pagent.exe did not get expected input payload'), }; function destroy(stream) { stream.buffer = null; if (stream.proc) { stream.proc.kill(); stream.proc = undefined; } } class PageantSocket extends Duplex { constructor() { super(); this.proc = undefined; this.buffer = null; } _read(n) {} _write(data, encoding, cb) { if (this.buffer === null) { this.buffer = data; } else { const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); this.buffer.copy(newBuffer, 0); data.copy(newBuffer, this.buffer.length); this.buffer = newBuffer; } // Wait for at least all length bytes if (this.buffer.length < 4) return cb(); const len = readUInt32BE(this.buffer, 0); // Make sure we have a full message before querying pageant if ((this.buffer.length - 4) < len) return cb(); data = this.buffer.slice(0, 4 + len); if (this.buffer.length > (4 + len)) return cb(new Error('Unexpected multiple agent requests')); this.buffer = null; let error; const proc = this.proc = spawn(__nccwpck_require__.ab + "pagent.exe", [ data.length ]); proc.stdout.on('data', (data) => { this.push(data); }); proc.on('error', (err) => { error = err; cb(error); }); proc.on('close', (code) => { this.proc = undefined; if (!error) { if (error = ERROR[code]) return cb(error); cb(); } }); proc.stdin.end(data); } _final(cb) { destroy(this); cb(); } _destroy(err, cb) { destroy(this); cb(); } } return class PageantAgent extends OpenSSHAgent { getStream(cb) { cb(null, new PageantSocket()); } }; })(); const CygwinAgent = (() => { const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; return class CygwinAgent extends OpenSSHAgent { getStream(cb) { cb = once(cb); // The cygwin ssh-agent connection process looks like this: // 1. Read the "socket" as a file to get the underlying TCP port and a // special "secret" that must be sent to the TCP server. // 2. Connect to the server listening on localhost at the TCP port. // 3. Send the "secret" to the server. // 4. The server sends back the same "secret". // 5. Send three 32-bit integer values of zero. This is ordinarily the // pid, uid, and gid of this process, but cygwin will actually // send us the correct values as a response. // 6. The server sends back the pid, uid, gid. // 7. Disconnect. // 8. Repeat steps 2-6, except send the received pid, uid, and gid in // step 5 instead of zeroes. // 9. Connection is ready to be used. let socketPath = this.socketPath; let triedCygpath = false; readFile(socketPath, function readCygsocket(err, data) { if (err) { if (triedCygpath) return cb(new Error('Invalid cygwin unix socket path')); // Try using `cygpath` to convert a possible *nix-style path to the // real Windows path before giving up ... execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { if (err || stdout.length === 0) return cb(new Error('Invalid cygwin unix socket path')); triedCygpath = true; socketPath = stdout.toString().replace(/[\r\n]/g, ''); readFile(socketPath, readCygsocket); }); return; } const m = RE_CYGWIN_SOCK.exec(data.toString('ascii')); if (!m) return cb(new Error('Malformed cygwin unix socket file')); let state; let bc = 0; let isRetrying = false; const inBuf = []; let sock; // Use 0 for pid, uid, and gid to ensure we get an error and also // a valid uid and gid from cygwin so that we don't have to figure it // out ourselves let credsBuf = Buffer.alloc(12); // Parse cygwin unix socket file contents const port = parseInt(m[1], 10); const secret = m[2].replace(/-/g, ''); const secretBuf = Buffer.allocUnsafe(16); for (let i = 0, j = 0; j < 32; ++i, j += 2) secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); // Convert to host order (always LE for Windows) for (let i = 0; i < 16; i += 4) writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); tryConnect(); function _onconnect() { bc = 0; state = 'secret'; sock.write(secretBuf); } function _ondata(data) { bc += data.length; if (state === 'secret') { // The secret we sent is echoed back to us by cygwin, not sure of // the reason for that, but we ignore it nonetheless ... if (bc === 16) { bc = 0; state = 'creds'; sock.write(credsBuf); } return; } if (state === 'creds') { // If this is the first attempt, make sure to gather the valid // uid and gid for our next attempt if (!isRetrying) inBuf.push(data); if (bc === 12) { sock.removeListener('connect', _onconnect); sock.removeListener('data', _ondata); sock.removeListener('error', onFail); sock.removeListener('end', onFail); sock.removeListener('close', onFail); if (isRetrying) return cb(null, sock); isRetrying = true; credsBuf = Buffer.concat(inBuf); writeUInt32LE(credsBuf, process.pid, 0); sock.on('error', () => {}); sock.destroy(); tryConnect(); } } } function onFail() { cb(new Error('Problem negotiating cygwin unix socket security')); } function tryConnect() { sock = new Socket(); sock.on('connect', _onconnect); sock.on('data', _ondata); sock.on('error', onFail); sock.on('end', onFail); sock.on('close', onFail); sock.connect(port); } }); } }; })(); // Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes // being interchangeable const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; function createAgent(path) { if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { return (path === 'pageant' ? new PageantAgent() : new CygwinAgent(path)); } return new OpenSSHAgent(path); } const AgentProtocol = (() => { // Client->Server messages const SSH_AGENTC_REQUEST_IDENTITIES = 11; const SSH_AGENTC_SIGN_REQUEST = 13; // const SSH_AGENTC_ADD_IDENTITY = 17; // const SSH_AGENTC_REMOVE_IDENTITY = 18; // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; // const SSH_AGENTC_LOCK = 22; // const SSH_AGENTC_UNLOCK = 23; // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; // const SSH_AGENTC_EXTENSION = 27; // Server->Client messages const SSH_AGENT_FAILURE = 5; // const SSH_AGENT_SUCCESS = 6; const SSH_AGENT_IDENTITIES_ANSWER = 12; const SSH_AGENT_SIGN_RESPONSE = 14; // const SSH_AGENT_EXTENSION_FAILURE = 28; // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; const SSH_AGENT_RSA_SHA2_256 = (1 << 1); const SSH_AGENT_RSA_SHA2_512 = (1 << 2); const ROLE_CLIENT = 0; const ROLE_SERVER = 1; // Ensures that responses get sent back in the same order the requests were // received function processResponses(protocol) { let ret; while (protocol[SYM_REQS].length) { const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; if (nextResponse === undefined) break; protocol[SYM_REQS].shift(); ret = protocol.push(nextResponse); } return ret; } const SYM_TYPE = Symbol('Inbound Request Type'); const SYM_RESP = Symbol('Inbound Request Response'); const SYM_CTX = Symbol('Inbound Request Context'); class AgentInboundRequest { constructor(type, ctx) { this[SYM_TYPE] = type; this[SYM_RESP] = undefined; this[SYM_CTX] = ctx; } hasResponded() { return (this[SYM_RESP] !== undefined); } getType() { return this[SYM_TYPE]; } getContext() { return this[SYM_CTX]; } } function respond(protocol, req, data) { req[SYM_RESP] = data; return processResponses(protocol); } function cleanup(protocol) { protocol[SYM_BUFFER] = null; if (protocol[SYM_MODE] === ROLE_CLIENT) { const reqs = protocol[SYM_REQS]; if (reqs && reqs.length) { protocol[SYM_REQS] = []; for (const req of reqs) req.cb(new Error('No reply from server')); } } // Node streams hackery to make streams do the "right thing" try { protocol.end(); } catch {} setImmediate(() => { if (!protocol[SYM_ENDED]) protocol.emit('end'); if (!protocol[SYM_CLOSED]) protocol.emit('close'); }); } function onClose() { this[SYM_CLOSED] = true; } function onEnd() { this[SYM_ENDED] = true; } const SYM_REQS = Symbol('Requests'); const SYM_MODE = Symbol('Agent Protocol Role'); const SYM_BUFFER = Symbol('Agent Protocol Buffer'); const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); const SYM_CLOSED = Symbol('Agent Protocol Closed'); const SYM_ENDED = Symbol('Agent Protocol Ended'); // Implementation based on: // https://tools.ietf.org/html/draft-miller-ssh-agent-04 return class AgentProtocol extends Duplex { /* Notes: - `constraint` type consists of: byte constraint_type byte[] constraint_data where `constraint_type` is one of: * SSH_AGENT_CONSTRAIN_LIFETIME - `constraint_data` consists of: uint32 seconds * SSH_AGENT_CONSTRAIN_CONFIRM - `constraint_data` N/A * SSH_AGENT_CONSTRAIN_EXTENSION - `constraint_data` consists of: string extension name byte[] extension-specific details */ constructor(isClient) { super({ autoDestroy: true, emitClose: false }); this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); this[SYM_REQS] = []; this[SYM_BUFFER] = null; this[SYM_MSGLEN] = -1; this.once('end', onEnd); this.once('close', onClose); } _read(n) {} _write(data, encoding, cb) { /* Messages are of the format: uint32 message length byte message type byte[message length - 1] message contents */ if (this[SYM_BUFFER] === null) this[SYM_BUFFER] = data; else this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); let buffer = this[SYM_BUFFER]; let bufferLen = buffer.length; let p = 0; while (p < bufferLen) { // Wait for length + type if (bufferLen < 5) break; if (this[SYM_MSGLEN] === -1) this[SYM_MSGLEN] = readUInt32BE(buffer, p); // Check if we have the entire message if (bufferLen < (4 + this[SYM_MSGLEN])) break; const msgType = buffer[p += 4]; ++p; if (this[SYM_MODE] === ROLE_CLIENT) { if (this[SYM_REQS].length === 0) return cb(new Error('Received unexpected message from server')); const req = this[SYM_REQS].shift(); switch (msgType) { case SSH_AGENT_FAILURE: req.cb(new Error('Agent responded with failure')); break; case SSH_AGENT_IDENTITIES_ANSWER: { if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) return cb(new Error('Agent responded with wrong message type')); /* byte SSH_AGENT_IDENTITIES_ANSWER uint32 nkeys where `nkeys` is 0 or more of: string key blob string comment */ binaryParser.init(buffer, p); const numKeys = binaryParser.readUInt32BE(); if (numKeys === undefined) { binaryParser.clear(); return cb(new Error('Malformed agent response')); } const keys = []; for (let i = 0; i < numKeys; ++i) { let pubKey = binaryParser.readString(); if (pubKey === undefined) { binaryParser.clear(); return cb(new Error('Malformed agent response')); } const comment = binaryParser.readString(true); if (comment === undefined) { binaryParser.clear(); return cb(new Error('Malformed agent response')); } pubKey = parseKey(pubKey); // We continue parsing the packet if we encounter an error // in case the error is due to the key being an unsupported // type if (pubKey instanceof Error) continue; pubKey.comment = pubKey.comment || comment; keys.push(pubKey); } p = binaryParser.pos(); binaryParser.clear(); req.cb(null, keys); break; } case SSH_AGENT_SIGN_RESPONSE: { if (req.type !== SSH_AGENTC_SIGN_REQUEST) return cb(new Error('Agent responded with wrong message type')); /* byte SSH_AGENT_SIGN_RESPONSE string signature */ binaryParser.init(buffer, p); let signature = binaryParser.readString(); p = binaryParser.pos(); binaryParser.clear(); if (signature === undefined) return cb(new Error('Malformed agent response')); // We strip the algorithm from OpenSSH's output and assume it's // using the algorithm we specified. This makes it easier on // custom Agent implementations so they don't have to construct // the correct binary format for a (OpenSSH-style) signature. // TODO: verify signature type based on key and options used // during initial sign request binaryParser.init(signature, 0); binaryParser.readString(true); signature = binaryParser.readString(); binaryParser.clear(); if (signature === undefined) return cb(new Error('Malformed OpenSSH signature format')); req.cb(null, signature); break; } default: return cb( new Error('Agent responded with unsupported message type') ); } } else { switch (msgType) { case SSH_AGENTC_REQUEST_IDENTITIES: { const req = new AgentInboundRequest(msgType); this[SYM_REQS].push(req); /* byte SSH_AGENTC_REQUEST_IDENTITIES */ this.emit('identities', req); break; } case SSH_AGENTC_SIGN_REQUEST: { /* byte SSH_AGENTC_SIGN_REQUEST string key_blob string data uint32 flags */ binaryParser.init(buffer, p); let pubKey = binaryParser.readString(); const data = binaryParser.readString(); const flagsVal = binaryParser.readUInt32BE(); p = binaryParser.pos(); binaryParser.clear(); if (flagsVal === undefined) { const req = new AgentInboundRequest(msgType); this[SYM_REQS].push(req); return this.failureReply(req); } pubKey = parseKey(pubKey); if (pubKey instanceof Error) { const req = new AgentInboundRequest(msgType); this[SYM_REQS].push(req); return this.failureReply(req); } const flags = { hash: undefined, }; let ctx; if (pubKey.type === 'ssh-rsa') { if (flagsVal & SSH_AGENT_RSA_SHA2_256) { ctx = 'rsa-sha2-256'; flags.hash = 'sha256'; } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { ctx = 'rsa-sha2-512'; flags.hash = 'sha512'; } } if (ctx === undefined) ctx = pubKey.type; const req = new AgentInboundRequest(msgType, ctx); this[SYM_REQS].push(req); this.emit('sign', req, pubKey, data, flags); break; } default: { const req = new AgentInboundRequest(msgType); this[SYM_REQS].push(req); this.failureReply(req); } } } // Get ready for next message this[SYM_MSGLEN] = -1; if (p === bufferLen) { // Nothing left to process for now this[SYM_BUFFER] = null; break; } else { this[SYM_BUFFER] = buffer = buffer.slice(p); bufferLen = buffer.length; p = 0; } } cb(); } _destroy(err, cb) { cleanup(this); cb(); } _final(cb) { cleanup(this); cb(); } // Client->Server messages ================================================= sign(pubKey, data, options, cb) { if (this[SYM_MODE] !== ROLE_CLIENT) throw new Error('Client-only method called with server role'); if (typeof options === 'function') { cb = options; options = undefined; } else if (typeof options !== 'object' || options === null) { options = undefined; } let flags = 0; pubKey = parseKey(pubKey); if (pubKey instanceof Error) throw new Error('Invalid public key argument'); if (pubKey.type === 'ssh-rsa' && options) { switch (options.hash) { case 'sha256': flags = SSH_AGENT_RSA_SHA2_256; break; case 'sha512': flags = SSH_AGENT_RSA_SHA2_512; break; } } pubKey = pubKey.getPublicSSH(); /* byte SSH_AGENTC_SIGN_REQUEST string key_blob string data uint32 flags */ const type = SSH_AGENTC_SIGN_REQUEST; const keyLen = pubKey.length; const dataLen = data.length; let p = 0; const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = type; writeUInt32BE(buf, keyLen, ++p); pubKey.copy(buf, p += 4); writeUInt32BE(buf, dataLen, p += keyLen); data.copy(buf, p += 4); writeUInt32BE(buf, flags, p += dataLen); if (typeof cb !== 'function') cb = noop; this[SYM_REQS].push({ type, cb }); return this.push(buf); } getIdentities(cb) { if (this[SYM_MODE] !== ROLE_CLIENT) throw new Error('Client-only method called with server role'); /* byte SSH_AGENTC_REQUEST_IDENTITIES */ const type = SSH_AGENTC_REQUEST_IDENTITIES; let p = 0; const buf = Buffer.allocUnsafe(4 + 1); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = type; if (typeof cb !== 'function') cb = noop; this[SYM_REQS].push({ type, cb }); return this.push(buf); } // Server->Client messages ================================================= failureReply(req) { if (this[SYM_MODE] !== ROLE_SERVER) throw new Error('Server-only method called with client role'); if (!(req instanceof AgentInboundRequest)) throw new Error('Wrong request argument'); if (req.hasResponded()) return true; let p = 0; const buf = Buffer.allocUnsafe(4 + 1); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = SSH_AGENT_FAILURE; return respond(this, req, buf); } getIdentitiesReply(req, keys) { if (this[SYM_MODE] !== ROLE_SERVER) throw new Error('Server-only method called with client role'); if (!(req instanceof AgentInboundRequest)) throw new Error('Wrong request argument'); if (req.hasResponded()) return true; /* byte SSH_AGENT_IDENTITIES_ANSWER uint32 nkeys where `nkeys` is 0 or more of: string key blob string comment */ if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) throw new Error('Invalid response to request'); if (!Array.isArray(keys)) throw new Error('Keys argument must be an array'); let totalKeysLen = 4; // Include `nkeys` size const newKeys = []; for (let i = 0; i < keys.length; ++i) { const entry = keys[i]; if (typeof entry !== 'object' || entry === null) throw new Error(`Invalid key entry: ${entry}`); let pubKey; let comment; if (isParsedKey(entry)) { pubKey = entry; } else if (isParsedKey(entry.pubKey)) { pubKey = entry.pubKey; } else { if (typeof entry.pubKey !== 'object' || entry.pubKey === null) continue; ({ pubKey, comment } = entry.pubKey); pubKey = parseKey(pubKey); if (pubKey instanceof Error) continue; // TODO: add debug output } comment = pubKey.comment || comment; pubKey = pubKey.getPublicSSH(); totalKeysLen += 4 + pubKey.length; if (comment && typeof comment === 'string') comment = Buffer.from(comment); else if (!Buffer.isBuffer(comment)) comment = EMPTY_BUF; totalKeysLen += 4 + comment.length; newKeys.push({ pubKey, comment }); } let p = 0; const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; writeUInt32BE(buf, newKeys.length, ++p); p += 4; for (let i = 0; i < newKeys.length; ++i) { const { pubKey, comment } = newKeys[i]; writeUInt32BE(buf, pubKey.length, p); pubKey.copy(buf, p += 4); writeUInt32BE(buf, comment.length, p += pubKey.length); p += 4; if (comment.length) { comment.copy(buf, p); p += comment.length; } } return respond(this, req, buf); } signReply(req, signature) { if (this[SYM_MODE] !== ROLE_SERVER) throw new Error('Server-only method called with client role'); if (!(req instanceof AgentInboundRequest)) throw new Error('Wrong request argument'); if (req.hasResponded()) return true; /* byte SSH_AGENT_SIGN_RESPONSE string signature */ if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) throw new Error('Invalid response to request'); if (!Buffer.isBuffer(signature)) throw new Error('Signature argument must be a Buffer'); if (signature.length === 0) throw new Error('Signature argument must be non-empty'); /* OpenSSH agent signatures are encoded as: string signature format identifier (as specified by the public key/certificate format) byte[n] signature blob in format specific encoding. - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 types */ let p = 0; const sigFormat = req.getContext(); const sigFormatLen = Buffer.byteLength(sigFormat); const buf = Buffer.allocUnsafe( 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length ); writeUInt32BE(buf, buf.length - 4, p); buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); writeUInt32BE(buf, sigFormatLen, p += 4); buf.utf8Write(sigFormat, p += 4, sigFormatLen); writeUInt32BE(buf, signature.length, p += sigFormatLen); signature.copy(buf, p += 4); return respond(this, req, buf); } }; })(); const SYM_AGENT = Symbol('Agent'); const SYM_AGENT_KEYS = Symbol('Agent Keys'); const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); class AgentContext { constructor(agent) { if (typeof agent === 'string') agent = createAgent(agent); else if (!isAgent(agent)) throw new Error('Invalid agent argument'); this[SYM_AGENT] = agent; this[SYM_AGENT_KEYS] = null; this[SYM_AGENT_KEYS_IDX] = -1; this[SYM_AGENT_CBS] = null; } init(cb) { if (typeof cb !== 'function') cb = noop; if (this[SYM_AGENT_KEYS] === null) { if (this[SYM_AGENT_CBS] === null) { this[SYM_AGENT_CBS] = [cb]; const doCbs = (...args) => { process.nextTick(() => { const cbs = this[SYM_AGENT_CBS]; this[SYM_AGENT_CBS] = null; for (const cb of cbs) cb(...args); }); }; this[SYM_AGENT].getIdentities(once((err, keys) => { if (err) return doCbs(err); if (!Array.isArray(keys)) { return doCbs(new Error( 'Agent implementation failed to provide keys' )); } const newKeys = []; for (let key of keys) { key = parseKey(key); if (key instanceof Error) { // TODO: add debug output continue; } newKeys.push(key); } this[SYM_AGENT_KEYS] = newKeys; this[SYM_AGENT_KEYS_IDX] = -1; doCbs(); })); } else { this[SYM_AGENT_CBS].push(cb); } } else { process.nextTick(cb); } } nextKey() { if (this[SYM_AGENT_KEYS] === null || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { return false; } return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; } currentKey() { if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { return null; } return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; } pos() { if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { return -1; } return this[SYM_AGENT_KEYS_IDX]; } reset() { this[SYM_AGENT_KEYS_IDX] = -1; } sign(...args) { this[SYM_AGENT].sign(...args); } } function isAgent(val) { return (val instanceof BaseAgent); } module.exports = { AgentContext, AgentProtocol, BaseAgent, createAgent, CygwinAgent, isAgent, OpenSSHAgent, PageantAgent, }; /***/ }), /***/ 6297: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // TODO: // * add `.connected` or similar property to allow immediate connection // status checking // * add/improve debug output during user authentication phase const { createHash, getHashes, randomFillSync, } = __nccwpck_require__(6982); const { Socket } = __nccwpck_require__(9278); const { lookup: dnsLookup } = __nccwpck_require__(2250); const EventEmitter = __nccwpck_require__(4434); const HASHES = getHashes(); const { COMPAT, CHANNEL_EXTENDED_DATATYPE: { STDERR }, CHANNEL_OPEN_FAILURE, DEFAULT_CIPHER, DEFAULT_COMPRESSION, DEFAULT_KEX, DEFAULT_MAC, DEFAULT_SERVER_HOST_KEY, DISCONNECT_REASON, DISCONNECT_REASON_BY_VALUE, SUPPORTED_CIPHER, SUPPORTED_COMPRESSION, SUPPORTED_KEX, SUPPORTED_MAC, SUPPORTED_SERVER_HOST_KEY, } = __nccwpck_require__(4020); const { init: cryptoInit } = __nccwpck_require__(2888); const Protocol = __nccwpck_require__(7841); const { parseKey } = __nccwpck_require__(1789); const { SFTP } = __nccwpck_require__(4996); const { bufferCopy, makeBufferParser, makeError, readUInt32BE, sigSSHToASN1, writeUInt32BE, } = __nccwpck_require__(2184); const { AgentContext, createAgent, isAgent } = __nccwpck_require__(3849); const { Channel, MAX_WINDOW, PACKET_SIZE, windowAdjust, WINDOW_THRESHOLD, } = __nccwpck_require__(5683); const { ChannelManager, generateAlgorithmList, isWritable, onChannelOpenFailure, onCHANNEL_CLOSE, } = __nccwpck_require__(2137); const bufferParser = makeBufferParser(); const sigParser = makeBufferParser(); const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; const noop = (err) => {}; class Client extends EventEmitter { constructor() { super(); this.config = { host: undefined, port: undefined, localAddress: undefined, localPort: undefined, forceIPv4: undefined, forceIPv6: undefined, keepaliveCountMax: undefined, keepaliveInterval: undefined, readyTimeout: undefined, ident: undefined, username: undefined, password: undefined, privateKey: undefined, tryKeyboard: undefined, agent: undefined, allowAgentFwd: undefined, authHandler: undefined, hostHashAlgo: undefined, hostHashCb: undefined, strictVendor: undefined, debug: undefined }; this._agent = undefined; this._readyTimeout = undefined; this._chanMgr = undefined; this._callbacks = undefined; this._forwarding = undefined; this._forwardingUnix = undefined; this._acceptX11 = undefined; this._agentFwdEnabled = undefined; this._remoteVer = undefined; this._protocol = undefined; this._sock = undefined; this._resetKA = undefined; } connect(cfg) { if (this._sock && isWritable(this._sock)) { this.once('close', () => { this.connect(cfg); }); this.end(); return this; } this.config.host = cfg.hostname || cfg.host || 'localhost'; this.config.port = cfg.port || 22; this.config.localAddress = (typeof cfg.localAddress === 'string' ? cfg.localAddress : undefined); this.config.localPort = (typeof cfg.localPort === 'string' || typeof cfg.localPort === 'number' ? cfg.localPort : undefined); this.config.forceIPv4 = cfg.forceIPv4 || false; this.config.forceIPv6 = cfg.forceIPv6 || false; this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' && cfg.keepaliveCountMax >= 0 ? cfg.keepaliveCountMax : 3); this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' && cfg.keepaliveInterval > 0 ? cfg.keepaliveInterval : 0); this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' && cfg.readyTimeout >= 0 ? cfg.readyTimeout : 20000); this.config.ident = (typeof cfg.ident === 'string' || Buffer.isBuffer(cfg.ident) ? cfg.ident : undefined); const algorithms = { kex: undefined, serverHostKey: undefined, cs: { cipher: undefined, mac: undefined, compress: undefined, lang: [], }, sc: undefined, }; let allOfferDefaults = true; if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, DEFAULT_KEX, SUPPORTED_KEX); if (algorithms.kex !== DEFAULT_KEX) allOfferDefaults = false; algorithms.serverHostKey = generateAlgorithmList(cfg.algorithms.serverHostKey, DEFAULT_SERVER_HOST_KEY, SUPPORTED_SERVER_HOST_KEY); if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) allOfferDefaults = false; algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, DEFAULT_CIPHER, SUPPORTED_CIPHER); if (algorithms.cs.cipher !== DEFAULT_CIPHER) allOfferDefaults = false; algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, DEFAULT_MAC, SUPPORTED_MAC); if (algorithms.cs.mac !== DEFAULT_MAC) allOfferDefaults = false; algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, DEFAULT_COMPRESSION, SUPPORTED_COMPRESSION); if (algorithms.cs.compress !== DEFAULT_COMPRESSION) allOfferDefaults = false; if (!allOfferDefaults) algorithms.sc = algorithms.cs; } if (typeof cfg.username === 'string') this.config.username = cfg.username; else if (typeof cfg.user === 'string') this.config.username = cfg.user; else throw new Error('Invalid username'); this.config.password = (typeof cfg.password === 'string' ? cfg.password : undefined); this.config.privateKey = (typeof cfg.privateKey === 'string' || Buffer.isBuffer(cfg.privateKey) ? cfg.privateKey : undefined); this.config.localHostname = (typeof cfg.localHostname === 'string' ? cfg.localHostname : undefined); this.config.localUsername = (typeof cfg.localUsername === 'string' ? cfg.localUsername : undefined); this.config.tryKeyboard = (cfg.tryKeyboard === true); if (typeof cfg.agent === 'string' && cfg.agent.length) this.config.agent = createAgent(cfg.agent); else if (isAgent(cfg.agent)) this.config.agent = cfg.agent; else this.config.agent = undefined; this.config.allowAgentFwd = (cfg.agentForward === true && this.config.agent !== undefined); let authHandler = this.config.authHandler = ( typeof cfg.authHandler === 'function' || Array.isArray(cfg.authHandler) ? cfg.authHandler : undefined ); this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' ? cfg.strictVendor : true); const debug = this.config.debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); if (cfg.agentForward === true && !this.config.allowAgentFwd) { throw new Error( 'You must set a valid agent path to allow agent forwarding' ); } let callbacks = this._callbacks = []; this._chanMgr = new ChannelManager(this); this._forwarding = {}; this._forwardingUnix = {}; this._acceptX11 = 0; this._agentFwdEnabled = false; this._agent = (this.config.agent ? this.config.agent : undefined); this._remoteVer = undefined; let privateKey; if (this.config.privateKey) { privateKey = parseKey(this.config.privateKey, cfg.passphrase); if (privateKey instanceof Error) throw new Error(`Cannot parse privateKey: ${privateKey.message}`); if (Array.isArray(privateKey)) { // OpenSSH's newer format only stores 1 key for now privateKey = privateKey[0]; } if (privateKey.getPrivatePEM() === null) { throw new Error( 'privateKey value does not contain a (valid) private key' ); } } let hostVerifier; if (typeof cfg.hostVerifier === 'function') { const hashCb = cfg.hostVerifier; let hashAlgo; if (HASHES.indexOf(cfg.hostHash) !== -1) { // Default to old behavior of hashing on user's behalf hashAlgo = cfg.hostHash; } hostVerifier = (key, verify) => { if (hashAlgo) key = createHash(hashAlgo).update(key).digest('hex'); const ret = hashCb(key, verify); if (ret !== undefined) verify(ret); }; } const sock = this._sock = (cfg.sock || new Socket()); let ready = false; let sawHeader = false; if (this._protocol) this._protocol.cleanup(); const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { debug(`Debug output from server: ${JSON.stringify(msg)}`); }); let serverSigAlgs; const proto = this._protocol = new Protocol({ ident: this.config.ident, offer: (allOfferDefaults ? undefined : algorithms), onWrite: (data) => { if (isWritable(sock)) sock.write(data); }, onError: (err) => { if (err.level === 'handshake') clearTimeout(this._readyTimeout); if (!proto._destruct) sock.removeAllListeners('data'); this.emit('error', err); try { sock.end(); } catch {} }, onHeader: (header) => { sawHeader = true; this._remoteVer = header.versions.software; if (header.greeting) this.emit('greeting', header.greeting); }, onHandshakeComplete: (negotiated) => { this.emit('handshake', negotiated); if (!ready) { ready = true; proto.service('ssh-userauth'); } }, debug, hostVerifier, messageHandlers: { DEBUG: DEBUG_HANDLER, DISCONNECT: (p, reason, desc) => { if (reason !== DISCONNECT_REASON.BY_APPLICATION) { if (!desc) { desc = DISCONNECT_REASON_BY_VALUE[reason]; if (desc === undefined) desc = `Unexpected disconnection reason: ${reason}`; } const err = new Error(desc); err.code = reason; this.emit('error', err); } sock.end(); }, SERVICE_ACCEPT: (p, name) => { if (name === 'ssh-userauth') tryNextAuth(); }, EXT_INFO: (p, exts) => { if (serverSigAlgs === undefined) { for (const ext of exts) { if (ext.name === 'server-sig-algs') { serverSigAlgs = ext.algs; return; } } serverSigAlgs = null; } }, USERAUTH_BANNER: (p, msg) => { this.emit('banner', msg); }, USERAUTH_SUCCESS: (p) => { // Start keepalive mechanism resetKA(); clearTimeout(this._readyTimeout); this.emit('ready'); }, USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { // For key-based authentication, check if we should retry the current // key with a different algorithm first if (curAuth.keyAlgos) { const oldKeyAlgo = curAuth.keyAlgos[0][0]; if (debug) debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); curAuth.keyAlgos.shift(); if (curAuth.keyAlgos.length) { const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; switch (curAuth.type) { case 'agent': proto.authPK( curAuth.username, curAuth.agentCtx.currentKey(), keyAlgo ); return; case 'publickey': proto.authPK(curAuth.username, curAuth.key, keyAlgo); return; case 'hostbased': proto.authHostbased(curAuth.username, curAuth.key, curAuth.localHostname, curAuth.localUsername, keyAlgo, (buf, cb) => { const signature = curAuth.key.sign(buf, hashAlgo); if (signature instanceof Error) { signature.message = `Error while signing with key: ${signature.message}`; signature.level = 'client-authentication'; this.emit('error', signature); return tryNextAuth(); } cb(signature); }); return; } } else { curAuth.keyAlgos = undefined; } } if (curAuth.type === 'agent') { const pos = curAuth.agentCtx.pos(); debug && debug(`Client: Agent key #${pos + 1} failed`); return tryNextAgentKey(); } debug && debug(`Client: ${curAuth.type} auth failed`); curPartial = partialSuccess; curAuthsLeft = authMethods; tryNextAuth(); }, USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { if (curAuth.type === 'password') { // TODO: support a `changePrompt()` on `curAuth` that defaults to // emitting 'change password' as before this.emit('change password', prompt, (newPassword) => { proto.authPassword( this.config.username, this.config.password, newPassword ); }); } }, USERAUTH_PK_OK: (p) => { let keyAlgo; let hashAlgo; if (curAuth.keyAlgos) [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; if (curAuth.type === 'agent') { const key = curAuth.agentCtx.currentKey(); proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => { const opts = { hash: hashAlgo }; curAuth.agentCtx.sign(key, buf, opts, (err, signed) => { if (err) { err.level = 'agent'; this.emit('error', err); } else { return cb(signed); } tryNextAgentKey(); }); }); } else if (curAuth.type === 'publickey') { proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => { const signature = curAuth.key.sign(buf, hashAlgo); if (signature instanceof Error) { signature.message = `Error signing data with key: ${signature.message}`; signature.level = 'client-authentication'; this.emit('error', signature); return tryNextAuth(); } cb(signature); }); } }, USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { if (curAuth.type === 'keyboard-interactive') { const nprompts = (Array.isArray(prompts) ? prompts.length : 0); if (nprompts === 0) { debug && debug( 'Client: Sending automatic USERAUTH_INFO_RESPONSE' ); proto.authInfoRes(); return; } // We sent a keyboard-interactive user authentication request and // now the server is sending us the prompts we need to present to // the user curAuth.prompt( name, instructions, '', prompts, (answers) => { proto.authInfoRes(answers); } ); } }, REQUEST_SUCCESS: (p, data) => { if (callbacks.length) callbacks.shift()(false, data); }, REQUEST_FAILURE: (p) => { if (callbacks.length) callbacks.shift()(true); }, GLOBAL_REQUEST: (p, name, wantReply, data) => { switch (name) { case 'hostkeys-00@openssh.com': // Automatically verify keys before passing to end user hostKeysProve(this, data, (err, keys) => { if (err) return; this.emit('hostkeys', keys); }); if (wantReply) proto.requestSuccess(); break; default: // Auto-reject all other global requests, this can be especially // useful if the server is sending us dummy keepalive global // requests if (wantReply) proto.requestFailure(); } }, CHANNEL_OPEN: (p, info) => { // Handle incoming requests from server, typically a forwarded TCP or // X11 connection onCHANNEL_OPEN(this, info); }, CHANNEL_OPEN_CONFIRMATION: (p, info) => { const channel = this._chanMgr.get(info.recipient); if (typeof channel !== 'function') return; const isSFTP = (channel.type === 'sftp'); const type = (isSFTP ? 'session' : channel.type); const chanInfo = { type, incoming: { id: info.recipient, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const instance = ( isSFTP ? new SFTP(this, chanInfo, { debug }) : new Channel(this, chanInfo) ); this._chanMgr.update(info.recipient, instance); channel(undefined, instance); }, CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'function') return; const info = { reason, description }; onChannelOpenFailure(this, recipient, info, channel); }, CHANNEL_DATA: (p, recipient, data) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; // The remote party should not be sending us data if there is no // window space available ... // TODO: raise error on data with not enough window? if (channel.incoming.window === 0) return; channel.incoming.window -= data.length; if (channel.push(data) === false) { channel._waitChanDrain = true; return; } if (channel.incoming.window <= WINDOW_THRESHOLD) windowAdjust(channel); }, CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { if (type !== STDERR) return; const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; // The remote party should not be sending us data if there is no // window space available ... // TODO: raise error on data with not enough window? if (channel.incoming.window === 0) return; channel.incoming.window -= data.length; if (!channel.stderr.push(data)) { channel._waitChanDrain = true; return; } if (channel.incoming.window <= WINDOW_THRESHOLD) windowAdjust(channel); }, CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; // The other side is allowing us to send `amount` more bytes of data channel.outgoing.window += amount; if (channel._waitWindow) { channel._waitWindow = false; if (channel._chunk) { channel._write(channel._chunk, null, channel._chunkcb); } else if (channel._chunkcb) { channel._chunkcb(); } else if (channel._chunkErr) { channel.stderr._write(channel._chunkErr, null, channel._chunkcbErr); } else if (channel._chunkcbErr) { channel._chunkcbErr(); } } }, CHANNEL_SUCCESS: (p, recipient) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; this._resetKA(); if (channel._callbacks.length) channel._callbacks.shift()(false); }, CHANNEL_FAILURE: (p, recipient) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; this._resetKA(); if (channel._callbacks.length) channel._callbacks.shift()(true); }, CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; const exit = channel._exit; if (exit.code !== undefined) return; switch (type) { case 'exit-status': channel.emit('exit', exit.code = data); return; case 'exit-signal': channel.emit('exit', exit.code = null, exit.signal = `SIG${data.signal}`, exit.dump = data.coreDumped, exit.desc = data.errorMessage); return; } // Keepalive request? OpenSSH will send one as a channel request if // there is a channel open if (wantReply) p.channelFailure(channel.outgoing.id); }, CHANNEL_EOF: (p, recipient) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.incoming.state !== 'open') return; channel.incoming.state = 'eof'; if (channel.readable) channel.push(null); if (channel.stderr.readable) channel.stderr.push(null); }, CHANNEL_CLOSE: (p, recipient) => { onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); }, }, }); sock.pause(); // TODO: check keepalive implementation // Keepalive-related const kainterval = this.config.keepaliveInterval; const kacountmax = this.config.keepaliveCountMax; let kacount = 0; let katimer; const sendKA = () => { if (++kacount > kacountmax) { clearInterval(katimer); if (sock.readable) { const err = new Error('Keepalive timeout'); err.level = 'client-timeout'; this.emit('error', err); sock.destroy(); } return; } if (isWritable(sock)) { // Append dummy callback to keep correct callback order callbacks.push(resetKA); proto.ping(); } else { clearInterval(katimer); } }; function resetKA() { if (kainterval > 0) { kacount = 0; clearInterval(katimer); if (isWritable(sock)) katimer = setInterval(sendKA, kainterval); } } this._resetKA = resetKA; const onDone = (() => { let called = false; return () => { if (called) return; called = true; if (wasConnected && !sawHeader) { const err = makeError('Connection lost before handshake', 'protocol', true); this.emit('error', err); } }; })(); const onConnect = (() => { let called = false; return () => { if (called) return; called = true; wasConnected = true; debug && debug('Socket connected'); this.emit('connect'); cryptoInit.then(() => { proto.start(); sock.on('data', (data) => { try { proto.parse(data, 0, data.length); } catch (ex) { this.emit('error', ex); try { if (isWritable(sock)) sock.end(); } catch {} } }); // Drain stderr if we are connection hopping using an exec stream if (sock.stderr && typeof sock.stderr.resume === 'function') sock.stderr.resume(); sock.resume(); }).catch((err) => { this.emit('error', err); try { if (isWritable(sock)) sock.end(); } catch {} }); }; })(); let wasConnected = false; sock.on('connect', onConnect) .on('timeout', () => { this.emit('timeout'); }).on('error', (err) => { debug && debug(`Socket error: ${err.message}`); clearTimeout(this._readyTimeout); err.level = 'client-socket'; this.emit('error', err); }).on('end', () => { debug && debug('Socket ended'); onDone(); proto.cleanup(); clearTimeout(this._readyTimeout); clearInterval(katimer); this.emit('end'); }).on('close', () => { debug && debug('Socket closed'); onDone(); proto.cleanup(); clearTimeout(this._readyTimeout); clearInterval(katimer); this.emit('close'); // Notify outstanding channel requests of disconnection ... const callbacks_ = callbacks; callbacks = this._callbacks = []; const err = new Error('No response from server'); for (let i = 0; i < callbacks_.length; ++i) callbacks_[i](err); // Simulate error for any channels waiting to be opened this._chanMgr.cleanup(err); }); // Begin authentication handling =========================================== let curAuth; let curPartial = null; let curAuthsLeft = null; const authsAllowed = ['none']; if (this.config.password !== undefined) authsAllowed.push('password'); if (privateKey !== undefined) authsAllowed.push('publickey'); if (this._agent !== undefined) authsAllowed.push('agent'); if (this.config.tryKeyboard) authsAllowed.push('keyboard-interactive'); if (privateKey !== undefined && this.config.localHostname !== undefined && this.config.localUsername !== undefined) { authsAllowed.push('hostbased'); } if (Array.isArray(authHandler)) authHandler = makeSimpleAuthHandler(authHandler); else if (typeof authHandler !== 'function') authHandler = makeSimpleAuthHandler(authsAllowed); let hasSentAuth = false; const doNextAuth = (nextAuth) => { if (hasSentAuth) return; hasSentAuth = true; if (nextAuth === false) { const err = new Error('All configured authentication methods failed'); err.level = 'client-authentication'; this.emit('error', err); this.end(); return; } if (typeof nextAuth === 'string') { // Remain backwards compatible with original `authHandler()` usage, // which only supported passing names of next method to try using data // from the `connect()` config object const type = nextAuth; if (authsAllowed.indexOf(type) === -1) return skipAuth(`Authentication method not allowed: ${type}`); const username = this.config.username; switch (type) { case 'password': nextAuth = { type, username, password: this.config.password }; break; case 'publickey': nextAuth = { type, username, key: privateKey }; break; case 'hostbased': nextAuth = { type, username, key: privateKey, localHostname: this.config.localHostname, localUsername: this.config.localUsername, }; break; case 'agent': nextAuth = { type, username, agentCtx: new AgentContext(this._agent), }; break; case 'keyboard-interactive': nextAuth = { type, username, prompt: (...args) => this.emit('keyboard-interactive', ...args), }; break; case 'none': nextAuth = { type, username }; break; default: return skipAuth( `Skipping unsupported authentication method: ${nextAuth}` ); } } else if (typeof nextAuth !== 'object' || nextAuth === null) { return skipAuth( `Skipping invalid authentication attempt: ${nextAuth}` ); } else { const username = nextAuth.username; if (typeof username !== 'string') { return skipAuth( `Skipping invalid authentication attempt: ${nextAuth}` ); } const type = nextAuth.type; switch (type) { case 'password': { const { password } = nextAuth; if (typeof password !== 'string' && !Buffer.isBuffer(password)) return skipAuth('Skipping invalid password auth attempt'); nextAuth = { type, username, password }; break; } case 'publickey': { const key = parseKey(nextAuth.key, nextAuth.passphrase); if (key instanceof Error) return skipAuth('Skipping invalid key auth attempt'); if (!key.isPrivateKey()) return skipAuth('Skipping non-private key'); nextAuth = { type, username, key }; break; } case 'hostbased': { const { localHostname, localUsername } = nextAuth; const key = parseKey(nextAuth.key, nextAuth.passphrase); if (key instanceof Error || typeof localHostname !== 'string' || typeof localUsername !== 'string') { return skipAuth('Skipping invalid hostbased auth attempt'); } if (!key.isPrivateKey()) return skipAuth('Skipping non-private key'); nextAuth = { type, username, key, localHostname, localUsername }; break; } case 'agent': { let agent = nextAuth.agent; if (typeof agent === 'string' && agent.length) { agent = createAgent(agent); } else if (!isAgent(agent)) { return skipAuth( `Skipping invalid agent: ${nextAuth.agent}` ); } nextAuth = { type, username, agentCtx: new AgentContext(agent) }; break; } case 'keyboard-interactive': { const { prompt } = nextAuth; if (typeof prompt !== 'function') { return skipAuth( 'Skipping invalid keyboard-interactive auth attempt' ); } nextAuth = { type, username, prompt }; break; } case 'none': nextAuth = { type, username }; break; default: return skipAuth( `Skipping unsupported authentication method: ${nextAuth}` ); } } curAuth = nextAuth; // Begin authentication method's process try { const username = curAuth.username; switch (curAuth.type) { case 'password': proto.authPassword(username, curAuth.password); break; case 'publickey': { let keyAlgo; curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); if (curAuth.keyAlgos) { if (curAuth.keyAlgos.length) { keyAlgo = curAuth.keyAlgos[0][0]; } else { return skipAuth( 'Skipping key authentication (no mutual hash algorithm)' ); } } proto.authPK(username, curAuth.key, keyAlgo); break; } case 'hostbased': { let keyAlgo; let hashAlgo; curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); if (curAuth.keyAlgos) { if (curAuth.keyAlgos.length) { [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; } else { return skipAuth( 'Skipping hostbased authentication (no mutual hash algorithm)' ); } } proto.authHostbased(username, curAuth.key, curAuth.localHostname, curAuth.localUsername, keyAlgo, (buf, cb) => { const signature = curAuth.key.sign(buf, hashAlgo); if (signature instanceof Error) { signature.message = `Error while signing with key: ${signature.message}`; signature.level = 'client-authentication'; this.emit('error', signature); return tryNextAuth(); } cb(signature); }); break; } case 'agent': curAuth.agentCtx.init((err) => { if (err) { err.level = 'agent'; this.emit('error', err); return tryNextAuth(); } tryNextAgentKey(); }); break; case 'keyboard-interactive': proto.authKeyboard(username); break; case 'none': proto.authNone(username); break; } } finally { hasSentAuth = false; } }; function skipAuth(msg) { debug && debug(msg); process.nextTick(tryNextAuth); } function tryNextAuth() { hasSentAuth = false; const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); if (hasSentAuth || auth === undefined) return; doNextAuth(auth); } const tryNextAgentKey = () => { if (curAuth.type === 'agent') { const key = curAuth.agentCtx.nextKey(); if (key === false) { debug && debug('Agent: No more keys left to try'); debug && debug('Client: agent auth failed'); tryNextAuth(); } else { const pos = curAuth.agentCtx.pos(); let keyAlgo; curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs); if (curAuth.keyAlgos) { if (curAuth.keyAlgos.length) { keyAlgo = curAuth.keyAlgos[0][0]; } else { debug && debug( `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)` ); tryNextAgentKey(); return; } } debug && debug(`Agent: Trying key #${pos + 1}`); proto.authPK(curAuth.username, key, keyAlgo); } } }; const startTimeout = () => { if (this.config.readyTimeout > 0) { this._readyTimeout = setTimeout(() => { const err = new Error('Timed out while waiting for handshake'); err.level = 'client-timeout'; this.emit('error', err); sock.destroy(); }, this.config.readyTimeout); } }; if (!cfg.sock) { let host = this.config.host; const forceIPv4 = this.config.forceIPv4; const forceIPv6 = this.config.forceIPv6; debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); const doConnect = () => { startTimeout(); sock.connect({ host, port: this.config.port, localAddress: this.config.localAddress, localPort: this.config.localPort }); sock.setMaxListeners(0); sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); }; if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { doConnect(); } else { dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { if (err) { const type = (forceIPv4 ? 'IPv4' : 'IPv6'); const error = new Error( `Error while looking up ${type} address for '${host}': ${err}` ); clearTimeout(this._readyTimeout); error.level = 'client-dns'; this.emit('error', error); this.emit('close'); return; } host = address; doConnect(); }); } } else { // Custom socket passed in startTimeout(); if (typeof sock.connecting === 'boolean') { // net.Socket if (!sock.connecting) { // Already connected onConnect(); } } else { // Assume socket/stream is already "connected" onConnect(); } } return this; } end() { if (this._sock && isWritable(this._sock)) { this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); this._sock.end(); } return this; } destroy() { this._sock && isWritable(this._sock) && this._sock.destroy(); return this; } exec(cmd, opts, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); if (typeof opts === 'function') { cb = opts; opts = {}; } const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; openChannel(this, 'session', extraOpts, (err, chan) => { if (err) { cb(err); return; } const todo = []; function reqCb(err) { if (err) { chan.close(); cb(err); return; } if (todo.length) todo.shift()(); } if (this.config.allowAgentFwd === true || (opts && opts.agentForward === true && this._agent !== undefined)) { todo.push(() => reqAgentFwd(chan, reqCb)); } if (typeof opts === 'object' && opts !== null) { if (typeof opts.env === 'object' && opts.env !== null) reqEnv(chan, opts.env); if ((typeof opts.pty === 'object' && opts.pty !== null) || opts.pty === true) { todo.push(() => reqPty(chan, opts.pty, reqCb)); } if ((typeof opts.x11 === 'object' && opts.x11 !== null) || opts.x11 === 'number' || opts.x11 === true) { todo.push(() => reqX11(chan, opts.x11, reqCb)); } } todo.push(() => reqExec(chan, cmd, opts, cb)); todo.shift()(); }); return this; } shell(wndopts, opts, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); if (typeof wndopts === 'function') { cb = wndopts; wndopts = opts = undefined; } else if (typeof opts === 'function') { cb = opts; opts = undefined; } if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { opts = wndopts; wndopts = undefined; } openChannel(this, 'session', (err, chan) => { if (err) { cb(err); return; } const todo = []; function reqCb(err) { if (err) { chan.close(); cb(err); return; } if (todo.length) todo.shift()(); } if (this.config.allowAgentFwd === true || (opts && opts.agentForward === true && this._agent !== undefined)) { todo.push(() => reqAgentFwd(chan, reqCb)); } if (wndopts !== false) todo.push(() => reqPty(chan, wndopts, reqCb)); if (typeof opts === 'object' && opts !== null) { if (typeof opts.env === 'object' && opts.env !== null) reqEnv(chan, opts.env); if ((typeof opts.x11 === 'object' && opts.x11 !== null) || opts.x11 === 'number' || opts.x11 === true) { todo.push(() => reqX11(chan, opts.x11, reqCb)); } } todo.push(() => reqShell(chan, cb)); todo.shift()(); }); return this; } subsys(name, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); openChannel(this, 'session', (err, chan) => { if (err) { cb(err); return; } reqSubsystem(chan, name, (err, stream) => { if (err) { cb(err); return; } cb(undefined, stream); }); }); return this; } forwardIn(bindAddr, bindPort, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); // Send a request for the server to start forwarding TCP connections to us // on a particular address and port const wantReply = (typeof cb === 'function'); if (wantReply) { this._callbacks.push((had_err, data) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); return; } let realPort = bindPort; if (bindPort === 0 && data && data.length >= 4) { realPort = readUInt32BE(data, 0); if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) bindPort = realPort; } this._forwarding[`${bindAddr}:${bindPort}`] = realPort; cb(undefined, realPort); }); } this._protocol.tcpipForward(bindAddr, bindPort, wantReply); return this; } unforwardIn(bindAddr, bindPort, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); // Send a request to stop forwarding us new connections for a particular // address and port const wantReply = (typeof cb === 'function'); if (wantReply) { this._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); return; } delete this._forwarding[`${bindAddr}:${bindPort}`]; cb(); }); } this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); return this; } forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); // Send a request to forward a TCP connection to the server const cfg = { srcIP: srcIP, srcPort: srcPort, dstIP: dstIP, dstPort: dstPort }; if (typeof cb !== 'function') cb = noop; openChannel(this, 'direct-tcpip', cfg, cb); return this; } openssh_noMoreSessions(cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); const wantReply = (typeof cb === 'function'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { if (wantReply) { this._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to disable future sessions')); return; } cb(); }); } this._protocol.openssh_noMoreSessions(wantReply); return this; } if (!wantReply) return this; process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); return this; } openssh_forwardInStreamLocal(socketPath, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); const wantReply = (typeof cb === 'function'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { if (wantReply) { this._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to bind to ${socketPath}`)); return; } this._forwardingUnix[socketPath] = true; cb(); }); } this._protocol.openssh_streamLocalForward(socketPath, wantReply); return this; } if (!wantReply) return this; process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); return this; } openssh_unforwardInStreamLocal(socketPath, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); const wantReply = (typeof cb === 'function'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { if (wantReply) { this._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to unbind from ${socketPath}`)); return; } delete this._forwardingUnix[socketPath]; cb(); }); } this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); return this; } if (!wantReply) return this; process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); return this; } openssh_forwardOutStreamLocal(socketPath, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); if (typeof cb !== 'function') cb = noop; if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); return this; } process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); return this; } sftp(env, cb) { if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected'); if (typeof env === 'function') { cb = env; env = undefined; } openChannel(this, 'sftp', (err, sftp) => { if (err) { cb(err); return; } const reqSubsystemCb = (err, sftp_) => { if (err) { cb(err); return; } function removeListeners() { sftp.removeListener('ready', onReady); sftp.removeListener('error', onError); sftp.removeListener('exit', onExit); sftp.removeListener('close', onExit); } function onReady() { // TODO: do not remove exit/close in case remote end closes the // channel abruptly and we need to notify outstanding callbacks removeListeners(); cb(undefined, sftp); } function onError(err) { removeListeners(); cb(err); } function onExit(code, signal) { removeListeners(); let msg; if (typeof code === 'number') msg = `Received exit code ${code} while establishing SFTP session`; else if (signal !== undefined) msg = `Received signal ${signal} while establishing SFTP session`; else msg = 'Received unexpected SFTP session termination'; const err = new Error(msg); err.code = code; err.signal = signal; cb(err); } sftp.on('ready', onReady) .on('error', onError) .on('exit', onExit) .on('close', onExit); sftp._init(); }; if (typeof env === 'object' && env !== null) { reqEnv(sftp, env, (err) => { if (err) { cb(err); return; } reqSubsystem(sftp, 'sftp', reqSubsystemCb); }); } else { reqSubsystem(sftp, 'sftp', reqSubsystemCb); } }); return this; } setNoDelay(noDelay) { if (this._sock && typeof this._sock.setNoDelay === 'function') this._sock.setNoDelay(noDelay); return this; } } function openChannel(self, type, opts, cb) { // Ask the server to open a channel for some purpose // (e.g. session (sftp, exec, shell), or forwarding a TCP connection const initWindow = MAX_WINDOW; const maxPacket = PACKET_SIZE; if (typeof opts === 'function') { cb = opts; opts = {}; } const wrapper = (err, stream) => { cb(err, stream); }; wrapper.type = type; const localChan = self._chanMgr.add(wrapper); if (localChan === -1) { cb(new Error('No free channels available')); return; } switch (type) { case 'session': case 'sftp': self._protocol.session(localChan, initWindow, maxPacket); break; case 'direct-tcpip': self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); break; case 'direct-streamlocal@openssh.com': self._protocol.openssh_directStreamLocal( localChan, initWindow, maxPacket, opts ); break; default: throw new Error(`Unsupported channel type: ${type}`); } } function reqX11(chan, screen, cb) { // Asks server to start sending us X11 connections const cfg = { single: false, protocol: 'MIT-MAGIC-COOKIE-1', cookie: undefined, screen: 0 }; if (typeof screen === 'function') { cb = screen; } else if (typeof screen === 'object' && screen !== null) { if (typeof screen.single === 'boolean') cfg.single = screen.single; if (typeof screen.screen === 'number') cfg.screen = screen.screen; if (typeof screen.protocol === 'string') cfg.protocol = screen.protocol; if (typeof screen.cookie === 'string') cfg.cookie = screen.cookie; else if (Buffer.isBuffer(screen.cookie)) cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); } if (cfg.cookie === undefined) cfg.cookie = randomCookie(); const wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { if (wantReply) cb(new Error('Channel is not open')); return; } if (wantReply) { chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to request X11')); return; } chan._hasX11 = true; ++chan._client._acceptX11; chan.once('close', () => { if (chan._client._acceptX11) --chan._client._acceptX11; }); cb(); }); } chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); } function reqPty(chan, opts, cb) { let rows = 24; let cols = 80; let width = 640; let height = 480; let term = 'vt100'; let modes = null; if (typeof opts === 'function') { cb = opts; } else if (typeof opts === 'object' && opts !== null) { if (typeof opts.rows === 'number') rows = opts.rows; if (typeof opts.cols === 'number') cols = opts.cols; if (typeof opts.width === 'number') width = opts.width; if (typeof opts.height === 'number') height = opts.height; if (typeof opts.term === 'string') term = opts.term; if (typeof opts.modes === 'object') modes = opts.modes; } const wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { if (wantReply) cb(new Error('Channel is not open')); return; } if (wantReply) { chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to request a pseudo-terminal')); return; } cb(); }); } chan._client._protocol.pty(chan.outgoing.id, rows, cols, height, width, term, modes, wantReply); } function reqAgentFwd(chan, cb) { const wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { wantReply && cb(new Error('Channel is not open')); return; } if (chan._client._agentFwdEnabled) { wantReply && cb(false); return; } chan._client._agentFwdEnabled = true; chan._callbacks.push((had_err) => { if (had_err) { chan._client._agentFwdEnabled = false; if (wantReply) { cb(had_err !== true ? had_err : new Error('Unable to request agent forwarding')); } return; } if (wantReply) cb(); }); chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); } function reqShell(chan, cb) { if (chan.outgoing.state !== 'open') { cb(new Error('Channel is not open')); return; } chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to open shell')); return; } chan.subtype = 'shell'; cb(undefined, chan); }); chan._client._protocol.shell(chan.outgoing.id, true); } function reqExec(chan, cmd, opts, cb) { if (chan.outgoing.state !== 'open') { cb(new Error('Channel is not open')); return; } chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to exec')); return; } chan.subtype = 'exec'; chan.allowHalfOpen = (opts.allowHalfOpen !== false); cb(undefined, chan); }); chan._client._protocol.exec(chan.outgoing.id, cmd, true); } function reqEnv(chan, env, cb) { const wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { if (wantReply) cb(new Error('Channel is not open')); return; } if (wantReply) { chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Unable to set environment')); return; } cb(); }); } const keys = Object.keys(env || {}); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; const val = env[key]; chan._client._protocol.env(chan.outgoing.id, key, val, wantReply); } } function reqSubsystem(chan, name, cb) { if (chan.outgoing.state !== 'open') { cb(new Error('Channel is not open')); return; } chan._callbacks.push((had_err) => { if (had_err) { cb(had_err !== true ? had_err : new Error(`Unable to start subsystem: ${name}`)); return; } chan.subtype = 'subsystem'; cb(undefined, chan); }); chan._client._protocol.subsystem(chan.outgoing.id, name, true); } // TODO: inline implementation into single call site function onCHANNEL_OPEN(self, info) { // The server is trying to open a channel with us, this is usually when // we asked the server to forward us connections on some port and now they // are asking us to accept/deny an incoming connection on their side let localChan = -1; let reason; const accept = () => { const chanInfo = { type: info.type, incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const stream = new Channel(self, chanInfo); self._chanMgr.update(localChan, stream); self._protocol.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return stream; }; const reject = () => { if (reason === undefined) { if (localChan === -1) reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; else reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; } if (localChan !== -1) self._chanMgr.remove(localChan); self._protocol.channelOpenFail(info.sender, reason, ''); }; const reserveChannel = () => { localChan = self._chanMgr.add(); if (localChan === -1) { reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of incoming channel open: ' + 'no channels available' ); } } return (localChan !== -1); }; const data = info.data; switch (info.type) { case 'forwarded-tcpip': { const val = self._forwarding[`${data.destIP}:${data.destPort}`]; if (val !== undefined && reserveChannel()) { if (data.destPort === 0) data.destPort = val; self.emit('tcp connection', data, accept, reject); return; } break; } case 'forwarded-streamlocal@openssh.com': if (self._forwardingUnix[data.socketPath] !== undefined && reserveChannel()) { self.emit('unix connection', data, accept, reject); return; } break; case 'auth-agent@openssh.com': if (self._agentFwdEnabled && typeof self._agent.getStream === 'function' && reserveChannel()) { self._agent.getStream((err, stream) => { if (err) return reject(); const upstream = accept(); upstream.pipe(stream).pipe(upstream); }); return; } break; case 'x11': if (self._acceptX11 !== 0 && reserveChannel()) { self.emit('x11', data, accept, reject); return; } break; default: // Automatically reject any unsupported channel open requests reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of unsupported incoming channel open ' + `type: ${info.type}` ); } } if (reason === undefined) { reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of unexpected incoming channel open for: ' + info.type ); } } reject(); } const randomCookie = (() => { const buffer = Buffer.allocUnsafe(16); return () => { randomFillSync(buffer, 0, 16); return buffer.hexSlice(0, 16); }; })(); function makeSimpleAuthHandler(authList) { if (!Array.isArray(authList)) throw new Error('authList must be an array'); let a = 0; return (authsLeft, partialSuccess, cb) => { if (a === authList.length) return false; return authList[a++]; }; } function hostKeysProve(client, keys_, cb) { if (!client._sock || !isWritable(client._sock)) return; if (typeof cb !== 'function') cb = noop; if (!Array.isArray(keys_)) throw new TypeError('Invalid keys argument type'); const keys = []; for (const key of keys_) { const parsed = parseKey(key); if (parsed instanceof Error) throw parsed; keys.push(parsed); } if (!client.config.strictVendor || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { client._callbacks.push((had_err, data) => { if (had_err) { cb(had_err !== true ? had_err : new Error('Server failed to prove supplied keys')); return; } // TODO: move all of this parsing/verifying logic out of the client? const ret = []; let keyIdx = 0; bufferParser.init(data, 0); while (bufferParser.avail()) { if (keyIdx === keys.length) break; const key = keys[keyIdx++]; const keyPublic = key.getPublicSSH(); const sigEntry = bufferParser.readString(); sigParser.init(sigEntry, 0); const type = sigParser.readString(true); let value = sigParser.readString(); let algo; if (type !== key.type) { if (key.type === 'ssh-rsa') { switch (type) { case 'rsa-sha2-256': algo = 'sha256'; break; case 'rsa-sha2-512': algo = 'sha512'; break; default: continue; } } else { continue; } } const sessionID = client._protocol._kex.sessionID; const verifyData = Buffer.allocUnsafe( 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length ); let p = 0; writeUInt32BE(verifyData, 29, p); verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); writeUInt32BE(verifyData, sessionID.length, p += 29); bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); if (!(value = sigSSHToASN1(value, type))) continue; if (key.verify(verifyData, value, algo) === true) ret.push(key); } sigParser.clear(); bufferParser.clear(); cb(null, ret); }); client._protocol.openssh_hostKeysProve(keys); return; } process.nextTick( cb, new Error( 'strictVendor enabled and server is not OpenSSH or compatible version' ) ); } function getKeyAlgos(client, key, serverSigAlgs) { switch (key.type) { case 'ssh-rsa': if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) { if (!Array.isArray(serverSigAlgs)) serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512']; else serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512', ...serverSigAlgs]; } if (Array.isArray(serverSigAlgs)) { if (serverSigAlgs.indexOf('rsa-sha2-256') !== -1) return [['rsa-sha2-256', 'sha256']]; if (serverSigAlgs.indexOf('rsa-sha2-512') !== -1) return [['rsa-sha2-512', 'sha512']]; if (serverSigAlgs.indexOf('ssh-rsa') === -1) return []; } return [['ssh-rsa', 'sha1']]; } } module.exports = Client; /***/ }), /***/ 137: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const { Agent: HttpAgent } = __nccwpck_require__(8611); const { Agent: HttpsAgent } = __nccwpck_require__(5692); const { connect: tlsConnect } = __nccwpck_require__(4756); let Client; for (const ctor of [HttpAgent, HttpsAgent]) { class SSHAgent extends ctor { constructor(connectCfg, agentOptions) { super(agentOptions); this._connectCfg = connectCfg; this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; } createConnection(options, cb) { const srcIP = (options && options.localAddress) || this._defaultSrcIP; const srcPort = (options && options.localPort) || 0; const dstIP = options.host; const dstPort = options.port; if (Client === undefined) Client = __nccwpck_require__(6297); const client = new Client(); let triedForward = false; client.on('ready', () => { client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { triedForward = true; if (err) { client.end(); return cb(err); } stream.once('close', () => client.end()); cb(null, decorateStream(stream, ctor, options)); }); }).on('error', cb).on('close', () => { if (!triedForward) cb(new Error('Unexpected connection close')); }).connect(this._connectCfg); } } exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; } function noop() {} function decorateStream(stream, ctor, options) { if (ctor === HttpAgent) { // HTTP stream.setKeepAlive = noop; stream.setNoDelay = noop; stream.setTimeout = noop; stream.ref = noop; stream.unref = noop; stream.destroySoon = stream.destroy; return stream; } // HTTPS options.socket = stream; const wrapped = tlsConnect(options); // This is a workaround for a regression in node v12.16.3+ // https://github.com/nodejs/node/issues/35904 const onClose = (() => { let called = false; return () => { if (called) return; called = true; if (stream.isPaused()) stream.resume(); }; })(); // 'end' listener is needed because 'close' is not emitted in some scenarios // in node v12.x for some unknown reason wrapped.on('end', onClose).on('close', onClose); return wrapped; } /***/ }), /***/ 5472: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { AgentProtocol, BaseAgent, createAgent, CygwinAgent, OpenSSHAgent, PageantAgent, } = __nccwpck_require__(3849); const { SSHTTPAgent: HTTPAgent, SSHTTPSAgent: HTTPSAgent, } = __nccwpck_require__(137); const { parseKey } = __nccwpck_require__(1789); const { flagsToString, OPEN_MODE, STATUS_CODE, stringToFlags, } = __nccwpck_require__(4996); module.exports = { AgentProtocol, BaseAgent, createAgent, Client: __nccwpck_require__(6297), CygwinAgent, HTTPAgent, HTTPSAgent, OpenSSHAgent, PageantAgent, Server: __nccwpck_require__(2605), utils: { parseKey, ...__nccwpck_require__(3489), sftp: { flagsToString, OPEN_MODE, STATUS_CODE, stringToFlags, }, }, }; /***/ }), /***/ 3489: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { createCipheriv, generateKeyPair: generateKeyPair_, generateKeyPairSync: generateKeyPairSync_, getCurves, randomBytes, } = __nccwpck_require__(6982); const { Ber } = __nccwpck_require__(9837); const bcrypt_pbkdf = (__nccwpck_require__(686).pbkdf); const { CIPHER_INFO } = __nccwpck_require__(2888); const SALT_LEN = 16; const DEFAULT_ROUNDS = 16; const curves = getCurves(); const ciphers = new Map(Object.entries(CIPHER_INFO)); function makeArgs(type, opts) { if (typeof type !== 'string') throw new TypeError('Key type must be a string'); const publicKeyEncoding = { type: 'spki', format: 'der' }; const privateKeyEncoding = { type: 'pkcs8', format: 'der' }; switch (type.toLowerCase()) { case 'rsa': { if (typeof opts !== 'object' || opts === null) throw new TypeError('Missing options object for RSA key'); const modulusLength = opts.bits; if (!Number.isInteger(modulusLength)) throw new TypeError('RSA bits must be an integer'); if (modulusLength <= 0 || modulusLength > 16384) throw new RangeError('RSA bits must be non-zero and <= 16384'); return ['rsa', { modulusLength, publicKeyEncoding, privateKeyEncoding }]; } case 'ecdsa': { if (typeof opts !== 'object' || opts === null) throw new TypeError('Missing options object for ECDSA key'); if (!Number.isInteger(opts.bits)) throw new TypeError('ECDSA bits must be an integer'); let namedCurve; switch (opts.bits) { case 256: namedCurve = 'prime256v1'; break; case 384: namedCurve = 'secp384r1'; break; case 521: namedCurve = 'secp521r1'; break; default: throw new Error('ECDSA bits must be 256, 384, or 521'); } if (!curves.includes(namedCurve)) throw new Error('Unsupported ECDSA bits value'); return ['ec', { namedCurve, publicKeyEncoding, privateKeyEncoding }]; } case 'ed25519': return ['ed25519', { publicKeyEncoding, privateKeyEncoding }]; default: throw new Error(`Unsupported key type: ${type}`); } } function parseDERs(keyType, pub, priv) { switch (keyType) { case 'rsa': { // Note: we don't need to parse the public key since the PKCS8 private key // already includes the public key parameters // Parse private key let reader = new Ber.Reader(priv); reader.readSequence(); // - Version if (reader.readInt() !== 0) throw new Error('Unsupported version in RSA private key'); // - Algorithm reader.readSequence(); if (reader.readOID() !== '1.2.840.113549.1.1.1') throw new Error('Bad RSA private OID'); // - Algorithm parameters (RSA has none) if (reader.readByte() !== Ber.Null) throw new Error('Malformed RSA private key (expected null)'); if (reader.readByte() !== 0x00) { throw new Error( 'Malformed RSA private key (expected zero-length null)' ); } reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); reader.readSequence(); if (reader.readInt() !== 0) throw new Error('Unsupported version in RSA private key'); const n = reader.readString(Ber.Integer, true); const e = reader.readString(Ber.Integer, true); const d = reader.readString(Ber.Integer, true); const p = reader.readString(Ber.Integer, true); const q = reader.readString(Ber.Integer, true); reader.readString(Ber.Integer, true); // dmp1 reader.readString(Ber.Integer, true); // dmq1 const iqmp = reader.readString(Ber.Integer, true); /* OpenSSH RSA private key: string "ssh-rsa" string n -- public string e -- public string d -- private string iqmp -- private string p -- private string q -- private */ const keyName = Buffer.from('ssh-rsa'); const privBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + n.length + 4 + e.length + 4 + d.length + 4 + iqmp.length + 4 + p.length + 4 + q.length ); let pos = 0; privBuf.writeUInt32BE(keyName.length, pos += 0); privBuf.set(keyName, pos += 4); privBuf.writeUInt32BE(n.length, pos += keyName.length); privBuf.set(n, pos += 4); privBuf.writeUInt32BE(e.length, pos += n.length); privBuf.set(e, pos += 4); privBuf.writeUInt32BE(d.length, pos += e.length); privBuf.set(d, pos += 4); privBuf.writeUInt32BE(iqmp.length, pos += d.length); privBuf.set(iqmp, pos += 4); privBuf.writeUInt32BE(p.length, pos += iqmp.length); privBuf.set(p, pos += 4); privBuf.writeUInt32BE(q.length, pos += p.length); privBuf.set(q, pos += 4); /* OpenSSH RSA public key: string "ssh-rsa" string e -- public string n -- public */ const pubBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + e.length + 4 + n.length ); pos = 0; pubBuf.writeUInt32BE(keyName.length, pos += 0); pubBuf.set(keyName, pos += 4); pubBuf.writeUInt32BE(e.length, pos += keyName.length); pubBuf.set(e, pos += 4); pubBuf.writeUInt32BE(n.length, pos += e.length); pubBuf.set(n, pos += 4); return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; } case 'ec': { // Parse public key let reader = new Ber.Reader(pub); reader.readSequence(); reader.readSequence(); if (reader.readOID() !== '1.2.840.10045.2.1') throw new Error('Bad ECDSA public OID'); // Skip curve OID, we'll get it from the private key reader.readOID(); let pubBin = reader.readString(Ber.BitString, true); { // Remove leading zero bytes let i = 0; for (; i < pubBin.length && pubBin[i] === 0x00; ++i); if (i > 0) pubBin = pubBin.slice(i); } // Parse private key reader = new Ber.Reader(priv); reader.readSequence(); // - Version if (reader.readInt() !== 0) throw new Error('Unsupported version in ECDSA private key'); reader.readSequence(); if (reader.readOID() !== '1.2.840.10045.2.1') throw new Error('Bad ECDSA private OID'); const curveOID = reader.readOID(); let sshCurveName; switch (curveOID) { case '1.2.840.10045.3.1.7': // prime256v1/secp256r1 sshCurveName = 'nistp256'; break; case '1.3.132.0.34': // secp384r1 sshCurveName = 'nistp384'; break; case '1.3.132.0.35': // secp521r1 sshCurveName = 'nistp521'; break; default: throw new Error('Unsupported curve in ECDSA private key'); } reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); reader.readSequence(); // - Version if (reader.readInt() !== 1) throw new Error('Unsupported version in ECDSA private key'); // Add leading zero byte to prevent negative bignum in private key const privBin = Buffer.concat([ Buffer.from([0x00]), reader.readString(Ber.OctetString, true) ]); /* OpenSSH ECDSA private key: string "ecdsa-sha2-" string curve name string Q -- public string d -- private */ const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`); sshCurveName = Buffer.from(sshCurveName); const privBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + sshCurveName.length + 4 + pubBin.length + 4 + privBin.length ); let pos = 0; privBuf.writeUInt32BE(keyName.length, pos += 0); privBuf.set(keyName, pos += 4); privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); privBuf.set(sshCurveName, pos += 4); privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); privBuf.set(pubBin, pos += 4); privBuf.writeUInt32BE(privBin.length, pos += pubBin.length); privBuf.set(privBin, pos += 4); /* OpenSSH ECDSA public key: string "ecdsa-sha2-" string curve name string Q -- public */ const pubBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + sshCurveName.length + 4 + pubBin.length ); pos = 0; pubBuf.writeUInt32BE(keyName.length, pos += 0); pubBuf.set(keyName, pos += 4); pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); pubBuf.set(sshCurveName, pos += 4); pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); pubBuf.set(pubBin, pos += 4); return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; } case 'ed25519': { // Parse public key let reader = new Ber.Reader(pub); reader.readSequence(); // - Algorithm reader.readSequence(); if (reader.readOID() !== '1.3.101.112') throw new Error('Bad ED25519 public OID'); // - Attributes (absent for ED25519) let pubBin = reader.readString(Ber.BitString, true); { // Remove leading zero bytes let i = 0; for (; i < pubBin.length && pubBin[i] === 0x00; ++i); if (i > 0) pubBin = pubBin.slice(i); } // Parse private key reader = new Ber.Reader(priv); reader.readSequence(); // - Version if (reader.readInt() !== 0) throw new Error('Unsupported version in ED25519 private key'); // - Algorithm reader.readSequence(); if (reader.readOID() !== '1.3.101.112') throw new Error('Bad ED25519 private OID'); // - Attributes (absent) reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); const privBin = reader.readString(Ber.OctetString, true); /* OpenSSH ed25519 private key: string "ssh-ed25519" string public key string private key + public key */ const keyName = Buffer.from('ssh-ed25519'); const privBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + pubBin.length + 4 + (privBin.length + pubBin.length) ); let pos = 0; privBuf.writeUInt32BE(keyName.length, pos += 0); privBuf.set(keyName, pos += 4); privBuf.writeUInt32BE(pubBin.length, pos += keyName.length); privBuf.set(pubBin, pos += 4); privBuf.writeUInt32BE( privBin.length + pubBin.length, pos += pubBin.length ); privBuf.set(privBin, pos += 4); privBuf.set(pubBin, pos += privBin.length); /* OpenSSH ed25519 public key: string "ssh-ed25519" string public key */ const pubBuf = Buffer.allocUnsafe( 4 + keyName.length + 4 + pubBin.length ); pos = 0; pubBuf.writeUInt32BE(keyName.length, pos += 0); pubBuf.set(keyName, pos += 4); pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length); pubBuf.set(pubBin, pos += 4); return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; } } } function convertKeys(keyType, pub, priv, opts) { let format = 'new'; let encrypted; let comment = ''; if (typeof opts === 'object' && opts !== null) { if (typeof opts.comment === 'string' && opts.comment) comment = opts.comment; if (typeof opts.format === 'string' && opts.format) format = opts.format; if (opts.passphrase) { let passphrase; if (typeof opts.passphrase === 'string') passphrase = Buffer.from(opts.passphrase); else if (Buffer.isBuffer(opts.passphrase)) passphrase = opts.passphrase; else throw new Error('Invalid passphrase'); if (opts.cipher === undefined) throw new Error('Missing cipher name'); const cipher = ciphers.get(opts.cipher); if (cipher === undefined) throw new Error('Invalid cipher name'); if (format === 'new') { let rounds = DEFAULT_ROUNDS; if (opts.rounds !== undefined) { if (!Number.isInteger(opts.rounds)) throw new TypeError('rounds must be an integer'); if (opts.rounds > 0) rounds = opts.rounds; } const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen); const salt = randomBytes(SALT_LEN); const r = bcrypt_pbkdf( passphrase, passphrase.length, salt, salt.length, gen, gen.length, rounds ); if (r !== 0) return new Error('Failed to generate information to encrypt key'); /* string salt uint32 rounds */ const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4); { let pos = 0; kdfOptions.writeUInt32BE(salt.length, pos += 0); kdfOptions.set(salt, pos += 4); kdfOptions.writeUInt32BE(rounds, pos += salt.length); } encrypted = { cipher, cipherName: opts.cipher, kdfName: 'bcrypt', kdfOptions, key: gen.slice(0, cipher.keyLen), iv: gen.slice(cipher.keyLen), }; } } } switch (format) { case 'new': { let privateB64 = '-----BEGIN OPENSSH PRIVATE KEY-----\n'; let publicB64; /* byte[] "openssh-key-v1\0" string ciphername string kdfname string kdfoptions uint32 number of keys N string publickey1 string encrypted, padded list of private keys uint32 checkint uint32 checkint byte[] privatekey1 string comment1 byte 1 byte 2 byte 3 ... byte padlen % 255 */ const cipherName = Buffer.from(encrypted ? encrypted.cipherName : 'none'); const kdfName = Buffer.from(encrypted ? encrypted.kdfName : 'none'); const kdfOptions = (encrypted ? encrypted.kdfOptions : Buffer.alloc(0)); const blockLen = (encrypted ? encrypted.cipher.blockLen : 8); const parsed = parseDERs(keyType, pub, priv); const checkInt = randomBytes(4); const commentBin = Buffer.from(comment); const privBlobLen = (4 + 4 + parsed.priv.length + 4 + commentBin.length); let padding = []; for (let i = 1; ((privBlobLen + padding.length) % blockLen); ++i) padding.push(i & 0xFF); padding = Buffer.from(padding); let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length); let extra; { let pos = 0; privBlob.set(checkInt, pos += 0); privBlob.set(checkInt, pos += 4); privBlob.set(parsed.priv, pos += 4); privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length); privBlob.set(commentBin, pos += 4); privBlob.set(padding, pos += commentBin.length); } if (encrypted) { const options = { authTagLength: encrypted.cipher.authLen }; const cipher = createCipheriv( encrypted.cipher.sslName, encrypted.key, encrypted.iv, options ); cipher.setAutoPadding(false); privBlob = Buffer.concat([ cipher.update(privBlob), cipher.final() ]); if (encrypted.cipher.authLen > 0) extra = cipher.getAuthTag(); else extra = Buffer.alloc(0); encrypted.key.fill(0); encrypted.iv.fill(0); } else { extra = Buffer.alloc(0); } const magicBytes = Buffer.from('openssh-key-v1\0'); const privBin = Buffer.allocUnsafe( magicBytes.length + 4 + cipherName.length + 4 + kdfName.length + 4 + kdfOptions.length + 4 + 4 + parsed.pub.length + 4 + privBlob.length + extra.length ); { let pos = 0; privBin.set(magicBytes, pos += 0); privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length); privBin.set(cipherName, pos += 4); privBin.writeUInt32BE(kdfName.length, pos += cipherName.length); privBin.set(kdfName, pos += 4); privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length); privBin.set(kdfOptions, pos += 4); privBin.writeUInt32BE(1, pos += kdfOptions.length); privBin.writeUInt32BE(parsed.pub.length, pos += 4); privBin.set(parsed.pub, pos += 4); privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length); privBin.set(privBlob, pos += 4); privBin.set(extra, pos += privBlob.length); } { const b64 = privBin.base64Slice(0, privBin.length); let formatted = b64.replace(/.{64}/g, '$&\n'); if (b64.length & 63) formatted += '\n'; privateB64 += formatted; } { const b64 = parsed.pub.base64Slice(0, parsed.pub.length); publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ''}`; } privateB64 += '-----END OPENSSH PRIVATE KEY-----\n'; return { private: privateB64, public: publicB64, }; } default: throw new Error('Invalid output key format'); } } function noop() {} module.exports = { generateKeyPair: (keyType, opts, cb) => { if (typeof opts === 'function') { cb = opts; opts = undefined; } if (typeof cb !== 'function') cb = noop; const args = makeArgs(keyType, opts); generateKeyPair_(...args, (err, pub, priv) => { if (err) return cb(err); let ret; try { ret = convertKeys(args[0], pub, priv, opts); } catch (ex) { return cb(ex); } cb(null, ret); }); }, generateKeyPairSync: (keyType, opts) => { const args = makeArgs(keyType, opts); const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args); return convertKeys(args[0], pub, priv, opts); } }; /***/ }), /***/ 7841: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* TODO: * Replace `buffer._pos` usage in keyParser.js and elsewhere * Utilize optional "writev" support when writing packets from cipher.encrypt() * Built-in support for automatic re-keying, on by default * Revisit receiving unexpected/unknown packets * Error (fatal or otherwise) or ignore or pass on to user (in some or all cases)? * Including server/client check for single directional packet types? * Check packets for validity or bail as early as possible? * Automatic re-key every 2**31 packets after the last key exchange (sent or received), as suggested by RFC4344. OpenSSH currently does this. * Automatic re-key every so many blocks depending on cipher. RFC4344: Because of a birthday property of block ciphers and some modes of operation, implementations must be careful not to encrypt too many blocks with the same encryption key. Let L be the block length (in bits) of an SSH encryption method's block cipher (e.g., 128 for AES). If L is at least 128, then, after rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) blocks before rekeying again. If L is at least 128, then SSH implementations should also attempt to force a rekey before receiving more than 2**(L/4) blocks. If L is less than 128 (which is the case for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, although it may be too expensive to rekey every 2**(L/4) blocks, it is still advisable for SSH implementations to follow the original recommendation in [RFC4253]: rekey at least once for every gigabyte of transmitted data. Note that if L is less than or equal to 128, then the recommendation in this subsection supersedes the recommendation in Section 3.1. If an SSH implementation uses a block cipher with a larger block size (e.g., Rijndael with 256-bit blocks), then the recommendations in Section 3.1 may supersede the recommendations in this subsection (depending on the lengths of the packets). */ const { inspect } = __nccwpck_require__(9023); const { bindingAvailable, NullCipher, NullDecipher } = __nccwpck_require__(2888); const { COMPAT_CHECKS, DISCONNECT_REASON, eddsaSupported, MESSAGE, SIGNALS, TERMINAL_MODE, } = __nccwpck_require__(4020); const { DEFAULT_KEXINIT_CLIENT, DEFAULT_KEXINIT_SERVER, KexInit, kexinit, onKEXPayload, } = __nccwpck_require__(4637); const { parseKey, } = __nccwpck_require__(1789); const MESSAGE_HANDLERS = __nccwpck_require__(9244); const { bufferCopy, bufferFill, bufferSlice, convertSignature, sendPacket, writeUInt32BE, } = __nccwpck_require__(2184); const { PacketReader, PacketWriter, ZlibPacketReader, ZlibPacketWriter, } = __nccwpck_require__(4592); const MODULE_VER = (__nccwpck_require__(8342)/* .version */ .rE); const VALID_DISCONNECT_REASONS = new Map( Object.values(DISCONNECT_REASON).map((n) => [n, 1]) ); const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); const MAX_LINE_LEN = 8192; const MAX_LINES = 1024; const PING_PAYLOAD = Buffer.from([ MESSAGE.GLOBAL_REQUEST, // "keepalive@openssh.com" 0, 0, 0, 21, 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, 115, 104, 46, 99, 111, 109, // Request a reply 1, ]); const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); function noop() {} /* Inbound: * kexinit payload (needed only until exchange hash is generated) * raw ident * rekey packet queue * expected packet (implemented as separate _parse() function?) Outbound: * kexinit payload (needed only until exchange hash is generated) * rekey packet queue * kex secret (needed only until NEWKEYS) * exchange hash (needed only until NEWKEYS) * session ID (set to exchange hash from initial handshake) */ class Protocol { constructor(config) { const onWrite = config.onWrite; if (typeof onWrite !== 'function') throw new Error('Missing onWrite function'); this._onWrite = (data) => { onWrite(data); }; const onError = config.onError; if (typeof onError !== 'function') throw new Error('Missing onError function'); this._onError = (err) => { onError(err); }; const debug = config.debug; this._debug = (typeof debug === 'function' ? (msg) => { debug(msg); } : undefined); const onHeader = config.onHeader; this._onHeader = (typeof onHeader === 'function' ? (...args) => { onHeader(...args); } : noop); const onPacket = config.onPacket; this._onPacket = (typeof onPacket === 'function' ? () => { onPacket(); } : noop); let onHandshakeComplete = config.onHandshakeComplete; if (typeof onHandshakeComplete !== 'function') onHandshakeComplete = noop; let firstHandshake; this._onHandshakeComplete = (...args) => { this._debug && this._debug('Handshake completed'); if (firstHandshake === undefined) firstHandshake = true; else firstHandshake = false; // Process packets queued during a rekey where necessary const oldQueue = this._queue; if (oldQueue) { this._queue = undefined; this._debug && this._debug( `Draining outbound queue (${oldQueue.length}) ...` ); for (let i = 0; i < oldQueue.length; ++i) { const data = oldQueue[i]; // data === payload only // XXX: hacky let finalized = this._packetRW.write.finalize(data); if (finalized === data) { const packet = this._cipher.allocPacket(data.length); packet.set(data, 5); finalized = packet; } sendPacket(this, finalized); } this._debug && this._debug('... finished draining outbound queue'); } if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled) sendExtInfo(this); onHandshakeComplete(...args); }; this._queue = undefined; const messageHandlers = config.messageHandlers; if (typeof messageHandlers === 'object' && messageHandlers !== null) this._handlers = messageHandlers; else this._handlers = {}; this._onPayload = onPayload.bind(this); this._server = !!config.server; this._banner = undefined; let greeting; if (this._server) { if (typeof config.hostKeys !== 'object' || config.hostKeys === null) throw new Error('Missing server host key(s)'); this._hostKeys = config.hostKeys; // Greeting displayed before the ssh identification string is sent, this // is usually ignored by most clients if (typeof config.greeting === 'string' && config.greeting.length) { greeting = (config.greeting.slice(-2) === '\r\n' ? config.greeting : `${config.greeting}\r\n`); } // Banner shown after the handshake completes, but before user // authentication begins if (typeof config.banner === 'string' && config.banner.length) { this._banner = (config.banner.slice(-2) === '\r\n' ? config.banner : `${config.banner}\r\n`); } } else { this._hostKeys = undefined; } let offer = config.offer; if (typeof offer !== 'object' || offer === null) { offer = (this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT); } else if (offer.constructor !== KexInit) { if (this._server) { offer.kex = offer.kex.concat(['kex-strict-s-v00@openssh.com']); } else { offer.kex = offer.kex.concat([ 'ext-info-c', 'kex-strict-c-v00@openssh.com', ]); } offer = new KexInit(offer); } this._kex = undefined; this._strictMode = undefined; this._kexinit = undefined; this._offer = offer; this._cipher = new NullCipher(0, this._onWrite); this._decipher = undefined; this._skipNextInboundPacket = false; this._packetRW = { read: new PacketReader(), write: new PacketWriter(this), }; this._hostVerifier = (!this._server && typeof config.hostVerifier === 'function' ? config.hostVerifier : undefined); this._parse = parseHeader; this._buffer = undefined; this._authsQueue = []; this._authenticated = false; this._remoteIdentRaw = undefined; let sentIdent; if (typeof config.ident === 'string') { this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); sentIdent.set(this._identRaw, 0); sentIdent[sentIdent.length - 2] = 13; // '\r' sentIdent[sentIdent.length - 1] = 10; // '\n' } else if (Buffer.isBuffer(config.ident)) { const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); fullIdent.latin1Write('SSH-2.0-', 0, 8); fullIdent.set(config.ident, 8); this._identRaw = fullIdent; sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); sentIdent.set(fullIdent, 0); sentIdent[sentIdent.length - 2] = 13; // '\r' sentIdent[sentIdent.length - 1] = 10; // '\n' } else { this._identRaw = IDENT_RAW; sentIdent = IDENT; } this._compatFlags = 0; if (this._debug) { if (bindingAvailable) this._debug('Custom crypto binding available'); else this._debug('Custom crypto binding not available'); } this._debug && this._debug( `Local ident: ${inspect(this._identRaw.toString())}` ); this.start = () => { this.start = undefined; if (greeting) this._onWrite(greeting); this._onWrite(sentIdent); }; } _destruct(reason) { this._packetRW.read.cleanup(); this._packetRW.write.cleanup(); this._cipher && this._cipher.free(); this._decipher && this._decipher.free(); if (typeof reason !== 'string' || reason.length === 0) reason = 'fatal error'; this.parse = () => { throw new Error(`Instance unusable after ${reason}`); }; this._onWrite = () => { throw new Error(`Instance unusable after ${reason}`); }; this._destruct = undefined; } cleanup() { this._destruct && this._destruct(); } parse(chunk, i, len) { while (i < len) i = this._parse(chunk, i, len); } // Protocol message API // =========================================================================== // Common/Shared ============================================================= // =========================================================================== // Global // ------ disconnect(reason) { const pktLen = 1 + 4 + 4 + 4; // We don't use _packetRW.write.* here because we need to make sure that // we always get a full packet allocated because this message can be sent // at any time -- even during a key exchange let p = this._packetRW.write.allocStartKEX; const packet = this._packetRW.write.alloc(pktLen, true); const end = p + pktLen; if (!VALID_DISCONNECT_REASONS.has(reason)) reason = DISCONNECT_REASON.PROTOCOL_ERROR; packet[p] = MESSAGE.DISCONNECT; writeUInt32BE(packet, reason, ++p); packet.fill(0, p += 4, end); this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); sendPacket(this, this._packetRW.write.finalize(packet, true), true); } ping() { const p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); packet.set(PING_PAYLOAD, p); this._debug && this._debug( 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' ); sendPacket(this, this._packetRW.write.finalize(packet)); } rekey() { if (this._kexinit === undefined) { this._debug && this._debug('Outbound: Initiated explicit rekey'); this._queue = []; kexinit(this); } else { this._debug && this._debug('Outbound: Ignoring rekey during handshake'); } } // 'ssh-connection' service-specific // --------------------------------- requestSuccess(data) { let p = this._packetRW.write.allocStart; let packet; if (Buffer.isBuffer(data)) { packet = this._packetRW.write.alloc(1 + data.length); packet[p] = MESSAGE.REQUEST_SUCCESS; packet.set(data, ++p); } else { packet = this._packetRW.write.alloc(1); packet[p] = MESSAGE.REQUEST_SUCCESS; } this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); sendPacket(this, this._packetRW.write.finalize(packet)); } requestFailure() { const p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1); packet[p] = MESSAGE.REQUEST_FAILURE; this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); sendPacket(this, this._packetRW.write.finalize(packet)); } channelSuccess(chan) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4); packet[p] = MESSAGE.CHANNEL_SUCCESS; writeUInt32BE(packet, chan, ++p); this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelFailure(chan) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4); packet[p] = MESSAGE.CHANNEL_FAILURE; writeUInt32BE(packet, chan, ++p); this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelEOF(chan) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4); packet[p] = MESSAGE.CHANNEL_EOF; writeUInt32BE(packet, chan, ++p); this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelClose(chan) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4); packet[p] = MESSAGE.CHANNEL_CLOSE; writeUInt32BE(packet, chan, ++p); this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelWindowAdjust(chan, amount) { // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4); packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, amount, p += 4); this._debug && this._debug( `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } channelData(chan, data) { const isBuffer = Buffer.isBuffer(data); const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); packet[p] = MESSAGE.CHANNEL_DATA; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, dataLen, p += 4); if (isBuffer) packet.set(data, p += 4); else packet.utf8Write(data, p += 4, dataLen); this._debug && this._debug( `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } channelExtData(chan, data, type) { const isBuffer = Buffer.isBuffer(data); const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, type, p += 4); writeUInt32BE(packet, dataLen, p += 4); if (isBuffer) packet.set(data, p += 4); else packet.utf8Write(data, p += 4, dataLen); this._debug && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); sendPacket(this, this._packetRW.write.finalize(packet)); } channelOpenConfirm(remote, local, initWindow, maxPacket) { let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; writeUInt32BE(packet, remote, ++p); writeUInt32BE(packet, local, p += 4); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } channelOpenFail(remote, reason, desc) { if (typeof desc !== 'string') desc = ''; const descLen = Buffer.byteLength(desc); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; writeUInt32BE(packet, remote, ++p); writeUInt32BE(packet, reason, p += 4); writeUInt32BE(packet, descLen, p += 4); p += 4; if (descLen) { packet.utf8Write(desc, p, descLen); p += descLen; } writeUInt32BE(packet, 0, p); // Empty language tag this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); sendPacket(this, this._packetRW.write.finalize(packet)); } // =========================================================================== // Client-specific =========================================================== // =========================================================================== // Global // ------ service(name) { if (this._server) throw new Error('Client-only method called in server mode'); const nameLen = Buffer.byteLength(name); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + nameLen); packet[p] = MESSAGE.SERVICE_REQUEST; writeUInt32BE(packet, nameLen, ++p); packet.utf8Write(name, p += 4, nameLen); this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); sendPacket(this, this._packetRW.write.finalize(packet)); } // 'ssh-userauth' service-specific // ------------------------------- authPassword(username, password, newPassword) { if (this._server) throw new Error('Client-only method called in server mode'); const userLen = Buffer.byteLength(username); const passLen = Buffer.byteLength(password); const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen + (newPassword ? 4 + newPassLen : 0) ); packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 8, p += 14); packet.utf8Write('password', p += 4, 8); packet[p += 8] = (newPassword ? 1 : 0); writeUInt32BE(packet, passLen, ++p); if (Buffer.isBuffer(password)) bufferCopy(password, packet, 0, passLen, p += 4); else packet.utf8Write(password, p += 4, passLen); if (newPassword) { writeUInt32BE(packet, newPassLen, p += passLen); if (Buffer.isBuffer(newPassword)) bufferCopy(newPassword, packet, 0, newPassLen, p += 4); else packet.utf8Write(newPassword, p += 4, newPassLen); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (changed password)' ); } else { this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (password)' ); } this._authsQueue.push('password'); sendPacket(this, this._packetRW.write.finalize(packet)); } authPK(username, pubKey, keyAlgo, cbSign) { if (this._server) throw new Error('Client-only method called in server mode'); pubKey = parseKey(pubKey); if (pubKey instanceof Error) throw new Error('Invalid key'); const keyType = pubKey.type; pubKey = pubKey.getPublicSSH(); if (typeof keyAlgo === 'function') { cbSign = keyAlgo; keyAlgo = undefined; } if (!keyAlgo) keyAlgo = keyType; const userLen = Buffer.byteLength(username); const algoLen = Buffer.byteLength(keyAlgo); const pubKeyLen = pubKey.length; const sessionID = this._kex.sessionID; const sesLen = sessionID.length; const payloadLen = (cbSign ? 4 + sesLen : 0) + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; let packet; let p; if (cbSign) { packet = Buffer.allocUnsafe(payloadLen); p = 0; writeUInt32BE(packet, sesLen, p); packet.set(sessionID, p += 4); p += sesLen; } else { packet = this._packetRW.write.alloc(payloadLen); p = this._packetRW.write.allocStart; } packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 9, p += 14); packet.utf8Write('publickey', p += 4, 9); packet[p += 9] = (cbSign ? 1 : 0); writeUInt32BE(packet, algoLen, ++p); packet.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(packet, pubKeyLen, p += algoLen); packet.set(pubKey, p += 4); if (!cbSign) { this._authsQueue.push('publickey'); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' ); sendPacket(this, this._packetRW.write.finalize(packet)); return; } cbSign(packet, (signature) => { signature = convertSignature(signature, keyType); if (signature === false) throw new Error('Error while converting handshake signature'); const sigLen = signature.length; p = this._packetRW.write.allocStart; packet = this._packetRW.write.alloc( 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 + 4 + algoLen + 4 + sigLen ); // TODO: simply copy from original "packet" to new `packet` to avoid // having to write each individual field a second time? packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 9, p += 14); packet.utf8Write('publickey', p += 4, 9); packet[p += 9] = 1; writeUInt32BE(packet, algoLen, ++p); packet.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(packet, pubKeyLen, p += algoLen); packet.set(pubKey, p += 4); writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); writeUInt32BE(packet, algoLen, p += 4); packet.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(packet, sigLen, p += algoLen); packet.set(signature, p += 4); // Servers shouldn't send packet type 60 in response to signed publickey // attempts, but if they do, interpret as type 60. this._authsQueue.push('publickey'); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (publickey)' ); sendPacket(this, this._packetRW.write.finalize(packet)); }); } authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) { // TODO: Make DRY by sharing similar code with authPK() if (this._server) throw new Error('Client-only method called in server mode'); pubKey = parseKey(pubKey); if (pubKey instanceof Error) throw new Error('Invalid key'); const keyType = pubKey.type; pubKey = pubKey.getPublicSSH(); if (typeof keyAlgo === 'function') { cbSign = keyAlgo; keyAlgo = undefined; } if (!keyAlgo) keyAlgo = keyType; const userLen = Buffer.byteLength(username); const algoLen = Buffer.byteLength(keyAlgo); const pubKeyLen = pubKey.length; const sessionID = this._kex.sessionID; const sesLen = sessionID.length; const hostnameLen = Buffer.byteLength(hostname); const userlocalLen = Buffer.byteLength(userlocal); const data = Buffer.allocUnsafe( 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen ); let p = 0; writeUInt32BE(data, sesLen, p); data.set(sessionID, p += 4); data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(data, userLen, ++p); data.utf8Write(username, p += 4, userLen); writeUInt32BE(data, 14, p += userLen); data.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(data, 9, p += 14); data.utf8Write('hostbased', p += 4, 9); writeUInt32BE(data, algoLen, p += 9); data.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(data, pubKeyLen, p += algoLen); data.set(pubKey, p += 4); writeUInt32BE(data, hostnameLen, p += pubKeyLen); data.utf8Write(hostname, p += 4, hostnameLen); writeUInt32BE(data, userlocalLen, p += hostnameLen); data.utf8Write(userlocal, p += 4, userlocalLen); cbSign(data, (signature) => { signature = convertSignature(signature, keyType); if (!signature) throw new Error('Error while converting handshake signature'); const sigLen = signature.length; const reqDataLen = (data.length - sesLen - 4); p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( reqDataLen + 4 + 4 + algoLen + 4 + sigLen ); bufferCopy(data, packet, 4 + sesLen, data.length, p); writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); writeUInt32BE(packet, algoLen, p += 4); packet.utf8Write(keyAlgo, p += 4, algoLen); writeUInt32BE(packet, sigLen, p += algoLen); packet.set(signature, p += 4); this._authsQueue.push('hostbased'); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (hostbased)' ); sendPacket(this, this._packetRW.write.finalize(packet)); }); } authKeyboard(username) { if (this._server) throw new Error('Client-only method called in server mode'); const userLen = Buffer.byteLength(username); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 ); packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 20, p += 14); packet.utf8Write('keyboard-interactive', p += 4, 20); writeUInt32BE(packet, 0, p += 20); writeUInt32BE(packet, 0, p += 4); this._authsQueue.push('keyboard-interactive'); this._debug && this._debug( 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' ); sendPacket(this, this._packetRW.write.finalize(packet)); } authNone(username) { if (this._server) throw new Error('Client-only method called in server mode'); const userLen = Buffer.byteLength(username); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); packet[p] = MESSAGE.USERAUTH_REQUEST; writeUInt32BE(packet, userLen, ++p); packet.utf8Write(username, p += 4, userLen); writeUInt32BE(packet, 14, p += userLen); packet.utf8Write('ssh-connection', p += 4, 14); writeUInt32BE(packet, 4, p += 14); packet.utf8Write('none', p += 4, 4); this._authsQueue.push('none'); this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); sendPacket(this, this._packetRW.write.finalize(packet)); } authInfoRes(responses) { if (this._server) throw new Error('Client-only method called in server mode'); let responsesTotalLen = 0; let responseLens; if (responses) { responseLens = new Array(responses.length); for (let i = 0; i < responses.length; ++i) { const len = Buffer.byteLength(responses[i]); responseLens[i] = len; responsesTotalLen += 4 + len; } } let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; if (responses) { writeUInt32BE(packet, responses.length, ++p); p += 4; for (let i = 0; i < responses.length; ++i) { const len = responseLens[i]; writeUInt32BE(packet, len, p); p += 4; if (len) { packet.utf8Write(responses[i], p, len); p += len; } } } else { writeUInt32BE(packet, 0, ++p); } this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); sendPacket(this, this._packetRW.write.finalize(packet)); } // 'ssh-connection' service-specific // --------------------------------- tcpipForward(bindAddr, bindPort, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); const addrLen = Buffer.byteLength(bindAddr); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 13, ++p); packet.utf8Write('tcpip-forward', p += 4, 13); packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, addrLen, ++p); packet.utf8Write(bindAddr, p += 4, addrLen); writeUInt32BE(packet, bindPort, p += addrLen); this._debug && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); sendPacket(this, this._packetRW.write.finalize(packet)); } cancelTcpipForward(bindAddr, bindPort, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); const addrLen = Buffer.byteLength(bindAddr); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 20, ++p); packet.utf8Write('cancel-tcpip-forward', p += 4, 20); packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, addrLen, ++p); packet.utf8Write(bindAddr, p += 4, addrLen); writeUInt32BE(packet, bindPort, p += addrLen); this._debug && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_streamLocalForward(socketPath, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); const socketPathLen = Buffer.byteLength(socketPath); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 31 + 1 + 4 + socketPathLen ); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 31, ++p); packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, socketPathLen, ++p); packet.utf8Write(socketPath, p += 4, socketPathLen); this._debug && this._debug( 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_cancelStreamLocalForward(socketPath, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); const socketPathLen = Buffer.byteLength(socketPath); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 38 + 1 + 4 + socketPathLen ); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 38, ++p); packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, socketPathLen, ++p); packet.utf8Write(socketPath, p += 4, socketPathLen); if (this._debug) { this._debug( 'Outbound: Sending GLOBAL_REQUEST ' + '(cancel-streamlocal-forward@openssh.com)' ); } sendPacket(this, this._packetRW.write.finalize(packet)); } directTcpip(chan, initWindow, maxPacket, cfg) { if (this._server) throw new Error('Client-only method called in server mode'); const srcLen = Buffer.byteLength(cfg.srcIP); const dstLen = Buffer.byteLength(cfg.dstIP); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 12, ++p); packet.utf8Write('direct-tcpip', p += 4, 12); writeUInt32BE(packet, chan, p += 12); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, dstLen, p += 4); packet.utf8Write(cfg.dstIP, p += 4, dstLen); writeUInt32BE(packet, cfg.dstPort, p += dstLen); writeUInt32BE(packet, srcLen, p += 4); packet.utf8Write(cfg.srcIP, p += 4, srcLen); writeUInt32BE(packet, cfg.srcPort, p += srcLen); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { if (this._server) throw new Error('Client-only method called in server mode'); const pathLen = Buffer.byteLength(cfg.socketPath); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 30, ++p); packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); writeUInt32BE(packet, chan, p += 30); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, pathLen, p += 4); packet.utf8Write(cfg.socketPath, p += 4, pathLen); // zero-fill reserved fields (string and uint32) bufferFill(packet, 0, p += pathLen, p + 8); if (this._debug) { this._debug( 'Outbound: Sending CHANNEL_OPEN ' + `(r:${chan}, direct-streamlocal@openssh.com)` ); } sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_noMoreSessions(wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 28, ++p); packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); this._debug && this._debug( 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' ); sendPacket(this, this._packetRW.write.finalize(packet)); } session(chan, initWindow, maxPacket) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 7, ++p); packet.utf8Write('session', p += 4, 7); writeUInt32BE(packet, chan, p += 7); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); sendPacket(this, this._packetRW.write.finalize(packet)); } windowChange(chan, rows, cols, height, width) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 13, p += 4); packet.utf8Write('window-change', p += 4, 13); packet[p += 13] = 0; writeUInt32BE(packet, cols, ++p); writeUInt32BE(packet, rows, p += 4); writeUInt32BE(packet, width, p += 4); writeUInt32BE(packet, height, p += 4); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } pty(chan, rows, cols, height, width, term, modes, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space if (!term || !term.length) term = 'vt100'; if (modes && !Buffer.isBuffer(modes) && !Array.isArray(modes) && typeof modes === 'object' && modes !== null) { modes = modesToBytes(modes); } if (!modes || !modes.length) modes = NO_TERMINAL_MODES_BUFFER; const termLen = term.length; const modesLen = modes.length; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 7, p += 4); packet.utf8Write('pty-req', p += 4, 7); packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, termLen, ++p); packet.utf8Write(term, p += 4, termLen); writeUInt32BE(packet, cols, p += termLen); writeUInt32BE(packet, rows, p += 4); writeUInt32BE(packet, width, p += 4); writeUInt32BE(packet, height, p += 4); writeUInt32BE(packet, modesLen, p += 4); p += 4; if (Array.isArray(modes)) { for (let i = 0; i < modesLen; ++i) packet[p++] = modes[i]; } else if (Buffer.isBuffer(modes)) { packet.set(modes, p); } this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); sendPacket(this, this._packetRW.write.finalize(packet)); } shell(chan, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 5, p += 4); packet.utf8Write('shell', p += 4, 5); packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); sendPacket(this, this._packetRW.write.finalize(packet)); } exec(chan, cmd, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const isBuf = Buffer.isBuffer(cmd); const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 4, p += 4); packet.utf8Write('exec', p += 4, 4); packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, cmdLen, ++p); if (isBuf) packet.set(cmd, p += 4); else packet.utf8Write(cmd, p += 4, cmdLen); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } signal(chan, signal) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const origSignal = signal; signal = signal.toUpperCase(); if (signal.slice(0, 3) === 'SIG') signal = signal.slice(3); if (SIGNALS[signal] !== 1) throw new Error(`Invalid signal: ${origSignal}`); const signalLen = signal.length; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 6 + 1 + 4 + signalLen ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 6, p += 4); packet.utf8Write('signal', p += 4, 6); packet[p += 6] = 0; writeUInt32BE(packet, signalLen, ++p); packet.utf8Write(signal, p += 4, signalLen); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } env(chan, key, val, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const keyLen = Buffer.byteLength(key); const isBuf = Buffer.isBuffer(val); const valLen = (isBuf ? val.length : Buffer.byteLength(val)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 3, p += 4); packet.utf8Write('env', p += 4, 3); packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, keyLen, ++p); packet.utf8Write(key, p += 4, keyLen); writeUInt32BE(packet, valLen, p += keyLen); if (isBuf) packet.set(val, p += 4); else packet.utf8Write(val, p += 4, valLen); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } x11Forward(chan, cfg, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const protocol = cfg.protocol; const cookie = cfg.cookie; const isBufProto = Buffer.isBuffer(protocol); const protoLen = (isBufProto ? protocol.length : Buffer.byteLength(protocol)); const isBufCookie = Buffer.isBuffer(cookie); const cookieLen = (isBufCookie ? cookie.length : Buffer.byteLength(cookie)); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 7, p += 4); packet.utf8Write('x11-req', p += 4, 7); packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); packet[++p] = (cfg.single ? 1 : 0); writeUInt32BE(packet, protoLen, ++p); if (isBufProto) packet.set(protocol, p += 4); else packet.utf8Write(protocol, p += 4, protoLen); writeUInt32BE(packet, cookieLen, p += protoLen); if (isBufCookie) packet.set(cookie, p += 4); else packet.latin1Write(cookie, p += 4, cookieLen); writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); sendPacket(this, this._packetRW.write.finalize(packet)); } subsystem(chan, name, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space const nameLen = Buffer.byteLength(name); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 9, p += 4); packet.utf8Write('subsystem', p += 4, 9); packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); writeUInt32BE(packet, nameLen, ++p); packet.utf8Write(name, p += 4, nameLen); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_agentForward(chan, wantReply) { if (this._server) throw new Error('Client-only method called in server mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 26, p += 4); packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); if (this._debug) { this._debug( 'Outbound: Sending CHANNEL_REQUEST ' + `(r:${chan}, auth-agent-req@openssh.com)` ); } sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_hostKeysProve(keys) { if (this._server) throw new Error('Client-only method called in server mode'); let keysTotal = 0; const publicKeys = []; for (const key of keys) { const publicKey = key.getPublicSSH(); keysTotal += 4 + publicKey.length; publicKeys.push(publicKey); } let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); packet[p] = MESSAGE.GLOBAL_REQUEST; writeUInt32BE(packet, 29, ++p); packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); packet[p += 29] = 1; // want reply ++p; for (const buf of publicKeys) { writeUInt32BE(packet, buf.length, p); bufferCopy(buf, packet, 0, buf.length, p += 4); p += buf.length; } if (this._debug) { this._debug( 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' ); } sendPacket(this, this._packetRW.write.finalize(packet)); } // =========================================================================== // Server-specific =========================================================== // =========================================================================== // Global // ------ serviceAccept(svcName) { if (!this._server) throw new Error('Server-only method called in client mode'); const svcNameLen = Buffer.byteLength(svcName); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); packet[p] = MESSAGE.SERVICE_ACCEPT; writeUInt32BE(packet, svcNameLen, ++p); packet.utf8Write(svcName, p += 4, svcNameLen); this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); sendPacket(this, this._packetRW.write.finalize(packet)); if (this._server && this._banner && svcName === 'ssh-userauth') { const banner = this._banner; this._banner = undefined; // Prevent banner from being displayed again const bannerLen = Buffer.byteLength(banner); p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); packet[p] = MESSAGE.USERAUTH_BANNER; writeUInt32BE(packet, bannerLen, ++p); packet.utf8Write(banner, p += 4, bannerLen); writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); sendPacket(this, this._packetRW.write.finalize(packet)); } } // 'ssh-connection' service-specific forwardedTcpip(chan, initWindow, maxPacket, cfg) { if (!this._server) throw new Error('Server-only method called in client mode'); const boundAddrLen = Buffer.byteLength(cfg.boundAddr); const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 15, ++p); packet.utf8Write('forwarded-tcpip', p += 4, 15); writeUInt32BE(packet, chan, p += 15); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, boundAddrLen, p += 4); packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); writeUInt32BE(packet, remoteAddrLen, p += 4); packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } x11(chan, initWindow, maxPacket, cfg) { if (!this._server) throw new Error('Server-only method called in client mode'); const addrLen = Buffer.byteLength(cfg.originAddr); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 3, ++p); packet.utf8Write('x11', p += 4, 3); writeUInt32BE(packet, chan, p += 3); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, addrLen, p += 4); packet.utf8Write(cfg.originAddr, p += 4, addrLen); writeUInt32BE(packet, cfg.originPort, p += addrLen); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_authAgent(chan, initWindow, maxPacket) { if (!this._server) throw new Error('Server-only method called in client mode'); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 22, ++p); packet.utf8Write('auth-agent@openssh.com', p += 4, 22); writeUInt32BE(packet, chan, p += 22); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); this._debug && this._debug( `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` ); sendPacket(this, this._packetRW.write.finalize(packet)); } openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { if (!this._server) throw new Error('Server-only method called in client mode'); const pathLen = Buffer.byteLength(cfg.socketPath); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 ); packet[p] = MESSAGE.CHANNEL_OPEN; writeUInt32BE(packet, 33, ++p); packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); writeUInt32BE(packet, chan, p += 33); writeUInt32BE(packet, initWindow, p += 4); writeUInt32BE(packet, maxPacket, p += 4); writeUInt32BE(packet, pathLen, p += 4); packet.utf8Write(cfg.socketPath, p += 4, pathLen); writeUInt32BE(packet, 0, p += pathLen); if (this._debug) { this._debug( 'Outbound: Sending CHANNEL_OPEN ' + `(r:${chan}, forwarded-streamlocal@openssh.com)` ); } sendPacket(this, this._packetRW.write.finalize(packet)); } exitStatus(chan, status) { if (!this._server) throw new Error('Server-only method called in client mode'); // Does not consume window space let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 11, p += 4); packet.utf8Write('exit-status', p += 4, 11); packet[p += 11] = 0; writeUInt32BE(packet, status, ++p); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } exitSignal(chan, name, coreDumped, msg) { if (!this._server) throw new Error('Server-only method called in client mode'); // Does not consume window space const origSignal = name; if (typeof origSignal !== 'string' || !origSignal) throw new Error(`Invalid signal: ${origSignal}`); let signal = name.toUpperCase(); if (signal.slice(0, 3) === 'SIG') signal = signal.slice(3); if (SIGNALS[signal] !== 1) throw new Error(`Invalid signal: ${origSignal}`); const nameLen = Buffer.byteLength(signal); const msgLen = (msg ? Buffer.byteLength(msg) : 0); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 ); packet[p] = MESSAGE.CHANNEL_REQUEST; writeUInt32BE(packet, chan, ++p); writeUInt32BE(packet, 11, p += 4); packet.utf8Write('exit-signal', p += 4, 11); packet[p += 11] = 0; writeUInt32BE(packet, nameLen, ++p); packet.utf8Write(signal, p += 4, nameLen); packet[p += nameLen] = (coreDumped ? 1 : 0); writeUInt32BE(packet, msgLen, ++p); p += 4; if (msgLen) { packet.utf8Write(msg, p, msgLen); p += msgLen; } writeUInt32BE(packet, 0, p); this._debug && this._debug( `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` ); sendPacket(this, this._packetRW.write.finalize(packet)); } // 'ssh-userauth' service-specific authFailure(authMethods, isPartial) { if (!this._server) throw new Error('Server-only method called in client mode'); if (this._authsQueue.length === 0) throw new Error('No auth in progress'); let methods; if (typeof authMethods === 'boolean') { isPartial = authMethods; authMethods = undefined; } if (authMethods) { methods = []; for (let i = 0; i < authMethods.length; ++i) { if (authMethods[i].toLowerCase() === 'none') continue; methods.push(authMethods[i]); } methods = methods.join(','); } else { methods = ''; } const methodsLen = methods.length; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); packet[p] = MESSAGE.USERAUTH_FAILURE; writeUInt32BE(packet, methodsLen, ++p); packet.utf8Write(methods, p += 4, methodsLen); packet[p += methodsLen] = (isPartial === true ? 1 : 0); this._authsQueue.shift(); this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); sendPacket(this, this._packetRW.write.finalize(packet)); } authSuccess() { if (!this._server) throw new Error('Server-only method called in client mode'); if (this._authsQueue.length === 0) throw new Error('No auth in progress'); const p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1); packet[p] = MESSAGE.USERAUTH_SUCCESS; this._authsQueue.shift(); this._authenticated = true; this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); sendPacket(this, this._packetRW.write.finalize(packet)); if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') this._packetRW.read = new ZlibPacketReader(); if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') this._packetRW.write = new ZlibPacketWriter(this); } authPKOK(keyAlgo, key) { if (!this._server) throw new Error('Server-only method called in client mode'); if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') throw new Error('"publickey" auth not in progress'); // TODO: support parsed key for `key` const keyAlgoLen = Buffer.byteLength(keyAlgo); const keyLen = key.length; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); packet[p] = MESSAGE.USERAUTH_PK_OK; writeUInt32BE(packet, keyAlgoLen, ++p); packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); writeUInt32BE(packet, keyLen, p += keyAlgoLen); packet.set(key, p += 4); this._authsQueue.shift(); this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); sendPacket(this, this._packetRW.write.finalize(packet)); } authPasswdChg(prompt) { if (!this._server) throw new Error('Server-only method called in client mode'); const promptLen = Buffer.byteLength(prompt); let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; writeUInt32BE(packet, promptLen, ++p); packet.utf8Write(prompt, p += 4, promptLen); writeUInt32BE(packet, 0, p += promptLen); // Empty language tag this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); sendPacket(this, this._packetRW.write.finalize(packet)); } authInfoReq(name, instructions, prompts) { if (!this._server) throw new Error('Server-only method called in client mode'); let promptsLen = 0; const nameLen = name ? Buffer.byteLength(name) : 0; const instrLen = instructions ? Buffer.byteLength(instructions) : 0; for (let i = 0; i < prompts.length; ++i) promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; let p = this._packetRW.write.allocStart; const packet = this._packetRW.write.alloc( 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen ); packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; writeUInt32BE(packet, nameLen, ++p); p += 4; if (name) { packet.utf8Write(name, p, nameLen); p += nameLen; } writeUInt32BE(packet, instrLen, p); p += 4; if (instructions) { packet.utf8Write(instructions, p, instrLen); p += instrLen; } writeUInt32BE(packet, 0, p); writeUInt32BE(packet, prompts.length, p += 4); p += 4; for (let i = 0; i < prompts.length; ++i) { const prompt = prompts[i]; const promptLen = Buffer.byteLength(prompt.prompt); writeUInt32BE(packet, promptLen, p); p += 4; if (promptLen) { packet.utf8Write(prompt.prompt, p, promptLen); p += promptLen; } packet[p++] = (prompt.echo ? 1 : 0); } this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); sendPacket(this, this._packetRW.write.finalize(packet)); } } // SSH-protoversion-softwareversion (SP comments) CR LF const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; // TODO: optimize this by starting n bytes from the end of this._buffer instead // of the beginning function parseHeader(chunk, p, len) { let data; let chunkOffset; if (this._buffer) { data = Buffer.allocUnsafe(this._buffer.length + (len - p)); data.set(this._buffer, 0); if (p === 0) { data.set(chunk, this._buffer.length); } else { data.set(new Uint8Array(chunk.buffer, chunk.byteOffset + p, (len - p)), this._buffer.length); } chunkOffset = this._buffer.length; p = 0; } else { data = chunk; chunkOffset = 0; } const op = p; let start = p; let end = p; let needNL = false; let lineLen = 0; let lines = 0; for (; p < data.length; ++p) { const ch = data[p]; if (ch === 13 /* '\r' */) { needNL = true; continue; } if (ch === 10 /* '\n' */) { if (end > start && end - start > 4 && data[start] === 83 /* 'S' */ && data[start + 1] === 83 /* 'S' */ && data[start + 2] === 72 /* 'H' */ && data[start + 3] === 45 /* '-' */) { const full = data.latin1Slice(op, end + 1); const identRaw = (start === op ? full : full.slice(start - op)); const m = RE_IDENT.exec(identRaw); if (!m) throw new Error('Invalid identification string'); const header = { greeting: (start === op ? '' : full.slice(0, start - op)), identRaw, versions: { protocol: m[1], software: m[2], }, comments: m[3] }; // Needed during handshake this._remoteIdentRaw = Buffer.from(identRaw); this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); this._compatFlags = getCompatFlags(header); this._buffer = undefined; this._decipher = new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); this._parse = parsePacket; this._onHeader(header); if (!this._destruct) { // We disconnected inside _onHeader return len; } kexinit(this); return p + 1 - chunkOffset; } // Only allow pre-ident greetings when we're a client if (this._server) throw new Error('Greetings from clients not permitted'); if (++lines > MAX_LINES) throw new Error('Max greeting lines exceeded'); needNL = false; start = p + 1; lineLen = 0; } else if (needNL) { throw new Error('Invalid header: expected newline'); } else if (++lineLen >= MAX_LINE_LEN) { throw new Error('Header line too long'); } end = p; } if (!this._buffer) this._buffer = bufferSlice(data, op); return p - chunkOffset; } function parsePacket(chunk, p, len) { return this._decipher.decrypt(chunk, p, len); } function onPayload(payload) { // XXX: move this to the Decipher implementations? this._onPacket(); if (payload.length === 0) { this._debug && this._debug('Inbound: Skipping empty packet payload'); return; } payload = this._packetRW.read.read(payload); const type = payload[0]; if (type === MESSAGE.USERAUTH_SUCCESS && !this._server && !this._authenticated) { this._authenticated = true; if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') this._packetRW.write = new ZlibPacketWriter(this); if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') this._packetRW.read = new ZlibPacketReader(); } const handler = MESSAGE_HANDLERS[type]; if (handler === undefined) { this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); return; } return handler(this, payload); } function getCompatFlags(header) { const software = header.versions.software; let flags = 0; for (const rule of COMPAT_CHECKS) { if (typeof rule[0] === 'string') { if (software === rule[0]) flags |= rule[1]; } else if (rule[0].test(software)) { flags |= rule[1]; } } return flags; } function modesToBytes(modes) { const keys = Object.keys(modes); const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); let b = 0; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (key === 'TTY_OP_END') continue; const opcode = TERMINAL_MODE[key]; if (opcode === undefined) continue; const val = modes[key]; if (typeof val === 'number' && isFinite(val)) { bytes[b++] = opcode; bytes[b++] = val >>> 24; bytes[b++] = val >>> 16; bytes[b++] = val >>> 8; bytes[b++] = val; } } bytes[b++] = TERMINAL_MODE.TTY_OP_END; if (b < bytes.length) return bufferSlice(bytes, 0, b); return bytes; } function sendExtInfo(proto) { let serverSigAlgs = 'ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521' + 'rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss'; if (eddsaSupported) serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`; const algsLen = Buffer.byteLength(serverSigAlgs); let p = proto._packetRW.write.allocStart; const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen); packet[p] = MESSAGE.EXT_INFO; writeUInt32BE(packet, 1, ++p); writeUInt32BE(packet, 15, p += 4); packet.utf8Write('server-sig-algs', p += 4, 15); writeUInt32BE(packet, algsLen, p += 15); packet.utf8Write(serverSigAlgs, p += 4, algsLen); proto._debug && proto._debug('Outbound: Sending EXT_INFO'); sendPacket(proto, proto._packetRW.write.finalize(packet)); } module.exports = Protocol; /***/ }), /***/ 4996: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(4434); const fs = __nccwpck_require__(9896); const { constants } = fs; const { Readable: ReadableStream, Writable: WritableStream } = __nccwpck_require__(2203); const { inherits, types: { isDate } } = __nccwpck_require__(9023); const FastBuffer = Buffer[Symbol.species]; const { bufferCopy, bufferSlice, makeBufferParser, writeUInt32BE, } = __nccwpck_require__(2184); const ATTR = { SIZE: 0x00000001, UIDGID: 0x00000002, PERMISSIONS: 0x00000004, ACMODTIME: 0x00000008, EXTENDED: 0x80000000, }; // Large enough to store all possible attributes const ATTRS_BUF = Buffer.alloc(28); const STATUS_CODE = { OK: 0, EOF: 1, NO_SUCH_FILE: 2, PERMISSION_DENIED: 3, FAILURE: 4, BAD_MESSAGE: 5, NO_CONNECTION: 6, CONNECTION_LOST: 7, OP_UNSUPPORTED: 8 }; const VALID_STATUS_CODES = new Map( Object.values(STATUS_CODE).map((n) => [n, 1]) ); const STATUS_CODE_STR = { [STATUS_CODE.OK]: 'No error', [STATUS_CODE.EOF]: 'End of file', [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', [STATUS_CODE.FAILURE]: 'Failure', [STATUS_CODE.BAD_MESSAGE]: 'Bad message', [STATUS_CODE.NO_CONNECTION]: 'No connection', [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', }; const REQUEST = { INIT: 1, OPEN: 3, CLOSE: 4, READ: 5, WRITE: 6, LSTAT: 7, FSTAT: 8, SETSTAT: 9, FSETSTAT: 10, OPENDIR: 11, READDIR: 12, REMOVE: 13, MKDIR: 14, RMDIR: 15, REALPATH: 16, STAT: 17, RENAME: 18, READLINK: 19, SYMLINK: 20, EXTENDED: 200 }; const RESPONSE = { VERSION: 2, STATUS: 101, HANDLE: 102, DATA: 103, NAME: 104, ATTRS: 105, EXTENDED: 201 }; const OPEN_MODE = { READ: 0x00000001, WRITE: 0x00000002, APPEND: 0x00000004, CREAT: 0x00000008, TRUNC: 0x00000010, EXCL: 0x00000020 }; const PKT_RW_OVERHEAD = 2 * 1024; const MAX_REQID = 2 ** 32 - 1; const CLIENT_VERSION_BUFFER = Buffer.from([ 0, 0, 0, 5 /* length */, REQUEST.INIT, 0, 0, 0, 3 /* version */ ]); const SERVER_VERSION_BUFFER = Buffer.from([ 0, 0, 0, 5 /* length */, RESPONSE.VERSION, 0, 0, 0, 3 /* version */ ]); const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; const OPENSSH_MAX_PKT_LEN = 256 * 1024; const bufferParser = makeBufferParser(); const fakeStderr = { readable: false, writable: false, push: (data) => {}, once: () => {}, on: () => {}, emit: () => {}, end: () => {}, }; function noop() {} // Emulates enough of `Channel` to be able to be used as a drop-in replacement // in order to process incoming data with as little overhead as possible class SFTP extends EventEmitter { constructor(client, chanInfo, cfg) { super(); if (typeof cfg !== 'object' || !cfg) cfg = {}; const remoteIdentRaw = client._protocol._remoteIdentRaw; this.server = !!cfg.server; this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); this._version = -1; this._extensions = {}; this._biOpt = cfg.biOpt; this._pktLenBytes = 0; this._pktLen = 0; this._pktPos = 0; this._pktType = 0; this._pktData = undefined; this._writeReqid = -1; this._requests = {}; this._maxInPktLen = OPENSSH_MAX_PKT_LEN; this._maxOutPktLen = 34000; this._maxReadLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; this._maxWriteLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; this.maxOpenHandles = undefined; // Channel compatibility this._client = client; this._protocol = client._protocol; this._callbacks = []; this._hasX11 = false; this._exit = { code: undefined, signal: undefined, dump: undefined, desc: undefined, }; this._waitWindow = false; // SSH-level backpressure this._chunkcb = undefined; this._buffer = []; this.type = chanInfo.type; this.subtype = undefined; this.incoming = chanInfo.incoming; this.outgoing = chanInfo.outgoing; this.stderr = fakeStderr; this.readable = true; } // This handles incoming data to parse push(data) { if (data === null) { cleanupRequests(this); if (!this.readable) return; // No more incoming data from the remote side this.readable = false; this.emit('end'); return; } /* uint32 length byte type byte[length - 1] data payload */ let p = 0; while (p < data.length) { if (this._pktLenBytes < 4) { let nb = Math.min(4 - this._pktLenBytes, data.length - p); this._pktLenBytes += nb; while (nb--) this._pktLen = (this._pktLen << 8) + data[p++]; if (this._pktLenBytes < 4) return; if (this._pktLen === 0) return doFatalSFTPError(this, 'Invalid packet length'); if (this._pktLen > this._maxInPktLen) { const max = this._maxInPktLen; return doFatalSFTPError( this, `Packet length ${this._pktLen} exceeds max length of ${max}` ); } if (p >= data.length) return; } if (this._pktPos < this._pktLen) { const nb = Math.min(this._pktLen - this._pktPos, data.length - p); if (p !== 0 || nb !== data.length) { if (nb === this._pktLen) { this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); } else { if (!this._pkt) this._pkt = Buffer.allocUnsafe(this._pktLen); this._pkt.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._pktPos ); } } else if (nb === this._pktLen) { this._pkt = data; } else { if (!this._pkt) this._pkt = Buffer.allocUnsafe(this._pktLen); this._pkt.set(data, this._pktPos); } p += nb; this._pktPos += nb; if (this._pktPos < this._pktLen) return; } const type = this._pkt[0]; const payload = this._pkt; // Prepare for next packet this._pktLen = 0; this._pktLenBytes = 0; this._pkt = undefined; this._pktPos = 0; const handler = (this.server ? SERVER_HANDLERS[type] : CLIENT_HANDLERS[type]); if (!handler) return doFatalSFTPError(this, `Unknown packet type ${type}`); if (this._version === -1) { if (this.server) { if (type !== REQUEST.INIT) return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); } else if (type !== RESPONSE.VERSION) { return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); } } if (handler(this, payload) === false) return; } } end() { this.destroy(); } destroy() { if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { this.outgoing.state = 'closing'; this._protocol.channelClose(this.outgoing.id); } } _init() { this._init = noop; if (!this.server) sendOrBuffer(this, CLIENT_VERSION_BUFFER); } // =========================================================================== // Client-specific =========================================================== // =========================================================================== createReadStream(path, options) { if (this.server) throw new Error('Client-only method called in server mode'); return new ReadStream(this, path, options); } createWriteStream(path, options) { if (this.server) throw new Error('Client-only method called in server mode'); return new WriteStream(this, path, options); } open(path, flags_, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (typeof attrs === 'function') { cb = attrs; attrs = undefined; } const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); if (flags === null) throw new Error(`Unknown flags string: ${flags_}`); let attrsFlags = 0; let attrsLen = 0; if (typeof attrs === 'string' || typeof attrs === 'number') attrs = { mode: attrs }; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); attrsFlags = attrs.flags; attrsLen = attrs.nb; } /* uint32 id string filename uint32 pflags ATTRS attrs */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.OPEN; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); writeUInt32BE(buf, flags, p += pathLen); writeUInt32BE(buf, attrsFlags, p += 4); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` ); } close(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string handle */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.CLOSE; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); buf.set(handle, p += 4); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` ); } read(handle, buf, off, len, position, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); if (!Buffer.isBuffer(buf)) throw new Error('buffer is not a Buffer'); if (off >= buf.length) throw new Error('offset is out of bounds'); if (off + len > buf.length) throw new Error('length extends beyond buffer'); if (position === null) throw new Error('null position currently unsupported'); read_(this, handle, buf, off, len, position, cb); } readData(handle, buf, off, len, position, cb) { // Backwards compatibility this.read(handle, buf, off, len, position, cb); } write(handle, buf, off, len, position, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); if (!Buffer.isBuffer(buf)) throw new Error('buffer is not a Buffer'); if (off > buf.length) throw new Error('offset is out of bounds'); if (off + len > buf.length) throw new Error('length extends beyond buffer'); if (position === null) throw new Error('null position currently unsupported'); if (!len) { cb && process.nextTick(cb, undefined, 0); return; } const maxDataLen = this._maxWriteLen; const overflow = Math.max(len - maxDataLen, 0); const origPosition = position; if (overflow) len = maxDataLen; /* uint32 id string handle uint64 offset string data */ const handleLen = handle.length; let p = 9; const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); writeUInt32BE(out, out.length - 4, 0); out[4] = REQUEST.WRITE; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(out, reqid, 5); writeUInt32BE(out, handleLen, p); out.set(handle, p += 4); p += handleLen; for (let i = 7; i >= 0; --i) { out[p + i] = position & 0xFF; position /= 256; } writeUInt32BE(out, len, p += 8); bufferCopy(buf, out, off, off + len, p += 4); this._requests[reqid] = { cb: (err) => { if (err) { if (typeof cb === 'function') cb(err); } else if (overflow) { this.write(handle, buf, off + len, overflow, origPosition + len, cb); } else if (typeof cb === 'function') { cb(undefined, off + len); } } }; const isSent = sendOrBuffer(this, out); if (this._debug) { const how = (isSent ? 'Sent' : 'Buffered'); this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); } } writeData(handle, buf, off, len, position, cb) { // Backwards compatibility this.write(handle, buf, off, len, position, cb); } fastGet(remotePath, localPath, opts, cb) { if (this.server) throw new Error('Client-only method called in server mode'); fastXfer(this, fs, remotePath, localPath, opts, cb); } fastPut(localPath, remotePath, opts, cb) { if (this.server) throw new Error('Client-only method called in server mode'); fastXfer(fs, this, localPath, remotePath, opts, cb); } readFile(path, options, callback_) { if (this.server) throw new Error('Client-only method called in server mode'); let callback; if (typeof callback_ === 'function') { callback = callback_; } else if (typeof options === 'function') { callback = options; options = undefined; } if (typeof options === 'string') options = { encoding: options, flag: 'r' }; else if (!options) options = { encoding: null, flag: 'r' }; else if (typeof options !== 'object') throw new TypeError('Bad arguments'); const encoding = options.encoding; if (encoding && !Buffer.isEncoding(encoding)) throw new Error(`Unknown encoding: ${encoding}`); // First stat the file, so we know the size. let size; let buffer; // Single buffer with file data let buffers; // List for when size is unknown let pos = 0; let handle; // SFTPv3 does not support using -1 for read position, so we have to track // read position manually let bytesRead = 0; const flag = options.flag || 'r'; const read = () => { if (size === 0) { buffer = Buffer.allocUnsafe(8192); this.read(handle, buffer, 0, 8192, bytesRead, afterRead); } else { this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); } }; const afterRead = (er, nbytes) => { let eof; if (er) { eof = (er.code === STATUS_CODE.EOF); if (!eof) { return this.close(handle, () => { return callback && callback(er); }); } } else { eof = false; } if (eof || (size === 0 && nbytes === 0)) return close(); bytesRead += nbytes; pos += nbytes; if (size !== 0) { if (pos === size) close(); else read(); } else { // Unknown size, just read until we don't get bytes. buffers.push(bufferSlice(buffer, 0, nbytes)); read(); } }; afterRead._wantEOFError = true; const close = () => { this.close(handle, (er) => { if (size === 0) { // Collect the data into the buffers list. buffer = Buffer.concat(buffers, pos); } else if (pos < size) { buffer = bufferSlice(buffer, 0, pos); } if (encoding) buffer = buffer.toString(encoding); return callback && callback(er, buffer); }); }; this.open(path, flag, 0o666, (er, handle_) => { if (er) return callback && callback(er); handle = handle_; const tryStat = (er, st) => { if (er) { // Try stat() for sftp servers that may not support fstat() for // whatever reason this.stat(path, (er_, st_) => { if (er_) { return this.close(handle, () => { callback && callback(er); }); } tryStat(null, st_); }); return; } size = st.size || 0; if (size === 0) { // The kernel lies about many files. // Go ahead and try to read some bytes. buffers = []; return read(); } buffer = Buffer.allocUnsafe(size); read(); }; this.fstat(handle, tryStat); }); } writeFile(path, data, options, callback_) { if (this.server) throw new Error('Client-only method called in server mode'); let callback; if (typeof callback_ === 'function') { callback = callback_; } else if (typeof options === 'function') { callback = options; options = undefined; } if (typeof options === 'string') options = { encoding: options, mode: 0o666, flag: 'w' }; else if (!options) options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; else if (typeof options !== 'object') throw new TypeError('Bad arguments'); if (options.encoding && !Buffer.isEncoding(options.encoding)) throw new Error(`Unknown encoding: ${options.encoding}`); const flag = options.flag || 'w'; this.open(path, flag, options.mode, (openErr, handle) => { if (openErr) { callback && callback(openErr); } else { const buffer = (Buffer.isBuffer(data) ? data : Buffer.from('' + data, options.encoding || 'utf8')); const position = (/a/.test(flag) ? null : 0); // SFTPv3 does not support the notion of 'current position' // (null position), so we just attempt to append to the end of the file // instead if (position === null) { const tryStat = (er, st) => { if (er) { // Try stat() for sftp servers that may not support fstat() for // whatever reason this.stat(path, (er_, st_) => { if (er_) { return this.close(handle, () => { callback && callback(er); }); } tryStat(null, st_); }); return; } writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); }; this.fstat(handle, tryStat); return; } writeAll(this, handle, buffer, 0, buffer.length, position, callback); } }); } appendFile(path, data, options, callback_) { if (this.server) throw new Error('Client-only method called in server mode'); let callback; if (typeof callback_ === 'function') { callback = callback_; } else if (typeof options === 'function') { callback = options; options = undefined; } if (typeof options === 'string') options = { encoding: options, mode: 0o666, flag: 'a' }; else if (!options) options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; else if (typeof options !== 'object') throw new TypeError('Bad arguments'); if (!options.flag) options = Object.assign({ flag: 'a' }, options); this.writeFile(path, data, options, callback); } exists(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); this.stat(path, (err) => { cb && cb(err ? false : true); }); } unlink(filename, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string filename */ const fnameLen = Buffer.byteLength(filename); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.REMOVE; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, fnameLen, p); buf.utf8Write(filename, p += 4, fnameLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` ); } rename(oldPath, newPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string oldpath string newpath */ const oldLen = Buffer.byteLength(oldPath); const newLen = Buffer.byteLength(newPath); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.RENAME; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, oldLen, p); buf.utf8Write(oldPath, p += 4, oldLen); writeUInt32BE(buf, newLen, p += oldLen); buf.utf8Write(newPath, p += 4, newLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` ); } mkdir(path, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); let flags = 0; let attrsLen = 0; if (typeof attrs === 'function') { cb = attrs; attrs = undefined; } if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrsLen = attrs.nb; } /* uint32 id string path ATTRS attrs */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.MKDIR; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); writeUInt32BE(buf, flags, p += pathLen); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` ); } rmdir(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.RMDIR; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` ); } readdir(where, opts, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (typeof opts === 'function') { cb = opts; opts = {}; } if (typeof opts !== 'object' || opts === null) opts = {}; const doFilter = (opts && opts.full ? false : true); if (!Buffer.isBuffer(where) && typeof where !== 'string') throw new Error('missing directory handle or path'); if (typeof where === 'string') { const entries = []; let e = 0; const reread = (err, handle) => { if (err) return cb(err); this.readdir(handle, opts, (err, list) => { const eof = (err && err.code === STATUS_CODE.EOF); if (err && !eof) return this.close(handle, () => cb(err)); if (eof) { return this.close(handle, (err) => { if (err) return cb(err); cb(undefined, entries); }); } for (let i = 0; i < list.length; ++i, ++e) entries[e] = list[i]; reread(undefined, handle); }); }; return this.opendir(where, reread); } /* uint32 id string handle */ const handleLen = where.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.READDIR; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); buf.set(where, p += 4); this._requests[reqid] = { cb: (doFilter ? (err, list) => { if (typeof cb !== 'function') return; if (err) return cb(err); for (let i = list.length - 1; i >= 0; --i) { if (list[i].filename === '.' || list[i].filename === '..') list.splice(i, 1); } cb(undefined, list); } : cb) }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` ); } fstat(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string handle */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.FSTAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); buf.set(handle, p += 4); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` ); } stat(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.STAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` ); } lstat(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.LSTAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` ); } opendir(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.OPENDIR; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` ); } setstat(path, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); let flags = 0; let attrsLen = 0; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrsLen = attrs.nb; } else if (typeof attrs === 'function') { cb = attrs; } /* uint32 id string path ATTRS attrs */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.SETSTAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); writeUInt32BE(buf, flags, p += pathLen); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` ); } fsetstat(handle, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); let flags = 0; let attrsLen = 0; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrsLen = attrs.nb; } else if (typeof attrs === 'function') { cb = attrs; } /* uint32 id string handle ATTRS attrs */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.FSETSTAT; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); buf.set(handle, p += 4); writeUInt32BE(buf, flags, p += handleLen); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` ); } futimes(handle, atime, mtime, cb) { return this.fsetstat(handle, { atime: toUnixTimestamp(atime), mtime: toUnixTimestamp(mtime) }, cb); } utimes(path, atime, mtime, cb) { return this.setstat(path, { atime: toUnixTimestamp(atime), mtime: toUnixTimestamp(mtime) }, cb); } fchown(handle, uid, gid, cb) { return this.fsetstat(handle, { uid: uid, gid: gid }, cb); } chown(path, uid, gid, cb) { return this.setstat(path, { uid: uid, gid: gid }, cb); } fchmod(handle, mode, cb) { return this.fsetstat(handle, { mode: mode }, cb); } chmod(path, mode, cb) { return this.setstat(path, { mode: mode }, cb); } readlink(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.READLINK; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb: (err, names) => { if (typeof cb !== 'function') return; if (err) return cb(err); if (!names || !names.length) return cb(new Error('Response missing link info')); cb(undefined, names[0].filename); } }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` ); } symlink(targetPath, linkPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string linkpath string targetpath */ const linkLen = Buffer.byteLength(linkPath); const targetLen = Buffer.byteLength(targetPath); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.SYMLINK; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); if (this._isOpenSSH) { // OpenSSH has linkpath and targetpath positions switched writeUInt32BE(buf, targetLen, p); buf.utf8Write(targetPath, p += 4, targetLen); writeUInt32BE(buf, linkLen, p += targetLen); buf.utf8Write(linkPath, p += 4, linkLen); } else { writeUInt32BE(buf, linkLen, p); buf.utf8Write(linkPath, p += 4, linkLen); writeUInt32BE(buf, targetLen, p += linkLen); buf.utf8Write(targetPath, p += 4, targetLen); } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` ); } realpath(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); /* uint32 id string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.REALPATH; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, pathLen, p); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb: (err, names) => { if (typeof cb !== 'function') return; if (err) return cb(err); if (!names || !names.length) return cb(new Error('Response missing path info')); cb(undefined, names[0].filename); } }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` ); } // extended requests ext_openssh_rename(oldPath, newPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['posix-rename@openssh.com']; if (!ext || ext !== '1') throw new Error('Server does not support this extended request'); /* uint32 id string "posix-rename@openssh.com" string oldpath string newpath */ const oldLen = Buffer.byteLength(oldPath); const newLen = Buffer.byteLength(newPath); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 24, p); buf.utf8Write('posix-rename@openssh.com', p += 4, 24); writeUInt32BE(buf, oldLen, p += 24); buf.utf8Write(oldPath, p += 4, oldLen); writeUInt32BE(buf, newLen, p += oldLen); buf.utf8Write(newPath, p += 4, newLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); } } ext_openssh_statvfs(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['statvfs@openssh.com']; if (!ext || ext !== '2') throw new Error('Server does not support this extended request'); /* uint32 id string "statvfs@openssh.com" string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 19, p); buf.utf8Write('statvfs@openssh.com', p += 4, 19); writeUInt32BE(buf, pathLen, p += 19); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); } } ext_openssh_fstatvfs(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['fstatvfs@openssh.com']; if (!ext || ext !== '2') throw new Error('Server does not support this extended request'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string "fstatvfs@openssh.com" string handle */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 20, p); buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); writeUInt32BE(buf, handleLen, p += 20); buf.set(handle, p += 4); this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); } } ext_openssh_hardlink(oldPath, newPath, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['hardlink@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); /* uint32 id string "hardlink@openssh.com" string oldpath string newpath */ const oldLen = Buffer.byteLength(oldPath); const newLen = Buffer.byteLength(newPath); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 20, p); buf.utf8Write('hardlink@openssh.com', p += 4, 20); writeUInt32BE(buf, oldLen, p += 20); buf.utf8Write(oldPath, p += 4, oldLen); writeUInt32BE(buf, newLen, p += oldLen); buf.utf8Write(newPath, p += 4, newLen); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); } } ext_openssh_fsync(handle, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['fsync@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); /* uint32 id string "fsync@openssh.com" string handle */ const handleLen = handle.length; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 17, p); buf.utf8Write('fsync@openssh.com', p += 4, 17); writeUInt32BE(buf, handleLen, p += 17); buf.set(handle, p += 4); this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` ); } ext_openssh_lsetstat(path, attrs, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['lsetstat@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); let flags = 0; let attrsLen = 0; if (typeof attrs === 'object' && attrs !== null) { attrs = attrsToBytes(attrs); flags = attrs.flags; attrsLen = attrs.nb; } else if (typeof attrs === 'function') { cb = attrs; } /* uint32 id string "lsetstat@openssh.com" string path ATTRS attrs */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 20, p); buf.utf8Write('lsetstat@openssh.com', p += 4, 20); writeUInt32BE(buf, pathLen, p += 20); buf.utf8Write(path, p += 4, pathLen); writeUInt32BE(buf, flags, p += pathLen); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); } } ext_openssh_expandPath(path, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['expand-path@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); /* uint32 id string "expand-path@openssh.com" string path */ const pathLen = Buffer.byteLength(path); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 23, p); buf.utf8Write('expand-path@openssh.com', p += 4, 23); writeUInt32BE(buf, pathLen, p += 20); buf.utf8Write(path, p += 4, pathLen); this._requests[reqid] = { cb: (err, names) => { if (typeof cb !== 'function') return; if (err) return cb(err); if (!names || !names.length) return cb(new Error('Response missing expanded path')); cb(undefined, names[0].filename); } }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); } } ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['copy-data']; if (ext !== '1') throw new Error('Server does not support this extended request'); if (!Buffer.isBuffer(srcHandle)) throw new Error('Source handle is not a Buffer'); if (!Buffer.isBuffer(dstHandle)) throw new Error('Destination handle is not a Buffer'); /* uint32 id string "copy-data" string read-from-handle uint64 read-from-offset uint64 read-data-length string write-to-handle uint64 write-to-offset */ let p = 0; const buf = Buffer.allocUnsafe( 4 + 1 + 4 + 4 + 9 + 4 + srcHandle.length + 8 + 8 + 4 + dstHandle.length + 8 ); writeUInt32BE(buf, buf.length - 4, p); p += 4; buf[p] = REQUEST.EXTENDED; ++p; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, p); p += 4; writeUInt32BE(buf, 9, p); p += 4; buf.utf8Write('copy-data', p, 9); p += 9; writeUInt32BE(buf, srcHandle.length, p); p += 4; buf.set(srcHandle, p); p += srcHandle.length; for (let i = 7; i >= 0; --i) { buf[p + i] = srcOffset & 0xFF; srcOffset /= 256; } p += 8; for (let i = 7; i >= 0; --i) { buf[p + i] = len & 0xFF; len /= 256; } p += 8; writeUInt32BE(buf, dstHandle.length, p); p += 4; buf.set(dstHandle, p); p += dstHandle.length; for (let i = 7; i >= 0; --i) { buf[p + i] = dstOffset & 0xFF; dstOffset /= 256; } this._requests[reqid] = { cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} copy-data`); } } ext_home_dir(username, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['home-directory']; if (ext !== '1') throw new Error('Server does not support this extended request'); if (typeof username !== 'string') throw new TypeError('username is not a string'); /* uint32 id string "home-directory" string username */ let p = 0; const usernameLen = Buffer.byteLength(username); const buf = Buffer.allocUnsafe( 4 + 1 + 4 + 4 + 14 + 4 + usernameLen ); writeUInt32BE(buf, buf.length - 4, p); p += 4; buf[p] = REQUEST.EXTENDED; ++p; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, p); p += 4; writeUInt32BE(buf, 14, p); p += 4; buf.utf8Write('home-directory', p, 14); p += 14; writeUInt32BE(buf, usernameLen, p); p += 4; buf.utf8Write(username, p, usernameLen); p += usernameLen; this._requests[reqid] = { cb: (err, names) => { if (typeof cb !== 'function') return; if (err) return cb(err); if (!names || !names.length) return cb(new Error('Response missing home directory')); cb(undefined, names[0].filename); } }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} home-directory`); } } ext_users_groups(uids, gids, cb) { if (this.server) throw new Error('Client-only method called in server mode'); const ext = this._extensions['users-groups-by-id@openssh.com']; if (ext !== '1') throw new Error('Server does not support this extended request'); if (!Array.isArray(uids)) throw new TypeError('uids is not an array'); for (const val of uids) { if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) throw new Error('uid values must all be 32-bit unsigned integers'); } if (!Array.isArray(gids)) throw new TypeError('gids is not an array'); for (const val of gids) { if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) throw new Error('gid values must all be 32-bit unsigned integers'); } /* uint32 id string "users-groups-by-id@openssh.com" string uids uint32 uid1 ... string gids uint32 gid1 ... */ let p = 0; const buf = Buffer.allocUnsafe( 4 + 1 + 4 + 4 + 30 + 4 + (4 * uids.length) + 4 + (4 * gids.length) ); writeUInt32BE(buf, buf.length - 4, p); p += 4; buf[p] = REQUEST.EXTENDED; ++p; const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, p); p += 4; writeUInt32BE(buf, 30, p); p += 4; buf.utf8Write('users-groups-by-id@openssh.com', p, 30); p += 30; writeUInt32BE(buf, 4 * uids.length, p); p += 4; for (const val of uids) { writeUInt32BE(buf, val, p); p += 4; } writeUInt32BE(buf, 4 * gids.length, p); p += 4; for (const val of gids) { writeUInt32BE(buf, val, p); p += 4; } this._requests[reqid] = { extended: 'users-groups-by-id@openssh.com', cb }; const isBuffered = sendOrBuffer(this, buf); if (this._debug) { const status = (isBuffered ? 'Buffered' : 'Sending'); this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`); } } // =========================================================================== // Server-specific =========================================================== // =========================================================================== handle(reqid, handle) { if (!this.server) throw new Error('Server-only method called in client mode'); if (!Buffer.isBuffer(handle)) throw new Error('handle is not a Buffer'); const handleLen = handle.length; if (handleLen > 256) throw new Error('handle too large (> 256 bytes)'); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.HANDLE; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, handleLen, p); if (handleLen) buf.set(handle, p += 4); const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` ); } status(reqid, code, message) { if (!this.server) throw new Error('Server-only method called in client mode'); if (!VALID_STATUS_CODES.has(code)) throw new Error(`Bad status code: ${code}`); message || (message = ''); const msgLen = Buffer.byteLength(message); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.STATUS; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, code, p); writeUInt32BE(buf, msgLen, p += 4); p += 4; if (msgLen) { buf.utf8Write(message, p, msgLen); p += msgLen; } writeUInt32BE(buf, 0, p); // Empty language tag const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` ); } data(reqid, data, encoding) { if (!this.server) throw new Error('Server-only method called in client mode'); const isBuffer = Buffer.isBuffer(data); if (!isBuffer && typeof data !== 'string') throw new Error('data is not a Buffer or string'); let isUTF8; if (!isBuffer && !encoding) { encoding = undefined; isUTF8 = true; } const dataLen = ( isBuffer ? data.length : Buffer.byteLength(data, encoding) ); let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.DATA; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, dataLen, p); if (dataLen) { if (isBuffer) buf.set(data, p += 4); else if (isUTF8) buf.utf8Write(data, p += 4, dataLen); else buf.write(data, p += 4, dataLen, encoding); } const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` ); } name(reqid, names) { if (!this.server) throw new Error('Server-only method called in client mode'); if (!Array.isArray(names)) { if (typeof names !== 'object' || names === null) throw new Error('names is not an object or array'); names = [ names ]; } const count = names.length; let namesLen = 0; let nameAttrs; const attrs = []; for (let i = 0; i < count; ++i) { const name = names[i]; const filename = ( !name || !name.filename || typeof name.filename !== 'string' ? '' : name.filename ); namesLen += 4 + Buffer.byteLength(filename); const longname = ( !name || !name.longname || typeof name.longname !== 'string' ? '' : name.longname ); namesLen += 4 + Buffer.byteLength(longname); if (typeof name.attrs === 'object' && name.attrs !== null) { nameAttrs = attrsToBytes(name.attrs); namesLen += 4 + nameAttrs.nb; if (nameAttrs.nb) { let bytes; if (nameAttrs.nb === ATTRS_BUF.length) { bytes = new Uint8Array(ATTRS_BUF); } else { bytes = new Uint8Array(nameAttrs.nb); bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); } nameAttrs.bytes = bytes; } attrs.push(nameAttrs); } else { namesLen += 4; attrs.push(null); } } let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.NAME; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, count, p); p += 4; for (let i = 0; i < count; ++i) { const name = names[i]; { const filename = ( !name || !name.filename || typeof name.filename !== 'string' ? '' : name.filename ); const len = Buffer.byteLength(filename); writeUInt32BE(buf, len, p); p += 4; if (len) { buf.utf8Write(filename, p, len); p += len; } } { const longname = ( !name || !name.longname || typeof name.longname !== 'string' ? '' : name.longname ); const len = Buffer.byteLength(longname); writeUInt32BE(buf, len, p); p += 4; if (len) { buf.utf8Write(longname, p, len); p += len; } } const attr = attrs[i]; if (attr) { writeUInt32BE(buf, attr.flags, p); p += 4; if (attr.flags && attr.bytes) { buf.set(attr.bytes, p); p += attr.nb; } } else { writeUInt32BE(buf, 0, p); p += 4; } } const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME` ); } attrs(reqid, attrs) { if (!this.server) throw new Error('Server-only method called in client mode'); if (typeof attrs !== 'object' || attrs === null) throw new Error('attrs is not an object'); attrs = attrsToBytes(attrs); const flags = attrs.flags; const attrsLen = attrs.nb; let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = RESPONSE.ATTRS; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, flags, p); if (attrsLen) { p += 4; if (attrsLen === ATTRS_BUF.length) buf.set(ATTRS_BUF, p); else bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); p += attrsLen; } const isBuffered = sendOrBuffer(this, buf); this._debug && this._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` ); } } function tryCreateBuffer(size) { try { return Buffer.allocUnsafe(size); } catch (ex) { return ex; } } function read_(self, handle, buf, off, len, position, cb, req_) { const maxDataLen = self._maxReadLen; const overflow = Math.max(len - maxDataLen, 0); if (overflow) len = maxDataLen; /* uint32 id string handle uint64 offset uint32 len */ const handleLen = handle.length; let p = 9; let pos = position; const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); writeUInt32BE(out, out.length - 4, 0); out[4] = REQUEST.READ; const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; writeUInt32BE(out, reqid, 5); writeUInt32BE(out, handleLen, p); out.set(handle, p += 4); p += handleLen; for (let i = 7; i >= 0; --i) { out[p + i] = pos & 0xFF; pos /= 256; } writeUInt32BE(out, len, p += 8); if (typeof cb !== 'function') cb = noop; const req = (req_ || { nb: 0, position, off, origOff: off, len: undefined, overflow: undefined, cb: (err, data, nb) => { const len = req.len; const overflow = req.overflow; if (err) { if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) return cb(err); } else if (nb > len) { return cb(new Error('Received more data than requested')); } else if (nb === len && overflow) { req.nb += nb; req.position += nb; req.off += nb; read_(self, handle, buf, req.off, overflow, req.position, cb, req); return; } nb = (nb || 0); if (req.origOff === 0 && buf.length === req.nb) data = buf; else data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb); cb(undefined, req.nb + nb, data, req.position); }, buffer: undefined, }); req.len = len; req.overflow = overflow; // TODO: avoid creating multiple buffer slices when we need to re-call read_() // because of overflow req.buffer = bufferSlice(buf, off, off + len); self._requests[reqid] = req; const isBuffered = sendOrBuffer(self, out); self._debug && self._debug( `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` ); } function fastXfer(src, dst, srcPath, dstPath, opts, cb) { let concurrency = 64; let chunkSize = 32768; let onstep; let mode; let fileSize; if (typeof opts === 'function') { cb = opts; } else if (typeof opts === 'object' && opts !== null) { if (typeof opts.concurrency === 'number' && opts.concurrency > 0 && !isNaN(opts.concurrency)) { concurrency = opts.concurrency; } if (typeof opts.chunkSize === 'number' && opts.chunkSize > 0 && !isNaN(opts.chunkSize)) { chunkSize = opts.chunkSize; } if (typeof opts.fileSize === 'number' && opts.fileSize > 0 && !isNaN(opts.fileSize)) { fileSize = opts.fileSize; } if (typeof opts.step === 'function') onstep = opts.step; if (typeof opts.mode === 'string' || typeof opts.mode === 'number') mode = modeNum(opts.mode); } // Internal state variables let fsize; let pdst = 0; let total = 0; let hadError = false; let srcHandle; let dstHandle; let readbuf; let bufsize = chunkSize * concurrency; function onerror(err) { if (hadError) return; hadError = true; let left = 0; let cbfinal; if (srcHandle || dstHandle) { cbfinal = () => { if (--left === 0) cb(err); }; if (srcHandle && (src === fs || src.outgoing.state === 'open')) ++left; if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) ++left; if (srcHandle && (src === fs || src.outgoing.state === 'open')) src.close(srcHandle, cbfinal); if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) dst.close(dstHandle, cbfinal); } else { cb(err); } } src.open(srcPath, 'r', (err, sourceHandle) => { if (err) return onerror(err); srcHandle = sourceHandle; if (fileSize === undefined) src.fstat(srcHandle, tryStat); else tryStat(null, { size: fileSize }); function tryStat(err, attrs) { if (err) { if (src !== fs) { // Try stat() for sftp servers that may not support fstat() for // whatever reason src.stat(srcPath, (err_, attrs_) => { if (err_) return onerror(err); tryStat(null, attrs_); }); return; } return onerror(err); } fsize = attrs.size; dst.open(dstPath, 'w', (err, destHandle) => { if (err) return onerror(err); dstHandle = destHandle; if (fsize <= 0) return onerror(); // Use less memory where possible while (bufsize > fsize) { if (concurrency === 1) { bufsize = fsize; break; } bufsize -= chunkSize; --concurrency; } readbuf = tryCreateBuffer(bufsize); if (readbuf instanceof Error) return onerror(readbuf); if (mode !== undefined) { dst.fchmod(dstHandle, mode, function tryAgain(err) { if (err) { // Try chmod() for sftp servers that may not support fchmod() // for whatever reason dst.chmod(dstPath, mode, (err_) => tryAgain()); return; } startReads(); }); } else { startReads(); } function onread(err, nb, data, dstpos, datapos, origChunkLen) { if (err) return onerror(err); datapos = datapos || 0; dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); function writeCb(err) { if (err) return onerror(err); total += nb; onstep && onstep(total, nb, fsize); if (nb < origChunkLen) return singleRead(datapos, dstpos + nb, origChunkLen - nb); if (total === fsize) { dst.close(dstHandle, (err) => { dstHandle = undefined; if (err) return onerror(err); src.close(srcHandle, (err) => { srcHandle = undefined; if (err) return onerror(err); cb(); }); }); return; } if (pdst >= fsize) return; const chunk = (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); singleRead(datapos, pdst, chunk); pdst += chunk; } } function makeCb(psrc, pdst, chunk) { return (err, nb, data) => { onread(err, nb, data, pdst, psrc, chunk); }; } function singleRead(psrc, pdst, chunk) { src.read(srcHandle, readbuf, psrc, chunk, pdst, makeCb(psrc, pdst, chunk)); } function startReads() { let reads = 0; let psrc = 0; while (pdst < fsize && reads < concurrency) { const chunk = (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); singleRead(psrc, pdst, chunk); psrc += chunk; pdst += chunk; ++reads; } } }); } }); } function writeAll(sftp, handle, buffer, offset, length, position, callback_) { const callback = (typeof callback_ === 'function' ? callback_ : undefined); sftp.write(handle, buffer, offset, length, position, (writeErr, written) => { if (writeErr) { return sftp.close(handle, () => { callback && callback(writeErr); }); } if (written === length) { sftp.close(handle, callback); } else { offset += written; length -= written; position += written; writeAll(sftp, handle, buffer, offset, length, position, callback); } }); } class Stats { constructor(initial) { this.mode = (initial && initial.mode); this.uid = (initial && initial.uid); this.gid = (initial && initial.gid); this.size = (initial && initial.size); this.atime = (initial && initial.atime); this.mtime = (initial && initial.mtime); this.extended = (initial && initial.extended); } isDirectory() { return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); } isFile() { return ((this.mode & constants.S_IFMT) === constants.S_IFREG); } isBlockDevice() { return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); } isCharacterDevice() { return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); } isSymbolicLink() { return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); } isFIFO() { return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); } isSocket() { return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); } } function attrsToBytes(attrs) { let flags = 0; let nb = 0; if (typeof attrs === 'object' && attrs !== null) { if (typeof attrs.size === 'number') { flags |= ATTR.SIZE; const val = attrs.size; // Big Endian ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 ATTRS_BUF[nb++] = val / 4294967296; // 2**32 ATTRS_BUF[nb++] = val / 16777216; // 2**24 ATTRS_BUF[nb++] = val / 65536; // 2**16 ATTRS_BUF[nb++] = val / 256; // 2**8 ATTRS_BUF[nb++] = val; } if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { flags |= ATTR.UIDGID; const uid = attrs.uid; const gid = attrs.gid; // Big Endian ATTRS_BUF[nb++] = uid >>> 24; ATTRS_BUF[nb++] = uid >>> 16; ATTRS_BUF[nb++] = uid >>> 8; ATTRS_BUF[nb++] = uid; ATTRS_BUF[nb++] = gid >>> 24; ATTRS_BUF[nb++] = gid >>> 16; ATTRS_BUF[nb++] = gid >>> 8; ATTRS_BUF[nb++] = gid; } if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { const mode = modeNum(attrs.mode); flags |= ATTR.PERMISSIONS; // Big Endian ATTRS_BUF[nb++] = mode >>> 24; ATTRS_BUF[nb++] = mode >>> 16; ATTRS_BUF[nb++] = mode >>> 8; ATTRS_BUF[nb++] = mode; } if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { const atime = toUnixTimestamp(attrs.atime); const mtime = toUnixTimestamp(attrs.mtime); flags |= ATTR.ACMODTIME; // Big Endian ATTRS_BUF[nb++] = atime >>> 24; ATTRS_BUF[nb++] = atime >>> 16; ATTRS_BUF[nb++] = atime >>> 8; ATTRS_BUF[nb++] = atime; ATTRS_BUF[nb++] = mtime >>> 24; ATTRS_BUF[nb++] = mtime >>> 16; ATTRS_BUF[nb++] = mtime >>> 8; ATTRS_BUF[nb++] = mtime; } // TODO: extended attributes } return { flags, nb }; } function toUnixTimestamp(time) { // eslint-disable-next-line no-self-compare if (typeof time === 'number' && time === time) // Valid, non-NaN number return time; if (isDate(time)) return parseInt(time.getTime() / 1000, 10); throw new Error(`Cannot parse time: ${time}`); } function modeNum(mode) { // eslint-disable-next-line no-self-compare if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number return mode; if (typeof mode === 'string') return modeNum(parseInt(mode, 8)); throw new Error(`Cannot parse mode: ${mode}`); } const stringFlagMap = { 'r': OPEN_MODE.READ, 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL, 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE | OPEN_MODE.EXCL }; function stringToFlags(str) { const flags = stringFlagMap[str]; return (flags !== undefined ? flags : null); } const flagsToString = (() => { const stringFlagMapKeys = Object.keys(stringFlagMap); return (flags) => { for (let i = 0; i < stringFlagMapKeys.length; ++i) { const key = stringFlagMapKeys[i]; if (stringFlagMap[key] === flags) return key; } return null; }; })(); function readAttrs(biOpt) { /* uint32 flags uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS uint32 atime present only if flag SSH_FILEXFER_ACMODTIME uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED string extended_type string extended_data ... more extended data (extended_type - extended_data pairs), so that number of pairs equals extended_count */ const flags = bufferParser.readUInt32BE(); if (flags === undefined) return; const attrs = new Stats(); if (flags & ATTR.SIZE) { const size = bufferParser.readUInt64BE(biOpt); if (size === undefined) return; attrs.size = size; } if (flags & ATTR.UIDGID) { const uid = bufferParser.readUInt32BE(); const gid = bufferParser.readUInt32BE(); if (gid === undefined) return; attrs.uid = uid; attrs.gid = gid; } if (flags & ATTR.PERMISSIONS) { const mode = bufferParser.readUInt32BE(); if (mode === undefined) return; attrs.mode = mode; } if (flags & ATTR.ACMODTIME) { const atime = bufferParser.readUInt32BE(); const mtime = bufferParser.readUInt32BE(); if (mtime === undefined) return; attrs.atime = atime; attrs.mtime = mtime; } if (flags & ATTR.EXTENDED) { const count = bufferParser.readUInt32BE(); if (count === undefined) return; const extended = {}; for (let i = 0; i < count; ++i) { const type = bufferParser.readString(true); const data = bufferParser.readString(); if (data === undefined) return; extended[type] = data; } attrs.extended = extended; } return attrs; } function sendOrBuffer(sftp, payload) { const ret = tryWritePayload(sftp, payload); if (ret !== undefined) { sftp._buffer.push(ret); return false; } return true; } function tryWritePayload(sftp, payload) { const outgoing = sftp.outgoing; if (outgoing.state !== 'open') return; if (outgoing.window === 0) { sftp._waitWindow = true; sftp._chunkcb = drainBuffer; return payload; } let ret; const len = payload.length; let p = 0; while (len - p > 0 && outgoing.window > 0) { const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); outgoing.window -= actualLen; if (outgoing.window === 0) { sftp._waitWindow = true; sftp._chunkcb = drainBuffer; } if (p === 0 && actualLen === len) { sftp._protocol.channelData(sftp.outgoing.id, payload); } else { sftp._protocol.channelData(sftp.outgoing.id, bufferSlice(payload, p, p + actualLen)); } p += actualLen; } if (len - p > 0) { if (p > 0) ret = bufferSlice(payload, p, len); else ret = payload; // XXX: should never get here? } return ret; } function drainBuffer() { this._chunkcb = undefined; const buffer = this._buffer; let i = 0; while (i < buffer.length) { const payload = buffer[i]; const ret = tryWritePayload(this, payload); if (ret !== undefined) { if (ret !== payload) buffer[i] = ret; if (i > 0) this._buffer = buffer.slice(i); return; } ++i; } if (i > 0) this._buffer = []; } function doFatalSFTPError(sftp, msg, noDebug) { const err = new Error(msg); err.level = 'sftp-protocol'; if (!noDebug && sftp._debug) sftp._debug(`SFTP: Inbound: ${msg}`); sftp.emit('error', err); sftp.destroy(); cleanupRequests(sftp); return false; } function cleanupRequests(sftp) { const keys = Object.keys(sftp._requests); if (keys.length === 0) return; const reqs = sftp._requests; sftp._requests = {}; const err = new Error('No response from server'); for (let i = 0; i < keys.length; ++i) { const req = reqs[keys[i]]; if (typeof req.cb === 'function') req.cb(err); } } function requestLimits(sftp, cb) { /* uint32 id string "limits@openssh.com" */ let p = 9; const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); writeUInt32BE(buf, buf.length - 4, 0); buf[4] = REQUEST.EXTENDED; const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; writeUInt32BE(buf, reqid, 5); writeUInt32BE(buf, 18, p); buf.utf8Write('limits@openssh.com', p += 4, 18); sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; const isBuffered = sendOrBuffer(sftp, buf); if (sftp._debug) { const which = (isBuffered ? 'Buffered' : 'Sending'); sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); } } const CLIENT_HANDLERS = { [RESPONSE.VERSION]: (sftp, payload) => { if (sftp._version !== -1) return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); const extensions = {}; /* uint32 version */ bufferParser.init(payload, 1); let version = bufferParser.readUInt32BE(); while (bufferParser.avail()) { const extName = bufferParser.readString(true); const extData = bufferParser.readString(true); if (extData === undefined) { version = undefined; break; } extensions[extName] = extData; } bufferParser.clear(); if (version === undefined) return doFatalSFTPError(sftp, 'Malformed VERSION packet'); if (sftp._debug) { const names = Object.keys(extensions); if (names.length) { sftp._debug( `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` ); } else { sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); } } sftp._version = version; sftp._extensions = extensions; if (extensions['limits@openssh.com'] === '1') { return requestLimits(sftp, (err, limits) => { if (!err) { if (limits.maxPktLen > 0) sftp._maxOutPktLen = limits.maxPktLen; if (limits.maxReadLen > 0) sftp._maxReadLen = limits.maxReadLen; if (limits.maxWriteLen > 0) sftp._maxWriteLen = limits.maxWriteLen; sftp.maxOpenHandles = ( limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity ); } sftp.emit('ready'); }); } sftp.emit('ready'); }, [RESPONSE.STATUS]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* uint32 error/status code string error message (ISO-10646 UTF-8) string language tag */ const errorCode = bufferParser.readUInt32BE(); const errorMsg = bufferParser.readString(true); bufferParser.clear(); // Note: we avoid checking that the error message and language tag are in // the packet because there are some broken implementations that incorrectly // omit them. The language tag in general was never really used amongst ssh // implementations, so in the case of a missing error message we just // default to something sensible. if (sftp._debug) { const jsonMsg = JSON.stringify(errorMsg); sftp._debug( `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` ); } const req = sftp._requests[reqID]; delete sftp._requests[reqID]; if (req && typeof req.cb === 'function') { if (errorCode === STATUS_CODE.OK) { req.cb(); return; } const err = new Error(errorMsg || STATUS_CODE_STR[errorCode] || 'Unknown status'); err.code = errorCode; req.cb(err); } }, [RESPONSE.HANDLE]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle */ const handle = bufferParser.readString(); bufferParser.clear(); if (handle === undefined) { if (reqID !== undefined) delete sftp._requests[reqID]; return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); } sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); const req = sftp._requests[reqID]; delete sftp._requests[reqID]; if (req && typeof req.cb === 'function') req.cb(undefined, handle); }, [RESPONSE.DATA]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); let req; if (reqID !== undefined) { req = sftp._requests[reqID]; delete sftp._requests[reqID]; } /* string data */ if (req && typeof req.cb === 'function') { if (req.buffer) { // We have already pre-allocated space to store the data const nb = bufferParser.readString(req.buffer); bufferParser.clear(); if (nb !== undefined) { sftp._debug && sftp._debug( `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` ); req.cb(undefined, req.buffer, nb); return; } } else { const data = bufferParser.readString(); bufferParser.clear(); if (data !== undefined) { sftp._debug && sftp._debug( `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` ); req.cb(undefined, data); return; } } } else { const nb = bufferParser.skipString(); bufferParser.clear(); if (nb !== undefined) { sftp._debug && sftp._debug( `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` ); return; } } return doFatalSFTPError(sftp, 'Malformed DATA packet'); }, [RESPONSE.NAME]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); let req; if (reqID !== undefined) { req = sftp._requests[reqID]; delete sftp._requests[reqID]; } /* uint32 count repeats count times: string filename string longname ATTRS attrs */ const count = bufferParser.readUInt32BE(); if (count !== undefined) { let names = []; for (let i = 0; i < count; ++i) { // We are going to assume UTF-8 for filenames despite the SFTPv3 // spec not specifying an encoding because the specs for newer // versions of the protocol all explicitly specify UTF-8 for // filenames const filename = bufferParser.readString(true); // `longname` only exists in SFTPv3 and since it typically will // contain the filename, we assume it is also UTF-8 const longname = bufferParser.readString(true); const attrs = readAttrs(sftp._biOpt); if (attrs === undefined) { names = undefined; break; } names.push({ filename, longname, attrs }); } if (names !== undefined) { sftp._debug && sftp._debug( `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` ); bufferParser.clear(); if (req && typeof req.cb === 'function') req.cb(undefined, names); return; } } bufferParser.clear(); return doFatalSFTPError(sftp, 'Malformed NAME packet'); }, [RESPONSE.ATTRS]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); let req; if (reqID !== undefined) { req = sftp._requests[reqID]; delete sftp._requests[reqID]; } /* ATTRS attrs */ const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs !== undefined) { sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); if (req && typeof req.cb === 'function') req.cb(undefined, attrs); return; } return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); }, [RESPONSE.EXTENDED]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); if (reqID !== undefined) { const req = sftp._requests[reqID]; if (req) { delete sftp._requests[reqID]; switch (req.extended) { case 'statvfs@openssh.com': case 'fstatvfs@openssh.com': { /* uint64 f_bsize // file system block size uint64 f_frsize // fundamental fs block size uint64 f_blocks // number of blocks (unit f_frsize) uint64 f_bfree // free blocks in file system uint64 f_bavail // free blocks for non-root uint64 f_files // total file inodes uint64 f_ffree // free file inodes uint64 f_favail // free file inodes for to non-root uint64 f_fsid // file system id uint64 f_flag // bit mask of f_flag values uint64 f_namemax // maximum filename length */ const biOpt = sftp._biOpt; const stats = { f_bsize: bufferParser.readUInt64BE(biOpt), f_frsize: bufferParser.readUInt64BE(biOpt), f_blocks: bufferParser.readUInt64BE(biOpt), f_bfree: bufferParser.readUInt64BE(biOpt), f_bavail: bufferParser.readUInt64BE(biOpt), f_files: bufferParser.readUInt64BE(biOpt), f_ffree: bufferParser.readUInt64BE(biOpt), f_favail: bufferParser.readUInt64BE(biOpt), f_sid: bufferParser.readUInt64BE(biOpt), f_flag: bufferParser.readUInt64BE(biOpt), f_namemax: bufferParser.readUInt64BE(biOpt), }; if (stats.f_namemax === undefined) break; if (sftp._debug) { sftp._debug( 'SFTP: Inbound: Received EXTENDED_REPLY ' + `(id:${reqID}, ${req.extended})` ); } bufferParser.clear(); if (typeof req.cb === 'function') req.cb(undefined, stats); return; } case 'limits@openssh.com': { /* uint64 max-packet-length uint64 max-read-length uint64 max-write-length uint64 max-open-handles */ const limits = { maxPktLen: bufferParser.readUInt64BE(), maxReadLen: bufferParser.readUInt64BE(), maxWriteLen: bufferParser.readUInt64BE(), maxOpenHandles: bufferParser.readUInt64BE(), }; if (limits.maxOpenHandles === undefined) break; if (sftp._debug) { sftp._debug( 'SFTP: Inbound: Received EXTENDED_REPLY ' + `(id:${reqID}, ${req.extended})` ); } bufferParser.clear(); if (typeof req.cb === 'function') req.cb(undefined, limits); return; } case 'users-groups-by-id@openssh.com': { /* string usernames string username1 ... string groupnames string groupname1 ... */ const usernameCount = bufferParser.readUInt32BE(); if (usernameCount === undefined) break; const usernames = new Array(usernameCount); for (let i = 0; i < usernames.length; ++i) usernames[i] = bufferParser.readString(true); const groupnameCount = bufferParser.readUInt32BE(); if (groupnameCount === undefined) break; const groupnames = new Array(groupnameCount); for (let i = 0; i < groupnames.length; ++i) groupnames[i] = bufferParser.readString(true); if (groupnames.length > 0 && groupnames[groupnames.length - 1] === undefined) { break; } if (sftp._debug) { sftp._debug( 'SFTP: Inbound: Received EXTENDED_REPLY ' + `(id:${reqID}, ${req.extended})` ); } bufferParser.clear(); if (typeof req.cb === 'function') req.cb(undefined, usernames, groupnames); return; } default: // Unknown extended request sftp._debug && sftp._debug( `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` ); bufferParser.clear(); if (typeof req.cb === 'function') req.cb(); return; } } else { sftp._debug && sftp._debug( `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` ); bufferParser.clear(); return; } } bufferParser.clear(); return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); }, }; const SERVER_HANDLERS = { [REQUEST.INIT]: (sftp, payload) => { if (sftp._version !== -1) return doFatalSFTPError(sftp, 'Duplicate INIT packet'); const extensions = {}; /* uint32 version */ bufferParser.init(payload, 1); let version = bufferParser.readUInt32BE(); while (bufferParser.avail()) { const extName = bufferParser.readString(true); const extData = bufferParser.readString(true); if (extData === undefined) { version = undefined; break; } extensions[extName] = extData; } bufferParser.clear(); if (version === undefined) return doFatalSFTPError(sftp, 'Malformed INIT packet'); if (sftp._debug) { const names = Object.keys(extensions); if (names.length) { sftp._debug( `SFTP: Inbound: Received INIT (v${version}, exts:${names})` ); } else { sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); } } sendOrBuffer(sftp, SERVER_VERSION_BUFFER); sftp._version = version; sftp._extensions = extensions; sftp.emit('ready'); }, [REQUEST.OPEN]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string filename uint32 pflags ATTRS attrs */ const filename = bufferParser.readString(true); const pflags = bufferParser.readUInt32BE(); const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs === undefined) return doFatalSFTPError(sftp, 'Malformed OPEN packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.CLOSE]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle */ const handle = bufferParser.readString(); bufferParser.clear(); if (handle === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); if (!sftp.emit('CLOSE', reqID, handle)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.READ]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle uint64 offset uint32 len */ const handle = bufferParser.readString(); const offset = bufferParser.readUInt64BE(sftp._biOpt); const len = bufferParser.readUInt32BE(); bufferParser.clear(); if (len === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed READ packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); if (!sftp.emit('READ', reqID, handle, offset, len)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.WRITE]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle uint64 offset string data */ const handle = bufferParser.readString(); const offset = bufferParser.readUInt64BE(sftp._biOpt); const data = bufferParser.readString(); bufferParser.clear(); if (data === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed WRITE packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); if (!sftp.emit('WRITE', reqID, handle, offset, data)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.LSTAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); if (!sftp.emit('LSTAT', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.FSTAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle */ const handle = bufferParser.readString(); bufferParser.clear(); if (handle === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); if (!sftp.emit('FSTAT', reqID, handle)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.SETSTAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path ATTRS attrs */ const path = bufferParser.readString(true); const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs === undefined) return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); if (!sftp.emit('SETSTAT', reqID, path, attrs)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.FSETSTAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle ATTRS attrs */ const handle = bufferParser.readString(); const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); sftp._debug && sftp._debug( `SFTP: Inbound: Received FSETSTAT (id:${reqID})` ); if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.OPENDIR]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); if (!sftp.emit('OPENDIR', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.READDIR]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string handle */ const handle = bufferParser.readString(); bufferParser.clear(); if (handle === undefined || handle.length > 256) return doFatalSFTPError(sftp, 'Malformed READDIR packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); if (!sftp.emit('READDIR', reqID, handle)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.REMOVE]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); if (!sftp.emit('REMOVE', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.MKDIR]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path ATTRS attrs */ const path = bufferParser.readString(true); const attrs = readAttrs(sftp._biOpt); bufferParser.clear(); if (attrs === undefined) return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); if (!sftp.emit('MKDIR', reqID, path, attrs)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.RMDIR]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); if (!sftp.emit('RMDIR', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.REALPATH]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); sftp._debug && sftp._debug( `SFTP: Inbound: Received REALPATH (id:${reqID})` ); if (!sftp.emit('REALPATH', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.STAT]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed STAT packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); if (!sftp.emit('STAT', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.RENAME]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string oldpath string newpath */ const oldPath = bufferParser.readString(true); const newPath = bufferParser.readString(true); bufferParser.clear(); if (newPath === undefined) return doFatalSFTPError(sftp, 'Malformed RENAME packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.READLINK]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string path */ const path = bufferParser.readString(true); bufferParser.clear(); if (path === undefined) return doFatalSFTPError(sftp, 'Malformed READLINK packet'); sftp._debug && sftp._debug( `SFTP: Inbound: Received READLINK (id:${reqID})` ); if (!sftp.emit('READLINK', reqID, path)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.SYMLINK]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string linkpath string targetpath */ const linkPath = bufferParser.readString(true); const targetPath = bufferParser.readString(true); bufferParser.clear(); if (targetPath === undefined) return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); let handled; if (sftp._isOpenSSH) { // OpenSSH has linkpath and targetpath positions switched handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); } else { handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); } if (!handled) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, [REQUEST.EXTENDED]: (sftp, payload) => { bufferParser.init(payload, 1); const reqID = bufferParser.readUInt32BE(); /* string extended-request ... any request-specific data ... */ const extName = bufferParser.readString(true); if (extName === undefined) { bufferParser.clear(); return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); } let extData; if (bufferParser.avail()) extData = bufferParser.readRaw(); bufferParser.clear(); sftp._debug && sftp._debug( `SFTP: Inbound: Received EXTENDED (id:${reqID})` ); if (!sftp.emit('EXTENDED', reqID, extName, extData)) { // Automatically reject request if no handler for request type sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } }, }; // ============================================================================= // ReadStream/WriteStream-related ============================================== // ============================================================================= const { ERR_INVALID_ARG_TYPE, ERR_OUT_OF_RANGE, validateNumber } = __nccwpck_require__(3208); const kMinPoolSpace = 128; let pool; // It can happen that we expect to read a large chunk of data, and reserve // a large chunk of the pool accordingly, but the read() call only filled // a portion of it. If a concurrently executing read() then uses the same pool, // the "reserved" portion cannot be used, so we allow it to be re-used as a // new pool later. const poolFragments = []; function allocNewPool(poolSize) { if (poolFragments.length > 0) pool = poolFragments.pop(); else pool = Buffer.allocUnsafe(poolSize); pool.used = 0; } // Check the `this.start` and `this.end` of stream. function checkPosition(pos, name) { if (!Number.isSafeInteger(pos)) { validateNumber(pos, name); if (!Number.isInteger(pos)) throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); } if (pos < 0) throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); } function roundUpToMultipleOf8(n) { return (n + 7) & ~7; // Align to 8 byte boundary. } function ReadStream(sftp, path, options) { if (options === undefined) options = {}; else if (typeof options === 'string') options = { encoding: options }; else if (options === null || typeof options !== 'object') throw new TypeError('"options" argument must be a string or an object'); else options = Object.create(options); // A little bit bigger buffer and water marks by default if (options.highWaterMark === undefined) options.highWaterMark = 64 * 1024; // For backwards compat do not emit close on destroy. options.emitClose = false; options.autoDestroy = false; // Node 14 major change. ReadableStream.call(this, options); this.path = path; this.flags = options.flags === undefined ? 'r' : options.flags; this.mode = options.mode === undefined ? 0o666 : options.mode; this.start = options.start; this.end = options.end; this.autoClose = options.autoClose === undefined ? true : options.autoClose; this.pos = 0; this.bytesRead = 0; this.isClosed = false; this.handle = options.handle === undefined ? null : options.handle; this.sftp = sftp; this._opening = false; if (this.start !== undefined) { checkPosition(this.start, 'start'); this.pos = this.start; } if (this.end === undefined) { this.end = Infinity; } else if (this.end !== Infinity) { checkPosition(this.end, 'end'); if (this.start !== undefined && this.start > this.end) { throw new ERR_OUT_OF_RANGE( 'start', `<= "end" (here: ${this.end})`, this.start ); } } this.on('end', function() { if (this.autoClose) this.destroy(); }); if (!Buffer.isBuffer(this.handle)) this.open(); } inherits(ReadStream, ReadableStream); ReadStream.prototype.open = function() { if (this._opening) return; this._opening = true; this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { this._opening = false; if (er) { this.emit('error', er); if (this.autoClose) this.destroy(); return; } this.handle = handle; this.emit('open', handle); this.emit('ready'); // Start the flow of data. this.read(); }); }; ReadStream.prototype._read = function(n) { if (!Buffer.isBuffer(this.handle)) return this.once('open', () => this._read(n)); // XXX: safe to remove this? if (this.destroyed) return; if (!pool || pool.length - pool.used < kMinPoolSpace) { // Discard the old pool. allocNewPool(this.readableHighWaterMark || this._readableState.highWaterMark); } // Grab another reference to the pool in the case that while we're // in the thread pool another read() finishes up the pool, and // allocates a new one. const thisPool = pool; let toRead = Math.min(pool.length - pool.used, n); const start = pool.used; if (this.end !== undefined) toRead = Math.min(this.end - this.pos + 1, toRead); // Already read everything we were supposed to read! // treat as EOF. if (toRead <= 0) return this.push(null); // the actual read. this.sftp.read(this.handle, pool, pool.used, toRead, this.pos, (er, bytesRead) => { if (er) { this.emit('error', er); if (this.autoClose) this.destroy(); return; } let b = null; // Now that we know how much data we have actually read, re-wind the // 'used' field if we can, and otherwise allow the remainder of our // reservation to be used as a new pool later. if (start + toRead === thisPool.used && thisPool === pool) { thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); } else { // Round down to the next lowest multiple of 8 to ensure the new pool // fragment start and end positions are aligned to an 8 byte boundary. const alignedEnd = (start + toRead) & ~7; const alignedStart = roundUpToMultipleOf8(start + bytesRead); if (alignedEnd - alignedStart >= kMinPoolSpace) poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); } if (bytesRead > 0) { this.bytesRead += bytesRead; b = thisPool.slice(start, start + bytesRead); } // Move the pool positions, and internal position for reading. this.pos += bytesRead; this.push(b); }); pool.used = roundUpToMultipleOf8(pool.used + toRead); }; ReadStream.prototype._destroy = function(err, cb) { if (this._opening && !Buffer.isBuffer(this.handle)) { this.once('open', closeStream.bind(null, this, cb, err)); return; } closeStream(this, cb, err); this.handle = null; this._opening = false; }; function closeStream(stream, cb, err) { if (!stream.handle) return onclose(); stream.sftp.close(stream.handle, onclose); function onclose(er) { er = er || err; cb(er); stream.isClosed = true; if (!er) stream.emit('close'); } } ReadStream.prototype.close = function(cb) { this.destroy(null, cb); }; Object.defineProperty(ReadStream.prototype, 'pending', { get() { return this.handle === null; }, configurable: true }); // TODO: add `concurrency` setting to allow more than one in-flight WRITE // request to server to improve throughput function WriteStream(sftp, path, options) { if (options === undefined) options = {}; else if (typeof options === 'string') options = { encoding: options }; else if (options === null || typeof options !== 'object') throw new TypeError('"options" argument must be a string or an object'); else options = Object.create(options); // For backwards compat do not emit close on destroy. options.emitClose = false; options.autoDestroy = false; // Node 14 major change. WritableStream.call(this, options); this.path = path; this.flags = options.flags === undefined ? 'w' : options.flags; this.mode = options.mode === undefined ? 0o666 : options.mode; this.start = options.start; this.autoClose = options.autoClose === undefined ? true : options.autoClose; this.pos = 0; this.bytesWritten = 0; this.isClosed = false; this.handle = options.handle === undefined ? null : options.handle; this.sftp = sftp; this._opening = false; if (this.start !== undefined) { checkPosition(this.start, 'start'); this.pos = this.start; } if (options.encoding) this.setDefaultEncoding(options.encoding); // Node v6.x only this.on('finish', function() { if (this._writableState.finalCalled) return; if (this.autoClose) this.destroy(); }); if (!Buffer.isBuffer(this.handle)) this.open(); } inherits(WriteStream, WritableStream); WriteStream.prototype._final = function(cb) { if (this.autoClose) this.destroy(); cb(); }; WriteStream.prototype.open = function() { if (this._opening) return; this._opening = true; this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { this._opening = false; if (er) { this.emit('error', er); if (this.autoClose) this.destroy(); return; } this.handle = handle; const tryAgain = (err) => { if (err) { // Try chmod() for sftp servers that may not support fchmod() for // whatever reason this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); return; } // SFTPv3 requires absolute offsets, no matter the open flag used if (this.flags[0] === 'a') { const tryStat = (err, st) => { if (err) { // Try stat() for sftp servers that may not support fstat() for // whatever reason this.sftp.stat(this.path, (err_, st_) => { if (err_) { this.destroy(); this.emit('error', err); return; } tryStat(null, st_); }); return; } this.pos = st.size; this.emit('open', handle); this.emit('ready'); }; this.sftp.fstat(handle, tryStat); return; } this.emit('open', handle); this.emit('ready'); }; this.sftp.fchmod(handle, this.mode, tryAgain); }); }; WriteStream.prototype._write = function(data, encoding, cb) { if (!Buffer.isBuffer(data)) { const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); return this.emit('error', err); } if (!Buffer.isBuffer(this.handle)) { return this.once('open', function() { this._write(data, encoding, cb); }); } this.sftp.write(this.handle, data, 0, data.length, this.pos, (er, bytes) => { if (er) { if (this.autoClose) this.destroy(); return cb(er); } this.bytesWritten += bytes; cb(); }); this.pos += data.length; }; WriteStream.prototype._writev = function(data, cb) { if (!Buffer.isBuffer(this.handle)) { return this.once('open', function() { this._writev(data, cb); }); } const sftp = this.sftp; const handle = this.handle; let writesLeft = data.length; const onwrite = (er, bytes) => { if (er) { this.destroy(); return cb(er); } this.bytesWritten += bytes; if (--writesLeft === 0) cb(); }; // TODO: try to combine chunks to reduce number of requests to the server? for (let i = 0; i < data.length; ++i) { const chunk = data[i].chunk; sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); this.pos += chunk.length; } }; if (typeof WritableStream.prototype.destroy !== 'function') WriteStream.prototype.destroy = ReadStream.prototype.destroy; WriteStream.prototype._destroy = ReadStream.prototype._destroy; WriteStream.prototype.close = function(cb) { if (cb) { if (this.isClosed) { process.nextTick(cb); return; } this.on('close', cb); } // If we are not autoClosing, we should call // destroy on 'finish'. if (!this.autoClose) this.on('finish', this.destroy.bind(this)); this.end(); }; // There is no shutdown() for files. WriteStream.prototype.destroySoon = WriteStream.prototype.end; Object.defineProperty(WriteStream.prototype, 'pending', { get() { return this.handle === null; }, configurable: true }); // ============================================================================= module.exports = { flagsToString, OPEN_MODE, SFTP, Stats, STATUS_CODE, stringToFlags, }; /***/ }), /***/ 4020: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const crypto = __nccwpck_require__(6982); let cpuInfo; try { cpuInfo = __nccwpck_require__(4982)(); } catch {} const { bindingAvailable, CIPHER_INFO, MAC_INFO } = __nccwpck_require__(2888); const eddsaSupported = (() => { if (typeof crypto.sign === 'function' && typeof crypto.verify === 'function') { const key = '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; const data = Buffer.from('a'); let sig; let verified; try { sig = crypto.sign(null, data, key); verified = crypto.verify(null, data, key, sig); } catch {} return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); } return false; })(); const curve25519Supported = (typeof crypto.diffieHellman === 'function' && typeof crypto.generateKeyPairSync === 'function' && typeof crypto.createPublicKey === 'function'); const DEFAULT_KEX = [ // https://tools.ietf.org/html/rfc5656#section-10.1 'ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', // https://tools.ietf.org/html/rfc4419#section-4 'diffie-hellman-group-exchange-sha256', // https://tools.ietf.org/html/rfc8268 'diffie-hellman-group14-sha256', 'diffie-hellman-group15-sha512', 'diffie-hellman-group16-sha512', 'diffie-hellman-group17-sha512', 'diffie-hellman-group18-sha512', ]; if (curve25519Supported) { DEFAULT_KEX.unshift('curve25519-sha256'); DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); } const SUPPORTED_KEX = DEFAULT_KEX.concat([ // https://tools.ietf.org/html/rfc4419#section-4 'diffie-hellman-group-exchange-sha1', 'diffie-hellman-group14-sha1', // REQUIRED 'diffie-hellman-group1-sha1', // REQUIRED ]); const DEFAULT_SERVER_HOST_KEY = [ 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521', 'rsa-sha2-512', // RFC 8332 'rsa-sha2-256', // RFC 8332 'ssh-rsa', ]; if (eddsaSupported) DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ 'ssh-dss', ]); const canUseCipher = (() => { const ciphers = crypto.getCiphers(); return (name) => ciphers.includes(CIPHER_INFO[name].sslName); })(); let DEFAULT_CIPHER = [ // http://tools.ietf.org/html/rfc5647 'aes128-gcm@openssh.com', 'aes256-gcm@openssh.com', // http://tools.ietf.org/html/rfc4344#section-4 'aes128-ctr', 'aes192-ctr', 'aes256-ctr', ]; if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { // We know for sure the CPU does not support AES acceleration if (bindingAvailable) DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); else DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); } else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers // seem to outperform it on x86, but it seems to be faster than CTR ciphers DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); } else { DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); } DEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher); const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ 'aes256-cbc', 'aes192-cbc', 'aes128-cbc', 'blowfish-cbc', '3des-cbc', 'aes128-gcm', 'aes256-gcm', // http://tools.ietf.org/html/rfc4345#section-4: 'arcfour256', 'arcfour128', 'cast128-cbc', 'arcfour', ].filter(canUseCipher)); const canUseMAC = (() => { const hashes = crypto.getHashes(); return (name) => hashes.includes(MAC_INFO[name].sslName); })(); const DEFAULT_MAC = [ 'hmac-sha2-256-etm@openssh.com', 'hmac-sha2-512-etm@openssh.com', 'hmac-sha1-etm@openssh.com', 'hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1', ].filter(canUseMAC); const SUPPORTED_MAC = DEFAULT_MAC.concat([ 'hmac-md5', 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 'hmac-ripemd160', 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 'hmac-md5-96', // first 96 bits of HMAC-MD5 ].filter(canUseMAC)); const DEFAULT_COMPRESSION = [ 'none', 'zlib@openssh.com', // ZLIB (LZ77) compression, except // compression/decompression does not start until after // successful user authentication 'zlib', // ZLIB (LZ77) compression ]; const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ ]); const COMPAT = { BAD_DHGEX: 1 << 0, OLD_EXIT: 1 << 1, DYN_RPORT_BUG: 1 << 2, BUG_DHGEX_LARGE: 1 << 3, IMPLY_RSA_SHA2_SIGALGS: 1 << 4, }; module.exports = { MESSAGE: { // Transport layer protocol -- generic (1-19) DISCONNECT: 1, IGNORE: 2, UNIMPLEMENTED: 3, DEBUG: 4, SERVICE_REQUEST: 5, SERVICE_ACCEPT: 6, EXT_INFO: 7, // RFC 8308 // Transport layer protocol -- algorithm negotiation (20-29) KEXINIT: 20, NEWKEYS: 21, // Transport layer protocol -- key exchange method-specific (30-49) KEXDH_INIT: 30, KEXDH_REPLY: 31, KEXDH_GEX_GROUP: 31, KEXDH_GEX_INIT: 32, KEXDH_GEX_REPLY: 33, KEXDH_GEX_REQUEST: 34, KEXECDH_INIT: 30, KEXECDH_REPLY: 31, // User auth protocol -- generic (50-59) USERAUTH_REQUEST: 50, USERAUTH_FAILURE: 51, USERAUTH_SUCCESS: 52, USERAUTH_BANNER: 53, // User auth protocol -- user auth method-specific (60-79) USERAUTH_PASSWD_CHANGEREQ: 60, USERAUTH_PK_OK: 60, USERAUTH_INFO_REQUEST: 60, USERAUTH_INFO_RESPONSE: 61, // Connection protocol -- generic (80-89) GLOBAL_REQUEST: 80, REQUEST_SUCCESS: 81, REQUEST_FAILURE: 82, // Connection protocol -- channel-related (90-127) CHANNEL_OPEN: 90, CHANNEL_OPEN_CONFIRMATION: 91, CHANNEL_OPEN_FAILURE: 92, CHANNEL_WINDOW_ADJUST: 93, CHANNEL_DATA: 94, CHANNEL_EXTENDED_DATA: 95, CHANNEL_EOF: 96, CHANNEL_CLOSE: 97, CHANNEL_REQUEST: 98, CHANNEL_SUCCESS: 99, CHANNEL_FAILURE: 100 // Reserved for client protocols (128-191) // Local extensions (192-155) }, DISCONNECT_REASON: { HOST_NOT_ALLOWED_TO_CONNECT: 1, PROTOCOL_ERROR: 2, KEY_EXCHANGE_FAILED: 3, RESERVED: 4, MAC_ERROR: 5, COMPRESSION_ERROR: 6, SERVICE_NOT_AVAILABLE: 7, PROTOCOL_VERSION_NOT_SUPPORTED: 8, HOST_KEY_NOT_VERIFIABLE: 9, CONNECTION_LOST: 10, BY_APPLICATION: 11, TOO_MANY_CONNECTIONS: 12, AUTH_CANCELED_BY_USER: 13, NO_MORE_AUTH_METHODS_AVAILABLE: 14, ILLEGAL_USER_NAME: 15, }, DISCONNECT_REASON_STR: undefined, CHANNEL_OPEN_FAILURE: { ADMINISTRATIVELY_PROHIBITED: 1, CONNECT_FAILED: 2, UNKNOWN_CHANNEL_TYPE: 3, RESOURCE_SHORTAGE: 4 }, TERMINAL_MODE: { TTY_OP_END: 0, // Indicates end of options. VINTR: 1, // Interrupt character; 255 if none. Similarly for the // other characters. Not all of these characters are // supported on all systems. VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX // systems). VERASE: 3, // Erase the character to left of the cursor. VKILL: 4, // Kill the current input line. VEOF: 5, // End-of-file character (sends EOF from the // terminal). VEOL: 6, // End-of-line character in addition to carriage // return and/or linefeed. VEOL2: 7, // Additional end-of-line character. VSTART: 8, // Continues paused output (normally control-Q). VSTOP: 9, // Pauses output (normally control-S). VSUSP: 10, // Suspends the current program. VDSUSP: 11, // Another suspend character. VREPRINT: 12, // Reprints the current input line. VWERASE: 13, // Erases a word left of cursor. VLNEXT: 14, // Enter the next character typed literally, even if // it is a special character VFLUSH: 15, // Character to flush output. VSWTCH: 16, // Switch to a different shell layer. VSTATUS: 17, // Prints system status line (load, command, pid, // etc). VDISCARD: 18, // Toggles the flushing of terminal output. IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 // if this flag is FALSE, and 1 if it is TRUE. PARMRK: 31, // Mark parity and framing errors. INPCK: 32, // Enable checking of parity errors. ISTRIP: 33, // Strip 8th bit off characters. INLCR: 34, // Map NL into CR on input. IGNCR: 35, // Ignore CR on input. ICRNL: 36, // Map CR to NL on input. IUCLC: 37, // Translate uppercase characters to lowercase. IXON: 38, // Enable output flow control. IXANY: 39, // Any char will restart after stop. IXOFF: 40, // Enable input flow control. IMAXBEL: 41, // Ring bell on input queue full. ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. ICANON: 51, // Canonicalize input lines. XCASE: 52, // Enable input and output of uppercase characters by // preceding their lowercase equivalents with "\". ECHO: 53, // Enable echoing. ECHOE: 54, // Visually erase chars. ECHOK: 55, // Kill character discards current line. ECHONL: 56, // Echo NL even if ECHO is off. NOFLSH: 57, // Don't flush after interrupt. TOSTOP: 58, // Stop background jobs from output. IEXTEN: 59, // Enable extensions. ECHOCTL: 60, // Echo control characters as ^(Char). ECHOKE: 61, // Visual erase for line kill. PENDIN: 62, // Retype pending input. OPOST: 70, // Enable output processing. OLCUC: 71, // Convert lowercase to uppercase. ONLCR: 72, // Map NL to CR-NL. OCRNL: 73, // Translate carriage return to newline (output). ONOCR: 74, // Translate newline to carriage return-newline // (output). ONLRET: 75, // Newline performs a carriage return (output). CS7: 90, // 7 bit mode. CS8: 91, // 8 bit mode. PARENB: 92, // Parity enable. PARODD: 93, // Odd parity, else even. TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. }, CHANNEL_EXTENDED_DATATYPE: { STDERR: 1, }, SIGNALS: [ 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', 'USR2', 'KILL', 'PIPE' ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), COMPAT, COMPAT_CHECKS: [ [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], [ /^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE ], [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations [ /^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG ], [ /^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS ], ], // KEX proposal-related DEFAULT_KEX, SUPPORTED_KEX, DEFAULT_SERVER_HOST_KEY, SUPPORTED_SERVER_HOST_KEY, DEFAULT_CIPHER, SUPPORTED_CIPHER, DEFAULT_MAC, SUPPORTED_MAC, DEFAULT_COMPRESSION, SUPPORTED_COMPRESSION, curve25519Supported, eddsaSupported, }; module.exports.DISCONNECT_REASON_BY_VALUE = Array.from(Object.entries(module.exports.DISCONNECT_REASON)) .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); /***/ }), /***/ 2888: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // TODO: // * make max packet size configurable // * if decompression is enabled, use `._packet` in decipher instances as // input to (sync) zlib inflater with appropriate offset and length to // avoid an additional copy of payload data before inflation // * factor decompression status into packet length checks const { createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual } = __nccwpck_require__(6982); const { readUInt32BE, writeUInt32BE } = __nccwpck_require__(2184); const FastBuffer = Buffer[Symbol.species]; const MAX_SEQNO = 2 ** 32 - 1; const EMPTY_BUFFER = Buffer.alloc(0); const BUF_INT = Buffer.alloc(4); const DISCARD_CACHE = new Map(); const MAX_PACKET_SIZE = 35000; let binding; let AESGCMCipher; let ChaChaPolyCipher; let GenericCipher; let AESGCMDecipher; let ChaChaPolyDecipher; let GenericDecipher; try { binding = __nccwpck_require__(8440); ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); } catch {} const CIPHER_STREAM = 1 << 0; const CIPHER_INFO = (() => { function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { return { sslName, blockLen, keyLen, ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) ? ivLen : blockLen), authLen, discardLen, stream: !!(flags & CIPHER_STREAM), }; } return { 'chacha20-poly1305@openssh.com': info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), 'aes128-gcm@openssh.com': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), 'aes256-gcm@openssh.com': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), /* The "arcfour128" algorithm is the RC4 cipher, as described in [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream generated by the cipher MUST be discarded, and the first byte of the first encrypted packet MUST be encrypted using the 1537th byte of keystream. -- http://tools.ietf.org/html/rfc4345#section-4 */ 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), }; })(); const MAC_INFO = (() => { function info(sslName, len, actualLen, isETM) { return { sslName, len, actualLen, isETM, }; } return { 'hmac-md5': info('md5', 16, 16, false), 'hmac-md5-96': info('md5', 16, 12, false), 'hmac-ripemd160': info('ripemd160', 20, 20, false), 'hmac-sha1': info('sha1', 20, 20, false), 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), 'hmac-sha1-96': info('sha1', 20, 12, false), 'hmac-sha2-256': info('sha256', 32, 32, false), 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), 'hmac-sha2-256-96': info('sha256', 32, 12, false), 'hmac-sha2-512': info('sha512', 64, 64, false), 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), 'hmac-sha2-512-96': info('sha512', 64, 12, false), }; })(); // Should only_be used during the initial handshake class NullCipher { constructor(seqno, onWrite) { this.outSeqno = seqno; this._onWrite = onWrite; this._dead = false; } free() { this._dead = true; } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 8 - (pktLen & (8 - 1)); if (padLen < 4) padLen += 8; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; this._onWrite(packet); this.outSeqno = (this.outSeqno + 1) >>> 0; } } const POLY1305_ZEROS = Buffer.alloc(32); const POLY1305_OUT_COMPUTE = Buffer.alloc(16); let POLY1305_WASM_MODULE; let POLY1305_RESULT_MALLOC; let poly1305_auth; class ChaChaPolyCipherNative { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._encKeyMain = enc.cipherKey.slice(0, 32); this._encKeyPktLen = enc.cipherKey.slice(32); this._dead = false; } free() { this._dead = true; } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 8 - ((pktLen - 4) & (8 - 1)); if (padLen < 4) padLen += 8; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; // Generate Poly1305 key POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); const polyKey = createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) .update(POLY1305_ZEROS); // Encrypt packet length const pktLenEnc = createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) .update(packet.slice(0, 4)); this._onWrite(pktLenEnc); // Encrypt rest of packet POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) const payloadEnc = createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) .update(packet.slice(4)); this._onWrite(payloadEnc); // Calculate Poly1305 MAC poly1305_auth(POLY1305_RESULT_MALLOC, pktLenEnc, pktLenEnc.length, payloadEnc, payloadEnc.length, polyKey); const mac = Buffer.allocUnsafe(16); mac.set( new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, POLY1305_RESULT_MALLOC, 16), 0 ); this._onWrite(mac); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class ChaChaPolyCipherBinding { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._instance = new ChaChaPolyCipher(enc.cipherKey); this._dead = false; } free() { this._dead = true; this._instance.free(); } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 8 - ((pktLen - 4) & (8 - 1)); if (padLen < 4) padLen += 8; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; // Encrypts in-place this._instance.encrypt(packet, this.outSeqno); this._onWrite(packet); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class AESGCMCipherNative { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._encSSLName = enc.cipherInfo.sslName; this._encKey = enc.cipherKey; this._encIV = enc.cipherIV; this._dead = false; } free() { this._dead = true; } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 16 - ((pktLen - 4) & (16 - 1)); if (padLen < 4) padLen += 16; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); cipher.setAutoPadding(false); const lenData = packet.slice(0, 4); cipher.setAAD(lenData); this._onWrite(lenData); // Encrypt pad length, payload, and padding const encrypted = cipher.update(packet.slice(4)); this._onWrite(encrypted); const final = cipher.final(); // XXX: final.length === 0 always? if (final.length) this._onWrite(final); // Generate MAC const tag = cipher.getAuthTag(); this._onWrite(tag); // Increment counter in IV by 1 for next packet ivIncrement(this._encIV); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class AESGCMCipherBinding { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._instance = new AESGCMCipher(enc.cipherInfo.sslName, enc.cipherKey, enc.cipherIV); this._dead = false; } free() { this._dead = true; this._instance.free(); } allocPacket(payloadLen) { let pktLen = 4 + 1 + payloadLen; let padLen = 16 - ((pktLen - 4) & (16 - 1)); if (padLen < 4) padLen += 16; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; // Encrypts in-place this._instance.encrypt(packet); this._onWrite(packet); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class GenericCipherNative { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._encBlockLen = enc.cipherInfo.blockLen; this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, enc.cipherKey, enc.cipherIV); this._macSSLName = enc.macInfo.sslName; this._macKey = enc.macKey; this._macActualLen = enc.macInfo.actualLen; this._macETM = enc.macInfo.isETM; this._aadLen = (this._macETM ? 4 : 0); this._dead = false; const discardLen = enc.cipherInfo.discardLen; if (discardLen) { let discard = DISCARD_CACHE.get(discardLen); if (discard === undefined) { discard = Buffer.alloc(discardLen); DISCARD_CACHE.set(discardLen, discard); } this._cipherInstance.update(discard); } } free() { this._dead = true; } allocPacket(payloadLen) { const blockLen = this._encBlockLen; let pktLen = 4 + 1 + payloadLen; let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); if (padLen < 4) padLen += blockLen; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; let mac; if (this._macETM) { // Encrypt pad length, payload, and padding const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); const encrypted = this._cipherInstance.update( new Uint8Array(packet.buffer, packet.byteOffset + 4, packet.length - 4) ); this._onWrite(lenBytes); this._onWrite(encrypted); // TODO: look into storing seqno as 4-byte buffer and incrementing like we // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time mac = createHmac(this._macSSLName, this._macKey); writeUInt32BE(BUF_INT, this.outSeqno, 0); mac.update(BUF_INT); mac.update(lenBytes); mac.update(encrypted); } else { // Encrypt length field, pad length, payload, and padding const encrypted = this._cipherInstance.update(packet); this._onWrite(encrypted); // TODO: look into storing seqno as 4-byte buffer and incrementing like we // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time mac = createHmac(this._macSSLName, this._macKey); writeUInt32BE(BUF_INT, this.outSeqno, 0); mac.update(BUF_INT); mac.update(packet); } let digest = mac.digest(); if (digest.length > this._macActualLen) digest = digest.slice(0, this._macActualLen); this._onWrite(digest); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class GenericCipherBinding { constructor(config) { const enc = config.outbound; this.outSeqno = enc.seqno; this._onWrite = enc.onWrite; this._encBlockLen = enc.cipherInfo.blockLen; this._macLen = enc.macInfo.len; this._macActualLen = enc.macInfo.actualLen; this._aadLen = (enc.macInfo.isETM ? 4 : 0); this._instance = new GenericCipher(enc.cipherInfo.sslName, enc.cipherKey, enc.cipherIV, enc.macInfo.sslName, enc.macKey, enc.macInfo.isETM); this._dead = false; } free() { this._dead = true; this._instance.free(); } allocPacket(payloadLen) { const blockLen = this._encBlockLen; let pktLen = 4 + 1 + payloadLen; let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); if (padLen < 4) padLen += blockLen; pktLen += padLen; const packet = Buffer.allocUnsafe(pktLen + this._macLen); writeUInt32BE(packet, pktLen - 4, 0); packet[4] = padLen; randomFillSync(packet, 5 + payloadLen, padLen); return packet; } encrypt(packet) { // `packet` === unencrypted packet if (this._dead) return; // Encrypts in-place this._instance.encrypt(packet, this.outSeqno); if (this._macActualLen < this._macLen) { packet = new FastBuffer(packet.buffer, packet.byteOffset, (packet.length - (this._macLen - this._macActualLen))); } this._onWrite(packet); this.outSeqno = (this.outSeqno + 1) >>> 0; } } class NullDecipher { constructor(seqno, onPayload) { this.inSeqno = seqno; this._onPayload = onPayload; this._len = 0; this._lenBytes = 0; this._packet = null; this._packetPos = 0; } free() {} decrypt(data, p, dataLen) { while (p < dataLen) { // Read packet length if (this._lenBytes < 4) { let nb = Math.min(4 - this._lenBytes, dataLen - p); this._lenBytes += nb; while (nb--) this._len = (this._len << 8) + data[p++]; if (this._lenBytes < 4) return; if (this._len > MAX_PACKET_SIZE || this._len < 8 || (4 + this._len & 7) !== 0) { throw new Error('Bad packet length'); } if (p >= dataLen) return; } // Read padding length, payload, and padding if (this._packetPos < this._len) { const nb = Math.min(this._len - this._packetPos, dataLen - p); let chunk; if (p !== 0 || nb !== dataLen) chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); else chunk = data; if (nb === this._len) { this._packet = chunk; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(chunk, this._packetPos); } p += nb; this._packetPos += nb; if (this._packetPos < this._len) return; } const payload = (!this._packet ? EMPTY_BUFFER : new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1)); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._len = 0; this._lenBytes = 0; this._packet = null; this._packetPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class ChaChaPolyDecipherNative { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._decKeyMain = dec.decipherKey.slice(0, 32); this._decKeyPktLen = dec.decipherKey.slice(32); this._len = 0; this._lenBuf = Buffer.alloc(4); this._lenPos = 0; this._packet = null; this._pktLen = 0; this._mac = Buffer.allocUnsafe(16); this._calcMac = Buffer.allocUnsafe(16); this._macPos = 0; } free() {} decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read packet length if (this._lenPos < 4) { let nb = Math.min(4 - this._lenPos, dataLen - p); while (nb--) this._lenBuf[this._lenPos++] = data[p++]; if (this._lenPos < 4) return; POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); const decLenBytes = createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) .update(this._lenBuf); this._len = readUInt32BE(decLenBytes, 0); if (this._len > MAX_PACKET_SIZE || this._len < 8 || (this._len & 7) !== 0) { throw new Error('Bad packet length'); } } // Read padding length, payload, and padding if (this._pktLen < this._len) { if (p >= dataLen) return; const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (nb === this._len) { this._packet = encrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(encrypted, this._pktLen); } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read Poly1305 MAC { const nb = Math.min(16 - this._macPos, dataLen - p); // TODO: avoid copying if entire MAC is in current chunk if (p !== 0 || nb !== dataLen) { this._mac.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._macPos ); } else { this._mac.set(data, this._macPos); } p += nb; this._macPos += nb; if (this._macPos < 16) return; } // Generate Poly1305 key POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); const polyKey = createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) .update(POLY1305_ZEROS); // Calculate and compare Poly1305 MACs poly1305_auth(POLY1305_RESULT_MALLOC, this._lenBuf, 4, this._packet, this._packet.length, polyKey); this._calcMac.set( new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, POLY1305_RESULT_MALLOC, 16), 0 ); if (!timingSafeEqual(this._calcMac, this._mac)) throw new Error('Invalid MAC'); // Decrypt packet POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) const packet = createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) .update(this._packet); const payload = new FastBuffer(packet.buffer, packet.byteOffset + 1, packet.length - packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._len = 0; this._lenPos = 0; this._packet = null; this._pktLen = 0; this._macPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class ChaChaPolyDecipherBinding { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._instance = new ChaChaPolyDecipher(dec.decipherKey); this._len = 0; this._lenBuf = Buffer.alloc(4); this._lenPos = 0; this._packet = null; this._pktLen = 0; this._mac = Buffer.allocUnsafe(16); this._macPos = 0; } free() { this._instance.free(); } decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read packet length if (this._lenPos < 4) { let nb = Math.min(4 - this._lenPos, dataLen - p); while (nb--) this._lenBuf[this._lenPos++] = data[p++]; if (this._lenPos < 4) return; this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); if (this._len > MAX_PACKET_SIZE || this._len < 8 || (this._len & 7) !== 0) { throw new Error('Bad packet length'); } if (p >= dataLen) return; } // Read padding length, payload, and padding if (this._pktLen < this._len) { const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (nb === this._len) { this._packet = encrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(encrypted, this._pktLen); } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read Poly1305 MAC { const nb = Math.min(16 - this._macPos, dataLen - p); // TODO: avoid copying if entire MAC is in current chunk if (p !== 0 || nb !== dataLen) { this._mac.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._macPos ); } else { this._mac.set(data, this._macPos); } p += nb; this._macPos += nb; if (this._macPos < 16) return; } this._instance.decrypt(this._packet, this._mac, this.inSeqno); const payload = new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._len = 0; this._lenPos = 0; this._packet = null; this._pktLen = 0; this._macPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class AESGCMDecipherNative { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._decipherInstance = null; this._decipherSSLName = dec.decipherInfo.sslName; this._decipherKey = dec.decipherKey; this._decipherIV = dec.decipherIV; this._len = 0; this._lenBytes = 0; this._packet = null; this._packetPos = 0; this._pktLen = 0; this._tag = Buffer.allocUnsafe(16); this._tagPos = 0; } free() {} decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read packet length (unencrypted, but AAD) if (this._lenBytes < 4) { let nb = Math.min(4 - this._lenBytes, dataLen - p); this._lenBytes += nb; while (nb--) this._len = (this._len << 8) + data[p++]; if (this._lenBytes < 4) return; if ((this._len + 20) > MAX_PACKET_SIZE || this._len < 16 || (this._len & 15) !== 0) { throw new Error('Bad packet length'); } this._decipherInstance = createDecipheriv( this._decipherSSLName, this._decipherKey, this._decipherIV ); this._decipherInstance.setAutoPadding(false); this._decipherInstance.setAAD(intToBytes(this._len)); } // Read padding length, payload, and padding if (this._pktLen < this._len) { if (p >= dataLen) return; const nb = Math.min(this._len - this._pktLen, dataLen - p); let decrypted; if (p !== 0 || nb !== dataLen) { decrypted = this._decipherInstance.update( new Uint8Array(data.buffer, data.byteOffset + p, nb) ); } else { decrypted = this._decipherInstance.update(data); } if (decrypted.length) { if (nb === this._len) { this._packet = decrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(decrypted, this._packetPos); } this._packetPos += decrypted.length; } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read authentication tag { const nb = Math.min(16 - this._tagPos, dataLen - p); if (p !== 0 || nb !== dataLen) { this._tag.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._tagPos ); } else { this._tag.set(data, this._tagPos); } p += nb; this._tagPos += nb; if (this._tagPos < 16) return; } { // Verify authentication tag this._decipherInstance.setAuthTag(this._tag); const decrypted = this._decipherInstance.final(); // XXX: this should never output any data since stream ciphers always // return data from .update() and block ciphers must end on a multiple // of the block length, which would have caused an exception to be // thrown if the total input was not... if (decrypted.length) { if (this._packet) this._packet.set(decrypted, this._packetPos); else this._packet = decrypted; } } const payload = (!this._packet ? EMPTY_BUFFER : new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1)); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; ivIncrement(this._decipherIV); this._len = 0; this._lenBytes = 0; this._packet = null; this._packetPos = 0; this._pktLen = 0; this._tagPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class AESGCMDecipherBinding { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, dec.decipherKey, dec.decipherIV); this._len = 0; this._lenBytes = 0; this._packet = null; this._pktLen = 0; this._tag = Buffer.allocUnsafe(16); this._tagPos = 0; } free() {} decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read packet length (unencrypted, but AAD) if (this._lenBytes < 4) { let nb = Math.min(4 - this._lenBytes, dataLen - p); this._lenBytes += nb; while (nb--) this._len = (this._len << 8) + data[p++]; if (this._lenBytes < 4) return; if ((this._len + 20) > MAX_PACKET_SIZE || this._len < 16 || (this._len & 15) !== 0) { throw new Error(`Bad packet length: ${this._len}`); } } // Read padding length, payload, and padding if (this._pktLen < this._len) { if (p >= dataLen) return; const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (nb === this._len) { this._packet = encrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(encrypted, this._pktLen); } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read authentication tag { const nb = Math.min(16 - this._tagPos, dataLen - p); if (p !== 0 || nb !== dataLen) { this._tag.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._tagPos ); } else { this._tag.set(data, this._tagPos); } p += nb; this._tagPos += nb; if (this._tagPos < 16) return; } this._instance.decrypt(this._packet, this._len, this._tag); const payload = new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._len = 0; this._lenBytes = 0; this._packet = null; this._pktLen = 0; this._tagPos = 0; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } // TODO: test incremental .update()s vs. copying to _packet and doing a single // .update() after entire packet read -- a single .update() would allow // verifying MAC before decrypting for ETM MACs class GenericDecipherNative { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, dec.decipherKey, dec.decipherIV); this._decipherInstance.setAutoPadding(false); this._block = Buffer.allocUnsafe( dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen ); this._blockSize = dec.decipherInfo.blockLen; this._blockPos = 0; this._len = 0; this._packet = null; this._packetPos = 0; this._pktLen = 0; this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); this._macPos = 0; this._macSSLName = dec.macInfo.sslName; this._macKey = dec.macKey; this._macActualLen = dec.macInfo.actualLen; this._macETM = dec.macInfo.isETM; this._macInstance = null; const discardLen = dec.decipherInfo.discardLen; if (discardLen) { let discard = DISCARD_CACHE.get(discardLen); if (discard === undefined) { discard = Buffer.alloc(discardLen); DISCARD_CACHE.set(discardLen, discard); } this._decipherInstance.update(discard); } } free() {} decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read first encrypted block if (this._blockPos < this._block.length) { const nb = Math.min(this._block.length - this._blockPos, dataLen - p); if (p !== 0 || nb !== dataLen || nb < data.length) { this._block.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._blockPos ); } else { this._block.set(data, this._blockPos); } p += nb; this._blockPos += nb; if (this._blockPos < this._block.length) return; let decrypted; let need; if (this._macETM) { this._len = need = readUInt32BE(this._block, 0); } else { // Decrypt first block to get packet length decrypted = this._decipherInstance.update(this._block); this._len = readUInt32BE(decrypted, 0); need = 4 + this._len - this._blockSize; } if (this._len > MAX_PACKET_SIZE || this._len < 5 || (need & (this._blockSize - 1)) !== 0) { throw new Error('Bad packet length'); } // Create MAC up front to calculate in parallel with decryption this._macInstance = createHmac(this._macSSLName, this._macKey); writeUInt32BE(BUF_INT, this.inSeqno, 0); this._macInstance.update(BUF_INT); if (this._macETM) { this._macInstance.update(this._block); } else { this._macInstance.update(new Uint8Array(decrypted.buffer, decrypted.byteOffset, 4)); this._pktLen = decrypted.length - 4; this._packetPos = this._pktLen; this._packet = Buffer.allocUnsafe(this._len); this._packet.set( new Uint8Array(decrypted.buffer, decrypted.byteOffset + 4, this._packetPos), 0 ); } if (p >= dataLen) return; } // Read padding length, payload, and padding if (this._pktLen < this._len) { const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (this._macETM) this._macInstance.update(encrypted); const decrypted = this._decipherInstance.update(encrypted); if (decrypted.length) { if (nb === this._len) { this._packet = decrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(decrypted, this._packetPos); } this._packetPos += decrypted.length; } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read MAC { const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); if (p !== 0 || nb !== dataLen) { this._mac.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._macPos ); } else { this._mac.set(data, this._macPos); } p += nb; this._macPos += nb; if (this._macPos < this._macActualLen) return; } // Verify MAC if (!this._macETM) this._macInstance.update(this._packet); let calculated = this._macInstance.digest(); if (this._macActualLen < calculated.length) { calculated = new Uint8Array(calculated.buffer, calculated.byteOffset, this._macActualLen); } if (!timingSafeEquals(calculated, this._mac)) throw new Error('Invalid MAC'); const payload = new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._blockPos = 0; this._len = 0; this._packet = null; this._packetPos = 0; this._pktLen = 0; this._macPos = 0; this._macInstance = null; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } class GenericDecipherBinding { constructor(config) { const dec = config.inbound; this.inSeqno = dec.seqno; this._onPayload = dec.onPayload; this._instance = new GenericDecipher(dec.decipherInfo.sslName, dec.decipherKey, dec.decipherIV, dec.macInfo.sslName, dec.macKey, dec.macInfo.isETM, dec.macInfo.actualLen); this._block = Buffer.allocUnsafe( dec.macInfo.isETM || dec.decipherInfo.stream ? 4 : dec.decipherInfo.blockLen ); this._blockPos = 0; this._len = 0; this._packet = null; this._pktLen = 0; this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); this._macPos = 0; this._macActualLen = dec.macInfo.actualLen; this._macETM = dec.macInfo.isETM; } free() { this._instance.free(); } decrypt(data, p, dataLen) { // `data` === encrypted data while (p < dataLen) { // Read first encrypted block if (this._blockPos < this._block.length) { const nb = Math.min(this._block.length - this._blockPos, dataLen - p); if (p !== 0 || nb !== dataLen || nb < data.length) { this._block.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._blockPos ); } else { this._block.set(data, this._blockPos); } p += nb; this._blockPos += nb; if (this._blockPos < this._block.length) return; let need; if (this._macETM) { this._len = need = readUInt32BE(this._block, 0); } else { // Decrypt first block to get packet length this._instance.decryptBlock(this._block); this._len = readUInt32BE(this._block, 0); need = 4 + this._len - this._block.length; } if (this._len > MAX_PACKET_SIZE || this._len < 5 || (need & (this._block.length - 1)) !== 0) { throw new Error('Bad packet length'); } if (!this._macETM) { this._pktLen = (this._block.length - 4); if (this._pktLen) { this._packet = Buffer.allocUnsafe(this._len); this._packet.set( new Uint8Array(this._block.buffer, this._block.byteOffset + 4, this._pktLen), 0 ); } } if (p >= dataLen) return; } // Read padding length, payload, and padding if (this._pktLen < this._len) { const nb = Math.min(this._len - this._pktLen, dataLen - p); let encrypted; if (p !== 0 || nb !== dataLen) encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); else encrypted = data; if (nb === this._len) { this._packet = encrypted; } else { if (!this._packet) this._packet = Buffer.allocUnsafe(this._len); this._packet.set(encrypted, this._pktLen); } p += nb; this._pktLen += nb; if (this._pktLen < this._len || p >= dataLen) return; } // Read MAC { const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); if (p !== 0 || nb !== dataLen) { this._mac.set( new Uint8Array(data.buffer, data.byteOffset + p, nb), this._macPos ); } else { this._mac.set(data, this._macPos); } p += nb; this._macPos += nb; if (this._macPos < this._macActualLen) return; } // Decrypt and verify MAC this._instance.decrypt(this._packet, this.inSeqno, this._block, this._mac); const payload = new FastBuffer(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1); // Prepare for next packet this.inSeqno = (this.inSeqno + 1) >>> 0; this._blockPos = 0; this._len = 0; this._packet = null; this._pktLen = 0; this._macPos = 0; this._macInstance = null; { const ret = this._onPayload(payload); if (ret !== undefined) return (ret === false ? p : ret); } } } } // Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV function ivIncrement(iv) { // eslint-disable-next-line no-unused-expressions ++iv[11] >>> 8 && ++iv[10] >>> 8 && ++iv[9] >>> 8 && ++iv[8] >>> 8 && ++iv[7] >>> 8 && ++iv[6] >>> 8 && ++iv[5] >>> 8 && ++iv[4] >>> 8; } const intToBytes = (() => { const ret = Buffer.alloc(4); return (n) => { ret[0] = (n >>> 24); ret[1] = (n >>> 16); ret[2] = (n >>> 8); ret[3] = n; return ret; }; })(); function timingSafeEquals(a, b) { if (a.length !== b.length) { timingSafeEqual(a, a); return false; } return timingSafeEqual(a, b); } function createCipher(config) { if (typeof config !== 'object' || config === null) throw new Error('Invalid config'); if (typeof config.outbound !== 'object' || config.outbound === null) throw new Error('Invalid outbound'); const outbound = config.outbound; if (typeof outbound.onWrite !== 'function') throw new Error('Invalid outbound.onWrite'); if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) throw new Error('Invalid outbound.cipherInfo'); if (!Buffer.isBuffer(outbound.cipherKey) || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { throw new Error('Invalid outbound.cipherKey'); } if (outbound.cipherInfo.ivLen && (!Buffer.isBuffer(outbound.cipherIV) || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { throw new Error('Invalid outbound.cipherIV'); } if (typeof outbound.seqno !== 'number' || outbound.seqno < 0 || outbound.seqno > MAX_SEQNO) { throw new Error('Invalid outbound.seqno'); } const forceNative = !!outbound.forceNative; switch (outbound.cipherInfo.sslName) { case 'aes-128-gcm': case 'aes-256-gcm': return (AESGCMCipher && !forceNative ? new AESGCMCipherBinding(config) : new AESGCMCipherNative(config)); case 'chacha20': return (ChaChaPolyCipher && !forceNative ? new ChaChaPolyCipherBinding(config) : new ChaChaPolyCipherNative(config)); default: { if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) throw new Error('Invalid outbound.macInfo'); if (!Buffer.isBuffer(outbound.macKey) || outbound.macKey.length !== outbound.macInfo.len) { throw new Error('Invalid outbound.macKey'); } return (GenericCipher && !forceNative ? new GenericCipherBinding(config) : new GenericCipherNative(config)); } } } function createDecipher(config) { if (typeof config !== 'object' || config === null) throw new Error('Invalid config'); if (typeof config.inbound !== 'object' || config.inbound === null) throw new Error('Invalid inbound'); const inbound = config.inbound; if (typeof inbound.onPayload !== 'function') throw new Error('Invalid inbound.onPayload'); if (typeof inbound.decipherInfo !== 'object' || inbound.decipherInfo === null) { throw new Error('Invalid inbound.decipherInfo'); } if (!Buffer.isBuffer(inbound.decipherKey) || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { throw new Error('Invalid inbound.decipherKey'); } if (inbound.decipherInfo.ivLen && (!Buffer.isBuffer(inbound.decipherIV) || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { throw new Error('Invalid inbound.decipherIV'); } if (typeof inbound.seqno !== 'number' || inbound.seqno < 0 || inbound.seqno > MAX_SEQNO) { throw new Error('Invalid inbound.seqno'); } const forceNative = !!inbound.forceNative; switch (inbound.decipherInfo.sslName) { case 'aes-128-gcm': case 'aes-256-gcm': return (AESGCMDecipher && !forceNative ? new AESGCMDecipherBinding(config) : new AESGCMDecipherNative(config)); case 'chacha20': return (ChaChaPolyDecipher && !forceNative ? new ChaChaPolyDecipherBinding(config) : new ChaChaPolyDecipherNative(config)); default: { if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) throw new Error('Invalid inbound.macInfo'); if (!Buffer.isBuffer(inbound.macKey) || inbound.macKey.length !== inbound.macInfo.len) { throw new Error('Invalid inbound.macKey'); } return (GenericDecipher && !forceNative ? new GenericDecipherBinding(config) : new GenericDecipherNative(config)); } } } module.exports = { CIPHER_INFO, MAC_INFO, bindingAvailable: !!binding, init: (() => { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { try { POLY1305_WASM_MODULE = await __nccwpck_require__(7830)(); POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); poly1305_auth = POLY1305_WASM_MODULE.cwrap( 'poly1305_auth', null, ['number', 'array', 'number', 'array', 'number', 'array'] ); } catch (ex) { return reject(ex); } resolve(); }); })(), NullCipher, createCipher, NullDecipher, createDecipher, }; /***/ }), /***/ 7830: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var createPoly1305 = (function() { var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; return ( function(createPoly1305) { createPoly1305 = createPoly1305 || {}; var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; if(z)B=y?(__nccwpck_require__(6928).dirname)(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=__nccwpck_require__(9896));G||(G=__nccwpck_require__(6928));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=__nccwpck_require__(9896));G||(G=__nccwpck_require__(6928));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= 0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38A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W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; (function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 { "use strict"; const MESSAGE_HANDLERS = new Array(256); [ (__nccwpck_require__(4637).HANDLERS), __nccwpck_require__(9964), ].forEach((handlers) => { // eslint-disable-next-line prefer-const for (let [type, handler] of Object.entries(handlers)) { type = +type; if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) MESSAGE_HANDLERS[type] = handler; } }); module.exports = MESSAGE_HANDLERS; /***/ }), /***/ 9964: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { bufferSlice, bufferParser, doFatalError, sigSSHToASN1, writeUInt32BE, } = __nccwpck_require__(2184); const { CHANNEL_OPEN_FAILURE, COMPAT, MESSAGE, TERMINAL_MODE, } = __nccwpck_require__(4020); const { parseKey, } = __nccwpck_require__(1789); const TERMINAL_MODE_BY_VALUE = Array.from(Object.entries(TERMINAL_MODE)) .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); module.exports = { // Transport layer protocol ================================================== [MESSAGE.DISCONNECT]: (self, payload) => { /* byte SSH_MSG_DISCONNECT uint32 reason code string description in ISO-10646 UTF-8 encoding string language tag */ bufferParser.init(payload, 1); const reason = bufferParser.readUInt32BE(); const desc = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed DISCONNECT packet' ); } self._debug && self._debug( `Inbound: Received DISCONNECT (${reason}, "${desc}")` ); const handler = self._handlers.DISCONNECT; handler && handler(self, reason, desc); }, [MESSAGE.IGNORE]: (self, payload) => { /* byte SSH_MSG_IGNORE string data */ self._debug && self._debug('Inbound: Received IGNORE'); }, [MESSAGE.UNIMPLEMENTED]: (self, payload) => { /* byte SSH_MSG_UNIMPLEMENTED uint32 packet sequence number of rejected message */ bufferParser.init(payload, 1); const seqno = bufferParser.readUInt32BE(); bufferParser.clear(); if (seqno === undefined) { return doFatalError( self, 'Inbound: Malformed UNIMPLEMENTED packet' ); } self._debug && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); }, [MESSAGE.DEBUG]: (self, payload) => { /* byte SSH_MSG_DEBUG boolean always_display string message in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ bufferParser.init(payload, 1); const display = bufferParser.readBool(); const msg = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed DEBUG packet' ); } self._debug && self._debug('Inbound: Received DEBUG'); const handler = self._handlers.DEBUG; handler && handler(self, display, msg); }, [MESSAGE.SERVICE_REQUEST]: (self, payload) => { /* byte SSH_MSG_SERVICE_REQUEST string service name */ bufferParser.init(payload, 1); const name = bufferParser.readString(true); bufferParser.clear(); if (name === undefined) { return doFatalError( self, 'Inbound: Malformed SERVICE_REQUEST packet' ); } self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); const handler = self._handlers.SERVICE_REQUEST; handler && handler(self, name); }, [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { // S->C /* byte SSH_MSG_SERVICE_ACCEPT string service name */ bufferParser.init(payload, 1); const name = bufferParser.readString(true); bufferParser.clear(); if (name === undefined) { return doFatalError( self, 'Inbound: Malformed SERVICE_ACCEPT packet' ); } self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); const handler = self._handlers.SERVICE_ACCEPT; handler && handler(self, name); }, [MESSAGE.EXT_INFO]: (self, payload) => { /* byte SSH_MSG_EXT_INFO uint32 nr-extensions repeat the following 2 fields "nr-extensions" times: string extension-name string extension-value (binary) */ bufferParser.init(payload, 1); const numExts = bufferParser.readUInt32BE(); let exts; if (numExts !== undefined) { exts = []; for (let i = 0; i < numExts; ++i) { const name = bufferParser.readString(true); const data = bufferParser.readString(); if (data !== undefined) { switch (name) { case 'server-sig-algs': { const algs = data.latin1Slice(0, data.length).split(','); exts.push({ name, algs }); continue; } default: continue; } } // Malformed exts = undefined; break; } } bufferParser.clear(); if (exts === undefined) return doFatalError(self, 'Inbound: Malformed EXT_INFO packet'); self._debug && self._debug('Inbound: Received EXT_INFO'); const handler = self._handlers.EXT_INFO; handler && handler(self, exts); }, // User auth protocol -- generic ============================================= [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { /* byte SSH_MSG_USERAUTH_REQUEST string user name in ISO-10646 UTF-8 encoding [RFC3629] string service name in US-ASCII string method name in US-ASCII .... method specific fields */ bufferParser.init(payload, 1); const user = bufferParser.readString(true); const service = bufferParser.readString(true); const method = bufferParser.readString(true); let methodData; let methodDesc; switch (method) { case 'none': methodData = null; break; case 'password': { /* boolean string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] [string new password] */ const isChange = bufferParser.readBool(); if (isChange !== undefined) { methodData = bufferParser.readString(true); if (methodData !== undefined && isChange) { const newPassword = bufferParser.readString(true); if (newPassword !== undefined) methodData = { oldPassword: methodData, newPassword }; else methodData = undefined; } } break; } case 'publickey': { /* boolean string public key algorithm name string public key blob [string signature] */ const hasSig = bufferParser.readBool(); if (hasSig !== undefined) { const keyAlgo = bufferParser.readString(true); let realKeyAlgo = keyAlgo; const key = bufferParser.readString(); let hashAlgo; switch (keyAlgo) { case 'rsa-sha2-256': realKeyAlgo = 'ssh-rsa'; hashAlgo = 'sha256'; break; case 'rsa-sha2-512': realKeyAlgo = 'ssh-rsa'; hashAlgo = 'sha512'; break; } if (hasSig) { const blobEnd = bufferParser.pos(); let signature = bufferParser.readString(); if (signature !== undefined) { if (signature.length > (4 + keyAlgo.length + 4) && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { // Skip algoLen + algo + sigLen signature = bufferSlice(signature, 4 + keyAlgo.length + 4); } signature = sigSSHToASN1(signature, realKeyAlgo); if (signature) { const sessionID = self._kex.sessionID; const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); writeUInt32BE(blob, sessionID.length, 0); blob.set(sessionID, 4); blob.set( new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), 4 + sessionID.length ); methodData = { keyAlgo: realKeyAlgo, key, signature, blob, hashAlgo, }; } } } else { methodData = { keyAlgo: realKeyAlgo, key, hashAlgo }; methodDesc = 'publickey -- check'; } } break; } case 'hostbased': { /* string public key algorithm for host key string public host key and certificates for client host string client host name expressed as the FQDN in US-ASCII string user name on the client host in ISO-10646 UTF-8 encoding [RFC3629] string signature */ const keyAlgo = bufferParser.readString(true); let realKeyAlgo = keyAlgo; const key = bufferParser.readString(); const localHostname = bufferParser.readString(true); const localUsername = bufferParser.readString(true); let hashAlgo; switch (keyAlgo) { case 'rsa-sha2-256': realKeyAlgo = 'ssh-rsa'; hashAlgo = 'sha256'; break; case 'rsa-sha2-512': realKeyAlgo = 'ssh-rsa'; hashAlgo = 'sha512'; break; } const blobEnd = bufferParser.pos(); let signature = bufferParser.readString(); if (signature !== undefined) { if (signature.length > (4 + keyAlgo.length + 4) && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { // Skip algoLen + algo + sigLen signature = bufferSlice(signature, 4 + keyAlgo.length + 4); } signature = sigSSHToASN1(signature, realKeyAlgo); if (signature !== undefined) { const sessionID = self._kex.sessionID; const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); writeUInt32BE(blob, sessionID.length, 0); blob.set(sessionID, 4); blob.set( new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), 4 + sessionID.length ); methodData = { keyAlgo: realKeyAlgo, key, signature, blob, localHostname, localUsername, hashAlgo }; } } break; } case 'keyboard-interactive': /* string language tag (as defined in [RFC-3066]) string submethods (ISO-10646 UTF-8) */ // Skip/ignore language field -- it's deprecated in RFC 4256 bufferParser.skipString(); methodData = bufferParser.readList(); break; default: if (method !== undefined) methodData = bufferParser.readRaw(); } bufferParser.clear(); if (methodData === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_REQUEST packet' ); } if (methodDesc === undefined) methodDesc = method; self._authsQueue.push(method); self._debug && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); const handler = self._handlers.USERAUTH_REQUEST; handler && handler(self, user, service, method, methodData); }, [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { // S->C /* byte SSH_MSG_USERAUTH_FAILURE name-list authentications that can continue boolean partial success */ bufferParser.init(payload, 1); const authMethods = bufferParser.readList(); const partialSuccess = bufferParser.readBool(); bufferParser.clear(); if (partialSuccess === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_FAILURE packet' ); } self._debug && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); self._authsQueue.shift(); const handler = self._handlers.USERAUTH_FAILURE; handler && handler(self, authMethods, partialSuccess); }, [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { // S->C /* byte SSH_MSG_USERAUTH_SUCCESS */ self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); self._authsQueue.shift(); const handler = self._handlers.USERAUTH_SUCCESS; handler && handler(self); }, [MESSAGE.USERAUTH_BANNER]: (self, payload) => { // S->C /* byte SSH_MSG_USERAUTH_BANNER string message in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ bufferParser.init(payload, 1); const msg = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_BANNER packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); const handler = self._handlers.USERAUTH_BANNER; handler && handler(self, msg); }, // User auth protocol -- method-specific ===================================== 60: (self, payload) => { if (!self._authsQueue.length) { self._debug && self._debug('Inbound: Received payload type 60 without auth'); return; } switch (self._authsQueue[0]) { case 'password': { // S->C /* byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ string prompt in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ bufferParser.init(payload, 1); const prompt = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; handler && handler(self, prompt); break; } case 'publickey': { // S->C /* byte SSH_MSG_USERAUTH_PK_OK string public key algorithm name from the request string public key blob from the request */ bufferParser.init(payload, 1); const keyAlgo = bufferParser.readString(true); const key = bufferParser.readString(); bufferParser.clear(); if (key === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_PK_OK packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); self._authsQueue.shift(); const handler = self._handlers.USERAUTH_PK_OK; handler && handler(self, keyAlgo, key); break; } case 'keyboard-interactive': { // S->C /* byte SSH_MSG_USERAUTH_INFO_REQUEST string name (ISO-10646 UTF-8) string instruction (ISO-10646 UTF-8) string language tag (as defined in [RFC-3066]) int num-prompts string prompt[1] (ISO-10646 UTF-8) boolean echo[1] ... string prompt[num-prompts] (ISO-10646 UTF-8) boolean echo[num-prompts] */ bufferParser.init(payload, 1); const name = bufferParser.readString(true); const instructions = bufferParser.readString(true); bufferParser.readString(); // skip lang const numPrompts = bufferParser.readUInt32BE(); let prompts; if (numPrompts !== undefined) { prompts = new Array(numPrompts); let i; for (i = 0; i < numPrompts; ++i) { const prompt = bufferParser.readString(true); const echo = bufferParser.readBool(); if (echo === undefined) break; prompts[i] = { prompt, echo }; } if (i !== numPrompts) prompts = undefined; } bufferParser.clear(); if (prompts === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); const handler = self._handlers.USERAUTH_INFO_REQUEST; handler && handler(self, name, instructions, prompts); break; } default: self._debug && self._debug('Inbound: Received unexpected payload type 60'); } }, 61: (self, payload) => { if (!self._authsQueue.length) { self._debug && self._debug('Inbound: Received payload type 61 without auth'); return; } /* byte SSH_MSG_USERAUTH_INFO_RESPONSE int num-responses string response[1] (ISO-10646 UTF-8) ... string response[num-responses] (ISO-10646 UTF-8) */ if (self._authsQueue[0] !== 'keyboard-interactive') { return doFatalError( self, 'Inbound: Received unexpected payload type 61' ); } bufferParser.init(payload, 1); const numResponses = bufferParser.readUInt32BE(); let responses; if (numResponses !== undefined) { responses = new Array(numResponses); let i; for (i = 0; i < numResponses; ++i) { const response = bufferParser.readString(true); if (response === undefined) break; responses[i] = response; } if (i !== numResponses) responses = undefined; } bufferParser.clear(); if (responses === undefined) { return doFatalError( self, 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' ); } self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); const handler = self._handlers.USERAUTH_INFO_RESPONSE; handler && handler(self, responses); }, // Connection protocol -- generic ============================================ [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { /* byte SSH_MSG_GLOBAL_REQUEST string request name in US-ASCII only boolean want reply .... request-specific data follows */ bufferParser.init(payload, 1); const name = bufferParser.readString(true); const wantReply = bufferParser.readBool(); let data; if (wantReply !== undefined) { switch (name) { case 'tcpip-forward': case 'cancel-tcpip-forward': { /* string address to bind (e.g., "0.0.0.0") uint32 port number to bind */ const bindAddr = bufferParser.readString(true); const bindPort = bufferParser.readUInt32BE(); if (bindPort !== undefined) data = { bindAddr, bindPort }; break; } case 'streamlocal-forward@openssh.com': case 'cancel-streamlocal-forward@openssh.com': { /* string socket path */ const socketPath = bufferParser.readString(true); if (socketPath !== undefined) data = { socketPath }; break; } case 'no-more-sessions@openssh.com': data = null; break; case 'hostkeys-00@openssh.com': { data = []; while (bufferParser.avail() > 0) { const keyRaw = bufferParser.readString(); if (keyRaw === undefined) { data = undefined; break; } const key = parseKey(keyRaw); if (!(key instanceof Error)) data.push(key); } break; } default: data = bufferParser.readRaw(); } } bufferParser.clear(); if (data === undefined) { return doFatalError( self, 'Inbound: Malformed GLOBAL_REQUEST packet' ); } self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); const handler = self._handlers.GLOBAL_REQUEST; if (handler) handler(self, name, wantReply, data); else self.requestFailure(); // Auto reject }, [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { /* byte SSH_MSG_REQUEST_SUCCESS .... response specific data */ const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); self._debug && self._debug('Inbound: REQUEST_SUCCESS'); const handler = self._handlers.REQUEST_SUCCESS; handler && handler(self, data); }, [MESSAGE.REQUEST_FAILURE]: (self, payload) => { /* byte SSH_MSG_REQUEST_FAILURE */ self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); const handler = self._handlers.REQUEST_FAILURE; handler && handler(self); }, // Connection protocol -- channel-related ==================================== [MESSAGE.CHANNEL_OPEN]: (self, payload) => { /* byte SSH_MSG_CHANNEL_OPEN string channel type in US-ASCII only uint32 sender channel uint32 initial window size uint32 maximum packet size .... channel type specific data follows */ bufferParser.init(payload, 1); const type = bufferParser.readString(true); const sender = bufferParser.readUInt32BE(); const window = bufferParser.readUInt32BE(); const packetSize = bufferParser.readUInt32BE(); let channelInfo; switch (type) { case 'forwarded-tcpip': // S->C case 'direct-tcpip': { // C->S /* string address that was connected / host to connect uint32 port that was connected / port to connect string originator IP address uint32 originator port */ const destIP = bufferParser.readString(true); const destPort = bufferParser.readUInt32BE(); const srcIP = bufferParser.readString(true); const srcPort = bufferParser.readUInt32BE(); if (srcPort !== undefined) { channelInfo = { type, sender, window, packetSize, data: { destIP, destPort, srcIP, srcPort } }; } break; } case 'forwarded-streamlocal@openssh.com': // S->C case 'direct-streamlocal@openssh.com': { // C->S /* string socket path string reserved for future use (direct-streamlocal@openssh.com additionally has:) uint32 reserved */ const socketPath = bufferParser.readString(true); if (socketPath !== undefined) { channelInfo = { type, sender, window, packetSize, data: { socketPath } }; } break; } case 'x11': { // S->C /* string originator address (e.g., "192.168.7.38") uint32 originator port */ const srcIP = bufferParser.readString(true); const srcPort = bufferParser.readUInt32BE(); if (srcPort !== undefined) { channelInfo = { type, sender, window, packetSize, data: { srcIP, srcPort } }; } break; } default: // Includes: // 'session' (C->S) // 'auth-agent@openssh.com' (S->C) channelInfo = { type, sender, window, packetSize, data: {} }; } bufferParser.clear(); if (channelInfo === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_OPEN packet' ); } self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); const handler = self._handlers.CHANNEL_OPEN; if (handler) { handler(self, channelInfo); } else { self.channelOpenFail( channelInfo.sender, CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, '', '' ); } }, [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { /* byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION uint32 recipient channel uint32 sender channel uint32 initial window size uint32 maximum packet size .... channel type specific data follows */ // "The 'recipient channel' is the channel number given in the // original open request, and 'sender channel' is the channel number // allocated by the other side." bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const sender = bufferParser.readUInt32BE(); const window = bufferParser.readUInt32BE(); const packetSize = bufferParser.readUInt32BE(); const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); bufferParser.clear(); if (packetSize === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' ); } self._debug && self._debug( `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` ); const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; if (handler) handler(self, { recipient, sender, window, packetSize, data }); }, [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { /* byte SSH_MSG_CHANNEL_OPEN_FAILURE uint32 recipient channel uint32 reason code string description in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const reason = bufferParser.readUInt32BE(); const description = bufferParser.readString(true); const lang = bufferParser.readString(); bufferParser.clear(); if (lang === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' ); } self._debug && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); const handler = self._handlers.CHANNEL_OPEN_FAILURE; handler && handler(self, recipient, reason, description); }, [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { /* byte SSH_MSG_CHANNEL_WINDOW_ADJUST uint32 recipient channel uint32 bytes to add */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const bytesToAdd = bufferParser.readUInt32BE(); bufferParser.clear(); if (bytesToAdd === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' ); } self._debug && self._debug( `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` ); const handler = self._handlers.CHANNEL_WINDOW_ADJUST; handler && handler(self, recipient, bytesToAdd); }, [MESSAGE.CHANNEL_DATA]: (self, payload) => { /* byte SSH_MSG_CHANNEL_DATA uint32 recipient channel string data */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const data = bufferParser.readString(); bufferParser.clear(); if (data === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_DATA packet' ); } self._debug && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); const handler = self._handlers.CHANNEL_DATA; handler && handler(self, recipient, data); }, [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { /* byte SSH_MSG_CHANNEL_EXTENDED_DATA uint32 recipient channel uint32 data_type_code string data */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const type = bufferParser.readUInt32BE(); const data = bufferParser.readString(); bufferParser.clear(); if (data === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' ); } self._debug && self._debug( `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` ); const handler = self._handlers.CHANNEL_EXTENDED_DATA; handler && handler(self, recipient, data, type); }, [MESSAGE.CHANNEL_EOF]: (self, payload) => { /* byte SSH_MSG_CHANNEL_EOF uint32 recipient channel */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); bufferParser.clear(); if (recipient === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_EOF packet' ); } self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); const handler = self._handlers.CHANNEL_EOF; handler && handler(self, recipient); }, [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { /* byte SSH_MSG_CHANNEL_CLOSE uint32 recipient channel */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); bufferParser.clear(); if (recipient === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_CLOSE packet' ); } self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); const handler = self._handlers.CHANNEL_CLOSE; handler && handler(self, recipient); }, [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string request type in US-ASCII characters only boolean want reply .... type-specific data follows */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); const type = bufferParser.readString(true); const wantReply = bufferParser.readBool(); let data; if (wantReply !== undefined) { switch (type) { case 'exit-status': // S->C /* uint32 exit_status */ data = bufferParser.readUInt32BE(); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'exit-signal': { // S->C /* string signal name (without the "SIG" prefix) boolean core dumped string error message in ISO-10646 UTF-8 encoding string language tag */ let signal; let coreDumped; if (self._compatFlags & COMPAT.OLD_EXIT) { /* Instead of `signal name` and `core dumped`, we have just: uint32 signal number */ const num = bufferParser.readUInt32BE(); switch (num) { case 1: signal = 'HUP'; break; case 2: signal = 'INT'; break; case 3: signal = 'QUIT'; break; case 6: signal = 'ABRT'; break; case 9: signal = 'KILL'; break; case 14: signal = 'ALRM'; break; case 15: signal = 'TERM'; break; default: if (num !== undefined) { // Unknown or OS-specific signal = `UNKNOWN (${num})`; } } coreDumped = false; } else { signal = bufferParser.readString(true); coreDumped = bufferParser.readBool(); if (coreDumped === undefined) signal = undefined; } const errorMessage = bufferParser.readString(true); if (bufferParser.skipString() !== undefined) data = { signal, coreDumped, errorMessage }; self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` ); break; } case 'pty-req': { // C->S /* string TERM environment variable value (e.g., vt100) uint32 terminal width, characters (e.g., 80) uint32 terminal height, rows (e.g., 24) uint32 terminal width, pixels (e.g., 640) uint32 terminal height, pixels (e.g., 480) string encoded terminal modes */ const term = bufferParser.readString(true); const cols = bufferParser.readUInt32BE(); const rows = bufferParser.readUInt32BE(); const width = bufferParser.readUInt32BE(); const height = bufferParser.readUInt32BE(); const modesBinary = bufferParser.readString(); if (modesBinary !== undefined) { bufferParser.init(modesBinary, 1); let modes = {}; while (bufferParser.avail()) { const opcode = bufferParser.readByte(); if (opcode === TERMINAL_MODE.TTY_OP_END) break; const name = TERMINAL_MODE_BY_VALUE[opcode]; const value = bufferParser.readUInt32BE(); if (opcode === undefined || name === undefined || value === undefined) { modes = undefined; break; } modes[name] = value; } if (modes !== undefined) data = { term, cols, rows, width, height, modes }; } self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; } case 'window-change': { // C->S /* uint32 terminal width, columns uint32 terminal height, rows uint32 terminal width, pixels uint32 terminal height, pixels */ const cols = bufferParser.readUInt32BE(); const rows = bufferParser.readUInt32BE(); const width = bufferParser.readUInt32BE(); const height = bufferParser.readUInt32BE(); if (height !== undefined) data = { cols, rows, width, height }; self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; } case 'x11-req': { // C->S /* boolean single connection string x11 authentication protocol string x11 authentication cookie uint32 x11 screen number */ const single = bufferParser.readBool(); const protocol = bufferParser.readString(true); const cookie = bufferParser.readString(); const screen = bufferParser.readUInt32BE(); if (screen !== undefined) data = { single, protocol, cookie, screen }; self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; } case 'env': { // C->S /* string variable name string variable value */ const name = bufferParser.readString(true); const value = bufferParser.readString(true); if (value !== undefined) data = { name, value }; if (self._debug) { self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` + `${name}=${value})` ); } break; } case 'shell': // C->S data = null; // No extra data self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; case 'exec': // C->S /* string command */ data = bufferParser.readString(true); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'subsystem': // C->S /* string subsystem name */ data = bufferParser.readString(true); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'signal': // C->S /* string signal name (without the "SIG" prefix) */ data = bufferParser.readString(true); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'xon-xoff': // C->S /* boolean client can do */ data = bufferParser.readBool(); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` ); break; case 'auth-agent-req@openssh.com': // C-S data = null; // No extra data self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); break; default: data = (bufferParser.avail() ? bufferParser.readRaw() : null); self._debug && self._debug( `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` ); } } bufferParser.clear(); if (data === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_REQUEST packet' ); } const handler = self._handlers.CHANNEL_REQUEST; handler && handler(self, recipient, type, wantReply, data); }, [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { /* byte SSH_MSG_CHANNEL_SUCCESS uint32 recipient channel */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); bufferParser.clear(); if (recipient === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_SUCCESS packet' ); } self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); const handler = self._handlers.CHANNEL_SUCCESS; handler && handler(self, recipient); }, [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { /* byte SSH_MSG_CHANNEL_FAILURE uint32 recipient channel */ bufferParser.init(payload, 1); const recipient = bufferParser.readUInt32BE(); bufferParser.clear(); if (recipient === undefined) { return doFatalError( self, 'Inbound: Malformed CHANNEL_FAILURE packet' ); } self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); const handler = self._handlers.CHANNEL_FAILURE; handler && handler(self, recipient); }, }; /***/ }), /***/ 4637: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { createDiffieHellman, createDiffieHellmanGroup, createECDH, createHash, createPublicKey, diffieHellman, generateKeyPairSync, randomFillSync, } = __nccwpck_require__(6982); const { Ber } = __nccwpck_require__(9837); const { COMPAT, curve25519Supported, DEFAULT_KEX, DEFAULT_SERVER_HOST_KEY, DEFAULT_CIPHER, DEFAULT_MAC, DEFAULT_COMPRESSION, DISCONNECT_REASON, MESSAGE, } = __nccwpck_require__(4020); const { CIPHER_INFO, createCipher, createDecipher, MAC_INFO, } = __nccwpck_require__(2888); const { parseDERKey } = __nccwpck_require__(1789); const { bufferFill, bufferParser, convertSignature, doFatalError, FastBuffer, sigSSHToASN1, writeUInt32BE, } = __nccwpck_require__(2184); const { PacketReader, PacketWriter, ZlibPacketReader, ZlibPacketWriter, } = __nccwpck_require__(4592); let MESSAGE_HANDLERS; const GEX_MIN_BITS = 2048; // RFC 8270 const GEX_MAX_BITS = 8192; // RFC 8270 const EMPTY_BUFFER = Buffer.alloc(0); // Client/Server function kexinit(self) { /* byte SSH_MSG_KEXINIT byte[16] cookie (random bytes) name-list kex_algorithms name-list server_host_key_algorithms name-list encryption_algorithms_client_to_server name-list encryption_algorithms_server_to_client name-list mac_algorithms_client_to_server name-list mac_algorithms_server_to_client name-list compression_algorithms_client_to_server name-list compression_algorithms_server_to_client name-list languages_client_to_server name-list languages_server_to_client boolean first_kex_packet_follows uint32 0 (reserved for future extension) */ let payload; if (self._compatFlags & COMPAT.BAD_DHGEX) { const entry = self._offer.lists.kex; let kex = entry.array; let found = false; for (let i = 0; i < kex.length; ++i) { if (kex[i].includes('group-exchange')) { if (!found) { found = true; // Copy array lazily kex = kex.slice(); } kex.splice(i--, 1); } } if (found) { let len = 1 + 16 + self._offer.totalSize + 1 + 4; const newKexBuf = Buffer.from(kex.join(',')); len -= (entry.buffer.length - newKexBuf.length); const all = self._offer.lists.all; const rest = new Uint8Array( all.buffer, all.byteOffset + 4 + entry.buffer.length, all.length - (4 + entry.buffer.length) ); payload = Buffer.allocUnsafe(len); writeUInt32BE(payload, newKexBuf.length, 17); payload.set(newKexBuf, 17 + 4); payload.set(rest, 17 + 4 + newKexBuf.length); } } if (payload === undefined) { payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); self._offer.copyAllTo(payload, 17); } self._debug && self._debug('Outbound: Sending KEXINIT'); payload[0] = MESSAGE.KEXINIT; randomFillSync(payload, 1, 16); // Zero-fill first_kex_packet_follows and reserved bytes bufferFill(payload, 0, payload.length - 5); self._kexinit = payload; // Needed to correct the starting position in allocated "packets" when packets // will be buffered due to active key exchange self._packetRW.write.allocStart = 0; // TODO: only create single buffer and set _kexinit as slice of packet instead { const p = self._packetRW.write.allocStartKEX; const packet = self._packetRW.write.alloc(payload.length, true); packet.set(payload, p); self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); } } function handleKexInit(self, payload) { /* byte SSH_MSG_KEXINIT byte[16] cookie (random bytes) name-list kex_algorithms name-list server_host_key_algorithms name-list encryption_algorithms_client_to_server name-list encryption_algorithms_server_to_client name-list mac_algorithms_client_to_server name-list mac_algorithms_server_to_client name-list compression_algorithms_client_to_server name-list compression_algorithms_server_to_client name-list languages_client_to_server name-list languages_server_to_client boolean first_kex_packet_follows uint32 0 (reserved for future extension) */ const init = { kex: undefined, serverHostKey: undefined, cs: { cipher: undefined, mac: undefined, compress: undefined, lang: undefined, }, sc: { cipher: undefined, mac: undefined, compress: undefined, lang: undefined, }, }; bufferParser.init(payload, 17); if ((init.kex = bufferParser.readList()) === undefined || (init.serverHostKey = bufferParser.readList()) === undefined || (init.cs.cipher = bufferParser.readList()) === undefined || (init.sc.cipher = bufferParser.readList()) === undefined || (init.cs.mac = bufferParser.readList()) === undefined || (init.sc.mac = bufferParser.readList()) === undefined || (init.cs.compress = bufferParser.readList()) === undefined || (init.sc.compress = bufferParser.readList()) === undefined || (init.cs.lang = bufferParser.readList()) === undefined || (init.sc.lang = bufferParser.readList()) === undefined) { bufferParser.clear(); return doFatalError( self, 'Received malformed KEXINIT', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } const pos = bufferParser.pos(); const firstFollows = (pos < payload.length && payload[pos] === 1); bufferParser.clear(); const local = self._offer; const remote = init; let localKex = local.lists.kex.array; if (self._compatFlags & COMPAT.BAD_DHGEX) { let found = false; for (let i = 0; i < localKex.length; ++i) { if (localKex[i].indexOf('group-exchange') !== -1) { if (!found) { found = true; // Copy array lazily localKex = localKex.slice(); } localKex.splice(i--, 1); } } } let clientList; let serverList; let i; const debug = self._debug; debug && debug('Inbound: Handshake in progress'); // Key exchange method ======================================================= debug && debug(`Handshake: (local) KEX method: ${localKex}`); debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); let remoteExtInfoEnabled; if (self._server) { serverList = localKex; clientList = remote.kex; remoteExtInfoEnabled = (clientList.indexOf('ext-info-c') !== -1); } else { serverList = remote.kex; clientList = localKex; remoteExtInfoEnabled = (serverList.indexOf('ext-info-s') !== -1); } if (self._strictMode === undefined) { if (self._server) { self._strictMode = (clientList.indexOf('kex-strict-c-v00@openssh.com') !== -1); } else { self._strictMode = (serverList.indexOf('kex-strict-s-v00@openssh.com') !== -1); } // Note: We check for seqno of 1 instead of 0 since we increment before // calling the packet handler if (self._strictMode) { debug && debug('Handshake: strict KEX mode enabled'); if (self._decipher.inSeqno !== 1) { if (debug) debug('Handshake: KEXINIT not first packet in strict KEX mode'); return doFatalError( self, 'Handshake failed: KEXINIT not first packet in strict KEX mode', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } } } // Check for agreeable key exchange algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: no matching key exchange algorithm'); return doFatalError( self, 'Handshake failed: no matching key exchange algorithm', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.kex = clientList[i]; debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { // Ignore next inbound packet, it was a wrong first guess at KEX algorithm self._skipNextInboundPacket = true; } // Server host key format ==================================================== const localSrvHostKey = local.lists.serverHostKey.array; debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); debug && debug( `Handshake: (remote) Host key format: ${remote.serverHostKey}` ); if (self._server) { serverList = localSrvHostKey; clientList = remote.serverHostKey; } else { serverList = remote.serverHostKey; clientList = localSrvHostKey; } // Check for agreeable server host key format for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching host key format'); return doFatalError( self, 'Handshake failed: no matching host key format', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.serverHostKey = clientList[i]; debug && debug(`Handshake: Host key format: ${clientList[i]}`); // Client->Server cipher ===================================================== const localCSCipher = local.lists.cs.cipher.array; debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); if (self._server) { serverList = localCSCipher; clientList = remote.cs.cipher; } else { serverList = remote.cs.cipher; clientList = localCSCipher; } // Check for agreeable client->server cipher for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching C->S cipher'); return doFatalError( self, 'Handshake failed: no matching C->S cipher', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.cs.cipher = clientList[i]; debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); // Server->Client cipher ===================================================== const localSCCipher = local.lists.sc.cipher.array; debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); if (self._server) { serverList = localSCCipher; clientList = remote.sc.cipher; } else { serverList = remote.sc.cipher; clientList = localSCCipher; } // Check for agreeable server->client cipher for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching S->C cipher'); return doFatalError( self, 'Handshake failed: no matching S->C cipher', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.sc.cipher = clientList[i]; debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); // Client->Server MAC ======================================================== const localCSMAC = local.lists.cs.mac.array; debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); if (CIPHER_INFO[init.cs.cipher].authLen > 0) { init.cs.mac = ''; debug && debug('Handshake: C->S MAC: '); } else { if (self._server) { serverList = localCSMAC; clientList = remote.cs.mac; } else { serverList = remote.cs.mac; clientList = localCSMAC; } // Check for agreeable client->server hmac algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching C->S MAC'); return doFatalError( self, 'Handshake failed: no matching C->S MAC', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.cs.mac = clientList[i]; debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); } // Server->Client MAC ======================================================== const localSCMAC = local.lists.sc.mac.array; debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); if (CIPHER_INFO[init.sc.cipher].authLen > 0) { init.sc.mac = ''; debug && debug('Handshake: S->C MAC: '); } else { if (self._server) { serverList = localSCMAC; clientList = remote.sc.mac; } else { serverList = remote.sc.mac; clientList = localSCMAC; } // Check for agreeable server->client hmac algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching S->C MAC'); return doFatalError( self, 'Handshake failed: no matching S->C MAC', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.sc.mac = clientList[i]; debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); } // Client->Server compression ================================================ const localCSCompress = local.lists.cs.compress.array; debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); if (self._server) { serverList = localCSCompress; clientList = remote.cs.compress; } else { serverList = remote.cs.compress; clientList = localCSCompress; } // Check for agreeable client->server compression algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching C->S compression'); return doFatalError( self, 'Handshake failed: no matching C->S compression', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.cs.compress = clientList[i]; debug && debug(`Handshake: C->S compression: ${clientList[i]}`); // Server->Client compression ================================================ const localSCCompress = local.lists.sc.compress.array; debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); if (self._server) { serverList = localSCCompress; clientList = remote.sc.compress; } else { serverList = remote.sc.compress; clientList = localSCCompress; } // Check for agreeable server->client compression algorithm for (i = 0; i < clientList.length && serverList.indexOf(clientList[i]) === -1; ++i); if (i === clientList.length) { // No suitable match found! debug && debug('Handshake: No matching S->C compression'); return doFatalError( self, 'Handshake failed: no matching S->C compression', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } init.sc.compress = clientList[i]; debug && debug(`Handshake: S->C compression: ${clientList[i]}`); init.cs.lang = ''; init.sc.lang = ''; // XXX: hack -- find a better way to do this if (self._kex) { if (!self._kexinit) { // We received a rekey request, but we haven't sent a KEXINIT in response // yet kexinit(self); } self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); } self._kex = createKeyExchange(init, self, payload); self._kex.remoteExtInfoEnabled = remoteExtInfoEnabled; self._kex.start(); } const createKeyExchange = (() => { function convertToMpint(buf) { let idx = 0; let length = buf.length; while (buf[idx] === 0x00) { ++idx; --length; } let newBuf; if (buf[idx] & 0x80) { newBuf = Buffer.allocUnsafe(1 + length); newBuf[0] = 0; buf.copy(newBuf, 1, idx); buf = newBuf; } else if (length !== buf.length) { newBuf = Buffer.allocUnsafe(length); buf.copy(newBuf, 0, idx); buf = newBuf; } return buf; } class KeyExchange { constructor(negotiated, protocol, remoteKexinit) { this._protocol = protocol; this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); this.negotiated = negotiated; this.remoteExtInfoEnabled = false; this._step = 1; this._public = null; this._dh = null; this._sentNEWKEYS = false; this._receivedNEWKEYS = false; this._finished = false; this._hostVerified = false; // Data needed for initializing cipher/decipher/etc. this._kexinit = protocol._kexinit; this._remoteKexinit = remoteKexinit; this._identRaw = protocol._identRaw; this._remoteIdentRaw = protocol._remoteIdentRaw; this._hostKey = undefined; this._dhData = undefined; this._sig = undefined; } finish(scOnly) { if (this._finished) return false; this._finished = true; const isServer = this._protocol._server; const negotiated = this.negotiated; const pubKey = this.convertPublicKey(this._dhData); let secret = this.computeSecret(this._dhData); if (secret instanceof Error) { secret.message = `Error while computing DH secret (${this.type}): ${secret.message}`; secret.level = 'handshake'; return doFatalError( this._protocol, secret, DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } const hash = createHash(this.hashName); // V_C hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); // "V_S" hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); // "I_C" hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); // "I_S" hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); // "K_S" const serverPublicHostKey = (isServer ? this._hostKey.getPublicSSH() : this._hostKey); hashString(hash, serverPublicHostKey); if (this.type === 'groupex') { // Group exchange-specific const params = this.getDHParams(); const num = Buffer.allocUnsafe(4); // min (uint32) writeUInt32BE(num, this._minBits, 0); hash.update(num); // preferred (uint32) writeUInt32BE(num, this._prefBits, 0); hash.update(num); // max (uint32) writeUInt32BE(num, this._maxBits, 0); hash.update(num); // prime hashString(hash, params.prime); // generator hashString(hash, params.generator); } // method-specific data sent by client hashString(hash, (isServer ? pubKey : this.getPublicKey())); // method-specific data sent by server const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); hashString(hash, serverPublicKey); // shared secret ("K") hashString(hash, secret); // "H" const exchangeHash = hash.digest(); if (!isServer) { bufferParser.init(this._sig, 0); const sigType = bufferParser.readString(true); if (!sigType) { return doFatalError( this._protocol, 'Malformed packet while reading signature', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } if (sigType !== negotiated.serverHostKey) { return doFatalError( this._protocol, `Wrong signature type: ${sigType}, ` + `expected: ${negotiated.serverHostKey}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } // "s" let sigValue = bufferParser.readString(); bufferParser.clear(); if (sigValue === undefined) { return doFatalError( this._protocol, 'Malformed packet while reading signature', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { return doFatalError( this._protocol, 'Malformed signature', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } let parsedHostKey; { bufferParser.init(this._hostKey, 0); const name = bufferParser.readString(true); const hostKey = this._hostKey.slice(bufferParser.pos()); bufferParser.clear(); parsedHostKey = parseDERKey(hostKey, name); if (parsedHostKey instanceof Error) { parsedHostKey.level = 'handshake'; return doFatalError( this._protocol, parsedHostKey, DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } } let hashAlgo; // Check if we need to override the default hash algorithm switch (this.negotiated.serverHostKey) { case 'rsa-sha2-256': hashAlgo = 'sha256'; break; case 'rsa-sha2-512': hashAlgo = 'sha512'; break; } this._protocol._debug && this._protocol._debug('Verifying signature ...'); const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); if (verified !== true) { if (verified instanceof Error) { this._protocol._debug && this._protocol._debug( `Signature verification failed: ${verified.stack}` ); } else { this._protocol._debug && this._protocol._debug( 'Signature verification failed' ); } return doFatalError( this._protocol, 'Handshake failed: signature verification failed', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug('Verified signature'); } else { // Server let hashAlgo; // Check if we need to override the default hash algorithm switch (this.negotiated.serverHostKey) { case 'rsa-sha2-256': hashAlgo = 'sha256'; break; case 'rsa-sha2-512': hashAlgo = 'sha512'; break; } this._protocol._debug && this._protocol._debug( 'Generating signature ...' ); let signature = this._hostKey.sign(exchangeHash, hashAlgo); if (signature instanceof Error) { return doFatalError( this._protocol, 'Handshake failed: signature generation failed for ' + `${this._hostKey.type} host key: ${signature.message}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } signature = convertSignature(signature, this._hostKey.type); if (signature === false) { return doFatalError( this._protocol, 'Handshake failed: signature conversion failed for ' + `${this._hostKey.type} host key`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } // Send KEX reply /* byte SSH_MSG_KEXDH_REPLY / SSH_MSG_KEX_DH_GEX_REPLY / SSH_MSG_KEX_ECDH_REPLY string server public host key and certificates (K_S) string string signature of H */ const sigType = this.negotiated.serverHostKey; const sigTypeLen = Buffer.byteLength(sigType); const sigLen = 4 + sigTypeLen + 4 + signature.length; let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc( 1 + 4 + serverPublicHostKey.length + 4 + serverPublicKey.length + 4 + sigLen, true ); packet[p] = MESSAGE.KEXDH_REPLY; writeUInt32BE(packet, serverPublicHostKey.length, ++p); packet.set(serverPublicHostKey, p += 4); writeUInt32BE(packet, serverPublicKey.length, p += serverPublicHostKey.length); packet.set(serverPublicKey, p += 4); writeUInt32BE(packet, sigLen, p += serverPublicKey.length); writeUInt32BE(packet, sigTypeLen, p += 4); packet.utf8Write(sigType, p += 4, sigTypeLen); writeUInt32BE(packet, signature.length, p += sigTypeLen); packet.set(signature, p += 4); if (this._protocol._debug) { let type; switch (this.type) { case 'group': type = 'KEXDH_REPLY'; break; case 'groupex': type = 'KEXDH_GEX_REPLY'; break; default: type = 'KEXECDH_REPLY'; } this._protocol._debug(`Outbound: Sending ${type}`); } this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); } if (isServer || !scOnly) trySendNEWKEYS(this); let hsCipherConfig; let hsWrite; const completeHandshake = (partial) => { if (hsCipherConfig) { trySendNEWKEYS(this); hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno; this._protocol._cipher.free(); this._protocol._cipher = createCipher(hsCipherConfig); this._protocol._packetRW.write = hsWrite; hsCipherConfig = undefined; hsWrite = undefined; this._protocol._onHandshakeComplete(negotiated); return false; } if (!this.sessionID) this.sessionID = exchangeHash; { const newSecret = Buffer.allocUnsafe(4 + secret.length); writeUInt32BE(newSecret, secret.length, 0); newSecret.set(secret, 4); secret = newSecret; } // Initialize new ciphers, deciphers, etc. const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; const csIV = generateKEXVal(csCipherInfo.ivLen, this.hashName, secret, exchangeHash, this.sessionID, 'A'); const scIV = generateKEXVal(scCipherInfo.ivLen, this.hashName, secret, exchangeHash, this.sessionID, 'B'); const csKey = generateKEXVal(csCipherInfo.keyLen, this.hashName, secret, exchangeHash, this.sessionID, 'C'); const scKey = generateKEXVal(scCipherInfo.keyLen, this.hashName, secret, exchangeHash, this.sessionID, 'D'); let csMacInfo; let csMacKey; if (!csCipherInfo.authLen) { csMacInfo = MAC_INFO[negotiated.cs.mac]; csMacKey = generateKEXVal(csMacInfo.len, this.hashName, secret, exchangeHash, this.sessionID, 'E'); } let scMacInfo; let scMacKey; if (!scCipherInfo.authLen) { scMacInfo = MAC_INFO[negotiated.sc.mac]; scMacKey = generateKEXVal(scMacInfo.len, this.hashName, secret, exchangeHash, this.sessionID, 'F'); } const config = { inbound: { onPayload: this._protocol._onPayload, seqno: this._protocol._decipher.inSeqno, decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), decipherIV: (!isServer ? scIV : csIV), decipherKey: (!isServer ? scKey : csKey), macInfo: (!isServer ? scMacInfo : csMacInfo), macKey: (!isServer ? scMacKey : csMacKey), }, outbound: { onWrite: this._protocol._onWrite, seqno: this._protocol._cipher.outSeqno, cipherInfo: (isServer ? scCipherInfo : csCipherInfo), cipherIV: (isServer ? scIV : csIV), cipherKey: (isServer ? scKey : csKey), macInfo: (isServer ? scMacInfo : csMacInfo), macKey: (isServer ? scMacKey : csMacKey), }, }; this._protocol._decipher.free(); hsCipherConfig = config; this._protocol._decipher = createDecipher(config); const rw = { read: undefined, write: undefined, }; switch (negotiated.cs.compress) { case 'zlib': // starts immediately if (isServer) rw.read = new ZlibPacketReader(); else rw.write = new ZlibPacketWriter(this._protocol); break; case 'zlib@openssh.com': // Starts after successful user authentication if (this._protocol._authenticated) { // If a rekey happens and this compression method is selected and // we already authenticated successfully, we need to start // immediately instead if (isServer) rw.read = new ZlibPacketReader(); else rw.write = new ZlibPacketWriter(this._protocol); break; } // FALLTHROUGH default: // none -- never any compression/decompression if (isServer) rw.read = new PacketReader(); else rw.write = new PacketWriter(this._protocol); } switch (negotiated.sc.compress) { case 'zlib': // starts immediately if (isServer) rw.write = new ZlibPacketWriter(this._protocol); else rw.read = new ZlibPacketReader(); break; case 'zlib@openssh.com': // Starts after successful user authentication if (this._protocol._authenticated) { // If a rekey happens and this compression method is selected and // we already authenticated successfully, we need to start // immediately instead if (isServer) rw.write = new ZlibPacketWriter(this._protocol); else rw.read = new ZlibPacketReader(); break; } // FALLTHROUGH default: // none -- never any compression/decompression if (isServer) rw.write = new PacketWriter(this._protocol); else rw.read = new PacketReader(); } this._protocol._packetRW.read.cleanup(); this._protocol._packetRW.write.cleanup(); this._protocol._packetRW.read = rw.read; hsWrite = rw.write; // Cleanup/reset various state this._public = null; this._dh = null; this._kexinit = this._protocol._kexinit = undefined; this._remoteKexinit = undefined; this._identRaw = undefined; this._remoteIdentRaw = undefined; this._hostKey = undefined; this._dhData = undefined; this._sig = undefined; if (!partial) return completeHandshake(); return false; }; if (isServer || scOnly) this.finish = completeHandshake; if (!isServer) return completeHandshake(scOnly); } start() { if (!this._protocol._server) { if (this._protocol._debug) { let type; switch (this.type) { case 'group': type = 'KEXDH_INIT'; break; default: type = 'KEXECDH_INIT'; } this._protocol._debug(`Outbound: Sending ${type}`); } const pubKey = this.getPublicKey(); let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc( 1 + 4 + pubKey.length, true ); packet[p] = MESSAGE.KEXDH_INIT; writeUInt32BE(packet, pubKey.length, ++p); packet.set(pubKey, p += 4); this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); } } getPublicKey() { this.generateKeys(); const key = this._public; if (key) return this.convertPublicKey(key); } convertPublicKey(key) { let newKey; let idx = 0; let len = key.length; while (key[idx] === 0x00) { ++idx; --len; } if (key[idx] & 0x80) { newKey = Buffer.allocUnsafe(1 + len); newKey[0] = 0; key.copy(newKey, 1, idx); return newKey; } if (len !== key.length) { newKey = Buffer.allocUnsafe(len); key.copy(newKey, 0, idx); key = newKey; } return key; } computeSecret(otherPublicKey) { this.generateKeys(); try { return convertToMpint(this._dh.computeSecret(otherPublicKey)); } catch (ex) { return ex; } } parse(payload) { const type = payload[0]; switch (this._step) { case 1: if (this._protocol._server) { // Server if (type !== MESSAGE.KEXDH_INIT) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH Init' ); /* byte SSH_MSG_KEXDH_INIT / SSH_MSG_KEX_ECDH_INIT string */ bufferParser.init(payload, 1); const dhData = bufferParser.readString(); bufferParser.clear(); if (dhData === undefined) { return doFatalError( this._protocol, 'Received malformed KEX*_INIT', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } // Client public key this._dhData = dhData; let hostKey = this._protocol._hostKeys[this.negotiated.serverHostKey]; if (Array.isArray(hostKey)) hostKey = hostKey[0]; this._hostKey = hostKey; this.finish(); } else { // Client if (type !== MESSAGE.KEXDH_REPLY) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH Reply' ); /* byte SSH_MSG_KEXDH_REPLY / SSH_MSG_KEX_DH_GEX_REPLY / SSH_MSG_KEX_ECDH_REPLY string server public host key and certificates (K_S) string string signature of H */ bufferParser.init(payload, 1); let hostPubKey; let dhData; let sig; if ((hostPubKey = bufferParser.readString()) === undefined || (dhData = bufferParser.readString()) === undefined || (sig = bufferParser.readString()) === undefined) { bufferParser.clear(); return doFatalError( this._protocol, 'Received malformed KEX*_REPLY', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } bufferParser.clear(); // Check that the host public key type matches what was negotiated // during KEXINIT swap bufferParser.init(hostPubKey, 0); const hostPubKeyType = bufferParser.readString(true); bufferParser.clear(); if (hostPubKeyType === undefined) { return doFatalError( this._protocol, 'Received malformed host public key', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } if (hostPubKeyType !== this.negotiated.serverHostKey) { // Check if we need to make an exception switch (this.negotiated.serverHostKey) { case 'rsa-sha2-256': case 'rsa-sha2-512': if (hostPubKeyType === 'ssh-rsa') break; // FALLTHROUGH default: return doFatalError( this._protocol, 'Host key does not match negotiated type', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } } this._hostKey = hostPubKey; this._dhData = dhData; this._sig = sig; let checked = false; let ret; if (this._protocol._hostVerifier === undefined) { ret = true; this._protocol._debug && this._protocol._debug( 'Host accepted by default (no verification)' ); } else { ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { if (checked) return; checked = true; if (permitted === false) { this._protocol._debug && this._protocol._debug( 'Host denied (verification failed)' ); return doFatalError( this._protocol, 'Host denied (verification failed)', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Host accepted (verified)' ); this._hostVerified = true; if (this._receivedNEWKEYS) this.finish(); else trySendNEWKEYS(this); }); } if (ret === undefined) { // Async host verification ++this._step; return; } checked = true; if (ret === false) { this._protocol._debug && this._protocol._debug( 'Host denied (verification failed)' ); return doFatalError( this._protocol, 'Host denied (verification failed)', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Host accepted (verified)' ); this._hostVerified = true; trySendNEWKEYS(this); } ++this._step; break; case 2: if (type !== MESSAGE.NEWKEYS) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Inbound: NEWKEYS' ); this._receivedNEWKEYS = true; if (this._protocol._strictMode) this._protocol._decipher.inSeqno = 0; ++this._step; return this.finish(!this._protocol._server && !this._hostVerified); default: return doFatalError( this._protocol, `Received unexpected packet ${type} after NEWKEYS`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } } } class Curve25519Exchange extends KeyExchange { constructor(hashName, ...args) { super(...args); this.type = '25519'; this.hashName = hashName; this._keys = null; } generateKeys() { if (!this._keys) this._keys = generateKeyPairSync('x25519'); } getPublicKey() { this.generateKeys(); const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); return key.slice(-32); // HACK: avoids parsing DER/BER header } convertPublicKey(key) { let newKey; let idx = 0; let len = key.length; while (key[idx] === 0x00) { ++idx; --len; } if (key.length === 32) return key; if (len !== key.length) { newKey = Buffer.allocUnsafe(len); key.copy(newKey, 0, idx); key = newKey; } return key; } computeSecret(otherPublicKey) { this.generateKeys(); try { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.3.101.110'); // id-X25519 asnWriter.endSequence(); // PublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(otherPublicKey.length); otherPublicKey.copy(asnWriter._buf, asnWriter._offset, 0, otherPublicKey.length); asnWriter._offset += otherPublicKey.length; asnWriter.endSequence(); asnWriter.endSequence(); return convertToMpint(diffieHellman({ privateKey: this._keys.privateKey, publicKey: createPublicKey({ key: asnWriter.buffer, type: 'spki', format: 'der', }), })); } catch (ex) { return ex; } } } class ECDHExchange extends KeyExchange { constructor(curveName, hashName, ...args) { super(...args); this.type = 'ecdh'; this.curveName = curveName; this.hashName = hashName; } generateKeys() { if (!this._dh) { this._dh = createECDH(this.curveName); this._public = this._dh.generateKeys(); } } } class DHGroupExchange extends KeyExchange { constructor(hashName, ...args) { super(...args); this.type = 'groupex'; this.hashName = hashName; this._prime = null; this._generator = null; this._minBits = GEX_MIN_BITS; this._prefBits = dhEstimate(this.negotiated); if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) this._prefBits = Math.min(this._prefBits, 4096); this._maxBits = GEX_MAX_BITS; } start() { if (this._protocol._server) return; this._protocol._debug && this._protocol._debug( 'Outbound: Sending KEXDH_GEX_REQUEST' ); let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc( 1 + 4 + 4 + 4, true ); packet[p] = MESSAGE.KEXDH_GEX_REQUEST; writeUInt32BE(packet, this._minBits, ++p); writeUInt32BE(packet, this._prefBits, p += 4); writeUInt32BE(packet, this._maxBits, p += 4); this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); } generateKeys() { if (!this._dh && this._prime && this._generator) { this._dh = createDiffieHellman(this._prime, this._generator); this._public = this._dh.generateKeys(); } } setDHParams(prime, generator) { if (!Buffer.isBuffer(prime)) throw new Error('Invalid prime value'); if (!Buffer.isBuffer(generator)) throw new Error('Invalid generator value'); this._prime = prime; this._generator = generator; } getDHParams() { if (this._dh) { return { prime: convertToMpint(this._dh.getPrime()), generator: convertToMpint(this._dh.getGenerator()), }; } } parse(payload) { const type = payload[0]; switch (this._step) { case 1: { if (this._protocol._server) { if (type !== MESSAGE.KEXDH_GEX_REQUEST) { return doFatalError( this._protocol, `Received packet ${type} instead of ` + MESSAGE.KEXDH_GEX_REQUEST, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } // TODO: allow user implementation to provide safe prime and // generator on demand to support group exchange on server side return doFatalError( this._protocol, 'Group exchange not implemented for server', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } if (type !== MESSAGE.KEXDH_GEX_GROUP) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH GEX Group' ); /* byte SSH_MSG_KEX_DH_GEX_GROUP mpint p, safe prime mpint g, generator for subgroup in GF(p) */ bufferParser.init(payload, 1); let prime; let gen; if ((prime = bufferParser.readString()) === undefined || (gen = bufferParser.readString()) === undefined) { bufferParser.clear(); return doFatalError( this._protocol, 'Received malformed KEXDH_GEX_GROUP', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } bufferParser.clear(); // TODO: validate prime this.setDHParams(prime, gen); this.generateKeys(); const pubkey = this.getPublicKey(); this._protocol._debug && this._protocol._debug( 'Outbound: Sending KEXDH_GEX_INIT' ); let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); packet[p] = MESSAGE.KEXDH_GEX_INIT; writeUInt32BE(packet, pubkey.length, ++p); packet.set(pubkey, p += 4); this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); ++this._step; break; } case 2: if (this._protocol._server) { if (type !== MESSAGE.KEXDH_GEX_INIT) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH GEX Init' ); return doFatalError( this._protocol, 'Group exchange not implemented for server', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { return doFatalError( this._protocol, `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } this._protocol._debug && this._protocol._debug( 'Received DH GEX Reply' ); this._step = 1; payload[0] = MESSAGE.KEXDH_REPLY; this.parse = KeyExchange.prototype.parse; this.parse(payload); } } } class DHExchange extends KeyExchange { constructor(groupName, hashName, ...args) { super(...args); this.type = 'group'; this.groupName = groupName; this.hashName = hashName; } start() { if (!this._protocol._server) { this._protocol._debug && this._protocol._debug( 'Outbound: Sending KEXDH_INIT' ); const pubKey = this.getPublicKey(); let p = this._protocol._packetRW.write.allocStartKEX; const packet = this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); packet[p] = MESSAGE.KEXDH_INIT; writeUInt32BE(packet, pubKey.length, ++p); packet.set(pubKey, p += 4); this._protocol._cipher.encrypt( this._protocol._packetRW.write.finalize(packet, true) ); } } generateKeys() { if (!this._dh) { this._dh = createDiffieHellmanGroup(this.groupName); this._public = this._dh.generateKeys(); } } getDHParams() { if (this._dh) { return { prime: convertToMpint(this._dh.getPrime()), generator: convertToMpint(this._dh.getGenerator()), }; } } } return (negotiated, ...args) => { if (typeof negotiated !== 'object' || negotiated === null) throw new Error('Invalid negotiated argument'); const kexType = negotiated.kex; if (typeof kexType === 'string') { args = [negotiated, ...args]; switch (kexType) { case 'curve25519-sha256': case 'curve25519-sha256@libssh.org': if (!curve25519Supported) break; return new Curve25519Exchange('sha256', ...args); case 'ecdh-sha2-nistp256': return new ECDHExchange('prime256v1', 'sha256', ...args); case 'ecdh-sha2-nistp384': return new ECDHExchange('secp384r1', 'sha384', ...args); case 'ecdh-sha2-nistp521': return new ECDHExchange('secp521r1', 'sha512', ...args); case 'diffie-hellman-group1-sha1': return new DHExchange('modp2', 'sha1', ...args); case 'diffie-hellman-group14-sha1': return new DHExchange('modp14', 'sha1', ...args); case 'diffie-hellman-group14-sha256': return new DHExchange('modp14', 'sha256', ...args); case 'diffie-hellman-group15-sha512': return new DHExchange('modp15', 'sha512', ...args); case 'diffie-hellman-group16-sha512': return new DHExchange('modp16', 'sha512', ...args); case 'diffie-hellman-group17-sha512': return new DHExchange('modp17', 'sha512', ...args); case 'diffie-hellman-group18-sha512': return new DHExchange('modp18', 'sha512', ...args); case 'diffie-hellman-group-exchange-sha1': return new DHGroupExchange('sha1', ...args); case 'diffie-hellman-group-exchange-sha256': return new DHGroupExchange('sha256', ...args); } throw new Error(`Unsupported key exchange algorithm: ${kexType}`); } throw new Error(`Invalid key exchange type: ${kexType}`); }; })(); const KexInit = (() => { const KEX_PROPERTY_NAMES = [ 'kex', 'serverHostKey', ['cs', 'cipher' ], ['sc', 'cipher' ], ['cs', 'mac' ], ['sc', 'mac' ], ['cs', 'compress' ], ['sc', 'compress' ], ['cs', 'lang' ], ['sc', 'lang' ], ]; return class KexInit { constructor(obj) { if (typeof obj !== 'object' || obj === null) throw new TypeError('Argument must be an object'); const lists = { kex: undefined, serverHostKey: undefined, cs: { cipher: undefined, mac: undefined, compress: undefined, lang: undefined, }, sc: { cipher: undefined, mac: undefined, compress: undefined, lang: undefined, }, all: undefined, }; let totalSize = 0; for (const prop of KEX_PROPERTY_NAMES) { let base; let val; let desc; let key; if (typeof prop === 'string') { base = lists; val = obj[prop]; desc = key = prop; } else { const parent = prop[0]; base = lists[parent]; key = prop[1]; val = obj[parent][key]; desc = `${parent}.${key}`; } const entry = { array: undefined, buffer: undefined }; if (Buffer.isBuffer(val)) { entry.array = ('' + val).split(','); entry.buffer = val; totalSize += 4 + val.length; } else { if (typeof val === 'string') val = val.split(','); if (Array.isArray(val)) { entry.array = val; entry.buffer = Buffer.from(val.join(',')); } else { throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); } totalSize += 4 + entry.buffer.length; } base[key] = entry; } const all = Buffer.allocUnsafe(totalSize); lists.all = all; let allPos = 0; for (const prop of KEX_PROPERTY_NAMES) { let data; if (typeof prop === 'string') data = lists[prop].buffer; else data = lists[prop[0]][prop[1]].buffer; allPos = writeUInt32BE(all, data.length, allPos); all.set(data, allPos); allPos += data.length; } this.totalSize = totalSize; this.lists = lists; } copyAllTo(buf, offset) { const src = this.lists.all; if (typeof offset !== 'number') throw new TypeError(`Invalid offset value: ${typeof offset}`); if (buf.length - offset < src.length) throw new Error('Insufficient space to copy list'); buf.set(src, offset); return src.length; } }; })(); const hashString = (() => { const LEN = Buffer.allocUnsafe(4); return (hash, buf) => { writeUInt32BE(LEN, buf.length, 0); hash.update(LEN); hash.update(buf); }; })(); function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { let ret; if (len) { let digest = createHash(hashName) .update(secret) .update(exchangeHash) .update(char) .update(sessionID) .digest(); while (digest.length < len) { const chunk = createHash(hashName) .update(secret) .update(exchangeHash) .update(digest) .digest(); const extended = Buffer.allocUnsafe(digest.length + chunk.length); extended.set(digest, 0); extended.set(chunk, digest.length); digest = extended; } if (digest.length === len) ret = digest; else ret = new FastBuffer(digest.buffer, digest.byteOffset, len); } else { ret = EMPTY_BUFFER; } return ret; } function onKEXPayload(state, payload) { // XXX: move this to the Decipher implementations? if (payload.length === 0) { this._debug && this._debug('Inbound: Skipping empty packet payload'); return; } if (this._skipNextInboundPacket) { this._skipNextInboundPacket = false; return; } payload = this._packetRW.read.read(payload); const type = payload[0]; if (!this._strictMode) { switch (type) { case MESSAGE.IGNORE: case MESSAGE.UNIMPLEMENTED: case MESSAGE.DEBUG: if (!MESSAGE_HANDLERS) MESSAGE_HANDLERS = __nccwpck_require__(9244); return MESSAGE_HANDLERS[type](this, payload); } } switch (type) { case MESSAGE.DISCONNECT: if (!MESSAGE_HANDLERS) MESSAGE_HANDLERS = __nccwpck_require__(9244); return MESSAGE_HANDLERS[type](this, payload); case MESSAGE.KEXINIT: if (!state.firstPacket) { return doFatalError( this, 'Received extra KEXINIT during handshake', 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } state.firstPacket = false; return handleKexInit(this, payload); default: // Ensure packet is either an algorithm negotiation or KEX // algorithm-specific packet if (type < 20 || type > 49) { return doFatalError( this, `Received unexpected packet type ${type}`, 'handshake', DISCONNECT_REASON.KEY_EXCHANGE_FAILED ); } } return this._kex.parse(payload); } function dhEstimate(neg) { const csCipher = CIPHER_INFO[neg.cs.cipher]; const scCipher = CIPHER_INFO[neg.sc.cipher]; // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will // also need to be considered when calculating `bits` const bits = Math.max( 0, (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), csCipher.blockLen, csCipher.ivLen, (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), scCipher.blockLen, scCipher.ivLen ) * 8; if (bits <= 112) return 2048; if (bits <= 128) return 3072; if (bits <= 192) return 7680; return 8192; } function trySendNEWKEYS(kex) { if (!kex._sentNEWKEYS) { kex._protocol._debug && kex._protocol._debug( 'Outbound: Sending NEWKEYS' ); const p = kex._protocol._packetRW.write.allocStartKEX; const packet = kex._protocol._packetRW.write.alloc(1, true); packet[p] = MESSAGE.NEWKEYS; kex._protocol._cipher.encrypt( kex._protocol._packetRW.write.finalize(packet, true) ); kex._sentNEWKEYS = true; if (kex._protocol._strictMode) kex._protocol._cipher.outSeqno = 0; } } module.exports = { KexInit, kexinit, onKEXPayload, DEFAULT_KEXINIT_CLIENT: new KexInit({ kex: DEFAULT_KEX.concat(['ext-info-c', 'kex-strict-c-v00@openssh.com']), serverHostKey: DEFAULT_SERVER_HOST_KEY, cs: { cipher: DEFAULT_CIPHER, mac: DEFAULT_MAC, compress: DEFAULT_COMPRESSION, lang: [], }, sc: { cipher: DEFAULT_CIPHER, mac: DEFAULT_MAC, compress: DEFAULT_COMPRESSION, lang: [], }, }), DEFAULT_KEXINIT_SERVER: new KexInit({ kex: DEFAULT_KEX.concat(['kex-strict-s-v00@openssh.com']), serverHostKey: DEFAULT_SERVER_HOST_KEY, cs: { cipher: DEFAULT_CIPHER, mac: DEFAULT_MAC, compress: DEFAULT_COMPRESSION, lang: [], }, sc: { cipher: DEFAULT_CIPHER, mac: DEFAULT_MAC, compress: DEFAULT_COMPRESSION, lang: [], }, }), HANDLERS: { [MESSAGE.KEXINIT]: handleKexInit, }, }; /***/ }), /***/ 1789: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // TODO: // * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` // * handle multi-line header values (OpenSSH)? // * more thorough validation? const { createDecipheriv, createECDH, createHash, createHmac, createSign, createVerify, getCiphers, sign: sign_, verify: verify_, } = __nccwpck_require__(6982); const supportedOpenSSLCiphers = getCiphers(); const { Ber } = __nccwpck_require__(9837); const bcrypt_pbkdf = (__nccwpck_require__(686).pbkdf); const { CIPHER_INFO } = __nccwpck_require__(2888); const { eddsaSupported, SUPPORTED_CIPHER } = __nccwpck_require__(4020); const { bufferSlice, makeBufferParser, readString, readUInt32BE, writeUInt32BE, } = __nccwpck_require__(2184); const SYM_HASH_ALGO = Symbol('Hash Algorithm'); const SYM_PRIV_PEM = Symbol('Private key PEM'); const SYM_PUB_PEM = Symbol('Public key PEM'); const SYM_PUB_SSH = Symbol('Public key SSH'); const SYM_DECRYPTED = Symbol('Decrypted Key'); // Create OpenSSL cipher name -> SSH cipher name conversion table const CIPHER_INFO_OPENSSL = Object.create(null); { const keys = Object.keys(CIPHER_INFO); for (let i = 0; i < keys.length; ++i) { const cipherName = CIPHER_INFO[keys[i]].sslName; if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) continue; CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; } } const binaryKeyParser = makeBufferParser(); function makePEM(type, data) { data = data.base64Slice(0, data.length); let formatted = data.replace(/.{64}/g, '$&\n'); if (data.length & 63) formatted += '\n'; return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; } function combineBuffers(buf1, buf2) { const result = Buffer.allocUnsafe(buf1.length + buf2.length); result.set(buf1, 0); result.set(buf2, buf1.length); return result; } function skipFields(buf, nfields) { const bufLen = buf.length; let pos = (buf._pos || 0); for (let i = 0; i < nfields; ++i) { const left = (bufLen - pos); if (pos >= bufLen || left < 4) return false; const len = readUInt32BE(buf, pos); if (left < 4 + len) return false; pos += 4 + len; } buf._pos = pos; return true; } function genOpenSSLRSAPub(n, e) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption // algorithm parameters (RSA has none) asnWriter.writeNull(); asnWriter.endSequence(); // subjectPublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); asnWriter.startSequence(); asnWriter.writeBuffer(n, Ber.Integer); asnWriter.writeBuffer(e, Ber.Integer); asnWriter.endSequence(); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHRSAPub(n, e) { const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); writeUInt32BE(publicKey, 7, 0); publicKey.utf8Write('ssh-rsa', 4, 7); let i = 4 + 7; writeUInt32BE(publicKey, e.length, i); publicKey.set(e, i += 4); writeUInt32BE(publicKey, n.length, i += e.length); publicKey.set(n, i + 4); return publicKey; } const genOpenSSLRSAPriv = (() => { function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); asnWriter.writeInt(0x00, Ber.Integer); asnWriter.writeBuffer(n, Ber.Integer); asnWriter.writeBuffer(e, Ber.Integer); asnWriter.writeBuffer(d, Ber.Integer); asnWriter.writeBuffer(p, Ber.Integer); asnWriter.writeBuffer(q, Ber.Integer); asnWriter.writeBuffer(dmp1, Ber.Integer); asnWriter.writeBuffer(dmq1, Ber.Integer); asnWriter.writeBuffer(iqmp, Ber.Integer); asnWriter.endSequence(); return asnWriter.buffer; } function bigIntFromBuffer(buf) { return BigInt(`0x${buf.hexSlice(0, buf.length)}`); } function bigIntToBuffer(bn) { let hex = bn.toString(16); if ((hex.length & 1) !== 0) { hex = `0${hex}`; } else { const sigbit = hex.charCodeAt(0); // BER/DER integers require leading zero byte to denote a positive value // when first byte >= 0x80 if (sigbit === 56/* '8' */ || sigbit === 57/* '9' */ || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { hex = `00${hex}`; } } return Buffer.from(hex, 'hex'); } return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { const bn_d = bigIntFromBuffer(d); const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); return makePEM('RSA PRIVATE', genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); }; })(); function genOpenSSLDSAPub(p, q, g, y) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa // algorithm parameters asnWriter.startSequence(); asnWriter.writeBuffer(p, Ber.Integer); asnWriter.writeBuffer(q, Ber.Integer); asnWriter.writeBuffer(g, Ber.Integer); asnWriter.endSequence(); asnWriter.endSequence(); // subjectPublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); asnWriter.writeBuffer(y, Ber.Integer); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHDSAPub(p, q, g, y) { const publicKey = Buffer.allocUnsafe( 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length ); writeUInt32BE(publicKey, 7, 0); publicKey.utf8Write('ssh-dss', 4, 7); let i = 4 + 7; writeUInt32BE(publicKey, p.length, i); publicKey.set(p, i += 4); writeUInt32BE(publicKey, q.length, i += p.length); publicKey.set(q, i += 4); writeUInt32BE(publicKey, g.length, i += q.length); publicKey.set(g, i += 4); writeUInt32BE(publicKey, y.length, i += g.length); publicKey.set(y, i + 4); return publicKey; } function genOpenSSLDSAPriv(p, q, g, y, x) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); asnWriter.writeInt(0x00, Ber.Integer); asnWriter.writeBuffer(p, Ber.Integer); asnWriter.writeBuffer(q, Ber.Integer); asnWriter.writeBuffer(g, Ber.Integer); asnWriter.writeBuffer(y, Ber.Integer); asnWriter.writeBuffer(x, Ber.Integer); asnWriter.endSequence(); return makePEM('DSA PRIVATE', asnWriter.buffer); } function genOpenSSLEdPub(pub) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.3.101.112'); // id-Ed25519 asnWriter.endSequence(); // PublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(pub.length); asnWriter._buf.set(pub, asnWriter._offset); asnWriter._offset += pub.length; asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHEdPub(pub) { const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); writeUInt32BE(publicKey, 11, 0); publicKey.utf8Write('ssh-ed25519', 4, 11); writeUInt32BE(publicKey, pub.length, 15); publicKey.set(pub, 19); return publicKey; } function genOpenSSLEdPriv(priv) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // version asnWriter.writeInt(0x00, Ber.Integer); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.3.101.112'); // id-Ed25519 asnWriter.endSequence(); // PrivateKey asnWriter.startSequence(Ber.OctetString); asnWriter.writeBuffer(priv, Ber.OctetString); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PRIVATE', asnWriter.buffer); } function genOpenSSLECDSAPub(oid, Q) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // algorithm asnWriter.startSequence(); asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey // algorithm parameters (namedCurve) asnWriter.writeOID(oid); asnWriter.endSequence(); // subjectPublicKey asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(Q.length); asnWriter._buf.set(Q, asnWriter._offset); asnWriter._offset += Q.length; // end hack asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('PUBLIC', asnWriter.buffer); } function genOpenSSHECDSAPub(oid, Q) { let curveName; switch (oid) { case '1.2.840.10045.3.1.7': // prime256v1/secp256r1 curveName = 'nistp256'; break; case '1.3.132.0.34': // secp384r1 curveName = 'nistp384'; break; case '1.3.132.0.35': // secp521r1 curveName = 'nistp521'; break; default: return; } const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); writeUInt32BE(publicKey, 19, 0); publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); writeUInt32BE(publicKey, 8, 23); publicKey.utf8Write(curveName, 27, 8); writeUInt32BE(publicKey, Q.length, 35); publicKey.set(Q, 39); return publicKey; } function genOpenSSLECDSAPriv(oid, pub, priv) { const asnWriter = new Ber.Writer(); asnWriter.startSequence(); // version asnWriter.writeInt(0x01, Ber.Integer); // privateKey asnWriter.writeBuffer(priv, Ber.OctetString); // parameters (optional) asnWriter.startSequence(0xA0); asnWriter.writeOID(oid); asnWriter.endSequence(); // publicKey (optional) asnWriter.startSequence(0xA1); asnWriter.startSequence(Ber.BitString); asnWriter.writeByte(0x00); // XXX: hack to write a raw buffer without a tag -- yuck asnWriter._ensure(pub.length); asnWriter._buf.set(pub, asnWriter._offset); asnWriter._offset += pub.length; // end hack asnWriter.endSequence(); asnWriter.endSequence(); asnWriter.endSequence(); return makePEM('EC PRIVATE', asnWriter.buffer); } function genOpenSSLECDSAPubFromPriv(curveName, priv) { const tempECDH = createECDH(curveName); tempECDH.setPrivateKey(priv); return tempECDH.getPublicKey(); } const BaseKey = { sign: (() => { if (typeof sign_ === 'function') { return function sign(data, algo) { const pem = this[SYM_PRIV_PEM]; if (pem === null) return new Error('No private key available'); if (!algo || typeof algo !== 'string') algo = this[SYM_HASH_ALGO]; try { return sign_(algo, data, pem); } catch (ex) { return ex; } }; } return function sign(data, algo) { const pem = this[SYM_PRIV_PEM]; if (pem === null) return new Error('No private key available'); if (!algo || typeof algo !== 'string') algo = this[SYM_HASH_ALGO]; const signature = createSign(algo); signature.update(data); try { return signature.sign(pem); } catch (ex) { return ex; } }; })(), verify: (() => { if (typeof verify_ === 'function') { return function verify(data, signature, algo) { const pem = this[SYM_PUB_PEM]; if (pem === null) return new Error('No public key available'); if (!algo || typeof algo !== 'string') algo = this[SYM_HASH_ALGO]; try { return verify_(algo, data, pem, signature); } catch (ex) { return ex; } }; } return function verify(data, signature, algo) { const pem = this[SYM_PUB_PEM]; if (pem === null) return new Error('No public key available'); if (!algo || typeof algo !== 'string') algo = this[SYM_HASH_ALGO]; const verifier = createVerify(algo); verifier.update(data); try { return verifier.verify(pem, signature); } catch (ex) { return ex; } }; })(), isPrivateKey: function isPrivateKey() { return (this[SYM_PRIV_PEM] !== null); }, getPrivatePEM: function getPrivatePEM() { return this[SYM_PRIV_PEM]; }, getPublicPEM: function getPublicPEM() { return this[SYM_PUB_PEM]; }, getPublicSSH: function getPublicSSH() { return this[SYM_PUB_SSH]; }, equals: function equals(key) { const parsed = parseKey(key); if (parsed instanceof Error) return false; return ( this.type === parsed.type && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] && this[SYM_PUB_SSH].equals(parsed[SYM_PUB_SSH]) ); }, }; function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; } OpenSSH_Private.prototype = BaseKey; { const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; OpenSSH_Private.parse = (str, passphrase) => { const m = regexp.exec(str); if (m === null) return null; let ret; const data = Buffer.from(m[1], 'base64'); if (data.length < 31) // magic (+ magic null term.) + minimum field lengths return new Error('Malformed OpenSSH private key'); const magic = data.utf8Slice(0, 15); if (magic !== 'openssh-key-v1\0') return new Error(`Unsupported OpenSSH key magic: ${magic}`); const cipherName = readString(data, 15, true); if (cipherName === undefined) return new Error('Malformed OpenSSH private key'); if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); const kdfName = readString(data, data._pos, true); if (kdfName === undefined) return new Error('Malformed OpenSSH private key'); if (kdfName !== 'none') { if (cipherName === 'none') return new Error('Malformed OpenSSH private key'); if (kdfName !== 'bcrypt') return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); if (!passphrase) { return new Error( 'Encrypted private OpenSSH key detected, but no passphrase given' ); } } else if (cipherName !== 'none') { return new Error('Malformed OpenSSH private key'); } let encInfo; let cipherKey; let cipherIV; if (cipherName !== 'none') encInfo = CIPHER_INFO[cipherName]; const kdfOptions = readString(data, data._pos); if (kdfOptions === undefined) return new Error('Malformed OpenSSH private key'); if (kdfOptions.length) { switch (kdfName) { case 'none': return new Error('Malformed OpenSSH private key'); case 'bcrypt': { /* string salt uint32 rounds */ const salt = readString(kdfOptions, 0); if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) return new Error('Malformed OpenSSH private key'); const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); const r = bcrypt_pbkdf(passphrase, passphrase.length, salt, salt.length, gen, gen.length, rounds); if (r !== 0) return new Error('Failed to generate information to decrypt key'); cipherKey = bufferSlice(gen, 0, encInfo.keyLen); cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); break; } } } else if (kdfName !== 'none') { return new Error('Malformed OpenSSH private key'); } if (data._pos + 3 >= data.length) return new Error('Malformed OpenSSH private key'); const keyCount = readUInt32BE(data, data._pos); data._pos += 4; if (keyCount > 0) { // TODO: place sensible limit on max `keyCount` // Read public keys first for (let i = 0; i < keyCount; ++i) { const pubData = readString(data, data._pos); if (pubData === undefined) return new Error('Malformed OpenSSH private key'); const type = readString(pubData, 0, true); if (type === undefined) return new Error('Malformed OpenSSH private key'); } let privBlob = readString(data, data._pos); if (privBlob === undefined) return new Error('Malformed OpenSSH private key'); if (cipherKey !== undefined) { // Encrypted private key(s) if (privBlob.length < encInfo.blockLen || (privBlob.length % encInfo.blockLen) !== 0) { return new Error('Malformed OpenSSH private key'); } try { const options = { authTagLength: encInfo.authLen }; const decipher = createDecipheriv(encInfo.sslName, cipherKey, cipherIV, options); decipher.setAutoPadding(false); if (encInfo.authLen > 0) { if (data.length - data._pos < encInfo.authLen) return new Error('Malformed OpenSSH private key'); decipher.setAuthTag( bufferSlice(data, data._pos, data._pos += encInfo.authLen) ); } privBlob = combineBuffers(decipher.update(privBlob), decipher.final()); } catch (ex) { return ex; } } // Nothing should we follow the private key(s), except a possible // authentication tag for relevant ciphers if (data._pos !== data.length) return new Error('Malformed OpenSSH private key'); ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); } else { ret = []; } if (ret instanceof Error) return ret; // This will need to change if/when OpenSSH ever starts storing multiple // keys in their key files return ret[0]; }; function parseOpenSSHPrivKeys(data, nkeys, decrypted) { const keys = []; /* uint32 checkint uint32 checkint string privatekey1 string comment1 string privatekey2 string comment2 ... string privatekeyN string commentN char 1 char 2 char 3 ... char padlen % 255 */ if (data.length < 8) return new Error('Malformed OpenSSH private key'); const check1 = readUInt32BE(data, 0); const check2 = readUInt32BE(data, 4); if (check1 !== check2) { if (decrypted) { return new Error( 'OpenSSH key integrity check failed -- bad passphrase?' ); } return new Error('OpenSSH key integrity check failed'); } data._pos = 8; let i; let oid; for (i = 0; i < nkeys; ++i) { let algo; let privPEM; let pubPEM; let pubSSH; // The OpenSSH documentation for the key format actually lies, the // entirety of the private key content is not contained with a string // field, it's actually the literal contents of the private key, so to be // able to find the end of the key data you need to know the layout/format // of each key type ... const type = readString(data, data._pos, true); if (type === undefined) return new Error('Malformed OpenSSH private key'); switch (type) { case 'ssh-rsa': { /* string n -- public string e -- public string d -- private string iqmp -- private string p -- private string q -- private */ const n = readString(data, data._pos); if (n === undefined) return new Error('Malformed OpenSSH private key'); const e = readString(data, data._pos); if (e === undefined) return new Error('Malformed OpenSSH private key'); const d = readString(data, data._pos); if (d === undefined) return new Error('Malformed OpenSSH private key'); const iqmp = readString(data, data._pos); if (iqmp === undefined) return new Error('Malformed OpenSSH private key'); const p = readString(data, data._pos); if (p === undefined) return new Error('Malformed OpenSSH private key'); const q = readString(data, data._pos); if (q === undefined) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); algo = 'sha1'; break; } case 'ssh-dss': { /* string p -- public string q -- public string g -- public string y -- public string x -- private */ const p = readString(data, data._pos); if (p === undefined) return new Error('Malformed OpenSSH private key'); const q = readString(data, data._pos); if (q === undefined) return new Error('Malformed OpenSSH private key'); const g = readString(data, data._pos); if (g === undefined) return new Error('Malformed OpenSSH private key'); const y = readString(data, data._pos); if (y === undefined) return new Error('Malformed OpenSSH private key'); const x = readString(data, data._pos); if (x === undefined) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); privPEM = genOpenSSLDSAPriv(p, q, g, y, x); algo = 'sha1'; break; } case 'ssh-ed25519': { if (!eddsaSupported) return new Error(`Unsupported OpenSSH private key type: ${type}`); /* * string public key * string private key + public key */ const edpub = readString(data, data._pos); if (edpub === undefined || edpub.length !== 32) return new Error('Malformed OpenSSH private key'); const edpriv = readString(data, data._pos); if (edpriv === undefined || edpriv.length !== 64) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLEdPub(edpub); pubSSH = genOpenSSHEdPub(edpub); privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); algo = null; break; } case 'ecdsa-sha2-nistp256': algo = 'sha256'; oid = '1.2.840.10045.3.1.7'; // FALLTHROUGH case 'ecdsa-sha2-nistp384': if (algo === undefined) { algo = 'sha384'; oid = '1.3.132.0.34'; } // FALLTHROUGH case 'ecdsa-sha2-nistp521': { if (algo === undefined) { algo = 'sha512'; oid = '1.3.132.0.35'; } /* string curve name string Q -- public string d -- private */ // TODO: validate curve name against type if (!skipFields(data, 1)) // Skip curve name return new Error('Malformed OpenSSH private key'); const ecpub = readString(data, data._pos); if (ecpub === undefined) return new Error('Malformed OpenSSH private key'); const ecpriv = readString(data, data._pos); if (ecpriv === undefined) return new Error('Malformed OpenSSH private key'); pubPEM = genOpenSSLECDSAPub(oid, ecpub); pubSSH = genOpenSSHECDSAPub(oid, ecpub); privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); break; } default: return new Error(`Unsupported OpenSSH private key type: ${type}`); } const privComment = readString(data, data._pos, true); if (privComment === undefined) return new Error('Malformed OpenSSH private key'); keys.push( new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, decrypted) ); } let cnt = 0; for (i = data._pos; i < data.length; ++i) { if (data[i] !== (++cnt % 255)) return new Error('Malformed OpenSSH private key'); } return keys; } } function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; } OpenSSH_Old_Private.prototype = BaseKey; { const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; OpenSSH_Old_Private.parse = (str, passphrase) => { const m = regexp.exec(str); if (m === null) return null; let privBlob = Buffer.from(m[3], 'base64'); let headers = m[2]; let decrypted = false; if (headers !== undefined) { // encrypted key headers = headers.split(/\r\n|\n/g); for (let i = 0; i < headers.length; ++i) { const header = headers[i]; let sepIdx = header.indexOf(':'); if (header.slice(0, sepIdx) === 'DEK-Info') { const val = header.slice(sepIdx + 2); sepIdx = val.indexOf(','); if (sepIdx === -1) continue; const cipherName = val.slice(0, sepIdx).toLowerCase(); if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { return new Error( `Cipher (${cipherName}) not supported ` + 'for encrypted OpenSSH private key' ); } const encInfo = CIPHER_INFO_OPENSSL[cipherName]; if (!encInfo) { return new Error( `Cipher (${cipherName}) not supported ` + 'for encrypted OpenSSH private key' ); } const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); if (cipherIV.length !== encInfo.ivLen) return new Error('Malformed encrypted OpenSSH private key'); if (!passphrase) { return new Error( 'Encrypted OpenSSH private key detected, but no passphrase given' ); } const ivSlice = bufferSlice(cipherIV, 0, 8); let cipherKey = createHash('md5') .update(passphrase) .update(ivSlice) .digest(); while (cipherKey.length < encInfo.keyLen) { cipherKey = combineBuffers( cipherKey, createHash('md5') .update(cipherKey) .update(passphrase) .update(ivSlice) .digest() ); } if (cipherKey.length > encInfo.keyLen) cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); try { const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); decipher.setAutoPadding(false); privBlob = combineBuffers(decipher.update(privBlob), decipher.final()); decrypted = true; } catch (ex) { return ex; } } } } let type; let privPEM; let pubPEM; let pubSSH; let algo; let reader; let errMsg = 'Malformed OpenSSH private key'; if (decrypted) errMsg += '. Bad passphrase?'; switch (m[1]) { case 'RSA': type = 'ssh-rsa'; privPEM = makePEM('RSA PRIVATE', privBlob); try { reader = new Ber.Reader(privBlob); reader.readSequence(); reader.readInt(); // skip version const n = reader.readString(Ber.Integer, true); if (n === null) return new Error(errMsg); const e = reader.readString(Ber.Integer, true); if (e === null) return new Error(errMsg); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); } catch { return new Error(errMsg); } algo = 'sha1'; break; case 'DSA': type = 'ssh-dss'; privPEM = makePEM('DSA PRIVATE', privBlob); try { reader = new Ber.Reader(privBlob); reader.readSequence(); reader.readInt(); // skip version const p = reader.readString(Ber.Integer, true); if (p === null) return new Error(errMsg); const q = reader.readString(Ber.Integer, true); if (q === null) return new Error(errMsg); const g = reader.readString(Ber.Integer, true); if (g === null) return new Error(errMsg); const y = reader.readString(Ber.Integer, true); if (y === null) return new Error(errMsg); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); } catch { return new Error(errMsg); } algo = 'sha1'; break; case 'EC': { let ecSSLName; let ecPriv; let ecOID; try { reader = new Ber.Reader(privBlob); reader.readSequence(); reader.readInt(); // skip version ecPriv = reader.readString(Ber.OctetString, true); reader.readByte(); // Skip "complex" context type byte const offset = reader.readLength(); // Skip context length if (offset !== null) { reader._offset = offset; ecOID = reader.readOID(); if (ecOID === null) return new Error(errMsg); switch (ecOID) { case '1.2.840.10045.3.1.7': // prime256v1/secp256r1 ecSSLName = 'prime256v1'; type = 'ecdsa-sha2-nistp256'; algo = 'sha256'; break; case '1.3.132.0.34': // secp384r1 ecSSLName = 'secp384r1'; type = 'ecdsa-sha2-nistp384'; algo = 'sha384'; break; case '1.3.132.0.35': // secp521r1 ecSSLName = 'secp521r1'; type = 'ecdsa-sha2-nistp521'; algo = 'sha512'; break; default: return new Error(`Unsupported private key EC OID: ${ecOID}`); } } else { return new Error(errMsg); } } catch { return new Error(errMsg); } privPEM = makePEM('EC PRIVATE', privBlob); const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); break; } } return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, decrypted); }; } function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = privPEM; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = decrypted; } PPK_Private.prototype = BaseKey; { const EMPTY_PASSPHRASE = Buffer.alloc(0); const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); const PPK_PP1 = Buffer.from([0, 0, 0, 0]); const PPK_PP2 = Buffer.from([0, 0, 0, 1]); const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; PPK_Private.parse = (str, passphrase) => { const m = regexp.exec(str); if (m === null) return null; // m[1] = key type // m[2] = encryption type // m[3] = comment // m[4] = base64-encoded public key data: // for "ssh-rsa": // string "ssh-rsa" // mpint e (public exponent) // mpint n (modulus) // for "ssh-dss": // string "ssh-dss" // mpint p (modulus) // mpint q (prime) // mpint g (base number) // mpint y (public key parameter: g^x mod p) // m[5] = base64-encoded private key data: // for "ssh-rsa": // mpint d (private exponent) // mpint p (prime 1) // mpint q (prime 2) // mpint iqmp ([inverse of q] mod p) // for "ssh-dss": // mpint x (private key parameter) // m[6] = SHA1 HMAC over: // string name of algorithm ("ssh-dss", "ssh-rsa") // string encryption type // string comment // string public key data // string private-plaintext (including the final padding) const cipherName = m[2]; const encrypted = (cipherName !== 'none'); if (encrypted && !passphrase) { return new Error( 'Encrypted PPK private key detected, but no passphrase given' ); } let privBlob = Buffer.from(m[5], 'base64'); if (encrypted) { const encInfo = CIPHER_INFO[cipherName]; let cipherKey = combineBuffers( createHash('sha1').update(PPK_PP1).update(passphrase).digest(), createHash('sha1').update(PPK_PP2).update(passphrase).digest() ); if (cipherKey.length > encInfo.keyLen) cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); try { const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV); decipher.setAutoPadding(false); privBlob = combineBuffers(decipher.update(privBlob), decipher.final()); } catch (ex) { return ex; } } const type = m[1]; const comment = m[3]; const pubBlob = Buffer.from(m[4], 'base64'); const mac = m[6]; const typeLen = type.length; const cipherNameLen = cipherName.length; const commentLen = Buffer.byteLength(comment); const pubLen = pubBlob.length; const privLen = privBlob.length; const macData = Buffer.allocUnsafe(4 + typeLen + 4 + cipherNameLen + 4 + commentLen + 4 + pubLen + 4 + privLen); let p = 0; writeUInt32BE(macData, typeLen, p); macData.utf8Write(type, p += 4, typeLen); writeUInt32BE(macData, cipherNameLen, p += typeLen); macData.utf8Write(cipherName, p += 4, cipherNameLen); writeUInt32BE(macData, commentLen, p += cipherNameLen); macData.utf8Write(comment, p += 4, commentLen); writeUInt32BE(macData, pubLen, p += commentLen); macData.set(pubBlob, p += 4); writeUInt32BE(macData, privLen, p += pubLen); macData.set(privBlob, p + 4); if (!passphrase) passphrase = EMPTY_PASSPHRASE; const calcMAC = createHmac( 'sha1', createHash('sha1') .update('putty-private-key-file-mac-key') .update(passphrase) .digest() ).update(macData).digest('hex'); if (calcMAC !== mac) { if (encrypted) { return new Error( 'PPK private key integrity check failed -- bad passphrase?' ); } return new Error('PPK private key integrity check failed'); } let pubPEM; let pubSSH; let privPEM; pubBlob._pos = 0; skipFields(pubBlob, 1); // skip (duplicate) key type switch (type) { case 'ssh-rsa': { const e = readString(pubBlob, pubBlob._pos); if (e === undefined) return new Error('Malformed PPK public key'); const n = readString(pubBlob, pubBlob._pos); if (n === undefined) return new Error('Malformed PPK public key'); const d = readString(privBlob, 0); if (d === undefined) return new Error('Malformed PPK private key'); const p = readString(privBlob, privBlob._pos); if (p === undefined) return new Error('Malformed PPK private key'); const q = readString(privBlob, privBlob._pos); if (q === undefined) return new Error('Malformed PPK private key'); const iqmp = readString(privBlob, privBlob._pos); if (iqmp === undefined) return new Error('Malformed PPK private key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); break; } case 'ssh-dss': { const p = readString(pubBlob, pubBlob._pos); if (p === undefined) return new Error('Malformed PPK public key'); const q = readString(pubBlob, pubBlob._pos); if (q === undefined) return new Error('Malformed PPK public key'); const g = readString(pubBlob, pubBlob._pos); if (g === undefined) return new Error('Malformed PPK public key'); const y = readString(pubBlob, pubBlob._pos); if (y === undefined) return new Error('Malformed PPK public key'); const x = readString(privBlob, 0); if (x === undefined) return new Error('Malformed PPK private key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); privPEM = genOpenSSLDSAPriv(p, q, g, y, x); break; } } return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', encrypted); }; } function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = null; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = false; } OpenSSH_Public.prototype = BaseKey; { let regexp; if (eddsaSupported) regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; else regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; OpenSSH_Public.parse = (str) => { const m = regexp.exec(str); if (m === null) return null; // m[1] = full type // m[2] = base type // m[3] = base64-encoded public key // m[4] = comment const fullType = m[1]; const baseType = m[2]; const data = Buffer.from(m[3], 'base64'); const comment = (m[4] || ''); const type = readString(data, data._pos, true); if (type === undefined || type.indexOf(baseType) !== 0) return new Error('Malformed OpenSSH public key'); return parseDER(data, baseType, comment, fullType); }; } function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { this.type = type; this.comment = comment; this[SYM_PRIV_PEM] = null; this[SYM_PUB_PEM] = pubPEM; this[SYM_PUB_SSH] = pubSSH; this[SYM_HASH_ALGO] = algo; this[SYM_DECRYPTED] = false; } RFC4716_Public.prototype = BaseKey; { const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; const RE_HEADER_ENDS = /\\\r?\n/g; RFC4716_Public.parse = (str) => { let m = regexp.exec(str); if (m === null) return null; const body = m[1]; let dataStart = 0; let comment = ''; while (m = RE_HEADER.exec(body)) { const headerName = m[1]; const headerValue = m[2].replace(RE_HEADER_ENDS, ''); if (headerValue.length > 1024) { RE_HEADER.lastIndex = 0; return new Error('Malformed RFC4716 public key'); } dataStart = RE_HEADER.lastIndex; if (headerName.toLowerCase() === 'comment') { comment = headerValue; if (comment.length > 1 && comment.charCodeAt(0) === 34/* '"' */ && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { comment = comment.slice(1, -1); } } } let data = body.slice(dataStart); if (!RE_DATA.test(data)) return new Error('Malformed RFC4716 public key'); data = Buffer.from(data, 'base64'); const type = readString(data, 0, true); if (type === undefined) return new Error('Malformed RFC4716 public key'); let pubPEM = null; let pubSSH = null; switch (type) { case 'ssh-rsa': { const e = readString(data, data._pos); if (e === undefined) return new Error('Malformed RFC4716 public key'); const n = readString(data, data._pos); if (n === undefined) return new Error('Malformed RFC4716 public key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); break; } case 'ssh-dss': { const p = readString(data, data._pos); if (p === undefined) return new Error('Malformed RFC4716 public key'); const q = readString(data, data._pos); if (q === undefined) return new Error('Malformed RFC4716 public key'); const g = readString(data, data._pos); if (g === undefined) return new Error('Malformed RFC4716 public key'); const y = readString(data, data._pos); if (y === undefined) return new Error('Malformed RFC4716 public key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); break; } default: return new Error('Malformed RFC4716 public key'); } return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); }; } function parseDER(data, baseType, comment, fullType) { if (!isSupportedKeyType(baseType)) return new Error(`Unsupported OpenSSH public key type: ${baseType}`); let algo; let oid; let pubPEM = null; let pubSSH = null; switch (baseType) { case 'ssh-rsa': { const e = readString(data, data._pos || 0); if (e === undefined) return new Error('Malformed OpenSSH public key'); const n = readString(data, data._pos); if (n === undefined) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLRSAPub(n, e); pubSSH = genOpenSSHRSAPub(n, e); algo = 'sha1'; break; } case 'ssh-dss': { const p = readString(data, data._pos || 0); if (p === undefined) return new Error('Malformed OpenSSH public key'); const q = readString(data, data._pos); if (q === undefined) return new Error('Malformed OpenSSH public key'); const g = readString(data, data._pos); if (g === undefined) return new Error('Malformed OpenSSH public key'); const y = readString(data, data._pos); if (y === undefined) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLDSAPub(p, q, g, y); pubSSH = genOpenSSHDSAPub(p, q, g, y); algo = 'sha1'; break; } case 'ssh-ed25519': { const edpub = readString(data, data._pos || 0); if (edpub === undefined || edpub.length !== 32) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLEdPub(edpub); pubSSH = genOpenSSHEdPub(edpub); algo = null; break; } case 'ecdsa-sha2-nistp256': algo = 'sha256'; oid = '1.2.840.10045.3.1.7'; // FALLTHROUGH case 'ecdsa-sha2-nistp384': if (algo === undefined) { algo = 'sha384'; oid = '1.3.132.0.34'; } // FALLTHROUGH case 'ecdsa-sha2-nistp521': { if (algo === undefined) { algo = 'sha512'; oid = '1.3.132.0.35'; } // TODO: validate curve name against type if (!skipFields(data, 1)) // Skip curve name return new Error('Malformed OpenSSH public key'); const ecpub = readString(data, data._pos || 0); if (ecpub === undefined) return new Error('Malformed OpenSSH public key'); pubPEM = genOpenSSLECDSAPub(oid, ecpub); pubSSH = genOpenSSHECDSAPub(oid, ecpub); break; } default: return new Error(`Unsupported OpenSSH public key type: ${baseType}`); } return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); } function isSupportedKeyType(type) { switch (type) { case 'ssh-rsa': case 'ssh-dss': case 'ecdsa-sha2-nistp256': case 'ecdsa-sha2-nistp384': case 'ecdsa-sha2-nistp521': return true; case 'ssh-ed25519': if (eddsaSupported) return true; // FALLTHROUGH default: return false; } } function isParsedKey(val) { if (!val) return false; return (typeof val[SYM_DECRYPTED] === 'boolean'); } function parseKey(data, passphrase) { if (isParsedKey(data)) return data; let origBuffer; if (Buffer.isBuffer(data)) { origBuffer = data; data = data.utf8Slice(0, data.length).trim(); } else if (typeof data === 'string') { data = data.trim(); } else { return new Error('Key data must be a Buffer or string'); } // eslint-disable-next-line eqeqeq if (passphrase != undefined) { if (typeof passphrase === 'string') passphrase = Buffer.from(passphrase); else if (!Buffer.isBuffer(passphrase)) return new Error('Passphrase must be a string or Buffer when supplied'); } let ret; // First try as printable string format (e.g. PEM) // Private keys if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) return ret; if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) return ret; if ((ret = PPK_Private.parse(data, passphrase)) !== null) return ret; // Public keys if ((ret = OpenSSH_Public.parse(data)) !== null) return ret; if ((ret = RFC4716_Public.parse(data)) !== null) return ret; // Finally try as a binary format if we were originally passed binary data if (origBuffer) { binaryKeyParser.init(origBuffer, 0); const type = binaryKeyParser.readString(true); if (type !== undefined) { data = binaryKeyParser.readRaw(); if (data !== undefined) { ret = parseDER(data, type, '', type); // Ignore potentially useless errors in case the data was not actually // in the binary format if (ret instanceof Error) ret = null; } } binaryKeyParser.clear(); } if (ret) return ret; return new Error('Unsupported key format'); } module.exports = { isParsedKey, isSupportedKeyType, parseDERKey: (data, type) => parseDER(data, type, '', type), parseKey, }; /***/ }), /***/ 3208: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(2613); const { inspect } = __nccwpck_require__(9023); // Only use this for integers! Decimal numbers do not work with this function. function addNumericalSeparator(val) { let res = ''; let i = val.length; const start = val[0] === '-' ? 1 : 0; for (; i >= start + 4; i -= 3) res = `_${val.slice(i - 3, i)}${res}`; return `${val.slice(0, i)}${res}`; } function oneOf(expected, thing) { assert(typeof thing === 'string', '`thing` has to be of type string'); if (Array.isArray(expected)) { const len = expected.length; assert(len > 0, 'At least one expected value needs to be specified'); expected = expected.map((i) => String(i)); if (len > 2) { return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; } else if (len === 2) { return `one of ${thing} ${expected[0]} or ${expected[1]}`; } return `of ${thing} ${expected[0]}`; } return `of ${thing} ${String(expected)}`; } exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { constructor(message) { super(); Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); const suffix = 'This is caused by either a bug in ssh2 ' + 'or incorrect usage of ssh2 internals.\n' + 'Please open an issue with this stack trace at ' + 'https://github.com/mscdex/ssh2/issues\n'; this.message = (message === undefined ? suffix : `${message}\n${suffix}`); } }; const MAX_32BIT_INT = 2 ** 32; const MAX_32BIT_BIGINT = (() => { try { return new Function('return 2n ** 32n')(); } catch {} })(); exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { constructor(str, range, input, replaceDefaultBoolean) { super(); Error.captureStackTrace(this, ERR_OUT_OF_RANGE); assert(range, 'Missing "range" argument'); let msg = (replaceDefaultBoolean ? str : `The value of "${str}" is out of range.`); let received; if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { received = addNumericalSeparator(String(input)); } else if (typeof input === 'bigint') { received = String(input); if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) received = addNumericalSeparator(received); received += 'n'; } else { received = inspect(input); } msg += ` It must be ${range}. Received ${received}`; this.message = msg; } }; class ERR_INVALID_ARG_TYPE extends TypeError { constructor(name, expected, actual) { super(); Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); assert(typeof name === 'string', `'name' must be a string`); // determiner: 'must be' or 'must not be' let determiner; if (typeof expected === 'string' && expected.startsWith('not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } let msg; if (name.endsWith(' argument')) { // For cases like 'first argument' msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { const type = (name.includes('.') ? 'property' : 'argument'); msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } msg += `. Received type ${typeof actual}`; this.message = msg; } } exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; exports.validateNumber = function validateNumber(value, name) { if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value); }; /***/ }), /***/ 2184: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Ber = (__nccwpck_require__(9837).Ber); let DISCONNECT_REASON; const FastBuffer = Buffer[Symbol.species]; const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; function readUInt32BE(buf, offset) { return (buf[offset++] * 16777216) + (buf[offset++] * 65536) + (buf[offset++] * 256) + buf[offset]; } function bufferCopy(src, dest, srcStart, srcEnd, destStart) { if (!destStart) destStart = 0; if (srcEnd > src.length) srcEnd = src.length; let nb = srcEnd - srcStart; const destLeft = (dest.length - destStart); if (nb > destLeft) nb = destLeft; dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), destStart); return nb; } function bufferSlice(buf, start, end) { if (end === undefined) end = buf.length; return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); } function makeBufferParser() { let pos = 0; let buffer; const self = { init: (buf, start) => { buffer = buf; pos = (typeof start === 'number' ? start : 0); }, pos: () => pos, length: () => (buffer ? buffer.length : 0), avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), clear: () => { buffer = undefined; }, readUInt32BE: () => { if (!buffer || pos + 3 >= buffer.length) return; return (buffer[pos++] * 16777216) + (buffer[pos++] * 65536) + (buffer[pos++] * 256) + buffer[pos++]; }, readUInt64BE: (behavior) => { if (!buffer || pos + 7 >= buffer.length) return; switch (behavior) { case 'always': return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); case 'maybe': if (buffer[pos] > 0x1F) return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); // FALLTHROUGH default: return (buffer[pos++] * 72057594037927940) + (buffer[pos++] * 281474976710656) + (buffer[pos++] * 1099511627776) + (buffer[pos++] * 4294967296) + (buffer[pos++] * 16777216) + (buffer[pos++] * 65536) + (buffer[pos++] * 256) + buffer[pos++]; } }, skip: (n) => { if (buffer && n > 0) pos += n; }, skipString: () => { const len = self.readUInt32BE(); if (len === undefined) return; pos += len; return (pos <= buffer.length ? len : undefined); }, readByte: () => { if (buffer && pos < buffer.length) return buffer[pos++]; }, readBool: () => { if (buffer && pos < buffer.length) return !!buffer[pos++]; }, readList: () => { const list = self.readString(true); if (list === undefined) return; return (list ? list.split(',') : []); }, readString: (dest, maxLen) => { if (typeof dest === 'number') { maxLen = dest; dest = undefined; } const len = self.readUInt32BE(); if (len === undefined) return; if ((buffer.length - pos) < len || (typeof maxLen === 'number' && len > maxLen)) { return; } if (dest) { if (Buffer.isBuffer(dest)) return bufferCopy(buffer, dest, pos, pos += len); return buffer.utf8Slice(pos, pos += len); } return bufferSlice(buffer, pos, pos += len); }, readRaw: (len) => { if (!buffer) return; if (typeof len !== 'number') return bufferSlice(buffer, pos, pos += (buffer.length - pos)); if ((buffer.length - pos) >= len) return bufferSlice(buffer, pos, pos += len); }, }; return self; } function makeError(msg, level, fatal) { const err = new Error(msg); if (typeof level === 'boolean') { fatal = level; err.level = 'protocol'; } else { err.level = level || 'protocol'; } err.fatal = !!fatal; return err; } function writeUInt32BE(buf, value, offset) { buf[offset++] = (value >>> 24); buf[offset++] = (value >>> 16); buf[offset++] = (value >>> 8); buf[offset++] = value; return offset; } const utilBufferParser = makeBufferParser(); module.exports = { bufferCopy, bufferSlice, FastBuffer, bufferFill: (buf, value, start, end) => { return TypedArrayFill.call(buf, value, start, end); }, makeError, doFatalError: (protocol, msg, level, reason) => { let err; if (DISCONNECT_REASON === undefined) ({ DISCONNECT_REASON } = __nccwpck_require__(4020)); if (msg instanceof Error) { // doFatalError(protocol, err[, reason]) err = msg; if (typeof level !== 'number') reason = DISCONNECT_REASON.PROTOCOL_ERROR; else reason = level; } else { // doFatalError(protocol, msg[, level[, reason]]) err = makeError(msg, level, true); } if (typeof reason !== 'number') reason = DISCONNECT_REASON.PROTOCOL_ERROR; protocol.disconnect(reason); protocol._destruct(); protocol._onError(err); return Infinity; }, readUInt32BE, writeUInt32BE, writeUInt32LE: (buf, value, offset) => { buf[offset++] = value; buf[offset++] = (value >>> 8); buf[offset++] = (value >>> 16); buf[offset++] = (value >>> 24); return offset; }, makeBufferParser, bufferParser: makeBufferParser(), readString: (buffer, start, dest, maxLen) => { if (typeof dest === 'number') { maxLen = dest; dest = undefined; } if (start === undefined) start = 0; const left = (buffer.length - start); if (start < 0 || start >= buffer.length || left < 4) return; const len = readUInt32BE(buffer, start); if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) return; start += 4; const end = start + len; buffer._pos = end; if (dest) { if (Buffer.isBuffer(dest)) return bufferCopy(buffer, dest, start, end); return buffer.utf8Slice(start, end); } return bufferSlice(buffer, start, end); }, sigSSHToASN1: (sig, type) => { switch (type) { case 'ssh-dss': { if (sig.length > 40) return sig; // Change bare signature r and s values to ASN.1 BER values for OpenSSL const asnWriter = new Ber.Writer(); asnWriter.startSequence(); let r = sig.slice(0, 20); let s = sig.slice(20); if (r[0] & 0x80) { const rNew = Buffer.allocUnsafe(21); rNew[0] = 0x00; r.copy(rNew, 1); r = rNew; } else if (r[0] === 0x00 && !(r[1] & 0x80)) { r = r.slice(1); } if (s[0] & 0x80) { const sNew = Buffer.allocUnsafe(21); sNew[0] = 0x00; s.copy(sNew, 1); s = sNew; } else if (s[0] === 0x00 && !(s[1] & 0x80)) { s = s.slice(1); } asnWriter.writeBuffer(r, Ber.Integer); asnWriter.writeBuffer(s, Ber.Integer); asnWriter.endSequence(); return asnWriter.buffer; } case 'ecdsa-sha2-nistp256': case 'ecdsa-sha2-nistp384': case 'ecdsa-sha2-nistp521': { utilBufferParser.init(sig, 0); const r = utilBufferParser.readString(); const s = utilBufferParser.readString(); utilBufferParser.clear(); if (r === undefined || s === undefined) return; const asnWriter = new Ber.Writer(); asnWriter.startSequence(); asnWriter.writeBuffer(r, Ber.Integer); asnWriter.writeBuffer(s, Ber.Integer); asnWriter.endSequence(); return asnWriter.buffer; } default: return sig; } }, convertSignature: (signature, keyType) => { switch (keyType) { case 'ssh-dss': { if (signature.length <= 40) return signature; // This is a quick and dirty way to get from BER encoded r and s that // OpenSSL gives us, to just the bare values back to back (40 bytes // total) like OpenSSH (and possibly others) are expecting const asnReader = new Ber.Reader(signature); asnReader.readSequence(); let r = asnReader.readString(Ber.Integer, true); let s = asnReader.readString(Ber.Integer, true); let rOffset = 0; let sOffset = 0; if (r.length < 20) { const rNew = Buffer.allocUnsafe(20); rNew.set(r, 1); r = rNew; r[0] = 0; } if (s.length < 20) { const sNew = Buffer.allocUnsafe(20); sNew.set(s, 1); s = sNew; s[0] = 0; } if (r.length > 20 && r[0] === 0) rOffset = 1; if (s.length > 20 && s[0] === 0) sOffset = 1; const newSig = Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); bufferCopy(r, newSig, rOffset, r.length, 0); bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); return newSig; } case 'ecdsa-sha2-nistp256': case 'ecdsa-sha2-nistp384': case 'ecdsa-sha2-nistp521': { if (signature[0] === 0) return signature; // Convert SSH signature parameters to ASN.1 BER values for OpenSSL const asnReader = new Ber.Reader(signature); asnReader.readSequence(); const r = asnReader.readString(Ber.Integer, true); const s = asnReader.readString(Ber.Integer, true); if (r === null || s === null) return; const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); writeUInt32BE(newSig, r.length, 0); newSig.set(r, 4); writeUInt32BE(newSig, s.length, 4 + r.length); newSig.set(s, 4 + 4 + r.length); return newSig; } } return signature; }, sendPacket: (proto, packet, bypass) => { if (!bypass && proto._kexinit !== undefined) { // We're currently in the middle of a handshake if (proto._queue === undefined) proto._queue = []; proto._queue.push(packet); proto._debug && proto._debug('Outbound: ... packet queued'); return false; } proto._cipher.encrypt(packet); return true; }, }; /***/ }), /***/ 4592: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kMaxLength } = __nccwpck_require__(181); const { createInflate, constants: { DEFLATE, INFLATE, Z_DEFAULT_CHUNK, Z_DEFAULT_COMPRESSION, Z_DEFAULT_MEMLEVEL, Z_DEFAULT_STRATEGY, Z_DEFAULT_WINDOWBITS, Z_PARTIAL_FLUSH, } } = __nccwpck_require__(3106); const ZlibHandle = createInflate()._handle.constructor; function processCallback() { throw new Error('Should not get here'); } function zlibOnError(message, errno, code) { const self = this._owner; // There is no way to cleanly recover. // Continuing only obscures problems. const error = new Error(message); error.errno = errno; error.code = code; self._err = error; } function _close(engine) { // Caller may invoke .close after a zlib error (which will null _handle). if (!engine._handle) return; engine._handle.close(); engine._handle = null; } class Zlib { constructor(mode) { const windowBits = Z_DEFAULT_WINDOWBITS; const level = Z_DEFAULT_COMPRESSION; const memLevel = Z_DEFAULT_MEMLEVEL; const strategy = Z_DEFAULT_STRATEGY; const dictionary = undefined; this._err = undefined; this._writeState = new Uint32Array(2); this._chunkSize = Z_DEFAULT_CHUNK; this._maxOutputLength = kMaxLength; this._outBuffer = Buffer.allocUnsafe(this._chunkSize); this._outOffset = 0; this._handle = new ZlibHandle(mode); this._handle._owner = this; this._handle.onerror = zlibOnError; this._handle.init(windowBits, level, memLevel, strategy, this._writeState, processCallback, dictionary); } writeSync(chunk, retChunks) { const handle = this._handle; if (!handle) throw new Error('Invalid Zlib instance'); let availInBefore = chunk.length; let availOutBefore = this._chunkSize - this._outOffset; let inOff = 0; let availOutAfter; let availInAfter; let buffers; let nread = 0; const state = this._writeState; let buffer = this._outBuffer; let offset = this._outOffset; const chunkSize = this._chunkSize; while (true) { handle.writeSync(Z_PARTIAL_FLUSH, chunk, // in inOff, // in_off availInBefore, // in_len buffer, // out offset, // out_off availOutBefore); // out_len if (this._err) throw this._err; availOutAfter = state[0]; availInAfter = state[1]; const inDelta = availInBefore - availInAfter; const have = availOutBefore - availOutAfter; if (have > 0) { const out = (offset === 0 && have === buffer.length ? buffer : buffer.slice(offset, offset + have)); offset += have; if (!buffers) buffers = out; else if (buffers.push === undefined) buffers = [buffers, out]; else buffers.push(out); nread += out.byteLength; if (nread > this._maxOutputLength) { _close(this); throw new Error( `Output length exceeded maximum of ${this._maxOutputLength}` ); } } else if (have !== 0) { throw new Error('have should not go down'); } // Exhausted the output buffer, or used all the input create a new one. if (availOutAfter === 0 || offset >= chunkSize) { availOutBefore = chunkSize; offset = 0; buffer = Buffer.allocUnsafe(chunkSize); } if (availOutAfter === 0) { // Not actually done. Need to reprocess. // Also, update the availInBefore to the availInAfter value, // so that if we have to hit it a third (fourth, etc.) time, // it'll have the correct byte counts. inOff += inDelta; availInBefore = availInAfter; } else { break; } } this._outBuffer = buffer; this._outOffset = offset; if (nread === 0) buffers = Buffer.alloc(0); if (retChunks) { buffers.totalLen = nread; return buffers; } if (buffers.push === undefined) return buffers; const output = Buffer.allocUnsafe(nread); for (let i = 0, p = 0; i < buffers.length; ++i) { const buf = buffers[i]; output.set(buf, p); p += buf.length; } return output; } } class ZlibPacketWriter { constructor(protocol) { this.allocStart = 0; this.allocStartKEX = 0; this._protocol = protocol; this._zlib = new Zlib(DEFLATE); } cleanup() { if (this._zlib) _close(this._zlib); } alloc(payloadSize, force) { return Buffer.allocUnsafe(payloadSize); } finalize(payload, force) { if (this._protocol._kexinit === undefined || force) { const output = this._zlib.writeSync(payload, true); const packet = this._protocol._cipher.allocPacket(output.totalLen); if (output.push === undefined) { packet.set(output, 5); } else { for (let i = 0, p = 5; i < output.length; ++i) { const chunk = output[i]; packet.set(chunk, p); p += chunk.length; } } return packet; } return payload; } } class PacketWriter { constructor(protocol) { this.allocStart = 5; this.allocStartKEX = 5; this._protocol = protocol; } cleanup() {} alloc(payloadSize, force) { if (this._protocol._kexinit === undefined || force) return this._protocol._cipher.allocPacket(payloadSize); return Buffer.allocUnsafe(payloadSize); } finalize(packet, force) { return packet; } } class ZlibPacketReader { constructor() { this._zlib = new Zlib(INFLATE); } cleanup() { if (this._zlib) _close(this._zlib); } read(data) { return this._zlib.writeSync(data, false); } } class PacketReader { cleanup() {} read(data) { return data; } } module.exports = { PacketReader, PacketWriter, ZlibPacketReader, ZlibPacketWriter, }; /***/ }), /***/ 2605: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // TODO: // * convert listenerCount() usage to emit() return value checking? // * emit error when connection severed early (e.g. before handshake) // * add '.connected' or similar property to connection objects to allow // immediate connection status checking const { Server: netServer } = __nccwpck_require__(9278); const EventEmitter = __nccwpck_require__(4434); const { listenerCount } = EventEmitter; const { CHANNEL_OPEN_FAILURE, DEFAULT_CIPHER, DEFAULT_COMPRESSION, DEFAULT_KEX, DEFAULT_MAC, DEFAULT_SERVER_HOST_KEY, DISCONNECT_REASON, DISCONNECT_REASON_BY_VALUE, SUPPORTED_CIPHER, SUPPORTED_COMPRESSION, SUPPORTED_KEX, SUPPORTED_MAC, SUPPORTED_SERVER_HOST_KEY, } = __nccwpck_require__(4020); const { init: cryptoInit } = __nccwpck_require__(2888); const { KexInit } = __nccwpck_require__(4637); const { parseKey } = __nccwpck_require__(1789); const Protocol = __nccwpck_require__(7841); const { SFTP } = __nccwpck_require__(4996); const { writeUInt32BE } = __nccwpck_require__(2184); const { Channel, MAX_WINDOW, PACKET_SIZE, windowAdjust, WINDOW_THRESHOLD, } = __nccwpck_require__(5683); const { ChannelManager, generateAlgorithmList, isWritable, onChannelOpenFailure, onCHANNEL_CLOSE, } = __nccwpck_require__(2137); const MAX_PENDING_AUTHS = 10; class AuthContext extends EventEmitter { constructor(protocol, username, service, method, cb) { super(); this.username = this.user = username; this.service = service; this.method = method; this._initialResponse = false; this._finalResponse = false; this._multistep = false; this._cbfinal = (allowed, methodsLeft, isPartial) => { if (!this._finalResponse) { this._finalResponse = true; cb(this, allowed, methodsLeft, isPartial); } }; this._protocol = protocol; } accept() { this._cleanup && this._cleanup(); this._initialResponse = true; this._cbfinal(true); } reject(methodsLeft, isPartial) { this._cleanup && this._cleanup(); this._initialResponse = true; this._cbfinal(false, methodsLeft, isPartial); } } class KeyboardAuthContext extends AuthContext { constructor(protocol, username, service, method, submethods, cb) { super(protocol, username, service, method, cb); this._multistep = true; this._cb = undefined; this._onInfoResponse = (responses) => { const callback = this._cb; if (callback) { this._cb = undefined; callback(responses); } }; this.submethods = submethods; this.on('abort', () => { this._cb && this._cb(new Error('Authentication request aborted')); }); } prompt(prompts, title, instructions, cb) { if (!Array.isArray(prompts)) prompts = [ prompts ]; if (typeof title === 'function') { cb = title; title = instructions = undefined; } else if (typeof instructions === 'function') { cb = instructions; instructions = undefined; } else if (typeof cb !== 'function') { cb = undefined; } for (let i = 0; i < prompts.length; ++i) { if (typeof prompts[i] === 'string') { prompts[i] = { prompt: prompts[i], echo: true }; } } this._cb = cb; this._initialResponse = true; this._protocol.authInfoReq(title, instructions, prompts); } } class PKAuthContext extends AuthContext { constructor(protocol, username, service, method, pkInfo, cb) { super(protocol, username, service, method, cb); this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; this.hashAlgo = pkInfo.hashAlgo; this.signature = pkInfo.signature; this.blob = pkInfo.blob; } accept() { if (!this.signature) { this._initialResponse = true; this._protocol.authPKOK(this.key.algo, this.key.data); } else { AuthContext.prototype.accept.call(this); } } } class HostbasedAuthContext extends AuthContext { constructor(protocol, username, service, method, pkInfo, cb) { super(protocol, username, service, method, cb); this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; this.hashAlgo = pkInfo.hashAlgo; this.signature = pkInfo.signature; this.blob = pkInfo.blob; this.localHostname = pkInfo.localHostname; this.localUsername = pkInfo.localUsername; } } class PwdAuthContext extends AuthContext { constructor(protocol, username, service, method, password, cb) { super(protocol, username, service, method, cb); this.password = password; this._changeCb = undefined; } requestChange(prompt, cb) { if (this._changeCb) throw new Error('Change request already in progress'); if (typeof prompt !== 'string') throw new Error('prompt argument must be a string'); if (typeof cb !== 'function') throw new Error('Callback argument must be a function'); this._changeCb = cb; this._protocol.authPasswdChg(prompt); } } class Session extends EventEmitter { constructor(client, info, localChan) { super(); this.type = 'session'; this.subtype = undefined; this.server = true; this._ending = false; this._channel = undefined; this._chanInfo = { type: 'session', incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; } } class Server extends EventEmitter { constructor(cfg, listener) { super(); if (typeof cfg !== 'object' || cfg === null) throw new Error('Missing configuration object'); const hostKeys = Object.create(null); const hostKeyAlgoOrder = []; const hostKeys_ = cfg.hostKeys; if (!Array.isArray(hostKeys_)) throw new Error('hostKeys must be an array'); const cfgAlgos = ( typeof cfg.algorithms === 'object' && cfg.algorithms !== null ? cfg.algorithms : {} ); const hostKeyAlgos = generateAlgorithmList( cfgAlgos.serverHostKey, DEFAULT_SERVER_HOST_KEY, SUPPORTED_SERVER_HOST_KEY ); for (let i = 0; i < hostKeys_.length; ++i) { let privateKey; if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') privateKey = parseKey(hostKeys_[i]); else privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); if (privateKey instanceof Error) throw new Error(`Cannot parse privateKey: ${privateKey.message}`); if (Array.isArray(privateKey)) { // OpenSSH's newer format only stores 1 key for now privateKey = privateKey[0]; } if (privateKey.getPrivatePEM() === null) throw new Error('privateKey value contains an invalid private key'); // Discard key if we already found a key of the same type if (hostKeyAlgoOrder.includes(privateKey.type)) continue; if (privateKey.type === 'ssh-rsa') { // SSH supports multiple signature hashing algorithms for RSA, so we add // the algorithms in the desired order let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); if (sha1Pos === -1) { // Fall back to giving SHA1 the lowest priority sha1Pos = Infinity; } [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { if (pos === -1) return; let type; switch (pos) { case sha1Pos: type = 'ssh-rsa'; break; case sha256Pos: type = 'rsa-sha2-256'; break; case sha512Pos: type = 'rsa-sha2-512'; break; default: return; } // Store same RSA key under each hash algorithm name for convenience hostKeys[type] = privateKey; hostKeyAlgoOrder.push(type); }); } else { hostKeys[privateKey.type] = privateKey; hostKeyAlgoOrder.push(privateKey.type); } } const algorithms = { kex: generateAlgorithmList( cfgAlgos.kex, DEFAULT_KEX, SUPPORTED_KEX ).concat(['kex-strict-s-v00@openssh.com']), serverHostKey: hostKeyAlgoOrder, cs: { cipher: generateAlgorithmList( cfgAlgos.cipher, DEFAULT_CIPHER, SUPPORTED_CIPHER ), mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), compress: generateAlgorithmList( cfgAlgos.compress, DEFAULT_COMPRESSION, SUPPORTED_COMPRESSION ), lang: [], }, sc: undefined, }; algorithms.sc = algorithms.cs; if (typeof listener === 'function') this.on('connection', listener); const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); const offer = new KexInit(algorithms); this._srv = new netServer((socket) => { if (this._connections >= this.maxConnections) { socket.destroy(); return; } ++this._connections; socket.once('close', () => { --this._connections; }); let debug; if (origDebug) { // Prepend debug output with a unique identifier in case there are // multiple clients connected at the same time const debugPrefix = `[${process.hrtime().join('.')}] `; debug = (msg) => { origDebug(`${debugPrefix}${msg}`); }; } // eslint-disable-next-line no-use-before-define new Client(socket, hostKeys, ident, offer, debug, this, cfg); }).on('error', (err) => { this.emit('error', err); }).on('listening', () => { this.emit('listening'); }).on('close', () => { this.emit('close'); }); this._connections = 0; this.maxConnections = Infinity; } injectSocket(socket) { this._srv.emit('connection', socket); } listen(...args) { this._srv.listen(...args); return this; } address() { return this._srv.address(); } getConnections(cb) { this._srv.getConnections(cb); return this; } close(cb) { this._srv.close(cb); return this; } ref() { this._srv.ref(); return this; } unref() { this._srv.unref(); return this; } } Server.KEEPALIVE_CLIENT_INTERVAL = 15000; Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; class Client extends EventEmitter { constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { super(); let exchanges = 0; let acceptedAuthSvc = false; let pendingAuths = []; let authCtx; let kaTimer; let onPacket; const unsentGlobalRequestsReplies = []; this._sock = socket; this._chanMgr = new ChannelManager(this); this._debug = debug; this.noMoreSessions = false; this.authenticated = false; // Silence pre-header errors function onClientPreHeaderError(err) {} this.on('error', onClientPreHeaderError); const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { debug(`Debug output from client: ${JSON.stringify(msg)}`); }); const kaIntvl = ( typeof srvCfg.keepaliveInterval === 'number' && isFinite(srvCfg.keepaliveInterval) && srvCfg.keepaliveInterval > 0 ? srvCfg.keepaliveInterval : ( typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) && Server.KEEPALIVE_CLIENT_INTERVAL > 0 ? Server.KEEPALIVE_CLIENT_INTERVAL : -1 ) ); const kaCountMax = ( typeof srvCfg.keepaliveCountMax === 'number' && isFinite(srvCfg.keepaliveCountMax) && srvCfg.keepaliveCountMax >= 0 ? srvCfg.keepaliveCountMax : ( typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 ? Server.KEEPALIVE_CLIENT_COUNT_MAX : -1 ) ); let kaCurCount = 0; if (kaIntvl !== -1 && kaCountMax !== -1) { this.once('ready', () => { const onClose = () => { clearInterval(kaTimer); }; this.on('close', onClose).on('end', onClose); kaTimer = setInterval(() => { if (++kaCurCount > kaCountMax) { clearInterval(kaTimer); const err = new Error('Keepalive timeout'); err.level = 'client-timeout'; this.emit('error', err); this.end(); } else { // XXX: if the server ever starts sending real global requests to // the client, we will need to add a dummy callback here to // keep the correct reply order proto.ping(); } }, kaIntvl); }); // TODO: re-verify keepalive behavior with OpenSSH onPacket = () => { kaTimer && kaTimer.refresh(); kaCurCount = 0; }; } const proto = this._protocol = new Protocol({ server: true, hostKeys, ident, offer, onPacket, greeting: srvCfg.greeting, banner: srvCfg.banner, onWrite: (data) => { if (isWritable(socket)) socket.write(data); }, onError: (err) => { if (!proto._destruct) socket.removeAllListeners('data'); this.emit('error', err); try { socket.end(); } catch {} }, onHeader: (header) => { this.removeListener('error', onClientPreHeaderError); const info = { ip: socket.remoteAddress, family: socket.remoteFamily, port: socket.remotePort, header, }; if (!server.emit('connection', this, info)) { // auto reject proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); socket.end(); return; } if (header.greeting) this.emit('greeting', header.greeting); }, onHandshakeComplete: (negotiated) => { if (++exchanges > 1) this.emit('rekey'); this.emit('handshake', negotiated); }, debug, messageHandlers: { DEBUG: DEBUG_HANDLER, DISCONNECT: (p, reason, desc) => { if (reason !== DISCONNECT_REASON.BY_APPLICATION) { if (!desc) { desc = DISCONNECT_REASON_BY_VALUE[reason]; if (desc === undefined) desc = `Unexpected disconnection reason: ${reason}`; } const err = new Error(desc); err.code = reason; this.emit('error', err); } socket.end(); }, CHANNEL_OPEN: (p, info) => { // Handle incoming requests from client // Do early reject in some cases to prevent wasteful channel // allocation if ((info.type === 'session' && this.noMoreSessions) || !this.authenticated) { const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; return proto.channelOpenFail(info.sender, reasonCode); } let localChan = -1; let reason; let replied = false; let accept; const reject = () => { if (replied) return; replied = true; if (reason === undefined) { if (localChan === -1) reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; else reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; } if (localChan !== -1) this._chanMgr.remove(localChan); proto.channelOpenFail(info.sender, reason, ''); }; const reserveChannel = () => { localChan = this._chanMgr.add(); if (localChan === -1) { reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; if (debug) { debug('Automatic rejection of incoming channel open: ' + 'no channels available'); } } return (localChan !== -1); }; const data = info.data; switch (info.type) { case 'session': if (listenerCount(this, 'session') && reserveChannel()) { accept = () => { if (replied) return; replied = true; const instance = new Session(this, info, localChan); this._chanMgr.update(localChan, instance); proto.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return instance; }; this.emit('session', accept, reject); return; } break; case 'direct-tcpip': if (listenerCount(this, 'tcpip') && reserveChannel()) { accept = () => { if (replied) return; replied = true; const chanInfo = { type: undefined, incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const stream = new Channel(this, chanInfo, { server: true }); this._chanMgr.update(localChan, stream); proto.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return stream; }; this.emit('tcpip', accept, reject, data); return; } break; case 'direct-streamlocal@openssh.com': if (listenerCount(this, 'openssh.streamlocal') && reserveChannel()) { accept = () => { if (replied) return; replied = true; const chanInfo = { type: undefined, incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const stream = new Channel(this, chanInfo, { server: true }); this._chanMgr.update(localChan, stream); proto.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return stream; }; this.emit('openssh.streamlocal', accept, reject, data); return; } break; default: // Automatically reject any unsupported channel open requests reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; if (debug) { debug('Automatic rejection of unsupported incoming channel open' + ` type: ${info.type}`); } } if (reason === undefined) { reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; if (debug) { debug('Automatic rejection of unexpected incoming channel open' + ` for: ${info.type}`); } } reject(); }, CHANNEL_OPEN_CONFIRMATION: (p, info) => { const channel = this._chanMgr.get(info.recipient); if (typeof channel !== 'function') return; const chanInfo = { type: channel.type, incoming: { id: info.recipient, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const instance = new Channel(this, chanInfo, { server: true }); this._chanMgr.update(info.recipient, instance); channel(undefined, instance); }, CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { const channel = this._chanMgr.get(recipient); if (typeof channel !== 'function') return; const info = { reason, description }; onChannelOpenFailure(this, recipient, info, channel); }, CHANNEL_DATA: (p, recipient, data) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel = channel._channel; if (!channel) return; } // The remote party should not be sending us data if there is no // window space available ... // TODO: raise error on data with not enough window? if (channel.incoming.window === 0) return; channel.incoming.window -= data.length; if (channel.push(data) === false) { channel._waitChanDrain = true; return; } if (channel.incoming.window <= WINDOW_THRESHOLD) windowAdjust(channel); }, CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { // NOOP -- should not be sent by client }, CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel = channel._channel; if (!channel) return; } // The other side is allowing us to send `amount` more bytes of data channel.outgoing.window += amount; if (channel._waitWindow) { channel._waitWindow = false; if (channel._chunk) { channel._write(channel._chunk, null, channel._chunkcb); } else if (channel._chunkcb) { channel._chunkcb(); } else if (channel._chunkErr) { channel.stderr._write(channel._chunkErr, null, channel._chunkcbErr); } else if (channel._chunkcbErr) { channel._chunkcbErr(); } } }, CHANNEL_SUCCESS: (p, recipient) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel = channel._channel; if (!channel) return; } if (channel._callbacks.length) channel._callbacks.shift()(false); }, CHANNEL_FAILURE: (p, recipient) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel = channel._channel; if (!channel) return; } if (channel._callbacks.length) channel._callbacks.shift()(true); }, CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { const session = this._chanMgr.get(recipient); if (typeof session !== 'object' || session === null) return; let replied = false; let accept; let reject; if (session.constructor !== Session) { // normal Channel instance if (wantReply) proto.channelFailure(session.outgoing.id); return; } if (wantReply) { // "real session" requests will have custom accept behaviors if (type !== 'shell' && type !== 'exec' && type !== 'subsystem') { accept = () => { if (replied || session._ending || session._channel) return; replied = true; proto.channelSuccess(session._chanInfo.outgoing.id); }; } reject = () => { if (replied || session._ending || session._channel) return; replied = true; proto.channelFailure(session._chanInfo.outgoing.id); }; } if (session._ending) { reject && reject(); return; } switch (type) { // "pre-real session start" requests case 'env': if (listenerCount(session, 'env')) { session.emit('env', accept, reject, { key: data.name, val: data.value }); return; } break; case 'pty-req': if (listenerCount(session, 'pty')) { session.emit('pty', accept, reject, data); return; } break; case 'window-change': if (listenerCount(session, 'window-change')) session.emit('window-change', accept, reject, data); else reject && reject(); break; case 'x11-req': if (listenerCount(session, 'x11')) { session.emit('x11', accept, reject, data); return; } break; // "post-real session start" requests case 'signal': if (listenerCount(session, 'signal')) { session.emit('signal', accept, reject, { name: data }); return; } break; // XXX: is `auth-agent-req@openssh.com` really "post-real session // start"? case 'auth-agent-req@openssh.com': if (listenerCount(session, 'auth-agent')) { session.emit('auth-agent', accept, reject); return; } break; // "real session start" requests case 'shell': if (listenerCount(session, 'shell')) { accept = () => { if (replied || session._ending || session._channel) return; replied = true; if (wantReply) proto.channelSuccess(session._chanInfo.outgoing.id); const channel = new Channel( this, session._chanInfo, { server: true } ); channel.subtype = session.subtype = type; session._channel = channel; return channel; }; session.emit('shell', accept, reject); return; } break; case 'exec': if (listenerCount(session, 'exec')) { accept = () => { if (replied || session._ending || session._channel) return; replied = true; if (wantReply) proto.channelSuccess(session._chanInfo.outgoing.id); const channel = new Channel( this, session._chanInfo, { server: true } ); channel.subtype = session.subtype = type; session._channel = channel; return channel; }; session.emit('exec', accept, reject, { command: data }); return; } break; case 'subsystem': { let useSFTP = (data === 'sftp'); accept = () => { if (replied || session._ending || session._channel) return; replied = true; if (wantReply) proto.channelSuccess(session._chanInfo.outgoing.id); let instance; if (useSFTP) { instance = new SFTP(this, session._chanInfo, { server: true, debug, }); } else { instance = new Channel( this, session._chanInfo, { server: true } ); instance.subtype = session.subtype = `${type}:${data}`; } session._channel = instance; return instance; }; if (data === 'sftp') { if (listenerCount(session, 'sftp')) { session.emit('sftp', accept, reject); return; } useSFTP = false; } if (listenerCount(session, 'subsystem')) { session.emit('subsystem', accept, reject, { name: data }); return; } break; } } debug && debug( `Automatic rejection of incoming channel request: ${type}` ); reject && reject(); }, CHANNEL_EOF: (p, recipient) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { if (!channel._ending) { channel._ending = true; channel.emit('eof'); channel.emit('end'); } channel = channel._channel; if (!channel) return; } if (channel.incoming.state !== 'open') return; channel.incoming.state = 'eof'; if (channel.readable) channel.push(null); }, CHANNEL_CLOSE: (p, recipient) => { let channel = this._chanMgr.get(recipient); if (typeof channel !== 'object' || channel === null) return; if (channel.constructor === Session) { channel._ending = true; channel.emit('close'); channel = channel._channel; if (!channel) return; } onCHANNEL_CLOSE(this, recipient, channel); }, // Begin service/auth-related ========================================== SERVICE_REQUEST: (p, service) => { if (exchanges === 0 || acceptedAuthSvc || this.authenticated || service !== 'ssh-userauth') { proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); socket.end(); return; } acceptedAuthSvc = true; proto.serviceAccept(service); }, USERAUTH_REQUEST: (p, username, service, method, methodData) => { if (exchanges === 0 || this.authenticated || (authCtx && (authCtx.username !== username || authCtx.service !== service)) // TODO: support hostbased auth || (method !== 'password' && method !== 'publickey' && method !== 'hostbased' && method !== 'keyboard-interactive' && method !== 'none') || pendingAuths.length === MAX_PENDING_AUTHS) { proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); socket.end(); return; } else if (service !== 'ssh-connection') { proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); socket.end(); return; } let ctx; switch (method) { case 'keyboard-interactive': ctx = new KeyboardAuthContext(proto, username, service, method, methodData, onAuthDecide); break; case 'publickey': ctx = new PKAuthContext(proto, username, service, method, methodData, onAuthDecide); break; case 'hostbased': ctx = new HostbasedAuthContext(proto, username, service, method, methodData, onAuthDecide); break; case 'password': if (authCtx && authCtx instanceof PwdAuthContext && authCtx._changeCb) { const cb = authCtx._changeCb; authCtx._changeCb = undefined; cb(methodData.newPassword); return; } ctx = new PwdAuthContext(proto, username, service, method, methodData, onAuthDecide); break; case 'none': ctx = new AuthContext(proto, username, service, method, onAuthDecide); break; } if (authCtx) { if (!authCtx._initialResponse) { return pendingAuths.push(ctx); } else if (authCtx._multistep && !authCtx._finalResponse) { // RFC 4252 says to silently abort the current auth request if a // new auth request comes in before the final response from an // auth method that requires additional request/response exchanges // -- this means keyboard-interactive for now ... authCtx._cleanup && authCtx._cleanup(); authCtx.emit('abort'); } } authCtx = ctx; if (listenerCount(this, 'authentication')) this.emit('authentication', authCtx); else authCtx.reject(); }, USERAUTH_INFO_RESPONSE: (p, responses) => { if (authCtx && authCtx instanceof KeyboardAuthContext) authCtx._onInfoResponse(responses); }, // End service/auth-related ============================================ GLOBAL_REQUEST: (p, name, wantReply, data) => { const reply = { type: null, buf: null }; function setReply(type, buf) { reply.type = type; reply.buf = buf; sendReplies(); } if (wantReply) unsentGlobalRequestsReplies.push(reply); if ((name === 'tcpip-forward' || name === 'cancel-tcpip-forward' || name === 'no-more-sessions@openssh.com' || name === 'streamlocal-forward@openssh.com' || name === 'cancel-streamlocal-forward@openssh.com') && listenerCount(this, 'request') && this.authenticated) { let accept; let reject; if (wantReply) { let replied = false; accept = (chosenPort) => { if (replied) return; replied = true; let bufPort; if (name === 'tcpip-forward' && data.bindPort === 0 && typeof chosenPort === 'number') { bufPort = Buffer.allocUnsafe(4); writeUInt32BE(bufPort, chosenPort, 0); } setReply('SUCCESS', bufPort); }; reject = () => { if (replied) return; replied = true; setReply('FAILURE'); }; } if (name === 'no-more-sessions@openssh.com') { this.noMoreSessions = true; accept && accept(); return; } this.emit('request', accept, reject, name, data); } else if (wantReply) { setReply('FAILURE'); } }, }, }); socket.pause(); cryptoInit.then(() => { proto.start(); socket.on('data', (data) => { try { proto.parse(data, 0, data.length); } catch (ex) { this.emit('error', ex); try { if (isWritable(socket)) socket.end(); } catch {} } }); socket.resume(); }).catch((err) => { this.emit('error', err); try { if (isWritable(socket)) socket.end(); } catch {} }); socket.on('error', (err) => { err.level = 'socket'; this.emit('error', err); }).once('end', () => { debug && debug('Socket ended'); proto.cleanup(); this.emit('end'); }).once('close', () => { debug && debug('Socket closed'); proto.cleanup(); this.emit('close'); const err = new Error('No response from server'); // Simulate error for pending channels and close any open channels this._chanMgr.cleanup(err); }); const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { if (authCtx === ctx && !this.authenticated) { if (allowed) { authCtx = undefined; this.authenticated = true; proto.authSuccess(); pendingAuths = []; this.emit('ready'); } else { proto.authFailure(methodsLeft, isPartial); if (pendingAuths.length) { authCtx = pendingAuths.pop(); if (listenerCount(this, 'authentication')) this.emit('authentication', authCtx); else authCtx.reject(); } } } }; function sendReplies() { while (unsentGlobalRequestsReplies.length > 0 && unsentGlobalRequestsReplies[0].type) { const reply = unsentGlobalRequestsReplies.shift(); if (reply.type === 'SUCCESS') proto.requestSuccess(reply.buf); if (reply.type === 'FAILURE') proto.requestFailure(); } } } end() { if (this._sock && isWritable(this._sock)) { this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); this._sock.end(); } return this; } x11(originAddr, originPort, cb) { const opts = { originAddr, originPort }; openChannel(this, 'x11', opts, cb); return this; } forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { const opts = { boundAddr, boundPort, remoteAddr, remotePort }; openChannel(this, 'forwarded-tcpip', opts, cb); return this; } openssh_forwardOutStreamLocal(socketPath, cb) { const opts = { socketPath }; openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); return this; } rekey(cb) { let error; try { this._protocol.rekey(); } catch (ex) { error = ex; } // TODO: re-throw error if no callback? if (typeof cb === 'function') { if (error) process.nextTick(cb, error); else this.once('rekey', cb); } } setNoDelay(noDelay) { if (this._sock && typeof this._sock.setNoDelay === 'function') this._sock.setNoDelay(noDelay); return this; } } function openChannel(self, type, opts, cb) { // Ask the client to open a channel for some purpose (e.g. a forwarded TCP // connection) const initWindow = MAX_WINDOW; const maxPacket = PACKET_SIZE; if (typeof opts === 'function') { cb = opts; opts = {}; } const wrapper = (err, stream) => { cb(err, stream); }; wrapper.type = type; const localChan = self._chanMgr.add(wrapper); if (localChan === -1) { cb(new Error('No free channels available')); return; } switch (type) { case 'forwarded-tcpip': self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); break; case 'x11': self._protocol.x11(localChan, initWindow, maxPacket, opts); break; case 'forwarded-streamlocal@openssh.com': self._protocol.openssh_forwardedStreamLocal( localChan, initWindow, maxPacket, opts ); break; default: throw new Error(`Unsupported channel type: ${type}`); } } function compareNumbers(a, b) { return a - b; } module.exports = Server; module.exports.IncomingClient = Client; /***/ }), /***/ 2137: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { SFTP } = __nccwpck_require__(4996); const MAX_CHANNEL = 2 ** 32 - 1; function onChannelOpenFailure(self, recipient, info, cb) { self._chanMgr.remove(recipient); if (typeof cb !== 'function') return; let err; if (info instanceof Error) { err = info; } else if (typeof info === 'object' && info !== null) { err = new Error(`(SSH) Channel open failure: ${info.description}`); err.reason = info.reason; } else { err = new Error( '(SSH) Channel open failure: server closed channel unexpectedly' ); err.reason = ''; } cb(err); } function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { if (typeof channel === 'function') { // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when // requesting to open a channel onChannelOpenFailure(self, recipient, err, channel); return; } if (typeof channel !== 'object' || channel === null) return; if (channel.incoming && channel.incoming.state === 'closed') return; self._chanMgr.remove(recipient); if (channel.server && channel.constructor.name === 'Session') return; channel.incoming.state = 'closed'; if (channel.readable) channel.push(null); if (channel.server) { if (channel.stderr.writable) channel.stderr.end(); } else if (channel.stderr.readable) { channel.stderr.push(null); } if (channel.constructor !== SFTP && (channel.outgoing.state === 'open' || channel.outgoing.state === 'eof') && !dead) { channel.close(); } if (channel.outgoing.state === 'closing') channel.outgoing.state = 'closed'; const readState = channel._readableState; const writeState = channel._writableState; if (writeState && !writeState.ending && !writeState.finished && !dead) channel.end(); // Take care of any outstanding channel requests const chanCallbacks = channel._callbacks; channel._callbacks = []; for (let i = 0; i < chanCallbacks.length; ++i) chanCallbacks[i](true); if (channel.server) { if (!channel.readable || channel.destroyed || (readState && readState.endEmitted)) { channel.emit('close'); } else { channel.once('end', () => channel.emit('close')); } } else { let doClose; switch (channel.type) { case 'direct-streamlocal@openssh.com': case 'direct-tcpip': doClose = () => channel.emit('close'); break; default: { // Align more with node child processes, where the close event gets // the same arguments as the exit event const exit = channel._exit; doClose = () => { if (exit.code === null) channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); else channel.emit('close', exit.code); }; } } if (!channel.readable || channel.destroyed || (readState && readState.endEmitted)) { doClose(); } else { channel.once('end', doClose); } const errReadState = channel.stderr._readableState; if (!channel.stderr.readable || channel.stderr.destroyed || (errReadState && errReadState.endEmitted)) { channel.stderr.emit('close'); } else { channel.stderr.once('end', () => channel.stderr.emit('close')); } } } class ChannelManager { constructor(client) { this._client = client; this._channels = {}; this._cur = -1; this._count = 0; } add(val) { // Attempt to reserve an id let id; // Optimized paths if (this._cur < MAX_CHANNEL) { id = ++this._cur; } else if (this._count === 0) { // Revert and reset back to fast path once we no longer have any channels // open this._cur = 0; id = 0; } else { // Slower lookup path // This path is triggered we have opened at least MAX_CHANNEL channels // while having at least one channel open at any given time, so we have // to search for a free id. const channels = this._channels; for (let i = 0; i < MAX_CHANNEL; ++i) { if (channels[i] === undefined) { id = i; break; } } } if (id === undefined) return -1; this._channels[id] = (val || true); ++this._count; return id; } update(id, val) { if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) throw new Error(`Invalid channel id: ${id}`); if (val && this._channels[id]) this._channels[id] = val; } get(id) { if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) throw new Error(`Invalid channel id: ${id}`); return this._channels[id]; } remove(id) { if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) throw new Error(`Invalid channel id: ${id}`); if (this._channels[id]) { delete this._channels[id]; if (this._count) --this._count; } } cleanup(err) { const channels = this._channels; this._channels = {}; this._cur = -1; this._count = 0; const chanIDs = Object.keys(channels); const client = this._client; for (let i = 0; i < chanIDs.length; ++i) { const id = +chanIDs[i]; const channel = channels[id]; onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); } } } const isRegExp = (() => { const toString = Object.prototype.toString; return (val) => toString.call(val) === '[object RegExp]'; })(); function generateAlgorithmList(algoList, defaultList, supportedList) { if (Array.isArray(algoList) && algoList.length > 0) { // Exact list for (let i = 0; i < algoList.length; ++i) { if (supportedList.indexOf(algoList[i]) === -1) throw new Error(`Unsupported algorithm: ${algoList[i]}`); } return algoList; } if (typeof algoList === 'object' && algoList !== null) { // Operations based on the default list const keys = Object.keys(algoList); let list = defaultList; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; let val = algoList[key]; switch (key) { case 'append': if (!Array.isArray(val)) val = [val]; if (Array.isArray(val)) { for (let j = 0; j < val.length; ++j) { const append = val[j]; if (typeof append === 'string') { if (!append || list.indexOf(append) !== -1) continue; if (supportedList.indexOf(append) === -1) throw new Error(`Unsupported algorithm: ${append}`); if (list === defaultList) list = list.slice(); list.push(append); } else if (isRegExp(append)) { for (let k = 0; k < supportedList.length; ++k) { const algo = supportedList[k]; if (append.test(algo)) { if (list.indexOf(algo) !== -1) continue; if (list === defaultList) list = list.slice(); list.push(algo); } } } } } break; case 'prepend': if (!Array.isArray(val)) val = [val]; if (Array.isArray(val)) { for (let j = val.length; j >= 0; --j) { const prepend = val[j]; if (typeof prepend === 'string') { if (!prepend || list.indexOf(prepend) !== -1) continue; if (supportedList.indexOf(prepend) === -1) throw new Error(`Unsupported algorithm: ${prepend}`); if (list === defaultList) list = list.slice(); list.unshift(prepend); } else if (isRegExp(prepend)) { for (let k = supportedList.length; k >= 0; --k) { const algo = supportedList[k]; if (prepend.test(algo)) { if (list.indexOf(algo) !== -1) continue; if (list === defaultList) list = list.slice(); list.unshift(algo); } } } } } break; case 'remove': if (!Array.isArray(val)) val = [val]; if (Array.isArray(val)) { for (let j = 0; j < val.length; ++j) { const search = val[j]; if (typeof search === 'string') { if (!search) continue; const idx = list.indexOf(search); if (idx === -1) continue; if (list === defaultList) list = list.slice(); list.splice(idx, 1); } else if (isRegExp(search)) { for (let k = 0; k < list.length; ++k) { if (search.test(list[k])) { if (list === defaultList) list = list.slice(); list.splice(k, 1); --k; } } } } } break; } } return list; } return defaultList; } module.exports = { ChannelManager, generateAlgorithmList, onChannelOpenFailure, onCHANNEL_CLOSE, isWritable: (stream) => { // XXX: hack to workaround regression in node // See: https://github.com/nodejs/node/issues/36029 return (stream && stream.writable && stream._readableState && stream._readableState.ended === false); }, }; /***/ }), /***/ 9026: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool */ var EventEmitter = (__nccwpck_require__(4434).EventEmitter), inherits = (__nccwpck_require__(9023).inherits); function jsmemcmp(buf1, pos1, buf2, pos2, num) { for (var i = 0; i < num; ++i, ++pos1, ++pos2) if (buf1[pos1] !== buf2[pos2]) return false; return true; } function SBMH(needle) { if (typeof needle === 'string') needle = new Buffer(needle); var i, j, needle_len = needle.length; this.maxMatches = Infinity; this.matches = 0; this._occ = new Array(256); this._lookbehind_size = 0; this._needle = needle; this._bufpos = 0; this._lookbehind = new Buffer(needle_len); // Initialize occurrence table. for (j = 0; j < 256; ++j) this._occ[j] = needle_len; // Populate occurrence table with analysis of the needle, // ignoring last letter. if (needle_len >= 1) { for (i = 0; i < needle_len - 1; ++i) this._occ[needle[i]] = needle_len - 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) { var r, chlen; if (!Buffer.isBuffer(chunk)) chunk = new Buffer(chunk, 'binary'); chlen = chunk.length; this._bufpos = pos || 0; while (r !== chlen && this.matches < this.maxMatches) r = this._sbmh_feed(chunk); return r; }; SBMH.prototype._sbmh_feed = function(data) { var len = data.length, needle = this._needle, needle_len = needle.length; // 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] var pos = -this._lookbehind_size, last_needle_char = needle[needle_len - 1], occ = this._occ, lookbehind = this._lookbehind; 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 - needle_len) { var ch = this._sbmh_lookup_char(data, pos + needle_len - 1); if (ch === last_needle_char && this._sbmh_memcmp(data, pos, needle_len - 1)) { this._lookbehind_size = 0; ++this.matches; if (pos > -this._lookbehind_size) this.emit('info', true, lookbehind, 0, this._lookbehind_size + pos); else this.emit('info', true); this._bufpos = pos + needle_len; return pos + needle_len; } else pos += 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, 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. var bytesToCutOff = this._lookbehind_size + pos; if (bytesToCutOff > 0) { // The cut off data is guaranteed not to contain the needle. this.emit('info', false, lookbehind, 0, bytesToCutOff); } lookbehind.copy(lookbehind, 0, bytesToCutOff, this._lookbehind_size - bytesToCutOff); this._lookbehind_size -= bytesToCutOff; data.copy(lookbehind, this._lookbehind_size); this._lookbehind_size += len; this._bufpos = len; return len; } } if (pos >= 0) pos += this._bufpos; // Lookbehind buffer is now empty. Perform Boyer-Moore-Horspool // search with optimized character lookup code that only considers // the current round's haystack data. while (pos <= len - needle_len) { var ch = data[pos + needle_len - 1]; if (ch === last_needle_char && data[pos] === needle[0] && jsmemcmp(needle, 0, data, pos, needle_len - 1)) { ++this.matches; if (pos > 0) this.emit('info', true, data, this._bufpos, pos); else this.emit('info', true); this._bufpos = pos + needle_len; return pos + needle_len; } else pos += occ[ch]; } // 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. if (pos < len) { while (pos < len && (data[pos] !== needle[0] || !jsmemcmp(data, pos, needle, 0, len - pos))) { ++pos; } if (pos < len) { data.copy(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) { if (pos < 0) return this._lookbehind[this._lookbehind_size + pos]; else return data[pos]; } SBMH.prototype._sbmh_memcmp = function(data, pos, len) { var i = 0; while (i < len) { if (this._sbmh_lookup_char(data, pos + i) === this._needle[i]) ++i; else return false; } return true; } module.exports = SBMH; /***/ }), /***/ 770: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(218); /***/ }), /***/ 218: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var net = __nccwpck_require__(9278); var tls = __nccwpck_require__(4756); var http = __nccwpck_require__(8611); var https = __nccwpck_require__(5692); var events = __nccwpck_require__(4434); var assert = __nccwpck_require__(2613); var util = __nccwpck_require__(9023); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port, localAddress) { var options = toOptions(host, port, localAddress); for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === options.host && pending.port === options.port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self = this; var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push(options); return; } // If we are under maxSockets create a new one. self.createSocket(options, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, options); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false, headers: { host: options.host + ':' + options.port } }); if (options.localAddress) { connectOptions.localAddress = options.localAddress; } if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); socket.destroy(); var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } if (head.length > 0) { debug('got illegal response body from proxy'); socket.destroy(); var error = new Error('got illegal response body from proxy'); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { var hostHeader = options.request.getHeader('host'); var tlsOptions = mergeOptions({}, self.options, { socket: socket, servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host }); // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, tlsOptions); self.sockets[self.sockets.indexOf(socket)] = secureSocket; cb(secureSocket); }); } function toOptions(host, port, localAddress) { if (typeof host === 'string') { // since v0.10 return { host: host, port: port, localAddress: localAddress }; } return host; // for v0.11 or later } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test /***/ }), /***/ 668: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { (function(nacl) { 'use strict'; // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. // Public domain. // // Implementation derived from TweetNaCl version 20140427. // See for details: http://tweetnacl.cr.yp.to/ var gf = function(init) { var i, r = new Float64Array(16); if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; return r; }; // Pluggable, initialized in high-level API below. var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; var _0 = new Uint8Array(16); var _9 = new Uint8Array(32); _9[0] = 9; var gf0 = gf(), gf1 = gf([1]), _121665 = gf([0xdb41, 1]), D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); function ts64(x, i, h, l) { x[i] = (h >> 24) & 0xff; x[i+1] = (h >> 16) & 0xff; x[i+2] = (h >> 8) & 0xff; x[i+3] = h & 0xff; x[i+4] = (l >> 24) & 0xff; x[i+5] = (l >> 16) & 0xff; x[i+6] = (l >> 8) & 0xff; x[i+7] = l & 0xff; } function vn(x, xi, y, yi, n) { var i,d = 0; for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; return (1 & ((d - 1) >>> 8)) - 1; } function crypto_verify_16(x, xi, y, yi) { return vn(x,xi,y,yi,16); } function crypto_verify_32(x, xi, y, yi) { return vn(x,xi,y,yi,32); } function core_salsa20(o, p, k, c) { var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u<<7 | u>>>(32-7); u = x4 + x0 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x4 | 0; x12 ^= u<<13 | u>>>(32-13); u = x12 + x8 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x1 | 0; x9 ^= u<<7 | u>>>(32-7); u = x9 + x5 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x9 | 0; x1 ^= u<<13 | u>>>(32-13); u = x1 + x13 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x6 | 0; x14 ^= u<<7 | u>>>(32-7); u = x14 + x10 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x14 | 0; x6 ^= u<<13 | u>>>(32-13); u = x6 + x2 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x11 | 0; x3 ^= u<<7 | u>>>(32-7); u = x3 + x15 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x3 | 0; x11 ^= u<<13 | u>>>(32-13); u = x11 + x7 | 0; x15 ^= u<<18 | u>>>(32-18); u = x0 + x3 | 0; x1 ^= u<<7 | u>>>(32-7); u = x1 + x0 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x1 | 0; x3 ^= u<<13 | u>>>(32-13); u = x3 + x2 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x4 | 0; x6 ^= u<<7 | u>>>(32-7); u = x6 + x5 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x6 | 0; x4 ^= u<<13 | u>>>(32-13); u = x4 + x7 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x9 | 0; x11 ^= u<<7 | u>>>(32-7); u = x11 + x10 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x11 | 0; x9 ^= u<<13 | u>>>(32-13); u = x9 + x8 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x14 | 0; x12 ^= u<<7 | u>>>(32-7); u = x12 + x15 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x12 | 0; x14 ^= u<<13 | u>>>(32-13); u = x14 + x13 | 0; x15 ^= u<<18 | u>>>(32-18); } x0 = x0 + j0 | 0; x1 = x1 + j1 | 0; x2 = x2 + j2 | 0; x3 = x3 + j3 | 0; x4 = x4 + j4 | 0; x5 = x5 + j5 | 0; x6 = x6 + j6 | 0; x7 = x7 + j7 | 0; x8 = x8 + j8 | 0; x9 = x9 + j9 | 0; x10 = x10 + j10 | 0; x11 = x11 + j11 | 0; x12 = x12 + j12 | 0; x13 = x13 + j13 | 0; x14 = x14 + j14 | 0; x15 = x15 + j15 | 0; o[ 0] = x0 >>> 0 & 0xff; o[ 1] = x0 >>> 8 & 0xff; o[ 2] = x0 >>> 16 & 0xff; o[ 3] = x0 >>> 24 & 0xff; o[ 4] = x1 >>> 0 & 0xff; o[ 5] = x1 >>> 8 & 0xff; o[ 6] = x1 >>> 16 & 0xff; o[ 7] = x1 >>> 24 & 0xff; o[ 8] = x2 >>> 0 & 0xff; o[ 9] = x2 >>> 8 & 0xff; o[10] = x2 >>> 16 & 0xff; o[11] = x2 >>> 24 & 0xff; o[12] = x3 >>> 0 & 0xff; o[13] = x3 >>> 8 & 0xff; o[14] = x3 >>> 16 & 0xff; o[15] = x3 >>> 24 & 0xff; o[16] = x4 >>> 0 & 0xff; o[17] = x4 >>> 8 & 0xff; o[18] = x4 >>> 16 & 0xff; o[19] = x4 >>> 24 & 0xff; o[20] = x5 >>> 0 & 0xff; o[21] = x5 >>> 8 & 0xff; o[22] = x5 >>> 16 & 0xff; o[23] = x5 >>> 24 & 0xff; o[24] = x6 >>> 0 & 0xff; o[25] = x6 >>> 8 & 0xff; o[26] = x6 >>> 16 & 0xff; o[27] = x6 >>> 24 & 0xff; o[28] = x7 >>> 0 & 0xff; o[29] = x7 >>> 8 & 0xff; o[30] = x7 >>> 16 & 0xff; o[31] = x7 >>> 24 & 0xff; o[32] = x8 >>> 0 & 0xff; o[33] = x8 >>> 8 & 0xff; o[34] = x8 >>> 16 & 0xff; o[35] = x8 >>> 24 & 0xff; o[36] = x9 >>> 0 & 0xff; o[37] = x9 >>> 8 & 0xff; o[38] = x9 >>> 16 & 0xff; o[39] = x9 >>> 24 & 0xff; o[40] = x10 >>> 0 & 0xff; o[41] = x10 >>> 8 & 0xff; o[42] = x10 >>> 16 & 0xff; o[43] = x10 >>> 24 & 0xff; o[44] = x11 >>> 0 & 0xff; o[45] = x11 >>> 8 & 0xff; o[46] = x11 >>> 16 & 0xff; o[47] = x11 >>> 24 & 0xff; o[48] = x12 >>> 0 & 0xff; o[49] = x12 >>> 8 & 0xff; o[50] = x12 >>> 16 & 0xff; o[51] = x12 >>> 24 & 0xff; o[52] = x13 >>> 0 & 0xff; o[53] = x13 >>> 8 & 0xff; o[54] = x13 >>> 16 & 0xff; o[55] = x13 >>> 24 & 0xff; o[56] = x14 >>> 0 & 0xff; o[57] = x14 >>> 8 & 0xff; o[58] = x14 >>> 16 & 0xff; o[59] = x14 >>> 24 & 0xff; o[60] = x15 >>> 0 & 0xff; o[61] = x15 >>> 8 & 0xff; o[62] = x15 >>> 16 & 0xff; o[63] = x15 >>> 24 & 0xff; } function core_hsalsa20(o,p,k,c) { var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u<<7 | u>>>(32-7); u = x4 + x0 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x4 | 0; x12 ^= u<<13 | u>>>(32-13); u = x12 + x8 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x1 | 0; x9 ^= u<<7 | u>>>(32-7); u = x9 + x5 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x9 | 0; x1 ^= u<<13 | u>>>(32-13); u = x1 + x13 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x6 | 0; x14 ^= u<<7 | u>>>(32-7); u = x14 + x10 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x14 | 0; x6 ^= u<<13 | u>>>(32-13); u = x6 + x2 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x11 | 0; x3 ^= u<<7 | u>>>(32-7); u = x3 + x15 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x3 | 0; x11 ^= u<<13 | u>>>(32-13); u = x11 + x7 | 0; x15 ^= u<<18 | u>>>(32-18); u = x0 + x3 | 0; x1 ^= u<<7 | u>>>(32-7); u = x1 + x0 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x1 | 0; x3 ^= u<<13 | u>>>(32-13); u = x3 + x2 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x4 | 0; x6 ^= u<<7 | u>>>(32-7); u = x6 + x5 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x6 | 0; x4 ^= u<<13 | u>>>(32-13); u = x4 + x7 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x9 | 0; x11 ^= u<<7 | u>>>(32-7); u = x11 + x10 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x11 | 0; x9 ^= u<<13 | u>>>(32-13); u = x9 + x8 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x14 | 0; x12 ^= u<<7 | u>>>(32-7); u = x12 + x15 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x12 | 0; x14 ^= u<<13 | u>>>(32-13); u = x14 + x13 | 0; x15 ^= u<<18 | u>>>(32-18); } o[ 0] = x0 >>> 0 & 0xff; o[ 1] = x0 >>> 8 & 0xff; o[ 2] = x0 >>> 16 & 0xff; o[ 3] = x0 >>> 24 & 0xff; o[ 4] = x5 >>> 0 & 0xff; o[ 5] = x5 >>> 8 & 0xff; o[ 6] = x5 >>> 16 & 0xff; o[ 7] = x5 >>> 24 & 0xff; o[ 8] = x10 >>> 0 & 0xff; o[ 9] = x10 >>> 8 & 0xff; o[10] = x10 >>> 16 & 0xff; o[11] = x10 >>> 24 & 0xff; o[12] = x15 >>> 0 & 0xff; o[13] = x15 >>> 8 & 0xff; o[14] = x15 >>> 16 & 0xff; o[15] = x15 >>> 24 & 0xff; o[16] = x6 >>> 0 & 0xff; o[17] = x6 >>> 8 & 0xff; o[18] = x6 >>> 16 & 0xff; o[19] = x6 >>> 24 & 0xff; o[20] = x7 >>> 0 & 0xff; o[21] = x7 >>> 8 & 0xff; o[22] = x7 >>> 16 & 0xff; o[23] = x7 >>> 24 & 0xff; o[24] = x8 >>> 0 & 0xff; o[25] = x8 >>> 8 & 0xff; o[26] = x8 >>> 16 & 0xff; o[27] = x8 >>> 24 & 0xff; o[28] = x9 >>> 0 & 0xff; o[29] = x9 >>> 8 & 0xff; o[30] = x9 >>> 16 & 0xff; o[31] = x9 >>> 24 & 0xff; } function crypto_core_salsa20(out,inp,k,c) { core_salsa20(out,inp,k,c); } function crypto_core_hsalsa20(out,inp,k,c) { core_hsalsa20(out,inp,k,c); } var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); // "expand 32-byte k" function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; mpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; } return 0; } function crypto_stream_salsa20(c,cpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = x[i]; } return 0; } function crypto_stream(c,cpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i+16]; return crypto_stream_salsa20(c,cpos,d,sn,s); } function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i+16]; return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); } /* * Port of Andrew Moon's Poly1305-donna-16. Public domain. * https://github.com/floodyberry/poly1305-donna */ var poly1305 = function(key) { this.buffer = new Uint8Array(16); this.r = new Uint16Array(10); this.h = new Uint16Array(10); this.pad = new Uint16Array(8); this.leftover = 0; this.fin = 0; var t0, t1, t2, t3, t4, t5, t6, t7; t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; this.r[5] = ((t4 >>> 1)) & 0x1ffe; t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; this.r[9] = ((t7 >>> 5)) & 0x007f; this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; }; poly1305.prototype.blocks = function(m, mpos, bytes) { var hibit = this.fin ? 0 : (1 << 11); var t0, t1, t2, t3, t4, t5, t6, t7, c; var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9]; var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9]; while (bytes >= 16) { t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; h5 += ((t4 >>> 1)) & 0x1fff; t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; h9 += ((t7 >>> 5)) | hibit; c = 0; d0 = c; d0 += h0 * r0; d0 += h1 * (5 * r9); d0 += h2 * (5 * r8); d0 += h3 * (5 * r7); d0 += h4 * (5 * r6); c = (d0 >>> 13); d0 &= 0x1fff; d0 += h5 * (5 * r5); d0 += h6 * (5 * r4); d0 += h7 * (5 * r3); d0 += h8 * (5 * r2); d0 += h9 * (5 * r1); c += (d0 >>> 13); d0 &= 0x1fff; d1 = c; d1 += h0 * r1; d1 += h1 * r0; d1 += h2 * (5 * r9); d1 += h3 * (5 * r8); d1 += h4 * (5 * r7); c = (d1 >>> 13); d1 &= 0x1fff; d1 += h5 * (5 * r6); d1 += h6 * (5 * r5); d1 += h7 * (5 * r4); d1 += h8 * (5 * r3); d1 += h9 * (5 * r2); c += (d1 >>> 13); d1 &= 0x1fff; d2 = c; d2 += h0 * r2; d2 += h1 * r1; d2 += h2 * r0; d2 += h3 * (5 * r9); d2 += h4 * (5 * r8); c = (d2 >>> 13); d2 &= 0x1fff; d2 += h5 * (5 * r7); d2 += h6 * (5 * r6); d2 += h7 * (5 * r5); d2 += h8 * (5 * r4); d2 += h9 * (5 * r3); c += (d2 >>> 13); d2 &= 0x1fff; d3 = c; d3 += h0 * r3; d3 += h1 * r2; d3 += h2 * r1; d3 += h3 * r0; d3 += h4 * (5 * r9); c = (d3 >>> 13); d3 &= 0x1fff; d3 += h5 * (5 * r8); d3 += h6 * (5 * r7); d3 += h7 * (5 * r6); d3 += h8 * (5 * r5); d3 += h9 * (5 * r4); c += (d3 >>> 13); d3 &= 0x1fff; d4 = c; d4 += h0 * r4; d4 += h1 * r3; d4 += h2 * r2; d4 += h3 * r1; d4 += h4 * r0; c = (d4 >>> 13); d4 &= 0x1fff; d4 += h5 * (5 * r9); d4 += h6 * (5 * r8); d4 += h7 * (5 * r7); d4 += h8 * (5 * r6); d4 += h9 * (5 * r5); c += (d4 >>> 13); d4 &= 0x1fff; d5 = c; d5 += h0 * r5; d5 += h1 * r4; d5 += h2 * r3; d5 += h3 * r2; d5 += h4 * r1; c = (d5 >>> 13); d5 &= 0x1fff; d5 += h5 * r0; d5 += h6 * (5 * r9); d5 += h7 * (5 * r8); d5 += h8 * (5 * r7); d5 += h9 * (5 * r6); c += (d5 >>> 13); d5 &= 0x1fff; d6 = c; d6 += h0 * r6; d6 += h1 * r5; d6 += h2 * r4; d6 += h3 * r3; d6 += h4 * r2; c = (d6 >>> 13); d6 &= 0x1fff; d6 += h5 * r1; d6 += h6 * r0; d6 += h7 * (5 * r9); d6 += h8 * (5 * r8); d6 += h9 * (5 * r7); c += (d6 >>> 13); d6 &= 0x1fff; d7 = c; d7 += h0 * r7; d7 += h1 * r6; d7 += h2 * r5; d7 += h3 * r4; d7 += h4 * r3; c = (d7 >>> 13); d7 &= 0x1fff; d7 += h5 * r2; d7 += h6 * r1; d7 += h7 * r0; d7 += h8 * (5 * r9); d7 += h9 * (5 * r8); c += (d7 >>> 13); d7 &= 0x1fff; d8 = c; d8 += h0 * r8; d8 += h1 * r7; d8 += h2 * r6; d8 += h3 * r5; d8 += h4 * r4; c = (d8 >>> 13); d8 &= 0x1fff; d8 += h5 * r3; d8 += h6 * r2; d8 += h7 * r1; d8 += h8 * r0; d8 += h9 * (5 * r9); c += (d8 >>> 13); d8 &= 0x1fff; d9 = c; d9 += h0 * r9; d9 += h1 * r8; d9 += h2 * r7; d9 += h3 * r6; d9 += h4 * r5; c = (d9 >>> 13); d9 &= 0x1fff; d9 += h5 * r4; d9 += h6 * r3; d9 += h7 * r2; d9 += h8 * r1; d9 += h9 * r0; c += (d9 >>> 13); d9 &= 0x1fff; c = (((c << 2) + c)) | 0; c = (c + d0) | 0; d0 = c & 0x1fff; c = (c >>> 13); d1 += c; h0 = d0; h1 = d1; h2 = d2; h3 = d3; h4 = d4; h5 = d5; h6 = d6; h7 = d7; h8 = d8; h9 = d9; mpos += 16; bytes -= 16; } this.h[0] = h0; this.h[1] = h1; this.h[2] = h2; this.h[3] = h3; this.h[4] = h4; this.h[5] = h5; this.h[6] = h6; this.h[7] = h7; this.h[8] = h8; this.h[9] = h9; }; poly1305.prototype.finish = function(mac, macpos) { var g = new Uint16Array(10); var c, mask, f, i; if (this.leftover) { i = this.leftover; this.buffer[i++] = 1; for (; i < 16; i++) this.buffer[i] = 0; this.fin = 1; this.blocks(this.buffer, 0, 16); } c = this.h[1] >>> 13; this.h[1] &= 0x1fff; for (i = 2; i < 10; i++) { this.h[i] += c; c = this.h[i] >>> 13; this.h[i] &= 0x1fff; } this.h[0] += (c * 5); c = this.h[0] >>> 13; this.h[0] &= 0x1fff; this.h[1] += c; c = this.h[1] >>> 13; this.h[1] &= 0x1fff; this.h[2] += c; g[0] = this.h[0] + 5; c = g[0] >>> 13; g[0] &= 0x1fff; for (i = 1; i < 10; i++) { g[i] = this.h[i] + c; c = g[i] >>> 13; g[i] &= 0x1fff; } g[9] -= (1 << 13); mask = (c ^ 1) - 1; for (i = 0; i < 10; i++) g[i] &= mask; mask = ~mask; for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; f = this.h[0] + this.pad[0]; this.h[0] = f & 0xffff; for (i = 1; i < 8; i++) { f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; this.h[i] = f & 0xffff; } mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; mac[macpos+10] = (this.h[5] >>> 0) & 0xff; mac[macpos+11] = (this.h[5] >>> 8) & 0xff; mac[macpos+12] = (this.h[6] >>> 0) & 0xff; mac[macpos+13] = (this.h[6] >>> 8) & 0xff; mac[macpos+14] = (this.h[7] >>> 0) & 0xff; mac[macpos+15] = (this.h[7] >>> 8) & 0xff; }; poly1305.prototype.update = function(m, mpos, bytes) { var i, want; if (this.leftover) { want = (16 - this.leftover); if (want > bytes) want = bytes; for (i = 0; i < want; i++) this.buffer[this.leftover + i] = m[mpos+i]; bytes -= want; mpos += want; this.leftover += want; if (this.leftover < 16) return; this.blocks(this.buffer, 0, 16); this.leftover = 0; } if (bytes >= 16) { want = bytes - (bytes % 16); this.blocks(m, mpos, want); mpos += want; bytes -= want; } if (bytes) { for (i = 0; i < bytes; i++) this.buffer[this.leftover + i] = m[mpos+i]; this.leftover += bytes; } }; function crypto_onetimeauth(out, outpos, m, mpos, n, k) { var s = new poly1305(k); s.update(m, mpos, n); s.finish(out, outpos); return 0; } function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { var x = new Uint8Array(16); crypto_onetimeauth(x,0,m,mpos,n,k); return crypto_verify_16(h,hpos,x,0); } function crypto_secretbox(c,m,d,n,k) { var i; if (d < 32) return -1; crypto_stream_xor(c,0,m,0,d,n,k); crypto_onetimeauth(c, 16, c, 32, d - 32, c); for (i = 0; i < 16; i++) c[i] = 0; return 0; } function crypto_secretbox_open(m,c,d,n,k) { var i; var x = new Uint8Array(32); if (d < 32) return -1; crypto_stream(x,0,32,n,k); if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; crypto_stream_xor(m,0,c,0,d,n,k); for (i = 0; i < 32; i++) m[i] = 0; return 0; } function set25519(r, a) { var i; for (i = 0; i < 16; i++) r[i] = a[i]|0; } function car25519(o) { var i, v, c = 1; for (i = 0; i < 16; i++) { v = o[i] + c + 65535; c = Math.floor(v / 65536); o[i] = v - c * 65536; } o[0] += c-1 + 37 * (c-1); } function sel25519(p, q, b) { var t, c = ~(b-1); for (var i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]); p[i] ^= t; q[i] ^= t; } } function pack25519(o, n) { var i, j, b; var m = gf(), t = gf(); for (i = 0; i < 16; i++) t[i] = n[i]; car25519(t); car25519(t); car25519(t); for (j = 0; j < 2; j++) { m[0] = t[0] - 0xffed; for (i = 1; i < 15; i++) { m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); m[i-1] &= 0xffff; } m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); b = (m[15]>>16) & 1; m[14] &= 0xffff; sel25519(t, m, 1-b); } for (i = 0; i < 16; i++) { o[2*i] = t[i] & 0xff; o[2*i+1] = t[i]>>8; } } function neq25519(a, b) { var c = new Uint8Array(32), d = new Uint8Array(32); pack25519(c, a); pack25519(d, b); return crypto_verify_32(c, 0, d, 0); } function par25519(a) { var d = new Uint8Array(32); pack25519(d, a); return d[0] & 1; } function unpack25519(o, n) { var i; for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); o[15] &= 0x7fff; } function A(o, a, b) { for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; } function Z(o, a, b) { for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; } function M(o, a, b) { var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; v = a[0]; t0 += v * b0; t1 += v * b1; t2 += v * b2; t3 += v * b3; t4 += v * b4; t5 += v * b5; t6 += v * b6; t7 += v * b7; t8 += v * b8; t9 += v * b9; t10 += v * b10; t11 += v * b11; t12 += v * b12; t13 += v * b13; t14 += v * b14; t15 += v * b15; v = a[1]; t1 += v * b0; t2 += v * b1; t3 += v * b2; t4 += v * b3; t5 += v * b4; t6 += v * b5; t7 += v * b6; t8 += v * b7; t9 += v * b8; t10 += v * b9; t11 += v * b10; t12 += v * b11; t13 += v * b12; t14 += v * b13; t15 += v * b14; t16 += v * b15; v = a[2]; t2 += v * b0; t3 += v * b1; t4 += v * b2; t5 += v * b3; t6 += v * b4; t7 += v * b5; t8 += v * b6; t9 += v * b7; t10 += v * b8; t11 += v * b9; t12 += v * b10; t13 += v * b11; t14 += v * b12; t15 += v * b13; t16 += v * b14; t17 += v * b15; v = a[3]; t3 += v * b0; t4 += v * b1; t5 += v * b2; t6 += v * b3; t7 += v * b4; t8 += v * b5; t9 += v * b6; t10 += v * b7; t11 += v * b8; t12 += v * b9; t13 += v * b10; t14 += v * b11; t15 += v * b12; t16 += v * b13; t17 += v * b14; t18 += v * b15; v = a[4]; t4 += v * b0; t5 += v * b1; t6 += v * b2; t7 += v * b3; t8 += v * b4; t9 += v * b5; t10 += v * b6; t11 += v * b7; t12 += v * b8; t13 += v * b9; t14 += v * b10; t15 += v * b11; t16 += v * b12; t17 += v * b13; t18 += v * b14; t19 += v * b15; v = a[5]; t5 += v * b0; t6 += v * b1; t7 += v * b2; t8 += v * b3; t9 += v * b4; t10 += v * b5; t11 += v * b6; t12 += v * b7; t13 += v * b8; t14 += v * b9; t15 += v * b10; t16 += v * b11; t17 += v * b12; t18 += v * b13; t19 += v * b14; t20 += v * b15; v = a[6]; t6 += v * b0; t7 += v * b1; t8 += v * b2; t9 += v * b3; t10 += v * b4; t11 += v * b5; t12 += v * b6; t13 += v * b7; t14 += v * b8; t15 += v * b9; t16 += v * b10; t17 += v * b11; t18 += v * b12; t19 += v * b13; t20 += v * b14; t21 += v * b15; v = a[7]; t7 += v * b0; t8 += v * b1; t9 += v * b2; t10 += v * b3; t11 += v * b4; t12 += v * b5; t13 += v * b6; t14 += v * b7; t15 += v * b8; t16 += v * b9; t17 += v * b10; t18 += v * b11; t19 += v * b12; t20 += v * b13; t21 += v * b14; t22 += v * b15; v = a[8]; t8 += v * b0; t9 += v * b1; t10 += v * b2; t11 += v * b3; t12 += v * b4; t13 += v * b5; t14 += v * b6; t15 += v * b7; t16 += v * b8; t17 += v * b9; t18 += v * b10; t19 += v * b11; t20 += v * b12; t21 += v * b13; t22 += v * b14; t23 += v * b15; v = a[9]; t9 += v * b0; t10 += v * b1; t11 += v * b2; t12 += v * b3; t13 += v * b4; t14 += v * b5; t15 += v * b6; t16 += v * b7; t17 += v * b8; t18 += v * b9; t19 += v * b10; t20 += v * b11; t21 += v * b12; t22 += v * b13; t23 += v * b14; t24 += v * b15; v = a[10]; t10 += v * b0; t11 += v * b1; t12 += v * b2; t13 += v * b3; t14 += v * b4; t15 += v * b5; t16 += v * b6; t17 += v * b7; t18 += v * b8; t19 += v * b9; t20 += v * b10; t21 += v * b11; t22 += v * b12; t23 += v * b13; t24 += v * b14; t25 += v * b15; v = a[11]; t11 += v * b0; t12 += v * b1; t13 += v * b2; t14 += v * b3; t15 += v * b4; t16 += v * b5; t17 += v * b6; t18 += v * b7; t19 += v * b8; t20 += v * b9; t21 += v * b10; t22 += v * b11; t23 += v * b12; t24 += v * b13; t25 += v * b14; t26 += v * b15; v = a[12]; t12 += v * b0; t13 += v * b1; t14 += v * b2; t15 += v * b3; t16 += v * b4; t17 += v * b5; t18 += v * b6; t19 += v * b7; t20 += v * b8; t21 += v * b9; t22 += v * b10; t23 += v * b11; t24 += v * b12; t25 += v * b13; t26 += v * b14; t27 += v * b15; v = a[13]; t13 += v * b0; t14 += v * b1; t15 += v * b2; t16 += v * b3; t17 += v * b4; t18 += v * b5; t19 += v * b6; t20 += v * b7; t21 += v * b8; t22 += v * b9; t23 += v * b10; t24 += v * b11; t25 += v * b12; t26 += v * b13; t27 += v * b14; t28 += v * b15; v = a[14]; t14 += v * b0; t15 += v * b1; t16 += v * b2; t17 += v * b3; t18 += v * b4; t19 += v * b5; t20 += v * b6; t21 += v * b7; t22 += v * b8; t23 += v * b9; t24 += v * b10; t25 += v * b11; t26 += v * b12; t27 += v * b13; t28 += v * b14; t29 += v * b15; v = a[15]; t15 += v * b0; t16 += v * b1; t17 += v * b2; t18 += v * b3; t19 += v * b4; t20 += v * b5; t21 += v * b6; t22 += v * b7; t23 += v * b8; t24 += v * b9; t25 += v * b10; t26 += v * b11; t27 += v * b12; t28 += v * b13; t29 += v * b14; t30 += v * b15; t0 += 38 * t16; t1 += 38 * t17; t2 += 38 * t18; t3 += 38 * t19; t4 += 38 * t20; t5 += 38 * t21; t6 += 38 * t22; t7 += 38 * t23; t8 += 38 * t24; t9 += 38 * t25; t10 += 38 * t26; t11 += 38 * t27; t12 += 38 * t28; t13 += 38 * t29; t14 += 38 * t30; // t15 left as is // first car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); // second car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); o[ 0] = t0; o[ 1] = t1; o[ 2] = t2; o[ 3] = t3; o[ 4] = t4; o[ 5] = t5; o[ 6] = t6; o[ 7] = t7; o[ 8] = t8; o[ 9] = t9; o[10] = t10; o[11] = t11; o[12] = t12; o[13] = t13; o[14] = t14; o[15] = t15; } function S(o, a) { M(o, a, a); } function inv25519(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 253; a >= 0; a--) { S(c, c); if(a !== 2 && a !== 4) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function pow2523(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 250; a >= 0; a--) { S(c, c); if(a !== 1) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function crypto_scalarmult(q, n, p) { var z = new Uint8Array(32); var x = new Float64Array(80), r, i; var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(); for (i = 0; i < 31; i++) z[i] = n[i]; z[31]=(n[31]&127)|64; z[0]&=248; unpack25519(x,p); for (i = 0; i < 16; i++) { b[i]=x[i]; d[i]=a[i]=c[i]=0; } a[0]=d[0]=1; for (i=254; i>=0; --i) { r=(z[i>>>3]>>>(i&7))&1; sel25519(a,b,r); sel25519(c,d,r); A(e,a,c); Z(a,a,c); A(c,b,d); Z(b,b,d); S(d,e); S(f,a); M(a,c,a); M(c,b,e); A(e,a,c); Z(a,a,c); S(b,a); Z(c,d,f); M(a,c,_121665); A(a,a,d); M(c,c,a); M(a,d,f); M(d,b,x); S(b,e); sel25519(a,b,r); sel25519(c,d,r); } for (i = 0; i < 16; i++) { x[i+16]=a[i]; x[i+32]=c[i]; x[i+48]=b[i]; x[i+64]=d[i]; } var x32 = x.subarray(32); var x16 = x.subarray(16); inv25519(x32,x32); M(x16,x16,x32); pack25519(q,x16); return 0; } function crypto_scalarmult_base(q, n) { return crypto_scalarmult(q, n, _9); } function crypto_box_keypair(y, x) { randombytes(x, 32); return crypto_scalarmult_base(y, x); } function crypto_box_beforenm(k, y, x) { var s = new Uint8Array(32); crypto_scalarmult(s, x, y); return crypto_core_hsalsa20(k, _0, s, sigma); } var crypto_box_afternm = crypto_secretbox; var crypto_box_open_afternm = crypto_secretbox_open; function crypto_box(c, m, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_afternm(c, m, d, n, k); } function crypto_box_open(m, c, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_open_afternm(m, c, d, n, k); } var K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ]; function crypto_hashblocks_hl(hh, hl, m, n) { var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d; var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; var pos = 0; while (n >= 128) { for (i = 0; i < 16; i++) { j = 8 * i + pos; wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; } for (i = 0; i < 80; i++) { bh0 = ah0; bh1 = ah1; bh2 = ah2; bh3 = ah3; bh4 = ah4; bh5 = ah5; bh6 = ah6; bh7 = ah7; bl0 = al0; bl1 = al1; bl2 = al2; bl3 = al3; bl4 = al4; bl5 = al5; bl6 = al6; bl7 = al7; // add h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma1 h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Ch h = (ah4 & ah5) ^ (~ah4 & ah6); l = (al4 & al5) ^ (~al4 & al6); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // K h = K[i*2]; l = K[i*2+1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // w h = wh[i%16]; l = wl[i%16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; th = c & 0xffff | d << 16; tl = a & 0xffff | b << 16; // add h = th; l = tl; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma0 h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Maj h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh7 = (c & 0xffff) | (d << 16); bl7 = (a & 0xffff) | (b << 16); // add h = bh3; l = bl3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = th; l = tl; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh3 = (c & 0xffff) | (d << 16); bl3 = (a & 0xffff) | (b << 16); ah1 = bh0; ah2 = bh1; ah3 = bh2; ah4 = bh3; ah5 = bh4; ah6 = bh5; ah7 = bh6; ah0 = bh7; al1 = bl0; al2 = bl1; al3 = bl2; al4 = bl3; al5 = bl4; al6 = bl5; al7 = bl6; al0 = bl7; if (i%16 === 15) { for (j = 0; j < 16; j++) { // add h = wh[j]; l = wl[j]; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = wh[(j+9)%16]; l = wl[(j+9)%16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma0 th = wh[(j+1)%16]; tl = wl[(j+1)%16]; h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma1 th = wh[(j+14)%16]; tl = wl[(j+14)%16]; h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; wh[j] = (c & 0xffff) | (d << 16); wl[j] = (a & 0xffff) | (b << 16); } } } // add h = ah0; l = al0; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[0]; l = hl[0]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[0] = ah0 = (c & 0xffff) | (d << 16); hl[0] = al0 = (a & 0xffff) | (b << 16); h = ah1; l = al1; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[1]; l = hl[1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[1] = ah1 = (c & 0xffff) | (d << 16); hl[1] = al1 = (a & 0xffff) | (b << 16); h = ah2; l = al2; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[2]; l = hl[2]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[2] = ah2 = (c & 0xffff) | (d << 16); hl[2] = al2 = (a & 0xffff) | (b << 16); h = ah3; l = al3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[3]; l = hl[3]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[3] = ah3 = (c & 0xffff) | (d << 16); hl[3] = al3 = (a & 0xffff) | (b << 16); h = ah4; l = al4; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[4]; l = hl[4]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[4] = ah4 = (c & 0xffff) | (d << 16); hl[4] = al4 = (a & 0xffff) | (b << 16); h = ah5; l = al5; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[5]; l = hl[5]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[5] = ah5 = (c & 0xffff) | (d << 16); hl[5] = al5 = (a & 0xffff) | (b << 16); h = ah6; l = al6; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[6]; l = hl[6]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[6] = ah6 = (c & 0xffff) | (d << 16); hl[6] = al6 = (a & 0xffff) | (b << 16); h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[7]; l = hl[7]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[7] = ah7 = (c & 0xffff) | (d << 16); hl[7] = al7 = (a & 0xffff) | (b << 16); pos += 128; n -= 128; } return n; } function crypto_hash(out, m, n) { var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n; hh[0] = 0x6a09e667; hh[1] = 0xbb67ae85; hh[2] = 0x3c6ef372; hh[3] = 0xa54ff53a; hh[4] = 0x510e527f; hh[5] = 0x9b05688c; hh[6] = 0x1f83d9ab; hh[7] = 0x5be0cd19; hl[0] = 0xf3bcc908; hl[1] = 0x84caa73b; hl[2] = 0xfe94f82b; hl[3] = 0x5f1d36f1; hl[4] = 0xade682d1; hl[5] = 0x2b3e6c1f; hl[6] = 0xfb41bd6b; hl[7] = 0x137e2179; crypto_hashblocks_hl(hh, hl, m, n); n %= 128; for (i = 0; i < n; i++) x[i] = m[b-n+i]; x[n] = 128; n = 256-128*(n<112?1:0); x[n-9] = 0; ts64(x, n-8, (b / 0x20000000) | 0, b << 3); crypto_hashblocks_hl(hh, hl, x, n); for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); return 0; } function add(p, q) { var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); Z(a, p[1], p[0]); Z(t, q[1], q[0]); M(a, a, t); A(b, p[0], p[1]); A(t, q[0], q[1]); M(b, b, t); M(c, p[3], q[3]); M(c, c, D2); M(d, p[2], q[2]); A(d, d, d); Z(e, b, a); Z(f, d, c); A(g, d, c); A(h, b, a); M(p[0], e, f); M(p[1], h, g); M(p[2], g, f); M(p[3], e, h); } function cswap(p, q, b) { var i; for (i = 0; i < 4; i++) { sel25519(p[i], q[i], b); } } function pack(r, p) { var tx = gf(), ty = gf(), zi = gf(); inv25519(zi, p[2]); M(tx, p[0], zi); M(ty, p[1], zi); pack25519(r, ty); r[31] ^= par25519(tx) << 7; } function scalarmult(p, q, s) { var b, i; set25519(p[0], gf0); set25519(p[1], gf1); set25519(p[2], gf1); set25519(p[3], gf0); for (i = 255; i >= 0; --i) { b = (s[(i/8)|0] >> (i&7)) & 1; cswap(p, q, b); add(q, p); add(p, p); cswap(p, q, b); } } function scalarbase(p, s) { var q = [gf(), gf(), gf(), gf()]; set25519(q[0], X); set25519(q[1], Y); set25519(q[2], gf1); M(q[3], X, Y); scalarmult(p, q, s); } function crypto_sign_keypair(pk, sk, seeded) { var d = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()]; var i; if (!seeded) randombytes(sk, 32); crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; scalarbase(p, d); pack(pk, p); for (i = 0; i < 32; i++) sk[i+32] = pk[i]; return 0; } var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); function modL(r, x) { var carry, i, j, k; for (i = 63; i >= 32; --i) { carry = 0; for (j = i - 32, k = i - 12; j < k; ++j) { x[j] += carry - 16 * x[i] * L[j - (i - 32)]; carry = (x[j] + 128) >> 8; x[j] -= carry * 256; } x[j] += carry; x[i] = 0; } carry = 0; for (j = 0; j < 32; j++) { x[j] += carry - (x[31] >> 4) * L[j]; carry = x[j] >> 8; x[j] &= 255; } for (j = 0; j < 32; j++) x[j] -= carry * L[j]; for (i = 0; i < 32; i++) { x[i+1] += x[i] >> 8; r[i] = x[i] & 255; } } function reduce(r) { var x = new Float64Array(64), i; for (i = 0; i < 64; i++) x[i] = r[i]; for (i = 0; i < 64; i++) r[i] = 0; modL(r, x); } // Note: difference from C - smlen returned, not passed as argument. function crypto_sign(sm, m, n, sk) { var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); var i, j, x = new Float64Array(64); var p = [gf(), gf(), gf(), gf()]; crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; var smlen = n + 64; for (i = 0; i < n; i++) sm[64 + i] = m[i]; for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; crypto_hash(r, sm.subarray(32), n+32); reduce(r); scalarbase(p, r); pack(sm, p); for (i = 32; i < 64; i++) sm[i] = sk[i]; crypto_hash(h, sm, n + 64); reduce(h); for (i = 0; i < 64; i++) x[i] = 0; for (i = 0; i < 32; i++) x[i] = r[i]; for (i = 0; i < 32; i++) { for (j = 0; j < 32; j++) { x[i+j] += h[i] * d[j]; } } modL(sm.subarray(32), x); return smlen; } function unpackneg(r, p) { var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); set25519(r[2], gf1); unpack25519(r[1], p); S(num, r[1]); M(den, num, D); Z(num, num, r[2]); A(den, r[2], den); S(den2, den); S(den4, den2); M(den6, den4, den2); M(t, den6, num); M(t, t, den); pow2523(t, t); M(t, t, num); M(t, t, den); M(t, t, den); M(r[0], t, den); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) M(r[0], r[0], I); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) return -1; if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); M(r[3], r[0], r[1]); return 0; } function crypto_sign_open(m, sm, n, pk) { var i, mlen; var t = new Uint8Array(32), h = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; mlen = -1; if (n < 64) return -1; if (unpackneg(q, pk)) return -1; for (i = 0; i < n; i++) m[i] = sm[i]; for (i = 0; i < 32; i++) m[i+32] = pk[i]; crypto_hash(h, m, n); reduce(h); scalarmult(p, q, h); scalarbase(q, sm.subarray(32)); add(p, q); pack(t, p); n -= 64; if (crypto_verify_32(sm, 0, t, 0)) { for (i = 0; i < n; i++) m[i] = 0; return -1; } for (i = 0; i < n; i++) m[i] = sm[i + 64]; mlen = n; return mlen; } var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; nacl.lowlevel = { crypto_core_hsalsa20: crypto_core_hsalsa20, crypto_stream_xor: crypto_stream_xor, crypto_stream: crypto_stream, crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, crypto_stream_salsa20: crypto_stream_salsa20, crypto_onetimeauth: crypto_onetimeauth, crypto_onetimeauth_verify: crypto_onetimeauth_verify, crypto_verify_16: crypto_verify_16, crypto_verify_32: crypto_verify_32, crypto_secretbox: crypto_secretbox, crypto_secretbox_open: crypto_secretbox_open, crypto_scalarmult: crypto_scalarmult, crypto_scalarmult_base: crypto_scalarmult_base, crypto_box_beforenm: crypto_box_beforenm, crypto_box_afternm: crypto_box_afternm, crypto_box: crypto_box, crypto_box_open: crypto_box_open, crypto_box_keypair: crypto_box_keypair, crypto_hash: crypto_hash, crypto_sign: crypto_sign, crypto_sign_keypair: crypto_sign_keypair, crypto_sign_open: crypto_sign_open, crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, crypto_sign_BYTES: crypto_sign_BYTES, crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, crypto_hash_BYTES: crypto_hash_BYTES }; /* High-level API */ function checkLengths(k, n) { if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); } function checkBoxLengths(pk, sk) { if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); } function checkArrayTypes() { var t, i; for (i = 0; i < arguments.length; i++) { if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') throw new TypeError('unexpected type ' + t + ', use Uint8Array'); } } function cleanup(arr) { for (var i = 0; i < arr.length; i++) arr[i] = 0; } // TODO: Completely remove this in v0.15. if (!nacl.util) { nacl.util = {}; nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); }; } nacl.randomBytes = function(n) { var b = new Uint8Array(n); randombytes(b, n); return b; }; nacl.secretbox = function(msg, nonce, key) { checkArrayTypes(msg, nonce, key); checkLengths(key, nonce); var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); var c = new Uint8Array(m.length); for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; crypto_secretbox(c, m, m.length, nonce, key); return c.subarray(crypto_secretbox_BOXZEROBYTES); }; nacl.secretbox.open = function(box, nonce, key) { checkArrayTypes(box, nonce, key); checkLengths(key, nonce); var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); var m = new Uint8Array(c.length); for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; if (c.length < 32) return false; if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; return m.subarray(crypto_secretbox_ZEROBYTES); }; nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; nacl.scalarMult = function(n, p) { checkArrayTypes(n, p); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult(q, n, p); return q; }; nacl.scalarMult.base = function(n) { checkArrayTypes(n); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult_base(q, n); return q; }; nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; nacl.box = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox(msg, nonce, k); }; nacl.box.before = function(publicKey, secretKey) { checkArrayTypes(publicKey, secretKey); checkBoxLengths(publicKey, secretKey); var k = new Uint8Array(crypto_box_BEFORENMBYTES); crypto_box_beforenm(k, publicKey, secretKey); return k; }; nacl.box.after = nacl.secretbox; nacl.box.open = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox.open(msg, nonce, k); }; nacl.box.open.after = nacl.secretbox.open; nacl.box.keyPair = function() { var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); crypto_box_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.box.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); crypto_scalarmult_base(pk, secretKey); return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; nacl.box.nonceLength = crypto_box_NONCEBYTES; nacl.box.overheadLength = nacl.secretbox.overheadLength; nacl.sign = function(msg, secretKey) { checkArrayTypes(msg, secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); crypto_sign(signedMsg, msg, msg.length, secretKey); return signedMsg; }; nacl.sign.open = function(signedMsg, publicKey) { if (arguments.length !== 2) throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); checkArrayTypes(signedMsg, publicKey); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var tmp = new Uint8Array(signedMsg.length); var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); if (mlen < 0) return null; var m = new Uint8Array(mlen); for (var i = 0; i < m.length; i++) m[i] = tmp[i]; return m; }; nacl.sign.detached = function(msg, secretKey) { var signedMsg = nacl.sign(msg, secretKey); var sig = new Uint8Array(crypto_sign_BYTES); for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; return sig; }; nacl.sign.detached.verify = function(msg, sig, publicKey) { checkArrayTypes(msg, sig, publicKey); if (sig.length !== crypto_sign_BYTES) throw new Error('bad signature size'); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var sm = new Uint8Array(crypto_sign_BYTES + msg.length); var m = new Uint8Array(crypto_sign_BYTES + msg.length); var i; for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); }; nacl.sign.keyPair = function() { var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); crypto_sign_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.sign.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.sign.keyPair.fromSeed = function(seed) { checkArrayTypes(seed); if (seed.length !== crypto_sign_SEEDBYTES) throw new Error('bad seed size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); for (var i = 0; i < 32; i++) sk[i] = seed[i]; crypto_sign_keypair(pk, sk, true); return {publicKey: pk, secretKey: sk}; }; nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; nacl.sign.seedLength = crypto_sign_SEEDBYTES; nacl.sign.signatureLength = crypto_sign_BYTES; nacl.hash = function(msg) { checkArrayTypes(msg); var h = new Uint8Array(crypto_hash_BYTES); crypto_hash(h, msg, msg.length); return h; }; nacl.hash.hashLength = crypto_hash_BYTES; nacl.verify = function(x, y) { checkArrayTypes(x, y); // Zero length arguments are considered not equal. if (x.length === 0 || y.length === 0) return false; if (x.length !== y.length) return false; return (vn(x, 0, y, 0, x.length) === 0) ? true : false; }; nacl.setPRNG = function(fn) { randombytes = fn; }; (function() { // Initialize PRNG if environment provides CSPRNG. // If not, methods calling randombytes will throw. var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; if (crypto && crypto.getRandomValues) { // Browsers. var QUOTA = 65536; nacl.setPRNG(function(x, n) { var i, v = new Uint8Array(n); for (i = 0; i < n; i += QUOTA) { crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); } for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } else if (true) { // Node.js. crypto = __nccwpck_require__(6982); if (crypto && crypto.randomBytes) { nacl.setPRNG(function(x, n) { var i, v = crypto.randomBytes(n); for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } } })(); })( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); /***/ }), /***/ 6752: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Client = __nccwpck_require__(3701) const Dispatcher = __nccwpck_require__(883) const Pool = __nccwpck_require__(628) const BalancedPool = __nccwpck_require__(837) const Agent = __nccwpck_require__(7405) const ProxyAgent = __nccwpck_require__(6672) const EnvHttpProxyAgent = __nccwpck_require__(3137) const RetryAgent = __nccwpck_require__(50) const errors = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { InvalidArgumentError } = errors const api = __nccwpck_require__(6615) const buildConnector = __nccwpck_require__(9136) const MockClient = __nccwpck_require__(7365) const MockAgent = __nccwpck_require__(7501) const MockPool = __nccwpck_require__(4004) const mockErrors = __nccwpck_require__(2429) const RetryHandler = __nccwpck_require__(7816) const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581) const DecoratorHandler = __nccwpck_require__(8155) const RedirectHandler = __nccwpck_require__(8754) const createRedirectInterceptor = __nccwpck_require__(5092) Object.assign(Dispatcher.prototype, api) module.exports.Dispatcher = Dispatcher module.exports.Client = Client module.exports.Pool = Pool module.exports.BalancedPool = BalancedPool module.exports.Agent = Agent module.exports.ProxyAgent = ProxyAgent module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent module.exports.RetryAgent = RetryAgent module.exports.RetryHandler = RetryHandler module.exports.DecoratorHandler = DecoratorHandler module.exports.RedirectHandler = RedirectHandler module.exports.createRedirectInterceptor = createRedirectInterceptor module.exports.interceptors = { redirect: __nccwpck_require__(1514), retry: __nccwpck_require__(2026), dump: __nccwpck_require__(8060), dns: __nccwpck_require__(379) } module.exports.buildConnector = buildConnector module.exports.errors = errors module.exports.util = { parseHeaders: util.parseHeaders, headerNameToString: util.headerNameToString } function makeDispatcher (fn) { return (url, opts, handler) => { if (typeof opts === 'function') { handler = opts opts = null } if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { throw new InvalidArgumentError('invalid url') } if (opts != null && typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (opts && opts.path != null) { if (typeof opts.path !== 'string') { throw new InvalidArgumentError('invalid opts.path') } let path = opts.path if (!opts.path.startsWith('/')) { path = `/${path}` } url = new URL(util.parseOrigin(url).origin + path) } else { if (!opts) { opts = typeof url === 'object' ? url : {} } url = util.parseURL(url) } const { agent, dispatcher = getGlobalDispatcher() } = opts if (agent) { throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') } return fn.call(dispatcher, { ...opts, origin: url.origin, path: url.search ? `${url.pathname}${url.search}` : url.pathname, method: opts.method || (opts.body ? 'PUT' : 'GET') }, handler) } } module.exports.setGlobalDispatcher = setGlobalDispatcher module.exports.getGlobalDispatcher = getGlobalDispatcher const fetchImpl = (__nccwpck_require__(4398).fetch) module.exports.fetch = async function fetch (init, options = undefined) { try { return await fetchImpl(init, options) } catch (err) { if (err && typeof err === 'object') { Error.captureStackTrace(err) } throw err } } module.exports.Headers = __nccwpck_require__(660).Headers module.exports.Response = __nccwpck_require__(9051).Response module.exports.Request = __nccwpck_require__(9967).Request module.exports.FormData = __nccwpck_require__(5910).FormData module.exports.File = globalThis.File ?? (__nccwpck_require__(4573).File) module.exports.FileReader = __nccwpck_require__(8355).FileReader const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(1059) module.exports.setGlobalOrigin = setGlobalOrigin module.exports.getGlobalOrigin = getGlobalOrigin const { CacheStorage } = __nccwpck_require__(3245) const { kConstruct } = __nccwpck_require__(109) // Cache & CacheStorage are tightly coupled with fetch. Even if it may run // in an older version of Node, it doesn't have any use without fetch. module.exports.caches = new CacheStorage(kConstruct) const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(9061) module.exports.deleteCookie = deleteCookie module.exports.getCookies = getCookies module.exports.getSetCookies = getSetCookies module.exports.setCookie = setCookie const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(1900) module.exports.parseMIMEType = parseMIMEType module.exports.serializeAMimeType = serializeAMimeType const { CloseEvent, ErrorEvent, MessageEvent } = __nccwpck_require__(5188) module.exports.WebSocket = __nccwpck_require__(3726).WebSocket module.exports.CloseEvent = CloseEvent module.exports.ErrorEvent = ErrorEvent module.exports.MessageEvent = MessageEvent module.exports.request = makeDispatcher(api.request) module.exports.stream = makeDispatcher(api.stream) module.exports.pipeline = makeDispatcher(api.pipeline) module.exports.connect = makeDispatcher(api.connect) module.exports.upgrade = makeDispatcher(api.upgrade) module.exports.MockClient = MockClient module.exports.MockPool = MockPool module.exports.MockAgent = MockAgent module.exports.mockErrors = mockErrors const { EventSource } = __nccwpck_require__(1238) module.exports.EventSource = EventSource /***/ }), /***/ 158: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { addAbortListener } = __nccwpck_require__(3440) const { RequestAbortedError } = __nccwpck_require__(8707) const kListener = Symbol('kListener') const kSignal = Symbol('kSignal') function abort (self) { if (self.abort) { self.abort(self[kSignal]?.reason) } else { self.reason = self[kSignal]?.reason ?? new RequestAbortedError() } removeSignal(self) } function addSignal (self, signal) { self.reason = null self[kSignal] = null self[kListener] = null if (!signal) { return } if (signal.aborted) { abort(self) return } self[kSignal] = signal self[kListener] = () => { abort(self) } addAbortListener(self[kSignal], self[kListener]) } function removeSignal (self) { if (!self[kSignal]) { return } if ('removeEventListener' in self[kSignal]) { self[kSignal].removeEventListener('abort', self[kListener]) } else { self[kSignal].removeListener('abort', self[kListener]) } self[kSignal] = null self[kListener] = null } module.exports = { addSignal, removeSignal } /***/ }), /***/ 2279: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) const { AsyncResource } = __nccwpck_require__(6698) const { InvalidArgumentError, SocketError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { addSignal, removeSignal } = __nccwpck_require__(158) class ConnectHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } const { signal, opaque, responseHeaders } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } super('UNDICI_CONNECT') this.opaque = opaque || null this.responseHeaders = responseHeaders || null this.callback = callback this.abort = null addSignal(this, signal) } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = context } onHeaders () { throw new SocketError('bad connect', null) } onUpgrade (statusCode, rawHeaders, socket) { const { callback, opaque, context } = this removeSignal(this) this.callback = null let headers = rawHeaders // Indicates is an HTTP2Session if (headers != null) { headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) } this.runInAsyncScope(callback, null, null, { statusCode, headers, socket, opaque, context }) } onError (err) { const { callback, opaque } = this removeSignal(this) if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } } } function connect (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { connect.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { const connectHandler = new ConnectHandler(opts, callback) this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = connect /***/ }), /***/ 6862: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Readable, Duplex, PassThrough } = __nccwpck_require__(7075) const { InvalidArgumentError, InvalidReturnValueError, RequestAbortedError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { AsyncResource } = __nccwpck_require__(6698) const { addSignal, removeSignal } = __nccwpck_require__(158) const assert = __nccwpck_require__(4589) const kResume = Symbol('resume') class PipelineRequest extends Readable { constructor () { super({ autoDestroy: true }) this[kResume] = null } _read () { const { [kResume]: resume } = this if (resume) { this[kResume] = null resume() } } _destroy (err, callback) { this._read() callback(err) } } class PipelineResponse extends Readable { constructor (resume) { super({ autoDestroy: true }) this[kResume] = resume } _read () { this[kResume]() } _destroy (err, callback) { if (!err && !this._readableState.endEmitted) { err = new RequestAbortedError() } callback(err) } } class PipelineHandler extends AsyncResource { constructor (opts, handler) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof handler !== 'function') { throw new InvalidArgumentError('invalid handler') } const { signal, method, opaque, onInfo, responseHeaders } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } super('UNDICI_PIPELINE') this.opaque = opaque || null this.responseHeaders = responseHeaders || null this.handler = handler this.abort = null this.context = null this.onInfo = onInfo || null this.req = new PipelineRequest().on('error', util.nop) this.ret = new Duplex({ readableObjectMode: opts.objectMode, autoDestroy: true, read: () => { const { body } = this if (body?.resume) { body.resume() } }, write: (chunk, encoding, callback) => { const { req } = this if (req.push(chunk, encoding) || req._readableState.destroyed) { callback() } else { req[kResume] = callback } }, destroy: (err, callback) => { const { body, req, res, ret, abort } = this if (!err && !ret._readableState.endEmitted) { err = new RequestAbortedError() } if (abort && err) { abort() } util.destroy(body, err) util.destroy(req, err) util.destroy(res, err) removeSignal(this) callback(err) } }).on('prefinish', () => { const { req } = this // Node < 15 does not call _final in same tick. req.push(null) }) this.res = null addSignal(this, signal) } onConnect (abort, context) { const { ret, res } = this if (this.reason) { abort(this.reason) return } assert(!res, 'pipeline cannot be retried') assert(!ret.destroyed) this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume) { const { opaque, handler, context } = this if (statusCode < 200) { if (this.onInfo) { const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) this.onInfo({ statusCode, headers }) } return } this.res = new PipelineResponse(resume) let body try { this.handler = null const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) body = this.runInAsyncScope(handler, null, { statusCode, headers, opaque, body: this.res, context }) } catch (err) { this.res.on('error', util.nop) throw err } if (!body || typeof body.on !== 'function') { throw new InvalidReturnValueError('expected Readable') } body .on('data', (chunk) => { const { ret, body } = this if (!ret.push(chunk) && body.pause) { body.pause() } }) .on('error', (err) => { const { ret } = this util.destroy(ret, err) }) .on('end', () => { const { ret } = this ret.push(null) }) .on('close', () => { const { ret } = this if (!ret._readableState.ended) { util.destroy(ret, new RequestAbortedError()) } }) this.body = body } onData (chunk) { const { res } = this return res.push(chunk) } onComplete (trailers) { const { res } = this res.push(null) } onError (err) { const { ret } = this this.handler = null util.destroy(ret, err) } } function pipeline (opts, handler) { try { const pipelineHandler = new PipelineHandler(opts, handler) this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) return pipelineHandler.ret } catch (err) { return new PassThrough().destroy(err) } } module.exports = pipeline /***/ }), /***/ 4043: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) const { Readable } = __nccwpck_require__(9927) const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) const { AsyncResource } = __nccwpck_require__(6698) class RequestHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts try { if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { throw new InvalidArgumentError('invalid highWaterMark') } if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } super('UNDICI_REQUEST') } catch (err) { if (util.isStream(body)) { util.destroy(body.on('error', util.nop), err) } throw err } this.method = method this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.callback = callback this.res = null this.abort = null this.body = body this.trailers = {} this.context = null this.onInfo = onInfo || null this.throwOnError = throwOnError this.highWaterMark = highWaterMark this.signal = signal this.reason = null this.removeAbortListener = null if (util.isStream(body)) { body.on('error', (err) => { this.onError(err) }) } if (this.signal) { if (this.signal.aborted) { this.reason = this.signal.reason ?? new RequestAbortedError() } else { this.removeAbortListener = util.addAbortListener(this.signal, () => { this.reason = this.signal.reason ?? new RequestAbortedError() if (this.res) { util.destroy(this.res.on('error', util.nop), this.reason) } else if (this.abort) { this.abort(this.reason) } if (this.removeAbortListener) { this.res?.off('close', this.removeAbortListener) this.removeAbortListener() this.removeAbortListener = null } }) } } } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }) } return } const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers const contentType = parsedHeaders['content-type'] const contentLength = parsedHeaders['content-length'] const res = new Readable({ resume, abort, contentType, contentLength: this.method !== 'HEAD' && contentLength ? Number(contentLength) : null, highWaterMark }) if (this.removeAbortListener) { res.on('close', this.removeAbortListener) } this.callback = null this.res = res if (callback !== null) { if (this.throwOnError && statusCode >= 400) { this.runInAsyncScope(getResolveErrorBodyCallback, null, { callback, body: res, contentType, statusCode, statusMessage, headers } ) } else { this.runInAsyncScope(callback, null, null, { statusCode, headers, trailers: this.trailers, opaque, body: res, context }) } } } onData (chunk) { return this.res.push(chunk) } onComplete (trailers) { util.parseHeaders(trailers, this.trailers) this.res.push(null) } onError (err) { const { res, callback, body, opaque } = this if (callback) { // TODO: Does this need queueMicrotask? this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } if (res) { this.res = null // Ensure all queued handlers are invoked before destroying res. queueMicrotask(() => { util.destroy(res, err) }) } if (body) { this.body = null util.destroy(body, err) } if (this.removeAbortListener) { res?.off('close', this.removeAbortListener) this.removeAbortListener() this.removeAbortListener = null } } } function request (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { request.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { this.dispatch(opts, new RequestHandler(opts, callback)) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = request module.exports.RequestHandler = RequestHandler /***/ }), /***/ 3560: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) const { finished, PassThrough } = __nccwpck_require__(7075) const { InvalidArgumentError, InvalidReturnValueError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) const { AsyncResource } = __nccwpck_require__(6698) const { addSignal, removeSignal } = __nccwpck_require__(158) class StreamHandler extends AsyncResource { constructor (opts, factory, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts try { if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (typeof factory !== 'function') { throw new InvalidArgumentError('invalid factory') } if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } super('UNDICI_STREAM') } catch (err) { if (util.isStream(body)) { util.destroy(body.on('error', util.nop), err) } throw err } this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.factory = factory this.callback = callback this.res = null this.abort = null this.context = null this.trailers = null this.body = body this.onInfo = onInfo || null this.throwOnError = throwOnError || false if (util.isStream(body)) { body.on('error', (err) => { this.onError(err) }) } addSignal(this, signal) } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const { factory, opaque, context, callback, responseHeaders } = this const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }) } return } this.factory = null let res if (this.throwOnError && statusCode >= 400) { const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers const contentType = parsedHeaders['content-type'] res = new PassThrough() this.callback = null this.runInAsyncScope(getResolveErrorBodyCallback, null, { callback, body: res, contentType, statusCode, statusMessage, headers } ) } else { if (factory === null) { return } res = this.runInAsyncScope(factory, null, { statusCode, headers, opaque, context }) if ( !res || typeof res.write !== 'function' || typeof res.end !== 'function' || typeof res.on !== 'function' ) { throw new InvalidReturnValueError('expected Writable') } // TODO: Avoid finished. It registers an unnecessary amount of listeners. finished(res, { readable: false }, (err) => { const { callback, res, opaque, trailers, abort } = this this.res = null if (err || !res.readable) { util.destroy(res, err) } this.callback = null this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) if (err) { abort() } }) } res.on('drain', resume) this.res = res const needDrain = res.writableNeedDrain !== undefined ? res.writableNeedDrain : res._writableState?.needDrain return needDrain !== true } onData (chunk) { const { res } = this return res ? res.write(chunk) : true } onComplete (trailers) { const { res } = this removeSignal(this) if (!res) { return } this.trailers = util.parseHeaders(trailers) res.end() } onError (err) { const { res, callback, opaque, body } = this removeSignal(this) this.factory = null if (res) { this.res = null util.destroy(res, err) } else if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } if (body) { this.body = null util.destroy(body, err) } } } function stream (opts, factory, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { stream.call(this, opts, factory, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { this.dispatch(opts, new StreamHandler(opts, factory, callback)) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = stream /***/ }), /***/ 1882: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError, SocketError } = __nccwpck_require__(8707) const { AsyncResource } = __nccwpck_require__(6698) const util = __nccwpck_require__(3440) const { addSignal, removeSignal } = __nccwpck_require__(158) const assert = __nccwpck_require__(4589) class UpgradeHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } const { signal, opaque, responseHeaders } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } super('UNDICI_UPGRADE') this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.callback = callback this.abort = null this.context = null addSignal(this, signal) } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = null } onHeaders () { throw new SocketError('bad upgrade', null) } onUpgrade (statusCode, rawHeaders, socket) { assert(statusCode === 101) const { callback, opaque, context } = this removeSignal(this) this.callback = null const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) this.runInAsyncScope(callback, null, null, { headers, socket, opaque, context }) } onError (err) { const { callback, opaque } = this removeSignal(this) if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } } } function upgrade (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { upgrade.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { const upgradeHandler = new UpgradeHandler(opts, callback) this.dispatch({ ...opts, method: opts.method || 'GET', upgrade: opts.protocol || 'Websocket' }, upgradeHandler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = upgrade /***/ }), /***/ 6615: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports.request = __nccwpck_require__(4043) module.exports.stream = __nccwpck_require__(3560) module.exports.pipeline = __nccwpck_require__(6862) module.exports.upgrade = __nccwpck_require__(1882) module.exports.connect = __nccwpck_require__(2279) /***/ }), /***/ 9927: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Ported from https://github.com/nodejs/undici/pull/907 const assert = __nccwpck_require__(4589) const { Readable } = __nccwpck_require__(7075) const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { ReadableStreamFrom } = __nccwpck_require__(3440) const kConsume = Symbol('kConsume') const kReading = Symbol('kReading') const kBody = Symbol('kBody') const kAbort = Symbol('kAbort') const kContentType = Symbol('kContentType') const kContentLength = Symbol('kContentLength') const noop = () => {} class BodyReadable extends Readable { constructor ({ resume, abort, contentType = '', contentLength, highWaterMark = 64 * 1024 // Same as nodejs fs streams. }) { super({ autoDestroy: true, read: resume, highWaterMark }) this._readableState.dataEmitted = false this[kAbort] = abort this[kConsume] = null this[kBody] = null this[kContentType] = contentType this[kContentLength] = contentLength // Is stream being consumed through Readable API? // This is an optimization so that we avoid checking // for 'data' and 'readable' listeners in the hot path // inside push(). this[kReading] = false } destroy (err) { if (!err && !this._readableState.endEmitted) { err = new RequestAbortedError() } if (err) { this[kAbort]() } return super.destroy(err) } _destroy (err, callback) { // Workaround for Node "bug". If the stream is destroyed in same // tick as it is created, then a user who is waiting for a // promise (i.e micro tick) for installing a 'error' listener will // never get a chance and will always encounter an unhandled exception. if (!this[kReading]) { setImmediate(() => { callback(err) }) } else { callback(err) } } on (ev, ...args) { if (ev === 'data' || ev === 'readable') { this[kReading] = true } return super.on(ev, ...args) } addListener (ev, ...args) { return this.on(ev, ...args) } off (ev, ...args) { const ret = super.off(ev, ...args) if (ev === 'data' || ev === 'readable') { this[kReading] = ( this.listenerCount('data') > 0 || this.listenerCount('readable') > 0 ) } return ret } removeListener (ev, ...args) { return this.off(ev, ...args) } push (chunk) { if (this[kConsume] && chunk !== null) { consumePush(this[kConsume], chunk) return this[kReading] ? super.push(chunk) : true } return super.push(chunk) } // https://fetch.spec.whatwg.org/#dom-body-text async text () { return consume(this, 'text') } // https://fetch.spec.whatwg.org/#dom-body-json async json () { return consume(this, 'json') } // https://fetch.spec.whatwg.org/#dom-body-blob async blob () { return consume(this, 'blob') } // https://fetch.spec.whatwg.org/#dom-body-bytes async bytes () { return consume(this, 'bytes') } // https://fetch.spec.whatwg.org/#dom-body-arraybuffer async arrayBuffer () { return consume(this, 'arrayBuffer') } // https://fetch.spec.whatwg.org/#dom-body-formdata async formData () { // TODO: Implement. throw new NotSupportedError() } // https://fetch.spec.whatwg.org/#dom-body-bodyused get bodyUsed () { return util.isDisturbed(this) } // https://fetch.spec.whatwg.org/#dom-body-body get body () { if (!this[kBody]) { this[kBody] = ReadableStreamFrom(this) if (this[kConsume]) { // TODO: Is this the best way to force a lock? this[kBody].getReader() // Ensure stream is locked. assert(this[kBody].locked) } } return this[kBody] } async dump (opts) { let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024 const signal = opts?.signal if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) { throw new InvalidArgumentError('signal must be an AbortSignal') } signal?.throwIfAborted() if (this._readableState.closeEmitted) { return null } return await new Promise((resolve, reject) => { if (this[kContentLength] > limit) { this.destroy(new AbortError()) } const onAbort = () => { this.destroy(signal.reason ?? new AbortError()) } signal?.addEventListener('abort', onAbort) this .on('close', function () { signal?.removeEventListener('abort', onAbort) if (signal?.aborted) { reject(signal.reason ?? new AbortError()) } else { resolve(null) } }) .on('error', noop) .on('data', function (chunk) { limit -= chunk.length if (limit <= 0) { this.destroy() } }) .resume() }) } } // https://streams.spec.whatwg.org/#readablestream-locked function isLocked (self) { // Consume is an implicit lock. return (self[kBody] && self[kBody].locked === true) || self[kConsume] } // https://fetch.spec.whatwg.org/#body-unusable function isUnusable (self) { return util.isDisturbed(self) || isLocked(self) } async function consume (stream, type) { assert(!stream[kConsume]) return new Promise((resolve, reject) => { if (isUnusable(stream)) { const rState = stream._readableState if (rState.destroyed && rState.closeEmitted === false) { stream .on('error', err => { reject(err) }) .on('close', () => { reject(new TypeError('unusable')) }) } else { reject(rState.errored ?? new TypeError('unusable')) } } else { queueMicrotask(() => { stream[kConsume] = { type, stream, resolve, reject, length: 0, body: [] } stream .on('error', function (err) { consumeFinish(this[kConsume], err) }) .on('close', function () { if (this[kConsume].body !== null) { consumeFinish(this[kConsume], new RequestAbortedError()) } }) consumeStart(stream[kConsume]) }) } }) } function consumeStart (consume) { if (consume.body === null) { return } const { _readableState: state } = consume.stream if (state.bufferIndex) { const start = state.bufferIndex const end = state.buffer.length for (let n = start; n < end; n++) { consumePush(consume, state.buffer[n]) } } else { for (const chunk of state.buffer) { consumePush(consume, chunk) } } if (state.endEmitted) { consumeEnd(this[kConsume]) } else { consume.stream.on('end', function () { consumeEnd(this[kConsume]) }) } consume.stream.resume() while (consume.stream.read() != null) { // Loop } } /** * @param {Buffer[]} chunks * @param {number} length */ function chunksDecode (chunks, length) { if (chunks.length === 0 || length === 0) { return '' } const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length) const bufferLength = buffer.length // Skip BOM. const start = bufferLength > 2 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf ? 3 : 0 return buffer.utf8Slice(start, bufferLength) } /** * @param {Buffer[]} chunks * @param {number} length * @returns {Uint8Array} */ function chunksConcat (chunks, length) { if (chunks.length === 0 || length === 0) { return new Uint8Array(0) } if (chunks.length === 1) { // fast-path return new Uint8Array(chunks[0]) } const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer) let offset = 0 for (let i = 0; i < chunks.length; ++i) { const chunk = chunks[i] buffer.set(chunk, offset) offset += chunk.length } return buffer } function consumeEnd (consume) { const { type, body, resolve, stream, length } = consume try { if (type === 'text') { resolve(chunksDecode(body, length)) } else if (type === 'json') { resolve(JSON.parse(chunksDecode(body, length))) } else if (type === 'arrayBuffer') { resolve(chunksConcat(body, length).buffer) } else if (type === 'blob') { resolve(new Blob(body, { type: stream[kContentType] })) } else if (type === 'bytes') { resolve(chunksConcat(body, length)) } consumeFinish(consume) } catch (err) { stream.destroy(err) } } function consumePush (consume, chunk) { consume.length += chunk.length consume.body.push(chunk) } function consumeFinish (consume, err) { if (consume.body === null) { return } if (err) { consume.reject(err) } else { consume.resolve() } consume.type = null consume.stream = null consume.resolve = null consume.reject = null consume.length = 0 consume.body = null } module.exports = { Readable: BodyReadable, chunksDecode } /***/ }), /***/ 7655: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const { ResponseStatusCodeError } = __nccwpck_require__(8707) const { chunksDecode } = __nccwpck_require__(9927) const CHUNK_LIMIT = 128 * 1024 async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { assert(body) let chunks = [] let length = 0 try { for await (const chunk of body) { chunks.push(chunk) length += chunk.length if (length > CHUNK_LIMIT) { chunks = [] length = 0 break } } } catch { chunks = [] length = 0 // Do nothing.... } const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}` if (statusCode === 204 || !contentType || !length) { queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers))) return } const stackTraceLimit = Error.stackTraceLimit Error.stackTraceLimit = 0 let payload try { if (isContentTypeApplicationJson(contentType)) { payload = JSON.parse(chunksDecode(chunks, length)) } else if (isContentTypeText(contentType)) { payload = chunksDecode(chunks, length) } } catch { // process in a callback to avoid throwing in the microtask queue } finally { Error.stackTraceLimit = stackTraceLimit } queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload))) } const isContentTypeApplicationJson = (contentType) => { return ( contentType.length > 15 && contentType[11] === '/' && contentType[0] === 'a' && contentType[1] === 'p' && contentType[2] === 'p' && contentType[3] === 'l' && contentType[4] === 'i' && contentType[5] === 'c' && contentType[6] === 'a' && contentType[7] === 't' && contentType[8] === 'i' && contentType[9] === 'o' && contentType[10] === 'n' && contentType[12] === 'j' && contentType[13] === 's' && contentType[14] === 'o' && contentType[15] === 'n' ) } const isContentTypeText = (contentType) => { return ( contentType.length > 4 && contentType[4] === '/' && contentType[0] === 't' && contentType[1] === 'e' && contentType[2] === 'x' && contentType[3] === 't' ) } module.exports = { getResolveErrorBodyCallback, isContentTypeApplicationJson, isContentTypeText } /***/ }), /***/ 9136: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const net = __nccwpck_require__(7030) const assert = __nccwpck_require__(4589) const util = __nccwpck_require__(3440) const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707) const timers = __nccwpck_require__(6603) function noop () {} let tls // include tls conditionally since it is not always available // TODO: session re-use does not wait for the first // connection to resolve the session and might therefore // resolve the same servername multiple times even when // re-use is enabled. let SessionCache // FIXME: remove workaround when the Node bug is fixed // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 if (global.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) { SessionCache = class WeakSessionCache { constructor (maxCachedSessions) { this._maxCachedSessions = maxCachedSessions this._sessionCache = new Map() this._sessionRegistry = new global.FinalizationRegistry((key) => { if (this._sessionCache.size < this._maxCachedSessions) { return } const ref = this._sessionCache.get(key) if (ref !== undefined && ref.deref() === undefined) { this._sessionCache.delete(key) } }) } get (sessionKey) { const ref = this._sessionCache.get(sessionKey) return ref ? ref.deref() : null } set (sessionKey, session) { if (this._maxCachedSessions === 0) { return } this._sessionCache.set(sessionKey, new WeakRef(session)) this._sessionRegistry.register(session, sessionKey) } } } else { SessionCache = class SimpleSessionCache { constructor (maxCachedSessions) { this._maxCachedSessions = maxCachedSessions this._sessionCache = new Map() } get (sessionKey) { return this._sessionCache.get(sessionKey) } set (sessionKey, session) { if (this._maxCachedSessions === 0) { return } if (this._sessionCache.size >= this._maxCachedSessions) { // remove the oldest session const { value: oldestKey } = this._sessionCache.keys().next() this._sessionCache.delete(oldestKey) } this._sessionCache.set(sessionKey, session) } } } function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') } const options = { path: socketPath, ...opts } const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) timeout = timeout == null ? 10e3 : timeout allowH2 = allowH2 != null ? allowH2 : false return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { let socket if (protocol === 'https:') { if (!tls) { tls = __nccwpck_require__(1692) } servername = servername || options.servername || util.getServerName(host) || null const sessionKey = servername || hostname assert(sessionKey) const session = customSession || sessionCache.get(sessionKey) || null port = port || 443 socket = tls.connect({ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... ...options, servername, session, localAddress, // TODO(HTTP/2): Add support for h2c ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], socket: httpSocket, // upgrade socket connection port, host: hostname }) socket .on('session', function (session) { // TODO (fix): Can a session become invalid once established? Don't think so? sessionCache.set(sessionKey, session) }) } else { assert(!httpSocket, 'httpSocket can only be sent on TLS update') port = port || 80 socket = net.connect({ highWaterMark: 64 * 1024, // Same as nodejs fs streams. ...options, localAddress, port, host: hostname }) } // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket if (options.keepAlive == null || options.keepAlive) { const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay socket.setKeepAlive(true, keepAliveInitialDelay) } const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }) socket .setNoDelay(true) .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { queueMicrotask(clearConnectTimeout) if (callback) { const cb = callback callback = null cb(null, this) } }) .on('error', function (err) { queueMicrotask(clearConnectTimeout) if (callback) { const cb = callback callback = null cb(err) } }) return socket } } /** * @param {WeakRef} socketWeakRef * @param {object} opts * @param {number} opts.timeout * @param {string} opts.hostname * @param {number} opts.port * @returns {() => void} */ const setupConnectTimeout = process.platform === 'win32' ? (socketWeakRef, opts) => { if (!opts.timeout) { return noop } let s1 = null let s2 = null const fastTimer = timers.setFastTimeout(() => { // setImmediate is added to make sure that we prioritize socket error events over timeouts s1 = setImmediate(() => { // Windows needs an extra setImmediate probably due to implementation differences in the socket logic s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)) }) }, opts.timeout) return () => { timers.clearFastTimeout(fastTimer) clearImmediate(s1) clearImmediate(s2) } } : (socketWeakRef, opts) => { if (!opts.timeout) { return noop } let s1 = null const fastTimer = timers.setFastTimeout(() => { // setImmediate is added to make sure that we prioritize socket error events over timeouts s1 = setImmediate(() => { onConnectTimeout(socketWeakRef.deref(), opts) }) }, opts.timeout) return () => { timers.clearFastTimeout(fastTimer) clearImmediate(s1) } } /** * @param {net.Socket} socket * @param {object} opts * @param {number} opts.timeout * @param {string} opts.hostname * @param {number} opts.port */ function onConnectTimeout (socket, opts) { // The socket could be already garbage collected if (socket == null) { return } let message = 'Connect Timeout Error' if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` } else { message += ` (attempted address: ${opts.hostname}:${opts.port},` } message += ` timeout: ${opts.timeout}ms)` util.destroy(socket, new ConnectTimeoutError(message)) } module.exports = buildConnector /***/ }), /***/ 735: /***/ ((module) => { "use strict"; /** @type {Record} */ const headerNameLowerCasedRecord = {} // https://developer.mozilla.org/docs/Web/HTTP/Headers const wellknownHeaderNames = [ 'Accept', 'Accept-Encoding', 'Accept-Language', 'Accept-Ranges', 'Access-Control-Allow-Credentials', 'Access-Control-Allow-Headers', 'Access-Control-Allow-Methods', 'Access-Control-Allow-Origin', 'Access-Control-Expose-Headers', 'Access-Control-Max-Age', 'Access-Control-Request-Headers', 'Access-Control-Request-Method', 'Age', 'Allow', 'Alt-Svc', 'Alt-Used', 'Authorization', 'Cache-Control', 'Clear-Site-Data', 'Connection', 'Content-Disposition', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Location', 'Content-Range', 'Content-Security-Policy', 'Content-Security-Policy-Report-Only', 'Content-Type', 'Cookie', 'Cross-Origin-Embedder-Policy', 'Cross-Origin-Opener-Policy', 'Cross-Origin-Resource-Policy', 'Date', 'Device-Memory', 'Downlink', 'ECT', 'ETag', 'Expect', 'Expect-CT', 'Expires', 'Forwarded', 'From', 'Host', 'If-Match', 'If-Modified-Since', 'If-None-Match', 'If-Range', 'If-Unmodified-Since', 'Keep-Alive', 'Last-Modified', 'Link', 'Location', 'Max-Forwards', 'Origin', 'Permissions-Policy', 'Pragma', 'Proxy-Authenticate', 'Proxy-Authorization', 'RTT', 'Range', 'Referer', 'Referrer-Policy', 'Refresh', 'Retry-After', 'Sec-WebSocket-Accept', 'Sec-WebSocket-Extensions', 'Sec-WebSocket-Key', 'Sec-WebSocket-Protocol', 'Sec-WebSocket-Version', 'Server', 'Server-Timing', 'Service-Worker-Allowed', 'Service-Worker-Navigation-Preload', 'Set-Cookie', 'SourceMap', 'Strict-Transport-Security', 'Supports-Loading-Mode', 'TE', 'Timing-Allow-Origin', 'Trailer', 'Transfer-Encoding', 'Upgrade', 'Upgrade-Insecure-Requests', 'User-Agent', 'Vary', 'Via', 'WWW-Authenticate', 'X-Content-Type-Options', 'X-DNS-Prefetch-Control', 'X-Frame-Options', 'X-Permitted-Cross-Domain-Policies', 'X-Powered-By', 'X-Requested-With', 'X-XSS-Protection' ] for (let i = 0; i < wellknownHeaderNames.length; ++i) { const key = wellknownHeaderNames[i] const lowerCasedKey = key.toLowerCase() headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey } // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. Object.setPrototypeOf(headerNameLowerCasedRecord, null) module.exports = { wellknownHeaderNames, headerNameLowerCasedRecord } /***/ }), /***/ 2414: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const diagnosticsChannel = __nccwpck_require__(3053) const util = __nccwpck_require__(7975) const undiciDebugLog = util.debuglog('undici') const fetchDebuglog = util.debuglog('fetch') const websocketDebuglog = util.debuglog('websocket') let isClientSet = false const channels = { // Client beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'), connected: diagnosticsChannel.channel('undici:client:connected'), connectError: diagnosticsChannel.channel('undici:client:connectError'), sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'), // Request create: diagnosticsChannel.channel('undici:request:create'), bodySent: diagnosticsChannel.channel('undici:request:bodySent'), headers: diagnosticsChannel.channel('undici:request:headers'), trailers: diagnosticsChannel.channel('undici:request:trailers'), error: diagnosticsChannel.channel('undici:request:error'), // WebSocket open: diagnosticsChannel.channel('undici:websocket:open'), close: diagnosticsChannel.channel('undici:websocket:close'), socketError: diagnosticsChannel.channel('undici:websocket:socket_error'), ping: diagnosticsChannel.channel('undici:websocket:ping'), pong: diagnosticsChannel.channel('undici:websocket:pong') } if (undiciDebugLog.enabled || fetchDebuglog.enabled) { const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog // Track all Client events diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => { const { connectParams: { version, protocol, port, host } } = evt debuglog( 'connecting to %s using %s%s', `${host}${port ? `:${port}` : ''}`, protocol, version ) }) diagnosticsChannel.channel('undici:client:connected').subscribe(evt => { const { connectParams: { version, protocol, port, host } } = evt debuglog( 'connected to %s using %s%s', `${host}${port ? `:${port}` : ''}`, protocol, version ) }) diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => { const { connectParams: { version, protocol, port, host }, error } = evt debuglog( 'connection to %s using %s%s errored - %s', `${host}${port ? `:${port}` : ''}`, protocol, version, error.message ) }) diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => { const { request: { method, path, origin } } = evt debuglog('sending request to %s %s/%s', method, origin, path) }) // Track Request events diagnosticsChannel.channel('undici:request:headers').subscribe(evt => { const { request: { method, path, origin }, response: { statusCode } } = evt debuglog( 'received response to %s %s/%s - HTTP %d', method, origin, path, statusCode ) }) diagnosticsChannel.channel('undici:request:trailers').subscribe(evt => { const { request: { method, path, origin } } = evt debuglog('trailers received from %s %s/%s', method, origin, path) }) diagnosticsChannel.channel('undici:request:error').subscribe(evt => { const { request: { method, path, origin }, error } = evt debuglog( 'request to %s %s/%s errored - %s', method, origin, path, error.message ) }) isClientSet = true } if (websocketDebuglog.enabled) { if (!isClientSet) { const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => { const { connectParams: { version, protocol, port, host } } = evt debuglog( 'connecting to %s%s using %s%s', host, port ? `:${port}` : '', protocol, version ) }) diagnosticsChannel.channel('undici:client:connected').subscribe(evt => { const { connectParams: { version, protocol, port, host } } = evt debuglog( 'connected to %s%s using %s%s', host, port ? `:${port}` : '', protocol, version ) }) diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => { const { connectParams: { version, protocol, port, host }, error } = evt debuglog( 'connection to %s%s using %s%s errored - %s', host, port ? `:${port}` : '', protocol, version, error.message ) }) diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => { const { request: { method, path, origin } } = evt debuglog('sending request to %s %s/%s', method, origin, path) }) } // Track all WebSocket events diagnosticsChannel.channel('undici:websocket:open').subscribe(evt => { const { address: { address, port } } = evt websocketDebuglog('connection opened %s%s', address, port ? `:${port}` : '') }) diagnosticsChannel.channel('undici:websocket:close').subscribe(evt => { const { websocket, code, reason } = evt websocketDebuglog( 'closed connection to %s - %s %s', websocket.url, code, reason ) }) diagnosticsChannel.channel('undici:websocket:socket_error').subscribe(err => { websocketDebuglog('connection errored - %s', err.message) }) diagnosticsChannel.channel('undici:websocket:ping').subscribe(evt => { websocketDebuglog('ping received') }) diagnosticsChannel.channel('undici:websocket:pong').subscribe(evt => { websocketDebuglog('pong received') }) } module.exports = { channels } /***/ }), /***/ 8707: /***/ ((module) => { "use strict"; const kUndiciError = Symbol.for('undici.error.UND_ERR') class UndiciError extends Error { constructor (message) { super(message) this.name = 'UndiciError' this.code = 'UND_ERR' } static [Symbol.hasInstance] (instance) { return instance && instance[kUndiciError] === true } [kUndiciError] = true } const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT') class ConnectTimeoutError extends UndiciError { constructor (message) { super(message) this.name = 'ConnectTimeoutError' this.message = message || 'Connect Timeout Error' this.code = 'UND_ERR_CONNECT_TIMEOUT' } static [Symbol.hasInstance] (instance) { return instance && instance[kConnectTimeoutError] === true } [kConnectTimeoutError] = true } const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT') class HeadersTimeoutError extends UndiciError { constructor (message) { super(message) this.name = 'HeadersTimeoutError' this.message = message || 'Headers Timeout Error' this.code = 'UND_ERR_HEADERS_TIMEOUT' } static [Symbol.hasInstance] (instance) { return instance && instance[kHeadersTimeoutError] === true } [kHeadersTimeoutError] = true } const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW') class HeadersOverflowError extends UndiciError { constructor (message) { super(message) this.name = 'HeadersOverflowError' this.message = message || 'Headers Overflow Error' this.code = 'UND_ERR_HEADERS_OVERFLOW' } static [Symbol.hasInstance] (instance) { return instance && instance[kHeadersOverflowError] === true } [kHeadersOverflowError] = true } const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT') class BodyTimeoutError extends UndiciError { constructor (message) { super(message) this.name = 'BodyTimeoutError' this.message = message || 'Body Timeout Error' this.code = 'UND_ERR_BODY_TIMEOUT' } static [Symbol.hasInstance] (instance) { return instance && instance[kBodyTimeoutError] === true } [kBodyTimeoutError] = true } const kResponseStatusCodeError = Symbol.for('undici.error.UND_ERR_RESPONSE_STATUS_CODE') class ResponseStatusCodeError extends UndiciError { constructor (message, statusCode, headers, body) { super(message) this.name = 'ResponseStatusCodeError' this.message = message || 'Response Status Code Error' this.code = 'UND_ERR_RESPONSE_STATUS_CODE' this.body = body this.status = statusCode this.statusCode = statusCode this.headers = headers } static [Symbol.hasInstance] (instance) { return instance && instance[kResponseStatusCodeError] === true } [kResponseStatusCodeError] = true } const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG') class InvalidArgumentError extends UndiciError { constructor (message) { super(message) this.name = 'InvalidArgumentError' this.message = message || 'Invalid Argument Error' this.code = 'UND_ERR_INVALID_ARG' } static [Symbol.hasInstance] (instance) { return instance && instance[kInvalidArgumentError] === true } [kInvalidArgumentError] = true } const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE') class InvalidReturnValueError extends UndiciError { constructor (message) { super(message) this.name = 'InvalidReturnValueError' this.message = message || 'Invalid Return Value Error' this.code = 'UND_ERR_INVALID_RETURN_VALUE' } static [Symbol.hasInstance] (instance) { return instance && instance[kInvalidReturnValueError] === true } [kInvalidReturnValueError] = true } const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT') class AbortError extends UndiciError { constructor (message) { super(message) this.name = 'AbortError' this.message = message || 'The operation was aborted' this.code = 'UND_ERR_ABORT' } static [Symbol.hasInstance] (instance) { return instance && instance[kAbortError] === true } [kAbortError] = true } const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED') class RequestAbortedError extends AbortError { constructor (message) { super(message) this.name = 'AbortError' this.message = message || 'Request aborted' this.code = 'UND_ERR_ABORTED' } static [Symbol.hasInstance] (instance) { return instance && instance[kRequestAbortedError] === true } [kRequestAbortedError] = true } const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO') class InformationalError extends UndiciError { constructor (message) { super(message) this.name = 'InformationalError' this.message = message || 'Request information' this.code = 'UND_ERR_INFO' } static [Symbol.hasInstance] (instance) { return instance && instance[kInformationalError] === true } [kInformationalError] = true } const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH') class RequestContentLengthMismatchError extends UndiciError { constructor (message) { super(message) this.name = 'RequestContentLengthMismatchError' this.message = message || 'Request body length does not match content-length header' this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' } static [Symbol.hasInstance] (instance) { return instance && instance[kRequestContentLengthMismatchError] === true } [kRequestContentLengthMismatchError] = true } const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH') class ResponseContentLengthMismatchError extends UndiciError { constructor (message) { super(message) this.name = 'ResponseContentLengthMismatchError' this.message = message || 'Response body length does not match content-length header' this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' } static [Symbol.hasInstance] (instance) { return instance && instance[kResponseContentLengthMismatchError] === true } [kResponseContentLengthMismatchError] = true } const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED') class ClientDestroyedError extends UndiciError { constructor (message) { super(message) this.name = 'ClientDestroyedError' this.message = message || 'The client is destroyed' this.code = 'UND_ERR_DESTROYED' } static [Symbol.hasInstance] (instance) { return instance && instance[kClientDestroyedError] === true } [kClientDestroyedError] = true } const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED') class ClientClosedError extends UndiciError { constructor (message) { super(message) this.name = 'ClientClosedError' this.message = message || 'The client is closed' this.code = 'UND_ERR_CLOSED' } static [Symbol.hasInstance] (instance) { return instance && instance[kClientClosedError] === true } [kClientClosedError] = true } const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET') class SocketError extends UndiciError { constructor (message, socket) { super(message) this.name = 'SocketError' this.message = message || 'Socket error' this.code = 'UND_ERR_SOCKET' this.socket = socket } static [Symbol.hasInstance] (instance) { return instance && instance[kSocketError] === true } [kSocketError] = true } const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED') class NotSupportedError extends UndiciError { constructor (message) { super(message) this.name = 'NotSupportedError' this.message = message || 'Not supported error' this.code = 'UND_ERR_NOT_SUPPORTED' } static [Symbol.hasInstance] (instance) { return instance && instance[kNotSupportedError] === true } [kNotSupportedError] = true } const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM') class BalancedPoolMissingUpstreamError extends UndiciError { constructor (message) { super(message) this.name = 'MissingUpstreamError' this.message = message || 'No upstream has been added to the BalancedPool' this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' } static [Symbol.hasInstance] (instance) { return instance && instance[kBalancedPoolMissingUpstreamError] === true } [kBalancedPoolMissingUpstreamError] = true } const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER') class HTTPParserError extends Error { constructor (message, code, data) { super(message) this.name = 'HTTPParserError' this.code = code ? `HPE_${code}` : undefined this.data = data ? data.toString() : undefined } static [Symbol.hasInstance] (instance) { return instance && instance[kHTTPParserError] === true } [kHTTPParserError] = true } const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE') class ResponseExceededMaxSizeError extends UndiciError { constructor (message) { super(message) this.name = 'ResponseExceededMaxSizeError' this.message = message || 'Response content exceeded max size' this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' } static [Symbol.hasInstance] (instance) { return instance && instance[kResponseExceededMaxSizeError] === true } [kResponseExceededMaxSizeError] = true } const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY') class RequestRetryError extends UndiciError { constructor (message, code, { headers, data }) { super(message) this.name = 'RequestRetryError' this.message = message || 'Request retry error' this.code = 'UND_ERR_REQ_RETRY' this.statusCode = code this.data = data this.headers = headers } static [Symbol.hasInstance] (instance) { return instance && instance[kRequestRetryError] === true } [kRequestRetryError] = true } const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE') class ResponseError extends UndiciError { constructor (message, code, { headers, data }) { super(message) this.name = 'ResponseError' this.message = message || 'Response error' this.code = 'UND_ERR_RESPONSE' this.statusCode = code this.data = data this.headers = headers } static [Symbol.hasInstance] (instance) { return instance && instance[kResponseError] === true } [kResponseError] = true } const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS') class SecureProxyConnectionError extends UndiciError { constructor (cause, message, options) { super(message, { cause, ...(options ?? {}) }) this.name = 'SecureProxyConnectionError' this.message = message || 'Secure Proxy Connection failed' this.code = 'UND_ERR_PRX_TLS' this.cause = cause } static [Symbol.hasInstance] (instance) { return instance && instance[kSecureProxyConnectionError] === true } [kSecureProxyConnectionError] = true } const kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED') class MessageSizeExceededError extends UndiciError { constructor (message) { super(message) this.name = 'MessageSizeExceededError' this.message = message || 'Max decompressed message size exceeded' this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED' } static [Symbol.hasInstance] (instance) { return instance && instance[kMessageSizeExceededError] === true } get [kMessageSizeExceededError] () { return true } } module.exports = { AbortError, HTTPParserError, UndiciError, HeadersTimeoutError, HeadersOverflowError, BodyTimeoutError, RequestContentLengthMismatchError, ConnectTimeoutError, ResponseStatusCodeError, InvalidArgumentError, InvalidReturnValueError, RequestAbortedError, ClientDestroyedError, ClientClosedError, InformationalError, SocketError, NotSupportedError, ResponseContentLengthMismatchError, BalancedPoolMissingUpstreamError, ResponseExceededMaxSizeError, RequestRetryError, ResponseError, SecureProxyConnectionError, MessageSizeExceededError } /***/ }), /***/ 4655: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError, NotSupportedError } = __nccwpck_require__(8707) const assert = __nccwpck_require__(4589) const { isValidHTTPToken, isValidHeaderValue, isStream, destroy, isBuffer, isFormDataLike, isIterable, isBlobLike, buildURL, validateHandler, getServerName, normalizedMethodRecords } = __nccwpck_require__(3440) const { channels } = __nccwpck_require__(2414) const { headerNameLowerCasedRecord } = __nccwpck_require__(735) // Verifies that a given path is valid does not contain control chars \x00 to \x20 const invalidPathRegex = /[^\u0021-\u00ff]/ const kHandler = Symbol('handler') class Request { constructor (origin, { path, method, body, headers, query, idempotent, blocking, upgrade, headersTimeout, bodyTimeout, reset, throwOnError, expectContinue, servername }, handler) { if (typeof path !== 'string') { throw new InvalidArgumentError('path must be a string') } else if ( path[0] !== '/' && !(path.startsWith('http://') || path.startsWith('https://')) && method !== 'CONNECT' ) { throw new InvalidArgumentError('path must be an absolute URL or start with a slash') } else if (invalidPathRegex.test(path)) { throw new InvalidArgumentError('invalid request path') } if (typeof method !== 'string') { throw new InvalidArgumentError('method must be a string') } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) { throw new InvalidArgumentError('invalid request method') } if (upgrade && typeof upgrade !== 'string') { throw new InvalidArgumentError('upgrade must be a string') } if (upgrade && !isValidHeaderValue(upgrade)) { throw new InvalidArgumentError('invalid upgrade header') } if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { throw new InvalidArgumentError('invalid headersTimeout') } if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { throw new InvalidArgumentError('invalid bodyTimeout') } if (reset != null && typeof reset !== 'boolean') { throw new InvalidArgumentError('invalid reset') } if (expectContinue != null && typeof expectContinue !== 'boolean') { throw new InvalidArgumentError('invalid expectContinue') } this.headersTimeout = headersTimeout this.bodyTimeout = bodyTimeout this.throwOnError = throwOnError === true this.method = method this.abort = null if (body == null) { this.body = null } else if (isStream(body)) { this.body = body const rState = this.body._readableState if (!rState || !rState.autoDestroy) { this.endHandler = function autoDestroy () { destroy(this) } this.body.on('end', this.endHandler) } this.errorHandler = err => { if (this.abort) { this.abort(err) } else { this.error = err } } this.body.on('error', this.errorHandler) } else if (isBuffer(body)) { this.body = body.byteLength ? body : null } else if (ArrayBuffer.isView(body)) { this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null } else if (body instanceof ArrayBuffer) { this.body = body.byteLength ? Buffer.from(body) : null } else if (typeof body === 'string') { this.body = body.length ? Buffer.from(body) : null } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { this.body = body } else { throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') } this.completed = false this.aborted = false this.upgrade = upgrade || null this.path = query ? buildURL(path, query) : path this.origin = origin this.idempotent = idempotent == null ? method === 'HEAD' || method === 'GET' : idempotent this.blocking = blocking == null ? false : blocking this.reset = reset == null ? null : reset this.host = null this.contentLength = null this.contentType = null this.headers = [] // Only for H2 this.expectContinue = expectContinue != null ? expectContinue : false if (Array.isArray(headers)) { if (headers.length % 2 !== 0) { throw new InvalidArgumentError('headers array must be even') } for (let i = 0; i < headers.length; i += 2) { processHeader(this, headers[i], headers[i + 1]) } } else if (headers && typeof headers === 'object') { if (headers[Symbol.iterator]) { for (const header of headers) { if (!Array.isArray(header) || header.length !== 2) { throw new InvalidArgumentError('headers must be in key-value pair format') } processHeader(this, header[0], header[1]) } } else { const keys = Object.keys(headers) for (let i = 0; i < keys.length; ++i) { processHeader(this, keys[i], headers[keys[i]]) } } } else if (headers != null) { throw new InvalidArgumentError('headers must be an object or an array') } validateHandler(handler, method, upgrade) this.servername = servername || getServerName(this.host) this[kHandler] = handler if (channels.create.hasSubscribers) { channels.create.publish({ request: this }) } } onBodySent (chunk) { if (this[kHandler].onBodySent) { try { return this[kHandler].onBodySent(chunk) } catch (err) { this.abort(err) } } } onRequestSent () { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }) } if (this[kHandler].onRequestSent) { try { return this[kHandler].onRequestSent() } catch (err) { this.abort(err) } } } onConnect (abort) { assert(!this.aborted) assert(!this.completed) if (this.error) { abort(this.error) } else { this.abort = abort return this[kHandler].onConnect(abort) } } onResponseStarted () { return this[kHandler].onResponseStarted?.() } onHeaders (statusCode, headers, resume, statusText) { assert(!this.aborted) assert(!this.completed) if (channels.headers.hasSubscribers) { channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) } try { return this[kHandler].onHeaders(statusCode, headers, resume, statusText) } catch (err) { this.abort(err) } } onData (chunk) { assert(!this.aborted) assert(!this.completed) try { return this[kHandler].onData(chunk) } catch (err) { this.abort(err) return false } } onUpgrade (statusCode, headers, socket) { assert(!this.aborted) assert(!this.completed) return this[kHandler].onUpgrade(statusCode, headers, socket) } onComplete (trailers) { this.onFinally() assert(!this.aborted) this.completed = true if (channels.trailers.hasSubscribers) { channels.trailers.publish({ request: this, trailers }) } try { return this[kHandler].onComplete(trailers) } catch (err) { // TODO (fix): This might be a bad idea? this.onError(err) } } onError (error) { this.onFinally() if (channels.error.hasSubscribers) { channels.error.publish({ request: this, error }) } if (this.aborted) { return } this.aborted = true return this[kHandler].onError(error) } onFinally () { if (this.errorHandler) { this.body.off('error', this.errorHandler) this.errorHandler = null } if (this.endHandler) { this.body.off('end', this.endHandler) this.endHandler = null } } addHeader (key, value) { processHeader(this, key, value) return this } } function processHeader (request, key, val) { if (val && (typeof val === 'object' && !Array.isArray(val))) { throw new InvalidArgumentError(`invalid ${key} header`) } else if (val === undefined) { return } let headerName = headerNameLowerCasedRecord[key] if (headerName === undefined) { headerName = key.toLowerCase() if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) { throw new InvalidArgumentError('invalid header key') } } if (Array.isArray(val)) { const arr = [] for (let i = 0; i < val.length; i++) { if (typeof val[i] === 'string') { if (!isValidHeaderValue(val[i])) { throw new InvalidArgumentError(`invalid ${key} header`) } arr.push(val[i]) } else if (val[i] === null) { arr.push('') } else if (typeof val[i] === 'object') { throw new InvalidArgumentError(`invalid ${key} header`) } else { arr.push(`${val[i]}`) } } val = arr } else if (typeof val === 'string') { if (!isValidHeaderValue(val)) { throw new InvalidArgumentError(`invalid ${key} header`) } } else if (val === null) { val = '' } else { val = `${val}` } if (headerName === 'host') { if (request.host !== null) { throw new InvalidArgumentError('duplicate host header') } if (typeof val !== 'string') { throw new InvalidArgumentError('invalid host header') } // Consumed by Client request.host = val } else if (headerName === 'content-length') { if (request.contentLength !== null) { throw new InvalidArgumentError('duplicate content-length header') } request.contentLength = parseInt(val, 10) if (!Number.isFinite(request.contentLength)) { throw new InvalidArgumentError('invalid content-length header') } } else if (request.contentType === null && headerName === 'content-type') { request.contentType = val request.headers.push(key, val) } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') { throw new InvalidArgumentError(`invalid ${headerName} header`) } else if (headerName === 'connection') { const value = typeof val === 'string' ? val.toLowerCase() : null if (value !== 'close' && value !== 'keep-alive') { throw new InvalidArgumentError('invalid connection header') } if (value === 'close') { request.reset = true } } else if (headerName === 'expect') { throw new NotSupportedError('expect header not supported') } else { request.headers.push(key, val) } } module.exports = Request /***/ }), /***/ 6443: /***/ ((module) => { module.exports = { kClose: Symbol('close'), kDestroy: Symbol('destroy'), kDispatch: Symbol('dispatch'), kUrl: Symbol('url'), kWriting: Symbol('writing'), kResuming: Symbol('resuming'), kQueue: Symbol('queue'), kConnect: Symbol('connect'), kConnecting: Symbol('connecting'), kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), kKeepAliveTimeoutValue: Symbol('keep alive timeout'), kKeepAlive: Symbol('keep alive'), kHeadersTimeout: Symbol('headers timeout'), kBodyTimeout: Symbol('body timeout'), kServerName: Symbol('server name'), kLocalAddress: Symbol('local address'), kHost: Symbol('host'), kNoRef: Symbol('no ref'), kBodyUsed: Symbol('used'), kBody: Symbol('abstracted request body'), kRunning: Symbol('running'), kBlocking: Symbol('blocking'), kPending: Symbol('pending'), kSize: Symbol('size'), kBusy: Symbol('busy'), kQueued: Symbol('queued'), kFree: Symbol('free'), kConnected: Symbol('connected'), kClosed: Symbol('closed'), kNeedDrain: Symbol('need drain'), kReset: Symbol('reset'), kDestroyed: Symbol.for('nodejs.stream.destroyed'), kResume: Symbol('resume'), kOnError: Symbol('on error'), kMaxHeadersSize: Symbol('max headers size'), kRunningIdx: Symbol('running index'), kPendingIdx: Symbol('pending index'), kError: Symbol('error'), kClients: Symbol('clients'), kClient: Symbol('client'), kParser: Symbol('parser'), kOnDestroyed: Symbol('destroy callbacks'), kPipelining: Symbol('pipelining'), kSocket: Symbol('socket'), kHostHeader: Symbol('host header'), kConnector: Symbol('connector'), kStrictContentLength: Symbol('strict content length'), kMaxRedirections: Symbol('maxRedirections'), kMaxRequests: Symbol('maxRequestsPerClient'), kProxy: Symbol('proxy agent options'), kCounter: Symbol('socket request counter'), kInterceptors: Symbol('dispatch interceptors'), kMaxResponseSize: Symbol('max response size'), kHTTP2Session: Symbol('http2Session'), kHTTP2SessionState: Symbol('http2Session state'), kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), kConstruct: Symbol('constructable'), kListeners: Symbol('listeners'), kHTTPContext: Symbol('http context'), kMaxConcurrentStreams: Symbol('max concurrent streams'), kNoProxyAgent: Symbol('no proxy agent'), kHttpProxyAgent: Symbol('http proxy agent'), kHttpsProxyAgent: Symbol('https proxy agent') } /***/ }), /***/ 7752: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { wellknownHeaderNames, headerNameLowerCasedRecord } = __nccwpck_require__(735) class TstNode { /** @type {any} */ value = null /** @type {null | TstNode} */ left = null /** @type {null | TstNode} */ middle = null /** @type {null | TstNode} */ right = null /** @type {number} */ code /** * @param {string} key * @param {any} value * @param {number} index */ constructor (key, value, index) { if (index === undefined || index >= key.length) { throw new TypeError('Unreachable') } const code = this.code = key.charCodeAt(index) // check code is ascii string if (code > 0x7F) { throw new TypeError('key must be ascii string') } if (key.length !== ++index) { this.middle = new TstNode(key, value, index) } else { this.value = value } } /** * @param {string} key * @param {any} value */ add (key, value) { const length = key.length if (length === 0) { throw new TypeError('Unreachable') } let index = 0 let node = this while (true) { const code = key.charCodeAt(index) // check code is ascii string if (code > 0x7F) { throw new TypeError('key must be ascii string') } if (node.code === code) { if (length === ++index) { node.value = value break } else if (node.middle !== null) { node = node.middle } else { node.middle = new TstNode(key, value, index) break } } else if (node.code < code) { if (node.left !== null) { node = node.left } else { node.left = new TstNode(key, value, index) break } } else if (node.right !== null) { node = node.right } else { node.right = new TstNode(key, value, index) break } } } /** * @param {Uint8Array} key * @return {TstNode | null} */ search (key) { const keylength = key.length let index = 0 let node = this while (node !== null && index < keylength) { let code = key[index] // A-Z // First check if it is bigger than 0x5a. // Lowercase letters have higher char codes than uppercase ones. // Also we assume that headers will mostly contain lowercase characters. if (code <= 0x5a && code >= 0x41) { // Lowercase for uppercase. code |= 32 } while (node !== null) { if (code === node.code) { if (keylength === ++index) { // Returns Node since it is the last key. return node } node = node.middle break } node = node.code < code ? node.left : node.right } } return null } } class TernarySearchTree { /** @type {TstNode | null} */ node = null /** * @param {string} key * @param {any} value * */ insert (key, value) { if (this.node === null) { this.node = new TstNode(key, value, 0) } else { this.node.add(key, value) } } /** * @param {Uint8Array} key * @return {any} */ lookup (key) { return this.node?.search(key)?.value ?? null } } const tree = new TernarySearchTree() for (let i = 0; i < wellknownHeaderNames.length; ++i) { const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]] tree.insert(key, key) } module.exports = { TernarySearchTree, tree } /***/ }), /***/ 3440: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) const { kDestroyed, kBodyUsed, kListeners, kBody } = __nccwpck_require__(6443) const { IncomingMessage } = __nccwpck_require__(7067) const stream = __nccwpck_require__(7075) const net = __nccwpck_require__(7030) const { Blob } = __nccwpck_require__(4573) const nodeUtil = __nccwpck_require__(7975) const { stringify } = __nccwpck_require__(1792) const { EventEmitter: EE } = __nccwpck_require__(8474) const { InvalidArgumentError } = __nccwpck_require__(8707) const { headerNameLowerCasedRecord } = __nccwpck_require__(735) const { tree } = __nccwpck_require__(7752) const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) class BodyAsyncIterable { constructor (body) { this[kBody] = body this[kBodyUsed] = false } async * [Symbol.asyncIterator] () { assert(!this[kBodyUsed], 'disturbed') this[kBodyUsed] = true yield * this[kBody] } } function wrapRequestBody (body) { if (isStream(body)) { // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp // so that it can be dispatched again? // TODO (fix): Do we need 100-expect support to provide a way to do this properly? if (bodyLength(body) === 0) { body .on('data', function () { assert(false) }) } if (typeof body.readableDidRead !== 'boolean') { body[kBodyUsed] = false EE.prototype.on.call(body, 'data', function () { this[kBodyUsed] = true }) } return body } else if (body && typeof body.pipeTo === 'function') { // TODO (fix): We can't access ReadableStream internal state // to determine whether or not it has been disturbed. This is just // a workaround. return new BodyAsyncIterable(body) } else if ( body && typeof body !== 'string' && !ArrayBuffer.isView(body) && isIterable(body) ) { // TODO: Should we allow re-using iterable if !this.opts.idempotent // or through some other flag? return new BodyAsyncIterable(body) } else { return body } } function nop () {} function isStream (obj) { return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' } // based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) function isBlobLike (object) { if (object === null) { return false } else if (object instanceof Blob) { return true } else if (typeof object !== 'object') { return false } else { const sTag = object[Symbol.toStringTag] return (sTag === 'Blob' || sTag === 'File') && ( ('stream' in object && typeof object.stream === 'function') || ('arrayBuffer' in object && typeof object.arrayBuffer === 'function') ) } } function buildURL (url, queryParams) { if (url.includes('?') || url.includes('#')) { throw new Error('Query params cannot be passed when url already contains "?" or "#".') } const stringified = stringify(queryParams) if (stringified) { url += '?' + stringified } return url } function isValidPort (port) { const value = parseInt(port, 10) return ( value === Number(port) && value >= 0 && value <= 65535 ) } function isHttpOrHttpsPrefixed (value) { return ( value != null && value[0] === 'h' && value[1] === 't' && value[2] === 't' && value[3] === 'p' && ( value[4] === ':' || ( value[4] === 's' && value[5] === ':' ) ) ) } function parseURL (url) { if (typeof url === 'string') { url = new URL(url) if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } return url } if (!url || typeof url !== 'object') { throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') } if (!(url instanceof URL)) { if (url.port != null && url.port !== '' && isValidPort(url.port) === false) { throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') } if (url.path != null && typeof url.path !== 'string') { throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') } if (url.pathname != null && typeof url.pathname !== 'string') { throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') } if (url.hostname != null && typeof url.hostname !== 'string') { throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') } if (url.origin != null && typeof url.origin !== 'string') { throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') } if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } const port = url.port != null ? url.port : (url.protocol === 'https:' ? 443 : 80) let origin = url.origin != null ? url.origin : `${url.protocol || ''}//${url.hostname || ''}:${port}` let path = url.path != null ? url.path : `${url.pathname || ''}${url.search || ''}` if (origin[origin.length - 1] === '/') { origin = origin.slice(0, origin.length - 1) } if (path && path[0] !== '/') { path = `/${path}` } // new URL(path, origin) is unsafe when `path` contains an absolute URL // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: // If first parameter is a relative URL, second param is required, and will be used as the base URL. // If first parameter is an absolute URL, a given second param will be ignored. return new URL(`${origin}${path}`) } if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } return url } function parseOrigin (url) { url = parseURL(url) if (url.pathname !== '/' || url.search || url.hash) { throw new InvalidArgumentError('invalid url') } return url } function getHostname (host) { if (host[0] === '[') { const idx = host.indexOf(']') assert(idx !== -1) return host.substring(1, idx) } const idx = host.indexOf(':') if (idx === -1) return host return host.substring(0, idx) } // IP addresses are not valid server names per RFC6066 // > Currently, the only server names supported are DNS hostnames function getServerName (host) { if (!host) { return null } assert(typeof host === 'string') const servername = getHostname(host) if (net.isIP(servername)) { return '' } return servername } function deepClone (obj) { return JSON.parse(JSON.stringify(obj)) } function isAsyncIterable (obj) { return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') } function isIterable (obj) { return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) } function bodyLength (body) { if (body == null) { return 0 } else if (isStream(body)) { const state = body._readableState return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null } else if (isBlobLike(body)) { return body.size != null ? body.size : null } else if (isBuffer(body)) { return body.byteLength } return null } function isDestroyed (body) { return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body))) } function destroy (stream, err) { if (stream == null || !isStream(stream) || isDestroyed(stream)) { return } if (typeof stream.destroy === 'function') { if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { // See: https://github.com/nodejs/node/pull/38505/files stream.socket = null } stream.destroy(err) } else if (err) { queueMicrotask(() => { stream.emit('error', err) }) } if (stream.destroyed !== true) { stream[kDestroyed] = true } } const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ function parseKeepAliveTimeout (val) { const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) return m ? parseInt(m[1], 10) * 1000 : null } /** * Retrieves a header name and returns its lowercase value. * @param {string | Buffer} value Header name * @returns {string} */ function headerNameToString (value) { return typeof value === 'string' ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString('latin1').toLowerCase() } /** * Receive the buffer as a string and return its lowercase value. * @param {Buffer} value Header name * @returns {string} */ function bufferToLowerCasedHeaderName (value) { return tree.lookup(value) ?? value.toString('latin1').toLowerCase() } /** * @param {Record | (Buffer | string | (Buffer | string)[])[]} headers * @param {Record} [obj] * @returns {Record} */ function parseHeaders (headers, obj) { if (obj === undefined) obj = {} for (let i = 0; i < headers.length; i += 2) { const key = headerNameToString(headers[i]) let val = obj[key] if (val) { if (typeof val === 'string') { val = [val] obj[key] = val } val.push(headers[i + 1].toString('utf8')) } else { const headersValue = headers[i + 1] if (typeof headersValue === 'string') { obj[key] = headersValue } else { obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8') } } } // See https://github.com/nodejs/node/pull/46528 if ('content-length' in obj && 'content-disposition' in obj) { obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') } return obj } function parseRawHeaders (headers) { const len = headers.length const ret = new Array(len) let hasContentLength = false let contentDispositionIdx = -1 let key let val let kLen = 0 for (let n = 0; n < headers.length; n += 2) { key = headers[n] val = headers[n + 1] typeof key !== 'string' && (key = key.toString()) typeof val !== 'string' && (val = val.toString('utf8')) kLen = key.length if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) { hasContentLength = true } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { contentDispositionIdx = n + 1 } ret[n] = key ret[n + 1] = val } // See https://github.com/nodejs/node/pull/46528 if (hasContentLength && contentDispositionIdx !== -1) { ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') } return ret } function isBuffer (buffer) { // See, https://github.com/mcollina/undici/pull/319 return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) } function validateHandler (handler, method, upgrade) { if (!handler || typeof handler !== 'object') { throw new InvalidArgumentError('handler must be an object') } if (typeof handler.onConnect !== 'function') { throw new InvalidArgumentError('invalid onConnect method') } if (typeof handler.onError !== 'function') { throw new InvalidArgumentError('invalid onError method') } if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { throw new InvalidArgumentError('invalid onBodySent method') } if (upgrade || method === 'CONNECT') { if (typeof handler.onUpgrade !== 'function') { throw new InvalidArgumentError('invalid onUpgrade method') } } else { if (typeof handler.onHeaders !== 'function') { throw new InvalidArgumentError('invalid onHeaders method') } if (typeof handler.onData !== 'function') { throw new InvalidArgumentError('invalid onData method') } if (typeof handler.onComplete !== 'function') { throw new InvalidArgumentError('invalid onComplete method') } } } // A body is disturbed if it has been read from and it cannot // be re-used without losing state or data. function isDisturbed (body) { // TODO (fix): Why is body[kBodyUsed] needed? return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])) } function isErrored (body) { return !!(body && stream.isErrored(body)) } function isReadable (body) { return !!(body && stream.isReadable(body)) } function getSocketInfo (socket) { return { localAddress: socket.localAddress, localPort: socket.localPort, remoteAddress: socket.remoteAddress, remotePort: socket.remotePort, remoteFamily: socket.remoteFamily, timeout: socket.timeout, bytesWritten: socket.bytesWritten, bytesRead: socket.bytesRead } } /** @type {globalThis['ReadableStream']} */ function ReadableStreamFrom (iterable) { // We cannot use ReadableStream.from here because it does not return a byte stream. let iterator return new ReadableStream( { async start () { iterator = iterable[Symbol.asyncIterator]() }, async pull (controller) { const { done, value } = await iterator.next() if (done) { queueMicrotask(() => { controller.close() controller.byobRequest?.respond(0) }) } else { const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) if (buf.byteLength) { controller.enqueue(new Uint8Array(buf)) } } return controller.desiredSize > 0 }, async cancel (reason) { await iterator.return() }, type: 'bytes' } ) } // The chunk should be a FormData instance and contains // all the required methods. function isFormDataLike (object) { return ( object && typeof object === 'object' && typeof object.append === 'function' && typeof object.delete === 'function' && typeof object.get === 'function' && typeof object.getAll === 'function' && typeof object.has === 'function' && typeof object.set === 'function' && object[Symbol.toStringTag] === 'FormData' ) } function addAbortListener (signal, listener) { if ('addEventListener' in signal) { signal.addEventListener('abort', listener, { once: true }) return () => signal.removeEventListener('abort', listener) } signal.addListener('abort', listener) return () => signal.removeListener('abort', listener) } const hasToWellFormed = typeof String.prototype.toWellFormed === 'function' const hasIsWellFormed = typeof String.prototype.isWellFormed === 'function' /** * @param {string} val */ function toUSVString (val) { return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val) } /** * @param {string} val */ // TODO: move this to webidl function isUSVString (val) { return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}` } /** * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 * @param {number} c */ function isTokenCharCode (c) { switch (c) { case 0x22: case 0x28: case 0x29: case 0x2c: case 0x2f: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f: case 0x40: case 0x5b: case 0x5c: case 0x5d: case 0x7b: case 0x7d: // DQUOTE and "(),/:;<=>?@[\]{}" return false default: // VCHAR %x21-7E return c >= 0x21 && c <= 0x7e } } /** * @param {string} characters */ function isValidHTTPToken (characters) { if (characters.length === 0) { return false } for (let i = 0; i < characters.length; ++i) { if (!isTokenCharCode(characters.charCodeAt(i))) { return false } } return true } // headerCharRegex have been lifted from // https://github.com/nodejs/node/blob/main/lib/_http_common.js /** * Matches if val contains an invalid field-vchar * field-value = *( field-content / obs-fold ) * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] * field-vchar = VCHAR / obs-text */ const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ /** * @param {string} characters */ function isValidHeaderValue (characters) { return !headerCharRegex.test(characters) } // Parsed accordingly to RFC 9110 // https://www.rfc-editor.org/rfc/rfc9110#field.content-range function parseRangeHeader (range) { if (range == null || range === '') return { start: 0, end: null, size: null } const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null return m ? { start: parseInt(m[1]), end: m[2] ? parseInt(m[2]) : null, size: m[3] ? parseInt(m[3]) : null } : null } function addListener (obj, name, listener) { const listeners = (obj[kListeners] ??= []) listeners.push([name, listener]) obj.on(name, listener) return obj } function removeAllListeners (obj) { for (const [name, listener] of obj[kListeners] ?? []) { obj.removeListener(name, listener) } obj[kListeners] = null } function errorRequest (client, request, err) { try { request.onError(err) assert(request.aborted) } catch (err) { client.emit('error', err) } } const kEnumerableProperty = Object.create(null) kEnumerableProperty.enumerable = true const normalizedMethodRecordsBase = { delete: 'DELETE', DELETE: 'DELETE', get: 'GET', GET: 'GET', head: 'HEAD', HEAD: 'HEAD', options: 'OPTIONS', OPTIONS: 'OPTIONS', post: 'POST', POST: 'POST', put: 'PUT', PUT: 'PUT' } const normalizedMethodRecords = { ...normalizedMethodRecordsBase, patch: 'patch', PATCH: 'PATCH' } // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. Object.setPrototypeOf(normalizedMethodRecordsBase, null) Object.setPrototypeOf(normalizedMethodRecords, null) module.exports = { kEnumerableProperty, nop, isDisturbed, isErrored, isReadable, toUSVString, isUSVString, isBlobLike, parseOrigin, parseURL, getServerName, isStream, isIterable, isAsyncIterable, isDestroyed, headerNameToString, bufferToLowerCasedHeaderName, addListener, removeAllListeners, errorRequest, parseRawHeaders, parseHeaders, parseKeepAliveTimeout, destroy, bodyLength, deepClone, ReadableStreamFrom, isBuffer, validateHandler, getSocketInfo, isFormDataLike, buildURL, addAbortListener, isValidHTTPToken, isValidHeaderValue, isTokenCharCode, parseRangeHeader, normalizedMethodRecordsBase, normalizedMethodRecords, isValidPort, isHttpOrHttpsPrefixed, nodeMajor, nodeMinor, safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'], wrapRequestBody } /***/ }), /***/ 7405: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError } = __nccwpck_require__(8707) const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) const DispatcherBase = __nccwpck_require__(1841) const Pool = __nccwpck_require__(628) const Client = __nccwpck_require__(3701) const util = __nccwpck_require__(3440) const createRedirectInterceptor = __nccwpck_require__(5092) const kOnConnect = Symbol('onConnect') const kOnDisconnect = Symbol('onDisconnect') const kOnConnectionError = Symbol('onConnectionError') const kMaxRedirections = Symbol('maxRedirections') const kOnDrain = Symbol('onDrain') const kFactory = Symbol('factory') const kOptions = Symbol('options') function defaultFactory (origin, opts) { return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts) } class Agent extends DispatcherBase { constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { super() if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError('maxRedirections must be a positive number') } if (connect && typeof connect !== 'function') { connect = { ...connect } } this[kInterceptors] = options.interceptors?.Agent && Array.isArray(options.interceptors.Agent) ? options.interceptors.Agent : [createRedirectInterceptor({ maxRedirections })] this[kOptions] = { ...util.deepClone(options), connect } this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : undefined this[kMaxRedirections] = maxRedirections this[kFactory] = factory this[kClients] = new Map() this[kOnDrain] = (origin, targets) => { this.emit('drain', origin, [this, ...targets]) } this[kOnConnect] = (origin, targets) => { this.emit('connect', origin, [this, ...targets]) } this[kOnDisconnect] = (origin, targets, err) => { this.emit('disconnect', origin, [this, ...targets], err) } this[kOnConnectionError] = (origin, targets, err) => { this.emit('connectionError', origin, [this, ...targets], err) } } get [kRunning] () { let ret = 0 for (const client of this[kClients].values()) { ret += client[kRunning] } return ret } [kDispatch] (opts, handler) { let key if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { key = String(opts.origin) } else { throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') } let dispatcher = this[kClients].get(key) if (!dispatcher) { dispatcher = this[kFactory](opts.origin, this[kOptions]) .on('drain', this[kOnDrain]) .on('connect', this[kOnConnect]) .on('disconnect', this[kOnDisconnect]) .on('connectionError', this[kOnConnectionError]) // This introduces a tiny memory leak, as dispatchers are never removed from the map. // TODO(mcollina): remove te timer when the client/pool do not have any more // active connections. this[kClients].set(key, dispatcher) } return dispatcher.dispatch(opts, handler) } async [kClose] () { const closePromises = [] for (const client of this[kClients].values()) { closePromises.push(client.close()) } this[kClients].clear() await Promise.all(closePromises) } async [kDestroy] (err) { const destroyPromises = [] for (const client of this[kClients].values()) { destroyPromises.push(client.destroy(err)) } this[kClients].clear() await Promise.all(destroyPromises) } } module.exports = Agent /***/ }), /***/ 837: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { BalancedPoolMissingUpstreamError, InvalidArgumentError } = __nccwpck_require__(8707) const { PoolBase, kClients, kNeedDrain, kAddClient, kRemoveClient, kGetDispatcher } = __nccwpck_require__(2128) const Pool = __nccwpck_require__(628) const { kUrl, kInterceptors } = __nccwpck_require__(6443) const { parseOrigin } = __nccwpck_require__(3440) const kFactory = Symbol('factory') const kOptions = Symbol('options') const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') const kCurrentWeight = Symbol('kCurrentWeight') const kIndex = Symbol('kIndex') const kWeight = Symbol('kWeight') const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') const kErrorPenalty = Symbol('kErrorPenalty') /** * Calculate the greatest common divisor of two numbers by * using the Euclidean algorithm. * * @param {number} a * @param {number} b * @returns {number} */ function getGreatestCommonDivisor (a, b) { if (a === 0) return b while (b !== 0) { const t = b b = a % b a = t } return a } function defaultFactory (origin, opts) { return new Pool(origin, opts) } class BalancedPool extends PoolBase { constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { super() this[kOptions] = opts this[kIndex] = -1 this[kCurrentWeight] = 0 this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 this[kErrorPenalty] = this[kOptions].errorPenalty || 15 if (!Array.isArray(upstreams)) { upstreams = [upstreams] } if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) ? opts.interceptors.BalancedPool : [] this[kFactory] = factory for (const upstream of upstreams) { this.addUpstream(upstream) } this._updateBalancedPoolStats() } addUpstream (upstream) { const upstreamOrigin = parseOrigin(upstream).origin if (this[kClients].find((pool) => ( pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true ))) { return this } const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) this[kAddClient](pool) pool.on('connect', () => { pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) }) pool.on('connectionError', () => { pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) this._updateBalancedPoolStats() }) pool.on('disconnect', (...args) => { const err = args[2] if (err && err.code === 'UND_ERR_SOCKET') { // decrease the weight of the pool. pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) this._updateBalancedPoolStats() } }) for (const client of this[kClients]) { client[kWeight] = this[kMaxWeightPerServer] } this._updateBalancedPoolStats() return this } _updateBalancedPoolStats () { let result = 0 for (let i = 0; i < this[kClients].length; i++) { result = getGreatestCommonDivisor(this[kClients][i][kWeight], result) } this[kGreatestCommonDivisor] = result } removeUpstream (upstream) { const upstreamOrigin = parseOrigin(upstream).origin const pool = this[kClients].find((pool) => ( pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true )) if (pool) { this[kRemoveClient](pool) } return this } get upstreams () { return this[kClients] .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) .map((p) => p[kUrl].origin) } [kGetDispatcher] () { // We validate that pools is greater than 0, // otherwise we would have to wait until an upstream // is added, which might never happen. if (this[kClients].length === 0) { throw new BalancedPoolMissingUpstreamError() } const dispatcher = this[kClients].find(dispatcher => ( !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true )) if (!dispatcher) { return } const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) if (allClientsBusy) { return } let counter = 0 let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) while (counter++ < this[kClients].length) { this[kIndex] = (this[kIndex] + 1) % this[kClients].length const pool = this[kClients][this[kIndex]] // find pool index with the largest weight if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { maxWeightIndex = this[kIndex] } // decrease the current weight every `this[kClients].length`. if (this[kIndex] === 0) { // Set the current weight to the next lower weight. this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] if (this[kCurrentWeight] <= 0) { this[kCurrentWeight] = this[kMaxWeightPerServer] } } if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { return pool } } this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] this[kIndex] = maxWeightIndex return this[kClients][maxWeightIndex] } } module.exports = BalancedPool /***/ }), /***/ 637: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* global WebAssembly */ const assert = __nccwpck_require__(4589) const util = __nccwpck_require__(3440) const { channels } = __nccwpck_require__(2414) const timers = __nccwpck_require__(6603) const { RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, HeadersTimeoutError, HeadersOverflowError, SocketError, InformationalError, BodyTimeoutError, HTTPParserError, ResponseExceededMaxSizeError } = __nccwpck_require__(8707) const { kUrl, kReset, kClient, kParser, kBlocking, kRunning, kPending, kSize, kWriting, kQueue, kNoRef, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kSocket, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kMaxRequests, kCounter, kMaxResponseSize, kOnError, kResume, kHTTPContext } = __nccwpck_require__(6443) const constants = __nccwpck_require__(2824) const EMPTY_BUF = Buffer.alloc(0) const FastBuffer = Buffer[Symbol.species] const addListener = util.addListener const removeAllListeners = util.removeAllListeners let extractBody async function lazyllhttp () { const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined let mod try { mod = await WebAssembly.compile(__nccwpck_require__(3434)) } catch (e) { /* istanbul ignore next */ // We could check if the error was caused by the simd option not // being enabled, but the occurring of this other error // * https://github.com/emscripten-core/emscripten/issues/11495 // got me to remove that check to avoid breaking Node 12. mod = await WebAssembly.compile(llhttpWasmData || __nccwpck_require__(3870)) } return await WebAssembly.instantiate(mod, { env: { /* eslint-disable camelcase */ wasm_on_url: (p, at, len) => { /* istanbul ignore next */ return 0 }, wasm_on_status: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_message_begin: (p) => { assert(currentParser.ptr === p) return currentParser.onMessageBegin() || 0 }, wasm_on_header_field: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_header_value: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { assert(currentParser.ptr === p) return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 }, wasm_on_body: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_message_complete: (p) => { assert(currentParser.ptr === p) return currentParser.onMessageComplete() || 0 } /* eslint-enable camelcase */ } }) } let llhttpInstance = null let llhttpPromise = lazyllhttp() llhttpPromise.catch() let currentParser = null let currentBufferRef = null let currentBufferSize = 0 let currentBufferPtr = null const USE_NATIVE_TIMER = 0 const USE_FAST_TIMER = 1 // Use fast timers for headers and body to take eventual event loop // latency into account. const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER const TIMEOUT_BODY = 4 | USE_FAST_TIMER // Use native timers to ignore event loop latency for keep-alive // handling. const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER class Parser { constructor (client, socket, { exports }) { assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) this.llhttp = exports this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) this.client = client this.socket = socket this.timeout = null this.timeoutValue = null this.timeoutType = null this.statusCode = null this.statusText = '' this.upgrade = false this.headers = [] this.headersSize = 0 this.headersMaxSize = client[kMaxHeadersSize] this.shouldKeepAlive = false this.paused = false this.resume = this.resume.bind(this) this.bytesRead = 0 this.keepAlive = '' this.contentLength = '' this.connection = '' this.maxResponseSize = client[kMaxResponseSize] } setTimeout (delay, type) { // If the existing timer and the new timer are of different timer type // (fast or native) or have different delay, we need to clear the existing // timer and set a new one. if ( delay !== this.timeoutValue || (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER) ) { // If a timeout is already set, clear it with clearTimeout of the fast // timer implementation, as it can clear fast and native timers. if (this.timeout) { timers.clearTimeout(this.timeout) this.timeout = null } if (delay) { if (type & USE_FAST_TIMER) { this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this)) } else { this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this)) this.timeout.unref() } } this.timeoutValue = delay } else if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } this.timeoutType = type } resume () { if (this.socket.destroyed || !this.paused) { return } assert(this.ptr != null) assert(currentParser == null) this.llhttp.llhttp_resume(this.ptr) assert(this.timeoutType === TIMEOUT_BODY) if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } this.paused = false this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. this.readMore() } readMore () { while (!this.paused && this.ptr) { const chunk = this.socket.read() if (chunk === null) { break } this.execute(chunk) } } execute (data) { assert(this.ptr != null) assert(currentParser == null) assert(!this.paused) const { socket, llhttp } = this if (data.length > currentBufferSize) { if (currentBufferPtr) { llhttp.free(currentBufferPtr) } currentBufferSize = Math.ceil(data.length / 4096) * 4096 currentBufferPtr = llhttp.malloc(currentBufferSize) } new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) // Call `execute` on the wasm parser. // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, // and finally the length of bytes to parse. // The return value is an error code or `constants.ERROR.OK`. try { let ret try { currentBufferRef = data currentParser = this ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) /* eslint-disable-next-line no-useless-catch */ } catch (err) { /* istanbul ignore next: difficult to make a test case for */ throw err } finally { currentParser = null currentBufferRef = null } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr if (ret === constants.ERROR.PAUSED_UPGRADE) { this.onUpgrade(data.slice(offset)) } else if (ret === constants.ERROR.PAUSED) { this.paused = true socket.unshift(data.slice(offset)) } else if (ret !== constants.ERROR.OK) { const ptr = llhttp.llhttp_get_error_reason(this.ptr) let message = '' /* istanbul ignore else: difficult to make a test case for */ if (ptr) { const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) message = 'Response does not match the HTTP/1.1 protocol (' + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ')' } throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) } } catch (err) { util.destroy(socket, err) } } destroy () { assert(this.ptr != null) assert(currentParser == null) this.llhttp.llhttp_free(this.ptr) this.ptr = null this.timeout && timers.clearTimeout(this.timeout) this.timeout = null this.timeoutValue = null this.timeoutType = null this.paused = false } onStatus (buf) { this.statusText = buf.toString() } onMessageBegin () { const { socket, client } = this /* istanbul ignore next: difficult to make a test case for */ if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] if (!request) { return -1 } request.onResponseStarted() } onHeaderField (buf) { const len = this.headers.length if ((len & 1) === 0) { this.headers.push(buf) } else { this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) } this.trackHeader(buf.length) } onHeaderValue (buf) { let len = this.headers.length if ((len & 1) === 1) { this.headers.push(buf) len += 1 } else { this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) } const key = this.headers[len - 2] if (key.length === 10) { const headerName = util.bufferToLowerCasedHeaderName(key) if (headerName === 'keep-alive') { this.keepAlive += buf.toString() } else if (headerName === 'connection') { this.connection += buf.toString() } } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') { this.contentLength += buf.toString() } this.trackHeader(buf.length) } trackHeader (len) { this.headersSize += len if (this.headersSize >= this.headersMaxSize) { util.destroy(this.socket, new HeadersOverflowError()) } } onUpgrade (head) { const { upgrade, client, socket, headers, statusCode } = this assert(upgrade) assert(client[kSocket] === socket) assert(!socket.destroyed) assert(!this.paused) assert((headers.length & 1) === 0) const request = client[kQueue][client[kRunningIdx]] assert(request) assert(request.upgrade || request.method === 'CONNECT') this.statusCode = null this.statusText = '' this.shouldKeepAlive = null this.headers = [] this.headersSize = 0 socket.unshift(head) socket[kParser].destroy() socket[kParser] = null socket[kClient] = null socket[kError] = null removeAllListeners(socket) client[kSocket] = null client[kHTTPContext] = null // TODO (fix): This is hacky... client[kQueue][client[kRunningIdx]++] = null client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) try { request.onUpgrade(statusCode, headers, socket) } catch (err) { util.destroy(socket, err) } client[kResume]() } onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { const { client, socket, headers, statusText } = this /* istanbul ignore next: difficult to make a test case for */ if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] /* istanbul ignore next: difficult to make a test case for */ if (!request) { return -1 } assert(!this.upgrade) assert(this.statusCode < 200) if (statusCode === 100) { util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) return -1 } /* this can only happen if server is misbehaving */ if (upgrade && !request.upgrade) { util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) return -1 } assert(this.timeoutType === TIMEOUT_HEADERS) this.statusCode = statusCode this.shouldKeepAlive = ( shouldKeepAlive || // Override llhttp value which does not allow keepAlive for HEAD. (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') ) if (this.statusCode >= 200) { const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout] this.setTimeout(bodyTimeout, TIMEOUT_BODY) } else if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } if (request.method === 'CONNECT') { assert(client[kRunning] === 1) this.upgrade = true return 2 } if (upgrade) { assert(client[kRunning] === 1) this.upgrade = true return 2 } assert((this.headers.length & 1) === 0) this.headers = [] this.headersSize = 0 if (this.shouldKeepAlive && client[kPipelining]) { const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null if (keepAliveTimeout != null) { const timeout = Math.min( keepAliveTimeout - client[kKeepAliveTimeoutThreshold], client[kKeepAliveMaxTimeout] ) if (timeout <= 0) { socket[kReset] = true } else { client[kKeepAliveTimeoutValue] = timeout } } else { client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] } } else { // Stop more requests from being dispatched. socket[kReset] = true } const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false if (request.aborted) { return -1 } if (request.method === 'HEAD') { return 1 } if (statusCode < 200) { return 1 } if (socket[kBlocking]) { socket[kBlocking] = false client[kResume]() } return pause ? constants.ERROR.PAUSED : 0 } onBody (buf) { const { client, socket, statusCode, maxResponseSize } = this if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] assert(request) assert(this.timeoutType === TIMEOUT_BODY) if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } assert(statusCode >= 200) if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { util.destroy(socket, new ResponseExceededMaxSizeError()) return -1 } this.bytesRead += buf.length if (request.onData(buf) === false) { return constants.ERROR.PAUSED } } onMessageComplete () { const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this if (socket.destroyed && (!statusCode || shouldKeepAlive)) { return -1 } if (upgrade) { return } assert(statusCode >= 100) assert((this.headers.length & 1) === 0) const request = client[kQueue][client[kRunningIdx]] assert(request) this.statusCode = null this.statusText = '' this.bytesRead = 0 this.contentLength = '' this.keepAlive = '' this.connection = '' this.headers = [] this.headersSize = 0 if (statusCode < 200) { return } /* istanbul ignore next: should be handled by llhttp? */ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { util.destroy(socket, new ResponseContentLengthMismatchError()) return -1 } request.onComplete(headers) client[kQueue][client[kRunningIdx]++] = null if (socket[kWriting]) { assert(client[kRunning] === 0) // Response completed before request. util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (!shouldKeepAlive) { util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (socket[kReset] && client[kRunning] === 0) { // Destroy socket once all requests have completed. // The request at the tail of the pipeline is the one // that requested reset and no further requests should // have been queued since then. util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (client[kPipelining] == null || client[kPipelining] === 1) { // We must wait a full event loop cycle to reuse this socket to make sure // that non-spec compliant servers are not closing the connection even if they // said they won't. setImmediate(() => client[kResume]()) } else { client[kResume]() } } } function onParserTimeout (parser) { const { socket, timeoutType, client, paused } = parser.deref() /* istanbul ignore else */ if (timeoutType === TIMEOUT_HEADERS) { if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { assert(!paused, 'cannot be paused while waiting for headers') util.destroy(socket, new HeadersTimeoutError()) } } else if (timeoutType === TIMEOUT_BODY) { if (!paused) { util.destroy(socket, new BodyTimeoutError()) } } else if (timeoutType === TIMEOUT_KEEP_ALIVE) { assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) util.destroy(socket, new InformationalError('socket idle timeout')) } } async function connectH1 (client, socket) { client[kSocket] = socket if (!llhttpInstance) { llhttpInstance = await llhttpPromise llhttpPromise = null } socket[kNoRef] = false socket[kWriting] = false socket[kReset] = false socket[kBlocking] = false socket[kParser] = new Parser(client, socket, llhttpInstance) addListener(socket, 'error', function (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') const parser = this[kParser] // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded // to the user. if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { // We treat all incoming data so for as a valid response. parser.onMessageComplete() return } this[kError] = err this[kClient][kOnError](err) }) addListener(socket, 'readable', function () { const parser = this[kParser] if (parser) { parser.readMore() } }) addListener(socket, 'end', function () { const parser = this[kParser] if (parser.statusCode && !parser.shouldKeepAlive) { // We treat all incoming data so far as a valid response. parser.onMessageComplete() return } util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) }) addListener(socket, 'close', function () { const client = this[kClient] const parser = this[kParser] if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { // We treat all incoming data so far as a valid response. parser.onMessageComplete() } this[kParser].destroy() this[kParser] = null } const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) client[kSocket] = null client[kHTTPContext] = null // TODO (fix): This is hacky... if (client.destroyed) { assert(client[kPending] === 0) // Fail entire queue. const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(client, request, err) } } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { // Fail head of pipeline. const request = client[kQueue][client[kRunningIdx]] client[kQueue][client[kRunningIdx]++] = null util.errorRequest(client, request, err) } client[kPendingIdx] = client[kRunningIdx] assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) client[kResume]() }) let closed = false socket.on('close', () => { closed = true }) return { version: 'h1', defaultPipelining: 1, write (...args) { return writeH1(client, ...args) }, resume () { resumeH1(client) }, destroy (err, callback) { if (closed) { queueMicrotask(callback) } else { socket.destroy(err).on('close', callback) } }, get destroyed () { return socket.destroyed }, busy (request) { if (socket[kWriting] || socket[kReset] || socket[kBlocking]) { return true } if (request) { if (client[kRunning] > 0 && !request.idempotent) { // Non-idempotent request cannot be retried. // Ensure that no other requests are inflight and // could cause failure. return true } if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { // Don't dispatch an upgrade until all preceding requests have completed. // A misbehaving server might upgrade the connection before all pipelined // request has completed. return true } if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) { // Request with stream or iterator body can error while other requests // are inflight and indirectly error those as well. // Ensure this doesn't happen by waiting for inflight // to complete before dispatching. // Request with stream or iterator body cannot be retried. // Ensure that no other requests are inflight and // could cause failure. return true } } return false } } } function resumeH1 (client) { const socket = client[kSocket] if (socket && !socket.destroyed) { if (client[kSize] === 0) { if (!socket[kNoRef] && socket.unref) { socket.unref() socket[kNoRef] = true } } else if (socket[kNoRef] && socket.ref) { socket.ref() socket[kNoRef] = false } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE) } } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { const request = client[kQueue][client[kRunningIdx]] const headersTimeout = request.headersTimeout != null ? request.headersTimeout : client[kHeadersTimeout] socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) } } } } // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 function shouldSendContentLength (method) { return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' } function writeH1 (client, request) { const { method, path, host, upgrade, blocking, reset } = request let { body, headers, contentLength } = request // https://tools.ietf.org/html/rfc7231#section-4.3.1 // https://tools.ietf.org/html/rfc7231#section-4.3.2 // https://tools.ietf.org/html/rfc7231#section-4.3.5 // Sending a payload body on a request that does not // expect it can cause undefined behavior on some // servers and corrupt connection state. Do not // re-use the connection for further requests. const expectsPayload = ( method === 'PUT' || method === 'POST' || method === 'PATCH' || method === 'QUERY' || method === 'PROPFIND' || method === 'PROPPATCH' ) if (util.isFormDataLike(body)) { if (!extractBody) { extractBody = (__nccwpck_require__(4492).extractBody) } const [bodyStream, contentType] = extractBody(body) if (request.contentType == null) { headers.push('content-type', contentType) } body = bodyStream.stream contentLength = bodyStream.length } else if (util.isBlobLike(body) && request.contentType == null && body.type) { headers.push('content-type', body.type) } if (body && typeof body.read === 'function') { // Try to read EOF in order to get length. body.read(0) } const bodyLength = util.bodyLength(body) contentLength = bodyLength ?? contentLength if (contentLength === null) { contentLength = request.contentLength } if (contentLength === 0 && !expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD NOT send a Content-Length header field when // the request message does not contain a payload body and the method // semantics do not anticipate such a body. contentLength = null } // https://github.com/nodejs/undici/issues/2046 // A user agent may send a Content-Length header with 0 value, this should be allowed. if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { util.errorRequest(client, request, new RequestContentLengthMismatchError()) return false } process.emitWarning(new RequestContentLengthMismatchError()) } const socket = client[kSocket] const abort = (err) => { if (request.aborted || request.completed) { return } util.errorRequest(client, request, err || new RequestAbortedError()) util.destroy(body) util.destroy(socket, new InformationalError('aborted')) } try { request.onConnect(abort) } catch (err) { util.errorRequest(client, request, err) } if (request.aborted) { return false } if (method === 'HEAD') { // https://github.com/mcollina/undici/issues/258 // Close after a HEAD request to interop with misbehaving servers // that may send a body in the response. socket[kReset] = true } if (upgrade || method === 'CONNECT') { // On CONNECT or upgrade, block pipeline from dispatching further // requests on this connection. socket[kReset] = true } if (reset != null) { socket[kReset] = reset } if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { socket[kReset] = true } if (blocking) { socket[kBlocking] = true } let header = `${method} ${path} HTTP/1.1\r\n` if (typeof host === 'string') { header += `host: ${host}\r\n` } else { header += client[kHostHeader] } if (upgrade) { header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` } else if (client[kPipelining] && !socket[kReset]) { header += 'connection: keep-alive\r\n' } else { header += 'connection: close\r\n' } if (Array.isArray(headers)) { for (let n = 0; n < headers.length; n += 2) { const key = headers[n + 0] const val = headers[n + 1] if (Array.isArray(val)) { for (let i = 0; i < val.length; i++) { header += `${key}: ${val[i]}\r\n` } } else { header += `${key}: ${val}\r\n` } } } if (channels.sendHeaders.hasSubscribers) { channels.sendHeaders.publish({ request, headers: header, socket }) } /* istanbul ignore else: assertion */ if (!body || bodyLength === 0) { writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload) } else if (util.isBuffer(body)) { writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload) } else if (util.isBlobLike(body)) { if (typeof body.stream === 'function') { writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload) } else { writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload) } } else if (util.isStream(body)) { writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload) } else if (util.isIterable(body)) { writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload) } else { assert(false) } return true } function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) { assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') let finished = false const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) const onData = function (chunk) { if (finished) { return } try { if (!writer.write(chunk) && this.pause) { this.pause() } } catch (err) { util.destroy(this, err) } } const onDrain = function () { if (finished) { return } if (body.resume) { body.resume() } } const onClose = function () { // 'close' might be emitted *before* 'error' for // broken streams. Wait a tick to avoid this case. queueMicrotask(() => { // It's only safe to remove 'error' listener after // 'close'. body.removeListener('error', onFinished) }) if (!finished) { const err = new RequestAbortedError() queueMicrotask(() => onFinished(err)) } } const onFinished = function (err) { if (finished) { return } finished = true assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) socket .off('drain', onDrain) .off('error', onFinished) body .removeListener('data', onData) .removeListener('end', onFinished) .removeListener('close', onClose) if (!err) { try { writer.end() } catch (er) { err = er } } writer.destroy(err) if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { util.destroy(body, err) } else { util.destroy(body) } } body .on('data', onData) .on('end', onFinished) .on('error', onFinished) .on('close', onClose) if (body.resume) { body.resume() } socket .on('drain', onDrain) .on('error', onFinished) if (body.errorEmitted ?? body.errored) { setImmediate(() => onFinished(body.errored)) } else if (body.endEmitted ?? body.readableEnded) { setImmediate(() => onFinished(null)) } if (body.closeEmitted ?? body.closed) { setImmediate(onClose) } } function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) { try { if (!body) { if (contentLength === 0) { socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { assert(contentLength === null, 'no body must not have content length') socket.write(`${header}\r\n`, 'latin1') } } else if (util.isBuffer(body)) { assert(contentLength === body.byteLength, 'buffer body must have content length') socket.cork() socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') socket.write(body) socket.uncork() request.onBodySent(body) if (!expectsPayload && request.reset !== false) { socket[kReset] = true } } request.onRequestSent() client[kResume]() } catch (err) { abort(err) } } async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) { assert(contentLength === body.size, 'blob body must have content length') try { if (contentLength != null && contentLength !== body.size) { throw new RequestContentLengthMismatchError() } const buffer = Buffer.from(await body.arrayBuffer()) socket.cork() socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') socket.write(buffer) socket.uncork() request.onBodySent(buffer) request.onRequestSent() if (!expectsPayload && request.reset !== false) { socket[kReset] = true } client[kResume]() } catch (err) { abort(err) } } async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) { assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') let callback = null function onDrain () { if (callback) { const cb = callback callback = null cb() } } const waitForDrain = () => new Promise((resolve, reject) => { assert(callback === null) if (socket[kError]) { reject(socket[kError]) } else { callback = resolve } }) socket .on('close', onDrain) .on('drain', onDrain) const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) try { // It's up to the user to somehow abort the async iterable. for await (const chunk of body) { if (socket[kError]) { throw socket[kError] } if (!writer.write(chunk)) { await waitForDrain() } } writer.end() } catch (err) { writer.destroy(err) } finally { socket .off('close', onDrain) .off('drain', onDrain) } } class AsyncWriter { constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) { this.socket = socket this.request = request this.contentLength = contentLength this.client = client this.bytesWritten = 0 this.expectsPayload = expectsPayload this.header = header this.abort = abort socket[kWriting] = true } write (chunk) { const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this if (socket[kError]) { throw socket[kError] } if (socket.destroyed) { return false } const len = Buffer.byteLength(chunk) if (!len) { return true } // We should defer writing chunks. if (contentLength !== null && bytesWritten + len > contentLength) { if (client[kStrictContentLength]) { throw new RequestContentLengthMismatchError() } process.emitWarning(new RequestContentLengthMismatchError()) } socket.cork() if (bytesWritten === 0) { if (!expectsPayload && request.reset !== false) { socket[kReset] = true } if (contentLength === null) { socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') } else { socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') } } if (contentLength === null) { socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') } this.bytesWritten += len const ret = socket.write(chunk) socket.uncork() request.onBodySent(chunk) if (!ret) { if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { // istanbul ignore else: only for jest if (socket[kParser].timeout.refresh) { socket[kParser].timeout.refresh() } } } return ret } end () { const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this request.onRequestSent() socket[kWriting] = false if (socket[kError]) { throw socket[kError] } if (socket.destroyed) { return } if (bytesWritten === 0) { if (expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD send a Content-Length in a request message when // no Transfer-Encoding is sent and the request method defines a meaning // for an enclosed payload body. socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { socket.write(`${header}\r\n`, 'latin1') } } else if (contentLength === null) { socket.write('\r\n0\r\n\r\n', 'latin1') } if (contentLength !== null && bytesWritten !== contentLength) { if (client[kStrictContentLength]) { throw new RequestContentLengthMismatchError() } else { process.emitWarning(new RequestContentLengthMismatchError()) } } if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { // istanbul ignore else: only for jest if (socket[kParser].timeout.refresh) { socket[kParser].timeout.refresh() } } client[kResume]() } destroy (err) { const { socket, client, abort } = this socket[kWriting] = false if (err) { assert(client[kRunning] <= 1, 'pipeline should only contain this request') abort(err) } } } module.exports = connectH1 /***/ }), /***/ 8788: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) const { pipeline } = __nccwpck_require__(7075) const util = __nccwpck_require__(3440) const { RequestContentLengthMismatchError, RequestAbortedError, SocketError, InformationalError } = __nccwpck_require__(8707) const { kUrl, kReset, kClient, kRunning, kPending, kQueue, kPendingIdx, kRunningIdx, kError, kSocket, kStrictContentLength, kOnError, kMaxConcurrentStreams, kHTTP2Session, kResume, kSize, kHTTPContext } = __nccwpck_require__(6443) const kOpenStreams = Symbol('open streams') let extractBody // Experimental let h2ExperimentalWarned = false /** @type {import('http2')} */ let http2 try { http2 = __nccwpck_require__(2467) } catch { // @ts-ignore http2 = { constants: {} } } const { constants: { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_SCHEME, HTTP2_HEADER_CONTENT_LENGTH, HTTP2_HEADER_EXPECT, HTTP2_HEADER_STATUS } } = http2 function parseH2Headers (headers) { const result = [] for (const [name, value] of Object.entries(headers)) { // h2 may concat the header value by array // e.g. Set-Cookie if (Array.isArray(value)) { for (const subvalue of value) { // we need to provide each header value of header name // because the headers handler expect name-value pair result.push(Buffer.from(name), Buffer.from(subvalue)) } } else { result.push(Buffer.from(name), Buffer.from(value)) } } return result } async function connectH2 (client, socket) { client[kSocket] = socket if (!h2ExperimentalWarned) { h2ExperimentalWarned = true process.emitWarning('H2 support is experimental, expect them to change at any time.', { code: 'UNDICI-H2' }) } const session = http2.connect(client[kUrl], { createConnection: () => socket, peerMaxConcurrentStreams: client[kMaxConcurrentStreams] }) session[kOpenStreams] = 0 session[kClient] = client session[kSocket] = socket util.addListener(session, 'error', onHttp2SessionError) util.addListener(session, 'frameError', onHttp2FrameError) util.addListener(session, 'end', onHttp2SessionEnd) util.addListener(session, 'goaway', onHTTP2GoAway) util.addListener(session, 'close', function () { const { [kClient]: client } = this const { [kSocket]: socket } = client const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket)) client[kHTTP2Session] = null if (client.destroyed) { assert(client[kPending] === 0) // Fail entire queue. const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(client, request, err) } } }) session.unref() client[kHTTP2Session] = session socket[kHTTP2Session] = session util.addListener(socket, 'error', function (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') this[kError] = err this[kClient][kOnError](err) }) util.addListener(socket, 'end', function () { util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) }) util.addListener(socket, 'close', function () { const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) client[kSocket] = null if (this[kHTTP2Session] != null) { this[kHTTP2Session].destroy(err) } client[kPendingIdx] = client[kRunningIdx] assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) client[kResume]() }) let closed = false socket.on('close', () => { closed = true }) return { version: 'h2', defaultPipelining: Infinity, write (...args) { return writeH2(client, ...args) }, resume () { resumeH2(client) }, destroy (err, callback) { if (closed) { queueMicrotask(callback) } else { // Destroying the socket will trigger the session close socket.destroy(err).on('close', callback) } }, get destroyed () { return socket.destroyed }, busy () { return false } } } function resumeH2 (client) { const socket = client[kSocket] if (socket?.destroyed === false) { if (client[kSize] === 0 && client[kMaxConcurrentStreams] === 0) { socket.unref() client[kHTTP2Session].unref() } else { socket.ref() client[kHTTP2Session].ref() } } } function onHttp2SessionError (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') this[kSocket][kError] = err this[kClient][kOnError](err) } function onHttp2FrameError (type, code, id) { if (id === 0) { const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) this[kSocket][kError] = err this[kClient][kOnError](err) } } function onHttp2SessionEnd () { const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket])) this.destroy(err) util.destroy(this[kSocket], err) } /** * This is the root cause of #3011 * We need to handle GOAWAY frames properly, and trigger the session close * along with the socket right away */ function onHTTP2GoAway (code) { // We cannot recover, so best to close the session and the socket const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code}`, util.getSocketInfo(this)) const client = this[kClient] client[kSocket] = null client[kHTTPContext] = null if (this[kHTTP2Session] != null) { this[kHTTP2Session].destroy(err) this[kHTTP2Session] = null } util.destroy(this[kSocket], err) // Fail head of pipeline. if (client[kRunningIdx] < client[kQueue].length) { const request = client[kQueue][client[kRunningIdx]] client[kQueue][client[kRunningIdx]++] = null util.errorRequest(client, request, err) client[kPendingIdx] = client[kRunningIdx] } assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) client[kResume]() } // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 function shouldSendContentLength (method) { return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' } function writeH2 (client, request) { const session = client[kHTTP2Session] const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request let { body } = request if (upgrade) { util.errorRequest(client, request, new Error('Upgrade not supported for H2')) return false } const headers = {} for (let n = 0; n < reqHeaders.length; n += 2) { const key = reqHeaders[n + 0] const val = reqHeaders[n + 1] if (Array.isArray(val)) { for (let i = 0; i < val.length; i++) { if (headers[key]) { headers[key] += `,${val[i]}` } else { headers[key] = val[i] } } } else { headers[key] = val } } /** @type {import('node:http2').ClientHttp2Stream} */ let stream const { hostname, port } = client[kUrl] headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}` headers[HTTP2_HEADER_METHOD] = method const abort = (err) => { if (request.aborted || request.completed) { return } err = err || new RequestAbortedError() util.errorRequest(client, request, err) if (stream != null) { util.destroy(stream, err) } // We do not destroy the socket as we can continue using the session // the stream get's destroyed and the session remains to create new streams util.destroy(body, err) client[kQueue][client[kRunningIdx]++] = null client[kResume]() } try { // We are already connected, streams are pending. // We can call on connect, and wait for abort request.onConnect(abort) } catch (err) { util.errorRequest(client, request, err) } if (request.aborted) { return false } if (method === 'CONNECT') { session.ref() // We are already connected, streams are pending, first request // will create a new stream. We trigger a request to create the stream and wait until // `ready` event is triggered // We disabled endStream to allow the user to write to the stream stream = session.request(headers, { endStream: false, signal }) if (stream.id && !stream.pending) { request.onUpgrade(null, null, stream) ++session[kOpenStreams] client[kQueue][client[kRunningIdx]++] = null } else { stream.once('ready', () => { request.onUpgrade(null, null, stream) ++session[kOpenStreams] client[kQueue][client[kRunningIdx]++] = null }) } stream.once('close', () => { session[kOpenStreams] -= 1 if (session[kOpenStreams] === 0) session.unref() }) return true } // https://tools.ietf.org/html/rfc7540#section-8.3 // :path and :scheme headers must be omitted when sending CONNECT headers[HTTP2_HEADER_PATH] = path headers[HTTP2_HEADER_SCHEME] = 'https' // https://tools.ietf.org/html/rfc7231#section-4.3.1 // https://tools.ietf.org/html/rfc7231#section-4.3.2 // https://tools.ietf.org/html/rfc7231#section-4.3.5 // Sending a payload body on a request that does not // expect it can cause undefined behavior on some // servers and corrupt connection state. Do not // re-use the connection for further requests. const expectsPayload = ( method === 'PUT' || method === 'POST' || method === 'PATCH' ) if (body && typeof body.read === 'function') { // Try to read EOF in order to get length. body.read(0) } let contentLength = util.bodyLength(body) if (util.isFormDataLike(body)) { extractBody ??= (__nccwpck_require__(4492).extractBody) const [bodyStream, contentType] = extractBody(body) headers['content-type'] = contentType body = bodyStream.stream contentLength = bodyStream.length } if (contentLength == null) { contentLength = request.contentLength } if (contentLength === 0 || !expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD NOT send a Content-Length header field when // the request message does not contain a payload body and the method // semantics do not anticipate such a body. contentLength = null } // https://github.com/nodejs/undici/issues/2046 // A user agent may send a Content-Length header with 0 value, this should be allowed. if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { util.errorRequest(client, request, new RequestContentLengthMismatchError()) return false } process.emitWarning(new RequestContentLengthMismatchError()) } if (contentLength != null) { assert(body, 'no body must not have content length') headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` } session.ref() const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null if (expectContinue) { headers[HTTP2_HEADER_EXPECT] = '100-continue' stream = session.request(headers, { endStream: shouldEndStream, signal }) stream.once('continue', writeBodyH2) } else { stream = session.request(headers, { endStream: shouldEndStream, signal }) writeBodyH2() } // Increment counter as we have new streams open ++session[kOpenStreams] stream.once('response', headers => { const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers request.onResponseStarted() // Due to the stream nature, it is possible we face a race condition // where the stream has been assigned, but the request has been aborted // the request remains in-flight and headers hasn't been received yet // for those scenarios, best effort is to destroy the stream immediately // as there's no value to keep it open. if (request.aborted) { const err = new RequestAbortedError() util.errorRequest(client, request, err) util.destroy(stream, err) return } if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) { stream.pause() } stream.on('data', (chunk) => { if (request.onData(chunk) === false) { stream.pause() } }) }) stream.once('end', () => { // When state is null, it means we haven't consumed body and the stream still do not have // a state. // Present specially when using pipeline or stream if (stream.state?.state == null || stream.state.state < 6) { request.onComplete([]) } if (session[kOpenStreams] === 0) { // Stream is closed or half-closed-remote (6), decrement counter and cleanup // It does not have sense to continue working with the stream as we do not // have yet RST_STREAM support on client-side session.unref() } abort(new InformationalError('HTTP/2: stream half-closed (remote)')) client[kQueue][client[kRunningIdx]++] = null client[kPendingIdx] = client[kRunningIdx] client[kResume]() }) stream.once('close', () => { session[kOpenStreams] -= 1 if (session[kOpenStreams] === 0) { session.unref() } }) stream.once('error', function (err) { abort(err) }) stream.once('frameError', (type, code) => { abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)) }) // stream.on('aborted', () => { // // TODO(HTTP/2): Support aborted // }) // stream.on('timeout', () => { // // TODO(HTTP/2): Support timeout // }) // stream.on('push', headers => { // // TODO(HTTP/2): Support push // }) // stream.on('trailers', headers => { // // TODO(HTTP/2): Support trailers // }) return true function writeBodyH2 () { /* istanbul ignore else: assertion */ if (!body || contentLength === 0) { writeBuffer( abort, stream, null, client, request, client[kSocket], contentLength, expectsPayload ) } else if (util.isBuffer(body)) { writeBuffer( abort, stream, body, client, request, client[kSocket], contentLength, expectsPayload ) } else if (util.isBlobLike(body)) { if (typeof body.stream === 'function') { writeIterable( abort, stream, body.stream(), client, request, client[kSocket], contentLength, expectsPayload ) } else { writeBlob( abort, stream, body, client, request, client[kSocket], contentLength, expectsPayload ) } } else if (util.isStream(body)) { writeStream( abort, client[kSocket], expectsPayload, stream, body, client, request, contentLength ) } else if (util.isIterable(body)) { writeIterable( abort, stream, body, client, request, client[kSocket], contentLength, expectsPayload ) } else { assert(false) } } } function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { try { if (body != null && util.isBuffer(body)) { assert(contentLength === body.byteLength, 'buffer body must have content length') h2stream.cork() h2stream.write(body) h2stream.uncork() h2stream.end() request.onBodySent(body) } if (!expectsPayload) { socket[kReset] = true } request.onRequestSent() client[kResume]() } catch (error) { abort(error) } } function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) { assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') // For HTTP/2, is enough to pipe the stream const pipe = pipeline( body, h2stream, (err) => { if (err) { util.destroy(pipe, err) abort(err) } else { util.removeAllListeners(pipe) request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } client[kResume]() } } ) util.addListener(pipe, 'data', onPipeData) function onPipeData (chunk) { request.onBodySent(chunk) } } async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { assert(contentLength === body.size, 'blob body must have content length') try { if (contentLength != null && contentLength !== body.size) { throw new RequestContentLengthMismatchError() } const buffer = Buffer.from(await body.arrayBuffer()) h2stream.cork() h2stream.write(buffer) h2stream.uncork() h2stream.end() request.onBodySent(buffer) request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } client[kResume]() } catch (err) { abort(err) } } async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') let callback = null function onDrain () { if (callback) { const cb = callback callback = null cb() } } const waitForDrain = () => new Promise((resolve, reject) => { assert(callback === null) if (socket[kError]) { reject(socket[kError]) } else { callback = resolve } }) h2stream .on('close', onDrain) .on('drain', onDrain) try { // It's up to the user to somehow abort the async iterable. for await (const chunk of body) { if (socket[kError]) { throw socket[kError] } const res = h2stream.write(chunk) request.onBodySent(chunk) if (!res) { await waitForDrain() } } h2stream.end() request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } client[kResume]() } catch (err) { abort(err) } finally { h2stream .off('close', onDrain) .off('drain', onDrain) } } module.exports = connectH2 /***/ }), /***/ 3701: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const assert = __nccwpck_require__(4589) const net = __nccwpck_require__(7030) const http = __nccwpck_require__(7067) const util = __nccwpck_require__(3440) const { channels } = __nccwpck_require__(2414) const Request = __nccwpck_require__(4655) const DispatcherBase = __nccwpck_require__(1841) const { InvalidArgumentError, InformationalError, ClientDestroyedError } = __nccwpck_require__(8707) const buildConnector = __nccwpck_require__(9136) const { kUrl, kServerName, kClient, kBusy, kConnect, kResuming, kRunning, kPending, kSize, kQueue, kConnected, kConnecting, kNeedDrain, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kConnector, kMaxRedirections, kMaxRequests, kCounter, kClose, kDestroy, kDispatch, kInterceptors, kLocalAddress, kMaxResponseSize, kOnError, kHTTPContext, kMaxConcurrentStreams, kResume } = __nccwpck_require__(6443) const connectH1 = __nccwpck_require__(637) const connectH2 = __nccwpck_require__(8788) let deprecatedInterceptorWarned = false const kClosedResolve = Symbol('kClosedResolve') const noop = () => {} function getPipelining (client) { return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1 } /** * @type {import('../../types/client.js').default} */ class Client extends DispatcherBase { /** * * @param {string|URL} url * @param {import('../../types/client.js').Client.Options} options */ constructor (url, { interceptors, maxHeaderSize, headersTimeout, socketTimeout, requestTimeout, connectTimeout, bodyTimeout, idleTimeout, keepAlive, keepAliveTimeout, maxKeepAliveTimeout, keepAliveMaxTimeout, keepAliveTimeoutThreshold, socketPath, pipelining, tls, strictContentLength, maxCachedSessions, maxRedirections, connect, maxRequestsPerClient, localAddress, maxResponseSize, autoSelectFamily, autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, allowH2 } = {}) { super() if (keepAlive !== undefined) { throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') } if (socketTimeout !== undefined) { throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') } if (requestTimeout !== undefined) { throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') } if (idleTimeout !== undefined) { throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') } if (maxKeepAliveTimeout !== undefined) { throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') } if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { throw new InvalidArgumentError('invalid maxHeaderSize') } if (socketPath != null && typeof socketPath !== 'string') { throw new InvalidArgumentError('invalid socketPath') } if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { throw new InvalidArgumentError('invalid connectTimeout') } if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { throw new InvalidArgumentError('invalid keepAliveTimeout') } if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { throw new InvalidArgumentError('invalid keepAliveMaxTimeout') } if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') } if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') } if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { throw new InvalidArgumentError('maxRedirections must be a positive number') } if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') } if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { throw new InvalidArgumentError('localAddress must be valid string IP address') } if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { throw new InvalidArgumentError('maxResponseSize must be a positive number') } if ( autoSelectFamilyAttemptTimeout != null && (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) ) { throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') } // h2 if (allowH2 != null && typeof allowH2 !== 'boolean') { throw new InvalidArgumentError('allowH2 must be a valid boolean value') } if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0') } if (typeof connect !== 'function') { connect = buildConnector({ ...tls, maxCachedSessions, allowH2, socketPath, timeout: connectTimeout, ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), ...connect }) } if (interceptors?.Client && Array.isArray(interceptors.Client)) { this[kInterceptors] = interceptors.Client if (!deprecatedInterceptorWarned) { deprecatedInterceptorWarned = true process.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', { code: 'UNDICI-CLIENT-INTERCEPTOR-DEPRECATED' }) } } else { this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })] } this[kUrl] = util.parseOrigin(url) this[kConnector] = connect this[kPipelining] = pipelining != null ? pipelining : 1 this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] this[kServerName] = null this[kLocalAddress] = localAddress != null ? localAddress : null this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength this[kMaxRedirections] = maxRedirections this[kMaxRequests] = maxRequestsPerClient this[kClosedResolve] = null this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server this[kHTTPContext] = null // kQueue is built up of 3 sections separated by // the kRunningIdx and kPendingIdx indices. // | complete | running | pending | // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length // kRunningIdx points to the first running element. // kPendingIdx points to the first pending element. // This implements a fast queue with an amortized // time of O(1). this[kQueue] = [] this[kRunningIdx] = 0 this[kPendingIdx] = 0 this[kResume] = (sync) => resume(this, sync) this[kOnError] = (err) => onError(this, err) } get pipelining () { return this[kPipelining] } set pipelining (value) { this[kPipelining] = value this[kResume](true) } get [kPending] () { return this[kQueue].length - this[kPendingIdx] } get [kRunning] () { return this[kPendingIdx] - this[kRunningIdx] } get [kSize] () { return this[kQueue].length - this[kRunningIdx] } get [kConnected] () { return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed } get [kBusy] () { return Boolean( this[kHTTPContext]?.busy(null) || (this[kSize] >= (getPipelining(this) || 1)) || this[kPending] > 0 ) } /* istanbul ignore: only used for test */ [kConnect] (cb) { connect(this) this.once('connect', cb) } [kDispatch] (opts, handler) { const origin = opts.origin || this[kUrl].origin const request = new Request(origin, opts, handler) this[kQueue].push(request) if (this[kResuming]) { // Do nothing. } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { // Wait a tick in case stream/iterator is ended in the same tick. this[kResuming] = 1 queueMicrotask(() => resume(this)) } else { this[kResume](true) } if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { this[kNeedDrain] = 2 } return this[kNeedDrain] < 2 } async [kClose] () { // TODO: for H2 we need to gracefully flush the remaining enqueued // request and close each stream. return new Promise((resolve) => { if (this[kSize]) { this[kClosedResolve] = resolve } else { resolve(null) } }) } async [kDestroy] (err) { return new Promise((resolve) => { const requests = this[kQueue].splice(this[kPendingIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(this, request, err) } const callback = () => { if (this[kClosedResolve]) { // TODO (fix): Should we error here with ClientDestroyedError? this[kClosedResolve]() this[kClosedResolve] = null } resolve(null) } if (this[kHTTPContext]) { this[kHTTPContext].destroy(err, callback) this[kHTTPContext] = null } else { queueMicrotask(callback) } this[kResume]() }) } } const createRedirectInterceptor = __nccwpck_require__(5092) function onError (client, err) { if ( client[kRunning] === 0 && err.code !== 'UND_ERR_INFO' && err.code !== 'UND_ERR_SOCKET' ) { // Error is not caused by running request and not a recoverable // socket error. assert(client[kPendingIdx] === client[kRunningIdx]) const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(client, request, err) } assert(client[kSize] === 0) } } /** * @param {Client} client * @returns */ async function connect (client) { assert(!client[kConnecting]) assert(!client[kHTTPContext]) let { host, hostname, protocol, port } = client[kUrl] // Resolve ipv6 if (hostname[0] === '[') { const idx = hostname.indexOf(']') assert(idx !== -1) const ip = hostname.substring(1, idx) assert(net.isIP(ip)) hostname = ip } client[kConnecting] = true if (channels.beforeConnect.hasSubscribers) { channels.beforeConnect.publish({ connectParams: { host, hostname, protocol, port, version: client[kHTTPContext]?.version, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector] }) } try { const socket = await new Promise((resolve, reject) => { client[kConnector]({ host, hostname, protocol, port, servername: client[kServerName], localAddress: client[kLocalAddress] }, (err, socket) => { if (err) { reject(err) } else { resolve(socket) } }) }) if (client.destroyed) { util.destroy(socket.on('error', noop), new ClientDestroyedError()) return } assert(socket) try { client[kHTTPContext] = socket.alpnProtocol === 'h2' ? await connectH2(client, socket) : await connectH1(client, socket) } catch (err) { socket.destroy().on('error', noop) throw err } client[kConnecting] = false socket[kCounter] = 0 socket[kMaxRequests] = client[kMaxRequests] socket[kClient] = client socket[kError] = null if (channels.connected.hasSubscribers) { channels.connected.publish({ connectParams: { host, hostname, protocol, port, version: client[kHTTPContext]?.version, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector], socket }) } client.emit('connect', client[kUrl], [client]) } catch (err) { if (client.destroyed) { return } client[kConnecting] = false if (channels.connectError.hasSubscribers) { channels.connectError.publish({ connectParams: { host, hostname, protocol, port, version: client[kHTTPContext]?.version, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector], error: err }) } if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { assert(client[kRunning] === 0) while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { const request = client[kQueue][client[kPendingIdx]++] util.errorRequest(client, request, err) } } else { onError(client, err) } client.emit('connectionError', client[kUrl], [client], err) } client[kResume]() } function emitDrain (client) { client[kNeedDrain] = 0 client.emit('drain', client[kUrl], [client]) } function resume (client, sync) { if (client[kResuming] === 2) { return } client[kResuming] = 2 _resume(client, sync) client[kResuming] = 0 if (client[kRunningIdx] > 256) { client[kQueue].splice(0, client[kRunningIdx]) client[kPendingIdx] -= client[kRunningIdx] client[kRunningIdx] = 0 } } function _resume (client, sync) { while (true) { if (client.destroyed) { assert(client[kPending] === 0) return } if (client[kClosedResolve] && !client[kSize]) { client[kClosedResolve]() client[kClosedResolve] = null return } if (client[kHTTPContext]) { client[kHTTPContext].resume() } if (client[kBusy]) { client[kNeedDrain] = 2 } else if (client[kNeedDrain] === 2) { if (sync) { client[kNeedDrain] = 1 queueMicrotask(() => emitDrain(client)) } else { emitDrain(client) } continue } if (client[kPending] === 0) { return } if (client[kRunning] >= (getPipelining(client) || 1)) { return } const request = client[kQueue][client[kPendingIdx]] if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { if (client[kRunning] > 0) { return } client[kServerName] = request.servername client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => { client[kHTTPContext] = null resume(client) }) } if (client[kConnecting]) { return } if (!client[kHTTPContext]) { connect(client) return } if (client[kHTTPContext].destroyed) { return } if (client[kHTTPContext].busy(request)) { return } if (!request.aborted && client[kHTTPContext].write(request)) { client[kPendingIdx]++ } else { client[kQueue].splice(client[kPendingIdx], 1) } } } module.exports = Client /***/ }), /***/ 1841: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Dispatcher = __nccwpck_require__(883) const { ClientDestroyedError, ClientClosedError, InvalidArgumentError } = __nccwpck_require__(8707) const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = __nccwpck_require__(6443) const kOnDestroyed = Symbol('onDestroyed') const kOnClosed = Symbol('onClosed') const kInterceptedDispatch = Symbol('Intercepted Dispatch') class DispatcherBase extends Dispatcher { constructor () { super() this[kDestroyed] = false this[kOnDestroyed] = null this[kClosed] = false this[kOnClosed] = [] } get destroyed () { return this[kDestroyed] } get closed () { return this[kClosed] } get interceptors () { return this[kInterceptors] } set interceptors (newInterceptors) { if (newInterceptors) { for (let i = newInterceptors.length - 1; i >= 0; i--) { const interceptor = this[kInterceptors][i] if (typeof interceptor !== 'function') { throw new InvalidArgumentError('interceptor must be an function') } } } this[kInterceptors] = newInterceptors } close (callback) { if (callback === undefined) { return new Promise((resolve, reject) => { this.close((err, data) => { return err ? reject(err) : resolve(data) }) }) } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (this[kDestroyed]) { queueMicrotask(() => callback(new ClientDestroyedError(), null)) return } if (this[kClosed]) { if (this[kOnClosed]) { this[kOnClosed].push(callback) } else { queueMicrotask(() => callback(null, null)) } return } this[kClosed] = true this[kOnClosed].push(callback) const onClosed = () => { const callbacks = this[kOnClosed] this[kOnClosed] = null for (let i = 0; i < callbacks.length; i++) { callbacks[i](null, null) } } // Should not error. this[kClose]() .then(() => this.destroy()) .then(() => { queueMicrotask(onClosed) }) } destroy (err, callback) { if (typeof err === 'function') { callback = err err = null } if (callback === undefined) { return new Promise((resolve, reject) => { this.destroy(err, (err, data) => { return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) }) }) } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (this[kDestroyed]) { if (this[kOnDestroyed]) { this[kOnDestroyed].push(callback) } else { queueMicrotask(() => callback(null, null)) } return } if (!err) { err = new ClientDestroyedError() } this[kDestroyed] = true this[kOnDestroyed] = this[kOnDestroyed] || [] this[kOnDestroyed].push(callback) const onDestroyed = () => { const callbacks = this[kOnDestroyed] this[kOnDestroyed] = null for (let i = 0; i < callbacks.length; i++) { callbacks[i](null, null) } } // Should not error. this[kDestroy](err).then(() => { queueMicrotask(onDestroyed) }) } [kInterceptedDispatch] (opts, handler) { if (!this[kInterceptors] || this[kInterceptors].length === 0) { this[kInterceptedDispatch] = this[kDispatch] return this[kDispatch](opts, handler) } let dispatch = this[kDispatch].bind(this) for (let i = this[kInterceptors].length - 1; i >= 0; i--) { dispatch = this[kInterceptors][i](dispatch) } this[kInterceptedDispatch] = dispatch return dispatch(opts, handler) } dispatch (opts, handler) { if (!handler || typeof handler !== 'object') { throw new InvalidArgumentError('handler must be an object') } try { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('opts must be an object.') } if (this[kDestroyed] || this[kOnDestroyed]) { throw new ClientDestroyedError() } if (this[kClosed]) { throw new ClientClosedError() } return this[kInterceptedDispatch](opts, handler) } catch (err) { if (typeof handler.onError !== 'function') { throw new InvalidArgumentError('invalid onError method') } handler.onError(err) return false } } } module.exports = DispatcherBase /***/ }), /***/ 883: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(8474) class Dispatcher extends EventEmitter { dispatch () { throw new Error('not implemented') } close () { throw new Error('not implemented') } destroy () { throw new Error('not implemented') } compose (...args) { // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ... const interceptors = Array.isArray(args[0]) ? args[0] : args let dispatch = this.dispatch.bind(this) for (const interceptor of interceptors) { if (interceptor == null) { continue } if (typeof interceptor !== 'function') { throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`) } dispatch = interceptor(dispatch) if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) { throw new TypeError('invalid interceptor') } } return new ComposedDispatcher(this, dispatch) } } class ComposedDispatcher extends Dispatcher { #dispatcher = null #dispatch = null constructor (dispatcher, dispatch) { super() this.#dispatcher = dispatcher this.#dispatch = dispatch } dispatch (...args) { this.#dispatch(...args) } close (...args) { return this.#dispatcher.close(...args) } destroy (...args) { return this.#dispatcher.destroy(...args) } } module.exports = Dispatcher /***/ }), /***/ 3137: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const DispatcherBase = __nccwpck_require__(1841) const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = __nccwpck_require__(6443) const ProxyAgent = __nccwpck_require__(6672) const Agent = __nccwpck_require__(7405) const DEFAULT_PORTS = { 'http:': 80, 'https:': 443 } let experimentalWarned = false class EnvHttpProxyAgent extends DispatcherBase { #noProxyValue = null #noProxyEntries = null #opts = null constructor (opts = {}) { super() this.#opts = opts if (!experimentalWarned) { experimentalWarned = true process.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', { code: 'UNDICI-EHPA' }) } const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts this[kNoProxyAgent] = new Agent(agentOpts) const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY if (HTTP_PROXY) { this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY }) } else { this[kHttpProxyAgent] = this[kNoProxyAgent] } const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY if (HTTPS_PROXY) { this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY }) } else { this[kHttpsProxyAgent] = this[kHttpProxyAgent] } this.#parseNoProxy() } [kDispatch] (opts, handler) { const url = new URL(opts.origin) const agent = this.#getProxyAgentForUrl(url) return agent.dispatch(opts, handler) } async [kClose] () { await this[kNoProxyAgent].close() if (!this[kHttpProxyAgent][kClosed]) { await this[kHttpProxyAgent].close() } if (!this[kHttpsProxyAgent][kClosed]) { await this[kHttpsProxyAgent].close() } } async [kDestroy] (err) { await this[kNoProxyAgent].destroy(err) if (!this[kHttpProxyAgent][kDestroyed]) { await this[kHttpProxyAgent].destroy(err) } if (!this[kHttpsProxyAgent][kDestroyed]) { await this[kHttpsProxyAgent].destroy(err) } } #getProxyAgentForUrl (url) { let { protocol, host: hostname, port } = url // Stripping ports in this way instead of using parsedUrl.hostname to make // sure that the brackets around IPv6 addresses are kept. hostname = hostname.replace(/:\d*$/, '').toLowerCase() port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0 if (!this.#shouldProxy(hostname, port)) { return this[kNoProxyAgent] } if (protocol === 'https:') { return this[kHttpsProxyAgent] } return this[kHttpProxyAgent] } #shouldProxy (hostname, port) { if (this.#noProxyChanged) { this.#parseNoProxy() } if (this.#noProxyEntries.length === 0) { return true // Always proxy if NO_PROXY is not set or empty. } if (this.#noProxyValue === '*') { return false // Never proxy if wildcard is set. } for (let i = 0; i < this.#noProxyEntries.length; i++) { const entry = this.#noProxyEntries[i] if (entry.port && entry.port !== port) { continue // Skip if ports don't match. } if (!/^[.*]/.test(entry.hostname)) { // No wildcards, so don't proxy only if there is not an exact match. if (hostname === entry.hostname) { return false } } else { // Don't proxy if the hostname ends with the no_proxy host. if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) { return false } } } return true } #parseNoProxy () { const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv const noProxySplit = noProxyValue.split(/[,\s]/) const noProxyEntries = [] for (let i = 0; i < noProxySplit.length; i++) { const entry = noProxySplit[i] if (!entry) { continue } const parsed = entry.match(/^(.+):(\d+)$/) noProxyEntries.push({ hostname: (parsed ? parsed[1] : entry).toLowerCase(), port: parsed ? Number.parseInt(parsed[2], 10) : 0 }) } this.#noProxyValue = noProxyValue this.#noProxyEntries = noProxyEntries } get #noProxyChanged () { if (this.#opts.noProxy !== undefined) { return false } return this.#noProxyValue !== this.#noProxyEnv } get #noProxyEnv () { return process.env.no_proxy ?? process.env.NO_PROXY ?? '' } } module.exports = EnvHttpProxyAgent /***/ }), /***/ 4660: /***/ ((module) => { "use strict"; /* eslint-disable */ // Extracted from node/lib/internal/fixed_queue.js // Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. const kSize = 2048; const kMask = kSize - 1; // The FixedQueue is implemented as a singly-linked list of fixed-size // circular buffers. It looks something like this: // // head tail // | | // v v // +-----------+ <-----\ +-----------+ <------\ +-----------+ // | [null] | \----- | next | \------- | next | // +-----------+ +-----------+ +-----------+ // | item | <-- bottom | item | <-- bottom | [empty] | // | item | | item | | [empty] | // | item | | item | | [empty] | // | item | | item | | [empty] | // | item | | item | bottom --> | item | // | item | | item | | item | // | ... | | ... | | ... | // | item | | item | | item | // | item | | item | | item | // | [empty] | <-- top | item | | item | // | [empty] | | item | | item | // | [empty] | | [empty] | <-- top top --> | [empty] | // +-----------+ +-----------+ +-----------+ // // Or, if there is only one circular buffer, it looks something // like either of these: // // head tail head tail // | | | | // v v v v // +-----------+ +-----------+ // | [null] | | [null] | // +-----------+ +-----------+ // | [empty] | | item | // | [empty] | | item | // | item | <-- bottom top --> | [empty] | // | item | | [empty] | // | [empty] | <-- top bottom --> | item | // | [empty] | | item | // +-----------+ +-----------+ // // Adding a value means moving `top` forward by one, removing means // moving `bottom` forward by one. After reaching the end, the queue // wraps around. // // When `top === bottom` the current queue is empty and when // `top + 1 === bottom` it's full. This wastes a single space of storage // but allows much quicker checks. class FixedCircularBuffer { constructor() { this.bottom = 0; this.top = 0; this.list = new Array(kSize); this.next = null; } isEmpty() { return this.top === this.bottom; } isFull() { return ((this.top + 1) & kMask) === this.bottom; } push(data) { this.list[this.top] = data; this.top = (this.top + 1) & kMask; } shift() { const nextItem = this.list[this.bottom]; if (nextItem === undefined) return null; this.list[this.bottom] = undefined; this.bottom = (this.bottom + 1) & kMask; return nextItem; } } module.exports = class FixedQueue { constructor() { this.head = this.tail = new FixedCircularBuffer(); } isEmpty() { return this.head.isEmpty(); } push(data) { if (this.head.isFull()) { // Head is full: Creates a new queue, sets the old queue's `.next` to it, // and sets it as the new main queue. this.head = this.head.next = new FixedCircularBuffer(); } this.head.push(data); } shift() { const tail = this.tail; const next = tail.shift(); if (tail.isEmpty() && tail.next !== null) { // If there is another queue, it forms the new tail. this.tail = tail.next; } return next; } }; /***/ }), /***/ 2128: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const DispatcherBase = __nccwpck_require__(1841) const FixedQueue = __nccwpck_require__(4660) const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(6443) const PoolStats = __nccwpck_require__(3246) const kClients = Symbol('clients') const kNeedDrain = Symbol('needDrain') const kQueue = Symbol('queue') const kClosedResolve = Symbol('closed resolve') const kOnDrain = Symbol('onDrain') const kOnConnect = Symbol('onConnect') const kOnDisconnect = Symbol('onDisconnect') const kOnConnectionError = Symbol('onConnectionError') const kGetDispatcher = Symbol('get dispatcher') const kAddClient = Symbol('add client') const kRemoveClient = Symbol('remove client') const kStats = Symbol('stats') class PoolBase extends DispatcherBase { constructor () { super() this[kQueue] = new FixedQueue() this[kClients] = [] this[kQueued] = 0 const pool = this this[kOnDrain] = function onDrain (origin, targets) { const queue = pool[kQueue] let needDrain = false while (!needDrain) { const item = queue.shift() if (!item) { break } pool[kQueued]-- needDrain = !this.dispatch(item.opts, item.handler) } this[kNeedDrain] = needDrain if (!this[kNeedDrain] && pool[kNeedDrain]) { pool[kNeedDrain] = false pool.emit('drain', origin, [pool, ...targets]) } if (pool[kClosedResolve] && queue.isEmpty()) { Promise .all(pool[kClients].map(c => c.close())) .then(pool[kClosedResolve]) } } this[kOnConnect] = (origin, targets) => { pool.emit('connect', origin, [pool, ...targets]) } this[kOnDisconnect] = (origin, targets, err) => { pool.emit('disconnect', origin, [pool, ...targets], err) } this[kOnConnectionError] = (origin, targets, err) => { pool.emit('connectionError', origin, [pool, ...targets], err) } this[kStats] = new PoolStats(this) } get [kBusy] () { return this[kNeedDrain] } get [kConnected] () { return this[kClients].filter(client => client[kConnected]).length } get [kFree] () { return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length } get [kPending] () { let ret = this[kQueued] for (const { [kPending]: pending } of this[kClients]) { ret += pending } return ret } get [kRunning] () { let ret = 0 for (const { [kRunning]: running } of this[kClients]) { ret += running } return ret } get [kSize] () { let ret = this[kQueued] for (const { [kSize]: size } of this[kClients]) { ret += size } return ret } get stats () { return this[kStats] } async [kClose] () { if (this[kQueue].isEmpty()) { await Promise.all(this[kClients].map(c => c.close())) } else { await new Promise((resolve) => { this[kClosedResolve] = resolve }) } } async [kDestroy] (err) { while (true) { const item = this[kQueue].shift() if (!item) { break } item.handler.onError(err) } await Promise.all(this[kClients].map(c => c.destroy(err))) } [kDispatch] (opts, handler) { const dispatcher = this[kGetDispatcher]() if (!dispatcher) { this[kNeedDrain] = true this[kQueue].push({ opts, handler }) this[kQueued]++ } else if (!dispatcher.dispatch(opts, handler)) { dispatcher[kNeedDrain] = true this[kNeedDrain] = !this[kGetDispatcher]() } return !this[kNeedDrain] } [kAddClient] (client) { client .on('drain', this[kOnDrain]) .on('connect', this[kOnConnect]) .on('disconnect', this[kOnDisconnect]) .on('connectionError', this[kOnConnectionError]) this[kClients].push(client) if (this[kNeedDrain]) { queueMicrotask(() => { if (this[kNeedDrain]) { this[kOnDrain](client[kUrl], [this, client]) } }) } return this } [kRemoveClient] (client) { client.close(() => { const idx = this[kClients].indexOf(client) if (idx !== -1) { this[kClients].splice(idx, 1) } }) this[kNeedDrain] = this[kClients].some(dispatcher => ( !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true )) } } module.exports = { PoolBase, kClients, kNeedDrain, kAddClient, kRemoveClient, kGetDispatcher } /***/ }), /***/ 3246: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(6443) const kPool = Symbol('pool') class PoolStats { constructor (pool) { this[kPool] = pool } get connected () { return this[kPool][kConnected] } get free () { return this[kPool][kFree] } get pending () { return this[kPool][kPending] } get queued () { return this[kPool][kQueued] } get running () { return this[kPool][kRunning] } get size () { return this[kPool][kSize] } } module.exports = PoolStats /***/ }), /***/ 628: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { PoolBase, kClients, kNeedDrain, kAddClient, kGetDispatcher } = __nccwpck_require__(2128) const Client = __nccwpck_require__(3701) const { InvalidArgumentError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { kUrl, kInterceptors } = __nccwpck_require__(6443) const buildConnector = __nccwpck_require__(9136) const kOptions = Symbol('options') const kConnections = Symbol('connections') const kFactory = Symbol('factory') function defaultFactory (origin, opts) { return new Client(origin, opts) } class Pool extends PoolBase { constructor (origin, { connections, factory = defaultFactory, connect, connectTimeout, tls, maxCachedSessions, socketPath, autoSelectFamily, autoSelectFamilyAttemptTimeout, allowH2, ...options } = {}) { super() if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError('invalid connections') } if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } if (typeof connect !== 'function') { connect = buildConnector({ ...tls, maxCachedSessions, allowH2, socketPath, timeout: connectTimeout, ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), ...connect }) } this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : [] this[kConnections] = connections || null this[kUrl] = util.parseOrigin(origin) this[kOptions] = { ...util.deepClone(options), connect, allowH2 } this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : undefined this[kFactory] = factory this.on('connectionError', (origin, targets, error) => { // If a connection error occurs, we remove the client from the pool, // and emit a connectionError event. They will not be re-used. // Fixes https://github.com/nodejs/undici/issues/3895 for (const target of targets) { // Do not use kRemoveClient here, as it will close the client, // but the client cannot be closed in this state. const idx = this[kClients].indexOf(target) if (idx !== -1) { this[kClients].splice(idx, 1) } } }) } [kGetDispatcher] () { for (const client of this[kClients]) { if (!client[kNeedDrain]) { return client } } if (!this[kConnections] || this[kClients].length < this[kConnections]) { const dispatcher = this[kFactory](this[kUrl], this[kOptions]) this[kAddClient](dispatcher) return dispatcher } } } module.exports = Pool /***/ }), /***/ 6672: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) const { URL } = __nccwpck_require__(3136) const Agent = __nccwpck_require__(7405) const Pool = __nccwpck_require__(628) const DispatcherBase = __nccwpck_require__(1841) const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = __nccwpck_require__(8707) const buildConnector = __nccwpck_require__(9136) const Client = __nccwpck_require__(3701) const kAgent = Symbol('proxy agent') const kClient = Symbol('proxy client') const kProxyHeaders = Symbol('proxy headers') const kRequestTls = Symbol('request tls settings') const kProxyTls = Symbol('proxy tls settings') const kConnectEndpoint = Symbol('connect endpoint function') const kTunnelProxy = Symbol('tunnel proxy') function defaultProtocolPort (protocol) { return protocol === 'https:' ? 443 : 80 } function defaultFactory (origin, opts) { return new Pool(origin, opts) } const noop = () => {} function defaultAgentFactory (origin, opts) { if (opts.connections === 1) { return new Client(origin, opts) } return new Pool(origin, opts) } class Http1ProxyWrapper extends DispatcherBase { #client constructor (proxyUrl, { headers = {}, connect, factory }) { super() if (!proxyUrl) { throw new InvalidArgumentError('Proxy URL is mandatory') } this[kProxyHeaders] = headers if (factory) { this.#client = factory(proxyUrl, { connect }) } else { this.#client = new Client(proxyUrl, { connect }) } } [kDispatch] (opts, handler) { const onHeaders = handler.onHeaders handler.onHeaders = function (statusCode, data, resume) { if (statusCode === 407) { if (typeof handler.onError === 'function') { handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)')) } return } if (onHeaders) onHeaders.call(this, statusCode, data, resume) } // Rewrite request as an HTTP1 Proxy request, without tunneling. const { origin, path = '/', headers = {} } = opts opts.path = origin + path if (!('host' in headers) && !('Host' in headers)) { const { host } = new URL(origin) headers.host = host } opts.headers = { ...this[kProxyHeaders], ...headers } return this.#client[kDispatch](opts, handler) } async [kClose] () { return this.#client.close() } async [kDestroy] (err) { return this.#client.destroy(err) } } class ProxyAgent extends DispatcherBase { constructor (opts) { super() if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) { throw new InvalidArgumentError('Proxy uri is mandatory') } const { clientFactory = defaultFactory } = opts if (typeof clientFactory !== 'function') { throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') } const { proxyTunnel = true } = opts const url = this.#getUrl(opts) const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url this[kProxy] = { uri: href, protocol } this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) ? opts.interceptors.ProxyAgent : [] this[kRequestTls] = opts.requestTls this[kProxyTls] = opts.proxyTls this[kProxyHeaders] = opts.headers || {} this[kTunnelProxy] = proxyTunnel if (opts.auth && opts.token) { throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') } else if (opts.auth) { /* @deprecated in favour of opts.token */ this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` } else if (opts.token) { this[kProxyHeaders]['proxy-authorization'] = opts.token } else if (username && password) { this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` } const connect = buildConnector({ ...opts.proxyTls }) this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) const agentFactory = opts.factory || defaultAgentFactory const factory = (origin, options) => { const { protocol } = new URL(origin) if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') { return new Http1ProxyWrapper(this[kProxy].uri, { headers: this[kProxyHeaders], connect, factory: agentFactory }) } return agentFactory(origin, options) } this[kClient] = clientFactory(url, { connect }) this[kAgent] = new Agent({ ...opts, factory, connect: async (opts, callback) => { let requestedPath = opts.host if (!opts.port) { requestedPath += `:${defaultProtocolPort(opts.protocol)}` } try { const { socket, statusCode } = await this[kClient].connect({ origin, port, path: requestedPath, signal: opts.signal, headers: { ...this[kProxyHeaders], host: opts.host }, servername: this[kProxyTls]?.servername || proxyHostname }) if (statusCode !== 200) { socket.on('error', noop).destroy() callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) } if (opts.protocol !== 'https:') { callback(null, socket) return } let servername if (this[kRequestTls]) { servername = this[kRequestTls].servername } else { servername = opts.servername } this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) } catch (err) { if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { // Throw a custom error to avoid loop in client.js#connect callback(new SecureProxyConnectionError(err)) } else { callback(err) } } } }) } dispatch (opts, handler) { const headers = buildHeaders(opts.headers) throwIfProxyAuthIsSent(headers) if (headers && !('host' in headers) && !('Host' in headers)) { const { host } = new URL(opts.origin) headers.host = host } return this[kAgent].dispatch( { ...opts, headers }, handler ) } /** * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts * @returns {URL} */ #getUrl (opts) { if (typeof opts === 'string') { return new URL(opts) } else if (opts instanceof URL) { return opts } else { return new URL(opts.uri) } } async [kClose] () { await this[kAgent].close() await this[kClient].close() } async [kDestroy] () { await this[kAgent].destroy() await this[kClient].destroy() } } /** * @param {string[] | Record} headers * @returns {Record} */ function buildHeaders (headers) { // When using undici.fetch, the headers list is stored // as an array. if (Array.isArray(headers)) { /** @type {Record} */ const headersPair = {} for (let i = 0; i < headers.length; i += 2) { headersPair[headers[i]] = headers[i + 1] } return headersPair } return headers } /** * @param {Record} headers * * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers * Nevertheless, it was changed and to avoid a security vulnerability by end users * this check was created. * It should be removed in the next major version for performance reasons */ function throwIfProxyAuthIsSent (headers) { const existProxyAuth = headers && Object.keys(headers) .find((key) => key.toLowerCase() === 'proxy-authorization') if (existProxyAuth) { throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') } } module.exports = ProxyAgent /***/ }), /***/ 50: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Dispatcher = __nccwpck_require__(883) const RetryHandler = __nccwpck_require__(7816) class RetryAgent extends Dispatcher { #agent = null #options = null constructor (agent, options = {}) { super(options) this.#agent = agent this.#options = options } dispatch (opts, handler) { const retry = new RetryHandler({ ...opts, retryOptions: this.#options }, { dispatch: this.#agent.dispatch.bind(this.#agent), handler }) return this.#agent.dispatch(opts, retry) } close () { return this.#agent.close() } destroy () { return this.#agent.destroy() } } module.exports = RetryAgent /***/ }), /***/ 2581: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // We include a version number for the Dispatcher API. In case of breaking changes, // this version number must be increased to avoid conflicts. const globalDispatcher = Symbol.for('undici.globalDispatcher.1') const { InvalidArgumentError } = __nccwpck_require__(8707) const Agent = __nccwpck_require__(7405) if (getGlobalDispatcher() === undefined) { setGlobalDispatcher(new Agent()) } function setGlobalDispatcher (agent) { if (!agent || typeof agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument agent must implement Agent') } Object.defineProperty(globalThis, globalDispatcher, { value: agent, writable: true, enumerable: false, configurable: false }) } function getGlobalDispatcher () { return globalThis[globalDispatcher] } module.exports = { setGlobalDispatcher, getGlobalDispatcher } /***/ }), /***/ 8155: /***/ ((module) => { "use strict"; module.exports = class DecoratorHandler { #handler constructor (handler) { if (typeof handler !== 'object' || handler === null) { throw new TypeError('handler must be an object') } this.#handler = handler } onConnect (...args) { return this.#handler.onConnect?.(...args) } onError (...args) { return this.#handler.onError?.(...args) } onUpgrade (...args) { return this.#handler.onUpgrade?.(...args) } onResponseStarted (...args) { return this.#handler.onResponseStarted?.(...args) } onHeaders (...args) { return this.#handler.onHeaders?.(...args) } onData (...args) { return this.#handler.onData?.(...args) } onComplete (...args) { return this.#handler.onComplete?.(...args) } onBodySent (...args) { return this.#handler.onBodySent?.(...args) } } /***/ }), /***/ 8754: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(3440) const { kBodyUsed } = __nccwpck_require__(6443) const assert = __nccwpck_require__(4589) const { InvalidArgumentError } = __nccwpck_require__(8707) const EE = __nccwpck_require__(8474) const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] const kBody = Symbol('body') class BodyAsyncIterable { constructor (body) { this[kBody] = body this[kBodyUsed] = false } async * [Symbol.asyncIterator] () { assert(!this[kBodyUsed], 'disturbed') this[kBodyUsed] = true yield * this[kBody] } } class RedirectHandler { constructor (dispatch, maxRedirections, opts, handler) { if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { throw new InvalidArgumentError('maxRedirections must be a positive number') } util.validateHandler(handler, opts.method, opts.upgrade) this.dispatch = dispatch this.location = null this.abort = null this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy this.maxRedirections = maxRedirections this.handler = handler this.history = [] this.redirectionLimitReached = false if (util.isStream(this.opts.body)) { // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp // so that it can be dispatched again? // TODO (fix): Do we need 100-expect support to provide a way to do this properly? if (util.bodyLength(this.opts.body) === 0) { this.opts.body .on('data', function () { assert(false) }) } if (typeof this.opts.body.readableDidRead !== 'boolean') { this.opts.body[kBodyUsed] = false EE.prototype.on.call(this.opts.body, 'data', function () { this[kBodyUsed] = true }) } } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { // TODO (fix): We can't access ReadableStream internal state // to determine whether or not it has been disturbed. This is just // a workaround. this.opts.body = new BodyAsyncIterable(this.opts.body) } else if ( this.opts.body && typeof this.opts.body !== 'string' && !ArrayBuffer.isView(this.opts.body) && util.isIterable(this.opts.body) ) { // TODO: Should we allow re-using iterable if !this.opts.idempotent // or through some other flag? this.opts.body = new BodyAsyncIterable(this.opts.body) } } onConnect (abort) { this.abort = abort this.handler.onConnect(abort, { history: this.history }) } onUpgrade (statusCode, headers, socket) { this.handler.onUpgrade(statusCode, headers, socket) } onError (error) { this.handler.onError(error) } onHeaders (statusCode, headers, resume, statusText) { this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) ? null : parseLocation(statusCode, headers) if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) { if (this.request) { this.request.abort(new Error('max redirects')) } this.redirectionLimitReached = true this.abort(new Error('max redirects')) return } if (this.opts.origin) { this.history.push(new URL(this.opts.path, this.opts.origin)) } if (!this.location) { return this.handler.onHeaders(statusCode, headers, resume, statusText) } const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) const path = search ? `${pathname}${search}` : pathname // Remove headers referring to the original URL. // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. // https://tools.ietf.org/html/rfc7231#section-6.4 this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) this.opts.path = path this.opts.origin = origin this.opts.maxRedirections = 0 this.opts.query = null // https://tools.ietf.org/html/rfc7231#section-6.4.4 // In case of HTTP 303, always replace method to be either HEAD or GET if (statusCode === 303 && this.opts.method !== 'HEAD') { this.opts.method = 'GET' this.opts.body = null } } onData (chunk) { if (this.location) { /* https://tools.ietf.org/html/rfc7231#section-6.4 TLDR: undici always ignores 3xx response bodies. Redirection is used to serve the requested resource from another URL, so it is assumes that no body is generated (and thus can be ignored). Even though generating a body is not prohibited. For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually (which means it's optional and not mandated) contain just an hyperlink to the value of the Location response header, so the body can be ignored safely. For status 300, which is "Multiple Choices", the spec mentions both generating a Location response header AND a response body with the other possible location to follow. Since the spec explicitly chooses not to specify a format for such body and leave it to servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. */ } else { return this.handler.onData(chunk) } } onComplete (trailers) { if (this.location) { /* https://tools.ietf.org/html/rfc7231#section-6.4 TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections and neither are useful if present. See comment on onData method above for more detailed information. */ this.location = null this.abort = null this.dispatch(this.opts, this) } else { this.handler.onComplete(trailers) } } onBodySent (chunk) { if (this.handler.onBodySent) { this.handler.onBodySent(chunk) } } } function parseLocation (statusCode, headers) { if (redirectableStatusCodes.indexOf(statusCode) === -1) { return null } for (let i = 0; i < headers.length; i += 2) { if (headers[i].length === 8 && util.headerNameToString(headers[i]) === 'location') { return headers[i + 1] } } } // https://tools.ietf.org/html/rfc7231#section-6.4.4 function shouldRemoveHeader (header, removeContent, unknownOrigin) { if (header.length === 4) { return util.headerNameToString(header) === 'host' } if (removeContent && util.headerNameToString(header).startsWith('content-')) { return true } if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { const name = util.headerNameToString(header) return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' } return false } // https://tools.ietf.org/html/rfc7231#section-6.4 function cleanRequestHeaders (headers, removeContent, unknownOrigin) { const ret = [] if (Array.isArray(headers)) { for (let i = 0; i < headers.length; i += 2) { if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { ret.push(headers[i], headers[i + 1]) } } } else if (headers && typeof headers === 'object') { for (const key of Object.keys(headers)) { if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { ret.push(key, headers[key]) } } } else { assert(headers == null, 'headers must be an object or an array') } return ret } module.exports = RedirectHandler /***/ }), /***/ 7816: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) const { kRetryHandlerDefaultRetry } = __nccwpck_require__(6443) const { RequestRetryError } = __nccwpck_require__(8707) const { isDisturbed, parseHeaders, parseRangeHeader, wrapRequestBody } = __nccwpck_require__(3440) function calculateRetryAfterHeader (retryAfter) { const current = Date.now() return new Date(retryAfter).getTime() - current } class RetryHandler { constructor (opts, handlers) { const { retryOptions, ...dispatchOpts } = opts const { // Retry scoped retry: retryFn, maxRetries, maxTimeout, minTimeout, timeoutFactor, // Response scoped methods, errorCodes, retryAfter, statusCodes } = retryOptions ?? {} this.dispatch = handlers.dispatch this.handler = handlers.handler this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) } this.abort = null this.aborted = false this.retryOpts = { retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], retryAfter: retryAfter ?? true, maxTimeout: maxTimeout ?? 30 * 1000, // 30s, minTimeout: minTimeout ?? 500, // .5s timeoutFactor: timeoutFactor ?? 2, maxRetries: maxRetries ?? 5, // What errors we should retry methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], // Indicates which errors to retry statusCodes: statusCodes ?? [500, 502, 503, 504, 429], // List of errors to retry errorCodes: errorCodes ?? [ 'ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN', 'ENETUNREACH', 'EHOSTDOWN', 'EHOSTUNREACH', 'EPIPE', 'UND_ERR_SOCKET' ] } this.retryCount = 0 this.retryCountCheckpoint = 0 this.start = 0 this.end = null this.etag = null this.resume = null // Handle possible onConnect duplication this.handler.onConnect(reason => { this.aborted = true if (this.abort) { this.abort(reason) } else { this.reason = reason } }) } onRequestSent () { if (this.handler.onRequestSent) { this.handler.onRequestSent() } } onUpgrade (statusCode, headers, socket) { if (this.handler.onUpgrade) { this.handler.onUpgrade(statusCode, headers, socket) } } onConnect (abort) { if (this.aborted) { abort(this.reason) } else { this.abort = abort } } onBodySent (chunk) { if (this.handler.onBodySent) return this.handler.onBodySent(chunk) } static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { const { statusCode, code, headers } = err const { method, retryOptions } = opts const { maxRetries, minTimeout, maxTimeout, timeoutFactor, statusCodes, errorCodes, methods } = retryOptions const { counter } = state // Any code that is not a Undici's originated and allowed to retry if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) { cb(err) return } // If a set of method are provided and the current method is not in the list if (Array.isArray(methods) && !methods.includes(method)) { cb(err) return } // If a set of status code are provided and the current status code is not in the list if ( statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode) ) { cb(err) return } // If we reached the max number of retries if (counter > maxRetries) { cb(err) return } let retryAfterHeader = headers?.['retry-after'] if (retryAfterHeader) { retryAfterHeader = Number(retryAfterHeader) retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(retryAfterHeader) : retryAfterHeader * 1e3 // Retry-After is in seconds } const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout) setTimeout(() => cb(null), retryTimeout) } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const headers = parseHeaders(rawHeaders) this.retryCount += 1 if (statusCode >= 300) { if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } else { this.abort( new RequestRetryError('Request failed', statusCode, { headers, data: { count: this.retryCount } }) ) return false } } // Checkpoint for resume from where we left it if (this.resume != null) { this.resume = null // Only Partial Content 206 supposed to provide Content-Range, // any other status code that partially consumed the payload // should not be retry because it would result in downstream // wrongly concatanete multiple responses. if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) { this.abort( new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, { headers, data: { count: this.retryCount } }) ) return false } const contentRange = parseRangeHeader(headers['content-range']) // If no content range if (!contentRange) { this.abort( new RequestRetryError('Content-Range mismatch', statusCode, { headers, data: { count: this.retryCount } }) ) return false } // Let's start with a weak etag check if (this.etag != null && this.etag !== headers.etag) { this.abort( new RequestRetryError('ETag mismatch', statusCode, { headers, data: { count: this.retryCount } }) ) return false } const { start, size, end = size - 1 } = contentRange assert(this.start === start, 'content-range mismatch') assert(this.end == null || this.end === end, 'content-range mismatch') this.resume = resume return true } if (this.end == null) { if (statusCode === 206) { // First time we receive 206 const range = parseRangeHeader(headers['content-range']) if (range == null) { return this.handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } const { start, size, end = size - 1 } = range assert( start != null && Number.isFinite(start), 'content-range mismatch' ) assert(end != null && Number.isFinite(end), 'invalid content-length') this.start = start this.end = end } // We make our best to checkpoint the body for further range headers if (this.end == null) { const contentLength = headers['content-length'] this.end = contentLength != null ? Number(contentLength) - 1 : null } assert(Number.isFinite(this.start)) assert( this.end == null || Number.isFinite(this.end), 'invalid content-length' ) this.resume = resume this.etag = headers.etag != null ? headers.etag : null // Weak etags are not useful for comparison nor cache // for instance not safe to assume if the response is byte-per-byte // equal if (this.etag != null && this.etag.startsWith('W/')) { this.etag = null } return this.handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } const err = new RequestRetryError('Request failed', statusCode, { headers, data: { count: this.retryCount } }) this.abort(err) return false } onData (chunk) { this.start += chunk.length return this.handler.onData(chunk) } onComplete (rawTrailers) { this.retryCount = 0 return this.handler.onComplete(rawTrailers) } onError (err) { if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err) } // We reconcile in case of a mix between network errors // and server error response if (this.retryCount - this.retryCountCheckpoint > 0) { // We count the difference between the last checkpoint and the current retry count this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint) } else { this.retryCount += 1 } this.retryOpts.retry( err, { state: { counter: this.retryCount }, opts: { retryOptions: this.retryOpts, ...this.opts } }, onRetry.bind(this) ) function onRetry (err) { if (err != null || this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err) } if (this.start !== 0) { const headers = { range: `bytes=${this.start}-${this.end ?? ''}` } // Weak etag check - weak etags will make comparison algorithms never match if (this.etag != null) { headers['if-match'] = this.etag } this.opts = { ...this.opts, headers: { ...this.opts.headers, ...headers } } } try { this.retryCountCheckpoint = this.retryCount this.dispatch(this.opts, this) } catch (err) { this.handler.onError(err) } } } } module.exports = RetryHandler /***/ }), /***/ 379: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { isIP } = __nccwpck_require__(7030) const { lookup } = __nccwpck_require__(610) const DecoratorHandler = __nccwpck_require__(8155) const { InvalidArgumentError, InformationalError } = __nccwpck_require__(8707) const maxInt = Math.pow(2, 31) - 1 class DNSInstance { #maxTTL = 0 #maxItems = 0 #records = new Map() dualStack = true affinity = null lookup = null pick = null constructor (opts) { this.#maxTTL = opts.maxTTL this.#maxItems = opts.maxItems this.dualStack = opts.dualStack this.affinity = opts.affinity this.lookup = opts.lookup ?? this.#defaultLookup this.pick = opts.pick ?? this.#defaultPick } get full () { return this.#records.size === this.#maxItems } runLookup (origin, opts, cb) { const ips = this.#records.get(origin.hostname) // If full, we just return the origin if (ips == null && this.full) { cb(null, origin.origin) return } const newOpts = { affinity: this.affinity, dualStack: this.dualStack, lookup: this.lookup, pick: this.pick, ...opts.dns, maxTTL: this.#maxTTL, maxItems: this.#maxItems } // If no IPs we lookup if (ips == null) { this.lookup(origin, newOpts, (err, addresses) => { if (err || addresses == null || addresses.length === 0) { cb(err ?? new InformationalError('No DNS entries found')) return } this.setRecords(origin, addresses) const records = this.#records.get(origin.hostname) const ip = this.pick( origin, records, newOpts.affinity ) let port if (typeof ip.port === 'number') { port = `:${ip.port}` } else if (origin.port !== '') { port = `:${origin.port}` } else { port = '' } cb( null, `${origin.protocol}//${ ip.family === 6 ? `[${ip.address}]` : ip.address }${port}` ) }) } else { // If there's IPs we pick const ip = this.pick( origin, ips, newOpts.affinity ) // If no IPs we lookup - deleting old records if (ip == null) { this.#records.delete(origin.hostname) this.runLookup(origin, opts, cb) return } let port if (typeof ip.port === 'number') { port = `:${ip.port}` } else if (origin.port !== '') { port = `:${origin.port}` } else { port = '' } cb( null, `${origin.protocol}//${ ip.family === 6 ? `[${ip.address}]` : ip.address }${port}` ) } } #defaultLookup (origin, opts, cb) { lookup( origin.hostname, { all: true, family: this.dualStack === false ? this.affinity : 0, order: 'ipv4first' }, (err, addresses) => { if (err) { return cb(err) } const results = new Map() for (const addr of addresses) { // On linux we found duplicates, we attempt to remove them with // the latest record results.set(`${addr.address}:${addr.family}`, addr) } cb(null, results.values()) } ) } #defaultPick (origin, hostnameRecords, affinity) { let ip = null const { records, offset } = hostnameRecords let family if (this.dualStack) { if (affinity == null) { // Balance between ip families if (offset == null || offset === maxInt) { hostnameRecords.offset = 0 affinity = 4 } else { hostnameRecords.offset++ affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4 } } if (records[affinity] != null && records[affinity].ips.length > 0) { family = records[affinity] } else { family = records[affinity === 4 ? 6 : 4] } } else { family = records[affinity] } // If no IPs we return null if (family == null || family.ips.length === 0) { return ip } if (family.offset == null || family.offset === maxInt) { family.offset = 0 } else { family.offset++ } const position = family.offset % family.ips.length ip = family.ips[position] ?? null if (ip == null) { return ip } if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms // We delete expired records // It is possible that they have different TTL, so we manage them individually family.ips.splice(position, 1) return this.pick(origin, hostnameRecords, affinity) } return ip } setRecords (origin, addresses) { const timestamp = Date.now() const records = { records: { 4: null, 6: null } } for (const record of addresses) { record.timestamp = timestamp if (typeof record.ttl === 'number') { // The record TTL is expected to be in ms record.ttl = Math.min(record.ttl, this.#maxTTL) } else { record.ttl = this.#maxTTL } const familyRecords = records.records[record.family] ?? { ips: [] } familyRecords.ips.push(record) records.records[record.family] = familyRecords } this.#records.set(origin.hostname, records) } getHandler (meta, opts) { return new DNSDispatchHandler(this, meta, opts) } } class DNSDispatchHandler extends DecoratorHandler { #state = null #opts = null #dispatch = null #handler = null #origin = null constructor (state, { origin, handler, dispatch }, opts) { super(handler) this.#origin = origin this.#handler = handler this.#opts = { ...opts } this.#state = state this.#dispatch = dispatch } onError (err) { switch (err.code) { case 'ETIMEDOUT': case 'ECONNREFUSED': { if (this.#state.dualStack) { // We delete the record and retry this.#state.runLookup(this.#origin, this.#opts, (err, newOrigin) => { if (err) { return this.#handler.onError(err) } const dispatchOpts = { ...this.#opts, origin: newOrigin } this.#dispatch(dispatchOpts, this) }) // if dual-stack disabled, we error out return } this.#handler.onError(err) return } case 'ENOTFOUND': this.#state.deleteRecord(this.#origin) // eslint-disable-next-line no-fallthrough default: this.#handler.onError(err) break } } } module.exports = interceptorOpts => { if ( interceptorOpts?.maxTTL != null && (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0) ) { throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number') } if ( interceptorOpts?.maxItems != null && (typeof interceptorOpts?.maxItems !== 'number' || interceptorOpts?.maxItems < 1) ) { throw new InvalidArgumentError( 'Invalid maxItems. Must be a positive number and greater than zero' ) } if ( interceptorOpts?.affinity != null && interceptorOpts?.affinity !== 4 && interceptorOpts?.affinity !== 6 ) { throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6') } if ( interceptorOpts?.dualStack != null && typeof interceptorOpts?.dualStack !== 'boolean' ) { throw new InvalidArgumentError('Invalid dualStack. Must be a boolean') } if ( interceptorOpts?.lookup != null && typeof interceptorOpts?.lookup !== 'function' ) { throw new InvalidArgumentError('Invalid lookup. Must be a function') } if ( interceptorOpts?.pick != null && typeof interceptorOpts?.pick !== 'function' ) { throw new InvalidArgumentError('Invalid pick. Must be a function') } const dualStack = interceptorOpts?.dualStack ?? true let affinity if (dualStack) { affinity = interceptorOpts?.affinity ?? null } else { affinity = interceptorOpts?.affinity ?? 4 } const opts = { maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms lookup: interceptorOpts?.lookup ?? null, pick: interceptorOpts?.pick ?? null, dualStack, affinity, maxItems: interceptorOpts?.maxItems ?? Infinity } const instance = new DNSInstance(opts) return dispatch => { return function dnsInterceptor (origDispatchOpts, handler) { const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin) if (isIP(origin.hostname) !== 0) { return dispatch(origDispatchOpts, handler) } instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => { if (err) { return handler.onError(err) } let dispatchOpts = null dispatchOpts = { ...origDispatchOpts, servername: origin.hostname, // For SNI on TLS origin: newOrigin, headers: { host: origin.hostname, ...origDispatchOpts.headers } } dispatch( dispatchOpts, instance.getHandler({ origin, dispatch, handler }, origDispatchOpts) ) }) return true } } } /***/ }), /***/ 8060: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(3440) const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707) const DecoratorHandler = __nccwpck_require__(8155) class DumpHandler extends DecoratorHandler { #maxSize = 1024 * 1024 #abort = null #dumped = false #aborted = false #size = 0 #reason = null #handler = null constructor ({ maxSize }, handler) { super(handler) if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) { throw new InvalidArgumentError('maxSize must be a number greater than 0') } this.#maxSize = maxSize ?? this.#maxSize this.#handler = handler } onConnect (abort) { this.#abort = abort this.#handler.onConnect(this.#customAbort.bind(this)) } #customAbort (reason) { this.#aborted = true this.#reason = reason } // TODO: will require adjustment after new hooks are out onHeaders (statusCode, rawHeaders, resume, statusMessage) { const headers = util.parseHeaders(rawHeaders) const contentLength = headers['content-length'] if (contentLength != null && contentLength > this.#maxSize) { throw new RequestAbortedError( `Response size (${contentLength}) larger than maxSize (${ this.#maxSize })` ) } if (this.#aborted) { return true } return this.#handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } onError (err) { if (this.#dumped) { return } err = this.#reason ?? err this.#handler.onError(err) } onData (chunk) { this.#size = this.#size + chunk.length if (this.#size >= this.#maxSize) { this.#dumped = true if (this.#aborted) { this.#handler.onError(this.#reason) } else { this.#handler.onComplete([]) } } return true } onComplete (trailers) { if (this.#dumped) { return } if (this.#aborted) { this.#handler.onError(this.reason) return } this.#handler.onComplete(trailers) } } function createDumpInterceptor ( { maxSize: defaultMaxSize } = { maxSize: 1024 * 1024 } ) { return dispatch => { return function Intercept (opts, handler) { const { dumpMaxSize = defaultMaxSize } = opts const dumpHandler = new DumpHandler( { maxSize: dumpMaxSize }, handler ) return dispatch(opts, dumpHandler) } } } module.exports = createDumpInterceptor /***/ }), /***/ 5092: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const RedirectHandler = __nccwpck_require__(8754) function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { return (dispatch) => { return function Intercept (opts, handler) { const { maxRedirections = defaultMaxRedirections } = opts if (!maxRedirections) { return dispatch(opts, handler) } const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. return dispatch(opts, redirectHandler) } } } module.exports = createRedirectInterceptor /***/ }), /***/ 1514: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const RedirectHandler = __nccwpck_require__(8754) module.exports = opts => { const globalMaxRedirections = opts?.maxRedirections return dispatch => { return function redirectInterceptor (opts, handler) { const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts if (!maxRedirections) { return dispatch(opts, handler) } const redirectHandler = new RedirectHandler( dispatch, maxRedirections, opts, handler ) return dispatch(baseOpts, redirectHandler) } } } /***/ }), /***/ 2026: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const RetryHandler = __nccwpck_require__(7816) module.exports = globalOpts => { return dispatch => { return function retryInterceptor (opts, handler) { return dispatch( opts, new RetryHandler( { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } }, { handler, dispatch } ) ) } } } /***/ }), /***/ 2824: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; const utils_1 = __nccwpck_require__(172); // C headers var ERROR; (function (ERROR) { ERROR[ERROR["OK"] = 0] = "OK"; ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; ERROR[ERROR["STRICT"] = 2] = "STRICT"; ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; ERROR[ERROR["USER"] = 24] = "USER"; })(ERROR = exports.ERROR || (exports.ERROR = {})); var TYPE; (function (TYPE) { TYPE[TYPE["BOTH"] = 0] = "BOTH"; TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; })(TYPE = exports.TYPE || (exports.TYPE = {})); var FLAGS; (function (FLAGS) { FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; // 1 << 8 is unused FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; })(FLAGS = exports.FLAGS || (exports.FLAGS = {})); var LENIENT_FLAGS; (function (LENIENT_FLAGS) { LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; })(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); var METHODS; (function (METHODS) { METHODS[METHODS["DELETE"] = 0] = "DELETE"; METHODS[METHODS["GET"] = 1] = "GET"; METHODS[METHODS["HEAD"] = 2] = "HEAD"; METHODS[METHODS["POST"] = 3] = "POST"; METHODS[METHODS["PUT"] = 4] = "PUT"; /* pathological */ METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; METHODS[METHODS["TRACE"] = 7] = "TRACE"; /* WebDAV */ METHODS[METHODS["COPY"] = 8] = "COPY"; METHODS[METHODS["LOCK"] = 9] = "LOCK"; METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; METHODS[METHODS["MOVE"] = 11] = "MOVE"; METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; METHODS[METHODS["BIND"] = 16] = "BIND"; METHODS[METHODS["REBIND"] = 17] = "REBIND"; METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; METHODS[METHODS["ACL"] = 19] = "ACL"; /* subversion */ METHODS[METHODS["REPORT"] = 20] = "REPORT"; METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; METHODS[METHODS["MERGE"] = 23] = "MERGE"; /* upnp */ METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; /* RFC-5789 */ METHODS[METHODS["PATCH"] = 28] = "PATCH"; METHODS[METHODS["PURGE"] = 29] = "PURGE"; /* CalDAV */ METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; /* RFC-2068, section 19.6.1.2 */ METHODS[METHODS["LINK"] = 31] = "LINK"; METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; /* icecast */ METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; /* RFC-7540, section 11.6 */ METHODS[METHODS["PRI"] = 34] = "PRI"; /* RFC-2326 RTSP */ METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; METHODS[METHODS["SETUP"] = 37] = "SETUP"; METHODS[METHODS["PLAY"] = 38] = "PLAY"; METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; METHODS[METHODS["RECORD"] = 44] = "RECORD"; /* RAOP */ METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; })(METHODS = exports.METHODS || (exports.METHODS = {})); exports.METHODS_HTTP = [ METHODS.DELETE, METHODS.GET, METHODS.HEAD, METHODS.POST, METHODS.PUT, METHODS.CONNECT, METHODS.OPTIONS, METHODS.TRACE, METHODS.COPY, METHODS.LOCK, METHODS.MKCOL, METHODS.MOVE, METHODS.PROPFIND, METHODS.PROPPATCH, METHODS.SEARCH, METHODS.UNLOCK, METHODS.BIND, METHODS.REBIND, METHODS.UNBIND, METHODS.ACL, METHODS.REPORT, METHODS.MKACTIVITY, METHODS.CHECKOUT, METHODS.MERGE, METHODS['M-SEARCH'], METHODS.NOTIFY, METHODS.SUBSCRIBE, METHODS.UNSUBSCRIBE, METHODS.PATCH, METHODS.PURGE, METHODS.MKCALENDAR, METHODS.LINK, METHODS.UNLINK, METHODS.PRI, // TODO(indutny): should we allow it with HTTP? METHODS.SOURCE, ]; exports.METHODS_ICE = [ METHODS.SOURCE, ]; exports.METHODS_RTSP = [ METHODS.OPTIONS, METHODS.DESCRIBE, METHODS.ANNOUNCE, METHODS.SETUP, METHODS.PLAY, METHODS.PAUSE, METHODS.TEARDOWN, METHODS.GET_PARAMETER, METHODS.SET_PARAMETER, METHODS.REDIRECT, METHODS.RECORD, METHODS.FLUSH, // For AirPlay METHODS.GET, METHODS.POST, ]; exports.METHOD_MAP = utils_1.enumToMap(METHODS); exports.H_METHOD_MAP = {}; Object.keys(exports.METHOD_MAP).forEach((key) => { if (/^H/.test(key)) { exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; } }); var FINISH; (function (FINISH) { FINISH[FINISH["SAFE"] = 0] = "SAFE"; FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; })(FINISH = exports.FINISH || (exports.FINISH = {})); exports.ALPHA = []; for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { // Upper case exports.ALPHA.push(String.fromCharCode(i)); // Lower case exports.ALPHA.push(String.fromCharCode(i + 0x20)); } exports.NUM_MAP = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, }; exports.HEX_MAP = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, }; exports.NUM = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ]; exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; exports.USERINFO_CHARS = exports.ALPHANUM .concat(exports.MARK) .concat(['%', ';', ':', '&', '=', '+', '$', ',']); // TODO(indutny): use RFC exports.STRICT_URL_CHAR = [ '!', '"', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', ].concat(exports.ALPHANUM); exports.URL_CHAR = exports.STRICT_URL_CHAR .concat(['\t', '\f']); // All characters with 0x80 bit set to 1 for (let i = 0x80; i <= 0xff; i++) { exports.URL_CHAR.push(i); } exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); /* Tokens as defined by rfc 2616. Also lowercases them. * token = 1* * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT */ exports.STRICT_TOKEN = [ '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '_', '`', '|', '~', ].concat(exports.ALPHANUM); exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); /* * Verify that a char is a valid visible (printable) US-ASCII * character or %x80-FF */ exports.HEADER_CHARS = ['\t']; for (let i = 32; i <= 255; i++) { if (i !== 127) { exports.HEADER_CHARS.push(i); } } // ',' = \x44 exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); exports.MAJOR = exports.NUM_MAP; exports.MINOR = exports.MAJOR; var HEADER_STATE; (function (HEADER_STATE) { HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; })(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); exports.SPECIAL_HEADERS = { 'connection': HEADER_STATE.CONNECTION, 'content-length': HEADER_STATE.CONTENT_LENGTH, 'proxy-connection': HEADER_STATE.CONNECTION, 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, 'upgrade': HEADER_STATE.UPGRADE, }; //# sourceMappingURL=constants.js.map /***/ }), /***/ 3870: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Buffer } = __nccwpck_require__(4573) module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl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AFBAWoiAUcNAAsgAiAFNgIADLACCyACQQA2AgAgBkEBaiEBQRAMcwtB/gAhAyABIARGDa4CIAIoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQfbOAGotAABHDXEgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK8CCyACQQA2AgAgBkEBaiEBQRYMcgtB/wAhAyABIARGDa0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQfzOAGotAABHDXAgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK4CCyACQQA2AgAgBkEBaiEBQQUMcQsgASAERgRAQYABIQMMrQILIAEtAABB2QBHDW4gAUEBaiEBQQgMcAsgASAERgRAQYEBIQMMrAILAkACQCABLQAAQc4Aaw4DAG8BbwsgAUEBaiEBQesAIQMMkwILIAFBAWohAUHsACEDDJICCyABIARGBEBBggEhAwyrAgsCQAJAIAEtAABByABrDggAbm5ubm5uAW4LIAFBAWohAUHqACEDDJICCyABQQFqIQFB7QAhAwyRAgtBgwEhAyABIARGDakCIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQYDPAGotAABHDWwgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKoCCyACQQA2AgAgBkEBaiEBQQAMbQtBhAEhAyABIARGDagCIAIoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQYPPAGotAABHDWsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKkCCyACQQA2AgAgBkEBaiEBQSMMbAsgASAERgRAQYUBIQMMqAILAkACQCABLQAAQcwAaw4IAGtra2trawFrCyABQQFqIQFB7wAhAwyPAgsgAUEBaiEBQfAAIQMMjgILIAEgBEYEQEGGASEDDKcCCyABLQAAQcUARw1oIAFBAWohAQxgC0GHASEDIAEgBEYNpQIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAA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ACQQA2AgQgAiAAIAEQJSIARQ0iIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADY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EBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAEH6yAALBAEAAAIAQZDJAAtfAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAQfrKAAsEAQAAAQBBkMsACwEBAEGqywALQQIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAEH6zAALBAEAAAEAQZDNAAsBAQBBms0ACwYCAAAAAAIAQbHNAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB8M4AC5YBTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRU9SRElSRUNUT1JUUkNIUEFSQU1FVEVSVVJDRUJTQ1JJQkVBUkRPV05BQ0VJTkROS0NLVUJTQ1JJQkVIVFRQL0FEVFAv', 'base64') /***/ }), /***/ 3434: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Buffer } = __nccwpck_require__(4573) module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9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JAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIoAhwiA0EBaw7dAdoBAdkBAgMEBQYHCAkKCwwNDtgBDxDXARES1gETFBUWFxgZGhvgAd8BHB0e1QEfICEiIyQl1AEmJygpKiss0wHSAS0u0QHQAS8w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AJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADDsYBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHyAhIyUmKCorLC8wMTIzNDU2Nzk6Ozw9lANAQkRFRklLTk9QUVJTVFVWWFpbXF1eX2BhYmNkZWZnaGpsb3Bxc3V2eHl6e3x/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBr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WohAUHmACEDDJgCCyABQQFqIQFB5wAhAwyXAgtB/QAhAyABIARGDa8CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDXIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADLACCyACQQA2AgAgBkEBaiEBQRAMcwtB/gAhAyABIARGDa4CIAIoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQfbOAGotAABHDXEgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK8CCyACQQA2AgAgBkEBaiEBQRYMcgtB/wAhAyABIARGDa0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQfzOAGotAABHDXAgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK4CCyACQQA2AgAgBkEBaiEBQQUMcQsgASAERgRAQYABIQMMrQILIAEtAABB2QBHDW4gAUEBaiEBQQgMcAsgASAERgRAQYEBIQMMrAILAkACQCABLQAAQc4Aaw4DAG8BbwsgAUEBaiEBQesAIQMMkwILIAFBAWohAUHsACEDDJICCyABIARGBEBBggEhAwyrAgsCQAJAIAEtAABByABrDggAbm5ubm5uAW4LIAFBAWohAUHqACEDDJICCyABQQFqIQFB7QAhAwyRAgtBgwEhAyABIARGDakCIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQYDPAGotAABHDWwgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKoCCyACQQA2AgAgBkEBaiEBQQAMbQtBhAEhAyABIARGDagCIAIoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQYPPAGotAABHDWsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKkCCyACQQA2AgAgBkEBaiEBQSMMbAsgASAERgRAQYUBIQMMqAILAkACQCABLQAAQcwAaw4IAGtra2trawFrCyABQQFqIQFB7wAhAwyP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QJSIARQ0RIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMtAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0gIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMswELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0iIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQA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EAIQMMlgELIAJB1wA2AhwgAiABNgIUIAJByRc2AhAgAkEVNgIMQQAhAwyVAQtBACEDIAJBADYCHCACIAE2AhQgAkGAETYCECACQQk2AgwMlAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0AIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMkwELQckAIQMMeQsgAkEANgIcIAIgATYCFCACQcEoNgIQIAJBBzYCDCACQQA2AgBBACEDDJEBCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAlIgBFDQAgAkHSADYCHCACIAE2AhQgAiAANgIMDJABC0HIACEDDHYLIAJBADYCACAFIQELIAJBgBI7ASogAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANAQtBxwAhAwxzCyAAQRVGBEAgAkHRADYCHCACIAE2AhQgAkHjFzYCECACQRU2AgxBACEDDIwBC0EAIQMgAkEANgIcIAIgATYCFCACQbkNNgIQIAJBGjYCDAyLAQtBACEDIAJBADYCHCACIAE2AhQgAkGgGTYCECACQR42AgwMigELIAEtAABBOkYEQCACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgBFDQEgAkHDADYCHCACIAA2AgwgAiABQQFqNgIUDIoBC0EAIQMgAkEANgIcIAIgATYCFCACQbERNgIQIAJBCjYCDAyJAQsgAUEBaiEBQTshAwxvCyACQcMANgIcIAIgADYCDCACIAFBAWo2AhQMhwELQQAhAyACQQA2AhwgAiABNgIUIAJB8A42AhAgAkEcNgIMDIYBCyACIAIvATBBEHI7ATAMZgsCQCACLwEwIgBBCHFFDQAgAi0AKEEBRw0AIAItAC1BCHFFDQMLIAIgAEH3+wNxQYAEcjsBMAwECyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE1IQMMbgsgAikDICIKQpmz5syZs+bMGVYNASACIApCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAIgCiALfDcDICAEIAFBAWoiAUcNAAtBOSEDDIUBCyACKAIEIQBBACEDIAJBADYCB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((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.enumToMap = void 0; function enumToMap(obj) { const res = {}; Object.keys(obj).forEach((key) => { const value = obj[key]; if (typeof value === 'number') { res[key] = value; } }); return res; } exports.enumToMap = enumToMap; //# sourceMappingURL=utils.js.map /***/ }), /***/ 7501: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kClients } = __nccwpck_require__(6443) const Agent = __nccwpck_require__(7405) const { kAgent, kMockAgentSet, kMockAgentGet, kDispatches, kIsMockActive, kNetConnect, kGetNetConnect, kOptions, kFactory } = __nccwpck_require__(1117) const MockClient = __nccwpck_require__(7365) const MockPool = __nccwpck_require__(4004) const { matchValue, buildMockOptions } = __nccwpck_require__(3397) const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8707) const Dispatcher = __nccwpck_require__(883) const Pluralizer = __nccwpck_require__(1529) const PendingInterceptorsFormatter = __nccwpck_require__(6142) class MockAgent extends Dispatcher { constructor (opts) { super(opts) this[kNetConnect] = true this[kIsMockActive] = true // Instantiate Agent and encapsulate if ((opts?.agent && typeof opts.agent.dispatch !== 'function')) { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } const agent = opts?.agent ? opts.agent : new Agent(opts) this[kAgent] = agent this[kClients] = agent[kClients] this[kOptions] = buildMockOptions(opts) } get (origin) { let dispatcher = this[kMockAgentGet](origin) if (!dispatcher) { dispatcher = this[kFactory](origin) this[kMockAgentSet](origin, dispatcher) } return dispatcher } dispatch (opts, handler) { // Call MockAgent.get to perform additional setup before dispatching as normal this.get(opts.origin) return this[kAgent].dispatch(opts, handler) } async close () { await this[kAgent].close() this[kClients].clear() } deactivate () { this[kIsMockActive] = false } activate () { this[kIsMockActive] = true } enableNetConnect (matcher) { if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { if (Array.isArray(this[kNetConnect])) { this[kNetConnect].push(matcher) } else { this[kNetConnect] = [matcher] } } else if (typeof matcher === 'undefined') { this[kNetConnect] = true } else { throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') } } disableNetConnect () { this[kNetConnect] = false } // This is required to bypass issues caused by using global symbols - see: // https://github.com/nodejs/undici/issues/1447 get isMockActive () { return this[kIsMockActive] } [kMockAgentSet] (origin, dispatcher) { this[kClients].set(origin, dispatcher) } [kFactory] (origin) { const mockOptions = Object.assign({ agent: this }, this[kOptions]) return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions) } [kMockAgentGet] (origin) { // First check if we can immediately find it const client = this[kClients].get(origin) if (client) { return client } // If the origin is not a string create a dummy parent pool and return to user if (typeof origin !== 'string') { const dispatcher = this[kFactory]('http://localhost:9999') this[kMockAgentSet](origin, dispatcher) return dispatcher } // If we match, create a pool and assign the same dispatches for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) { if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { const dispatcher = this[kFactory](origin) this[kMockAgentSet](origin, dispatcher) dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] return dispatcher } } } [kGetNetConnect] () { return this[kNetConnect] } pendingInterceptors () { const mockAgentClients = this[kClients] return Array.from(mockAgentClients.entries()) .flatMap(([origin, scope]) => scope[kDispatches].map(dispatch => ({ ...dispatch, origin }))) .filter(({ pending }) => pending) } assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { const pending = this.pendingInterceptors() if (pending.length === 0) { return } const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) throw new UndiciError(` ${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: ${pendingInterceptorsFormatter.format(pending)} `.trim()) } } module.exports = MockAgent /***/ }), /***/ 7365: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(7975) const Client = __nccwpck_require__(3701) const { buildMockDispatch } = __nccwpck_require__(3397) const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected } = __nccwpck_require__(1117) const { MockInterceptor } = __nccwpck_require__(1511) const Symbols = __nccwpck_require__(6443) const { InvalidArgumentError } = __nccwpck_require__(8707) /** * MockClient provides an API that extends the Client to influence the mockDispatches. */ class MockClient extends Client { constructor (origin, opts) { super(origin, opts) if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } this[kMockAgent] = opts.agent this[kOrigin] = origin this[kDispatches] = [] this[kConnected] = 1 this[kOriginalDispatch] = this.dispatch this[kOriginalClose] = this.close.bind(this) this.dispatch = buildMockDispatch.call(this) this.close = this[kClose] } get [Symbols.kConnected] () { return this[kConnected] } /** * Sets up the base interceptor for mocking replies from undici. */ intercept (opts) { return new MockInterceptor(opts, this[kDispatches]) } async [kClose] () { await promisify(this[kOriginalClose])() this[kConnected] = 0 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) } } module.exports = MockClient /***/ }), /***/ 2429: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { UndiciError } = __nccwpck_require__(8707) const kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED') /** * The request does not match any registered mock dispatches. */ class MockNotMatchedError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, MockNotMatchedError) this.name = 'MockNotMatchedError' this.message = message || 'The request does not match any registered mock dispatches' this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' } static [Symbol.hasInstance] (instance) { return instance && instance[kMockNotMatchedError] === true } [kMockNotMatchedError] = true } module.exports = { MockNotMatchedError } /***/ }), /***/ 1511: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(3397) const { kDispatches, kDispatchKey, kDefaultHeaders, kDefaultTrailers, kContentLength, kMockDispatch } = __nccwpck_require__(1117) const { InvalidArgumentError } = __nccwpck_require__(8707) const { buildURL } = __nccwpck_require__(3440) /** * Defines the scope API for an interceptor reply */ class MockScope { constructor (mockDispatch) { this[kMockDispatch] = mockDispatch } /** * Delay a reply by a set amount in ms. */ delay (waitInMs) { if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { throw new InvalidArgumentError('waitInMs must be a valid integer > 0') } this[kMockDispatch].delay = waitInMs return this } /** * For a defined reply, never mark as consumed. */ persist () { this[kMockDispatch].persist = true return this } /** * Allow one to define a reply for a set amount of matching requests. */ times (repeatTimes) { if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') } this[kMockDispatch].times = repeatTimes return this } } /** * Defines an interceptor for a Mock */ class MockInterceptor { constructor (opts, mockDispatches) { if (typeof opts !== 'object') { throw new InvalidArgumentError('opts must be an object') } if (typeof opts.path === 'undefined') { throw new InvalidArgumentError('opts.path must be defined') } if (typeof opts.method === 'undefined') { opts.method = 'GET' } // See https://github.com/nodejs/undici/issues/1245 // As per RFC 3986, clients are not supposed to send URI // fragments to servers when they retrieve a document, if (typeof opts.path === 'string') { if (opts.query) { opts.path = buildURL(opts.path, opts.query) } else { // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811 const parsedURL = new URL(opts.path, 'data://') opts.path = parsedURL.pathname + parsedURL.search } } if (typeof opts.method === 'string') { opts.method = opts.method.toUpperCase() } this[kDispatchKey] = buildKey(opts) this[kDispatches] = mockDispatches this[kDefaultHeaders] = {} this[kDefaultTrailers] = {} this[kContentLength] = false } createMockScopeDispatchData ({ statusCode, data, responseOptions }) { const responseData = getResponseData(data) const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } return { statusCode, data, headers, trailers } } validateReplyParameters (replyParameters) { if (typeof replyParameters.statusCode === 'undefined') { throw new InvalidArgumentError('statusCode must be defined') } if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) { throw new InvalidArgumentError('responseOptions must be an object') } } /** * Mock an undici request with a defined reply. */ reply (replyOptionsCallbackOrStatusCode) { // Values of reply aren't available right now as they // can only be available when the reply callback is invoked. if (typeof replyOptionsCallbackOrStatusCode === 'function') { // We'll first wrap the provided callback in another function, // this function will properly resolve the data from the callback // when invoked. const wrappedDefaultsCallback = (opts) => { // Our reply options callback contains the parameter for statusCode, data and options. const resolvedData = replyOptionsCallbackOrStatusCode(opts) // Check if it is in the right format if (typeof resolvedData !== 'object' || resolvedData === null) { throw new InvalidArgumentError('reply options callback must return an object') } const replyParameters = { data: '', responseOptions: {}, ...resolvedData } this.validateReplyParameters(replyParameters) // Since the values can be obtained immediately we return them // from this higher order function that will be resolved later. return { ...this.createMockScopeDispatchData(replyParameters) } } // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) return new MockScope(newMockDispatch) } // We can have either one or three parameters, if we get here, // we should have 1-3 parameters. So we spread the arguments of // this function to obtain the parameters, since replyData will always // just be the statusCode. const replyParameters = { statusCode: replyOptionsCallbackOrStatusCode, data: arguments[1] === undefined ? '' : arguments[1], responseOptions: arguments[2] === undefined ? {} : arguments[2] } this.validateReplyParameters(replyParameters) // Send in-already provided data like usual const dispatchData = this.createMockScopeDispatchData(replyParameters) const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) return new MockScope(newMockDispatch) } /** * Mock an undici request with a defined error. */ replyWithError (error) { if (typeof error === 'undefined') { throw new InvalidArgumentError('error must be defined') } const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) return new MockScope(newMockDispatch) } /** * Set default reply headers on the interceptor for subsequent replies */ defaultReplyHeaders (headers) { if (typeof headers === 'undefined') { throw new InvalidArgumentError('headers must be defined') } this[kDefaultHeaders] = headers return this } /** * Set default reply trailers on the interceptor for subsequent replies */ defaultReplyTrailers (trailers) { if (typeof trailers === 'undefined') { throw new InvalidArgumentError('trailers must be defined') } this[kDefaultTrailers] = trailers return this } /** * Set reply content length header for replies on the interceptor */ replyContentLength () { this[kContentLength] = true return this } } module.exports.MockInterceptor = MockInterceptor module.exports.MockScope = MockScope /***/ }), /***/ 4004: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(7975) const Pool = __nccwpck_require__(628) const { buildMockDispatch } = __nccwpck_require__(3397) const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected } = __nccwpck_require__(1117) const { MockInterceptor } = __nccwpck_require__(1511) const Symbols = __nccwpck_require__(6443) const { InvalidArgumentError } = __nccwpck_require__(8707) /** * MockPool provides an API that extends the Pool to influence the mockDispatches. */ class MockPool extends Pool { constructor (origin, opts) { super(origin, opts) if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } this[kMockAgent] = opts.agent this[kOrigin] = origin this[kDispatches] = [] this[kConnected] = 1 this[kOriginalDispatch] = this.dispatch this[kOriginalClose] = this.close.bind(this) this.dispatch = buildMockDispatch.call(this) this.close = this[kClose] } get [Symbols.kConnected] () { return this[kConnected] } /** * Sets up the base interceptor for mocking replies from undici. */ intercept (opts) { return new MockInterceptor(opts, this[kDispatches]) } async [kClose] () { await promisify(this[kOriginalClose])() this[kConnected] = 0 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) } } module.exports = MockPool /***/ }), /***/ 1117: /***/ ((module) => { "use strict"; module.exports = { kAgent: Symbol('agent'), kOptions: Symbol('options'), kFactory: Symbol('factory'), kDispatches: Symbol('dispatches'), kDispatchKey: Symbol('dispatch key'), kDefaultHeaders: Symbol('default headers'), kDefaultTrailers: Symbol('default trailers'), kContentLength: Symbol('content length'), kMockAgent: Symbol('mock agent'), kMockAgentSet: Symbol('mock agent set'), kMockAgentGet: Symbol('mock agent get'), kMockDispatch: Symbol('mock dispatch'), kClose: Symbol('close'), kOriginalClose: Symbol('original agent close'), kOrigin: Symbol('origin'), kIsMockActive: Symbol('is mock active'), kNetConnect: Symbol('net connect'), kGetNetConnect: Symbol('get net connect'), kConnected: Symbol('connected') } /***/ }), /***/ 3397: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { MockNotMatchedError } = __nccwpck_require__(2429) const { kDispatches, kMockAgent, kOriginalDispatch, kOrigin, kGetNetConnect } = __nccwpck_require__(1117) const { buildURL } = __nccwpck_require__(3440) const { STATUS_CODES } = __nccwpck_require__(7067) const { types: { isPromise } } = __nccwpck_require__(7975) function matchValue (match, value) { if (typeof match === 'string') { return match === value } if (match instanceof RegExp) { return match.test(value) } if (typeof match === 'function') { return match(value) === true } return false } function lowerCaseEntries (headers) { return Object.fromEntries( Object.entries(headers).map(([headerName, headerValue]) => { return [headerName.toLocaleLowerCase(), headerValue] }) ) } /** * @param {import('../../index').Headers|string[]|Record} headers * @param {string} key */ function getHeaderByName (headers, key) { if (Array.isArray(headers)) { for (let i = 0; i < headers.length; i += 2) { if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { return headers[i + 1] } } return undefined } else if (typeof headers.get === 'function') { return headers.get(key) } else { return lowerCaseEntries(headers)[key.toLocaleLowerCase()] } } /** @param {string[]} headers */ function buildHeadersFromArray (headers) { // fetch HeadersList const clone = headers.slice() const entries = [] for (let index = 0; index < clone.length; index += 2) { entries.push([clone[index], clone[index + 1]]) } return Object.fromEntries(entries) } function matchHeaders (mockDispatch, headers) { if (typeof mockDispatch.headers === 'function') { if (Array.isArray(headers)) { // fetch HeadersList headers = buildHeadersFromArray(headers) } return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) } if (typeof mockDispatch.headers === 'undefined') { return true } if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { return false } for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { const headerValue = getHeaderByName(headers, matchHeaderName) if (!matchValue(matchHeaderValue, headerValue)) { return false } } return true } function safeUrl (path) { if (typeof path !== 'string') { return path } const pathSegments = path.split('?') if (pathSegments.length !== 2) { return path } const qp = new URLSearchParams(pathSegments.pop()) qp.sort() return [...pathSegments, qp.toString()].join('?') } function matchKey (mockDispatch, { path, method, body, headers }) { const pathMatch = matchValue(mockDispatch.path, path) const methodMatch = matchValue(mockDispatch.method, method) const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true const headersMatch = matchHeaders(mockDispatch, headers) return pathMatch && methodMatch && bodyMatch && headersMatch } function getResponseData (data) { if (Buffer.isBuffer(data)) { return data } else if (data instanceof Uint8Array) { return data } else if (data instanceof ArrayBuffer) { return data } else if (typeof data === 'object') { return JSON.stringify(data) } else { return data.toString() } } function getMockDispatch (mockDispatches, key) { const basePath = key.query ? buildURL(key.path, key.query) : key.path const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath // Match path let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) } // Match method matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`) } // Match body matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`) } // Match headers matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) if (matchedMockDispatches.length === 0) { const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`) } return matchedMockDispatches[0] } function addMockDispatch (mockDispatches, key, data) { const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } const replyData = typeof data === 'function' ? { callback: data } : { ...data } const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } mockDispatches.push(newMockDispatch) return newMockDispatch } function deleteMockDispatch (mockDispatches, key) { const index = mockDispatches.findIndex(dispatch => { if (!dispatch.consumed) { return false } return matchKey(dispatch, key) }) if (index !== -1) { mockDispatches.splice(index, 1) } } function buildKey (opts) { const { path, method, body, headers, query } = opts return { path, method, body, headers, query } } function generateKeyValues (data) { const keys = Object.keys(data) const result = [] for (let i = 0; i < keys.length; ++i) { const key = keys[i] const value = data[key] const name = Buffer.from(`${key}`) if (Array.isArray(value)) { for (let j = 0; j < value.length; ++j) { result.push(name, Buffer.from(`${value[j]}`)) } } else { result.push(name, Buffer.from(`${value}`)) } } return result } /** * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status * @param {number} statusCode */ function getStatusText (statusCode) { return STATUS_CODES[statusCode] || 'unknown' } async function getResponse (body) { const buffers = [] for await (const data of body) { buffers.push(data) } return Buffer.concat(buffers).toString('utf8') } /** * Mock dispatch function used to simulate undici dispatches */ function mockDispatch (opts, handler) { // Get mock dispatch from built key const key = buildKey(opts) const mockDispatch = getMockDispatch(this[kDispatches], key) mockDispatch.timesInvoked++ // Here's where we resolve a callback if a callback is present for the dispatch data. if (mockDispatch.data.callback) { mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } } // Parse mockDispatch data const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch const { timesInvoked, times } = mockDispatch // If it's used up and not persistent, mark as consumed mockDispatch.consumed = !persist && timesInvoked >= times mockDispatch.pending = timesInvoked < times // If specified, trigger dispatch error if (error !== null) { deleteMockDispatch(this[kDispatches], key) handler.onError(error) return true } // Handle the request with a delay if necessary if (typeof delay === 'number' && delay > 0) { setTimeout(() => { handleReply(this[kDispatches]) }, delay) } else { handleReply(this[kDispatches]) } function handleReply (mockDispatches, _data = data) { // fetch's HeadersList is a 1D string array const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers const body = typeof _data === 'function' ? _data({ ...opts, headers: optsHeaders }) : _data // util.types.isPromise is likely needed for jest. if (isPromise(body)) { // If handleReply is asynchronous, throwing an error // in the callback will reject the promise, rather than // synchronously throw the error, which breaks some tests. // Rather, we wait for the callback to resolve if it is a // promise, and then re-run handleReply with the new body. body.then((newData) => handleReply(mockDispatches, newData)) return } const responseData = getResponseData(body) const responseHeaders = generateKeyValues(headers) const responseTrailers = generateKeyValues(trailers) handler.onConnect?.(err => handler.onError(err), null) handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode)) handler.onData?.(Buffer.from(responseData)) handler.onComplete?.(responseTrailers) deleteMockDispatch(mockDispatches, key) } function resume () {} return true } function buildMockDispatch () { const agent = this[kMockAgent] const origin = this[kOrigin] const originalDispatch = this[kOriginalDispatch] return function dispatch (opts, handler) { if (agent.isMockActive) { try { mockDispatch.call(this, opts, handler) } catch (error) { if (error instanceof MockNotMatchedError) { const netConnect = agent[kGetNetConnect]() if (netConnect === false) { throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) } if (checkNetConnect(netConnect, origin)) { originalDispatch.call(this, opts, handler) } else { throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) } } else { throw error } } } else { originalDispatch.call(this, opts, handler) } } } function checkNetConnect (netConnect, origin) { const url = new URL(origin) if (netConnect === true) { return true } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { return true } return false } function buildMockOptions (opts) { if (opts) { const { agent, ...mockOptions } = opts return mockOptions } } module.exports = { getResponseData, getMockDispatch, addMockDispatch, deleteMockDispatch, buildKey, generateKeyValues, matchValue, getResponse, getStatusText, mockDispatch, buildMockDispatch, checkNetConnect, buildMockOptions, getHeaderByName, buildHeadersFromArray } /***/ }), /***/ 6142: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Transform } = __nccwpck_require__(7075) const { Console } = __nccwpck_require__(7540) const PERSISTENT = process.versions.icu ? '✅' : 'Y ' const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N ' /** * Gets the output of `console.table(…)` as a string. */ module.exports = class PendingInterceptorsFormatter { constructor ({ disableColors } = {}) { this.transform = new Transform({ transform (chunk, _enc, cb) { cb(null, chunk) } }) this.logger = new Console({ stdout: this.transform, inspectOptions: { colors: !disableColors && !process.env.CI } }) } format (pendingInterceptors) { const withPrettyHeaders = pendingInterceptors.map( ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ Method: method, Origin: origin, Path: path, 'Status code': statusCode, Persistent: persist ? PERSISTENT : NOT_PERSISTENT, Invocations: timesInvoked, Remaining: persist ? Infinity : times - timesInvoked })) this.logger.table(withPrettyHeaders) return this.transform.read().toString() } } /***/ }), /***/ 1529: /***/ ((module) => { "use strict"; const singulars = { pronoun: 'it', is: 'is', was: 'was', this: 'this' } const plurals = { pronoun: 'they', is: 'are', was: 'were', this: 'these' } module.exports = class Pluralizer { constructor (singular, plural) { this.singular = singular this.plural = plural } pluralize (count) { const one = count === 1 const keys = one ? singulars : plurals const noun = one ? this.singular : this.plural return { ...keys, count, noun } } } /***/ }), /***/ 6603: /***/ ((module) => { "use strict"; /** * This module offers an optimized timer implementation designed for scenarios * where high precision is not critical. * * The timer achieves faster performance by using a low-resolution approach, * with an accuracy target of within 500ms. This makes it particularly useful * for timers with delays of 1 second or more, where exact timing is less * crucial. * * It's important to note that Node.js timers are inherently imprecise, as * delays can occur due to the event loop being blocked by other operations. * Consequently, timers may trigger later than their scheduled time. */ /** * The fastNow variable contains the internal fast timer clock value. * * @type {number} */ let fastNow = 0 /** * RESOLUTION_MS represents the target resolution time in milliseconds. * * @type {number} * @default 1000 */ const RESOLUTION_MS = 1e3 /** * TICK_MS defines the desired interval in milliseconds between each tick. * The target value is set to half the resolution time, minus 1 ms, to account * for potential event loop overhead. * * @type {number} * @default 499 */ const TICK_MS = (RESOLUTION_MS >> 1) - 1 /** * fastNowTimeout is a Node.js timer used to manage and process * the FastTimers stored in the `fastTimers` array. * * @type {NodeJS.Timeout} */ let fastNowTimeout /** * The kFastTimer symbol is used to identify FastTimer instances. * * @type {Symbol} */ const kFastTimer = Symbol('kFastTimer') /** * The fastTimers array contains all active FastTimers. * * @type {FastTimer[]} */ const fastTimers = [] /** * These constants represent the various states of a FastTimer. */ /** * The `NOT_IN_LIST` constant indicates that the FastTimer is not included * in the `fastTimers` array. Timers with this status will not be processed * during the next tick by the `onTick` function. * * A FastTimer can be re-added to the `fastTimers` array by invoking the * `refresh` method on the FastTimer instance. * * @type {-2} */ const NOT_IN_LIST = -2 /** * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled * for removal from the `fastTimers` array. A FastTimer in this state will * be removed in the next tick by the `onTick` function and will no longer * be processed. * * This status is also set when the `clear` method is called on the FastTimer instance. * * @type {-1} */ const TO_BE_CLEARED = -1 /** * The `PENDING` constant signifies that the FastTimer is awaiting processing * in the next tick by the `onTick` function. Timers with this status will have * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick. * * @type {0} */ const PENDING = 0 /** * The `ACTIVE` constant indicates that the FastTimer is active and waiting * for its timer to expire. During the next tick, the `onTick` function will * check if the timer has expired, and if so, it will execute the associated callback. * * @type {1} */ const ACTIVE = 1 /** * The onTick function processes the fastTimers array. * * @returns {void} */ function onTick () { /** * Increment the fastNow value by the TICK_MS value, despite the actual time * that has passed since the last tick. This approach ensures independence * from the system clock and delays caused by a blocked event loop. * * @type {number} */ fastNow += TICK_MS /** * The `idx` variable is used to iterate over the `fastTimers` array. * Expired timers are removed by replacing them with the last element in the array. * Consequently, `idx` is only incremented when the current element is not removed. * * @type {number} */ let idx = 0 /** * The len variable will contain the length of the fastTimers array * and will be decremented when a FastTimer should be removed from the * fastTimers array. * * @type {number} */ let len = fastTimers.length while (idx < len) { /** * @type {FastTimer} */ const timer = fastTimers[idx] // If the timer is in the ACTIVE state and the timer has expired, it will // be processed in the next tick. if (timer._state === PENDING) { // Set the _idleStart value to the fastNow value minus the TICK_MS value // to account for the time the timer was in the PENDING state. timer._idleStart = fastNow - TICK_MS timer._state = ACTIVE } else if ( timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout ) { timer._state = TO_BE_CLEARED timer._idleStart = -1 timer._onTimeout(timer._timerArg) } if (timer._state === TO_BE_CLEARED) { timer._state = NOT_IN_LIST // Move the last element to the current index and decrement len if it is // not the only element in the array. if (--len !== 0) { fastTimers[idx] = fastTimers[len] } } else { ++idx } } // Set the length of the fastTimers array to the new length and thus // removing the excess FastTimers elements from the array. fastTimers.length = len // If there are still active FastTimers in the array, refresh the Timer. // If there are no active FastTimers, the timer will be refreshed again // when a new FastTimer is instantiated. if (fastTimers.length !== 0) { refreshTimeout() } } function refreshTimeout () { // If the fastNowTimeout is already set, refresh it. if (fastNowTimeout) { fastNowTimeout.refresh() // fastNowTimeout is not instantiated yet, create a new Timer. } else { clearTimeout(fastNowTimeout) fastNowTimeout = setTimeout(onTick, TICK_MS) // If the Timer has an unref method, call it to allow the process to exit if // there are no other active handles. if (fastNowTimeout.unref) { fastNowTimeout.unref() } } } /** * The `FastTimer` class is a data structure designed to store and manage * timer information. */ class FastTimer { [kFastTimer] = true /** * The state of the timer, which can be one of the following: * - NOT_IN_LIST (-2) * - TO_BE_CLEARED (-1) * - PENDING (0) * - ACTIVE (1) * * @type {-2|-1|0|1} * @private */ _state = NOT_IN_LIST /** * The number of milliseconds to wait before calling the callback. * * @type {number} * @private */ _idleTimeout = -1 /** * The time in milliseconds when the timer was started. This value is used to * calculate when the timer should expire. * * @type {number} * @default -1 * @private */ _idleStart = -1 /** * The function to be executed when the timer expires. * @type {Function} * @private */ _onTimeout /** * The argument to be passed to the callback when the timer expires. * * @type {*} * @private */ _timerArg /** * @constructor * @param {Function} callback A function to be executed after the timer * expires. * @param {number} delay The time, in milliseconds that the timer should wait * before the specified function or code is executed. * @param {*} arg */ constructor (callback, delay, arg) { this._onTimeout = callback this._idleTimeout = delay this._timerArg = arg this.refresh() } /** * Sets the timer's start time to the current time, and reschedules the timer * to call its callback at the previously specified duration adjusted to the * current time. * Using this on a timer that has already called its callback will reactivate * the timer. * * @returns {void} */ refresh () { // In the special case that the timer is not in the list of active timers, // add it back to the array to be processed in the next tick by the onTick // function. if (this._state === NOT_IN_LIST) { fastTimers.push(this) } // If the timer is the only active timer, refresh the fastNowTimeout for // better resolution. if (!fastNowTimeout || fastTimers.length === 1) { refreshTimeout() } // Setting the state to PENDING will cause the timer to be reset in the // next tick by the onTick function. this._state = PENDING } /** * The `clear` method cancels the timer, preventing it from executing. * * @returns {void} * @private */ clear () { // Set the state to TO_BE_CLEARED to mark the timer for removal in the next // tick by the onTick function. this._state = TO_BE_CLEARED // Reset the _idleStart value to -1 to indicate that the timer is no longer // active. this._idleStart = -1 } } /** * This module exports a setTimeout and clearTimeout function that can be * used as a drop-in replacement for the native functions. */ module.exports = { /** * The setTimeout() method sets a timer which executes a function once the * timer expires. * @param {Function} callback A function to be executed after the timer * expires. * @param {number} delay The time, in milliseconds that the timer should * wait before the specified function or code is executed. * @param {*} [arg] An optional argument to be passed to the callback function * when the timer expires. * @returns {NodeJS.Timeout|FastTimer} */ setTimeout (callback, delay, arg) { // If the delay is less than or equal to the RESOLUTION_MS value return a // native Node.js Timer instance. return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg) }, /** * The clearTimeout method cancels an instantiated Timer previously created * by calling setTimeout. * * @param {NodeJS.Timeout|FastTimer} timeout */ clearTimeout (timeout) { // If the timeout is a FastTimer, call its own clear method. if (timeout[kFastTimer]) { /** * @type {FastTimer} */ timeout.clear() // Otherwise it is an instance of a native NodeJS.Timeout, so call the // Node.js native clearTimeout function. } else { clearTimeout(timeout) } }, /** * The setFastTimeout() method sets a fastTimer which executes a function once * the timer expires. * @param {Function} callback A function to be executed after the timer * expires. * @param {number} delay The time, in milliseconds that the timer should * wait before the specified function or code is executed. * @param {*} [arg] An optional argument to be passed to the callback function * when the timer expires. * @returns {FastTimer} */ setFastTimeout (callback, delay, arg) { return new FastTimer(callback, delay, arg) }, /** * The clearTimeout method cancels an instantiated FastTimer previously * created by calling setFastTimeout. * * @param {FastTimer} timeout */ clearFastTimeout (timeout) { timeout.clear() }, /** * The now method returns the value of the internal fast timer clock. * * @returns {number} */ now () { return fastNow }, /** * Trigger the onTick function to process the fastTimers array. * Exported for testing purposes only. * Marking as deprecated to discourage any use outside of testing. * @deprecated * @param {number} [delay=0] The delay in milliseconds to add to the now value. */ tick (delay = 0) { fastNow += delay - RESOLUTION_MS + 1 onTick() onTick() }, /** * Reset FastTimers. * Exported for testing purposes only. * Marking as deprecated to discourage any use outside of testing. * @deprecated */ reset () { fastNow = 0 fastTimers.length = 0 clearTimeout(fastNowTimeout) fastNowTimeout = null }, /** * Exporting for testing purposes only. * Marking as deprecated to discourage any use outside of testing. * @deprecated */ kFastTimer } /***/ }), /***/ 9634: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kConstruct } = __nccwpck_require__(109) const { urlEquals, getFieldValues } = __nccwpck_require__(6798) const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440) const { webidl } = __nccwpck_require__(5893) const { Response, cloneResponse, fromInnerResponse } = __nccwpck_require__(9051) const { Request, fromInnerRequest } = __nccwpck_require__(9967) const { kState } = __nccwpck_require__(3627) const { fetching } = __nccwpck_require__(4398) const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(3168) const assert = __nccwpck_require__(4589) /** * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation * @typedef {Object} CacheBatchOperation * @property {'delete' | 'put'} type * @property {any} request * @property {any} response * @property {import('../../types/cache').CacheQueryOptions} options */ /** * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list * @typedef {[any, any][]} requestResponseList */ class Cache { /** * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list * @type {requestResponseList} */ #relevantRequestResponseList constructor () { if (arguments[0] !== kConstruct) { webidl.illegalConstructor() } webidl.util.markAsUncloneable(this) this.#relevantRequestResponseList = arguments[1] } async match (request, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.match' webidl.argumentLengthCheck(arguments, 1, prefix) request = webidl.converters.RequestInfo(request, prefix, 'request') options = webidl.converters.CacheQueryOptions(options, prefix, 'options') const p = this.#internalMatchAll(request, options, 1) if (p.length === 0) { return } return p[0] } async matchAll (request = undefined, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.matchAll' if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request') options = webidl.converters.CacheQueryOptions(options, prefix, 'options') return this.#internalMatchAll(request, options) } async add (request) { webidl.brandCheck(this, Cache) const prefix = 'Cache.add' webidl.argumentLengthCheck(arguments, 1, prefix) request = webidl.converters.RequestInfo(request, prefix, 'request') // 1. const requests = [request] // 2. const responseArrayPromise = this.addAll(requests) // 3. return await responseArrayPromise } async addAll (requests) { webidl.brandCheck(this, Cache) const prefix = 'Cache.addAll' webidl.argumentLengthCheck(arguments, 1, prefix) // 1. const responsePromises = [] // 2. const requestList = [] // 3. for (let request of requests) { if (request === undefined) { throw webidl.errors.conversionFailed({ prefix, argument: 'Argument 1', types: ['undefined is not allowed'] }) } request = webidl.converters.RequestInfo(request) if (typeof request === 'string') { continue } // 3.1 const r = request[kState] // 3.2 if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { throw webidl.errors.exception({ header: prefix, message: 'Expected http/s scheme when method is not GET.' }) } } // 4. /** @type {ReturnType[]} */ const fetchControllers = [] // 5. for (const request of requests) { // 5.1 const r = new Request(request)[kState] // 5.2 if (!urlIsHttpHttpsScheme(r.url)) { throw webidl.errors.exception({ header: prefix, message: 'Expected http/s scheme.' }) } // 5.4 r.initiator = 'fetch' r.destination = 'subresource' // 5.5 requestList.push(r) // 5.6 const responsePromise = createDeferredPromise() // 5.7 fetchControllers.push(fetching({ request: r, processResponse (response) { // 1. if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { responsePromise.reject(webidl.errors.exception({ header: 'Cache.addAll', message: 'Received an invalid status code or the request failed.' })) } else if (response.headersList.contains('vary')) { // 2. // 2.1 const fieldValues = getFieldValues(response.headersList.get('vary')) // 2.2 for (const fieldValue of fieldValues) { // 2.2.1 if (fieldValue === '*') { responsePromise.reject(webidl.errors.exception({ header: 'Cache.addAll', message: 'invalid vary field value' })) for (const controller of fetchControllers) { controller.abort() } return } } } }, processResponseEndOfBody (response) { // 1. if (response.aborted) { responsePromise.reject(new DOMException('aborted', 'AbortError')) return } // 2. responsePromise.resolve(response) } })) // 5.8 responsePromises.push(responsePromise.promise) } // 6. const p = Promise.all(responsePromises) // 7. const responses = await p // 7.1 const operations = [] // 7.2 let index = 0 // 7.3 for (const response of responses) { // 7.3.1 /** @type {CacheBatchOperation} */ const operation = { type: 'put', // 7.3.2 request: requestList[index], // 7.3.3 response // 7.3.4 } operations.push(operation) // 7.3.5 index++ // 7.3.6 } // 7.5 const cacheJobPromise = createDeferredPromise() // 7.6.1 let errorData = null // 7.6.2 try { this.#batchCacheOperations(operations) } catch (e) { errorData = e } // 7.6.3 queueMicrotask(() => { // 7.6.3.1 if (errorData === null) { cacheJobPromise.resolve(undefined) } else { // 7.6.3.2 cacheJobPromise.reject(errorData) } }) // 7.7 return cacheJobPromise.promise } async put (request, response) { webidl.brandCheck(this, Cache) const prefix = 'Cache.put' webidl.argumentLengthCheck(arguments, 2, prefix) request = webidl.converters.RequestInfo(request, prefix, 'request') response = webidl.converters.Response(response, prefix, 'response') // 1. let innerRequest = null // 2. if (request instanceof Request) { innerRequest = request[kState] } else { // 3. innerRequest = new Request(request)[kState] } // 4. if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { throw webidl.errors.exception({ header: prefix, message: 'Expected an http/s scheme when method is not GET' }) } // 5. const innerResponse = response[kState] // 6. if (innerResponse.status === 206) { throw webidl.errors.exception({ header: prefix, message: 'Got 206 status' }) } // 7. if (innerResponse.headersList.contains('vary')) { // 7.1. const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) // 7.2. for (const fieldValue of fieldValues) { // 7.2.1 if (fieldValue === '*') { throw webidl.errors.exception({ header: prefix, message: 'Got * vary field value' }) } } } // 8. if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { throw webidl.errors.exception({ header: prefix, message: 'Response body is locked or disturbed' }) } // 9. const clonedResponse = cloneResponse(innerResponse) // 10. const bodyReadPromise = createDeferredPromise() // 11. if (innerResponse.body != null) { // 11.1 const stream = innerResponse.body.stream // 11.2 const reader = stream.getReader() // 11.3 readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) } else { bodyReadPromise.resolve(undefined) } // 12. /** @type {CacheBatchOperation[]} */ const operations = [] // 13. /** @type {CacheBatchOperation} */ const operation = { type: 'put', // 14. request: innerRequest, // 15. response: clonedResponse // 16. } // 17. operations.push(operation) // 19. const bytes = await bodyReadPromise.promise if (clonedResponse.body != null) { clonedResponse.body.source = bytes } // 19.1 const cacheJobPromise = createDeferredPromise() // 19.2.1 let errorData = null // 19.2.2 try { this.#batchCacheOperations(operations) } catch (e) { errorData = e } // 19.2.3 queueMicrotask(() => { // 19.2.3.1 if (errorData === null) { cacheJobPromise.resolve() } else { // 19.2.3.2 cacheJobPromise.reject(errorData) } }) return cacheJobPromise.promise } async delete (request, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.delete' webidl.argumentLengthCheck(arguments, 1, prefix) request = webidl.converters.RequestInfo(request, prefix, 'request') options = webidl.converters.CacheQueryOptions(options, prefix, 'options') /** * @type {Request} */ let r = null if (request instanceof Request) { r = request[kState] if (r.method !== 'GET' && !options.ignoreMethod) { return false } } else { assert(typeof request === 'string') r = new Request(request)[kState] } /** @type {CacheBatchOperation[]} */ const operations = [] /** @type {CacheBatchOperation} */ const operation = { type: 'delete', request: r, options } operations.push(operation) const cacheJobPromise = createDeferredPromise() let errorData = null let requestResponses try { requestResponses = this.#batchCacheOperations(operations) } catch (e) { errorData = e } queueMicrotask(() => { if (errorData === null) { cacheJobPromise.resolve(!!requestResponses?.length) } else { cacheJobPromise.reject(errorData) } }) return cacheJobPromise.promise } /** * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys * @param {any} request * @param {import('../../types/cache').CacheQueryOptions} options * @returns {Promise} */ async keys (request = undefined, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.keys' if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request') options = webidl.converters.CacheQueryOptions(options, prefix, 'options') // 1. let r = null // 2. if (request !== undefined) { // 2.1 if (request instanceof Request) { // 2.1.1 r = request[kState] // 2.1.2 if (r.method !== 'GET' && !options.ignoreMethod) { return [] } } else if (typeof request === 'string') { // 2.2 r = new Request(request)[kState] } } // 4. const promise = createDeferredPromise() // 5. // 5.1 const requests = [] // 5.2 if (request === undefined) { // 5.2.1 for (const requestResponse of this.#relevantRequestResponseList) { // 5.2.1.1 requests.push(requestResponse[0]) } } else { // 5.3 // 5.3.1 const requestResponses = this.#queryCache(r, options) // 5.3.2 for (const requestResponse of requestResponses) { // 5.3.2.1 requests.push(requestResponse[0]) } } // 5.4 queueMicrotask(() => { // 5.4.1 const requestList = [] // 5.4.2 for (const request of requests) { const requestObject = fromInnerRequest( request, new AbortController().signal, 'immutable' ) // 5.4.2.1 requestList.push(requestObject) } // 5.4.3 promise.resolve(Object.freeze(requestList)) }) return promise.promise } /** * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm * @param {CacheBatchOperation[]} operations * @returns {requestResponseList} */ #batchCacheOperations (operations) { // 1. const cache = this.#relevantRequestResponseList // 2. const backupCache = [...cache] // 3. const addedItems = [] // 4.1 const resultList = [] try { // 4.2 for (const operation of operations) { // 4.2.1 if (operation.type !== 'delete' && operation.type !== 'put') { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'operation type does not match "delete" or "put"' }) } // 4.2.2 if (operation.type === 'delete' && operation.response != null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'delete operation should not have an associated response' }) } // 4.2.3 if (this.#queryCache(operation.request, operation.options, addedItems).length) { throw new DOMException('???', 'InvalidStateError') } // 4.2.4 let requestResponses // 4.2.5 if (operation.type === 'delete') { // 4.2.5.1 requestResponses = this.#queryCache(operation.request, operation.options) // TODO: the spec is wrong, this is needed to pass WPTs if (requestResponses.length === 0) { return [] } // 4.2.5.2 for (const requestResponse of requestResponses) { const idx = cache.indexOf(requestResponse) assert(idx !== -1) // 4.2.5.2.1 cache.splice(idx, 1) } } else if (operation.type === 'put') { // 4.2.6 // 4.2.6.1 if (operation.response == null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'put operation should have an associated response' }) } // 4.2.6.2 const r = operation.request // 4.2.6.3 if (!urlIsHttpHttpsScheme(r.url)) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'expected http or https scheme' }) } // 4.2.6.4 if (r.method !== 'GET') { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'not get method' }) } // 4.2.6.5 if (operation.options != null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'options must not be defined' }) } // 4.2.6.6 requestResponses = this.#queryCache(operation.request) // 4.2.6.7 for (const requestResponse of requestResponses) { const idx = cache.indexOf(requestResponse) assert(idx !== -1) // 4.2.6.7.1 cache.splice(idx, 1) } // 4.2.6.8 cache.push([operation.request, operation.response]) // 4.2.6.10 addedItems.push([operation.request, operation.response]) } // 4.2.7 resultList.push([operation.request, operation.response]) } // 4.3 return resultList } catch (e) { // 5. // 5.1 this.#relevantRequestResponseList.length = 0 // 5.2 this.#relevantRequestResponseList = backupCache // 5.3 throw e } } /** * @see https://w3c.github.io/ServiceWorker/#query-cache * @param {any} requestQuery * @param {import('../../types/cache').CacheQueryOptions} options * @param {requestResponseList} targetStorage * @returns {requestResponseList} */ #queryCache (requestQuery, options, targetStorage) { /** @type {requestResponseList} */ const resultList = [] const storage = targetStorage ?? this.#relevantRequestResponseList for (const requestResponse of storage) { const [cachedRequest, cachedResponse] = requestResponse if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { resultList.push(requestResponse) } } return resultList } /** * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm * @param {any} requestQuery * @param {any} request * @param {any | null} response * @param {import('../../types/cache').CacheQueryOptions | undefined} options * @returns {boolean} */ #requestMatchesCachedItem (requestQuery, request, response = null, options) { // if (options?.ignoreMethod === false && request.method === 'GET') { // return false // } const queryURL = new URL(requestQuery.url) const cachedURL = new URL(request.url) if (options?.ignoreSearch) { cachedURL.search = '' queryURL.search = '' } if (!urlEquals(queryURL, cachedURL, true)) { return false } if ( response == null || options?.ignoreVary || !response.headersList.contains('vary') ) { return true } const fieldValues = getFieldValues(response.headersList.get('vary')) for (const fieldValue of fieldValues) { if (fieldValue === '*') { return false } const requestValue = request.headersList.get(fieldValue) const queryValue = requestQuery.headersList.get(fieldValue) // If one has the header and the other doesn't, or one has // a different value than the other, return false if (requestValue !== queryValue) { return false } } return true } #internalMatchAll (request, options, maxResponses = Infinity) { // 1. let r = null // 2. if (request !== undefined) { if (request instanceof Request) { // 2.1.1 r = request[kState] // 2.1.2 if (r.method !== 'GET' && !options.ignoreMethod) { return [] } } else if (typeof request === 'string') { // 2.2.1 r = new Request(request)[kState] } } // 5. // 5.1 const responses = [] // 5.2 if (request === undefined) { // 5.2.1 for (const requestResponse of this.#relevantRequestResponseList) { responses.push(requestResponse[1]) } } else { // 5.3 // 5.3.1 const requestResponses = this.#queryCache(r, options) // 5.3.2 for (const requestResponse of requestResponses) { responses.push(requestResponse[1]) } } // 5.4 // We don't implement CORs so we don't need to loop over the responses, yay! // 5.5.1 const responseList = [] // 5.5.2 for (const response of responses) { // 5.5.2.1 const responseObject = fromInnerResponse(response, 'immutable') responseList.push(responseObject.clone()) if (responseList.length >= maxResponses) { break } } // 6. return Object.freeze(responseList) } } Object.defineProperties(Cache.prototype, { [Symbol.toStringTag]: { value: 'Cache', configurable: true }, match: kEnumerableProperty, matchAll: kEnumerableProperty, add: kEnumerableProperty, addAll: kEnumerableProperty, put: kEnumerableProperty, delete: kEnumerableProperty, keys: kEnumerableProperty }) const cacheQueryOptionConverters = [ { key: 'ignoreSearch', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'ignoreMethod', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'ignoreVary', converter: webidl.converters.boolean, defaultValue: () => false } ] webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ ...cacheQueryOptionConverters, { key: 'cacheName', converter: webidl.converters.DOMString } ]) webidl.converters.Response = webidl.interfaceConverter(Response) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.RequestInfo ) module.exports = { Cache } /***/ }), /***/ 3245: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kConstruct } = __nccwpck_require__(109) const { Cache } = __nccwpck_require__(9634) const { webidl } = __nccwpck_require__(5893) const { kEnumerableProperty } = __nccwpck_require__(3440) class CacheStorage { /** * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map * @type {Map} */ async has (cacheName) { webidl.brandCheck(this, CacheStorage) const prefix = 'CacheStorage.has' webidl.argumentLengthCheck(arguments, 1, prefix) cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') // 2.1.1 // 2.2 return this.#caches.has(cacheName) } /** * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open * @param {string} cacheName * @returns {Promise} */ async open (cacheName) { webidl.brandCheck(this, CacheStorage) const prefix = 'CacheStorage.open' webidl.argumentLengthCheck(arguments, 1, prefix) cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') // 2.1 if (this.#caches.has(cacheName)) { // await caches.open('v1') !== await caches.open('v1') // 2.1.1 const cache = this.#caches.get(cacheName) // 2.1.1.1 return new Cache(kConstruct, cache) } // 2.2 const cache = [] // 2.3 this.#caches.set(cacheName, cache) // 2.4 return new Cache(kConstruct, cache) } /** * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete * @param {string} cacheName * @returns {Promise} */ async delete (cacheName) { webidl.brandCheck(this, CacheStorage) const prefix = 'CacheStorage.delete' webidl.argumentLengthCheck(arguments, 1, prefix) cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') return this.#caches.delete(cacheName) } /** * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys * @returns {Promise} */ async keys () { webidl.brandCheck(this, CacheStorage) // 2.1 const keys = this.#caches.keys() // 2.2 return [...keys] } } Object.defineProperties(CacheStorage.prototype, { [Symbol.toStringTag]: { value: 'CacheStorage', configurable: true }, match: kEnumerableProperty, has: kEnumerableProperty, open: kEnumerableProperty, delete: kEnumerableProperty, keys: kEnumerableProperty }) module.exports = { CacheStorage } /***/ }), /***/ 109: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = { kConstruct: (__nccwpck_require__(6443).kConstruct) } /***/ }), /***/ 6798: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) const { URLSerializer } = __nccwpck_require__(1900) const { isValidHeaderName } = __nccwpck_require__(3168) /** * @see https://url.spec.whatwg.org/#concept-url-equals * @param {URL} A * @param {URL} B * @param {boolean | undefined} excludeFragment * @returns {boolean} */ function urlEquals (A, B, excludeFragment = false) { const serializedA = URLSerializer(A, excludeFragment) const serializedB = URLSerializer(B, excludeFragment) return serializedA === serializedB } /** * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 * @param {string} header */ function getFieldValues (header) { assert(header !== null) const values = [] for (let value of header.split(',')) { value = value.trim() if (isValidHeaderName(value)) { values.push(value) } } return values } module.exports = { urlEquals, getFieldValues } /***/ }), /***/ 1276: /***/ ((module) => { "use strict"; // https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size const maxAttributeValueSize = 1024 // https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size const maxNameValuePairSize = 4096 module.exports = { maxAttributeValueSize, maxNameValuePairSize } /***/ }), /***/ 9061: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { parseSetCookie } = __nccwpck_require__(1978) const { stringify } = __nccwpck_require__(7797) const { webidl } = __nccwpck_require__(5893) const { Headers } = __nccwpck_require__(660) /** * @typedef {Object} Cookie * @property {string} name * @property {string} value * @property {Date|number|undefined} expires * @property {number|undefined} maxAge * @property {string|undefined} domain * @property {string|undefined} path * @property {boolean|undefined} secure * @property {boolean|undefined} httpOnly * @property {'Strict'|'Lax'|'None'} sameSite * @property {string[]} unparsed */ /** * @param {Headers} headers * @returns {Record} */ function getCookies (headers) { webidl.argumentLengthCheck(arguments, 1, 'getCookies') webidl.brandCheck(headers, Headers, { strict: false }) const cookie = headers.get('cookie') const out = {} if (!cookie) { return out } for (const piece of cookie.split(';')) { const [name, ...value] = piece.split('=') out[name.trim()] = value.join('=') } return out } /** * @param {Headers} headers * @param {string} name * @param {{ path?: string, domain?: string }|undefined} attributes * @returns {void} */ function deleteCookie (headers, name, attributes) { webidl.brandCheck(headers, Headers, { strict: false }) const prefix = 'deleteCookie' webidl.argumentLengthCheck(arguments, 2, prefix) name = webidl.converters.DOMString(name, prefix, 'name') attributes = webidl.converters.DeleteCookieAttributes(attributes) // Matches behavior of // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 setCookie(headers, { name, value: '', expires: new Date(0), ...attributes }) } /** * @param {Headers} headers * @returns {Cookie[]} */ function getSetCookies (headers) { webidl.argumentLengthCheck(arguments, 1, 'getSetCookies') webidl.brandCheck(headers, Headers, { strict: false }) const cookies = headers.getSetCookie() if (!cookies) { return [] } return cookies.map((pair) => parseSetCookie(pair)) } /** * @param {Headers} headers * @param {Cookie} cookie * @returns {void} */ function setCookie (headers, cookie) { webidl.argumentLengthCheck(arguments, 2, 'setCookie') webidl.brandCheck(headers, Headers, { strict: false }) cookie = webidl.converters.Cookie(cookie) const str = stringify(cookie) if (str) { headers.append('Set-Cookie', str) } } webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'path', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'domain', defaultValue: () => null } ]) webidl.converters.Cookie = webidl.dictionaryConverter([ { converter: webidl.converters.DOMString, key: 'name' }, { converter: webidl.converters.DOMString, key: 'value' }, { converter: webidl.nullableConverter((value) => { if (typeof value === 'number') { return webidl.converters['unsigned long long'](value) } return new Date(value) }), key: 'expires', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters['long long']), key: 'maxAge', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'domain', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'path', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.boolean), key: 'secure', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.boolean), key: 'httpOnly', defaultValue: () => null }, { converter: webidl.converters.USVString, key: 'sameSite', allowedValues: ['Strict', 'Lax', 'None'] }, { converter: webidl.sequenceConverter(webidl.converters.DOMString), key: 'unparsed', defaultValue: () => new Array(0) } ]) module.exports = { getCookies, deleteCookie, getSetCookies, setCookie } /***/ }), /***/ 1978: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(1276) const { isCTLExcludingHtab } = __nccwpck_require__(7797) const { collectASequenceOfCodePointsFast } = __nccwpck_require__(1900) const assert = __nccwpck_require__(4589) /** * @description Parses the field-value attributes of a set-cookie header string. * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 * @param {string} header * @returns if the header is invalid, null will be returned */ function parseSetCookie (header) { // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F // character (CTL characters excluding HTAB): Abort these steps and // ignore the set-cookie-string entirely. if (isCTLExcludingHtab(header)) { return null } let nameValuePair = '' let unparsedAttributes = '' let name = '' let value = '' // 2. If the set-cookie-string contains a %x3B (";") character: if (header.includes(';')) { // 1. The name-value-pair string consists of the characters up to, // but not including, the first %x3B (";"), and the unparsed- // attributes consist of the remainder of the set-cookie-string // (including the %x3B (";") in question). const position = { position: 0 } nameValuePair = collectASequenceOfCodePointsFast(';', header, position) unparsedAttributes = header.slice(position.position) } else { // Otherwise: // 1. The name-value-pair string consists of all the characters // contained in the set-cookie-string, and the unparsed- // attributes is the empty string. nameValuePair = header } // 3. If the name-value-pair string lacks a %x3D ("=") character, then // the name string is empty, and the value string is the value of // name-value-pair. if (!nameValuePair.includes('=')) { value = nameValuePair } else { // Otherwise, the name string consists of the characters up to, but // not including, the first %x3D ("=") character, and the (possibly // empty) value string consists of the characters after the first // %x3D ("=") character. const position = { position: 0 } name = collectASequenceOfCodePointsFast( '=', nameValuePair, position ) value = nameValuePair.slice(position.position + 1) } // 4. Remove any leading or trailing WSP characters from the name // string and the value string. name = name.trim() value = value.trim() // 5. If the sum of the lengths of the name string and the value string // is more than 4096 octets, abort these steps and ignore the set- // cookie-string entirely. if (name.length + value.length > maxNameValuePairSize) { return null } // 6. The cookie-name is the name string, and the cookie-value is the // value string. return { name, value, ...parseUnparsedAttributes(unparsedAttributes) } } /** * Parses the remaining attributes of a set-cookie header * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 * @param {string} unparsedAttributes * @param {[Object.]={}} cookieAttributeList */ function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { // 1. If the unparsed-attributes string is empty, skip the rest of // these steps. if (unparsedAttributes.length === 0) { return cookieAttributeList } // 2. Discard the first character of the unparsed-attributes (which // will be a %x3B (";") character). assert(unparsedAttributes[0] === ';') unparsedAttributes = unparsedAttributes.slice(1) let cookieAv = '' // 3. If the remaining unparsed-attributes contains a %x3B (";") // character: if (unparsedAttributes.includes(';')) { // 1. Consume the characters of the unparsed-attributes up to, but // not including, the first %x3B (";") character. cookieAv = collectASequenceOfCodePointsFast( ';', unparsedAttributes, { position: 0 } ) unparsedAttributes = unparsedAttributes.slice(cookieAv.length) } else { // Otherwise: // 1. Consume the remainder of the unparsed-attributes. cookieAv = unparsedAttributes unparsedAttributes = '' } // Let the cookie-av string be the characters consumed in this step. let attributeName = '' let attributeValue = '' // 4. If the cookie-av string contains a %x3D ("=") character: if (cookieAv.includes('=')) { // 1. The (possibly empty) attribute-name string consists of the // characters up to, but not including, the first %x3D ("=") // character, and the (possibly empty) attribute-value string // consists of the characters after the first %x3D ("=") // character. const position = { position: 0 } attributeName = collectASequenceOfCodePointsFast( '=', cookieAv, position ) attributeValue = cookieAv.slice(position.position + 1) } else { // Otherwise: // 1. The attribute-name string consists of the entire cookie-av // string, and the attribute-value string is empty. attributeName = cookieAv } // 5. Remove any leading or trailing WSP characters from the attribute- // name string and the attribute-value string. attributeName = attributeName.trim() attributeValue = attributeValue.trim() // 6. If the attribute-value is longer than 1024 octets, ignore the // cookie-av string and return to Step 1 of this algorithm. if (attributeValue.length > maxAttributeValueSize) { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 7. Process the attribute-name and attribute-value according to the // requirements in the following subsections. (Notice that // attributes with unrecognized attribute-names are ignored.) const attributeNameLowercase = attributeName.toLowerCase() // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 // If the attribute-name case-insensitively matches the string // "Expires", the user agent MUST process the cookie-av as follows. if (attributeNameLowercase === 'expires') { // 1. Let the expiry-time be the result of parsing the attribute-value // as cookie-date (see Section 5.1.1). const expiryTime = new Date(attributeValue) // 2. If the attribute-value failed to parse as a cookie date, ignore // the cookie-av. cookieAttributeList.expires = expiryTime } else if (attributeNameLowercase === 'max-age') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 // If the attribute-name case-insensitively matches the string "Max- // Age", the user agent MUST process the cookie-av as follows. // 1. If the first character of the attribute-value is not a DIGIT or a // "-" character, ignore the cookie-av. const charCode = attributeValue.charCodeAt(0) if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 2. If the remainder of attribute-value contains a non-DIGIT // character, ignore the cookie-av. if (!/^\d+$/.test(attributeValue)) { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 3. Let delta-seconds be the attribute-value converted to an integer. const deltaSeconds = Number(attributeValue) // 4. Let cookie-age-limit be the maximum age of the cookie (which // SHOULD be 400 days or less, see Section 4.1.2.2). // 5. Set delta-seconds to the smaller of its present value and cookie- // age-limit. // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) // 6. If delta-seconds is less than or equal to zero (0), let expiry- // time be the earliest representable date and time. Otherwise, let // the expiry-time be the current date and time plus delta-seconds // seconds. // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds // 7. Append an attribute to the cookie-attribute-list with an // attribute-name of Max-Age and an attribute-value of expiry-time. cookieAttributeList.maxAge = deltaSeconds } else if (attributeNameLowercase === 'domain') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 // If the attribute-name case-insensitively matches the string "Domain", // the user agent MUST process the cookie-av as follows. // 1. Let cookie-domain be the attribute-value. let cookieDomain = attributeValue // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be // cookie-domain without its leading %x2E ("."). if (cookieDomain[0] === '.') { cookieDomain = cookieDomain.slice(1) } // 3. Convert the cookie-domain to lower case. cookieDomain = cookieDomain.toLowerCase() // 4. Append an attribute to the cookie-attribute-list with an // attribute-name of Domain and an attribute-value of cookie-domain. cookieAttributeList.domain = cookieDomain } else if (attributeNameLowercase === 'path') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 // If the attribute-name case-insensitively matches the string "Path", // the user agent MUST process the cookie-av as follows. // 1. If the attribute-value is empty or if the first character of the // attribute-value is not %x2F ("/"): let cookiePath = '' if (attributeValue.length === 0 || attributeValue[0] !== '/') { // 1. Let cookie-path be the default-path. cookiePath = '/' } else { // Otherwise: // 1. Let cookie-path be the attribute-value. cookiePath = attributeValue } // 2. Append an attribute to the cookie-attribute-list with an // attribute-name of Path and an attribute-value of cookie-path. cookieAttributeList.path = cookiePath } else if (attributeNameLowercase === 'secure') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 // If the attribute-name case-insensitively matches the string "Secure", // the user agent MUST append an attribute to the cookie-attribute-list // with an attribute-name of Secure and an empty attribute-value. cookieAttributeList.secure = true } else if (attributeNameLowercase === 'httponly') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 // If the attribute-name case-insensitively matches the string // "HttpOnly", the user agent MUST append an attribute to the cookie- // attribute-list with an attribute-name of HttpOnly and an empty // attribute-value. cookieAttributeList.httpOnly = true } else if (attributeNameLowercase === 'samesite') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 // If the attribute-name case-insensitively matches the string // "SameSite", the user agent MUST process the cookie-av as follows: // 1. Let enforcement be "Default". let enforcement = 'Default' const attributeValueLowercase = attributeValue.toLowerCase() // 2. If cookie-av's attribute-value is a case-insensitive match for // "None", set enforcement to "None". if (attributeValueLowercase.includes('none')) { enforcement = 'None' } // 3. If cookie-av's attribute-value is a case-insensitive match for // "Strict", set enforcement to "Strict". if (attributeValueLowercase.includes('strict')) { enforcement = 'Strict' } // 4. If cookie-av's attribute-value is a case-insensitive match for // "Lax", set enforcement to "Lax". if (attributeValueLowercase.includes('lax')) { enforcement = 'Lax' } // 5. Append an attribute to the cookie-attribute-list with an // attribute-name of "SameSite" and an attribute-value of // enforcement. cookieAttributeList.sameSite = enforcement } else { cookieAttributeList.unparsed ??= [] cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) } // 8. Return to Step 1 of this algorithm. return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } module.exports = { parseSetCookie, parseUnparsedAttributes } /***/ }), /***/ 7797: /***/ ((module) => { "use strict"; /** * @param {string} value * @returns {boolean} */ function isCTLExcludingHtab (value) { for (let i = 0; i < value.length; ++i) { const code = value.charCodeAt(i) if ( (code >= 0x00 && code <= 0x08) || (code >= 0x0A && code <= 0x1F) || code === 0x7F ) { return true } } return false } /** CHAR = token = 1* separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT * @param {string} name */ function validateCookieName (name) { for (let i = 0; i < name.length; ++i) { const code = name.charCodeAt(i) if ( code < 0x21 || // exclude CTLs (0-31), SP and HT code > 0x7E || // exclude non-ascii and DEL code === 0x22 || // " code === 0x28 || // ( code === 0x29 || // ) code === 0x3C || // < code === 0x3E || // > code === 0x40 || // @ code === 0x2C || // , code === 0x3B || // ; code === 0x3A || // : code === 0x5C || // \ code === 0x2F || // / code === 0x5B || // [ code === 0x5D || // ] code === 0x3F || // ? code === 0x3D || // = code === 0x7B || // { code === 0x7D // } ) { throw new Error('Invalid cookie name') } } } /** 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 * @param {string} value */ function validateCookieValue (value) { let len = value.length let i = 0 // if the value is wrapped in DQUOTE if (value[0] === '"') { if (len === 1 || value[len - 1] !== '"') { throw new Error('Invalid cookie value') } --len ++i } while (i < len) { const code = value.charCodeAt(i++) if ( code < 0x21 || // exclude CTLs (0-31) code > 0x7E || // non-ascii and DEL (127) code === 0x22 || // " code === 0x2C || // , code === 0x3B || // ; code === 0x5C // \ ) { throw new Error('Invalid cookie value') } } } /** * path-value = * @param {string} path */ function validateCookiePath (path) { for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i) if ( code < 0x20 || // exclude CTLs (0-31) code === 0x7F || // DEL code === 0x3B // ; ) { throw new Error('Invalid cookie path') } } } /** * I have no idea why these values aren't allowed to be honest, * but Deno tests these. - Khafra * @param {string} domain */ function validateCookieDomain (domain) { if ( domain.startsWith('-') || domain.endsWith('.') || domain.endsWith('-') ) { throw new Error('Invalid cookie domain') } } const IMFDays = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ] const IMFMonths = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0')) /** * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 * @param {number|Date} date IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT ; fixed length/zone/capitalization subset of the format ; see Section 3.3 of [RFC5322] day-name = %x4D.6F.6E ; "Mon", case-sensitive / %x54.75.65 ; "Tue", case-sensitive / %x57.65.64 ; "Wed", case-sensitive / %x54.68.75 ; "Thu", case-sensitive / %x46.72.69 ; "Fri", case-sensitive / %x53.61.74 ; "Sat", case-sensitive / %x53.75.6E ; "Sun", case-sensitive date1 = day SP month SP year ; e.g., 02 Jun 1982 day = 2DIGIT month = %x4A.61.6E ; "Jan", case-sensitive / %x46.65.62 ; "Feb", case-sensitive / %x4D.61.72 ; "Mar", case-sensitive / %x41.70.72 ; "Apr", case-sensitive / %x4D.61.79 ; "May", case-sensitive / %x4A.75.6E ; "Jun", case-sensitive / %x4A.75.6C ; "Jul", case-sensitive / %x41.75.67 ; "Aug", case-sensitive / %x53.65.70 ; "Sep", case-sensitive / %x4F.63.74 ; "Oct", case-sensitive / %x4E.6F.76 ; "Nov", case-sensitive / %x44.65.63 ; "Dec", case-sensitive year = 4DIGIT GMT = %x47.4D.54 ; "GMT", case-sensitive time-of-day = hour ":" minute ":" second ; 00:00:00 - 23:59:60 (leap second) hour = 2DIGIT minute = 2DIGIT second = 2DIGIT */ function toIMFDate (date) { if (typeof date === 'number') { date = new Date(date) } return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT` } /** max-age-av = "Max-Age=" non-zero-digit *DIGIT ; In practice, both expires-av and max-age-av ; are limited to dates representable by the ; user agent. * @param {number} maxAge */ function validateCookieMaxAge (maxAge) { if (maxAge < 0) { throw new Error('Invalid cookie max-age') } } /** * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 * @param {import('./index').Cookie} cookie */ function stringify (cookie) { if (cookie.name.length === 0) { return null } validateCookieName(cookie.name) validateCookieValue(cookie.value) const out = [`${cookie.name}=${cookie.value}`] // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 if (cookie.name.startsWith('__Secure-')) { cookie.secure = true } if (cookie.name.startsWith('__Host-')) { cookie.secure = true cookie.domain = null cookie.path = '/' } if (cookie.secure) { out.push('Secure') } if (cookie.httpOnly) { out.push('HttpOnly') } if (typeof cookie.maxAge === 'number') { validateCookieMaxAge(cookie.maxAge) out.push(`Max-Age=${cookie.maxAge}`) } if (cookie.domain) { validateCookieDomain(cookie.domain) out.push(`Domain=${cookie.domain}`) } if (cookie.path) { validateCookiePath(cookie.path) out.push(`Path=${cookie.path}`) } if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { out.push(`Expires=${toIMFDate(cookie.expires)}`) } if (cookie.sameSite) { out.push(`SameSite=${cookie.sameSite}`) } for (const part of cookie.unparsed) { if (!part.includes('=')) { throw new Error('Invalid unparsed') } const [key, ...value] = part.split('=') out.push(`${key.trim()}=${value.join('=')}`) } return out.join('; ') } module.exports = { isCTLExcludingHtab, validateCookieName, validateCookiePath, validateCookieValue, toIMFDate, stringify } /***/ }), /***/ 4031: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Transform } = __nccwpck_require__(7075) const { isASCIINumber, isValidLastEventId } = __nccwpck_require__(4811) /** * @type {number[]} BOM */ const BOM = [0xEF, 0xBB, 0xBF] /** * @type {10} LF */ const LF = 0x0A /** * @type {13} CR */ const CR = 0x0D /** * @type {58} COLON */ const COLON = 0x3A /** * @type {32} SPACE */ const SPACE = 0x20 /** * @typedef {object} EventSourceStreamEvent * @type {object} * @property {string} [event] The event type. * @property {string} [data] The data of the message. * @property {string} [id] A unique ID for the event. * @property {string} [retry] The reconnection time, in milliseconds. */ /** * @typedef eventSourceSettings * @type {object} * @property {string} lastEventId The last event ID received from the server. * @property {string} origin The origin of the event source. * @property {number} reconnectionTime The reconnection time, in milliseconds. */ class EventSourceStream extends Transform { /** * @type {eventSourceSettings} */ state = null /** * Leading byte-order-mark check. * @type {boolean} */ checkBOM = true /** * @type {boolean} */ crlfCheck = false /** * @type {boolean} */ eventEndCheck = false /** * @type {Buffer} */ buffer = null pos = 0 event = { data: undefined, event: undefined, id: undefined, retry: undefined } /** * @param {object} options * @param {eventSourceSettings} options.eventSourceSettings * @param {Function} [options.push] */ constructor (options = {}) { // Enable object mode as EventSourceStream emits objects of shape // EventSourceStreamEvent options.readableObjectMode = true super(options) this.state = options.eventSourceSettings || {} if (options.push) { this.push = options.push } } /** * @param {Buffer} chunk * @param {string} _encoding * @param {Function} callback * @returns {void} */ _transform (chunk, _encoding, callback) { if (chunk.length === 0) { callback() return } // Cache the chunk in the buffer, as the data might not be complete while // processing it // TODO: Investigate if there is a more performant way to handle // incoming chunks // see: https://github.com/nodejs/undici/issues/2630 if (this.buffer) { this.buffer = Buffer.concat([this.buffer, chunk]) } else { this.buffer = chunk } // Strip leading byte-order-mark if we opened the stream and started // the processing of the incoming data if (this.checkBOM) { switch (this.buffer.length) { case 1: // Check if the first byte is the same as the first byte of the BOM if (this.buffer[0] === BOM[0]) { // If it is, we need to wait for more data callback() return } // Set the checkBOM flag to false as we don't need to check for the // BOM anymore this.checkBOM = false // The buffer only contains one byte so we need to wait for more data callback() return case 2: // Check if the first two bytes are the same as the first two bytes // of the BOM if ( this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] ) { // If it is, we need to wait for more data, because the third byte // is needed to determine if it is the BOM or not callback() return } // Set the checkBOM flag to false as we don't need to check for the // BOM anymore this.checkBOM = false break case 3: // Check if the first three bytes are the same as the first three // bytes of the BOM if ( this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2] ) { // If it is, we can drop the buffered data, as it is only the BOM this.buffer = Buffer.alloc(0) // Set the checkBOM flag to false as we don't need to check for the // BOM anymore this.checkBOM = false // Await more data callback() return } // If it is not the BOM, we can start processing the data this.checkBOM = false break default: // The buffer is longer than 3 bytes, so we can drop the BOM if it is // present if ( this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2] ) { // Remove the BOM from the buffer this.buffer = this.buffer.subarray(3) } // Set the checkBOM flag to false as we don't need to check for the this.checkBOM = false break } } while (this.pos < this.buffer.length) { // If the previous line ended with an end-of-line, we need to check // if the next character is also an end-of-line. if (this.eventEndCheck) { // If the the current character is an end-of-line, then the event // is finished and we can process it // If the previous line ended with a carriage return, we need to // check if the current character is a line feed and remove it // from the buffer. if (this.crlfCheck) { // If the current character is a line feed, we can remove it // from the buffer and reset the crlfCheck flag if (this.buffer[this.pos] === LF) { this.buffer = this.buffer.subarray(this.pos + 1) this.pos = 0 this.crlfCheck = false // It is possible that the line feed is not the end of the // event. We need to check if the next character is an // end-of-line character to determine if the event is // finished. We simply continue the loop to check the next // character. // As we removed the line feed from the buffer and set the // crlfCheck flag to false, we basically don't make any // distinction between a line feed and a carriage return. continue } this.crlfCheck = false } if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { // If the current character is a carriage return, we need to // set the crlfCheck flag to true, as we need to check if the // next character is a line feed so we can remove it from the // buffer if (this.buffer[this.pos] === CR) { this.crlfCheck = true } this.buffer = this.buffer.subarray(this.pos + 1) this.pos = 0 if ( this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event) } this.clearEvent() continue } // If the current character is not an end-of-line, then the event // is not finished and we have to reset the eventEndCheck flag this.eventEndCheck = false continue } // If the current character is an end-of-line, we can process the // line if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { // If the current character is a carriage return, we need to // set the crlfCheck flag to true, as we need to check if the // next character is a line feed if (this.buffer[this.pos] === CR) { this.crlfCheck = true } // In any case, we can process the line as we reached an // end-of-line character this.parseLine(this.buffer.subarray(0, this.pos), this.event) // Remove the processed line from the buffer this.buffer = this.buffer.subarray(this.pos + 1) // Reset the position as we removed the processed line from the buffer this.pos = 0 // A line was processed and this could be the end of the event. We need // to check if the next line is empty to determine if the event is // finished. this.eventEndCheck = true continue } this.pos++ } callback() } /** * @param {Buffer} line * @param {EventStreamEvent} event */ parseLine (line, event) { // If the line is empty (a blank line) // Dispatch the event, as defined below. // This will be handled in the _transform method if (line.length === 0) { return } // If the line starts with a U+003A COLON character (:) // Ignore the line. const colonPosition = line.indexOf(COLON) if (colonPosition === 0) { return } let field = '' let value = '' // If the line contains a U+003A COLON character (:) if (colonPosition !== -1) { // Collect the characters on the line before the first U+003A COLON // character (:), and let field be that string. // TODO: Investigate if there is a more performant way to extract the // field // see: https://github.com/nodejs/undici/issues/2630 field = line.subarray(0, colonPosition).toString('utf8') // Collect the characters on the line after the first U+003A COLON // character (:), and let value be that string. // If value starts with a U+0020 SPACE character, remove it from value. let valueStart = colonPosition + 1 if (line[valueStart] === SPACE) { ++valueStart } // TODO: Investigate if there is a more performant way to extract the // value // see: https://github.com/nodejs/undici/issues/2630 value = line.subarray(valueStart).toString('utf8') // Otherwise, the string is not empty but does not contain a U+003A COLON // character (:) } else { // Process the field using the steps described below, using the whole // line as the field name, and the empty string as the field value. field = line.toString('utf8') value = '' } // Modify the event with the field name and value. The value is also // decoded as UTF-8 switch (field) { case 'data': if (event[field] === undefined) { event[field] = value } else { event[field] += `\n${value}` } break case 'retry': if (isASCIINumber(value)) { event[field] = value } break case 'id': if (isValidLastEventId(value)) { event[field] = value } break case 'event': if (value.length > 0) { event[field] = value } break } } /** * @param {EventSourceStreamEvent} event */ processEvent (event) { if (event.retry && isASCIINumber(event.retry)) { this.state.reconnectionTime = parseInt(event.retry, 10) } if (event.id && isValidLastEventId(event.id)) { this.state.lastEventId = event.id } // only dispatch event, when data is provided if (event.data !== undefined) { this.push({ type: event.event || 'message', options: { data: event.data, lastEventId: this.state.lastEventId, origin: this.state.origin } }) } } clearEvent () { this.event = { data: undefined, event: undefined, id: undefined, retry: undefined } } } module.exports = { EventSourceStream } /***/ }), /***/ 1238: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { pipeline } = __nccwpck_require__(7075) const { fetching } = __nccwpck_require__(4398) const { makeRequest } = __nccwpck_require__(9967) const { webidl } = __nccwpck_require__(5893) const { EventSourceStream } = __nccwpck_require__(4031) const { parseMIMEType } = __nccwpck_require__(1900) const { createFastMessageEvent } = __nccwpck_require__(5188) const { isNetworkError } = __nccwpck_require__(9051) const { delay } = __nccwpck_require__(4811) const { kEnumerableProperty } = __nccwpck_require__(3440) const { environmentSettingsObject } = __nccwpck_require__(3168) let experimentalWarned = false /** * A reconnection time, in milliseconds. This must initially be an implementation-defined value, * probably in the region of a few seconds. * * In Comparison: * - Chrome uses 3000ms. * - Deno uses 5000ms. * * @type {3000} */ const defaultReconnectionTime = 3000 /** * The readyState attribute represents the state of the connection. * @enum * @readonly * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev */ /** * The connection has not yet been established, or it was closed and the user * agent is reconnecting. * @type {0} */ const CONNECTING = 0 /** * The user agent has an open connection and is dispatching events as it * receives them. * @type {1} */ const OPEN = 1 /** * The connection is not open, and the user agent is not trying to reconnect. * @type {2} */ const CLOSED = 2 /** * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin". * @type {'anonymous'} */ const ANONYMOUS = 'anonymous' /** * Requests for the element will have their mode set to "cors" and their credentials mode set to "include". * @type {'use-credentials'} */ const USE_CREDENTIALS = 'use-credentials' /** * The EventSource interface is used to receive server-sent events. It * connects to a server over HTTP and receives events in text/event-stream * format without closing the connection. * @extends {EventTarget} * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events * @api public */ class EventSource extends EventTarget { #events = { open: null, error: null, message: null } #url = null #withCredentials = false #readyState = CONNECTING #request = null #controller = null #dispatcher /** * @type {import('./eventsource-stream').eventSourceSettings} */ #state /** * Creates a new EventSource object. * @param {string} url * @param {EventSourceInit} [eventSourceInitDict] * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface */ constructor (url, eventSourceInitDict = {}) { // 1. Let ev be a new EventSource object. super() webidl.util.markAsUncloneable(this) const prefix = 'EventSource constructor' webidl.argumentLengthCheck(arguments, 1, prefix) if (!experimentalWarned) { experimentalWarned = true process.emitWarning('EventSource is experimental, expect them to change at any time.', { code: 'UNDICI-ES' }) } url = webidl.converters.USVString(url, prefix, 'url') eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict') this.#dispatcher = eventSourceInitDict.dispatcher this.#state = { lastEventId: '', reconnectionTime: defaultReconnectionTime } // 2. Let settings be ev's relevant settings object. // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object const settings = environmentSettingsObject let urlRecord try { // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings. urlRecord = new URL(url, settings.settingsObject.baseUrl) this.#state.origin = urlRecord.origin } catch (e) { // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException. throw new DOMException(e, 'SyntaxError') } // 5. Set ev's url to urlRecord. this.#url = urlRecord.href // 6. Let corsAttributeState be Anonymous. let corsAttributeState = ANONYMOUS // 7. If the value of eventSourceInitDict's withCredentials member is true, // then set corsAttributeState to Use Credentials and set ev's // withCredentials attribute to true. if (eventSourceInitDict.withCredentials) { corsAttributeState = USE_CREDENTIALS this.#withCredentials = true } // 8. Let request be the result of creating a potential-CORS request given // urlRecord, the empty string, and corsAttributeState. const initRequest = { redirect: 'follow', keepalive: true, // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes mode: 'cors', credentials: corsAttributeState === 'anonymous' ? 'same-origin' : 'omit', referrer: 'no-referrer' } // 9. Set request's client to settings. initRequest.client = environmentSettingsObject.settingsObject // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list. initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]] // 11. Set request's cache mode to "no-store". initRequest.cache = 'no-store' // 12. Set request's initiator type to "other". initRequest.initiator = 'other' initRequest.urlList = [new URL(this.#url)] // 13. Set ev's request to request. this.#request = makeRequest(initRequest) this.#connect() } /** * Returns the state of this EventSource object's connection. It can have the * values described below. * @returns {0|1|2} * @readonly */ get readyState () { return this.#readyState } /** * Returns the URL providing the event stream. * @readonly * @returns {string} */ get url () { return this.#url } /** * Returns a boolean indicating whether the EventSource object was * instantiated with CORS credentials set (true), or not (false, the default). */ get withCredentials () { return this.#withCredentials } #connect () { if (this.#readyState === CLOSED) return this.#readyState = CONNECTING const fetchParams = { request: this.#request, dispatcher: this.#dispatcher } // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection. const processEventSourceEndOfBody = (response) => { if (isNetworkError(response)) { this.dispatchEvent(new Event('error')) this.close() } this.#reconnect() } // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody... fetchParams.processResponseEndOfBody = processEventSourceEndOfBody // and processResponse set to the following steps given response res: fetchParams.processResponse = (response) => { // 1. If res is an aborted network error, then fail the connection. if (isNetworkError(response)) { // 1. When a user agent is to fail the connection, the user agent // must queue a task which, if the readyState attribute is set to a // value other than CLOSED, sets the readyState attribute to CLOSED // and fires an event named error at the EventSource object. Once the // user agent has failed the connection, it does not attempt to // reconnect. if (response.aborted) { this.close() this.dispatchEvent(new Event('error')) return // 2. Otherwise, if res is a network error, then reestablish the // connection, unless the user agent knows that to be futile, in // which case the user agent may fail the connection. } else { this.#reconnect() return } } // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` // is not `text/event-stream`, then fail the connection. const contentType = response.headersList.get('content-type', true) const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure' const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream' if ( response.status !== 200 || contentTypeValid === false ) { this.close() this.dispatchEvent(new Event('error')) return } // 4. Otherwise, announce the connection and interpret res's body // line by line. // When a user agent is to announce the connection, the user agent // must queue a task which, if the readyState attribute is set to a // value other than CLOSED, sets the readyState attribute to OPEN // and fires an event named open at the EventSource object. // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model this.#readyState = OPEN this.dispatchEvent(new Event('open')) // If redirected to a different origin, set the origin to the new origin. this.#state.origin = response.urlList[response.urlList.length - 1].origin const eventSourceStream = new EventSourceStream({ eventSourceSettings: this.#state, push: (event) => { this.dispatchEvent(createFastMessageEvent( event.type, event.options )) } }) pipeline(response.body.stream, eventSourceStream, (error) => { if ( error?.aborted === false ) { this.close() this.dispatchEvent(new Event('error')) } }) } this.#controller = fetching(fetchParams) } /** * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model * @returns {Promise} */ async #reconnect () { // When a user agent is to reestablish the connection, the user agent must // run the following steps. These steps are run in parallel, not as part of // a task. (The tasks that it queues, of course, are run like normal tasks // and not themselves in parallel.) // 1. Queue a task to run the following steps: // 1. If the readyState attribute is set to CLOSED, abort the task. if (this.#readyState === CLOSED) return // 2. Set the readyState attribute to CONNECTING. this.#readyState = CONNECTING // 3. Fire an event named error at the EventSource object. this.dispatchEvent(new Event('error')) // 2. Wait a delay equal to the reconnection time of the event source. await delay(this.#state.reconnectionTime) // 5. Queue a task to run the following steps: // 1. If the EventSource object's readyState attribute is not set to // CONNECTING, then return. if (this.#readyState !== CONNECTING) return // 2. Let request be the EventSource object's request. // 3. If the EventSource object's last event ID string is not the empty // string, then: // 1. Let lastEventIDValue be the EventSource object's last event ID // string, encoded as UTF-8. // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header // list. if (this.#state.lastEventId.length) { this.#request.headersList.set('last-event-id', this.#state.lastEventId, true) } // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section. this.#connect() } /** * Closes the connection, if any, and sets the readyState attribute to * CLOSED. */ close () { webidl.brandCheck(this, EventSource) if (this.#readyState === CLOSED) return this.#readyState = CLOSED this.#controller.abort() this.#request = null } get onopen () { return this.#events.open } set onopen (fn) { if (this.#events.open) { this.removeEventListener('open', this.#events.open) } if (typeof fn === 'function') { this.#events.open = fn this.addEventListener('open', fn) } else { this.#events.open = null } } get onmessage () { return this.#events.message } set onmessage (fn) { if (this.#events.message) { this.removeEventListener('message', this.#events.message) } if (typeof fn === 'function') { this.#events.message = fn this.addEventListener('message', fn) } else { this.#events.message = null } } get onerror () { return this.#events.error } set onerror (fn) { if (this.#events.error) { this.removeEventListener('error', this.#events.error) } if (typeof fn === 'function') { this.#events.error = fn this.addEventListener('error', fn) } else { this.#events.error = null } } } const constantsPropertyDescriptors = { CONNECTING: { __proto__: null, configurable: false, enumerable: true, value: CONNECTING, writable: false }, OPEN: { __proto__: null, configurable: false, enumerable: true, value: OPEN, writable: false }, CLOSED: { __proto__: null, configurable: false, enumerable: true, value: CLOSED, writable: false } } Object.defineProperties(EventSource, constantsPropertyDescriptors) Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors) Object.defineProperties(EventSource.prototype, { close: kEnumerableProperty, onerror: kEnumerableProperty, onmessage: kEnumerableProperty, onopen: kEnumerableProperty, readyState: kEnumerableProperty, url: kEnumerableProperty, withCredentials: kEnumerableProperty }) webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ { key: 'withCredentials', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'dispatcher', // undici only converter: webidl.converters.any } ]) module.exports = { EventSource, defaultReconnectionTime } /***/ }), /***/ 4811: /***/ ((module) => { "use strict"; /** * Checks if the given value is a valid LastEventId. * @param {string} value * @returns {boolean} */ function isValidLastEventId (value) { // LastEventId should not contain U+0000 NULL return value.indexOf('\u0000') === -1 } /** * Checks if the given value is a base 10 digit. * @param {string} value * @returns {boolean} */ function isASCIINumber (value) { if (value.length === 0) return false for (let i = 0; i < value.length; i++) { if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false } return true } // https://github.com/nodejs/undici/issues/2664 function delay (ms) { return new Promise((resolve) => { setTimeout(resolve, ms).unref() }) } module.exports = { isValidLastEventId, isASCIINumber, delay } /***/ }), /***/ 4492: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(3440) const { ReadableStreamFrom, isBlobLike, isReadableStreamLike, readableStreamClose, createDeferredPromise, fullyReadBody, extractMimeType, utf8DecodeBytes } = __nccwpck_require__(3168) const { FormData } = __nccwpck_require__(5910) const { kState } = __nccwpck_require__(3627) const { webidl } = __nccwpck_require__(5893) const { Blob } = __nccwpck_require__(4573) const assert = __nccwpck_require__(4589) const { isErrored, isDisturbed } = __nccwpck_require__(7075) const { isArrayBuffer } = __nccwpck_require__(3429) const { serializeAMimeType } = __nccwpck_require__(1900) const { multipartFormDataParser } = __nccwpck_require__(116) let random try { const crypto = __nccwpck_require__(7598) random = (max) => crypto.randomInt(0, max) } catch { random = (max) => Math.floor(Math.random(max)) } const textEncoder = new TextEncoder() function noop () {} const hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf('v18') !== 0 let streamRegistry if (hasFinalizationRegistry) { streamRegistry = new FinalizationRegistry((weakRef) => { const stream = weakRef.deref() if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) { stream.cancel('Response object has been garbage collected').catch(noop) } }) } // https://fetch.spec.whatwg.org/#concept-bodyinit-extract function extractBody (object, keepalive = false) { // 1. Let stream be null. let stream = null // 2. If object is a ReadableStream object, then set stream to object. if (object instanceof ReadableStream) { stream = object } else if (isBlobLike(object)) { // 3. Otherwise, if object is a Blob object, set stream to the // result of running object’s get stream. stream = object.stream() } else { // 4. Otherwise, set stream to a new ReadableStream object, and set // up stream with byte reading support. stream = new ReadableStream({ async pull (controller) { const buffer = typeof source === 'string' ? textEncoder.encode(source) : source if (buffer.byteLength) { controller.enqueue(buffer) } queueMicrotask(() => readableStreamClose(controller)) }, start () {}, type: 'bytes' }) } // 5. Assert: stream is a ReadableStream object. assert(isReadableStreamLike(stream)) // 6. Let action be null. let action = null // 7. Let source be null. let source = null // 8. Let length be null. let length = null // 9. Let type be null. let type = null // 10. Switch on object: if (typeof object === 'string') { // Set source to the UTF-8 encoding of object. // Note: setting source to a Uint8Array here breaks some mocking assumptions. source = object // Set type to `text/plain;charset=UTF-8`. type = 'text/plain;charset=UTF-8' } else if (object instanceof URLSearchParams) { // URLSearchParams // spec says to run application/x-www-form-urlencoded on body.list // this is implemented in Node.js as apart of an URLSearchParams instance toString method // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. source = object.toString() // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. type = 'application/x-www-form-urlencoded;charset=UTF-8' } else if (isArrayBuffer(object)) { // BufferSource/ArrayBuffer // Set source to a copy of the bytes held by object. source = new Uint8Array(object.slice()) } else if (ArrayBuffer.isView(object)) { // BufferSource/ArrayBufferView // Set source to a copy of the bytes held by object. source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) } else if (util.isFormDataLike(object)) { const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` const prefix = `--${boundary}\r\nContent-Disposition: form-data` /*! formdata-polyfill. MIT License. Jimmy Wärting */ const escape = (str) => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') // Set action to this step: run the multipart/form-data // encoding algorithm, with object’s entry list and UTF-8. // - This ensures that the body is immutable and can't be changed afterwords // - That the content-length is calculated in advance. // - And that all parts are pre-encoded and ready to be sent. const blobParts = [] const rn = new Uint8Array([13, 10]) // '\r\n' length = 0 let hasUnknownSizeValue = false for (const [name, value] of object) { if (typeof value === 'string') { const chunk = textEncoder.encode(prefix + `; name="${escape(normalizeLinefeeds(name))}"` + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) blobParts.push(chunk) length += chunk.byteLength } else { const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + `Content-Type: ${ value.type || 'application/octet-stream' }\r\n\r\n`) blobParts.push(chunk, value, rn) if (typeof value.size === 'number') { length += chunk.byteLength + value.size + rn.byteLength } else { hasUnknownSizeValue = true } } } // CRLF is appended to the body to function with legacy servers and match other implementations. // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030 // https://github.com/form-data/form-data/issues/63 const chunk = textEncoder.encode(`--${boundary}--\r\n`) blobParts.push(chunk) length += chunk.byteLength if (hasUnknownSizeValue) { length = null } // Set source to object. source = object action = async function * () { for (const part of blobParts) { if (part.stream) { yield * part.stream() } else { yield part } } } // Set type to `multipart/form-data; boundary=`, // followed by the multipart/form-data boundary string generated // by the multipart/form-data encoding algorithm. type = `multipart/form-data; boundary=${boundary}` } else if (isBlobLike(object)) { // Blob // Set source to object. source = object // Set length to object’s size. length = object.size // If object’s type attribute is not the empty byte sequence, set // type to its value. if (object.type) { type = object.type } } else if (typeof object[Symbol.asyncIterator] === 'function') { // If keepalive is true, then throw a TypeError. if (keepalive) { throw new TypeError('keepalive') } // If object is disturbed or locked, then throw a TypeError. if (util.isDisturbed(object) || object.locked) { throw new TypeError( 'Response body object should not be disturbed or locked' ) } stream = object instanceof ReadableStream ? object : ReadableStreamFrom(object) } // 11. If source is a byte sequence, then set action to a // step that returns source and length to source’s length. if (typeof source === 'string' || util.isBuffer(source)) { length = Buffer.byteLength(source) } // 12. If action is non-null, then run these steps in in parallel: if (action != null) { // Run action. let iterator stream = new ReadableStream({ async start () { iterator = action(object)[Symbol.asyncIterator]() }, async pull (controller) { const { value, done } = await iterator.next() if (done) { // When running action is done, close stream. queueMicrotask(() => { controller.close() controller.byobRequest?.respond(0) }) } else { // Whenever one or more bytes are available and stream is not errored, // enqueue a Uint8Array wrapping an ArrayBuffer containing the available // bytes into stream. if (!isErrored(stream)) { const buffer = new Uint8Array(value) if (buffer.byteLength) { controller.enqueue(buffer) } } } return controller.desiredSize > 0 }, async cancel (reason) { await iterator.return() }, type: 'bytes' }) } // 13. Let body be a body whose stream is stream, source is source, // and length is length. const body = { stream, source, length } // 14. Return (body, type). return [body, type] } // https://fetch.spec.whatwg.org/#bodyinit-safely-extract function safelyExtractBody (object, keepalive = false) { // To safely extract a body and a `Content-Type` value from // a byte sequence or BodyInit object object, run these steps: // 1. If object is a ReadableStream object, then: if (object instanceof ReadableStream) { // Assert: object is neither disturbed nor locked. // istanbul ignore next assert(!util.isDisturbed(object), 'The body has already been consumed.') // istanbul ignore next assert(!object.locked, 'The stream is locked.') } // 2. Return the results of extracting object. return extractBody(object, keepalive) } function cloneBody (instance, body) { // To clone a body body, run these steps: // https://fetch.spec.whatwg.org/#concept-body-clone // 1. Let « out1, out2 » be the result of teeing body’s stream. const [out1, out2] = body.stream.tee() // 2. Set body’s stream to out1. body.stream = out1 // 3. Return a body whose stream is out2 and other members are copied from body. return { stream: out2, length: body.length, source: body.source } } function throwIfAborted (state) { if (state.aborted) { throw new DOMException('The operation was aborted.', 'AbortError') } } function bodyMixinMethods (instance) { const methods = { blob () { // The blob() method steps are to return the result of // running consume body with this and the following step // given a byte sequence bytes: return a Blob whose // contents are bytes and whose type attribute is this’s // MIME type. return consumeBody(this, (bytes) => { let mimeType = bodyMimeType(this) if (mimeType === null) { mimeType = '' } else if (mimeType) { mimeType = serializeAMimeType(mimeType) } // Return a Blob whose contents are bytes and type attribute // is mimeType. return new Blob([bytes], { type: mimeType }) }, instance) }, arrayBuffer () { // The arrayBuffer() method steps are to return the result // of running consume body with this and the following step // given a byte sequence bytes: return a new ArrayBuffer // whose contents are bytes. return consumeBody(this, (bytes) => { return new Uint8Array(bytes).buffer }, instance) }, text () { // The text() method steps are to return the result of running // consume body with this and UTF-8 decode. return consumeBody(this, utf8DecodeBytes, instance) }, json () { // The json() method steps are to return the result of running // consume body with this and parse JSON from bytes. return consumeBody(this, parseJSONFromBytes, instance) }, formData () { // The formData() method steps are to return the result of running // consume body with this and the following step given a byte sequence bytes: return consumeBody(this, (value) => { // 1. Let mimeType be the result of get the MIME type with this. const mimeType = bodyMimeType(this) // 2. If mimeType is non-null, then switch on mimeType’s essence and run // the corresponding steps: if (mimeType !== null) { switch (mimeType.essence) { case 'multipart/form-data': { // 1. ... [long step] const parsed = multipartFormDataParser(value, mimeType) // 2. If that fails for some reason, then throw a TypeError. if (parsed === 'failure') { throw new TypeError('Failed to parse body as FormData.') } // 3. Return a new FormData object, appending each entry, // resulting from the parsing operation, to its entry list. const fd = new FormData() fd[kState] = parsed return fd } case 'application/x-www-form-urlencoded': { // 1. Let entries be the result of parsing bytes. const entries = new URLSearchParams(value.toString()) // 2. If entries is failure, then throw a TypeError. // 3. Return a new FormData object whose entry list is entries. const fd = new FormData() for (const [name, value] of entries) { fd.append(name, value) } return fd } } } // 3. Throw a TypeError. throw new TypeError( 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".' ) }, instance) }, bytes () { // The bytes() method steps are to return the result of running consume body // with this and the following step given a byte sequence bytes: return the // result of creating a Uint8Array from bytes in this’s relevant realm. return consumeBody(this, (bytes) => { return new Uint8Array(bytes) }, instance) } } return methods } function mixinBody (prototype) { Object.assign(prototype.prototype, bodyMixinMethods(prototype)) } /** * @see https://fetch.spec.whatwg.org/#concept-body-consume-body * @param {Response|Request} object * @param {(value: unknown) => unknown} convertBytesToJSValue * @param {Response|Request} instance */ async function consumeBody (object, convertBytesToJSValue, instance) { webidl.brandCheck(object, instance) // 1. If object is unusable, then return a promise rejected // with a TypeError. if (bodyUnusable(object)) { throw new TypeError('Body is unusable: Body has already been read') } throwIfAborted(object[kState]) // 2. Let promise be a new promise. const promise = createDeferredPromise() // 3. Let errorSteps given error be to reject promise with error. const errorSteps = (error) => promise.reject(error) // 4. Let successSteps given a byte sequence data be to resolve // promise with the result of running convertBytesToJSValue // with data. If that threw an exception, then run errorSteps // with that exception. const successSteps = (data) => { try { promise.resolve(convertBytesToJSValue(data)) } catch (e) { errorSteps(e) } } // 5. If object’s body is null, then run successSteps with an // empty byte sequence. if (object[kState].body == null) { successSteps(Buffer.allocUnsafe(0)) return promise.promise } // 6. Otherwise, fully read object’s body given successSteps, // errorSteps, and object’s relevant global object. await fullyReadBody(object[kState].body, successSteps, errorSteps) // 7. Return promise. return promise.promise } // https://fetch.spec.whatwg.org/#body-unusable function bodyUnusable (object) { const body = object[kState].body // An object including the Body interface mixin is // said to be unusable if its body is non-null and // its body’s stream is disturbed or locked. return body != null && (body.stream.locked || util.isDisturbed(body.stream)) } /** * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value * @param {Uint8Array} bytes */ function parseJSONFromBytes (bytes) { return JSON.parse(utf8DecodeBytes(bytes)) } /** * @see https://fetch.spec.whatwg.org/#concept-body-mime-type * @param {import('./response').Response|import('./request').Request} requestOrResponse */ function bodyMimeType (requestOrResponse) { // 1. Let headers be null. // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list. // 3. Otherwise, set headers to requestOrResponse’s response’s header list. /** @type {import('./headers').HeadersList} */ const headers = requestOrResponse[kState].headersList // 4. Let mimeType be the result of extracting a MIME type from headers. const mimeType = extractMimeType(headers) // 5. If mimeType is failure, then return null. if (mimeType === 'failure') { return null } // 6. Return mimeType. return mimeType } module.exports = { extractBody, safelyExtractBody, cloneBody, mixinBody, streamRegistry, hasFinalizationRegistry, bodyUnusable } /***/ }), /***/ 4495: /***/ ((module) => { "use strict"; const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST']) const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304]) const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308]) const redirectStatusSet = new Set(redirectStatus) /** * @see https://fetch.spec.whatwg.org/#block-bad-port */ const badPorts = /** @type {const} */ ([ '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679', '6697', '10080' ]) const badPortsSet = new Set(badPorts) /** * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies */ const referrerPolicy = /** @type {const} */ ([ '', 'no-referrer', 'no-referrer-when-downgrade', 'same-origin', 'origin', 'strict-origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin', 'unsafe-url' ]) const referrerPolicySet = new Set(referrerPolicy) const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error']) const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE']) const safeMethodsSet = new Set(safeMethods) const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors']) const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include']) const requestCache = /** @type {const} */ ([ 'default', 'no-store', 'reload', 'no-cache', 'force-cache', 'only-if-cached' ]) /** * @see https://fetch.spec.whatwg.org/#request-body-header-name */ const requestBodyHeader = /** @type {const} */ ([ 'content-encoding', 'content-language', 'content-location', 'content-type', // See https://github.com/nodejs/undici/issues/2021 // 'Content-Length' is a forbidden header name, which is typically // removed in the Headers implementation. However, undici doesn't // filter out headers, so we add it here. 'content-length' ]) /** * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex */ const requestDuplex = /** @type {const} */ ([ 'half' ]) /** * @see http://fetch.spec.whatwg.org/#forbidden-method */ const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK']) const forbiddenMethodsSet = new Set(forbiddenMethods) const subresource = /** @type {const} */ ([ 'audio', 'audioworklet', 'font', 'image', 'manifest', 'paintworklet', 'script', 'style', 'track', 'video', 'xslt', '' ]) const subresourceSet = new Set(subresource) module.exports = { subresource, forbiddenMethods, requestBodyHeader, referrerPolicy, requestRedirect, requestMode, requestCredentials, requestCache, redirectStatus, corsSafeListedMethods, nullBodyStatus, safeMethods, badPorts, requestDuplex, subresourceSet, badPortsSet, redirectStatusSet, corsSafeListedMethodsSet, safeMethodsSet, forbiddenMethodsSet, referrerPolicySet } /***/ }), /***/ 1900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) const encoder = new TextEncoder() /** * @see https://mimesniff.spec.whatwg.org/#http-token-code-point */ const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/ const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/ // eslint-disable-line const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line /** * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point */ const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/ // eslint-disable-line // https://fetch.spec.whatwg.org/#data-url-processor /** @param {URL} dataURL */ function dataURLProcessor (dataURL) { // 1. Assert: dataURL’s scheme is "data". assert(dataURL.protocol === 'data:') // 2. Let input be the result of running the URL // serializer on dataURL with exclude fragment // set to true. let input = URLSerializer(dataURL, true) // 3. Remove the leading "data:" string from input. input = input.slice(5) // 4. Let position point at the start of input. const position = { position: 0 } // 5. Let mimeType be the result of collecting a // sequence of code points that are not equal // to U+002C (,), given position. let mimeType = collectASequenceOfCodePointsFast( ',', input, position ) // 6. Strip leading and trailing ASCII whitespace // from mimeType. // Undici implementation note: we need to store the // length because if the mimetype has spaces removed, // the wrong amount will be sliced from the input in // step #9 const mimeTypeLength = mimeType.length mimeType = removeASCIIWhitespace(mimeType, true, true) // 7. If position is past the end of input, then // return failure if (position.position >= input.length) { return 'failure' } // 8. Advance position by 1. position.position++ // 9. Let encodedBody be the remainder of input. const encodedBody = input.slice(mimeTypeLength + 1) // 10. Let body be the percent-decoding of encodedBody. let body = stringPercentDecode(encodedBody) // 11. If mimeType ends with U+003B (;), followed by // zero or more U+0020 SPACE, followed by an ASCII // case-insensitive match for "base64", then: if (/;(\u0020){0,}base64$/i.test(mimeType)) { // 1. Let stringBody be the isomorphic decode of body. const stringBody = isomorphicDecode(body) // 2. Set body to the forgiving-base64 decode of // stringBody. body = forgivingBase64(stringBody) // 3. If body is failure, then return failure. if (body === 'failure') { return 'failure' } // 4. Remove the last 6 code points from mimeType. mimeType = mimeType.slice(0, -6) // 5. Remove trailing U+0020 SPACE code points from mimeType, // if any. mimeType = mimeType.replace(/(\u0020)+$/, '') // 6. Remove the last U+003B (;) code point from mimeType. mimeType = mimeType.slice(0, -1) } // 12. If mimeType starts with U+003B (;), then prepend // "text/plain" to mimeType. if (mimeType.startsWith(';')) { mimeType = 'text/plain' + mimeType } // 13. Let mimeTypeRecord be the result of parsing // mimeType. let mimeTypeRecord = parseMIMEType(mimeType) // 14. If mimeTypeRecord is failure, then set // mimeTypeRecord to text/plain;charset=US-ASCII. if (mimeTypeRecord === 'failure') { mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') } // 15. Return a new data: URL struct whose MIME // type is mimeTypeRecord and body is body. // https://fetch.spec.whatwg.org/#data-url-struct return { mimeType: mimeTypeRecord, body } } // https://url.spec.whatwg.org/#concept-url-serializer /** * @param {URL} url * @param {boolean} excludeFragment */ function URLSerializer (url, excludeFragment = false) { if (!excludeFragment) { return url.href } const href = url.href const hashLength = url.hash.length const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength) if (!hashLength && href.endsWith('#')) { return serialized.slice(0, -1) } return serialized } // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points /** * @param {(char: string) => boolean} condition * @param {string} input * @param {{ position: number }} position */ function collectASequenceOfCodePoints (condition, input, position) { // 1. Let result be the empty string. let result = '' // 2. While position doesn’t point past the end of input and the // code point at position within input meets the condition condition: while (position.position < input.length && condition(input[position.position])) { // 1. Append that code point to the end of result. result += input[position.position] // 2. Advance position by 1. position.position++ } // 3. Return result. return result } /** * A faster collectASequenceOfCodePoints that only works when comparing a single character. * @param {string} char * @param {string} input * @param {{ position: number }} position */ function collectASequenceOfCodePointsFast (char, input, position) { const idx = input.indexOf(char, position.position) const start = position.position if (idx === -1) { position.position = input.length return input.slice(start) } position.position = idx return input.slice(start, position.position) } // https://url.spec.whatwg.org/#string-percent-decode /** @param {string} input */ function stringPercentDecode (input) { // 1. Let bytes be the UTF-8 encoding of input. const bytes = encoder.encode(input) // 2. Return the percent-decoding of bytes. return percentDecode(bytes) } /** * @param {number} byte */ function isHexCharByte (byte) { // 0-9 A-F a-f return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66) } /** * @param {number} byte */ function hexByteToNumber (byte) { return ( // 0-9 byte >= 0x30 && byte <= 0x39 ? (byte - 48) // Convert to uppercase // ((byte & 0xDF) - 65) + 10 : ((byte & 0xDF) - 55) ) } // https://url.spec.whatwg.org/#percent-decode /** @param {Uint8Array} input */ function percentDecode (input) { const length = input.length // 1. Let output be an empty byte sequence. /** @type {Uint8Array} */ const output = new Uint8Array(length) let j = 0 // 2. For each byte byte in input: for (let i = 0; i < length; ++i) { const byte = input[i] // 1. If byte is not 0x25 (%), then append byte to output. if (byte !== 0x25) { output[j++] = byte // 2. Otherwise, if byte is 0x25 (%) and the next two bytes // after byte in input are not in the ranges // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), // and 0x61 (a) to 0x66 (f), all inclusive, append byte // to output. } else if ( byte === 0x25 && !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2])) ) { output[j++] = 0x25 // 3. Otherwise: } else { // 1. Let bytePoint be the two bytes after byte in input, // decoded, and then interpreted as hexadecimal number. // 2. Append a byte whose value is bytePoint to output. output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2]) // 3. Skip the next two bytes in input. i += 2 } } // 3. Return output. return length === j ? output : output.subarray(0, j) } // https://mimesniff.spec.whatwg.org/#parse-a-mime-type /** @param {string} input */ function parseMIMEType (input) { // 1. Remove any leading and trailing HTTP whitespace // from input. input = removeHTTPWhitespace(input, true, true) // 2. Let position be a position variable for input, // initially pointing at the start of input. const position = { position: 0 } // 3. Let type be the result of collecting a sequence // of code points that are not U+002F (/) from // input, given position. const type = collectASequenceOfCodePointsFast( '/', input, position ) // 4. If type is the empty string or does not solely // contain HTTP token code points, then return failure. // https://mimesniff.spec.whatwg.org/#http-token-code-point if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { return 'failure' } // 5. If position is past the end of input, then return // failure if (position.position > input.length) { return 'failure' } // 6. Advance position by 1. (This skips past U+002F (/).) position.position++ // 7. Let subtype be the result of collecting a sequence of // code points that are not U+003B (;) from input, given // position. let subtype = collectASequenceOfCodePointsFast( ';', input, position ) // 8. Remove any trailing HTTP whitespace from subtype. subtype = removeHTTPWhitespace(subtype, false, true) // 9. If subtype is the empty string or does not solely // contain HTTP token code points, then return failure. if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { return 'failure' } const typeLowercase = type.toLowerCase() const subtypeLowercase = subtype.toLowerCase() // 10. Let mimeType be a new MIME type record whose type // is type, in ASCII lowercase, and subtype is subtype, // in ASCII lowercase. // https://mimesniff.spec.whatwg.org/#mime-type const mimeType = { type: typeLowercase, subtype: subtypeLowercase, /** @type {Map} */ parameters: new Map(), // https://mimesniff.spec.whatwg.org/#mime-type-essence essence: `${typeLowercase}/${subtypeLowercase}` } // 11. While position is not past the end of input: while (position.position < input.length) { // 1. Advance position by 1. (This skips past U+003B (;).) position.position++ // 2. Collect a sequence of code points that are HTTP // whitespace from input given position. collectASequenceOfCodePoints( // https://fetch.spec.whatwg.org/#http-whitespace char => HTTP_WHITESPACE_REGEX.test(char), input, position ) // 3. Let parameterName be the result of collecting a // sequence of code points that are not U+003B (;) // or U+003D (=) from input, given position. let parameterName = collectASequenceOfCodePoints( (char) => char !== ';' && char !== '=', input, position ) // 4. Set parameterName to parameterName, in ASCII // lowercase. parameterName = parameterName.toLowerCase() // 5. If position is not past the end of input, then: if (position.position < input.length) { // 1. If the code point at position within input is // U+003B (;), then continue. if (input[position.position] === ';') { continue } // 2. Advance position by 1. (This skips past U+003D (=).) position.position++ } // 6. If position is past the end of input, then break. if (position.position > input.length) { break } // 7. Let parameterValue be null. let parameterValue = null // 8. If the code point at position within input is // U+0022 ("), then: if (input[position.position] === '"') { // 1. Set parameterValue to the result of collecting // an HTTP quoted string from input, given position // and the extract-value flag. parameterValue = collectAnHTTPQuotedString(input, position, true) // 2. Collect a sequence of code points that are not // U+003B (;) from input, given position. collectASequenceOfCodePointsFast( ';', input, position ) // 9. Otherwise: } else { // 1. Set parameterValue to the result of collecting // a sequence of code points that are not U+003B (;) // from input, given position. parameterValue = collectASequenceOfCodePointsFast( ';', input, position ) // 2. Remove any trailing HTTP whitespace from parameterValue. parameterValue = removeHTTPWhitespace(parameterValue, false, true) // 3. If parameterValue is the empty string, then continue. if (parameterValue.length === 0) { continue } } // 10. If all of the following are true // - parameterName is not the empty string // - parameterName solely contains HTTP token code points // - parameterValue solely contains HTTP quoted-string token code points // - mimeType’s parameters[parameterName] does not exist // then set mimeType’s parameters[parameterName] to parameterValue. if ( parameterName.length !== 0 && HTTP_TOKEN_CODEPOINTS.test(parameterName) && (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && !mimeType.parameters.has(parameterName) ) { mimeType.parameters.set(parameterName, parameterValue) } } // 12. Return mimeType. return mimeType } // https://infra.spec.whatwg.org/#forgiving-base64-decode /** @param {string} data */ function forgivingBase64 (data) { // 1. Remove all ASCII whitespace from data. data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line let dataLength = data.length // 2. If data’s code point length divides by 4 leaving // no remainder, then: if (dataLength % 4 === 0) { // 1. If data ends with one or two U+003D (=) code points, // then remove them from data. if (data.charCodeAt(dataLength - 1) === 0x003D) { --dataLength if (data.charCodeAt(dataLength - 1) === 0x003D) { --dataLength } } } // 3. If data’s code point length divides by 4 leaving // a remainder of 1, then return failure. if (dataLength % 4 === 1) { return 'failure' } // 4. If data contains a code point that is not one of // U+002B (+) // U+002F (/) // ASCII alphanumeric // then return failure. if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) { return 'failure' } const buffer = Buffer.from(data, 'base64') return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) } // https://fetch.spec.whatwg.org/#collect-an-http-quoted-string // tests: https://fetch.spec.whatwg.org/#example-http-quoted-string /** * @param {string} input * @param {{ position: number }} position * @param {boolean?} extractValue */ function collectAnHTTPQuotedString (input, position, extractValue) { // 1. Let positionStart be position. const positionStart = position.position // 2. Let value be the empty string. let value = '' // 3. Assert: the code point at position within input // is U+0022 ("). assert(input[position.position] === '"') // 4. Advance position by 1. position.position++ // 5. While true: while (true) { // 1. Append the result of collecting a sequence of code points // that are not U+0022 (") or U+005C (\) from input, given // position, to value. value += collectASequenceOfCodePoints( (char) => char !== '"' && char !== '\\', input, position ) // 2. If position is past the end of input, then break. if (position.position >= input.length) { break } // 3. Let quoteOrBackslash be the code point at position within // input. const quoteOrBackslash = input[position.position] // 4. Advance position by 1. position.position++ // 5. If quoteOrBackslash is U+005C (\), then: if (quoteOrBackslash === '\\') { // 1. If position is past the end of input, then append // U+005C (\) to value and break. if (position.position >= input.length) { value += '\\' break } // 2. Append the code point at position within input to value. value += input[position.position] // 3. Advance position by 1. position.position++ // 6. Otherwise: } else { // 1. Assert: quoteOrBackslash is U+0022 ("). assert(quoteOrBackslash === '"') // 2. Break. break } } // 6. If the extract-value flag is set, then return value. if (extractValue) { return value } // 7. Return the code points from positionStart to position, // inclusive, within input. return input.slice(positionStart, position.position) } /** * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type */ function serializeAMimeType (mimeType) { assert(mimeType !== 'failure') const { parameters, essence } = mimeType // 1. Let serialization be the concatenation of mimeType’s // type, U+002F (/), and mimeType’s subtype. let serialization = essence // 2. For each name → value of mimeType’s parameters: for (let [name, value] of parameters.entries()) { // 1. Append U+003B (;) to serialization. serialization += ';' // 2. Append name to serialization. serialization += name // 3. Append U+003D (=) to serialization. serialization += '=' // 4. If value does not solely contain HTTP token code // points or value is the empty string, then: if (!HTTP_TOKEN_CODEPOINTS.test(value)) { // 1. Precede each occurrence of U+0022 (") or // U+005C (\) in value with U+005C (\). value = value.replace(/(\\|")/g, '\\$1') // 2. Prepend U+0022 (") to value. value = '"' + value // 3. Append U+0022 (") to value. value += '"' } // 5. Append value to serialization. serialization += value } // 3. Return serialization. return serialization } /** * @see https://fetch.spec.whatwg.org/#http-whitespace * @param {number} char */ function isHTTPWhiteSpace (char) { // "\r\n\t " return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020 } /** * @see https://fetch.spec.whatwg.org/#http-whitespace * @param {string} str * @param {boolean} [leading=true] * @param {boolean} [trailing=true] */ function removeHTTPWhitespace (str, leading = true, trailing = true) { return removeChars(str, leading, trailing, isHTTPWhiteSpace) } /** * @see https://infra.spec.whatwg.org/#ascii-whitespace * @param {number} char */ function isASCIIWhitespace (char) { // "\r\n\t\f " return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020 } /** * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace * @param {string} str * @param {boolean} [leading=true] * @param {boolean} [trailing=true] */ function removeASCIIWhitespace (str, leading = true, trailing = true) { return removeChars(str, leading, trailing, isASCIIWhitespace) } /** * @param {string} str * @param {boolean} leading * @param {boolean} trailing * @param {(charCode: number) => boolean} predicate * @returns */ function removeChars (str, leading, trailing, predicate) { let lead = 0 let trail = str.length - 1 if (leading) { while (lead < str.length && predicate(str.charCodeAt(lead))) lead++ } if (trailing) { while (trail > 0 && predicate(str.charCodeAt(trail))) trail-- } return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1) } /** * @see https://infra.spec.whatwg.org/#isomorphic-decode * @param {Uint8Array} input * @returns {string} */ function isomorphicDecode (input) { // 1. To isomorphic decode a byte sequence input, return a string whose code point // length is equal to input’s length and whose code points have the same values // as the values of input’s bytes, in the same order. const length = input.length if ((2 << 15) - 1 > length) { return String.fromCharCode.apply(null, input) } let result = ''; let i = 0 let addition = (2 << 15) - 1 while (i < length) { if (i + addition > length) { addition = length - i } result += String.fromCharCode.apply(null, input.subarray(i, i += addition)) } return result } /** * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type * @param {Exclude, 'failure'>} mimeType */ function minimizeSupportedMimeType (mimeType) { switch (mimeType.essence) { case 'application/ecmascript': case 'application/javascript': case 'application/x-ecmascript': case 'application/x-javascript': case 'text/ecmascript': case 'text/javascript': case 'text/javascript1.0': case 'text/javascript1.1': case 'text/javascript1.2': case 'text/javascript1.3': case 'text/javascript1.4': case 'text/javascript1.5': case 'text/jscript': case 'text/livescript': case 'text/x-ecmascript': case 'text/x-javascript': // 1. If mimeType is a JavaScript MIME type, then return "text/javascript". return 'text/javascript' case 'application/json': case 'text/json': // 2. If mimeType is a JSON MIME type, then return "application/json". return 'application/json' case 'image/svg+xml': // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml". return 'image/svg+xml' case 'text/xml': case 'application/xml': // 4. If mimeType is an XML MIME type, then return "application/xml". return 'application/xml' } // 2. If mimeType is a JSON MIME type, then return "application/json". if (mimeType.subtype.endsWith('+json')) { return 'application/json' } // 4. If mimeType is an XML MIME type, then return "application/xml". if (mimeType.subtype.endsWith('+xml')) { return 'application/xml' } // 5. If mimeType is supported by the user agent, then return mimeType’s essence. // Technically, node doesn't support any mimetypes. // 6. Return the empty string. return '' } module.exports = { dataURLProcessor, URLSerializer, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, stringPercentDecode, parseMIMEType, collectAnHTTPQuotedString, serializeAMimeType, removeChars, removeHTTPWhitespace, minimizeSupportedMimeType, HTTP_TOKEN_CODEPOINTS, isomorphicDecode } /***/ }), /***/ 6653: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kConnected, kSize } = __nccwpck_require__(6443) class CompatWeakRef { constructor (value) { this.value = value } deref () { return this.value[kConnected] === 0 && this.value[kSize] === 0 ? undefined : this.value } } class CompatFinalizer { constructor (finalizer) { this.finalizer = finalizer } register (dispatcher, key) { if (dispatcher.on) { dispatcher.on('disconnect', () => { if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { this.finalizer(key) } }) } } unregister (key) {} } module.exports = function () { // FIXME: remove workaround when the Node bug is backported to v18 // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 if (process.env.NODE_V8_COVERAGE && process.version.startsWith('v18')) { process._rawDebug('Using compatibility WeakRef and FinalizationRegistry') return { WeakRef: CompatWeakRef, FinalizationRegistry: CompatFinalizer } } return { WeakRef, FinalizationRegistry } } /***/ }), /***/ 7114: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Blob, File } = __nccwpck_require__(4573) const { kState } = __nccwpck_require__(3627) const { webidl } = __nccwpck_require__(5893) // TODO(@KhafraDev): remove class FileLike { constructor (blobLike, fileName, options = {}) { // TODO: argument idl type check // The File constructor is invoked with two or three parameters, depending // on whether the optional dictionary parameter is used. When the File() // constructor is invoked, user agents must run the following steps: // 1. Let bytes be the result of processing blob parts given fileBits and // options. // 2. Let n be the fileName argument to the constructor. const n = fileName // 3. Process FilePropertyBag dictionary argument by running the following // substeps: // 1. If the type member is provided and is not the empty string, let t // be set to the type dictionary member. If t contains any characters // outside the range U+0020 to U+007E, then set t to the empty string // and return from these substeps. // TODO const t = options.type // 2. Convert every character in t to ASCII lowercase. // TODO // 3. If the lastModified member is provided, let d be set to the // lastModified dictionary member. If it is not provided, set d to the // current date and time represented as the number of milliseconds since // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). const d = options.lastModified ?? Date.now() // 4. Return a new File object F such that: // F refers to the bytes byte sequence. // F.size is set to the number of total bytes in bytes. // F.name is set to n. // F.type is set to t. // F.lastModified is set to d. this[kState] = { blobLike, name: n, type: t, lastModified: d } } stream (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.stream(...args) } arrayBuffer (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.arrayBuffer(...args) } slice (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.slice(...args) } text (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.text(...args) } get size () { webidl.brandCheck(this, FileLike) return this[kState].blobLike.size } get type () { webidl.brandCheck(this, FileLike) return this[kState].blobLike.type } get name () { webidl.brandCheck(this, FileLike) return this[kState].name } get lastModified () { webidl.brandCheck(this, FileLike) return this[kState].lastModified } get [Symbol.toStringTag] () { return 'File' } } webidl.converters.Blob = webidl.interfaceConverter(Blob) // If this function is moved to ./util.js, some tools (such as // rollup) will warn about circular dependencies. See: // https://github.com/nodejs/undici/issues/1629 function isFileLike (object) { return ( (object instanceof File) || ( object && (typeof object.stream === 'function' || typeof object.arrayBuffer === 'function') && object[Symbol.toStringTag] === 'File' ) ) } module.exports = { FileLike, isFileLike } /***/ }), /***/ 116: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { isUSVString, bufferToLowerCasedHeaderName } = __nccwpck_require__(3440) const { utf8DecodeBytes } = __nccwpck_require__(3168) const { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = __nccwpck_require__(1900) const { isFileLike } = __nccwpck_require__(7114) const { makeEntry } = __nccwpck_require__(5910) const assert = __nccwpck_require__(4589) const { File: NodeFile } = __nccwpck_require__(4573) const File = globalThis.File ?? NodeFile const formDataNameBuffer = Buffer.from('form-data; name="') const filenameBuffer = Buffer.from('; filename') const dd = Buffer.from('--') const ddcrlf = Buffer.from('--\r\n') /** * @param {string} chars */ function isAsciiString (chars) { for (let i = 0; i < chars.length; ++i) { if ((chars.charCodeAt(i) & ~0x7F) !== 0) { return false } } return true } /** * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary * @param {string} boundary */ function validateBoundary (boundary) { const length = boundary.length // - its length is greater or equal to 27 and lesser or equal to 70, and if (length < 27 || length > 70) { return false } // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('), // 0x2D (-) or 0x5F (_). for (let i = 0; i < length; ++i) { const cp = boundary.charCodeAt(i) if (!( (cp >= 0x30 && cp <= 0x39) || (cp >= 0x41 && cp <= 0x5a) || (cp >= 0x61 && cp <= 0x7a) || cp === 0x27 || cp === 0x2d || cp === 0x5f )) { return false } } return true } /** * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser * @param {Buffer} input * @param {ReturnType} mimeType */ function multipartFormDataParser (input, mimeType) { // 1. Assert: mimeType’s essence is "multipart/form-data". assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data') const boundaryString = mimeType.parameters.get('boundary') // 2. If mimeType’s parameters["boundary"] does not exist, return failure. // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s // parameters["boundary"]. if (boundaryString === undefined) { return 'failure' } const boundary = Buffer.from(`--${boundaryString}`, 'utf8') // 3. Let entry list be an empty entry list. const entryList = [] // 4. Let position be a pointer to a byte in input, initially pointing at // the first byte. const position = { position: 0 } // Note: undici addition, allows leading and trailing CRLFs. while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { position.position += 2 } let trailing = input.length while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) { trailing -= 2 } if (trailing !== input.length) { input = input.subarray(0, trailing) } // 5. While true: while (true) { // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D // (`--`) followed by boundary, advance position by 2 + the length of // boundary. Otherwise, return failure. // Note: boundary is padded with 2 dashes already, no need to add 2. if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) { position.position += boundary.length } else { return 'failure' } // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A // (`--` followed by CR LF) followed by the end of input, return entry list. // Note: a body does NOT need to end with CRLF. It can end with --. if ( (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) || (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position)) ) { return entryList } // 5.3. If position does not point to a sequence of bytes starting with 0x0D // 0x0A (CR LF), return failure. if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { return 'failure' } // 5.4. Advance position by 2. (This skips past the newline.) position.position += 2 // 5.5. Let name, filename and contentType be the result of parsing // multipart/form-data headers on input and position, if the result // is not failure. Otherwise, return failure. const result = parseMultipartFormDataHeaders(input, position) if (result === 'failure') { return 'failure' } let { name, filename, contentType, encoding } = result // 5.6. Advance position by 2. (This skips past the empty line that marks // the end of the headers.) position.position += 2 // 5.7. Let body be the empty byte sequence. let body // 5.8. Body loop: While position is not past the end of input: // TODO: the steps here are completely wrong { const boundaryIndex = input.indexOf(boundary.subarray(2), position.position) if (boundaryIndex === -1) { return 'failure' } body = input.subarray(position.position, boundaryIndex - 4) position.position += body.length // Note: position must be advanced by the body's length before being // decoded, otherwise the parsing will fail. if (encoding === 'base64') { body = Buffer.from(body.toString(), 'base64') } } // 5.9. If position does not point to a sequence of bytes starting with // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2. if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { return 'failure' } else { position.position += 2 } // 5.10. If filename is not null: let value if (filename !== null) { // 5.10.1. If contentType is null, set contentType to "text/plain". contentType ??= 'text/plain' // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string. // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead. // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`. if (!isAsciiString(contentType)) { contentType = '' } // 5.10.3. Let value be a new File object with name filename, type contentType, and body body. value = new File([body], filename, { type: contentType }) } else { // 5.11. Otherwise: // 5.11.1. Let value be the UTF-8 decoding without BOM of body. value = utf8DecodeBytes(Buffer.from(body)) } // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object. assert(isUSVString(name)) assert((typeof value === 'string' && isUSVString(value)) || isFileLike(value)) // 5.13. Create an entry with name and value, and append it to entry list. entryList.push(makeEntry(name, value, filename)) } } /** * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers * @param {Buffer} input * @param {{ position: number }} position */ function parseMultipartFormDataHeaders (input, position) { // 1. Let name, filename and contentType be null. let name = null let filename = null let contentType = null let encoding = null // 2. While true: while (true) { // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF): if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { // 2.1.1. If name is null, return failure. if (name === null) { return 'failure' } // 2.1.2. Return name, filename and contentType. return { name, filename, contentType, encoding } } // 2.2. Let header name be the result of collecting a sequence of bytes that are // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position. let headerName = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a, input, position ) // 2.3. Remove any HTTP tab or space bytes from the start or end of header name. headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20) // 2.4. If header name does not match the field-name token production, return failure. if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) { return 'failure' } // 2.5. If the byte at position is not 0x3A (:), return failure. if (input[position.position] !== 0x3a) { return 'failure' } // 2.6. Advance position by 1. position.position++ // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position. // (Do nothing with those bytes.) collectASequenceOfBytes( (char) => char === 0x20 || char === 0x09, input, position ) // 2.8. Byte-lowercase header name and switch on the result: switch (bufferToLowerCasedHeaderName(headerName)) { case 'content-disposition': { // 1. Set name and filename to null. name = filename = null // 2. If position does not point to a sequence of bytes starting with // `form-data; name="`, return failure. if (!bufferStartsWith(input, formDataNameBuffer, position)) { return 'failure' } // 3. Advance position so it points at the byte after the next 0x22 (") // byte (the one in the sequence of bytes matched above). position.position += 17 // 4. Set name to the result of parsing a multipart/form-data name given // input and position, if the result is not failure. Otherwise, return // failure. name = parseMultipartFormDataName(input, position) if (name === null) { return 'failure' } // 5. If position points to a sequence of bytes starting with `; filename="`: if (bufferStartsWith(input, filenameBuffer, position)) { // Note: undici also handles filename* let check = position.position + filenameBuffer.length if (input[check] === 0x2a) { position.position += 1 check += 1 } if (input[check] !== 0x3d || input[check + 1] !== 0x22) { // =" return 'failure' } // 1. Advance position so it points at the byte after the next 0x22 (") byte // (the one in the sequence of bytes matched above). position.position += 12 // 2. Set filename to the result of parsing a multipart/form-data name given // input and position, if the result is not failure. Otherwise, return failure. filename = parseMultipartFormDataName(input, position) if (filename === null) { return 'failure' } } break } case 'content-type': { // 1. Let header value be the result of collecting a sequence of bytes that are // not 0x0A (LF) or 0x0D (CR), given position. let headerValue = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d, input, position ) // 2. Remove any HTTP tab or space bytes from the end of header value. headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) // 3. Set contentType to the isomorphic decoding of header value. contentType = isomorphicDecode(headerValue) break } case 'content-transfer-encoding': { let headerValue = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d, input, position ) headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) encoding = isomorphicDecode(headerValue) break } default: { // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position. // (Do nothing with those bytes.) collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d, input, position ) } } // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A // (CR LF), return failure. Otherwise, advance position by 2 (past the newline). if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) { return 'failure' } else { position.position += 2 } } } /** * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name * @param {Buffer} input * @param {{ position: number }} position */ function parseMultipartFormDataName (input, position) { // 1. Assert: The byte at (position - 1) is 0x22 ("). assert(input[position.position - 1] === 0x22) // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 ("), given position. /** @type {string | Buffer} */ let name = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d && char !== 0x22, input, position ) // 3. If the byte at position is not 0x22 ("), return failure. Otherwise, advance position by 1. if (input[position.position] !== 0x22) { return null // name could be 'failure' } else { position.position++ } // 4. Replace any occurrence of the following subsequences in name with the given byte: // - `%0A`: 0x0A (LF) // - `%0D`: 0x0D (CR) // - `%22`: 0x22 (") name = new TextDecoder().decode(name) .replace(/%0A/ig, '\n') .replace(/%0D/ig, '\r') .replace(/%22/g, '"') // 5. Return the UTF-8 decoding without BOM of name. return name } /** * @param {(char: number) => boolean} condition * @param {Buffer} input * @param {{ position: number }} position */ function collectASequenceOfBytes (condition, input, position) { let start = position.position while (start < input.length && condition(input[start])) { ++start } return input.subarray(position.position, (position.position = start)) } /** * @param {Buffer} buf * @param {boolean} leading * @param {boolean} trailing * @param {(charCode: number) => boolean} predicate * @returns {Buffer} */ function removeChars (buf, leading, trailing, predicate) { let lead = 0 let trail = buf.length - 1 if (leading) { while (lead < buf.length && predicate(buf[lead])) lead++ } if (trailing) { while (trail > 0 && predicate(buf[trail])) trail-- } return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1) } /** * Checks if {@param buffer} starts with {@param start} * @param {Buffer} buffer * @param {Buffer} start * @param {{ position: number }} position */ function bufferStartsWith (buffer, start, position) { if (buffer.length < start.length) { return false } for (let i = 0; i < start.length; i++) { if (start[i] !== buffer[position.position + i]) { return false } } return true } module.exports = { multipartFormDataParser, validateBoundary } /***/ }), /***/ 5910: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { isBlobLike, iteratorMixin } = __nccwpck_require__(3168) const { kState } = __nccwpck_require__(3627) const { kEnumerableProperty } = __nccwpck_require__(3440) const { FileLike, isFileLike } = __nccwpck_require__(7114) const { webidl } = __nccwpck_require__(5893) const { File: NativeFile } = __nccwpck_require__(4573) const nodeUtil = __nccwpck_require__(7975) /** @type {globalThis['File']} */ const File = globalThis.File ?? NativeFile // https://xhr.spec.whatwg.org/#formdata class FormData { constructor (form) { webidl.util.markAsUncloneable(this) if (form !== undefined) { throw webidl.errors.conversionFailed({ prefix: 'FormData constructor', argument: 'Argument 1', types: ['undefined'] }) } this[kState] = [] } append (name, value, filename = undefined) { webidl.brandCheck(this, FormData) const prefix = 'FormData.append' webidl.argumentLengthCheck(arguments, 2, prefix) if (arguments.length === 3 && !isBlobLike(value)) { throw new TypeError( "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" ) } // 1. Let value be value if given; otherwise blobValue. name = webidl.converters.USVString(name, prefix, 'name') value = isBlobLike(value) ? webidl.converters.Blob(value, prefix, 'value', { strict: false }) : webidl.converters.USVString(value, prefix, 'value') filename = arguments.length === 3 ? webidl.converters.USVString(filename, prefix, 'filename') : undefined // 2. Let entry be the result of creating an entry with // name, value, and filename if given. const entry = makeEntry(name, value, filename) // 3. Append entry to this’s entry list. this[kState].push(entry) } delete (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.delete' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name, prefix, 'name') // The delete(name) method steps are to remove all entries whose name // is name from this’s entry list. this[kState] = this[kState].filter(entry => entry.name !== name) } get (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.get' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name, prefix, 'name') // 1. If there is no entry whose name is name in this’s entry list, // then return null. const idx = this[kState].findIndex((entry) => entry.name === name) if (idx === -1) { return null } // 2. Return the value of the first entry whose name is name from // this’s entry list. return this[kState][idx].value } getAll (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.getAll' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name, prefix, 'name') // 1. If there is no entry whose name is name in this’s entry list, // then return the empty list. // 2. Return the values of all entries whose name is name, in order, // from this’s entry list. return this[kState] .filter((entry) => entry.name === name) .map((entry) => entry.value) } has (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.has' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name, prefix, 'name') // The has(name) method steps are to return true if there is an entry // whose name is name in this’s entry list; otherwise false. return this[kState].findIndex((entry) => entry.name === name) !== -1 } set (name, value, filename = undefined) { webidl.brandCheck(this, FormData) const prefix = 'FormData.set' webidl.argumentLengthCheck(arguments, 2, prefix) if (arguments.length === 3 && !isBlobLike(value)) { throw new TypeError( "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" ) } // The set(name, value) and set(name, blobValue, filename) method steps // are: // 1. Let value be value if given; otherwise blobValue. name = webidl.converters.USVString(name, prefix, 'name') value = isBlobLike(value) ? webidl.converters.Blob(value, prefix, 'name', { strict: false }) : webidl.converters.USVString(value, prefix, 'name') filename = arguments.length === 3 ? webidl.converters.USVString(filename, prefix, 'name') : undefined // 2. Let entry be the result of creating an entry with name, value, and // filename if given. const entry = makeEntry(name, value, filename) // 3. If there are entries in this’s entry list whose name is name, then // replace the first such entry with entry and remove the others. const idx = this[kState].findIndex((entry) => entry.name === name) if (idx !== -1) { this[kState] = [ ...this[kState].slice(0, idx), entry, ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) ] } else { // 4. Otherwise, append entry to this’s entry list. this[kState].push(entry) } } [nodeUtil.inspect.custom] (depth, options) { const state = this[kState].reduce((a, b) => { if (a[b.name]) { if (Array.isArray(a[b.name])) { a[b.name].push(b.value) } else { a[b.name] = [a[b.name], b.value] } } else { a[b.name] = b.value } return a }, { __proto__: null }) options.depth ??= depth options.colors ??= true const output = nodeUtil.formatWithOptions(options, state) // remove [Object null prototype] return `FormData ${output.slice(output.indexOf(']') + 2)}` } } iteratorMixin('FormData', FormData, kState, 'name', 'value') Object.defineProperties(FormData.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, get: kEnumerableProperty, getAll: kEnumerableProperty, has: kEnumerableProperty, set: kEnumerableProperty, [Symbol.toStringTag]: { value: 'FormData', configurable: true } }) /** * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry * @param {string} name * @param {string|Blob} value * @param {?string} filename * @returns */ function makeEntry (name, value, filename) { // 1. Set name to the result of converting name into a scalar value string. // Note: This operation was done by the webidl converter USVString. // 2. If value is a string, then set value to the result of converting // value into a scalar value string. if (typeof value === 'string') { // Note: This operation was done by the webidl converter USVString. } else { // 3. Otherwise: // 1. If value is not a File object, then set value to a new File object, // representing the same bytes, whose name attribute value is "blob" if (!isFileLike(value)) { value = value instanceof Blob ? new File([value], 'blob', { type: value.type }) : new FileLike(value, 'blob', { type: value.type }) } // 2. If filename is given, then set value to a new File object, // representing the same bytes, whose name attribute is filename. if (filename !== undefined) { /** @type {FilePropertyBag} */ const options = { type: value.type, lastModified: value.lastModified } value = value instanceof NativeFile ? new File([value], filename, options) : new FileLike(value, filename, options) } } // 4. Return an entry whose name is name and whose value is value. return { name, value } } module.exports = { FormData, makeEntry } /***/ }), /***/ 1059: /***/ ((module) => { "use strict"; // In case of breaking changes, increase the version // number to avoid conflicts. const globalOrigin = Symbol.for('undici.globalOrigin.1') function getGlobalOrigin () { return globalThis[globalOrigin] } function setGlobalOrigin (newOrigin) { if (newOrigin === undefined) { Object.defineProperty(globalThis, globalOrigin, { value: undefined, writable: true, enumerable: false, configurable: false }) return } const parsedURL = new URL(newOrigin) if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) } Object.defineProperty(globalThis, globalOrigin, { value: parsedURL, writable: true, enumerable: false, configurable: false }) } module.exports = { getGlobalOrigin, setGlobalOrigin } /***/ }), /***/ 660: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // https://github.com/Ethan-Arrowood/undici-fetch const { kConstruct } = __nccwpck_require__(6443) const { kEnumerableProperty } = __nccwpck_require__(3440) const { iteratorMixin, isValidHeaderName, isValidHeaderValue } = __nccwpck_require__(3168) const { webidl } = __nccwpck_require__(5893) const assert = __nccwpck_require__(4589) const util = __nccwpck_require__(7975) const kHeadersMap = Symbol('headers map') const kHeadersSortedMap = Symbol('headers map sorted') /** * @param {number} code */ function isHTTPWhiteSpaceCharCode (code) { return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 } /** * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize * @param {string} potentialValue */ function headerValueNormalize (potentialValue) { // To normalize a byte sequence potentialValue, remove // any leading and trailing HTTP whitespace bytes from // potentialValue. let i = 0; let j = potentialValue.length while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) } function fill (headers, object) { // To fill a Headers object headers with a given object object, run these steps: // 1. If object is a sequence, then for each header in object: // Note: webidl conversion to array has already been done. if (Array.isArray(object)) { for (let i = 0; i < object.length; ++i) { const header = object[i] // 1. If header does not contain exactly two items, then throw a TypeError. if (header.length !== 2) { throw webidl.errors.exception({ header: 'Headers constructor', message: `expected name/value pair to be length 2, found ${header.length}.` }) } // 2. Append (header’s first item, header’s second item) to headers. appendHeader(headers, header[0], header[1]) } } else if (typeof object === 'object' && object !== null) { // Note: null should throw // 2. Otherwise, object is a record, then for each key → value in object, // append (key, value) to headers const keys = Object.keys(object) for (let i = 0; i < keys.length; ++i) { appendHeader(headers, keys[i], object[keys[i]]) } } else { throw webidl.errors.conversionFailed({ prefix: 'Headers constructor', argument: 'Argument 1', types: ['sequence>', 'record'] }) } } /** * @see https://fetch.spec.whatwg.org/#concept-headers-append */ function appendHeader (headers, name, value) { // 1. Normalize value. value = headerValueNormalize(value) // 2. If name is not a header name or value is not a // header value, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.append', value: name, type: 'header name' }) } else if (!isValidHeaderValue(value)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.append', value, type: 'header value' }) } // 3. If headers’s guard is "immutable", then throw a TypeError. // 4. Otherwise, if headers’s guard is "request" and name is a // forbidden header name, return. // 5. Otherwise, if headers’s guard is "request-no-cors": // TODO // Note: undici does not implement forbidden header names if (getHeadersGuard(headers) === 'immutable') { throw new TypeError('immutable') } // 6. Otherwise, if headers’s guard is "response" and name is a // forbidden response-header name, return. // 7. Append (name, value) to headers’s header list. return getHeadersList(headers).append(name, value, false) // 8. If headers’s guard is "request-no-cors", then remove // privileged no-CORS request headers from headers } function compareHeaderName (a, b) { return a[0] < b[0] ? -1 : 1 } class HeadersList { /** @type {[string, string][]|null} */ cookies = null constructor (init) { if (init instanceof HeadersList) { this[kHeadersMap] = new Map(init[kHeadersMap]) this[kHeadersSortedMap] = init[kHeadersSortedMap] this.cookies = init.cookies === null ? null : [...init.cookies] } else { this[kHeadersMap] = new Map(init) this[kHeadersSortedMap] = null } } /** * @see https://fetch.spec.whatwg.org/#header-list-contains * @param {string} name * @param {boolean} isLowerCase */ contains (name, isLowerCase) { // A header list list contains a header name name if list // contains a header whose name is a byte-case-insensitive // match for name. return this[kHeadersMap].has(isLowerCase ? name : name.toLowerCase()) } clear () { this[kHeadersMap].clear() this[kHeadersSortedMap] = null this.cookies = null } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-append * @param {string} name * @param {string} value * @param {boolean} isLowerCase */ append (name, value, isLowerCase) { this[kHeadersSortedMap] = null // 1. If list contains name, then set name to the first such // header’s name. const lowercaseName = isLowerCase ? name : name.toLowerCase() const exists = this[kHeadersMap].get(lowercaseName) // 2. Append (name, value) to list. if (exists) { const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' this[kHeadersMap].set(lowercaseName, { name: exists.name, value: `${exists.value}${delimiter}${value}` }) } else { this[kHeadersMap].set(lowercaseName, { name, value }) } if (lowercaseName === 'set-cookie') { (this.cookies ??= []).push(value) } } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-set * @param {string} name * @param {string} value * @param {boolean} isLowerCase */ set (name, value, isLowerCase) { this[kHeadersSortedMap] = null const lowercaseName = isLowerCase ? name : name.toLowerCase() if (lowercaseName === 'set-cookie') { this.cookies = [value] } // 1. If list contains name, then set the value of // the first such header to value and remove the // others. // 2. Otherwise, append header (name, value) to list. this[kHeadersMap].set(lowercaseName, { name, value }) } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-delete * @param {string} name * @param {boolean} isLowerCase */ delete (name, isLowerCase) { this[kHeadersSortedMap] = null if (!isLowerCase) name = name.toLowerCase() if (name === 'set-cookie') { this.cookies = null } this[kHeadersMap].delete(name) } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-get * @param {string} name * @param {boolean} isLowerCase * @returns {string | null} */ get (name, isLowerCase) { // 1. If list does not contain name, then return null. // 2. Return the values of all headers in list whose name // is a byte-case-insensitive match for name, // separated from each other by 0x2C 0x20, in order. return this[kHeadersMap].get(isLowerCase ? name : name.toLowerCase())?.value ?? null } * [Symbol.iterator] () { // use the lowercased name for (const { 0: name, 1: { value } } of this[kHeadersMap]) { yield [name, value] } } get entries () { const headers = {} if (this[kHeadersMap].size !== 0) { for (const { name, value } of this[kHeadersMap].values()) { headers[name] = value } } return headers } rawValues () { return this[kHeadersMap].values() } get entriesList () { const headers = [] if (this[kHeadersMap].size !== 0) { for (const { 0: lowerName, 1: { name, value } } of this[kHeadersMap]) { if (lowerName === 'set-cookie') { for (const cookie of this.cookies) { headers.push([name, cookie]) } } else { headers.push([name, value]) } } } return headers } // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set toSortedArray () { const size = this[kHeadersMap].size const array = new Array(size) // In most cases, you will use the fast-path. // fast-path: Use binary insertion sort for small arrays. if (size <= 32) { if (size === 0) { // If empty, it is an empty array. To avoid the first index assignment. return array } // Improve performance by unrolling loop and avoiding double-loop. // Double-loop-less version of the binary insertion sort. const iterator = this[kHeadersMap][Symbol.iterator]() const firstValue = iterator.next().value // set [name, value] to first index. array[0] = [firstValue[0], firstValue[1].value] // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine // 3.2.2. Assert: value is non-null. assert(firstValue[1].value !== null) for ( let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; i < size; ++i ) { // get next value value = iterator.next().value // set [name, value] to current index. x = array[i] = [value[0], value[1].value] // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine // 3.2.2. Assert: value is non-null. assert(x[1] !== null) left = 0 right = i // binary search while (left < right) { // middle index pivot = left + ((right - left) >> 1) // compare header name if (array[pivot][0] <= x[0]) { left = pivot + 1 } else { right = pivot } } if (i !== pivot) { j = i while (j > left) { array[j] = array[--j] } array[left] = x } } /* c8 ignore next 4 */ if (!iterator.next().done) { // This is for debugging and will never be called. throw new TypeError('Unreachable') } return array } else { // This case would be a rare occurrence. // slow-path: fallback let i = 0 for (const { 0: name, 1: { value } } of this[kHeadersMap]) { array[i++] = [name, value] // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine // 3.2.2. Assert: value is non-null. assert(value !== null) } return array.sort(compareHeaderName) } } } // https://fetch.spec.whatwg.org/#headers-class class Headers { #guard #headersList constructor (init = undefined) { webidl.util.markAsUncloneable(this) if (init === kConstruct) { return } this.#headersList = new HeadersList() // The new Headers(init) constructor steps are: // 1. Set this’s guard to "none". this.#guard = 'none' // 2. If init is given, then fill this with init. if (init !== undefined) { init = webidl.converters.HeadersInit(init, 'Headers contructor', 'init') fill(this, init) } } // https://fetch.spec.whatwg.org/#dom-headers-append append (name, value) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 2, 'Headers.append') const prefix = 'Headers.append' name = webidl.converters.ByteString(name, prefix, 'name') value = webidl.converters.ByteString(value, prefix, 'value') return appendHeader(this, name, value) } // https://fetch.spec.whatwg.org/#dom-headers-delete delete (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, 'Headers.delete') const prefix = 'Headers.delete' name = webidl.converters.ByteString(name, prefix, 'name') // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.delete', value: name, type: 'header name' }) } // 2. If this’s guard is "immutable", then throw a TypeError. // 3. Otherwise, if this’s guard is "request" and name is a // forbidden header name, return. // 4. Otherwise, if this’s guard is "request-no-cors", name // is not a no-CORS-safelisted request-header name, and // name is not a privileged no-CORS request-header name, // return. // 5. Otherwise, if this’s guard is "response" and name is // a forbidden response-header name, return. // Note: undici does not implement forbidden header names if (this.#guard === 'immutable') { throw new TypeError('immutable') } // 6. If this’s header list does not contain name, then // return. if (!this.#headersList.contains(name, false)) { return } // 7. Delete name from this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this. this.#headersList.delete(name, false) } // https://fetch.spec.whatwg.org/#dom-headers-get get (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, 'Headers.get') const prefix = 'Headers.get' name = webidl.converters.ByteString(name, prefix, 'name') // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix, value: name, type: 'header name' }) } // 2. Return the result of getting name from this’s header // list. return this.#headersList.get(name, false) } // https://fetch.spec.whatwg.org/#dom-headers-has has (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, 'Headers.has') const prefix = 'Headers.has' name = webidl.converters.ByteString(name, prefix, 'name') // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix, value: name, type: 'header name' }) } // 2. Return true if this’s header list contains name; // otherwise false. return this.#headersList.contains(name, false) } // https://fetch.spec.whatwg.org/#dom-headers-set set (name, value) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 2, 'Headers.set') const prefix = 'Headers.set' name = webidl.converters.ByteString(name, prefix, 'name') value = webidl.converters.ByteString(value, prefix, 'value') // 1. Normalize value. value = headerValueNormalize(value) // 2. If name is not a header name or value is not a // header value, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix, value: name, type: 'header name' }) } else if (!isValidHeaderValue(value)) { throw webidl.errors.invalidArgument({ prefix, value, type: 'header value' }) } // 3. If this’s guard is "immutable", then throw a TypeError. // 4. Otherwise, if this’s guard is "request" and name is a // forbidden header name, return. // 5. Otherwise, if this’s guard is "request-no-cors" and // name/value is not a no-CORS-safelisted request-header, // return. // 6. Otherwise, if this’s guard is "response" and name is a // forbidden response-header name, return. // Note: undici does not implement forbidden header names if (this.#guard === 'immutable') { throw new TypeError('immutable') } // 7. Set (name, value) in this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this this.#headersList.set(name, value, false) } // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie getSetCookie () { webidl.brandCheck(this, Headers) // 1. If this’s header list does not contain `Set-Cookie`, then return « ». // 2. Return the values of all headers in this’s header list whose name is // a byte-case-insensitive match for `Set-Cookie`, in order. const list = this.#headersList.cookies if (list) { return [...list] } return [] } // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine get [kHeadersSortedMap] () { if (this.#headersList[kHeadersSortedMap]) { return this.#headersList[kHeadersSortedMap] } // 1. Let headers be an empty list of headers with the key being the name // and value the value. const headers = [] // 2. Let names be the result of convert header names to a sorted-lowercase // set with all the names of the headers in list. const names = this.#headersList.toSortedArray() const cookies = this.#headersList.cookies // fast-path if (cookies === null || cookies.length === 1) { // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray` return (this.#headersList[kHeadersSortedMap] = names) } // 3. For each name of names: for (let i = 0; i < names.length; ++i) { const { 0: name, 1: value } = names[i] // 1. If name is `set-cookie`, then: if (name === 'set-cookie') { // 1. Let values be a list of all values of headers in list whose name // is a byte-case-insensitive match for name, in order. // 2. For each value of values: // 1. Append (name, value) to headers. for (let j = 0; j < cookies.length; ++j) { headers.push([name, cookies[j]]) } } else { // 2. Otherwise: // 1. Let value be the result of getting name from list. // 2. Assert: value is non-null. // Note: This operation was done by `HeadersList#toSortedArray`. // 3. Append (name, value) to headers. headers.push([name, value]) } } // 4. Return headers. return (this.#headersList[kHeadersSortedMap] = headers) } [util.inspect.custom] (depth, options) { options.depth ??= depth return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}` } static getHeadersGuard (o) { return o.#guard } static setHeadersGuard (o, guard) { o.#guard = guard } static getHeadersList (o) { return o.#headersList } static setHeadersList (o, list) { o.#headersList = list } } const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers Reflect.deleteProperty(Headers, 'getHeadersGuard') Reflect.deleteProperty(Headers, 'setHeadersGuard') Reflect.deleteProperty(Headers, 'getHeadersList') Reflect.deleteProperty(Headers, 'setHeadersList') iteratorMixin('Headers', Headers, kHeadersSortedMap, 0, 1) Object.defineProperties(Headers.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, get: kEnumerableProperty, has: kEnumerableProperty, set: kEnumerableProperty, getSetCookie: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Headers', configurable: true }, [util.inspect.custom]: { enumerable: false } }) webidl.converters.HeadersInit = function (V, prefix, argument) { if (webidl.util.Type(V) === 'Object') { const iterator = Reflect.get(V, Symbol.iterator) // A work-around to ensure we send the properly-cased Headers when V is a Headers object. // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please. if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object try { return getHeadersList(V).entriesList } catch { // fall-through } } if (typeof iterator === 'function') { return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V)) } return webidl.converters['record'](V, prefix, argument) } throw webidl.errors.conversionFailed({ prefix: 'Headers constructor', argument: 'Argument 1', types: ['sequence>', 'record'] }) } module.exports = { fill, // for test. compareHeaderName, Headers, HeadersList, getHeadersGuard, setHeadersGuard, setHeadersList, getHeadersList } /***/ }), /***/ 4398: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // https://github.com/Ethan-Arrowood/undici-fetch const { makeNetworkError, makeAppropriateNetworkError, filterResponse, makeResponse, fromInnerResponse } = __nccwpck_require__(9051) const { HeadersList } = __nccwpck_require__(660) const { Request, cloneRequest } = __nccwpck_require__(9967) const zlib = __nccwpck_require__(8522) const { bytesMatch, makePolicyContainer, clonePolicyContainer, requestBadPort, TAOCheck, appendRequestOriginHeader, responseLocationURL, requestCurrentURL, setRequestReferrerPolicyOnRedirect, tryUpgradeRequestToAPotentiallyTrustworthyURL, createOpaqueTimingInfo, appendFetchMetadata, corsCheck, crossOriginResourcePolicyCheck, determineRequestsReferrer, coarsenedSharedCurrentTime, createDeferredPromise, isBlobLike, sameOrigin, isCancelled, isAborted, isErrorLike, fullyReadBody, readableStreamClose, isomorphicEncode, urlIsLocal, urlIsHttpHttpsScheme, urlHasHttpsScheme, clampAndCoarsenConnectionTimingInfo, simpleRangeHeaderValue, buildContentRange, createInflate, extractMimeType } = __nccwpck_require__(3168) const { kState, kDispatcher } = __nccwpck_require__(3627) const assert = __nccwpck_require__(4589) const { safelyExtractBody, extractBody } = __nccwpck_require__(4492) const { redirectStatusSet, nullBodyStatus, safeMethodsSet, requestBodyHeader, subresourceSet } = __nccwpck_require__(4495) const EE = __nccwpck_require__(8474) const { Readable, pipeline, finished } = __nccwpck_require__(7075) const { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = __nccwpck_require__(3440) const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = __nccwpck_require__(1900) const { getGlobalDispatcher } = __nccwpck_require__(2581) const { webidl } = __nccwpck_require__(5893) const { STATUS_CODES } = __nccwpck_require__(7067) const GET_OR_HEAD = ['GET', 'HEAD'] const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined' ? 'node' : 'undici' /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL class Fetch extends EE { constructor (dispatcher) { super() this.dispatcher = dispatcher this.connection = null this.dump = false this.state = 'ongoing' } terminate (reason) { if (this.state !== 'ongoing') { return } this.state = 'terminated' this.connection?.destroy(reason) this.emit('terminated', reason) } // https://fetch.spec.whatwg.org/#fetch-controller-abort abort (error) { if (this.state !== 'ongoing') { return } // 1. Set controller’s state to "aborted". this.state = 'aborted' // 2. Let fallbackError be an "AbortError" DOMException. // 3. Set error to fallbackError if it is not given. if (!error) { error = new DOMException('The operation was aborted.', 'AbortError') } // 4. Let serializedError be StructuredSerialize(error). // If that threw an exception, catch it, and let // serializedError be StructuredSerialize(fallbackError). // 5. Set controller’s serialized abort reason to serializedError. this.serializedAbortReason = error this.connection?.destroy(error) this.emit('terminated', error) } } function handleFetchDone (response) { finalizeAndReportTiming(response, 'fetch') } // https://fetch.spec.whatwg.org/#fetch-method function fetch (input, init = undefined) { webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch') // 1. Let p be a new promise. let p = createDeferredPromise() // 2. Let requestObject be the result of invoking the initial value of // Request as constructor with input and init as arguments. If this throws // an exception, reject p with it and return p. let requestObject try { requestObject = new Request(input, init) } catch (e) { p.reject(e) return p.promise } // 3. Let request be requestObject’s request. const request = requestObject[kState] // 4. If requestObject’s signal’s aborted flag is set, then: if (requestObject.signal.aborted) { // 1. Abort the fetch() call with p, request, null, and // requestObject’s signal’s abort reason. abortFetch(p, request, null, requestObject.signal.reason) // 2. Return p. return p.promise } // 5. Let globalObject be request’s client’s global object. const globalObject = request.client.globalObject // 6. If globalObject is a ServiceWorkerGlobalScope object, then set // request’s service-workers mode to "none". if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { request.serviceWorkers = 'none' } // 7. Let responseObject be null. let responseObject = null // 8. Let relevantRealm be this’s relevant Realm. // 9. Let locallyAborted be false. let locallyAborted = false // 10. Let controller be null. let controller = null // 11. Add the following abort steps to requestObject’s signal: addAbortListener( requestObject.signal, () => { // 1. Set locallyAborted to true. locallyAborted = true // 2. Assert: controller is non-null. assert(controller != null) // 3. Abort controller with requestObject’s signal’s abort reason. controller.abort(requestObject.signal.reason) const realResponse = responseObject?.deref() // 4. Abort the fetch() call with p, request, responseObject, // and requestObject’s signal’s abort reason. abortFetch(p, request, realResponse, requestObject.signal.reason) } ) // 12. Let handleFetchDone given response response be to finalize and // report timing with response, globalObject, and "fetch". // see function handleFetchDone // 13. Set controller to the result of calling fetch given request, // with processResponseEndOfBody set to handleFetchDone, and processResponse // given response being these substeps: const processResponse = (response) => { // 1. If locallyAborted is true, terminate these substeps. if (locallyAborted) { return } // 2. If response’s aborted flag is set, then: if (response.aborted) { // 1. Let deserializedError be the result of deserialize a serialized // abort reason given controller’s serialized abort reason and // relevantRealm. // 2. Abort the fetch() call with p, request, responseObject, and // deserializedError. abortFetch(p, request, responseObject, controller.serializedAbortReason) return } // 3. If response is a network error, then reject p with a TypeError // and terminate these substeps. if (response.type === 'error') { p.reject(new TypeError('fetch failed', { cause: response.error })) return } // 4. Set responseObject to the result of creating a Response object, // given response, "immutable", and relevantRealm. responseObject = new WeakRef(fromInnerResponse(response, 'immutable')) // 5. Resolve p with responseObject. p.resolve(responseObject.deref()) p = null } controller = fetching({ request, processResponseEndOfBody: handleFetchDone, processResponse, dispatcher: requestObject[kDispatcher] // undici }) // 14. Return p. return p.promise } // https://fetch.spec.whatwg.org/#finalize-and-report-timing function finalizeAndReportTiming (response, initiatorType = 'other') { // 1. If response is an aborted network error, then return. if (response.type === 'error' && response.aborted) { return } // 2. If response’s URL list is null or empty, then return. if (!response.urlList?.length) { return } // 3. Let originalURL be response’s URL list[0]. const originalURL = response.urlList[0] // 4. Let timingInfo be response’s timing info. let timingInfo = response.timingInfo // 5. Let cacheState be response’s cache state. let cacheState = response.cacheState // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. if (!urlIsHttpHttpsScheme(originalURL)) { return } // 7. If timingInfo is null, then return. if (timingInfo === null) { return } // 8. If response’s timing allow passed flag is not set, then: if (!response.timingAllowPassed) { // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. timingInfo = createOpaqueTimingInfo({ startTime: timingInfo.startTime }) // 2. Set cacheState to the empty string. cacheState = '' } // 9. Set timingInfo’s end time to the coarsened shared current time // given global’s relevant settings object’s cross-origin isolated // capability. // TODO: given global’s relevant settings object’s cross-origin isolated // capability? timingInfo.endTime = coarsenedSharedCurrentTime() // 10. Set response’s timing info to timingInfo. response.timingInfo = timingInfo // 11. Mark resource timing for timingInfo, originalURL, initiatorType, // global, and cacheState. markResourceTiming( timingInfo, originalURL.href, initiatorType, globalThis, cacheState ) } // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing const markResourceTiming = performance.markResourceTiming // https://fetch.spec.whatwg.org/#abort-fetch function abortFetch (p, request, responseObject, error) { // 1. Reject promise with error. if (p) { // We might have already resolved the promise at this stage p.reject(error) } // 2. If request’s body is not null and is readable, then cancel request’s // body with error. if (request.body != null && isReadable(request.body?.stream)) { request.body.stream.cancel(error).catch((err) => { if (err.code === 'ERR_INVALID_STATE') { // Node bug? return } throw err }) } // 3. If responseObject is null, then return. if (responseObject == null) { return } // 4. Let response be responseObject’s response. const response = responseObject[kState] // 5. If response’s body is not null and is readable, then error response’s // body with error. if (response.body != null && isReadable(response.body?.stream)) { response.body.stream.cancel(error).catch((err) => { if (err.code === 'ERR_INVALID_STATE') { // Node bug? return } throw err }) } } // https://fetch.spec.whatwg.org/#fetching function fetching ({ request, processRequestBodyChunkLength, processRequestEndOfBody, processResponse, processResponseEndOfBody, processResponseConsumeBody, useParallelQueue = false, dispatcher = getGlobalDispatcher() // undici }) { // Ensure that the dispatcher is set accordingly assert(dispatcher) // 1. Let taskDestination be null. let taskDestination = null // 2. Let crossOriginIsolatedCapability be false. let crossOriginIsolatedCapability = false // 3. If request’s client is non-null, then: if (request.client != null) { // 1. Set taskDestination to request’s client’s global object. taskDestination = request.client.globalObject // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin // isolated capability. crossOriginIsolatedCapability = request.client.crossOriginIsolatedCapability } // 4. If useParallelQueue is true, then set taskDestination to the result of // starting a new parallel queue. // TODO // 5. Let timingInfo be a new fetch timing info whose start time and // post-redirect start time are the coarsened shared current time given // crossOriginIsolatedCapability. const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) const timingInfo = createOpaqueTimingInfo({ startTime: currentTime }) // 6. Let fetchParams be a new fetch params whose // request is request, // timing info is timingInfo, // process request body chunk length is processRequestBodyChunkLength, // process request end-of-body is processRequestEndOfBody, // process response is processResponse, // process response consume body is processResponseConsumeBody, // process response end-of-body is processResponseEndOfBody, // task destination is taskDestination, // and cross-origin isolated capability is crossOriginIsolatedCapability. const fetchParams = { controller: new Fetch(dispatcher), request, timingInfo, processRequestBodyChunkLength, processRequestEndOfBody, processResponse, processResponseConsumeBody, processResponseEndOfBody, taskDestination, crossOriginIsolatedCapability } // 7. If request’s body is a byte sequence, then set request’s body to // request’s body as a body. // NOTE: Since fetching is only called from fetch, body should already be // extracted. assert(!request.body || request.body.stream) // 8. If request’s window is "client", then set request’s window to request’s // client, if request’s client’s global object is a Window object; otherwise // "no-window". if (request.window === 'client') { // TODO: What if request.client is null? request.window = request.client?.globalObject?.constructor?.name === 'Window' ? request.client : 'no-window' } // 9. If request’s origin is "client", then set request’s origin to request’s // client’s origin. if (request.origin === 'client') { request.origin = request.client.origin } // 10. If all of the following conditions are true: // TODO // 11. If request’s policy container is "client", then: if (request.policyContainer === 'client') { // 1. If request’s client is non-null, then set request’s policy // container to a clone of request’s client’s policy container. [HTML] if (request.client != null) { request.policyContainer = clonePolicyContainer( request.client.policyContainer ) } else { // 2. Otherwise, set request’s policy container to a new policy // container. request.policyContainer = makePolicyContainer() } } // 12. If request’s header list does not contain `Accept`, then: if (!request.headersList.contains('accept', true)) { // 1. Let value be `*/*`. const value = '*/*' // 2. A user agent should set value to the first matching statement, if // any, switching on request’s destination: // "document" // "frame" // "iframe" // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` // "image" // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` // "style" // `text/css,*/*;q=0.1` // TODO // 3. Append `Accept`/value to request’s header list. request.headersList.append('accept', value, true) } // 13. If request’s header list does not contain `Accept-Language`, then // user agents should append `Accept-Language`/an appropriate value to // request’s header list. if (!request.headersList.contains('accept-language', true)) { request.headersList.append('accept-language', '*', true) } // 14. If request’s priority is null, then use request’s initiator and // destination appropriately in setting request’s priority to a // user-agent-defined object. if (request.priority === null) { // TODO } // 15. If request is a subresource request, then: if (subresourceSet.has(request.destination)) { // TODO } // 16. Run main fetch given fetchParams. mainFetch(fetchParams) .catch(err => { fetchParams.controller.terminate(err) }) // 17. Return fetchParam's controller return fetchParams.controller } // https://fetch.spec.whatwg.org/#concept-main-fetch async function mainFetch (fetchParams, recursive = false) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. If request’s local-URLs-only flag is set and request’s current URL is // not local, then set response to a network error. if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { response = makeNetworkError('local URLs only') } // 4. Run report Content Security Policy violations for request. // TODO // 5. Upgrade request to a potentially trustworthy URL, if appropriate. tryUpgradeRequestToAPotentiallyTrustworthyURL(request) // 6. If should request be blocked due to a bad port, should fetching request // be blocked as mixed content, or should request be blocked by Content // Security Policy returns blocked, then set response to a network error. if (requestBadPort(request) === 'blocked') { response = makeNetworkError('bad port') } // TODO: should fetching request be blocked as mixed content? // TODO: should request be blocked by Content Security Policy? // 7. If request’s referrer policy is the empty string, then set request’s // referrer policy to request’s policy container’s referrer policy. if (request.referrerPolicy === '') { request.referrerPolicy = request.policyContainer.referrerPolicy } // 8. If request’s referrer is not "no-referrer", then set request’s // referrer to the result of invoking determine request’s referrer. if (request.referrer !== 'no-referrer') { request.referrer = determineRequestsReferrer(request) } // 9. Set request’s current URL’s scheme to "https" if all of the following // conditions are true: // - request’s current URL’s scheme is "http" // - request’s current URL’s host is a domain // - Matching request’s current URL’s host per Known HSTS Host Domain Name // Matching results in either a superdomain match with an asserted // includeSubDomains directive or a congruent match (with or without an // asserted includeSubDomains directive). [HSTS] // TODO // 10. If recursive is false, then run the remaining steps in parallel. // TODO // 11. If response is null, then set response to the result of running // the steps corresponding to the first matching statement: if (response === null) { response = await (async () => { const currentURL = requestCurrentURL(request) if ( // - request’s current URL’s origin is same origin with request’s origin, // and request’s response tainting is "basic" (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || // request’s current URL’s scheme is "data" (currentURL.protocol === 'data:') || // - request’s mode is "navigate" or "websocket" (request.mode === 'navigate' || request.mode === 'websocket') ) { // 1. Set request’s response tainting to "basic". request.responseTainting = 'basic' // 2. Return the result of running scheme fetch given fetchParams. return await schemeFetch(fetchParams) } // request’s mode is "same-origin" if (request.mode === 'same-origin') { // 1. Return a network error. return makeNetworkError('request mode cannot be "same-origin"') } // request’s mode is "no-cors" if (request.mode === 'no-cors') { // 1. If request’s redirect mode is not "follow", then return a network // error. if (request.redirect !== 'follow') { return makeNetworkError( 'redirect mode cannot be "follow" for "no-cors" request' ) } // 2. Set request’s response tainting to "opaque". request.responseTainting = 'opaque' // 3. Return the result of running scheme fetch given fetchParams. return await schemeFetch(fetchParams) } // request’s current URL’s scheme is not an HTTP(S) scheme if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { // Return a network error. return makeNetworkError('URL scheme must be a HTTP(S) scheme') } // - request’s use-CORS-preflight flag is set // - request’s unsafe-request flag is set and either request’s method is // not a CORS-safelisted method or CORS-unsafe request-header names with // request’s header list is not empty // 1. Set request’s response tainting to "cors". // 2. Let corsWithPreflightResponse be the result of running HTTP fetch // given fetchParams and true. // 3. If corsWithPreflightResponse is a network error, then clear cache // entries using request. // 4. Return corsWithPreflightResponse. // TODO // Otherwise // 1. Set request’s response tainting to "cors". request.responseTainting = 'cors' // 2. Return the result of running HTTP fetch given fetchParams. return await httpFetch(fetchParams) })() } // 12. If recursive is true, then return response. if (recursive) { return response } // 13. If response is not a network error and response is not a filtered // response, then: if (response.status !== 0 && !response.internalResponse) { // If request’s response tainting is "cors", then: if (request.responseTainting === 'cors') { // 1. Let headerNames be the result of extracting header list values // given `Access-Control-Expose-Headers` and response’s header list. // TODO // 2. If request’s credentials mode is not "include" and headerNames // contains `*`, then set response’s CORS-exposed header-name list to // all unique header names in response’s header list. // TODO // 3. Otherwise, if headerNames is not null or failure, then set // response’s CORS-exposed header-name list to headerNames. // TODO } // Set response to the following filtered response with response as its // internal response, depending on request’s response tainting: if (request.responseTainting === 'basic') { response = filterResponse(response, 'basic') } else if (request.responseTainting === 'cors') { response = filterResponse(response, 'cors') } else if (request.responseTainting === 'opaque') { response = filterResponse(response, 'opaque') } else { assert(false) } } // 14. Let internalResponse be response, if response is a network error, // and response’s internal response otherwise. let internalResponse = response.status === 0 ? response : response.internalResponse // 15. If internalResponse’s URL list is empty, then set it to a clone of // request’s URL list. if (internalResponse.urlList.length === 0) { internalResponse.urlList.push(...request.urlList) } // 16. If request’s timing allow failed flag is unset, then set // internalResponse’s timing allow passed flag. if (!request.timingAllowFailed) { response.timingAllowPassed = true } // 17. If response is not a network error and any of the following returns // blocked // - should internalResponse to request be blocked as mixed content // - should internalResponse to request be blocked by Content Security Policy // - should internalResponse to request be blocked due to its MIME type // - should internalResponse to request be blocked due to nosniff // TODO // 18. If response’s type is "opaque", internalResponse’s status is 206, // internalResponse’s range-requested flag is set, and request’s header // list does not contain `Range`, then set response and internalResponse // to a network error. if ( response.type === 'opaque' && internalResponse.status === 206 && internalResponse.rangeRequested && !request.headers.contains('range', true) ) { response = internalResponse = makeNetworkError() } // 19. If response is not a network error and either request’s method is // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, // set internalResponse’s body to null and disregard any enqueuing toward // it (if any). if ( response.status !== 0 && (request.method === 'HEAD' || request.method === 'CONNECT' || nullBodyStatus.includes(internalResponse.status)) ) { internalResponse.body = null fetchParams.controller.dump = true } // 20. If request’s integrity metadata is not the empty string, then: if (request.integrity) { // 1. Let processBodyError be this step: run fetch finale given fetchParams // and a network error. const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason)) // 2. If request’s response tainting is "opaque", or response’s body is null, // then run processBodyError and abort these steps. if (request.responseTainting === 'opaque' || response.body == null) { processBodyError(response.error) return } // 3. Let processBody given bytes be these steps: const processBody = (bytes) => { // 1. If bytes do not match request’s integrity metadata, // then run processBodyError and abort these steps. [SRI] if (!bytesMatch(bytes, request.integrity)) { processBodyError('integrity mismatch') return } // 2. Set response’s body to bytes as a body. response.body = safelyExtractBody(bytes)[0] // 3. Run fetch finale given fetchParams and response. fetchFinale(fetchParams, response) } // 4. Fully read response’s body given processBody and processBodyError. await fullyReadBody(response.body, processBody, processBodyError) } else { // 21. Otherwise, run fetch finale given fetchParams and response. fetchFinale(fetchParams, response) } } // https://fetch.spec.whatwg.org/#concept-scheme-fetch // given a fetch params fetchParams function schemeFetch (fetchParams) { // Note: since the connection is destroyed on redirect, which sets fetchParams to a // cancelled state, we do not want this condition to trigger *unless* there have been // no redirects. See https://github.com/nodejs/undici/issues/1776 // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { return Promise.resolve(makeAppropriateNetworkError(fetchParams)) } // 2. Let request be fetchParams’s request. const { request } = fetchParams const { protocol: scheme } = requestCurrentURL(request) // 3. Switch on request’s current URL’s scheme and run the associated steps: switch (scheme) { case 'about:': { // If request’s current URL’s path is the string "blank", then return a new response // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », // and body is the empty byte sequence as a body. // Otherwise, return a network error. return Promise.resolve(makeNetworkError('about scheme is not supported')) } case 'blob:': { if (!resolveObjectURL) { resolveObjectURL = (__nccwpck_require__(4573).resolveObjectURL) } // 1. Let blobURLEntry be request’s current URL’s blob URL entry. const blobURLEntry = requestCurrentURL(request) // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 // Buffer.resolveObjectURL does not ignore URL queries. if (blobURLEntry.search.length !== 0) { return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } const blob = resolveObjectURL(blobURLEntry.toString()) // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s // object is not a Blob object, then return a network error. if (request.method !== 'GET' || !isBlobLike(blob)) { return Promise.resolve(makeNetworkError('invalid method')) } // 3. Let blob be blobURLEntry’s object. // Note: done above // 4. Let response be a new response. const response = makeResponse() // 5. Let fullLength be blob’s size. const fullLength = blob.size // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded. const serializedFullLength = isomorphicEncode(`${fullLength}`) // 7. Let type be blob’s type. const type = blob.type // 8. If request’s header list does not contain `Range`: // 9. Otherwise: if (!request.headersList.contains('range', true)) { // 1. Let bodyWithType be the result of safely extracting blob. // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource. // In node, this can only ever be a Blob. Therefore we can safely // use extractBody directly. const bodyWithType = extractBody(blob) // 2. Set response’s status message to `OK`. response.statusText = 'OK' // 3. Set response’s body to bodyWithType’s body. response.body = bodyWithType[0] // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ». response.headersList.set('content-length', serializedFullLength, true) response.headersList.set('content-type', type, true) } else { // 1. Set response’s range-requested flag. response.rangeRequested = true // 2. Let rangeHeader be the result of getting `Range` from request’s header list. const rangeHeader = request.headersList.get('range', true) // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true. const rangeValue = simpleRangeHeaderValue(rangeHeader, true) // 4. If rangeValue is failure, then return a network error. if (rangeValue === 'failure') { return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 5. Let (rangeStart, rangeEnd) be rangeValue. let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue // 6. If rangeStart is null: // 7. Otherwise: if (rangeStart === null) { // 1. Set rangeStart to fullLength − rangeEnd. rangeStart = fullLength - rangeEnd // 2. Set rangeEnd to rangeStart + rangeEnd − 1. rangeEnd = rangeStart + rangeEnd - 1 } else { // 1. If rangeStart is greater than or equal to fullLength, then return a network error. if (rangeStart >= fullLength) { return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.')) } // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set // rangeEnd to fullLength − 1. if (rangeEnd === null || rangeEnd >= fullLength) { rangeEnd = fullLength - 1 } } // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, // rangeEnd + 1, and type. const slicedBlob = blob.slice(rangeStart, rangeEnd, type) // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob. // Note: same reason as mentioned above as to why we use extractBody const slicedBodyWithType = extractBody(slicedBlob) // 10. Set response’s body to slicedBodyWithType’s body. response.body = slicedBodyWithType[0] // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded. const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`) // 12. Let contentRange be the result of invoking build a content range given rangeStart, // rangeEnd, and fullLength. const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength) // 13. Set response’s status to 206. response.status = 206 // 14. Set response’s status message to `Partial Content`. response.statusText = 'Partial Content' // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength), // (`Content-Type`, type), (`Content-Range`, contentRange) ». response.headersList.set('content-length', serializedSlicedLength, true) response.headersList.set('content-type', type, true) response.headersList.set('content-range', contentRange, true) } // 10. Return response. return Promise.resolve(response) } case 'data:': { // 1. Let dataURLStruct be the result of running the // data: URL processor on request’s current URL. const currentURL = requestCurrentURL(request) const dataURLStruct = dataURLProcessor(currentURL) // 2. If dataURLStruct is failure, then return a // network error. if (dataURLStruct === 'failure') { return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 3. Let mimeType be dataURLStruct’s MIME type, serialized. const mimeType = serializeAMimeType(dataURLStruct.mimeType) // 4. Return a response whose status message is `OK`, // header list is « (`Content-Type`, mimeType) », // and body is dataURLStruct’s body as a body. return Promise.resolve(makeResponse({ statusText: 'OK', headersList: [ ['content-type', { name: 'Content-Type', value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] })) } case 'file:': { // For now, unfortunate as it is, file URLs are left as an exercise for the reader. // When in doubt, return a network error. return Promise.resolve(makeNetworkError('not implemented... yet...')) } case 'http:': case 'https:': { // Return the result of running HTTP fetch given fetchParams. return httpFetch(fetchParams) .catch((err) => makeNetworkError(err)) } default: { return Promise.resolve(makeNetworkError('unknown scheme')) } } } // https://fetch.spec.whatwg.org/#finalize-response function finalizeResponse (fetchParams, response) { // 1. Set fetchParams’s request’s done flag. fetchParams.request.done = true // 2, If fetchParams’s process response done is not null, then queue a fetch // task to run fetchParams’s process response done given response, with // fetchParams’s task destination. if (fetchParams.processResponseDone != null) { queueMicrotask(() => fetchParams.processResponseDone(response)) } } // https://fetch.spec.whatwg.org/#fetch-finale function fetchFinale (fetchParams, response) { // 1. Let timingInfo be fetchParams’s timing info. let timingInfo = fetchParams.timingInfo // 2. If response is not a network error and fetchParams’s request’s client is a secure context, // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting // `Server-Timing` from response’s internal response’s header list. // TODO // 3. Let processResponseEndOfBody be the following steps: const processResponseEndOfBody = () => { // 1. Let unsafeEndTime be the unsafe shared current time. const unsafeEndTime = Date.now() // ? // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s // full timing info to fetchParams’s timing info. if (fetchParams.request.destination === 'document') { fetchParams.controller.fullTimingInfo = timingInfo } // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global: fetchParams.controller.reportTimingSteps = () => { // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return. if (fetchParams.request.url.protocol !== 'https:') { return } // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global. timingInfo.endTime = unsafeEndTime // 3. Let cacheState be response’s cache state. let cacheState = response.cacheState // 4. Let bodyInfo be response’s body info. const bodyInfo = response.bodyInfo // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an // opaque timing info for timingInfo and set cacheState to the empty string. if (!response.timingAllowPassed) { timingInfo = createOpaqueTimingInfo(timingInfo) cacheState = '' } // 6. Let responseStatus be 0. let responseStatus = 0 // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false: if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) { // 1. Set responseStatus to response’s status. responseStatus = response.status // 2. Let mimeType be the result of extracting a MIME type from response’s header list. const mimeType = extractMimeType(response.headersList) // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType. if (mimeType !== 'failure') { bodyInfo.contentType = minimizeSupportedMimeType(mimeType) } } // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo, // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo, // and responseStatus. if (fetchParams.request.initiatorType != null) { // TODO: update markresourcetiming markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus) } } // 4. Let processResponseEndOfBodyTask be the following steps: const processResponseEndOfBodyTask = () => { // 1. Set fetchParams’s request’s done flag. fetchParams.request.done = true // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process // response end-of-body given response. if (fetchParams.processResponseEndOfBody != null) { queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) } // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s // global object is fetchParams’s task destination, then run fetchParams’s controller’s report // timing steps given fetchParams’s request’s client’s global object. if (fetchParams.request.initiatorType != null) { fetchParams.controller.reportTimingSteps() } } // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination queueMicrotask(() => processResponseEndOfBodyTask()) } // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s // process response given response, with fetchParams’s task destination. if (fetchParams.processResponse != null) { queueMicrotask(() => { fetchParams.processResponse(response) fetchParams.processResponse = null }) } // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response. const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response) // 6. If internalResponse’s body is null, then run processResponseEndOfBody. // 7. Otherwise: if (internalResponse.body == null) { processResponseEndOfBody() } else { // mcollina: all the following steps of the specs are skipped. // The internal transform stream is not needed. // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541 // 1. Let transformStream be a new TransformStream. // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream. // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm // set to processResponseEndOfBody. // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream. finished(internalResponse.body.stream, () => { processResponseEndOfBody() }) } } // https://fetch.spec.whatwg.org/#http-fetch async function httpFetch (fetchParams) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. Let actualResponse be null. let actualResponse = null // 4. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 5. If request’s service-workers mode is "all", then: if (request.serviceWorkers === 'all') { // TODO } // 6. If response is null, then: if (response === null) { // 1. If makeCORSPreflight is true and one of these conditions is true: // TODO // 2. If request’s redirect mode is "follow", then set request’s // service-workers mode to "none". if (request.redirect === 'follow') { request.serviceWorkers = 'none' } // 3. Set response and actualResponse to the result of running // HTTP-network-or-cache fetch given fetchParams. actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) // 4. If request’s response tainting is "cors" and a CORS check // for request and response returns failure, then return a network error. if ( request.responseTainting === 'cors' && corsCheck(request, response) === 'failure' ) { return makeNetworkError('cors failure') } // 5. If the TAO check for request and response returns failure, then set // request’s timing allow failed flag. if (TAOCheck(request, response) === 'failure') { request.timingAllowFailed = true } } // 7. If either request’s response tainting or response’s type // is "opaque", and the cross-origin resource policy check with // request’s origin, request’s client, request’s destination, // and actualResponse returns blocked, then return a network error. if ( (request.responseTainting === 'opaque' || response.type === 'opaque') && crossOriginResourcePolicyCheck( request.origin, request.client, request.destination, actualResponse ) === 'blocked' ) { return makeNetworkError('blocked') } // 8. If actualResponse’s status is a redirect status, then: if (redirectStatusSet.has(actualResponse.status)) { // 1. If actualResponse’s status is not 303, request’s body is not null, // and the connection uses HTTP/2, then user agents may, and are even // encouraged to, transmit an RST_STREAM frame. // See, https://github.com/whatwg/fetch/issues/1288 if (request.redirect !== 'manual') { fetchParams.controller.connection.destroy(undefined, false) } // 2. Switch on request’s redirect mode: if (request.redirect === 'error') { // Set response to a network error. response = makeNetworkError('unexpected redirect') } else if (request.redirect === 'manual') { // Set response to an opaque-redirect filtered response whose internal // response is actualResponse. // NOTE(spec): On the web this would return an `opaqueredirect` response, // but that doesn't make sense server side. // See https://github.com/nodejs/undici/issues/1193. response = actualResponse } else if (request.redirect === 'follow') { // Set response to the result of running HTTP-redirect fetch given // fetchParams and response. response = await httpRedirectFetch(fetchParams, response) } else { assert(false) } } // 9. Set response’s timing info to timingInfo. response.timingInfo = timingInfo // 10. Return response. return response } // https://fetch.spec.whatwg.org/#http-redirect-fetch function httpRedirectFetch (fetchParams, response) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let actualResponse be response, if response is not a filtered response, // and response’s internal response otherwise. const actualResponse = response.internalResponse ? response.internalResponse : response // 3. Let locationURL be actualResponse’s location URL given request’s current // URL’s fragment. let locationURL try { locationURL = responseLocationURL( actualResponse, requestCurrentURL(request).hash ) // 4. If locationURL is null, then return response. if (locationURL == null) { return response } } catch (err) { // 5. If locationURL is failure, then return a network error. return Promise.resolve(makeNetworkError(err)) } // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network // error. if (!urlIsHttpHttpsScheme(locationURL)) { return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) } // 7. If request’s redirect count is 20, then return a network error. if (request.redirectCount === 20) { return Promise.resolve(makeNetworkError('redirect count exceeded')) } // 8. Increase request’s redirect count by 1. request.redirectCount += 1 // 9. If request’s mode is "cors", locationURL includes credentials, and // request’s origin is not same origin with locationURL’s origin, then return // a network error. if ( request.mode === 'cors' && (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL) ) { return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) } // 10. If request’s response tainting is "cors" and locationURL includes // credentials, then return a network error. if ( request.responseTainting === 'cors' && (locationURL.username || locationURL.password) ) { return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' )) } // 11. If actualResponse’s status is not 303, request’s body is non-null, // and request’s body’s source is null, then return a network error. if ( actualResponse.status !== 303 && request.body != null && request.body.source == null ) { return Promise.resolve(makeNetworkError()) } // 12. If one of the following is true // - actualResponse’s status is 301 or 302 and request’s method is `POST` // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && !GET_OR_HEAD.includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. request.method = 'GET' request.body = null // 2. For each headerName of request-body-header name, delete headerName from // request’s header list. for (const headerName of requestBodyHeader) { request.headersList.delete(headerName) } } // 13. If request’s current URL’s origin is not same origin with locationURL’s // origin, then for each headerName of CORS non-wildcard request-header name, // delete headerName from request’s header list. if (!sameOrigin(requestCurrentURL(request), locationURL)) { // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name request.headersList.delete('authorization', true) // https://fetch.spec.whatwg.org/#authentication-entries request.headersList.delete('proxy-authorization', true) // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. request.headersList.delete('cookie', true) request.headersList.delete('host', true) } // 14. If request’s body is non-null, then set request’s body to the first return // value of safely extracting request’s body’s source. if (request.body != null) { assert(request.body.source != null) request.body = safelyExtractBody(request.body.source)[0] } // 15. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 16. Set timingInfo’s redirect end time and post-redirect start time to the // coarsened shared current time given fetchParams’s cross-origin isolated // capability. timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s // redirect start time to timingInfo’s start time. if (timingInfo.redirectStartTime === 0) { timingInfo.redirectStartTime = timingInfo.startTime } // 18. Append locationURL to request’s URL list. request.urlList.push(locationURL) // 19. Invoke set request’s referrer policy on redirect on request and // actualResponse. setRequestReferrerPolicyOnRedirect(request, actualResponse) // 20. Return the result of running main fetch given fetchParams and true. return mainFetch(fetchParams, true) } // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch async function httpNetworkOrCacheFetch ( fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false ) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let httpFetchParams be null. let httpFetchParams = null // 3. Let httpRequest be null. let httpRequest = null // 4. Let response be null. let response = null // 5. Let storedResponse be null. // TODO: cache // 6. Let httpCache be null. const httpCache = null // 7. Let the revalidatingFlag be unset. const revalidatingFlag = false // 8. Run these steps, but abort when the ongoing fetch is terminated: // 1. If request’s window is "no-window" and request’s redirect mode is // "error", then set httpFetchParams to fetchParams and httpRequest to // request. if (request.window === 'no-window' && request.redirect === 'error') { httpFetchParams = fetchParams httpRequest = request } else { // Otherwise: // 1. Set httpRequest to a clone of request. httpRequest = cloneRequest(request) // 2. Set httpFetchParams to a copy of fetchParams. httpFetchParams = { ...fetchParams } // 3. Set httpFetchParams’s request to httpRequest. httpFetchParams.request = httpRequest } // 3. Let includeCredentials be true if one of const includeCredentials = request.credentials === 'include' || (request.credentials === 'same-origin' && request.responseTainting === 'basic') // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s // body is non-null; otherwise null. const contentLength = httpRequest.body ? httpRequest.body.length : null // 5. Let contentLengthHeaderValue be null. let contentLengthHeaderValue = null // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or // `PUT`, then set contentLengthHeaderValue to `0`. if ( httpRequest.body == null && ['POST', 'PUT'].includes(httpRequest.method) ) { contentLengthHeaderValue = '0' } // 7. If contentLength is non-null, then set contentLengthHeaderValue to // contentLength, serialized and isomorphic encoded. if (contentLength != null) { contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) } // 8. If contentLengthHeaderValue is non-null, then append // `Content-Length`/contentLengthHeaderValue to httpRequest’s header // list. if (contentLengthHeaderValue != null) { httpRequest.headersList.append('content-length', contentLengthHeaderValue, true) } // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, // contentLengthHeaderValue) to httpRequest’s header list. // 10. If contentLength is non-null and httpRequest’s keepalive is true, // then: if (contentLength != null && httpRequest.keepalive) { // NOTE: keepalive is a noop outside of browser context. } // 11. If httpRequest’s referrer is a URL, then append // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, // to httpRequest’s header list. if (httpRequest.referrer instanceof URL) { httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true) } // 12. Append a request `Origin` header for httpRequest. appendRequestOriginHeader(httpRequest) // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] appendFetchMetadata(httpRequest) // 14. If httpRequest’s header list does not contain `User-Agent`, then // user agents should append `User-Agent`/default `User-Agent` value to // httpRequest’s header list. if (!httpRequest.headersList.contains('user-agent', true)) { httpRequest.headersList.append('user-agent', defaultUserAgent) } // 15. If httpRequest’s cache mode is "default" and httpRequest’s header // list contains `If-Modified-Since`, `If-None-Match`, // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set // httpRequest’s cache mode to "no-store". if ( httpRequest.cache === 'default' && (httpRequest.headersList.contains('if-modified-since', true) || httpRequest.headersList.contains('if-none-match', true) || httpRequest.headersList.contains('if-unmodified-since', true) || httpRequest.headersList.contains('if-match', true) || httpRequest.headersList.contains('if-range', true)) ) { httpRequest.cache = 'no-store' } // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent // no-cache cache-control header modification flag is unset, and // httpRequest’s header list does not contain `Cache-Control`, then append // `Cache-Control`/`max-age=0` to httpRequest’s header list. if ( httpRequest.cache === 'no-cache' && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains('cache-control', true) ) { httpRequest.headersList.append('cache-control', 'max-age=0', true) } // 17. If httpRequest’s cache mode is "no-store" or "reload", then: if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { // 1. If httpRequest’s header list does not contain `Pragma`, then append // `Pragma`/`no-cache` to httpRequest’s header list. if (!httpRequest.headersList.contains('pragma', true)) { httpRequest.headersList.append('pragma', 'no-cache', true) } // 2. If httpRequest’s header list does not contain `Cache-Control`, // then append `Cache-Control`/`no-cache` to httpRequest’s header list. if (!httpRequest.headersList.contains('cache-control', true)) { httpRequest.headersList.append('cache-control', 'no-cache', true) } } // 18. If httpRequest’s header list contains `Range`, then append // `Accept-Encoding`/`identity` to httpRequest’s header list. if (httpRequest.headersList.contains('range', true)) { httpRequest.headersList.append('accept-encoding', 'identity', true) } // 19. Modify httpRequest’s header list per HTTP. Do not append a given // header if httpRequest’s header list contains that header’s name. // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 if (!httpRequest.headersList.contains('accept-encoding', true)) { if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true) } else { httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true) } } httpRequest.headersList.delete('host', true) // 20. If includeCredentials is true, then: if (includeCredentials) { // 1. If the user agent is not configured to block cookies for httpRequest // (see section 7 of [COOKIES]), then: // TODO: credentials // 2. If httpRequest’s header list does not contain `Authorization`, then: // TODO: credentials } // 21. If there’s a proxy-authentication entry, use it as appropriate. // TODO: proxy-authentication // 22. Set httpCache to the result of determining the HTTP cache // partition, given httpRequest. // TODO: cache // 23. If httpCache is null, then set httpRequest’s cache mode to // "no-store". if (httpCache == null) { httpRequest.cache = 'no-store' } // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", // then: if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') { // TODO: cache } // 9. If aborted, then return the appropriate network error for fetchParams. // TODO // 10. If response is null, then: if (response == null) { // 1. If httpRequest’s cache mode is "only-if-cached", then return a // network error. if (httpRequest.cache === 'only-if-cached') { return makeNetworkError('only if cached') } // 2. Let forwardResponse be the result of running HTTP-network fetch // given httpFetchParams, includeCredentials, and isNewConnectionFetch. const forwardResponse = await httpNetworkFetch( httpFetchParams, includeCredentials, isNewConnectionFetch ) // 3. If httpRequest’s method is unsafe and forwardResponse’s status is // in the range 200 to 399, inclusive, invalidate appropriate stored // responses in httpCache, as per the "Invalidation" chapter of HTTP // Caching, and set storedResponse to null. [HTTP-CACHING] if ( !safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399 ) { // TODO: cache } // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, // then: if (revalidatingFlag && forwardResponse.status === 304) { // TODO: cache } // 5. If response is null, then: if (response == null) { // 1. Set response to forwardResponse. response = forwardResponse // 2. Store httpRequest and forwardResponse in httpCache, as per the // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] // TODO: cache } } // 11. Set response’s URL list to a clone of httpRequest’s URL list. response.urlList = [...httpRequest.urlList] // 12. If httpRequest’s header list contains `Range`, then set response’s // range-requested flag. if (httpRequest.headersList.contains('range', true)) { response.rangeRequested = true } // 13. Set response’s request-includes-credentials to includeCredentials. response.requestIncludesCredentials = includeCredentials // 14. If response’s status is 401, httpRequest’s response tainting is not // "cors", includeCredentials is true, and request’s window is an environment // settings object, then: // TODO // 15. If response’s status is 407, then: if (response.status === 407) { // 1. If request’s window is "no-window", then return a network error. if (request.window === 'no-window') { return makeNetworkError() } // 2. ??? // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams)) { return makeAppropriateNetworkError(fetchParams) } // 4. Prompt the end user as appropriate in request’s window and store // the result as a proxy-authentication entry. [HTTP-AUTH] // TODO: Invoke some kind of callback? // 5. Set response to the result of running HTTP-network-or-cache fetch given // fetchParams. // TODO return makeNetworkError('proxy authentication required') } // 16. If all of the following are true if ( // response’s status is 421 response.status === 421 && // isNewConnectionFetch is false !isNewConnectionFetch && // request’s body is null, or request’s body is non-null and request’s body’s source is non-null (request.body == null || request.body.source != null) ) { // then: // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams)) { return makeAppropriateNetworkError(fetchParams) } // 2. Set response to the result of running HTTP-network-or-cache // fetch given fetchParams, isAuthenticationFetch, and true. // TODO (spec): The spec doesn't specify this but we need to cancel // the active response before we can start a new one. // https://github.com/whatwg/fetch/issues/1293 fetchParams.controller.connection.destroy() response = await httpNetworkOrCacheFetch( fetchParams, isAuthenticationFetch, true ) } // 17. If isAuthenticationFetch is true, then create an authentication entry if (isAuthenticationFetch) { // TODO } // 18. Return response. return response } // https://fetch.spec.whatwg.org/#http-network-fetch async function httpNetworkFetch ( fetchParams, includeCredentials = false, forceNewConnection = false ) { assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) fetchParams.controller.connection = { abort: null, destroyed: false, destroy (err, abort = true) { if (!this.destroyed) { this.destroyed = true if (abort) { this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) } } } } // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 4. Let httpCache be the result of determining the HTTP cache partition, // given request. // TODO: cache const httpCache = null // 5. If httpCache is null, then set request’s cache mode to "no-store". if (httpCache == null) { request.cache = 'no-store' } // 6. Let networkPartitionKey be the result of determining the network // partition key given request. // TODO // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise // "no". const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars // 8. Switch on request’s mode: if (request.mode === 'websocket') { // Let connection be the result of obtaining a WebSocket connection, // given request’s current URL. // TODO } else { // Let connection be the result of obtaining a connection, given // networkPartitionKey, request’s current URL’s origin, // includeCredentials, and forceNewConnection. // TODO } // 9. Run these steps, but abort when the ongoing fetch is terminated: // 1. If connection is failure, then return a network error. // 2. Set timingInfo’s final connection timing info to the result of // calling clamp and coarsen connection timing info with connection’s // timing info, timingInfo’s post-redirect start time, and fetchParams’s // cross-origin isolated capability. // 3. If connection is not an HTTP/2 connection, request’s body is non-null, // and request’s body’s source is null, then append (`Transfer-Encoding`, // `chunked`) to request’s header list. // 4. Set timingInfo’s final network-request start time to the coarsened // shared current time given fetchParams’s cross-origin isolated // capability. // 5. Set response to the result of making an HTTP request over connection // using request with the following caveats: // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] // - If request’s body is non-null, and request’s body’s source is null, // then the user agent may have a buffer of up to 64 kibibytes and store // a part of request’s body in that buffer. If the user agent reads from // request’s body beyond that buffer’s size and the user agent needs to // resend request, then instead return a network error. // - Set timingInfo’s final network-response start time to the coarsened // shared current time given fetchParams’s cross-origin isolated capability, // immediately after the user agent’s HTTP parser receives the first byte // of the response (e.g., frame header bytes for HTTP/2 or response status // line for HTTP/1.x). // - Wait until all the headers are transmitted. // - Any responses whose status is in the range 100 to 199, inclusive, // and is not 101, are to be ignored, except for the purposes of setting // timingInfo’s final network-response start time above. // - If request’s header list contains `Transfer-Encoding`/`chunked` and // response is transferred via HTTP/1.0 or older, then return a network // error. // - If the HTTP request results in a TLS client certificate dialog, then: // 1. If request’s window is an environment settings object, make the // dialog available in request’s window. // 2. Otherwise, return a network error. // To transmit request’s body body, run these steps: let requestBody = null // 1. If body is null and fetchParams’s process request end-of-body is // non-null, then queue a fetch task given fetchParams’s process request // end-of-body and fetchParams’s task destination. if (request.body == null && fetchParams.processRequestEndOfBody) { queueMicrotask(() => fetchParams.processRequestEndOfBody()) } else if (request.body != null) { // 2. Otherwise, if body is non-null: // 1. Let processBodyChunk given bytes be these steps: const processBodyChunk = async function * (bytes) { // 1. If the ongoing fetch is terminated, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. Run this step in parallel: transmit bytes. yield bytes // 3. If fetchParams’s process request body is non-null, then run // fetchParams’s process request body given bytes’s length. fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) } // 2. Let processEndOfBody be these steps: const processEndOfBody = () => { // 1. If fetchParams is canceled, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. If fetchParams’s process request end-of-body is non-null, // then run fetchParams’s process request end-of-body. if (fetchParams.processRequestEndOfBody) { fetchParams.processRequestEndOfBody() } } // 3. Let processBodyError given e be these steps: const processBodyError = (e) => { // 1. If fetchParams is canceled, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. if (e.name === 'AbortError') { fetchParams.controller.abort() } else { fetchParams.controller.terminate(e) } } // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, // processBodyError, and fetchParams’s task destination. requestBody = (async function * () { try { for await (const bytes of request.body.stream) { yield * processBodyChunk(bytes) } processEndOfBody() } catch (err) { processBodyError(err) } })() } try { // socket is only provided for websockets const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) if (socket) { response = makeResponse({ status, statusText, headersList, socket }) } else { const iterator = body[Symbol.asyncIterator]() fetchParams.controller.next = () => iterator.next() response = makeResponse({ status, statusText, headersList }) } } catch (err) { // 10. If aborted, then: if (err.name === 'AbortError') { // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. fetchParams.controller.connection.destroy() // 2. Return the appropriate network error for fetchParams. return makeAppropriateNetworkError(fetchParams, err) } return makeNetworkError(err) } // 11. Let pullAlgorithm be an action that resumes the ongoing fetch // if it is suspended. const pullAlgorithm = async () => { await fetchParams.controller.resume() } // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s // controller with reason, given reason. const cancelAlgorithm = (reason) => { // If the aborted fetch was already terminated, then we do not // need to do anything. if (!isCancelled(fetchParams)) { fetchParams.controller.abort(reason) } } // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by // the user agent. // TODO // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. // TODO // 15. Let stream be a new ReadableStream. // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, // cancelAlgorithm set to cancelAlgorithm. const stream = new ReadableStream( { async start (controller) { fetchParams.controller.controller = controller }, async pull (controller) { await pullAlgorithm(controller) }, async cancel (reason) { await cancelAlgorithm(reason) }, type: 'bytes' } ) // 17. Run these steps, but abort when the ongoing fetch is terminated: // 1. Set response’s body to a new body whose stream is stream. response.body = { stream, source: null, length: null } // 2. If response is not a network error and request’s cache mode is // not "no-store", then update response in httpCache for request. // TODO // 3. If includeCredentials is true and the user agent is not configured // to block cookies for request (see section 7 of [COOKIES]), then run the // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on // the value of each header whose name is a byte-case-insensitive match for // `Set-Cookie` in response’s header list, if any, and request’s current URL. // TODO // 18. If aborted, then: // TODO // 19. Run these steps in parallel: // 1. Run these steps, but abort when fetchParams is canceled: fetchParams.controller.onAborted = onAborted fetchParams.controller.on('terminated', onAborted) fetchParams.controller.resume = async () => { // 1. While true while (true) { // 1-3. See onData... // 4. Set bytes to the result of handling content codings given // codings and bytes. let bytes let isFailure try { const { done, value } = await fetchParams.controller.next() if (isAborted(fetchParams)) { break } bytes = done ? undefined : value } catch (err) { if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { // zlib doesn't like empty streams. bytes = undefined } else { bytes = err // err may be propagated from the result of calling readablestream.cancel, // which might not be an error. https://github.com/nodejs/undici/issues/2009 isFailure = true } } if (bytes === undefined) { // 2. Otherwise, if the bytes transmission for response’s message // body is done normally and stream is readable, then close // stream, finalize response for fetchParams and response, and // abort these in-parallel steps. readableStreamClose(fetchParams.controller.controller) finalizeResponse(fetchParams, response) return } // 5. Increase timingInfo’s decoded body size by bytes’s length. timingInfo.decodedBodySize += bytes?.byteLength ?? 0 // 6. If bytes is failure, then terminate fetchParams’s controller. if (isFailure) { fetchParams.controller.terminate(bytes) return } // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes // into stream. const buffer = new Uint8Array(bytes) if (buffer.byteLength) { fetchParams.controller.controller.enqueue(buffer) } // 8. If stream is errored, then terminate the ongoing fetch. if (isErrored(stream)) { fetchParams.controller.terminate() return } // 9. If stream doesn’t need more data ask the user agent to suspend // the ongoing fetch. if (fetchParams.controller.controller.desiredSize <= 0) { return } } } // 2. If aborted, then: function onAborted (reason) { // 2. If fetchParams is aborted, then: if (isAborted(fetchParams)) { // 1. Set response’s aborted flag. response.aborted = true // 2. If stream is readable, then error stream with the result of // deserialize a serialized abort reason given fetchParams’s // controller’s serialized abort reason and an // implementation-defined realm. if (isReadable(stream)) { fetchParams.controller.controller.error( fetchParams.controller.serializedAbortReason ) } } else { // 3. Otherwise, if stream is readable, error stream with a TypeError. if (isReadable(stream)) { fetchParams.controller.controller.error(new TypeError('terminated', { cause: isErrorLike(reason) ? reason : undefined })) } } // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. fetchParams.controller.connection.destroy() } // 20. Return response. return response function dispatch ({ body }) { const url = requestCurrentURL(request) /** @type {import('../..').Agent} */ const agent = fetchParams.controller.dispatcher return new Promise((resolve, reject) => agent.dispatch( { path: url.pathname + url.search, origin: url.origin, method: request.method, body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body, headers: request.headersList.entries, maxRedirections: 0, upgrade: request.mode === 'websocket' ? 'websocket' : undefined }, { body: null, abort: null, onConnect (abort) { // TODO (fix): Do we need connection here? const { connection } = fetchParams.controller // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen // connection timing info with connection’s timing info, timingInfo’s post-redirect start // time, and fetchParams’s cross-origin isolated capability. // TODO: implement connection timing timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability) if (connection.destroyed) { abort(new DOMException('The operation was aborted.', 'AbortError')) } else { fetchParams.controller.on('terminated', abort) this.abort = connection.abort = abort } // Set timingInfo’s final network-request start time to the coarsened shared current time given // fetchParams’s cross-origin isolated capability. timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) }, onResponseStarted () { // Set timingInfo’s final network-response start time to the coarsened shared current // time given fetchParams’s cross-origin isolated capability, immediately after the // user agent’s HTTP parser receives the first byte of the response (e.g., frame header // bytes for HTTP/2 or response status line for HTTP/1.x). timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) }, onHeaders (status, rawHeaders, resume, statusText) { if (status < 200) { return } let location = '' const headersList = new HeadersList() for (let i = 0; i < rawHeaders.length; i += 2) { headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) } location = headersList.get('location', true) this.body = new Readable({ read: resume }) const decoders = [] const willFollow = location && request.redirect === 'follow' && redirectStatusSet.has(status) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 const contentEncoding = headersList.get('content-encoding', true) // "All content-coding values are case-insensitive..." /** @type {string[]} */ const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : [] // Limit the number of content-encodings to prevent resource exhaustion. // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206). const maxContentEncodings = 5 if (codings.length > maxContentEncodings) { reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`)) return true } for (let i = codings.length - 1; i >= 0; --i) { const coding = codings[i].trim() // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 if (coding === 'x-gzip' || coding === 'gzip') { decoders.push(zlib.createGunzip({ // Be less strict when decoding compressed responses, since sometimes // servers send slightly invalid responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH })) } else if (coding === 'deflate') { decoders.push(createInflate({ flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH })) } else if (coding === 'br') { decoders.push(zlib.createBrotliDecompress({ flush: zlib.constants.BROTLI_OPERATION_FLUSH, finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH })) } else { decoders.length = 0 break } } } const onError = this.onError.bind(this) resolve({ status, statusText, headersList, body: decoders.length ? pipeline(this.body, ...decoders, (err) => { if (err) { this.onError(err) } }).on('error', onError) : this.body.on('error', onError) }) return true }, onData (chunk) { if (fetchParams.controller.dump) { return } // 1. If one or more bytes have been transmitted from response’s // message body, then: // 1. Let bytes be the transmitted bytes. const bytes = chunk // 2. Let codings be the result of extracting header list values // given `Content-Encoding` and response’s header list. // See pullAlgorithm. // 3. Increase timingInfo’s encoded body size by bytes’s length. timingInfo.encodedBodySize += bytes.byteLength // 4. See pullAlgorithm... return this.body.push(bytes) }, onComplete () { if (this.abort) { fetchParams.controller.off('terminated', this.abort) } if (fetchParams.controller.onAborted) { fetchParams.controller.off('terminated', fetchParams.controller.onAborted) } fetchParams.controller.ended = true this.body.push(null) }, onError (error) { if (this.abort) { fetchParams.controller.off('terminated', this.abort) } this.body?.destroy(error) fetchParams.controller.terminate(error) reject(error) }, onUpgrade (status, rawHeaders, socket) { if (status !== 101) { return } const headersList = new HeadersList() for (let i = 0; i < rawHeaders.length; i += 2) { headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) } resolve({ status, statusText: STATUS_CODES[status], headersList, socket }) return true } } )) } } module.exports = { fetch, Fetch, fetching, finalizeAndReportTiming } /***/ }), /***/ 9967: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* globals AbortController */ const { extractBody, mixinBody, cloneBody, bodyUnusable } = __nccwpck_require__(4492) const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = __nccwpck_require__(660) const { FinalizationRegistry } = __nccwpck_require__(6653)() const util = __nccwpck_require__(3440) const nodeUtil = __nccwpck_require__(7975) const { isValidHTTPToken, sameOrigin, environmentSettingsObject } = __nccwpck_require__(3168) const { forbiddenMethodsSet, corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, requestCredentials, requestCache, requestDuplex } = __nccwpck_require__(4495) const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util const { kHeaders, kSignal, kState, kDispatcher } = __nccwpck_require__(3627) const { webidl } = __nccwpck_require__(5893) const { URLSerializer } = __nccwpck_require__(1900) const { kConstruct } = __nccwpck_require__(6443) const assert = __nccwpck_require__(4589) const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(8474) const kAbortController = Symbol('abortController') const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { signal.removeEventListener('abort', abort) }) const dependentControllerMap = new WeakMap() function buildAbort (acRef) { return abort function abort () { const ac = acRef.deref() if (ac !== undefined) { // Currently, there is a problem with FinalizationRegistry. // https://github.com/nodejs/node/issues/49344 // https://github.com/nodejs/node/issues/47748 // In the case of abort, the first step is to unregister from it. // If the controller can refer to it, it is still registered. // It will be removed in the future. requestFinalizer.unregister(abort) // Unsubscribe a listener. // FinalizationRegistry will no longer be called, so this must be done. this.removeEventListener('abort', abort) ac.abort(this.reason) const controllerList = dependentControllerMap.get(ac.signal) if (controllerList !== undefined) { if (controllerList.size !== 0) { for (const ref of controllerList) { const ctrl = ref.deref() if (ctrl !== undefined) { ctrl.abort(this.reason) } } controllerList.clear() } dependentControllerMap.delete(ac.signal) } } } } let patchMethodWarning = false // https://fetch.spec.whatwg.org/#request-class class Request { // https://fetch.spec.whatwg.org/#dom-request constructor (input, init = {}) { webidl.util.markAsUncloneable(this) if (input === kConstruct) { return } const prefix = 'Request constructor' webidl.argumentLengthCheck(arguments, 1, prefix) input = webidl.converters.RequestInfo(input, prefix, 'input') init = webidl.converters.RequestInit(init, prefix, 'init') // 1. Let request be null. let request = null // 2. Let fallbackMode be null. let fallbackMode = null // 3. Let baseURL be this’s relevant settings object’s API base URL. const baseUrl = environmentSettingsObject.settingsObject.baseUrl // 4. Let signal be null. let signal = null // 5. If input is a string, then: if (typeof input === 'string') { this[kDispatcher] = init.dispatcher // 1. Let parsedURL be the result of parsing input with baseURL. // 2. If parsedURL is failure, then throw a TypeError. let parsedURL try { parsedURL = new URL(input, baseUrl) } catch (err) { throw new TypeError('Failed to parse URL from ' + input, { cause: err }) } // 3. If parsedURL includes credentials, then throw a TypeError. if (parsedURL.username || parsedURL.password) { throw new TypeError( 'Request cannot be constructed from a URL that includes credentials: ' + input ) } // 4. Set request to a new request whose URL is parsedURL. request = makeRequest({ urlList: [parsedURL] }) // 5. Set fallbackMode to "cors". fallbackMode = 'cors' } else { this[kDispatcher] = init.dispatcher || input[kDispatcher] // 6. Otherwise: // 7. Assert: input is a Request object. assert(input instanceof Request) // 8. Set request to input’s request. request = input[kState] // 9. Set signal to input’s signal. signal = input[kSignal] } // 7. Let origin be this’s relevant settings object’s origin. const origin = environmentSettingsObject.settingsObject.origin // 8. Let window be "client". let window = 'client' // 9. If request’s window is an environment settings object and its origin // is same origin with origin, then set window to request’s window. if ( request.window?.constructor?.name === 'EnvironmentSettingsObject' && sameOrigin(request.window, origin) ) { window = request.window } // 10. If init["window"] exists and is non-null, then throw a TypeError. if (init.window != null) { throw new TypeError(`'window' option '${window}' must be null`) } // 11. If init["window"] exists, then set window to "no-window". if ('window' in init) { window = 'no-window' } // 12. Set request to a new request with the following properties: request = makeRequest({ // URL request’s URL. // undici implementation note: this is set as the first item in request's urlList in makeRequest // method request’s method. method: request.method, // header list A copy of request’s header list. // undici implementation note: headersList is cloned in makeRequest headersList: request.headersList, // unsafe-request flag Set. unsafeRequest: request.unsafeRequest, // client This’s relevant settings object. client: environmentSettingsObject.settingsObject, // window window. window, // priority request’s priority. priority: request.priority, // origin request’s origin. The propagation of the origin is only significant for navigation requests // being handled by a service worker. In this scenario a request can have an origin that is different // from the current client. origin: request.origin, // referrer request’s referrer. referrer: request.referrer, // referrer policy request’s referrer policy. referrerPolicy: request.referrerPolicy, // mode request’s mode. mode: request.mode, // credentials mode request’s credentials mode. credentials: request.credentials, // cache mode request’s cache mode. cache: request.cache, // redirect mode request’s redirect mode. redirect: request.redirect, // integrity metadata request’s integrity metadata. integrity: request.integrity, // keepalive request’s keepalive. keepalive: request.keepalive, // reload-navigation flag request’s reload-navigation flag. reloadNavigation: request.reloadNavigation, // history-navigation flag request’s history-navigation flag. historyNavigation: request.historyNavigation, // URL list A clone of request’s URL list. urlList: [...request.urlList] }) const initHasKey = Object.keys(init).length !== 0 // 13. If init is not empty, then: if (initHasKey) { // 1. If request’s mode is "navigate", then set it to "same-origin". if (request.mode === 'navigate') { request.mode = 'same-origin' } // 2. Unset request’s reload-navigation flag. request.reloadNavigation = false // 3. Unset request’s history-navigation flag. request.historyNavigation = false // 4. Set request’s origin to "client". request.origin = 'client' // 5. Set request’s referrer to "client" request.referrer = 'client' // 6. Set request’s referrer policy to the empty string. request.referrerPolicy = '' // 7. Set request’s URL to request’s current URL. request.url = request.urlList[request.urlList.length - 1] // 8. Set request’s URL list to « request’s URL ». request.urlList = [request.url] } // 14. If init["referrer"] exists, then: if (init.referrer !== undefined) { // 1. Let referrer be init["referrer"]. const referrer = init.referrer // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". if (referrer === '') { request.referrer = 'no-referrer' } else { // 1. Let parsedReferrer be the result of parsing referrer with // baseURL. // 2. If parsedReferrer is failure, then throw a TypeError. let parsedReferrer try { parsedReferrer = new URL(referrer, baseUrl) } catch (err) { throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) } // 3. If one of the following is true // - parsedReferrer’s scheme is "about" and path is the string "client" // - parsedReferrer’s origin is not same origin with origin // then set request’s referrer to "client". if ( (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) ) { request.referrer = 'client' } else { // 4. Otherwise, set request’s referrer to parsedReferrer. request.referrer = parsedReferrer } } } // 15. If init["referrerPolicy"] exists, then set request’s referrer policy // to it. if (init.referrerPolicy !== undefined) { request.referrerPolicy = init.referrerPolicy } // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. let mode if (init.mode !== undefined) { mode = init.mode } else { mode = fallbackMode } // 17. If mode is "navigate", then throw a TypeError. if (mode === 'navigate') { throw webidl.errors.exception({ header: 'Request constructor', message: 'invalid request mode navigate.' }) } // 18. If mode is non-null, set request’s mode to mode. if (mode != null) { request.mode = mode } // 19. If init["credentials"] exists, then set request’s credentials mode // to it. if (init.credentials !== undefined) { request.credentials = init.credentials } // 18. If init["cache"] exists, then set request’s cache mode to it. if (init.cache !== undefined) { request.cache = init.cache } // 21. If request’s cache mode is "only-if-cached" and request’s mode is // not "same-origin", then throw a TypeError. if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { throw new TypeError( "'only-if-cached' can be set only with 'same-origin' mode" ) } // 22. If init["redirect"] exists, then set request’s redirect mode to it. if (init.redirect !== undefined) { request.redirect = init.redirect } // 23. If init["integrity"] exists, then set request’s integrity metadata to it. if (init.integrity != null) { request.integrity = String(init.integrity) } // 24. If init["keepalive"] exists, then set request’s keepalive to it. if (init.keepalive !== undefined) { request.keepalive = Boolean(init.keepalive) } // 25. If init["method"] exists, then: if (init.method !== undefined) { // 1. Let method be init["method"]. let method = init.method const mayBeNormalized = normalizedMethodRecords[method] if (mayBeNormalized !== undefined) { // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones request.method = mayBeNormalized } else { // 2. If method is not a method or method is a forbidden method, then // throw a TypeError. if (!isValidHTTPToken(method)) { throw new TypeError(`'${method}' is not a valid HTTP method.`) } const upperCase = method.toUpperCase() if (forbiddenMethodsSet.has(upperCase)) { throw new TypeError(`'${method}' HTTP method is unsupported.`) } // 3. Normalize method. // https://fetch.spec.whatwg.org/#concept-method-normalize // Note: must be in uppercase method = normalizedMethodRecordsBase[upperCase] ?? method // 4. Set request’s method to method. request.method = method } if (!patchMethodWarning && request.method === 'patch') { process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', { code: 'UNDICI-FETCH-patch' }) patchMethodWarning = true } } // 26. If init["signal"] exists, then set signal to it. if (init.signal !== undefined) { signal = init.signal } // 27. Set this’s request to request. this[kState] = request // 28. Set this’s signal to a new AbortSignal object with this’s relevant // Realm. // TODO: could this be simplified with AbortSignal.any // (https://dom.spec.whatwg.org/#dom-abortsignal-any) const ac = new AbortController() this[kSignal] = ac.signal // 29. If signal is not null, then make this’s signal follow signal. if (signal != null) { if ( !signal || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function' ) { throw new TypeError( "Failed to construct 'Request': member signal is not of type AbortSignal." ) } if (signal.aborted) { ac.abort(signal.reason) } else { // Keep a strong ref to ac while request object // is alive. This is needed to prevent AbortController // from being prematurely garbage collected. // See, https://github.com/nodejs/undici/issues/1926. this[kAbortController] = ac const acRef = new WeakRef(ac) const abort = buildAbort(acRef) // Third-party AbortControllers may not work with these. // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. try { // If the max amount of listeners is equal to the default, increase it // This is only available in node >= v19.9.0 if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { setMaxListeners(1500, signal) } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { setMaxListeners(1500, signal) } } catch {} util.addAbortListener(signal, abort) // The third argument must be a registry key to be unregistered. // Without it, you cannot unregister. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry // abort is used as the unregister key. (because it is unique) requestFinalizer.register(ac, { signal, abort }, abort) } } // 30. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is request’s header list and guard is // "request". this[kHeaders] = new Headers(kConstruct) setHeadersList(this[kHeaders], request.headersList) setHeadersGuard(this[kHeaders], 'request') // 31. If this’s request’s mode is "no-cors", then: if (mode === 'no-cors') { // 1. If this’s request’s method is not a CORS-safelisted method, // then throw a TypeError. if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ) } // 2. Set this’s headers’s guard to "request-no-cors". setHeadersGuard(this[kHeaders], 'request-no-cors') } // 32. If init is not empty, then: if (initHasKey) { /** @type {HeadersList} */ const headersList = getHeadersList(this[kHeaders]) // 1. Let headers be a copy of this’s headers and its associated header // list. // 2. If init["headers"] exists, then set headers to init["headers"]. const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) // 3. Empty this’s headers’s header list. headersList.clear() // 4. If headers is a Headers object, then for each header in its header // list, append header’s name/header’s value to this’s headers. if (headers instanceof HeadersList) { for (const { name, value } of headers.rawValues()) { headersList.append(name, value, false) } // Note: Copy the `set-cookie` meta-data. headersList.cookies = headers.cookies } else { // 5. Otherwise, fill this’s headers with headers. fillHeaders(this[kHeaders], headers) } } // 33. Let inputBody be input’s request’s body if input is a Request // object; otherwise null. const inputBody = input instanceof Request ? input[kState].body : null // 34. If either init["body"] exists and is non-null or inputBody is // non-null, and request’s method is `GET` or `HEAD`, then throw a // TypeError. if ( (init.body != null || inputBody != null) && (request.method === 'GET' || request.method === 'HEAD') ) { throw new TypeError('Request with GET/HEAD method cannot have body.') } // 35. Let initBody be null. let initBody = null // 36. If init["body"] exists and is non-null, then: if (init.body != null) { // 1. Let Content-Type be null. // 2. Set initBody and Content-Type to the result of extracting // init["body"], with keepalive set to request’s keepalive. const [extractedBody, contentType] = extractBody( init.body, request.keepalive ) initBody = extractedBody // 3, If Content-Type is non-null and this’s headers’s header list does // not contain `Content-Type`, then append `Content-Type`/Content-Type to // this’s headers. if (contentType && !getHeadersList(this[kHeaders]).contains('content-type', true)) { this[kHeaders].append('content-type', contentType) } } // 37. Let inputOrInitBody be initBody if it is non-null; otherwise // inputBody. const inputOrInitBody = initBody ?? inputBody // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is // null, then: if (inputOrInitBody != null && inputOrInitBody.source == null) { // 1. If initBody is non-null and init["duplex"] does not exist, // then throw a TypeError. if (initBody != null && init.duplex == null) { throw new TypeError('RequestInit: duplex option is required when sending a body.') } // 2. If this’s request’s mode is neither "same-origin" nor "cors", // then throw a TypeError. if (request.mode !== 'same-origin' && request.mode !== 'cors') { throw new TypeError( 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' ) } // 3. Set this’s request’s use-CORS-preflight flag. request.useCORSPreflightFlag = true } // 39. Let finalBody be inputOrInitBody. let finalBody = inputOrInitBody // 40. If initBody is null and inputBody is non-null, then: if (initBody == null && inputBody != null) { // 1. If input is unusable, then throw a TypeError. if (bodyUnusable(input)) { throw new TypeError( 'Cannot construct a Request with a Request object that has already been used.' ) } // 2. Set finalBody to the result of creating a proxy for inputBody. // https://streams.spec.whatwg.org/#readablestream-create-a-proxy const identityTransform = new TransformStream() inputBody.stream.pipeThrough(identityTransform) finalBody = { source: inputBody.source, length: inputBody.length, stream: identityTransform.readable } } // 41. Set this’s request’s body to finalBody. this[kState].body = finalBody } // Returns request’s HTTP method, which is "GET" by default. get method () { webidl.brandCheck(this, Request) // The method getter steps are to return this’s request’s method. return this[kState].method } // Returns the URL of request as a string. get url () { webidl.brandCheck(this, Request) // The url getter steps are to return this’s request’s URL, serialized. return URLSerializer(this[kState].url) } // Returns a Headers object consisting of the headers associated with request. // Note that headers added in the network layer by the user agent will not // be accounted for in this object, e.g., the "Host" header. get headers () { webidl.brandCheck(this, Request) // The headers getter steps are to return this’s headers. return this[kHeaders] } // Returns the kind of resource requested by request, e.g., "document" // or "script". get destination () { webidl.brandCheck(this, Request) // The destination getter are to return this’s request’s destination. return this[kState].destination } // Returns the referrer of request. Its value can be a same-origin URL if // explicitly set in init, the empty string to indicate no referrer, and // "about:client" when defaulting to the global’s default. This is used // during fetching to determine the value of the `Referer` header of the // request being made. get referrer () { webidl.brandCheck(this, Request) // 1. If this’s request’s referrer is "no-referrer", then return the // empty string. if (this[kState].referrer === 'no-referrer') { return '' } // 2. If this’s request’s referrer is "client", then return // "about:client". if (this[kState].referrer === 'client') { return 'about:client' } // Return this’s request’s referrer, serialized. return this[kState].referrer.toString() } // Returns the referrer policy associated with request. // This is used during fetching to compute the value of the request’s // referrer. get referrerPolicy () { webidl.brandCheck(this, Request) // The referrerPolicy getter steps are to return this’s request’s referrer policy. return this[kState].referrerPolicy } // Returns the mode associated with request, which is a string indicating // whether the request will use CORS, or will be restricted to same-origin // URLs. get mode () { webidl.brandCheck(this, Request) // The mode getter steps are to return this’s request’s mode. return this[kState].mode } // Returns the credentials mode associated with request, // which is a string indicating whether credentials will be sent with the // request always, never, or only when sent to a same-origin URL. get credentials () { // The credentials getter steps are to return this’s request’s credentials mode. return this[kState].credentials } // Returns the cache mode associated with request, // which is a string indicating how the request will // interact with the browser’s cache when fetching. get cache () { webidl.brandCheck(this, Request) // The cache getter steps are to return this’s request’s cache mode. return this[kState].cache } // Returns the redirect mode associated with request, // which is a string indicating how redirects for the // request will be handled during fetching. A request // will follow redirects by default. get redirect () { webidl.brandCheck(this, Request) // The redirect getter steps are to return this’s request’s redirect mode. return this[kState].redirect } // Returns request’s subresource integrity metadata, which is a // cryptographic hash of the resource being fetched. Its value // consists of multiple hashes separated by whitespace. [SRI] get integrity () { webidl.brandCheck(this, Request) // The integrity getter steps are to return this’s request’s integrity // metadata. return this[kState].integrity } // Returns a boolean indicating whether or not request can outlive the // global in which it was created. get keepalive () { webidl.brandCheck(this, Request) // The keepalive getter steps are to return this’s request’s keepalive. return this[kState].keepalive } // Returns a boolean indicating whether or not request is for a reload // navigation. get isReloadNavigation () { webidl.brandCheck(this, Request) // The isReloadNavigation getter steps are to return true if this’s // request’s reload-navigation flag is set; otherwise false. return this[kState].reloadNavigation } // Returns a boolean indicating whether or not request is for a history // navigation (a.k.a. back-forward navigation). get isHistoryNavigation () { webidl.brandCheck(this, Request) // The isHistoryNavigation getter steps are to return true if this’s request’s // history-navigation flag is set; otherwise false. return this[kState].historyNavigation } // Returns the signal associated with request, which is an AbortSignal // object indicating whether or not request has been aborted, and its // abort event handler. get signal () { webidl.brandCheck(this, Request) // The signal getter steps are to return this’s signal. return this[kSignal] } get body () { webidl.brandCheck(this, Request) return this[kState].body ? this[kState].body.stream : null } get bodyUsed () { webidl.brandCheck(this, Request) return !!this[kState].body && util.isDisturbed(this[kState].body.stream) } get duplex () { webidl.brandCheck(this, Request) return 'half' } // Returns a clone of request. clone () { webidl.brandCheck(this, Request) // 1. If this is unusable, then throw a TypeError. if (bodyUnusable(this)) { throw new TypeError('unusable') } // 2. Let clonedRequest be the result of cloning this’s request. const clonedRequest = cloneRequest(this[kState]) // 3. Let clonedRequestObject be the result of creating a Request object, // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. // 4. Make clonedRequestObject’s signal follow this’s signal. const ac = new AbortController() if (this.signal.aborted) { ac.abort(this.signal.reason) } else { let list = dependentControllerMap.get(this.signal) if (list === undefined) { list = new Set() dependentControllerMap.set(this.signal, list) } const acRef = new WeakRef(ac) list.add(acRef) util.addAbortListener( ac.signal, buildAbort(acRef) ) } // 4. Return clonedRequestObject. return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders])) } [nodeUtil.inspect.custom] (depth, options) { if (options.depth === null) { options.depth = 2 } options.colors ??= true const properties = { method: this.method, url: this.url, headers: this.headers, destination: this.destination, referrer: this.referrer, referrerPolicy: this.referrerPolicy, mode: this.mode, credentials: this.credentials, cache: this.cache, redirect: this.redirect, integrity: this.integrity, keepalive: this.keepalive, isReloadNavigation: this.isReloadNavigation, isHistoryNavigation: this.isHistoryNavigation, signal: this.signal } return `Request ${nodeUtil.formatWithOptions(options, properties)}` } } mixinBody(Request) // https://fetch.spec.whatwg.org/#requests function makeRequest (init) { return { method: init.method ?? 'GET', localURLsOnly: init.localURLsOnly ?? false, unsafeRequest: init.unsafeRequest ?? false, body: init.body ?? null, client: init.client ?? null, reservedClient: init.reservedClient ?? null, replacesClientId: init.replacesClientId ?? '', window: init.window ?? 'client', keepalive: init.keepalive ?? false, serviceWorkers: init.serviceWorkers ?? 'all', initiator: init.initiator ?? '', destination: init.destination ?? '', priority: init.priority ?? null, origin: init.origin ?? 'client', policyContainer: init.policyContainer ?? 'client', referrer: init.referrer ?? 'client', referrerPolicy: init.referrerPolicy ?? '', mode: init.mode ?? 'no-cors', useCORSPreflightFlag: init.useCORSPreflightFlag ?? false, credentials: init.credentials ?? 'same-origin', useCredentials: init.useCredentials ?? false, cache: init.cache ?? 'default', redirect: init.redirect ?? 'follow', integrity: init.integrity ?? '', cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '', parserMetadata: init.parserMetadata ?? '', reloadNavigation: init.reloadNavigation ?? false, historyNavigation: init.historyNavigation ?? false, userActivation: init.userActivation ?? false, taintedOrigin: init.taintedOrigin ?? false, redirectCount: init.redirectCount ?? 0, responseTainting: init.responseTainting ?? 'basic', preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false, done: init.done ?? false, timingAllowFailed: init.timingAllowFailed ?? false, urlList: init.urlList, url: init.urlList[0], headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList() } } // https://fetch.spec.whatwg.org/#concept-request-clone function cloneRequest (request) { // To clone a request request, run these steps: // 1. Let newRequest be a copy of request, except for its body. const newRequest = makeRequest({ ...request, body: null }) // 2. If request’s body is non-null, set newRequest’s body to the // result of cloning request’s body. if (request.body != null) { newRequest.body = cloneBody(newRequest, request.body) } // 3. Return newRequest. return newRequest } /** * @see https://fetch.spec.whatwg.org/#request-create * @param {any} innerRequest * @param {AbortSignal} signal * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard * @returns {Request} */ function fromInnerRequest (innerRequest, signal, guard) { const request = new Request(kConstruct) request[kState] = innerRequest request[kSignal] = signal request[kHeaders] = new Headers(kConstruct) setHeadersList(request[kHeaders], innerRequest.headersList) setHeadersGuard(request[kHeaders], guard) return request } Object.defineProperties(Request.prototype, { method: kEnumerableProperty, url: kEnumerableProperty, headers: kEnumerableProperty, redirect: kEnumerableProperty, clone: kEnumerableProperty, signal: kEnumerableProperty, duplex: kEnumerableProperty, destination: kEnumerableProperty, body: kEnumerableProperty, bodyUsed: kEnumerableProperty, isHistoryNavigation: kEnumerableProperty, isReloadNavigation: kEnumerableProperty, keepalive: kEnumerableProperty, integrity: kEnumerableProperty, cache: kEnumerableProperty, credentials: kEnumerableProperty, attribute: kEnumerableProperty, referrerPolicy: kEnumerableProperty, referrer: kEnumerableProperty, mode: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Request', configurable: true } }) webidl.converters.Request = webidl.interfaceConverter( Request ) // https://fetch.spec.whatwg.org/#requestinfo webidl.converters.RequestInfo = function (V, prefix, argument) { if (typeof V === 'string') { return webidl.converters.USVString(V, prefix, argument) } if (V instanceof Request) { return webidl.converters.Request(V, prefix, argument) } return webidl.converters.USVString(V, prefix, argument) } webidl.converters.AbortSignal = webidl.interfaceConverter( AbortSignal ) // https://fetch.spec.whatwg.org/#requestinit webidl.converters.RequestInit = webidl.dictionaryConverter([ { key: 'method', converter: webidl.converters.ByteString }, { key: 'headers', converter: webidl.converters.HeadersInit }, { key: 'body', converter: webidl.nullableConverter( webidl.converters.BodyInit ) }, { key: 'referrer', converter: webidl.converters.USVString }, { key: 'referrerPolicy', converter: webidl.converters.DOMString, // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy allowedValues: referrerPolicy }, { key: 'mode', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#concept-request-mode allowedValues: requestMode }, { key: 'credentials', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestcredentials allowedValues: requestCredentials }, { key: 'cache', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestcache allowedValues: requestCache }, { key: 'redirect', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestredirect allowedValues: requestRedirect }, { key: 'integrity', converter: webidl.converters.DOMString }, { key: 'keepalive', converter: webidl.converters.boolean }, { key: 'signal', converter: webidl.nullableConverter( (signal) => webidl.converters.AbortSignal( signal, 'RequestInit', 'signal', { strict: false } ) ) }, { key: 'window', converter: webidl.converters.any }, { key: 'duplex', converter: webidl.converters.DOMString, allowedValues: requestDuplex }, { key: 'dispatcher', // undici specific option converter: webidl.converters.any } ]) module.exports = { Request, makeRequest, fromInnerRequest, cloneRequest } /***/ }), /***/ 9051: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = __nccwpck_require__(660) const { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = __nccwpck_require__(4492) const util = __nccwpck_require__(3440) const nodeUtil = __nccwpck_require__(7975) const { kEnumerableProperty } = util const { isValidReasonPhrase, isCancelled, isAborted, isBlobLike, serializeJavascriptValueToJSONString, isErrorLike, isomorphicEncode, environmentSettingsObject: relevantRealm } = __nccwpck_require__(3168) const { redirectStatusSet, nullBodyStatus } = __nccwpck_require__(4495) const { kState, kHeaders } = __nccwpck_require__(3627) const { webidl } = __nccwpck_require__(5893) const { FormData } = __nccwpck_require__(5910) const { URLSerializer } = __nccwpck_require__(1900) const { kConstruct } = __nccwpck_require__(6443) const assert = __nccwpck_require__(4589) const { types } = __nccwpck_require__(7975) const textEncoder = new TextEncoder('utf-8') // https://fetch.spec.whatwg.org/#response-class class Response { // Creates network error Response. static error () { // The static error() method steps are to return the result of creating a // Response object, given a new network error, "immutable", and this’s // relevant Realm. const responseObject = fromInnerResponse(makeNetworkError(), 'immutable') return responseObject } // https://fetch.spec.whatwg.org/#dom-response-json static json (data, init = {}) { webidl.argumentLengthCheck(arguments, 1, 'Response.json') if (init !== null) { init = webidl.converters.ResponseInit(init) } // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ) // 2. Let body be the result of extracting bytes. const body = extractBody(bytes) // 3. Let responseObject be the result of creating a Response object, given a new response, // "response", and this’s relevant Realm. const responseObject = fromInnerResponse(makeResponse({}), 'response') // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) // 5. Return responseObject. return responseObject } // Creates a redirect Response that redirects to url with status status. static redirect (url, status = 302) { webidl.argumentLengthCheck(arguments, 1, 'Response.redirect') url = webidl.converters.USVString(url) status = webidl.converters['unsigned short'](status) // 1. Let parsedURL be the result of parsing url with current settings // object’s API base URL. // 2. If parsedURL is failure, then throw a TypeError. // TODO: base-URL? let parsedURL try { parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl) } catch (err) { throw new TypeError(`Failed to parse URL from ${url}`, { cause: err }) } // 3. If status is not a redirect status, then throw a RangeError. if (!redirectStatusSet.has(status)) { throw new RangeError(`Invalid status code ${status}`) } // 4. Let responseObject be the result of creating a Response object, // given a new response, "immutable", and this’s relevant Realm. const responseObject = fromInnerResponse(makeResponse({}), 'immutable') // 5. Set responseObject’s response’s status to status. responseObject[kState].status = status // 6. Let value be parsedURL, serialized and isomorphic encoded. const value = isomorphicEncode(URLSerializer(parsedURL)) // 7. Append `Location`/value to responseObject’s response’s header list. responseObject[kState].headersList.append('location', value, true) // 8. Return responseObject. return responseObject } // https://fetch.spec.whatwg.org/#dom-response constructor (body = null, init = {}) { webidl.util.markAsUncloneable(this) if (body === kConstruct) { return } if (body !== null) { body = webidl.converters.BodyInit(body) } init = webidl.converters.ResponseInit(init) // 1. Set this’s response to a new response. this[kState] = makeResponse({}) // 2. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is this’s response’s header list and guard // is "response". this[kHeaders] = new Headers(kConstruct) setHeadersGuard(this[kHeaders], 'response') setHeadersList(this[kHeaders], this[kState].headersList) // 3. Let bodyWithType be null. let bodyWithType = null // 4. If body is non-null, then set bodyWithType to the result of extracting body. if (body != null) { const [extractedBody, type] = extractBody(body) bodyWithType = { body: extractedBody, type } } // 5. Perform initialize a response given this, init, and bodyWithType. initializeResponse(this, init, bodyWithType) } // Returns response’s type, e.g., "cors". get type () { webidl.brandCheck(this, Response) // The type getter steps are to return this’s response’s type. return this[kState].type } // Returns response’s URL, if it has one; otherwise the empty string. get url () { webidl.brandCheck(this, Response) const urlList = this[kState].urlList // The url getter steps are to return the empty string if this’s // response’s URL is null; otherwise this’s response’s URL, // serialized with exclude fragment set to true. const url = urlList[urlList.length - 1] ?? null if (url === null) { return '' } return URLSerializer(url, true) } // Returns whether response was obtained through a redirect. get redirected () { webidl.brandCheck(this, Response) // The redirected getter steps are to return true if this’s response’s URL // list has more than one item; otherwise false. return this[kState].urlList.length > 1 } // Returns response’s status. get status () { webidl.brandCheck(this, Response) // The status getter steps are to return this’s response’s status. return this[kState].status } // Returns whether response’s status is an ok status. get ok () { webidl.brandCheck(this, Response) // The ok getter steps are to return true if this’s response’s status is an // ok status; otherwise false. return this[kState].status >= 200 && this[kState].status <= 299 } // Returns response’s status message. get statusText () { webidl.brandCheck(this, Response) // The statusText getter steps are to return this’s response’s status // message. return this[kState].statusText } // Returns response’s headers as Headers. get headers () { webidl.brandCheck(this, Response) // The headers getter steps are to return this’s headers. return this[kHeaders] } get body () { webidl.brandCheck(this, Response) return this[kState].body ? this[kState].body.stream : null } get bodyUsed () { webidl.brandCheck(this, Response) return !!this[kState].body && util.isDisturbed(this[kState].body.stream) } // Returns a clone of response. clone () { webidl.brandCheck(this, Response) // 1. If this is unusable, then throw a TypeError. if (bodyUnusable(this)) { throw webidl.errors.exception({ header: 'Response.clone', message: 'Body has already been consumed.' }) } // 2. Let clonedResponse be the result of cloning this’s response. const clonedResponse = cloneResponse(this[kState]) // Note: To re-register because of a new stream. if (hasFinalizationRegistry && this[kState].body?.stream) { streamRegistry.register(this, new WeakRef(this[kState].body.stream)) } // 3. Return the result of creating a Response object, given // clonedResponse, this’s headers’s guard, and this’s relevant Realm. return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders])) } [nodeUtil.inspect.custom] (depth, options) { if (options.depth === null) { options.depth = 2 } options.colors ??= true const properties = { status: this.status, statusText: this.statusText, headers: this.headers, body: this.body, bodyUsed: this.bodyUsed, ok: this.ok, redirected: this.redirected, type: this.type, url: this.url } return `Response ${nodeUtil.formatWithOptions(options, properties)}` } } mixinBody(Response) Object.defineProperties(Response.prototype, { type: kEnumerableProperty, url: kEnumerableProperty, status: kEnumerableProperty, ok: kEnumerableProperty, redirected: kEnumerableProperty, statusText: kEnumerableProperty, headers: kEnumerableProperty, clone: kEnumerableProperty, body: kEnumerableProperty, bodyUsed: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Response', configurable: true } }) Object.defineProperties(Response, { json: kEnumerableProperty, redirect: kEnumerableProperty, error: kEnumerableProperty }) // https://fetch.spec.whatwg.org/#concept-response-clone function cloneResponse (response) { // To clone a response response, run these steps: // 1. If response is a filtered response, then return a new identical // filtered response whose internal response is a clone of response’s // internal response. if (response.internalResponse) { return filterResponse( cloneResponse(response.internalResponse), response.type ) } // 2. Let newResponse be a copy of response, except for its body. const newResponse = makeResponse({ ...response, body: null }) // 3. If response’s body is non-null, then set newResponse’s body to the // result of cloning response’s body. if (response.body != null) { newResponse.body = cloneBody(newResponse, response.body) } // 4. Return newResponse. return newResponse } function makeResponse (init) { return { aborted: false, rangeRequested: false, timingAllowPassed: false, requestIncludesCredentials: false, type: 'default', status: 200, timingInfo: null, cacheState: '', statusText: '', ...init, headersList: init?.headersList ? new HeadersList(init?.headersList) : new HeadersList(), urlList: init?.urlList ? [...init.urlList] : [] } } function makeNetworkError (reason) { const isError = isErrorLike(reason) return makeResponse({ type: 'error', status: 0, error: isError ? reason : new Error(reason ? String(reason) : reason), aborted: reason && reason.name === 'AbortError' }) } // @see https://fetch.spec.whatwg.org/#concept-network-error function isNetworkError (response) { return ( // A network error is a response whose type is "error", response.type === 'error' && // status is 0 response.status === 0 ) } function makeFilteredResponse (response, state) { state = { internalResponse: response, ...state } return new Proxy(response, { get (target, p) { return p in state ? state[p] : target[p] }, set (target, p, value) { assert(!(p in state)) target[p] = value return true } }) } // https://fetch.spec.whatwg.org/#concept-filtered-response function filterResponse (response, type) { // Set response to the following filtered response with response as its // internal response, depending on request’s response tainting: if (type === 'basic') { // A basic filtered response is a filtered response whose type is "basic" // and header list excludes any headers in internal response’s header list // whose name is a forbidden response-header name. // Note: undici does not implement forbidden response-header names return makeFilteredResponse(response, { type: 'basic', headersList: response.headersList }) } else if (type === 'cors') { // A CORS filtered response is a filtered response whose type is "cors" // and header list excludes any headers in internal response’s header // list whose name is not a CORS-safelisted response-header name, given // internal response’s CORS-exposed header-name list. // Note: undici does not implement CORS-safelisted response-header names return makeFilteredResponse(response, { type: 'cors', headersList: response.headersList }) } else if (type === 'opaque') { // An opaque filtered response is a filtered response whose type is // "opaque", URL list is the empty list, status is 0, status message // is the empty byte sequence, header list is empty, and body is null. return makeFilteredResponse(response, { type: 'opaque', urlList: Object.freeze([]), status: 0, statusText: '', body: null }) } else if (type === 'opaqueredirect') { // An opaque-redirect filtered response is a filtered response whose type // is "opaqueredirect", status is 0, status message is the empty byte // sequence, header list is empty, and body is null. return makeFilteredResponse(response, { type: 'opaqueredirect', status: 0, statusText: '', headersList: [], body: null }) } else { assert(false) } } // https://fetch.spec.whatwg.org/#appropriate-network-error function makeAppropriateNetworkError (fetchParams, err = null) { // 1. Assert: fetchParams is canceled. assert(isCancelled(fetchParams)) // 2. Return an aborted network error if fetchParams is aborted; // otherwise return a network error. return isAborted(fetchParams) ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) } // https://whatpr.org/fetch/1392.html#initialize-a-response function initializeResponse (response, init, body) { // 1. If init["status"] is not in the range 200 to 599, inclusive, then // throw a RangeError. if (init.status !== null && (init.status < 200 || init.status > 599)) { throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') } // 2. If init["statusText"] does not match the reason-phrase token production, // then throw a TypeError. if ('statusText' in init && init.statusText != null) { // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) if (!isValidReasonPhrase(String(init.statusText))) { throw new TypeError('Invalid statusText') } } // 3. Set response’s response’s status to init["status"]. if ('status' in init && init.status != null) { response[kState].status = init.status } // 4. Set response’s response’s status message to init["statusText"]. if ('statusText' in init && init.statusText != null) { response[kState].statusText = init.statusText } // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. if ('headers' in init && init.headers != null) { fill(response[kHeaders], init.headers) } // 6. If body was given, then: if (body) { // 1. If response's status is a null body status, then throw a TypeError. if (nullBodyStatus.includes(response.status)) { throw webidl.errors.exception({ header: 'Response constructor', message: `Invalid response status code ${response.status}` }) } // 2. Set response's body to body's body. response[kState].body = body.body // 3. If body's type is non-null and response's header list does not contain // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. if (body.type != null && !response[kState].headersList.contains('content-type', true)) { response[kState].headersList.append('content-type', body.type, true) } } } /** * @see https://fetch.spec.whatwg.org/#response-create * @param {any} innerResponse * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard * @returns {Response} */ function fromInnerResponse (innerResponse, guard) { const response = new Response(kConstruct) response[kState] = innerResponse response[kHeaders] = new Headers(kConstruct) setHeadersList(response[kHeaders], innerResponse.headersList) setHeadersGuard(response[kHeaders], guard) if (hasFinalizationRegistry && innerResponse.body?.stream) { // If the target (response) is reclaimed, the cleanup callback may be called at some point with // the held value provided for it (innerResponse.body.stream). The held value can be any value: // a primitive or an object, even undefined. If the held value is an object, the registry keeps // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry streamRegistry.register(response, new WeakRef(innerResponse.body.stream)) } return response } webidl.converters.ReadableStream = webidl.interfaceConverter( ReadableStream ) webidl.converters.FormData = webidl.interfaceConverter( FormData ) webidl.converters.URLSearchParams = webidl.interfaceConverter( URLSearchParams ) // https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) { if (typeof V === 'string') { return webidl.converters.USVString(V, prefix, name) } if (isBlobLike(V)) { return webidl.converters.Blob(V, prefix, name, { strict: false }) } if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { return webidl.converters.BufferSource(V, prefix, name) } if (util.isFormDataLike(V)) { return webidl.converters.FormData(V, prefix, name, { strict: false }) } if (V instanceof URLSearchParams) { return webidl.converters.URLSearchParams(V, prefix, name) } return webidl.converters.DOMString(V, prefix, name) } // https://fetch.spec.whatwg.org/#bodyinit webidl.converters.BodyInit = function (V, prefix, argument) { if (V instanceof ReadableStream) { return webidl.converters.ReadableStream(V, prefix, argument) } // Note: the spec doesn't include async iterables, // this is an undici extension. if (V?.[Symbol.asyncIterator]) { return V } return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument) } webidl.converters.ResponseInit = webidl.dictionaryConverter([ { key: 'status', converter: webidl.converters['unsigned short'], defaultValue: () => 200 }, { key: 'statusText', converter: webidl.converters.ByteString, defaultValue: () => '' }, { key: 'headers', converter: webidl.converters.HeadersInit } ]) module.exports = { isNetworkError, makeNetworkError, makeResponse, makeAppropriateNetworkError, filterResponse, Response, cloneResponse, fromInnerResponse } /***/ }), /***/ 3627: /***/ ((module) => { "use strict"; module.exports = { kUrl: Symbol('url'), kHeaders: Symbol('headers'), kSignal: Symbol('signal'), kState: Symbol('state'), kDispatcher: Symbol('dispatcher') } /***/ }), /***/ 3168: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Transform } = __nccwpck_require__(7075) const zlib = __nccwpck_require__(8522) const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(4495) const { getGlobalOrigin } = __nccwpck_require__(1059) const { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = __nccwpck_require__(1900) const { performance } = __nccwpck_require__(643) const { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = __nccwpck_require__(3440) const assert = __nccwpck_require__(4589) const { isUint8Array } = __nccwpck_require__(3429) const { webidl } = __nccwpck_require__(5893) let supportedHashes = [] // https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable /** @type {import('crypto')} */ let crypto try { crypto = __nccwpck_require__(7598) const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) /* c8 ignore next 3 */ } catch { } function responseURL (response) { // https://fetch.spec.whatwg.org/#responses // A response has an associated URL. It is a pointer to the last URL // in response’s URL list and null if response’s URL list is empty. const urlList = response.urlList const length = urlList.length return length === 0 ? null : urlList[length - 1].toString() } // https://fetch.spec.whatwg.org/#concept-response-location-url function responseLocationURL (response, requestFragment) { // 1. If response’s status is not a redirect status, then return null. if (!redirectStatusSet.has(response.status)) { return null } // 2. Let location be the result of extracting header list values given // `Location` and response’s header list. let location = response.headersList.get('location', true) // 3. If location is a header value, then set location to the result of // parsing location with response’s URL. if (location !== null && isValidHeaderValue(location)) { if (!isValidEncodedURL(location)) { // Some websites respond location header in UTF-8 form without encoding them as ASCII // and major browsers redirect them to correctly UTF-8 encoded addresses. // Here, we handle that behavior in the same way. location = normalizeBinaryStringToUtf8(location) } location = new URL(location, responseURL(response)) } // 4. If location is a URL whose fragment is null, then set location’s // fragment to requestFragment. if (location && !location.hash) { location.hash = requestFragment } // 5. Return location. return location } /** * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2 * @param {string} url * @returns {boolean} */ function isValidEncodedURL (url) { for (let i = 0; i < url.length; ++i) { const code = url.charCodeAt(i) if ( code > 0x7E || // Non-US-ASCII + DEL code < 0x20 // Control characters NUL - US ) { return false } } return true } /** * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it. * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well. * @param {string} value * @returns {string} */ function normalizeBinaryStringToUtf8 (value) { return Buffer.from(value, 'binary').toString('utf8') } /** @returns {URL} */ function requestCurrentURL (request) { return request.urlList[request.urlList.length - 1] } function requestBadPort (request) { // 1. Let url be request’s current URL. const url = requestCurrentURL(request) // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, // then return blocked. if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return 'blocked' } // 3. Return allowed. return 'allowed' } function isErrorLike (object) { return object instanceof Error || ( object?.constructor?.name === 'Error' || object?.constructor?.name === 'DOMException' ) } // Check whether |statusText| is a ByteString and // matches the Reason-Phrase token production. // RFC 2616: https://tools.ietf.org/html/rfc2616 // RFC 7230: https://tools.ietf.org/html/rfc7230 // "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" // https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 function isValidReasonPhrase (statusText) { for (let i = 0; i < statusText.length; ++i) { const c = statusText.charCodeAt(i) if ( !( ( c === 0x09 || // HTAB (c >= 0x20 && c <= 0x7e) || // SP / VCHAR (c >= 0x80 && c <= 0xff) ) // obs-text ) ) { return false } } return true } /** * @see https://fetch.spec.whatwg.org/#header-name * @param {string} potentialValue */ const isValidHeaderName = isValidHTTPToken /** * @see https://fetch.spec.whatwg.org/#header-value * @param {string} potentialValue */ function isValidHeaderValue (potentialValue) { // - Has no leading or trailing HTTP tab or space bytes. // - Contains no 0x00 (NUL) or HTTP newline bytes. return ( potentialValue[0] === '\t' || potentialValue[0] === ' ' || potentialValue[potentialValue.length - 1] === '\t' || potentialValue[potentialValue.length - 1] === ' ' || potentialValue.includes('\n') || potentialValue.includes('\r') || potentialValue.includes('\0') ) === false } // https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect function setRequestReferrerPolicyOnRedirect (request, actualResponse) { // Given a request request and a response actualResponse, this algorithm // updates request’s referrer policy according to the Referrer-Policy // header (if any) in actualResponse. // 1. Let policy be the result of executing § 8.1 Parse a referrer policy // from a Referrer-Policy header on actualResponse. // 8.1 Parse a referrer policy from a Referrer-Policy header // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. const { headersList } = actualResponse // 2. Let policy be the empty string. // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. // 4. Return policy. const policyHeader = (headersList.get('referrer-policy', true) ?? '').split(',') // Note: As the referrer-policy can contain multiple policies // separated by comma, we need to loop through all of them // and pick the first valid one. // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy let policy = '' if (policyHeader.length > 0) { // The right-most policy takes precedence. // The left-most policy is the fallback. for (let i = policyHeader.length; i !== 0; i--) { const token = policyHeader[i - 1].trim() if (referrerPolicyTokens.has(token)) { policy = token break } } } // 2. If policy is not the empty string, then set request’s referrer policy to policy. if (policy !== '') { request.referrerPolicy = policy } } // https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check function crossOriginResourcePolicyCheck () { // TODO return 'allowed' } // https://fetch.spec.whatwg.org/#concept-cors-check function corsCheck () { // TODO return 'success' } // https://fetch.spec.whatwg.org/#concept-tao-check function TAOCheck () { // TODO return 'success' } function appendFetchMetadata (httpRequest) { // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header // TODO // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header // 1. Assert: r’s url is a potentially trustworthy URL. // TODO // 2. Let header be a Structured Header whose value is a token. let header = null // 3. Set header’s value to r’s mode. header = httpRequest.mode // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. httpRequest.headersList.set('sec-fetch-mode', header, true) // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header // TODO // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header // TODO } // https://fetch.spec.whatwg.org/#append-a-request-origin-header function appendRequestOriginHeader (request) { // 1. Let serializedOrigin be the result of byte-serializing a request origin // with request. // TODO: implement "byte-serializing a request origin" let serializedOrigin = request.origin // - "'client' is changed to an origin during fetching." // This doesn't happen in undici (in most cases) because undici, by default, // has no concept of origin. // - request.origin can also be set to request.client.origin (client being // an environment settings object), which is undefined without using // setGlobalOrigin. if (serializedOrigin === 'client' || serializedOrigin === undefined) { return } // 2. If request’s response tainting is "cors" or request’s mode is "websocket", // then append (`Origin`, serializedOrigin) to request’s header list. // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: if (request.responseTainting === 'cors' || request.mode === 'websocket') { request.headersList.append('origin', serializedOrigin, true) } else if (request.method !== 'GET' && request.method !== 'HEAD') { // 1. Switch on request’s referrer policy: switch (request.referrerPolicy) { case 'no-referrer': // Set serializedOrigin to `null`. serializedOrigin = null break case 'no-referrer-when-downgrade': case 'strict-origin': case 'strict-origin-when-cross-origin': // If request’s origin is a tuple origin, its scheme is "https", and // request’s current URL’s scheme is not "https", then set // serializedOrigin to `null`. if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { serializedOrigin = null } break case 'same-origin': // If request’s origin is not same origin with request’s current URL’s // origin, then set serializedOrigin to `null`. if (!sameOrigin(request, requestCurrentURL(request))) { serializedOrigin = null } break default: // Do nothing. } // 2. Append (`Origin`, serializedOrigin) to request’s header list. request.headersList.append('origin', serializedOrigin, true) } } // https://w3c.github.io/hr-time/#dfn-coarsen-time function coarsenTime (timestamp, crossOriginIsolatedCapability) { // TODO return timestamp } // https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) { if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) { return { domainLookupStartTime: defaultStartTime, domainLookupEndTime: defaultStartTime, connectionStartTime: defaultStartTime, connectionEndTime: defaultStartTime, secureConnectionStartTime: defaultStartTime, ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol } } return { domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability), domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability), connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability), connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability), secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability), ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol } } // https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { return coarsenTime(performance.now(), crossOriginIsolatedCapability) } // https://fetch.spec.whatwg.org/#create-an-opaque-timing-info function createOpaqueTimingInfo (timingInfo) { return { startTime: timingInfo.startTime ?? 0, redirectStartTime: 0, redirectEndTime: 0, postRedirectStartTime: timingInfo.startTime ?? 0, finalServiceWorkerStartTime: 0, finalNetworkResponseStartTime: 0, finalNetworkRequestStartTime: 0, endTime: 0, encodedBodySize: 0, decodedBodySize: 0, finalConnectionTimingInfo: null } } // https://html.spec.whatwg.org/multipage/origin.html#policy-container function makePolicyContainer () { // Note: the fetch spec doesn't make use of embedder policy or CSP list return { referrerPolicy: 'strict-origin-when-cross-origin' } } // https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container function clonePolicyContainer (policyContainer) { return { referrerPolicy: policyContainer.referrerPolicy } } // https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer function determineRequestsReferrer (request) { // 1. Let policy be request's referrer policy. const policy = request.referrerPolicy // Note: policy cannot (shouldn't) be null or an empty string. assert(policy) // 2. Let environment be request’s client. let referrerSource = null // 3. Switch on request’s referrer: if (request.referrer === 'client') { // Note: node isn't a browser and doesn't implement document/iframes, // so we bypass this step and replace it with our own. const globalOrigin = getGlobalOrigin() if (!globalOrigin || globalOrigin.origin === 'null') { return 'no-referrer' } // note: we need to clone it as it's mutated referrerSource = new URL(globalOrigin) } else if (request.referrer instanceof URL) { // Let referrerSource be request’s referrer. referrerSource = request.referrer } // 4. Let request’s referrerURL be the result of stripping referrerSource for // use as a referrer. let referrerURL = stripURLForReferrer(referrerSource) // 5. Let referrerOrigin be the result of stripping referrerSource for use as // a referrer, with the origin-only flag set to true. const referrerOrigin = stripURLForReferrer(referrerSource, true) // 6. If the result of serializing referrerURL is a string whose length is // greater than 4096, set referrerURL to referrerOrigin. if (referrerURL.toString().length > 4096) { referrerURL = referrerOrigin } const areSameOrigin = sameOrigin(request, referrerURL) const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(request.url) // 8. Execute the switch statements corresponding to the value of policy: switch (policy) { case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) case 'unsafe-url': return referrerURL case 'same-origin': return areSameOrigin ? referrerOrigin : 'no-referrer' case 'origin-when-cross-origin': return areSameOrigin ? referrerURL : referrerOrigin case 'strict-origin-when-cross-origin': { const currentURL = requestCurrentURL(request) // 1. If the origin of referrerURL and the origin of request’s current // URL are the same, then return referrerURL. if (sameOrigin(referrerURL, currentURL)) { return referrerURL } // 2. If referrerURL is a potentially trustworthy URL and request’s // current URL is not a potentially trustworthy URL, then return no // referrer. if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { return 'no-referrer' } // 3. Return referrerOrigin. return referrerOrigin } case 'strict-origin': // eslint-disable-line /** * 1. If referrerURL is a potentially trustworthy URL and * request’s current URL is not a potentially trustworthy URL, * then return no referrer. * 2. Return referrerOrigin */ case 'no-referrer-when-downgrade': // eslint-disable-line /** * 1. If referrerURL is a potentially trustworthy URL and * request’s current URL is not a potentially trustworthy URL, * then return no referrer. * 2. Return referrerOrigin */ default: // eslint-disable-line return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin } } /** * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url * @param {URL} url * @param {boolean|undefined} originOnly */ function stripURLForReferrer (url, originOnly) { // 1. Assert: url is a URL. assert(url instanceof URL) url = new URL(url) // 2. If url’s scheme is a local scheme, then return no referrer. if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { return 'no-referrer' } // 3. Set url’s username to the empty string. url.username = '' // 4. Set url’s password to the empty string. url.password = '' // 5. Set url’s fragment to null. url.hash = '' // 6. If the origin-only flag is true, then: if (originOnly) { // 1. Set url’s path to « the empty string ». url.pathname = '' // 2. Set url’s query to null. url.search = '' } // 7. Return url. return url } function isURLPotentiallyTrustworthy (url) { if (!(url instanceof URL)) { return false } // If child of about, return true if (url.href === 'about:blank' || url.href === 'about:srcdoc') { return true } // If scheme is data, return true if (url.protocol === 'data:') return true // If file, return true if (url.protocol === 'file:') return true return isOriginPotentiallyTrustworthy(url.origin) function isOriginPotentiallyTrustworthy (origin) { // If origin is explicitly null, return false if (origin == null || origin === 'null') return false const originAsURL = new URL(origin) // If secure, return true if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { return true } // If localhost or variants, return true if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || (originAsURL.hostname.endsWith('.localhost'))) { return true } // If any other, return false return false } } /** * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist * @param {Uint8Array} bytes * @param {string} metadataList */ function bytesMatch (bytes, metadataList) { // If node is not built with OpenSSL support, we cannot check // a request's integrity, so allow it by default (the spec will // allow requests if an invalid hash is given, as precedence). /* istanbul ignore if: only if node is built with --without-ssl */ if (crypto === undefined) { return true } // 1. Let parsedMetadata be the result of parsing metadataList. const parsedMetadata = parseMetadata(metadataList) // 2. If parsedMetadata is no metadata, return true. if (parsedMetadata === 'no metadata') { return true } // 3. If response is not eligible for integrity validation, return false. // TODO // 4. If parsedMetadata is the empty set, return true. if (parsedMetadata.length === 0) { return true } // 5. Let metadata be the result of getting the strongest // metadata from parsedMetadata. const strongest = getStrongestMetadata(parsedMetadata) const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) // 6. For each item in metadata: for (const item of metadata) { // 1. Let algorithm be the alg component of item. const algorithm = item.algo // 2. Let expectedValue be the val component of item. const expectedValue = item.hash // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e // "be liberal with padding". This is annoying, and it's not even in the spec. // 3. Let actualValue be the result of applying algorithm to bytes. let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') if (actualValue[actualValue.length - 1] === '=') { if (actualValue[actualValue.length - 2] === '=') { actualValue = actualValue.slice(0, -2) } else { actualValue = actualValue.slice(0, -1) } } // 4. If actualValue is a case-sensitive match for expectedValue, // return true. if (compareBase64Mixed(actualValue, expectedValue)) { return true } } // 7. Return false. return false } // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options // https://www.w3.org/TR/CSP2/#source-list-syntax // https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i /** * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata * @param {string} metadata */ function parseMetadata (metadata) { // 1. Let result be the empty set. /** @type {{ algo: string, hash: string }[]} */ const result = [] // 2. Let empty be equal to true. let empty = true // 3. For each token returned by splitting metadata on spaces: for (const token of metadata.split(' ')) { // 1. Set empty to false. empty = false // 2. Parse token as a hash-with-options. const parsedToken = parseHashWithOptions.exec(token) // 3. If token does not parse, continue to the next token. if ( parsedToken === null || parsedToken.groups === undefined || parsedToken.groups.algo === undefined ) { // Note: Chromium blocks the request at this point, but Firefox // gives a warning that an invalid integrity was given. The // correct behavior is to ignore these, and subsequently not // check the integrity of the resource. continue } // 4. Let algorithm be the hash-algo component of token. const algorithm = parsedToken.groups.algo.toLowerCase() // 5. If algorithm is a hash function recognized by the user // agent, add the parsed token to result. if (supportedHashes.includes(algorithm)) { result.push(parsedToken.groups) } } // 4. Return no metadata if empty is true, otherwise return result. if (empty === true) { return 'no metadata' } return result } /** * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList */ function getStrongestMetadata (metadataList) { // Let algorithm be the algo component of the first item in metadataList. // Can be sha256 let algorithm = metadataList[0].algo // If the algorithm is sha512, then it is the strongest // and we can return immediately if (algorithm[3] === '5') { return algorithm } for (let i = 1; i < metadataList.length; ++i) { const metadata = metadataList[i] // If the algorithm is sha512, then it is the strongest // and we can break the loop immediately if (metadata.algo[3] === '5') { algorithm = 'sha512' break // If the algorithm is sha384, then a potential sha256 or sha384 is ignored } else if (algorithm[3] === '3') { continue // algorithm is sha256, check if algorithm is sha384 and if so, set it as // the strongest } else if (metadata.algo[3] === '3') { algorithm = 'sha384' } } return algorithm } function filterMetadataListByAlgorithm (metadataList, algorithm) { if (metadataList.length === 1) { return metadataList } let pos = 0 for (let i = 0; i < metadataList.length; ++i) { if (metadataList[i].algo === algorithm) { metadataList[pos++] = metadataList[i] } } metadataList.length = pos return metadataList } /** * Compares two base64 strings, allowing for base64url * in the second string. * * @param {string} actualValue always base64 * @param {string} expectedValue base64 or base64url * @returns {boolean} */ function compareBase64Mixed (actualValue, expectedValue) { if (actualValue.length !== expectedValue.length) { return false } for (let i = 0; i < actualValue.length; ++i) { if (actualValue[i] !== expectedValue[i]) { if ( (actualValue[i] === '+' && expectedValue[i] === '-') || (actualValue[i] === '/' && expectedValue[i] === '_') ) { continue } return false } } return true } // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { // TODO } /** * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} * @param {URL} A * @param {URL} B */ function sameOrigin (A, B) { // 1. If A and B are the same opaque origin, then return true. if (A.origin === B.origin && A.origin === 'null') { return true } // 2. If A and B are both tuple origins and their schemes, // hosts, and port are identical, then return true. if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { return true } // 3. Return false. return false } function createDeferredPromise () { let res let rej const promise = new Promise((resolve, reject) => { res = resolve rej = reject }) return { promise, resolve: res, reject: rej } } function isAborted (fetchParams) { return fetchParams.controller.state === 'aborted' } function isCancelled (fetchParams) { return fetchParams.controller.state === 'aborted' || fetchParams.controller.state === 'terminated' } /** * @see https://fetch.spec.whatwg.org/#concept-method-normalize * @param {string} method */ function normalizeMethod (method) { return normalizedMethodRecordsBase[method.toLowerCase()] ?? method } // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string function serializeJavascriptValueToJSONString (value) { // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). const result = JSON.stringify(value) // 2. If result is undefined, then throw a TypeError. if (result === undefined) { throw new TypeError('Value is not JSON serializable') } // 3. Assert: result is a string. assert(typeof result === 'string') // 4. Return result. return result } // https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) /** * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object * @param {string} name name of the instance * @param {symbol} kInternalIterator * @param {string | number} [keyIndex] * @param {string | number} [valueIndex] */ function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) { class FastIterableIterator { /** @type {any} */ #target /** @type {'key' | 'value' | 'key+value'} */ #kind /** @type {number} */ #index /** * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object * @param {unknown} target * @param {'key' | 'value' | 'key+value'} kind */ constructor (target, kind) { this.#target = target this.#kind = kind this.#index = 0 } next () { // 1. Let interface be the interface for which the iterator prototype object exists. // 2. Let thisValue be the this value. // 3. Let object be ? ToObject(thisValue). // 4. If object is a platform object, then perform a security // check, passing: // 5. If object is not a default iterator object for interface, // then throw a TypeError. if (typeof this !== 'object' || this === null || !(#target in this)) { throw new TypeError( `'next' called on an object that does not implement interface ${name} Iterator.` ) } // 6. Let index be object’s index. // 7. Let kind be object’s kind. // 8. Let values be object’s target's value pairs to iterate over. const index = this.#index const values = this.#target[kInternalIterator] // 9. Let len be the length of values. const len = values.length // 10. If index is greater than or equal to len, then return // CreateIterResultObject(undefined, true). if (index >= len) { return { value: undefined, done: true } } // 11. Let pair be the entry in values at index index. const { [keyIndex]: key, [valueIndex]: value } = values[index] // 12. Set object’s index to index + 1. this.#index = index + 1 // 13. Return the iterator result for pair and kind. // https://webidl.spec.whatwg.org/#iterator-result // 1. Let result be a value determined by the value of kind: let result switch (this.#kind) { case 'key': // 1. Let idlKey be pair’s key. // 2. Let key be the result of converting idlKey to an // ECMAScript value. // 3. result is key. result = key break case 'value': // 1. Let idlValue be pair’s value. // 2. Let value be the result of converting idlValue to // an ECMAScript value. // 3. result is value. result = value break case 'key+value': // 1. Let idlKey be pair’s key. // 2. Let idlValue be pair’s value. // 3. Let key be the result of converting idlKey to an // ECMAScript value. // 4. Let value be the result of converting idlValue to // an ECMAScript value. // 5. Let array be ! ArrayCreate(2). // 6. Call ! CreateDataProperty(array, "0", key). // 7. Call ! CreateDataProperty(array, "1", value). // 8. result is array. result = [key, value] break } // 2. Return CreateIterResultObject(result, false). return { value: result, done: false } } } // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object // @ts-ignore delete FastIterableIterator.prototype.constructor Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype) Object.defineProperties(FastIterableIterator.prototype, { [Symbol.toStringTag]: { writable: false, enumerable: false, configurable: true, value: `${name} Iterator` }, next: { writable: true, enumerable: true, configurable: true } }) /** * @param {unknown} target * @param {'key' | 'value' | 'key+value'} kind * @returns {IterableIterator} */ return function (target, kind) { return new FastIterableIterator(target, kind) } } /** * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object * @param {string} name name of the instance * @param {any} object class * @param {symbol} kInternalIterator * @param {string | number} [keyIndex] * @param {string | number} [valueIndex] */ function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) { const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex) const properties = { keys: { writable: true, enumerable: true, configurable: true, value: function keys () { webidl.brandCheck(this, object) return makeIterator(this, 'key') } }, values: { writable: true, enumerable: true, configurable: true, value: function values () { webidl.brandCheck(this, object) return makeIterator(this, 'value') } }, entries: { writable: true, enumerable: true, configurable: true, value: function entries () { webidl.brandCheck(this, object) return makeIterator(this, 'key+value') } }, forEach: { writable: true, enumerable: true, configurable: true, value: function forEach (callbackfn, thisArg = globalThis) { webidl.brandCheck(this, object) webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`) if (typeof callbackfn !== 'function') { throw new TypeError( `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.` ) } for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) { callbackfn.call(thisArg, value, key, this) } } } } return Object.defineProperties(object.prototype, { ...properties, [Symbol.iterator]: { writable: true, enumerable: false, configurable: true, value: properties.entries.value } }) } /** * @see https://fetch.spec.whatwg.org/#body-fully-read */ async function fullyReadBody (body, processBody, processBodyError) { // 1. If taskDestination is null, then set taskDestination to // the result of starting a new parallel queue. // 2. Let successSteps given a byte sequence bytes be to queue a // fetch task to run processBody given bytes, with taskDestination. const successSteps = processBody // 3. Let errorSteps be to queue a fetch task to run processBodyError, // with taskDestination. const errorSteps = processBodyError // 4. Let reader be the result of getting a reader for body’s stream. // If that threw an exception, then run errorSteps with that // exception and return. let reader try { reader = body.stream.getReader() } catch (e) { errorSteps(e) return } // 5. Read all bytes from reader, given successSteps and errorSteps. try { successSteps(await readAllBytes(reader)) } catch (e) { errorSteps(e) } } function isReadableStreamLike (stream) { return stream instanceof ReadableStream || ( stream[Symbol.toStringTag] === 'ReadableStream' && typeof stream.tee === 'function' ) } /** * @param {ReadableStreamController} controller */ function readableStreamClose (controller) { try { controller.close() controller.byobRequest?.respond(0) } catch (err) { // TODO: add comment explaining why this error occurs. if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) { throw err } } } const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/ // eslint-disable-line /** * @see https://infra.spec.whatwg.org/#isomorphic-encode * @param {string} input */ function isomorphicEncode (input) { // 1. Assert: input contains no code points greater than U+00FF. assert(!invalidIsomorphicEncodeValueRegex.test(input)) // 2. Return a byte sequence whose length is equal to input’s code // point length and whose bytes have the same values as the // values of input’s code points, in the same order return input } /** * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes * @see https://streams.spec.whatwg.org/#read-loop * @param {ReadableStreamDefaultReader} reader */ async function readAllBytes (reader) { const bytes = [] let byteLength = 0 while (true) { const { done, value: chunk } = await reader.read() if (done) { // 1. Call successSteps with bytes. return Buffer.concat(bytes, byteLength) } // 1. If chunk is not a Uint8Array object, call failureSteps // with a TypeError and abort these steps. if (!isUint8Array(chunk)) { throw new TypeError('Received non-Uint8Array chunk') } // 2. Append the bytes represented by chunk to bytes. bytes.push(chunk) byteLength += chunk.length // 3. Read-loop given reader, bytes, successSteps, and failureSteps. } } /** * @see https://fetch.spec.whatwg.org/#is-local * @param {URL} url */ function urlIsLocal (url) { assert('protocol' in url) // ensure it's a url object const protocol = url.protocol return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' } /** * @param {string|URL} url * @returns {boolean} */ function urlHasHttpsScheme (url) { return ( ( typeof url === 'string' && url[5] === ':' && url[0] === 'h' && url[1] === 't' && url[2] === 't' && url[3] === 'p' && url[4] === 's' ) || url.protocol === 'https:' ) } /** * @see https://fetch.spec.whatwg.org/#http-scheme * @param {URL} url */ function urlIsHttpHttpsScheme (url) { assert('protocol' in url) // ensure it's a url object const protocol = url.protocol return protocol === 'http:' || protocol === 'https:' } /** * @see https://fetch.spec.whatwg.org/#simple-range-header-value * @param {string} value * @param {boolean} allowWhitespace */ function simpleRangeHeaderValue (value, allowWhitespace) { // 1. Let data be the isomorphic decoding of value. // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string, // nothing more. We obviously don't need to do that if value is a string already. const data = value // 2. If data does not start with "bytes", then return failure. if (!data.startsWith('bytes')) { return 'failure' } // 3. Let position be a position variable for data, initially pointing at the 5th code point of data. const position = { position: 5 } // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, // from data given position. if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 5. If the code point at position within data is not U+003D (=), then return failure. if (data.charCodeAt(position.position) !== 0x3D) { return 'failure' } // 6. Advance position by 1. position.position++ // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from // data given position. if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits, // from data given position. const rangeStart = collectASequenceOfCodePoints( (char) => { const code = char.charCodeAt(0) return code >= 0x30 && code <= 0x39 }, data, position ) // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the // empty string; otherwise null. const rangeStartValue = rangeStart.length ? Number(rangeStart) : null // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, // from data given position. if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 11. If the code point at position within data is not U+002D (-), then return failure. if (data.charCodeAt(position.position) !== 0x2D) { return 'failure' } // 12. Advance position by 1. position.position++ // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab // or space, from data given position. // Note from Khafra: its the same step as in #8 again lol if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 14. Let rangeEnd be the result of collecting a sequence of code points that are // ASCII digits, from data given position. // Note from Khafra: you wouldn't guess it, but this is also the same step as #8 const rangeEnd = collectASequenceOfCodePoints( (char) => { const code = char.charCodeAt(0) return code >= 0x30 && code <= 0x39 }, data, position ) // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd // is not the empty string; otherwise null. // Note from Khafra: THE SAME STEP, AGAIN!!! // Note: why interpret as a decimal if we only collect ascii digits? const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null // 16. If position is not past the end of data, then return failure. if (position.position < data.length) { return 'failure' } // 17. If rangeEndValue and rangeStartValue are null, then return failure. if (rangeEndValue === null && rangeStartValue === null) { return 'failure' } // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is // greater than rangeEndValue, then return failure. // Note: ... when can they not be numbers? if (rangeStartValue > rangeEndValue) { return 'failure' } // 19. Return (rangeStartValue, rangeEndValue). return { rangeStartValue, rangeEndValue } } /** * @see https://fetch.spec.whatwg.org/#build-a-content-range * @param {number} rangeStart * @param {number} rangeEnd * @param {number} fullLength */ function buildContentRange (rangeStart, rangeEnd, fullLength) { // 1. Let contentRange be `bytes `. let contentRange = 'bytes ' // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange. contentRange += isomorphicEncode(`${rangeStart}`) // 3. Append 0x2D (-) to contentRange. contentRange += '-' // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange. contentRange += isomorphicEncode(`${rangeEnd}`) // 5. Append 0x2F (/) to contentRange. contentRange += '/' // 6. Append fullLength, serialized and isomorphic encoded to contentRange. contentRange += isomorphicEncode(`${fullLength}`) // 7. Return contentRange. return contentRange } // A Stream, which pipes the response to zlib.createInflate() or // zlib.createInflateRaw() depending on the first byte of the Buffer. // If the lower byte of the first byte is 0x08, then the stream is // interpreted as a zlib stream, otherwise it's interpreted as a // raw deflate stream. class InflateStream extends Transform { #zlibOptions /** @param {zlib.ZlibOptions} [zlibOptions] */ constructor (zlibOptions) { super() this.#zlibOptions = zlibOptions } _transform (chunk, encoding, callback) { if (!this._inflateStream) { if (chunk.length === 0) { callback() return } this._inflateStream = (chunk[0] & 0x0F) === 0x08 ? zlib.createInflate(this.#zlibOptions) : zlib.createInflateRaw(this.#zlibOptions) this._inflateStream.on('data', this.push.bind(this)) this._inflateStream.on('end', () => this.push(null)) this._inflateStream.on('error', (err) => this.destroy(err)) } this._inflateStream.write(chunk, encoding, callback) } _final (callback) { if (this._inflateStream) { this._inflateStream.end() this._inflateStream = null } callback() } } /** * @param {zlib.ZlibOptions} [zlibOptions] * @returns {InflateStream} */ function createInflate (zlibOptions) { return new InflateStream(zlibOptions) } /** * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type * @param {import('./headers').HeadersList} headers */ function extractMimeType (headers) { // 1. Let charset be null. let charset = null // 2. Let essence be null. let essence = null // 3. Let mimeType be null. let mimeType = null // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers. const values = getDecodeSplit('content-type', headers) // 5. If values is null, then return failure. if (values === null) { return 'failure' } // 6. For each value of values: for (const value of values) { // 6.1. Let temporaryMimeType be the result of parsing value. const temporaryMimeType = parseMIMEType(value) // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue. if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') { continue } // 6.3. Set mimeType to temporaryMimeType. mimeType = temporaryMimeType // 6.4. If mimeType’s essence is not essence, then: if (mimeType.essence !== essence) { // 6.4.1. Set charset to null. charset = null // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to // mimeType’s parameters["charset"]. if (mimeType.parameters.has('charset')) { charset = mimeType.parameters.get('charset') } // 6.4.3. Set essence to mimeType’s essence. essence = mimeType.essence } else if (!mimeType.parameters.has('charset') && charset !== null) { // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and // charset is non-null, set mimeType’s parameters["charset"] to charset. mimeType.parameters.set('charset', charset) } } // 7. If mimeType is null, then return failure. if (mimeType == null) { return 'failure' } // 8. Return mimeType. return mimeType } /** * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split * @param {string|null} value */ function gettingDecodingSplitting (value) { // 1. Let input be the result of isomorphic decoding value. const input = value // 2. Let position be a position variable for input, initially pointing at the start of input. const position = { position: 0 } // 3. Let values be a list of strings, initially empty. const values = [] // 4. Let temporaryValue be the empty string. let temporaryValue = '' // 5. While position is not past the end of input: while (position.position < input.length) { // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (") // or U+002C (,) from input, given position, to temporaryValue. temporaryValue += collectASequenceOfCodePoints( (char) => char !== '"' && char !== ',', input, position ) // 5.2. If position is not past the end of input, then: if (position.position < input.length) { // 5.2.1. If the code point at position within input is U+0022 ("), then: if (input.charCodeAt(position.position) === 0x22) { // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue. temporaryValue += collectAnHTTPQuotedString( input, position ) // 5.2.1.2. If position is not past the end of input, then continue. if (position.position < input.length) { continue } } else { // 5.2.2. Otherwise: // 5.2.2.1. Assert: the code point at position within input is U+002C (,). assert(input.charCodeAt(position.position) === 0x2C) // 5.2.2.2. Advance position by 1. position.position++ } } // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue. temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20) // 5.4. Append temporaryValue to values. values.push(temporaryValue) // 5.6. Set temporaryValue to the empty string. temporaryValue = '' } // 6. Return values. return values } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split * @param {string} name lowercase header name * @param {import('./headers').HeadersList} list */ function getDecodeSplit (name, list) { // 1. Let value be the result of getting name from list. const value = list.get(name, true) // 2. If value is null, then return null. if (value === null) { return null } // 3. Return the result of getting, decoding, and splitting value. return gettingDecodingSplitting(value) } const textDecoder = new TextDecoder() /** * @see https://encoding.spec.whatwg.org/#utf-8-decode * @param {Buffer} buffer */ function utf8DecodeBytes (buffer) { if (buffer.length === 0) { return '' } // 1. Let buffer be the result of peeking three bytes from // ioQueue, converted to a byte sequence. // 2. If buffer is 0xEF 0xBB 0xBF, then read three // bytes from ioQueue. (Do nothing with those bytes.) if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { buffer = buffer.subarray(3) } // 3. Process a queue with an instance of UTF-8’s // decoder, ioQueue, output, and "replacement". const output = textDecoder.decode(buffer) // 4. Return output. return output } class EnvironmentSettingsObjectBase { get baseUrl () { return getGlobalOrigin() } get origin () { return this.baseUrl?.origin } policyContainer = makePolicyContainer() } class EnvironmentSettingsObject { settingsObject = new EnvironmentSettingsObjectBase() } const environmentSettingsObject = new EnvironmentSettingsObject() module.exports = { isAborted, isCancelled, isValidEncodedURL, createDeferredPromise, ReadableStreamFrom, tryUpgradeRequestToAPotentiallyTrustworthyURL, clampAndCoarsenConnectionTimingInfo, coarsenedSharedCurrentTime, determineRequestsReferrer, makePolicyContainer, clonePolicyContainer, appendFetchMetadata, appendRequestOriginHeader, TAOCheck, corsCheck, crossOriginResourcePolicyCheck, createOpaqueTimingInfo, setRequestReferrerPolicyOnRedirect, isValidHTTPToken, requestBadPort, requestCurrentURL, responseURL, responseLocationURL, isBlobLike, isURLPotentiallyTrustworthy, isValidReasonPhrase, sameOrigin, normalizeMethod, serializeJavascriptValueToJSONString, iteratorMixin, createIterator, isValidHeaderName, isValidHeaderValue, isErrorLike, fullyReadBody, bytesMatch, isReadableStreamLike, readableStreamClose, isomorphicEncode, urlIsLocal, urlHasHttpsScheme, urlIsHttpHttpsScheme, readAllBytes, simpleRangeHeaderValue, buildContentRange, parseMetadata, createInflate, extractMimeType, getDecodeSplit, utf8DecodeBytes, environmentSettingsObject } /***/ }), /***/ 5893: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { types, inspect } = __nccwpck_require__(7975) const { markAsUncloneable } = __nccwpck_require__(5919) const { toUSVString } = __nccwpck_require__(3440) /** @type {import('../../../types/webidl').Webidl} */ const webidl = {} webidl.converters = {} webidl.util = {} webidl.errors = {} webidl.errors.exception = function (message) { return new TypeError(`${message.header}: ${message.message}`) } webidl.errors.conversionFailed = function (context) { const plural = context.types.length === 1 ? '' : ' one of' const message = `${context.argument} could not be converted to` + `${plural}: ${context.types.join(', ')}.` return webidl.errors.exception({ header: context.prefix, message }) } webidl.errors.invalidArgument = function (context) { return webidl.errors.exception({ header: context.prefix, message: `"${context.value}" is an invalid ${context.type}.` }) } // https://webidl.spec.whatwg.org/#implements webidl.brandCheck = function (V, I, opts) { if (opts?.strict !== false) { if (!(V instanceof I)) { const err = new TypeError('Illegal invocation') err.code = 'ERR_INVALID_THIS' // node compat. throw err } } else { if (V?.[Symbol.toStringTag] !== I.prototype[Symbol.toStringTag]) { const err = new TypeError('Illegal invocation') err.code = 'ERR_INVALID_THIS' // node compat. throw err } } } webidl.argumentLengthCheck = function ({ length }, min, ctx) { if (length < min) { throw webidl.errors.exception({ message: `${min} argument${min !== 1 ? 's' : ''} required, ` + `but${length ? ' only' : ''} ${length} found.`, header: ctx }) } } webidl.illegalConstructor = function () { throw webidl.errors.exception({ header: 'TypeError', message: 'Illegal constructor' }) } // https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values webidl.util.Type = function (V) { switch (typeof V) { case 'undefined': return 'Undefined' case 'boolean': return 'Boolean' case 'string': return 'String' case 'symbol': return 'Symbol' case 'number': return 'Number' case 'bigint': return 'BigInt' case 'function': case 'object': { if (V === null) { return 'Null' } return 'Object' } } } webidl.util.markAsUncloneable = markAsUncloneable || (() => {}) // https://webidl.spec.whatwg.org/#abstract-opdef-converttoint webidl.util.ConvertToInt = function (V, bitLength, signedness, opts) { let upperBound let lowerBound // 1. If bitLength is 64, then: if (bitLength === 64) { // 1. Let upperBound be 2^53 − 1. upperBound = Math.pow(2, 53) - 1 // 2. If signedness is "unsigned", then let lowerBound be 0. if (signedness === 'unsigned') { lowerBound = 0 } else { // 3. Otherwise let lowerBound be −2^53 + 1. lowerBound = Math.pow(-2, 53) + 1 } } else if (signedness === 'unsigned') { // 2. Otherwise, if signedness is "unsigned", then: // 1. Let lowerBound be 0. lowerBound = 0 // 2. Let upperBound be 2^bitLength − 1. upperBound = Math.pow(2, bitLength) - 1 } else { // 3. Otherwise: // 1. Let lowerBound be -2^bitLength − 1. lowerBound = Math.pow(-2, bitLength) - 1 // 2. Let upperBound be 2^bitLength − 1 − 1. upperBound = Math.pow(2, bitLength - 1) - 1 } // 4. Let x be ? ToNumber(V). let x = Number(V) // 5. If x is −0, then set x to +0. if (x === 0) { x = 0 } // 6. If the conversion is to an IDL type associated // with the [EnforceRange] extended attribute, then: if (opts?.enforceRange === true) { // 1. If x is NaN, +∞, or −∞, then throw a TypeError. if ( Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Could not convert ${webidl.util.Stringify(V)} to an integer.` }) } // 2. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 3. If x < lowerBound or x > upperBound, then // throw a TypeError. if (x < lowerBound || x > upperBound) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` }) } // 4. Return x. return x } // 7. If x is not NaN and the conversion is to an IDL // type associated with the [Clamp] extended // attribute, then: if (!Number.isNaN(x) && opts?.clamp === true) { // 1. Set x to min(max(x, lowerBound), upperBound). x = Math.min(Math.max(x, lowerBound), upperBound) // 2. Round x to the nearest integer, choosing the // even integer if it lies halfway between two, // and choosing +0 rather than −0. if (Math.floor(x) % 2 === 0) { x = Math.floor(x) } else { x = Math.ceil(x) } // 3. Return x. return x } // 8. If x is NaN, +0, +∞, or −∞, then return +0. if ( Number.isNaN(x) || (x === 0 && Object.is(0, x)) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { return 0 } // 9. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 10. Set x to x modulo 2^bitLength. x = x % Math.pow(2, bitLength) // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, // then return x − 2^bitLength. if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { return x - Math.pow(2, bitLength) } // 12. Otherwise, return x. return x } // https://webidl.spec.whatwg.org/#abstract-opdef-integerpart webidl.util.IntegerPart = function (n) { // 1. Let r be floor(abs(n)). const r = Math.floor(Math.abs(n)) // 2. If n < 0, then return -1 × r. if (n < 0) { return -1 * r } // 3. Otherwise, return r. return r } webidl.util.Stringify = function (V) { const type = webidl.util.Type(V) switch (type) { case 'Symbol': return `Symbol(${V.description})` case 'Object': return inspect(V) case 'String': return `"${V}"` default: return `${V}` } } // https://webidl.spec.whatwg.org/#es-sequence webidl.sequenceConverter = function (converter) { return (V, prefix, argument, Iterable) => { // 1. If Type(V) is not Object, throw a TypeError. if (webidl.util.Type(V) !== 'Object') { throw webidl.errors.exception({ header: prefix, message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.` }) } // 2. Let method be ? GetMethod(V, @@iterator). /** @type {Generator} */ const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.() const seq = [] let index = 0 // 3. If method is undefined, throw a TypeError. if ( method === undefined || typeof method.next !== 'function' ) { throw webidl.errors.exception({ header: prefix, message: `${argument} is not iterable.` }) } // https://webidl.spec.whatwg.org/#create-sequence-from-iterable while (true) { const { done, value } = method.next() if (done) { break } seq.push(converter(value, prefix, `${argument}[${index++}]`)) } return seq } } // https://webidl.spec.whatwg.org/#es-to-record webidl.recordConverter = function (keyConverter, valueConverter) { return (O, prefix, argument) => { // 1. If Type(O) is not Object, throw a TypeError. if (webidl.util.Type(O) !== 'Object') { throw webidl.errors.exception({ header: prefix, message: `${argument} ("${webidl.util.Type(O)}") is not an Object.` }) } // 2. Let result be a new empty instance of record. const result = {} if (!types.isProxy(O)) { // 1. Let desc be ? O.[[GetOwnProperty]](key). const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)] for (const key of keys) { // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key, prefix, argument) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key], prefix, argument) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } // 5. Return result. return result } // 3. Let keys be ? O.[[OwnPropertyKeys]](). const keys = Reflect.ownKeys(O) // 4. For each key of keys. for (const key of keys) { // 1. Let desc be ? O.[[GetOwnProperty]](key). const desc = Reflect.getOwnPropertyDescriptor(O, key) // 2. If desc is not undefined and desc.[[Enumerable]] is true: if (desc?.enumerable) { // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key, prefix, argument) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key], prefix, argument) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } } // 5. Return result. return result } } webidl.interfaceConverter = function (i) { return (V, prefix, argument, opts) => { if (opts?.strict !== false && !(V instanceof i)) { throw webidl.errors.exception({ header: prefix, message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${i.name}.` }) } return V } } webidl.dictionaryConverter = function (converters) { return (dictionary, prefix, argument) => { const type = webidl.util.Type(dictionary) const dict = {} if (type === 'Null' || type === 'Undefined') { return dict } else if (type !== 'Object') { throw webidl.errors.exception({ header: prefix, message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` }) } for (const options of converters) { const { key, defaultValue, required, converter } = options if (required === true) { if (!Object.hasOwn(dictionary, key)) { throw webidl.errors.exception({ header: prefix, message: `Missing required key "${key}".` }) } } let value = dictionary[key] const hasDefault = Object.hasOwn(options, 'defaultValue') // Only use defaultValue if value is undefined and // a defaultValue options was provided. if (hasDefault && value !== null) { value ??= defaultValue() } // A key can be optional and have no default value. // When this happens, do not perform a conversion, // and do not assign the key a value. if (required || hasDefault || value !== undefined) { value = converter(value, prefix, `${argument}.${key}`) if ( options.allowedValues && !options.allowedValues.includes(value) ) { throw webidl.errors.exception({ header: prefix, message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` }) } dict[key] = value } } return dict } } webidl.nullableConverter = function (converter) { return (V, prefix, argument) => { if (V === null) { return V } return converter(V, prefix, argument) } } // https://webidl.spec.whatwg.org/#es-DOMString webidl.converters.DOMString = function (V, prefix, argument, opts) { // 1. If V is null and the conversion is to an IDL type // associated with the [LegacyNullToEmptyString] // extended attribute, then return the DOMString value // that represents the empty string. if (V === null && opts?.legacyNullToEmptyString) { return '' } // 2. Let x be ? ToString(V). if (typeof V === 'symbol') { throw webidl.errors.exception({ header: prefix, message: `${argument} is a symbol, which cannot be converted to a DOMString.` }) } // 3. Return the IDL DOMString value that represents the // same sequence of code units as the one the // ECMAScript String value x represents. return String(V) } // https://webidl.spec.whatwg.org/#es-ByteString webidl.converters.ByteString = function (V, prefix, argument) { // 1. Let x be ? ToString(V). // Note: DOMString converter perform ? ToString(V) const x = webidl.converters.DOMString(V, prefix, argument) // 2. If the value of any element of x is greater than // 255, then throw a TypeError. for (let index = 0; index < x.length; index++) { if (x.charCodeAt(index) > 255) { throw new TypeError( 'Cannot convert argument to a ByteString because the character at ' + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` ) } } // 3. Return an IDL ByteString value whose length is the // length of x, and where the value of each element is // the value of the corresponding element of x. return x } // https://webidl.spec.whatwg.org/#es-USVString // TODO: rewrite this so we can control the errors thrown webidl.converters.USVString = toUSVString // https://webidl.spec.whatwg.org/#es-boolean webidl.converters.boolean = function (V) { // 1. Let x be the result of computing ToBoolean(V). const x = Boolean(V) // 2. Return the IDL boolean value that is the one that represents // the same truth value as the ECMAScript Boolean value x. return x } // https://webidl.spec.whatwg.org/#es-any webidl.converters.any = function (V) { return V } // https://webidl.spec.whatwg.org/#es-long-long webidl.converters['long long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 64, "signed"). const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument) // 2. Return the IDL long long value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long-long webidl.converters['unsigned long long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument) // 2. Return the IDL unsigned long long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long webidl.converters['unsigned long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument) // 2. Return the IDL unsigned long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-short webidl.converters['unsigned short'] = function (V, prefix, argument, opts) { // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument) // 2. Return the IDL unsigned short value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#idl-ArrayBuffer webidl.converters.ArrayBuffer = function (V, prefix, argument, opts) { // 1. If Type(V) is not Object, or V does not have an // [[ArrayBufferData]] internal slot, then throw a // TypeError. // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances if ( webidl.util.Type(V) !== 'Object' || !types.isAnyArrayBuffer(V) ) { throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ['ArrayBuffer'] }) } // 2. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V) is true, then throw a // TypeError. if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V) is true, then throw a // TypeError. if (V.resizable || V.growable) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'Received a resizable ArrayBuffer.' }) } // 4. Return the IDL ArrayBuffer value that is a // reference to the same object as V. return V } webidl.converters.TypedArray = function (V, T, prefix, name, opts) { // 1. Let T be the IDL type V is being converted to. // 2. If Type(V) is not Object, or V does not have a // [[TypedArrayName]] internal slot with a value // equal to T’s name, then throw a TypeError. if ( webidl.util.Type(V) !== 'Object' || !types.isTypedArray(V) || V.constructor.name !== T.name ) { throw webidl.errors.conversionFailed({ prefix, argument: `${name} ("${webidl.util.Stringify(V)}")`, types: [T.name] }) } // 3. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 4. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (V.buffer.resizable || V.buffer.growable) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'Received a resizable ArrayBuffer.' }) } // 5. Return the IDL value of type T that is a reference // to the same object as V. return V } webidl.converters.DataView = function (V, prefix, name, opts) { // 1. If Type(V) is not Object, or V does not have a // [[DataView]] internal slot, then throw a TypeError. if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { throw webidl.errors.exception({ header: prefix, message: `${name} is not a DataView.` }) } // 2. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, // then throw a TypeError. if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (V.buffer.resizable || V.buffer.growable) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'Received a resizable ArrayBuffer.' }) } // 4. Return the IDL DataView value that is a reference // to the same object as V. return V } // https://webidl.spec.whatwg.org/#BufferSource webidl.converters.BufferSource = function (V, prefix, name, opts) { if (types.isAnyArrayBuffer(V)) { return webidl.converters.ArrayBuffer(V, prefix, name, { ...opts, allowShared: false }) } if (types.isTypedArray(V)) { return webidl.converters.TypedArray(V, V.constructor, prefix, name, { ...opts, allowShared: false }) } if (types.isDataView(V)) { return webidl.converters.DataView(V, prefix, name, { ...opts, allowShared: false }) } throw webidl.errors.conversionFailed({ prefix, argument: `${name} ("${webidl.util.Stringify(V)}")`, types: ['BufferSource'] }) } webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.ByteString ) webidl.converters['sequence>'] = webidl.sequenceConverter( webidl.converters['sequence'] ) webidl.converters['record'] = webidl.recordConverter( webidl.converters.ByteString, webidl.converters.ByteString ) module.exports = { webidl } /***/ }), /***/ 2607: /***/ ((module) => { "use strict"; /** * @see https://encoding.spec.whatwg.org/#concept-encoding-get * @param {string|undefined} label */ function getEncoding (label) { if (!label) { return 'failure' } // 1. Remove any leading and trailing ASCII whitespace from label. // 2. If label is an ASCII case-insensitive match for any of the // labels listed in the table below, then return the // corresponding encoding; otherwise return failure. switch (label.trim().toLowerCase()) { case 'unicode-1-1-utf-8': case 'unicode11utf8': case 'unicode20utf8': case 'utf-8': case 'utf8': case 'x-unicode20utf8': return 'UTF-8' case '866': case 'cp866': case 'csibm866': case 'ibm866': return 'IBM866' case 'csisolatin2': case 'iso-8859-2': case 'iso-ir-101': case 'iso8859-2': case 'iso88592': case 'iso_8859-2': case 'iso_8859-2:1987': case 'l2': case 'latin2': return 'ISO-8859-2' case 'csisolatin3': case 'iso-8859-3': case 'iso-ir-109': case 'iso8859-3': case 'iso88593': case 'iso_8859-3': case 'iso_8859-3:1988': case 'l3': case 'latin3': return 'ISO-8859-3' case 'csisolatin4': case 'iso-8859-4': case 'iso-ir-110': case 'iso8859-4': case 'iso88594': case 'iso_8859-4': case 'iso_8859-4:1988': case 'l4': case 'latin4': return 'ISO-8859-4' case 'csisolatincyrillic': case 'cyrillic': case 'iso-8859-5': case 'iso-ir-144': case 'iso8859-5': case 'iso88595': case 'iso_8859-5': case 'iso_8859-5:1988': return 'ISO-8859-5' case 'arabic': case 'asmo-708': case 'csiso88596e': case 'csiso88596i': case 'csisolatinarabic': case 'ecma-114': case 'iso-8859-6': case 'iso-8859-6-e': case 'iso-8859-6-i': case 'iso-ir-127': case 'iso8859-6': case 'iso88596': case 'iso_8859-6': case 'iso_8859-6:1987': return 'ISO-8859-6' case 'csisolatingreek': case 'ecma-118': case 'elot_928': case 'greek': case 'greek8': case 'iso-8859-7': case 'iso-ir-126': case 'iso8859-7': case 'iso88597': case 'iso_8859-7': case 'iso_8859-7:1987': case 'sun_eu_greek': return 'ISO-8859-7' case 'csiso88598e': case 'csisolatinhebrew': case 'hebrew': case 'iso-8859-8': case 'iso-8859-8-e': case 'iso-ir-138': case 'iso8859-8': case 'iso88598': case 'iso_8859-8': case 'iso_8859-8:1988': case 'visual': return 'ISO-8859-8' case 'csiso88598i': case 'iso-8859-8-i': case 'logical': return 'ISO-8859-8-I' case 'csisolatin6': case 'iso-8859-10': case 'iso-ir-157': case 'iso8859-10': case 'iso885910': case 'l6': case 'latin6': return 'ISO-8859-10' case 'iso-8859-13': case 'iso8859-13': case 'iso885913': return 'ISO-8859-13' case 'iso-8859-14': case 'iso8859-14': case 'iso885914': return 'ISO-8859-14' case 'csisolatin9': case 'iso-8859-15': case 'iso8859-15': case 'iso885915': case 'iso_8859-15': case 'l9': return 'ISO-8859-15' case 'iso-8859-16': return 'ISO-8859-16' case 'cskoi8r': case 'koi': case 'koi8': case 'koi8-r': case 'koi8_r': return 'KOI8-R' case 'koi8-ru': case 'koi8-u': return 'KOI8-U' case 'csmacintosh': case 'mac': case 'macintosh': case 'x-mac-roman': return 'macintosh' case 'iso-8859-11': case 'iso8859-11': case 'iso885911': case 'tis-620': case 'windows-874': return 'windows-874' case 'cp1250': case 'windows-1250': case 'x-cp1250': return 'windows-1250' case 'cp1251': case 'windows-1251': case 'x-cp1251': return 'windows-1251' case 'ansi_x3.4-1968': case 'ascii': case 'cp1252': case 'cp819': case 'csisolatin1': case 'ibm819': case 'iso-8859-1': case 'iso-ir-100': case 'iso8859-1': case 'iso88591': case 'iso_8859-1': case 'iso_8859-1:1987': case 'l1': case 'latin1': case 'us-ascii': case 'windows-1252': case 'x-cp1252': return 'windows-1252' case 'cp1253': case 'windows-1253': case 'x-cp1253': return 'windows-1253' case 'cp1254': case 'csisolatin5': case 'iso-8859-9': case 'iso-ir-148': case 'iso8859-9': case 'iso88599': case 'iso_8859-9': case 'iso_8859-9:1989': case 'l5': case 'latin5': case 'windows-1254': case 'x-cp1254': return 'windows-1254' case 'cp1255': case 'windows-1255': case 'x-cp1255': return 'windows-1255' case 'cp1256': case 'windows-1256': case 'x-cp1256': return 'windows-1256' case 'cp1257': case 'windows-1257': case 'x-cp1257': return 'windows-1257' case 'cp1258': case 'windows-1258': case 'x-cp1258': return 'windows-1258' case 'x-mac-cyrillic': case 'x-mac-ukrainian': return 'x-mac-cyrillic' case 'chinese': case 'csgb2312': case 'csiso58gb231280': case 'gb2312': case 'gb_2312': case 'gb_2312-80': case 'gbk': case 'iso-ir-58': case 'x-gbk': return 'GBK' case 'gb18030': return 'gb18030' case 'big5': case 'big5-hkscs': case 'cn-big5': case 'csbig5': case 'x-x-big5': return 'Big5' case 'cseucpkdfmtjapanese': case 'euc-jp': case 'x-euc-jp': return 'EUC-JP' case 'csiso2022jp': case 'iso-2022-jp': return 'ISO-2022-JP' case 'csshiftjis': case 'ms932': case 'ms_kanji': case 'shift-jis': case 'shift_jis': case 'sjis': case 'windows-31j': case 'x-sjis': return 'Shift_JIS' case 'cseuckr': case 'csksc56011987': case 'euc-kr': case 'iso-ir-149': case 'korean': case 'ks_c_5601-1987': case 'ks_c_5601-1989': case 'ksc5601': case 'ksc_5601': case 'windows-949': return 'EUC-KR' case 'csiso2022kr': case 'hz-gb-2312': case 'iso-2022-cn': case 'iso-2022-cn-ext': case 'iso-2022-kr': case 'replacement': return 'replacement' case 'unicodefffe': case 'utf-16be': return 'UTF-16BE' case 'csunicode': case 'iso-10646-ucs-2': case 'ucs-2': case 'unicode': case 'unicodefeff': case 'utf-16': case 'utf-16le': return 'UTF-16LE' case 'x-user-defined': return 'x-user-defined' default: return 'failure' } } module.exports = { getEncoding } /***/ }), /***/ 8355: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { staticPropertyDescriptors, readOperation, fireAProgressEvent } = __nccwpck_require__(3610) const { kState, kError, kResult, kEvents, kAborted } = __nccwpck_require__(961) const { webidl } = __nccwpck_require__(5893) const { kEnumerableProperty } = __nccwpck_require__(3440) class FileReader extends EventTarget { constructor () { super() this[kState] = 'empty' this[kResult] = null this[kError] = null this[kEvents] = { loadend: null, error: null, abort: null, load: null, progress: null, loadstart: null } } /** * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer * @param {import('buffer').Blob} blob */ readAsArrayBuffer (blob) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsArrayBuffer') blob = webidl.converters.Blob(blob, { strict: false }) // The readAsArrayBuffer(blob) method, when invoked, // must initiate a read operation for blob with ArrayBuffer. readOperation(this, blob, 'ArrayBuffer') } /** * @see https://w3c.github.io/FileAPI/#readAsBinaryString * @param {import('buffer').Blob} blob */ readAsBinaryString (blob) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsBinaryString') blob = webidl.converters.Blob(blob, { strict: false }) // The readAsBinaryString(blob) method, when invoked, // must initiate a read operation for blob with BinaryString. readOperation(this, blob, 'BinaryString') } /** * @see https://w3c.github.io/FileAPI/#readAsDataText * @param {import('buffer').Blob} blob * @param {string?} encoding */ readAsText (blob, encoding = undefined) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsText') blob = webidl.converters.Blob(blob, { strict: false }) if (encoding !== undefined) { encoding = webidl.converters.DOMString(encoding, 'FileReader.readAsText', 'encoding') } // The readAsText(blob, encoding) method, when invoked, // must initiate a read operation for blob with Text and encoding. readOperation(this, blob, 'Text', encoding) } /** * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL * @param {import('buffer').Blob} blob */ readAsDataURL (blob) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsDataURL') blob = webidl.converters.Blob(blob, { strict: false }) // The readAsDataURL(blob) method, when invoked, must // initiate a read operation for blob with DataURL. readOperation(this, blob, 'DataURL') } /** * @see https://w3c.github.io/FileAPI/#dfn-abort */ abort () { // 1. If this's state is "empty" or if this's state is // "done" set this's result to null and terminate // this algorithm. if (this[kState] === 'empty' || this[kState] === 'done') { this[kResult] = null return } // 2. If this's state is "loading" set this's state to // "done" and set this's result to null. if (this[kState] === 'loading') { this[kState] = 'done' this[kResult] = null } // 3. If there are any tasks from this on the file reading // task source in an affiliated task queue, then remove // those tasks from that task queue. this[kAborted] = true // 4. Terminate the algorithm for the read method being processed. // TODO // 5. Fire a progress event called abort at this. fireAProgressEvent('abort', this) // 6. If this's state is not "loading", fire a progress // event called loadend at this. if (this[kState] !== 'loading') { fireAProgressEvent('loadend', this) } } /** * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate */ get readyState () { webidl.brandCheck(this, FileReader) switch (this[kState]) { case 'empty': return this.EMPTY case 'loading': return this.LOADING case 'done': return this.DONE } } /** * @see https://w3c.github.io/FileAPI/#dom-filereader-result */ get result () { webidl.brandCheck(this, FileReader) // The result attribute’s getter, when invoked, must return // this's result. return this[kResult] } /** * @see https://w3c.github.io/FileAPI/#dom-filereader-error */ get error () { webidl.brandCheck(this, FileReader) // The error attribute’s getter, when invoked, must return // this's error. return this[kError] } get onloadend () { webidl.brandCheck(this, FileReader) return this[kEvents].loadend } set onloadend (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].loadend) { this.removeEventListener('loadend', this[kEvents].loadend) } if (typeof fn === 'function') { this[kEvents].loadend = fn this.addEventListener('loadend', fn) } else { this[kEvents].loadend = null } } get onerror () { webidl.brandCheck(this, FileReader) return this[kEvents].error } set onerror (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].error) { this.removeEventListener('error', this[kEvents].error) } if (typeof fn === 'function') { this[kEvents].error = fn this.addEventListener('error', fn) } else { this[kEvents].error = null } } get onloadstart () { webidl.brandCheck(this, FileReader) return this[kEvents].loadstart } set onloadstart (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].loadstart) { this.removeEventListener('loadstart', this[kEvents].loadstart) } if (typeof fn === 'function') { this[kEvents].loadstart = fn this.addEventListener('loadstart', fn) } else { this[kEvents].loadstart = null } } get onprogress () { webidl.brandCheck(this, FileReader) return this[kEvents].progress } set onprogress (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].progress) { this.removeEventListener('progress', this[kEvents].progress) } if (typeof fn === 'function') { this[kEvents].progress = fn this.addEventListener('progress', fn) } else { this[kEvents].progress = null } } get onload () { webidl.brandCheck(this, FileReader) return this[kEvents].load } set onload (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].load) { this.removeEventListener('load', this[kEvents].load) } if (typeof fn === 'function') { this[kEvents].load = fn this.addEventListener('load', fn) } else { this[kEvents].load = null } } get onabort () { webidl.brandCheck(this, FileReader) return this[kEvents].abort } set onabort (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].abort) { this.removeEventListener('abort', this[kEvents].abort) } if (typeof fn === 'function') { this[kEvents].abort = fn this.addEventListener('abort', fn) } else { this[kEvents].abort = null } } } // https://w3c.github.io/FileAPI/#dom-filereader-empty FileReader.EMPTY = FileReader.prototype.EMPTY = 0 // https://w3c.github.io/FileAPI/#dom-filereader-loading FileReader.LOADING = FileReader.prototype.LOADING = 1 // https://w3c.github.io/FileAPI/#dom-filereader-done FileReader.DONE = FileReader.prototype.DONE = 2 Object.defineProperties(FileReader.prototype, { EMPTY: staticPropertyDescriptors, LOADING: staticPropertyDescriptors, DONE: staticPropertyDescriptors, readAsArrayBuffer: kEnumerableProperty, readAsBinaryString: kEnumerableProperty, readAsText: kEnumerableProperty, readAsDataURL: kEnumerableProperty, abort: kEnumerableProperty, readyState: kEnumerableProperty, result: kEnumerableProperty, error: kEnumerableProperty, onloadstart: kEnumerableProperty, onprogress: kEnumerableProperty, onload: kEnumerableProperty, onabort: kEnumerableProperty, onerror: kEnumerableProperty, onloadend: kEnumerableProperty, [Symbol.toStringTag]: { value: 'FileReader', writable: false, enumerable: false, configurable: true } }) Object.defineProperties(FileReader, { EMPTY: staticPropertyDescriptors, LOADING: staticPropertyDescriptors, DONE: staticPropertyDescriptors }) module.exports = { FileReader } /***/ }), /***/ 8573: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { webidl } = __nccwpck_require__(5893) const kState = Symbol('ProgressEvent state') /** * @see https://xhr.spec.whatwg.org/#progressevent */ class ProgressEvent extends Event { constructor (type, eventInitDict = {}) { type = webidl.converters.DOMString(type, 'ProgressEvent constructor', 'type') eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) super(type, eventInitDict) this[kState] = { lengthComputable: eventInitDict.lengthComputable, loaded: eventInitDict.loaded, total: eventInitDict.total } } get lengthComputable () { webidl.brandCheck(this, ProgressEvent) return this[kState].lengthComputable } get loaded () { webidl.brandCheck(this, ProgressEvent) return this[kState].loaded } get total () { webidl.brandCheck(this, ProgressEvent) return this[kState].total } } webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ { key: 'lengthComputable', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'loaded', converter: webidl.converters['unsigned long long'], defaultValue: () => 0 }, { key: 'total', converter: webidl.converters['unsigned long long'], defaultValue: () => 0 }, { key: 'bubbles', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'cancelable', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'composed', converter: webidl.converters.boolean, defaultValue: () => false } ]) module.exports = { ProgressEvent } /***/ }), /***/ 961: /***/ ((module) => { "use strict"; module.exports = { kState: Symbol('FileReader state'), kResult: Symbol('FileReader result'), kError: Symbol('FileReader error'), kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), kEvents: Symbol('FileReader events'), kAborted: Symbol('FileReader aborted') } /***/ }), /***/ 3610: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kState, kError, kResult, kAborted, kLastProgressEventFired } = __nccwpck_require__(961) const { ProgressEvent } = __nccwpck_require__(8573) const { getEncoding } = __nccwpck_require__(2607) const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(1900) const { types } = __nccwpck_require__(7975) const { StringDecoder } = __nccwpck_require__(3193) const { btoa } = __nccwpck_require__(4573) /** @type {PropertyDescriptor} */ const staticPropertyDescriptors = { enumerable: true, writable: false, configurable: false } /** * @see https://w3c.github.io/FileAPI/#readOperation * @param {import('./filereader').FileReader} fr * @param {import('buffer').Blob} blob * @param {string} type * @param {string?} encodingName */ function readOperation (fr, blob, type, encodingName) { // 1. If fr’s state is "loading", throw an InvalidStateError // DOMException. if (fr[kState] === 'loading') { throw new DOMException('Invalid state', 'InvalidStateError') } // 2. Set fr’s state to "loading". fr[kState] = 'loading' // 3. Set fr’s result to null. fr[kResult] = null // 4. Set fr’s error to null. fr[kError] = null // 5. Let stream be the result of calling get stream on blob. /** @type {import('stream/web').ReadableStream} */ const stream = blob.stream() // 6. Let reader be the result of getting a reader from stream. const reader = stream.getReader() // 7. Let bytes be an empty byte sequence. /** @type {Uint8Array[]} */ const bytes = [] // 8. Let chunkPromise be the result of reading a chunk from // stream with reader. let chunkPromise = reader.read() // 9. Let isFirstChunk be true. let isFirstChunk = true // 10. In parallel, while true: // Note: "In parallel" just means non-blocking // Note 2: readOperation itself cannot be async as double // reading the body would then reject the promise, instead // of throwing an error. ;(async () => { while (!fr[kAborted]) { // 1. Wait for chunkPromise to be fulfilled or rejected. try { const { done, value } = await chunkPromise // 2. If chunkPromise is fulfilled, and isFirstChunk is // true, queue a task to fire a progress event called // loadstart at fr. if (isFirstChunk && !fr[kAborted]) { queueMicrotask(() => { fireAProgressEvent('loadstart', fr) }) } // 3. Set isFirstChunk to false. isFirstChunk = false // 4. If chunkPromise is fulfilled with an object whose // done property is false and whose value property is // a Uint8Array object, run these steps: if (!done && types.isUint8Array(value)) { // 1. Let bs be the byte sequence represented by the // Uint8Array object. // 2. Append bs to bytes. bytes.push(value) // 3. If roughly 50ms have passed since these steps // were last invoked, queue a task to fire a // progress event called progress at fr. if ( ( fr[kLastProgressEventFired] === undefined || Date.now() - fr[kLastProgressEventFired] >= 50 ) && !fr[kAborted] ) { fr[kLastProgressEventFired] = Date.now() queueMicrotask(() => { fireAProgressEvent('progress', fr) }) } // 4. Set chunkPromise to the result of reading a // chunk from stream with reader. chunkPromise = reader.read() } else if (done) { // 5. Otherwise, if chunkPromise is fulfilled with an // object whose done property is true, queue a task // to run the following steps and abort this algorithm: queueMicrotask(() => { // 1. Set fr’s state to "done". fr[kState] = 'done' // 2. Let result be the result of package data given // bytes, type, blob’s type, and encodingName. try { const result = packageData(bytes, type, blob.type, encodingName) // 4. Else: if (fr[kAborted]) { return } // 1. Set fr’s result to result. fr[kResult] = result // 2. Fire a progress event called load at the fr. fireAProgressEvent('load', fr) } catch (error) { // 3. If package data threw an exception error: // 1. Set fr’s error to error. fr[kError] = error // 2. Fire a progress event called error at fr. fireAProgressEvent('error', fr) } // 5. If fr’s state is not "loading", fire a progress // event called loadend at the fr. if (fr[kState] !== 'loading') { fireAProgressEvent('loadend', fr) } }) break } } catch (error) { if (fr[kAborted]) { return } // 6. Otherwise, if chunkPromise is rejected with an // error error, queue a task to run the following // steps and abort this algorithm: queueMicrotask(() => { // 1. Set fr’s state to "done". fr[kState] = 'done' // 2. Set fr’s error to error. fr[kError] = error // 3. Fire a progress event called error at fr. fireAProgressEvent('error', fr) // 4. If fr’s state is not "loading", fire a progress // event called loadend at fr. if (fr[kState] !== 'loading') { fireAProgressEvent('loadend', fr) } }) break } } })() } /** * @see https://w3c.github.io/FileAPI/#fire-a-progress-event * @see https://dom.spec.whatwg.org/#concept-event-fire * @param {string} e The name of the event * @param {import('./filereader').FileReader} reader */ function fireAProgressEvent (e, reader) { // The progress event e does not bubble. e.bubbles must be false // The progress event e is NOT cancelable. e.cancelable must be false const event = new ProgressEvent(e, { bubbles: false, cancelable: false }) reader.dispatchEvent(event) } /** * @see https://w3c.github.io/FileAPI/#blob-package-data * @param {Uint8Array[]} bytes * @param {string} type * @param {string?} mimeType * @param {string?} encodingName */ function packageData (bytes, type, mimeType, encodingName) { // 1. A Blob has an associated package data algorithm, given // bytes, a type, a optional mimeType, and a optional // encodingName, which switches on type and runs the // associated steps: switch (type) { case 'DataURL': { // 1. Return bytes as a DataURL [RFC2397] subject to // the considerations below: // * Use mimeType as part of the Data URL if it is // available in keeping with the Data URL // specification [RFC2397]. // * If mimeType is not available return a Data URL // without a media-type. [RFC2397]. // https://datatracker.ietf.org/doc/html/rfc2397#section-3 // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data // mediatype := [ type "/" subtype ] *( ";" parameter ) // data := *urlchar // parameter := attribute "=" value let dataURL = 'data:' const parsed = parseMIMEType(mimeType || 'application/octet-stream') if (parsed !== 'failure') { dataURL += serializeAMimeType(parsed) } dataURL += ';base64,' const decoder = new StringDecoder('latin1') for (const chunk of bytes) { dataURL += btoa(decoder.write(chunk)) } dataURL += btoa(decoder.end()) return dataURL } case 'Text': { // 1. Let encoding be failure let encoding = 'failure' // 2. If the encodingName is present, set encoding to the // result of getting an encoding from encodingName. if (encodingName) { encoding = getEncoding(encodingName) } // 3. If encoding is failure, and mimeType is present: if (encoding === 'failure' && mimeType) { // 1. Let type be the result of parse a MIME type // given mimeType. const type = parseMIMEType(mimeType) // 2. If type is not failure, set encoding to the result // of getting an encoding from type’s parameters["charset"]. if (type !== 'failure') { encoding = getEncoding(type.parameters.get('charset')) } } // 4. If encoding is failure, then set encoding to UTF-8. if (encoding === 'failure') { encoding = 'UTF-8' } // 5. Decode bytes using fallback encoding encoding, and // return the result. return decode(bytes, encoding) } case 'ArrayBuffer': { // Return a new ArrayBuffer whose contents are bytes. const sequence = combineByteSequences(bytes) return sequence.buffer } case 'BinaryString': { // Return bytes as a binary string, in which every byte // is represented by a code unit of equal value [0..255]. let binaryString = '' const decoder = new StringDecoder('latin1') for (const chunk of bytes) { binaryString += decoder.write(chunk) } binaryString += decoder.end() return binaryString } } } /** * @see https://encoding.spec.whatwg.org/#decode * @param {Uint8Array[]} ioQueue * @param {string} encoding */ function decode (ioQueue, encoding) { const bytes = combineByteSequences(ioQueue) // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. const BOMEncoding = BOMSniffing(bytes) let slice = 0 // 2. If BOMEncoding is non-null: if (BOMEncoding !== null) { // 1. Set encoding to BOMEncoding. encoding = BOMEncoding // 2. Read three bytes from ioQueue, if BOMEncoding is // UTF-8; otherwise read two bytes. // (Do nothing with those bytes.) slice = BOMEncoding === 'UTF-8' ? 3 : 2 } // 3. Process a queue with an instance of encoding’s // decoder, ioQueue, output, and "replacement". // 4. Return output. const sliced = bytes.slice(slice) return new TextDecoder(encoding).decode(sliced) } /** * @see https://encoding.spec.whatwg.org/#bom-sniff * @param {Uint8Array} ioQueue */ function BOMSniffing (ioQueue) { // 1. Let BOM be the result of peeking 3 bytes from ioQueue, // converted to a byte sequence. const [a, b, c] = ioQueue // 2. For each of the rows in the table below, starting with // the first one and going down, if BOM starts with the // bytes given in the first column, then return the // encoding given in the cell in the second column of that // row. Otherwise, return null. if (a === 0xEF && b === 0xBB && c === 0xBF) { return 'UTF-8' } else if (a === 0xFE && b === 0xFF) { return 'UTF-16BE' } else if (a === 0xFF && b === 0xFE) { return 'UTF-16LE' } return null } /** * @param {Uint8Array[]} sequences */ function combineByteSequences (sequences) { const size = sequences.reduce((a, b) => { return a + b.byteLength }, 0) let offset = 0 return sequences.reduce((a, b) => { a.set(b, offset) offset += b.byteLength return a }, new Uint8Array(size)) } module.exports = { staticPropertyDescriptors, readOperation, fireAProgressEvent } /***/ }), /***/ 6897: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = __nccwpck_require__(736) const { kReadyState, kSentClose, kByteParser, kReceivedClose, kResponse } = __nccwpck_require__(1216) const { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = __nccwpck_require__(8625) const { channels } = __nccwpck_require__(2414) const { CloseEvent } = __nccwpck_require__(5188) const { makeRequest } = __nccwpck_require__(9967) const { fetching } = __nccwpck_require__(4398) const { Headers, getHeadersList } = __nccwpck_require__(660) const { getDecodeSplit } = __nccwpck_require__(3168) const { WebsocketFrameSend } = __nccwpck_require__(3264) /** @type {import('crypto')} */ let crypto try { crypto = __nccwpck_require__(7598) /* c8 ignore next 3 */ } catch { } /** * @see https://websockets.spec.whatwg.org/#concept-websocket-establish * @param {URL} url * @param {string|string[]} protocols * @param {import('./websocket').WebSocket} ws * @param {(response: any, extensions: string[] | undefined) => void} onEstablish * @param {Partial} options */ function establishWebSocketConnection (url, protocols, client, ws, onEstablish, options) { // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s // scheme is "ws", and to "https" otherwise. const requestURL = url requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' // 2. Let request be a new request, whose URL is requestURL, client is client, // service-workers mode is "none", referrer is "no-referrer", mode is // "websocket", credentials mode is "include", cache mode is "no-store" , // and redirect mode is "error". const request = makeRequest({ urlList: [requestURL], client, serviceWorkers: 'none', referrer: 'no-referrer', mode: 'websocket', credentials: 'include', cache: 'no-store', redirect: 'error' }) // Note: undici extension, allow setting custom headers. if (options.headers) { const headersList = getHeadersList(new Headers(options.headers)) request.headersList = headersList } // 3. Append (`Upgrade`, `websocket`) to request’s header list. // 4. Append (`Connection`, `Upgrade`) to request’s header list. // Note: both of these are handled by undici currently. // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 // 5. Let keyValue be a nonce consisting of a randomly selected // 16-byte value that has been forgiving-base64-encoded and // isomorphic encoded. const keyValue = crypto.randomBytes(16).toString('base64') // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s // header list. request.headersList.append('sec-websocket-key', keyValue) // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s // header list. request.headersList.append('sec-websocket-version', '13') // 8. For each protocol in protocols, combine // (`Sec-WebSocket-Protocol`, protocol) in request’s header // list. for (const protocol of protocols) { request.headersList.append('sec-websocket-protocol', protocol) } // 9. Let permessageDeflate be a user-agent defined // "permessage-deflate" extension header value. // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 const permessageDeflate = 'permessage-deflate; client_max_window_bits' // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to // request’s header list. request.headersList.append('sec-websocket-extensions', permessageDeflate) // 11. Fetch request with useParallelQueue set to true, and // processResponse given response being these steps: const controller = fetching({ request, useParallelQueue: true, dispatcher: options.dispatcher, processResponse (response) { // 1. If response is a network error or its status is not 101, // fail the WebSocket connection. if (response.type === 'error' || response.status !== 101) { failWebsocketConnection(ws, 'Received network error or non-101 status code.') return } // 2. If protocols is not the empty list and extracting header // list values given `Sec-WebSocket-Protocol` and response’s // header list results in null, failure, or the empty byte // sequence, then fail the WebSocket connection. if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { failWebsocketConnection(ws, 'Server did not respond with sent protocols.') return } // 3. Follow the requirements stated step 2 to step 6, inclusive, // of the last set of steps in section 4.1 of The WebSocket // Protocol to validate response. This either results in fail // the WebSocket connection or the WebSocket connection is // established. // 2. If the response lacks an |Upgrade| header field or the |Upgrade| // header field contains a value that is not an ASCII case- // insensitive match for the value "websocket", the client MUST // _Fail the WebSocket Connection_. if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') return } // 3. If the response lacks a |Connection| header field or the // |Connection| header field doesn't contain a token that is an // ASCII case-insensitive match for the value "Upgrade", the client // MUST _Fail the WebSocket Connection_. if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') return } // 4. If the response lacks a |Sec-WebSocket-Accept| header field or // the |Sec-WebSocket-Accept| contains a value other than the // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- // Key| (as a string, not base64-decoded) with the string "258EAFA5- // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and // trailing whitespace, the client MUST _Fail the WebSocket // Connection_. const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') if (secWSAccept !== digest) { failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') return } // 5. If the response includes a |Sec-WebSocket-Extensions| header // field and this header field indicates the use of an extension // that was not present in the client's handshake (the server has // indicated an extension not requested by the client), the client // MUST _Fail the WebSocket Connection_. (The parsing of this // header field to determine which extensions are requested is // discussed in Section 9.1.) const secExtension = response.headersList.get('Sec-WebSocket-Extensions') let extensions if (secExtension !== null) { extensions = parseExtensions(secExtension) if (!extensions.has('permessage-deflate')) { failWebsocketConnection(ws, 'Sec-WebSocket-Extensions header does not match.') return } } // 6. If the response includes a |Sec-WebSocket-Protocol| header field // and this header field indicates the use of a subprotocol that was // not present in the client's handshake (the server has indicated a // subprotocol not requested by the client), the client MUST _Fail // the WebSocket Connection_. const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') if (secProtocol !== null) { const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList) // The client can request that the server use a specific subprotocol by // including the |Sec-WebSocket-Protocol| field in its handshake. If it // is specified, the server needs to include the same field and one of // the selected subprotocol values in its response for the connection to // be established. if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') return } } response.socket.on('data', onSocketData) response.socket.on('close', onSocketClose) response.socket.on('error', onSocketError) if (channels.open.hasSubscribers) { channels.open.publish({ address: response.socket.address(), protocol: secProtocol, extensions: secExtension }) } onEstablish(response, extensions) } }) return controller } function closeWebSocketConnection (ws, code, reason, reasonByteLength) { if (isClosing(ws) || isClosed(ws)) { // If this's ready state is CLOSING (2) or CLOSED (3) // Do nothing. } else if (!isEstablished(ws)) { // If the WebSocket connection is not yet established // Fail the WebSocket connection and set this's ready state // to CLOSING (2). failWebsocketConnection(ws, 'Connection was closed before it was established.') ws[kReadyState] = states.CLOSING } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) { // If the WebSocket closing handshake has not yet been started // Start the WebSocket closing handshake and set this's ready // state to CLOSING (2). // - If neither code nor reason is present, the WebSocket Close // message must not have a body. // - If code is present, then the status code to use in the // WebSocket Close message must be the integer given by code. // - If reason is also present, then reasonBytes must be // provided in the Close message after the status code. ws[kSentClose] = sentCloseFrameState.PROCESSING const frame = new WebsocketFrameSend() // If neither code nor reason is present, the WebSocket Close // message must not have a body. // If code is present, then the status code to use in the // WebSocket Close message must be the integer given by code. if (code !== undefined && reason === undefined) { frame.frameData = Buffer.allocUnsafe(2) frame.frameData.writeUInt16BE(code, 0) } else if (code !== undefined && reason !== undefined) { // If reason is also present, then reasonBytes must be // provided in the Close message after the status code. frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) frame.frameData.writeUInt16BE(code, 0) // the body MAY contain UTF-8-encoded data with value /reason/ frame.frameData.write(reason, 2, 'utf-8') } else { frame.frameData = emptyBuffer } /** @type {import('stream').Duplex} */ const socket = ws[kResponse].socket socket.write(frame.createFrame(opcodes.CLOSE)) ws[kSentClose] = sentCloseFrameState.SENT // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. ws[kReadyState] = states.CLOSING } else { // Otherwise // Set this's ready state to CLOSING (2). ws[kReadyState] = states.CLOSING } } /** * @param {Buffer} chunk */ function onSocketData (chunk) { if (!this.ws[kByteParser].write(chunk)) { this.pause() } } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 */ function onSocketClose () { const { ws } = this const { [kResponse]: response } = ws response.socket.off('data', onSocketData) response.socket.off('close', onSocketClose) response.socket.off('error', onSocketError) // If the TCP connection was closed after the // WebSocket closing handshake was completed, the WebSocket connection // is said to have been closed _cleanly_. const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose] let code = 1005 let reason = '' const result = ws[kByteParser].closingInfo if (result && !result.error) { code = result.code ?? 1005 reason = result.reason } else if (!ws[kReceivedClose]) { // If _The WebSocket // Connection is Closed_ and no Close control frame was received by the // endpoint (such as could occur if the underlying transport connection // is lost), _The WebSocket Connection Close Code_ is considered to be // 1006. code = 1006 } // 1. Change the ready state to CLOSED (3). ws[kReadyState] = states.CLOSED // 2. If the user agent was required to fail the WebSocket // connection, or if the WebSocket connection was closed // after being flagged as full, fire an event named error // at the WebSocket object. // TODO // 3. Fire an event named close at the WebSocket object, // using CloseEvent, with the wasClean attribute // initialized to true if the connection closed cleanly // and false otherwise, the code attribute initialized to // the WebSocket connection close code, and the reason // attribute initialized to the result of applying UTF-8 // decode without BOM to the WebSocket connection close // reason. // TODO: process.nextTick fireEvent('close', ws, (type, init) => new CloseEvent(type, init), { wasClean, code, reason }) if (channels.close.hasSubscribers) { channels.close.publish({ websocket: ws, code, reason }) } } function onSocketError (error) { const { ws } = this ws[kReadyState] = states.CLOSING if (channels.socketError.hasSubscribers) { channels.socketError.publish(error) } this.destroy() } module.exports = { establishWebSocketConnection, closeWebSocketConnection } /***/ }), /***/ 736: /***/ ((module) => { "use strict"; // This is a Globally Unique Identifier unique used // to validate that the endpoint accepts websocket // connections. // See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' /** @type {PropertyDescriptor} */ const staticPropertyDescriptors = { enumerable: true, writable: false, configurable: false } const states = { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 } const sentCloseFrameState = { NOT_SENT: 0, PROCESSING: 1, SENT: 2 } const opcodes = { CONTINUATION: 0x0, TEXT: 0x1, BINARY: 0x2, CLOSE: 0x8, PING: 0x9, PONG: 0xA } const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 const parserStates = { INFO: 0, PAYLOADLENGTH_16: 2, PAYLOADLENGTH_64: 3, READ_DATA: 4 } const emptyBuffer = Buffer.allocUnsafe(0) const sendHints = { string: 1, typedArray: 2, arrayBuffer: 3, blob: 4 } module.exports = { uid, sentCloseFrameState, staticPropertyDescriptors, states, opcodes, maxUnsigned16Bit, parserStates, emptyBuffer, sendHints } /***/ }), /***/ 5188: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { webidl } = __nccwpck_require__(5893) const { kEnumerableProperty } = __nccwpck_require__(3440) const { kConstruct } = __nccwpck_require__(6443) const { MessagePort } = __nccwpck_require__(5919) /** * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent */ class MessageEvent extends Event { #eventInit constructor (type, eventInitDict = {}) { if (type === kConstruct) { super(arguments[1], arguments[2]) webidl.util.markAsUncloneable(this) return } const prefix = 'MessageEvent constructor' webidl.argumentLengthCheck(arguments, 1, prefix) type = webidl.converters.DOMString(type, prefix, 'type') eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict') super(type, eventInitDict) this.#eventInit = eventInitDict webidl.util.markAsUncloneable(this) } get data () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.data } get origin () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.origin } get lastEventId () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.lastEventId } get source () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.source } get ports () { webidl.brandCheck(this, MessageEvent) if (!Object.isFrozen(this.#eventInit.ports)) { Object.freeze(this.#eventInit.ports) } return this.#eventInit.ports } initMessageEvent ( type, bubbles = false, cancelable = false, data = null, origin = '', lastEventId = '', source = null, ports = [] ) { webidl.brandCheck(this, MessageEvent) webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent') return new MessageEvent(type, { bubbles, cancelable, data, origin, lastEventId, source, ports }) } static createFastMessageEvent (type, init) { const messageEvent = new MessageEvent(kConstruct, type, init) messageEvent.#eventInit = init messageEvent.#eventInit.data ??= null messageEvent.#eventInit.origin ??= '' messageEvent.#eventInit.lastEventId ??= '' messageEvent.#eventInit.source ??= null messageEvent.#eventInit.ports ??= [] return messageEvent } } const { createFastMessageEvent } = MessageEvent delete MessageEvent.createFastMessageEvent /** * @see https://websockets.spec.whatwg.org/#the-closeevent-interface */ class CloseEvent extends Event { #eventInit constructor (type, eventInitDict = {}) { const prefix = 'CloseEvent constructor' webidl.argumentLengthCheck(arguments, 1, prefix) type = webidl.converters.DOMString(type, prefix, 'type') eventInitDict = webidl.converters.CloseEventInit(eventInitDict) super(type, eventInitDict) this.#eventInit = eventInitDict webidl.util.markAsUncloneable(this) } get wasClean () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.wasClean } get code () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.code } get reason () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.reason } } // https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface class ErrorEvent extends Event { #eventInit constructor (type, eventInitDict) { const prefix = 'ErrorEvent constructor' webidl.argumentLengthCheck(arguments, 1, prefix) super(type, eventInitDict) webidl.util.markAsUncloneable(this) type = webidl.converters.DOMString(type, prefix, 'type') eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) this.#eventInit = eventInitDict } get message () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.message } get filename () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.filename } get lineno () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.lineno } get colno () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.colno } get error () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.error } } Object.defineProperties(MessageEvent.prototype, { [Symbol.toStringTag]: { value: 'MessageEvent', configurable: true }, data: kEnumerableProperty, origin: kEnumerableProperty, lastEventId: kEnumerableProperty, source: kEnumerableProperty, ports: kEnumerableProperty, initMessageEvent: kEnumerableProperty }) Object.defineProperties(CloseEvent.prototype, { [Symbol.toStringTag]: { value: 'CloseEvent', configurable: true }, reason: kEnumerableProperty, code: kEnumerableProperty, wasClean: kEnumerableProperty }) Object.defineProperties(ErrorEvent.prototype, { [Symbol.toStringTag]: { value: 'ErrorEvent', configurable: true }, message: kEnumerableProperty, filename: kEnumerableProperty, lineno: kEnumerableProperty, colno: kEnumerableProperty, error: kEnumerableProperty }) webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.MessagePort ) const eventInit = [ { key: 'bubbles', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'cancelable', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'composed', converter: webidl.converters.boolean, defaultValue: () => false } ] webidl.converters.MessageEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'data', converter: webidl.converters.any, defaultValue: () => null }, { key: 'origin', converter: webidl.converters.USVString, defaultValue: () => '' }, { key: 'lastEventId', converter: webidl.converters.DOMString, defaultValue: () => '' }, { key: 'source', // Node doesn't implement WindowProxy or ServiceWorker, so the only // valid value for source is a MessagePort. converter: webidl.nullableConverter(webidl.converters.MessagePort), defaultValue: () => null }, { key: 'ports', converter: webidl.converters['sequence'], defaultValue: () => new Array(0) } ]) webidl.converters.CloseEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'wasClean', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'code', converter: webidl.converters['unsigned short'], defaultValue: () => 0 }, { key: 'reason', converter: webidl.converters.USVString, defaultValue: () => '' } ]) webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'message', converter: webidl.converters.DOMString, defaultValue: () => '' }, { key: 'filename', converter: webidl.converters.USVString, defaultValue: () => '' }, { key: 'lineno', converter: webidl.converters['unsigned long'], defaultValue: () => 0 }, { key: 'colno', converter: webidl.converters['unsigned long'], defaultValue: () => 0 }, { key: 'error', converter: webidl.converters.any } ]) module.exports = { MessageEvent, CloseEvent, ErrorEvent, createFastMessageEvent } /***/ }), /***/ 3264: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { maxUnsigned16Bit } = __nccwpck_require__(736) const BUFFER_SIZE = 16386 /** @type {import('crypto')} */ let crypto let buffer = null let bufIdx = BUFFER_SIZE try { crypto = __nccwpck_require__(7598) /* c8 ignore next 3 */ } catch { crypto = { // not full compatibility, but minimum. randomFillSync: function randomFillSync (buffer, _offset, _size) { for (let i = 0; i < buffer.length; ++i) { buffer[i] = Math.random() * 255 | 0 } return buffer } } } function generateMask () { if (bufIdx === BUFFER_SIZE) { bufIdx = 0 crypto.randomFillSync((buffer ??= Buffer.allocUnsafe(BUFFER_SIZE)), 0, BUFFER_SIZE) } return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]] } class WebsocketFrameSend { /** * @param {Buffer|undefined} data */ constructor (data) { this.frameData = data } createFrame (opcode) { const frameData = this.frameData const maskKey = generateMask() const bodyLength = frameData?.byteLength ?? 0 /** @type {number} */ let payloadLength = bodyLength // 0-125 let offset = 6 if (bodyLength > maxUnsigned16Bit) { offset += 8 // payload length is next 8 bytes payloadLength = 127 } else if (bodyLength > 125) { offset += 2 // payload length is next 2 bytes payloadLength = 126 } const buffer = Buffer.allocUnsafe(bodyLength + offset) // Clear first 2 bytes, everything else is overwritten buffer[0] = buffer[1] = 0 buffer[0] |= 0x80 // FIN buffer[0] = (buffer[0] & 0xF0) + opcode // opcode /*! ws. MIT License. Einar Otto Stangvik */ buffer[offset - 4] = maskKey[0] buffer[offset - 3] = maskKey[1] buffer[offset - 2] = maskKey[2] buffer[offset - 1] = maskKey[3] buffer[1] = payloadLength if (payloadLength === 126) { buffer.writeUInt16BE(bodyLength, 2) } else if (payloadLength === 127) { // Clear extended payload length buffer[2] = buffer[3] = 0 buffer.writeUIntBE(bodyLength, 4, 6) } buffer[1] |= 0x80 // MASK // mask body for (let i = 0; i < bodyLength; ++i) { buffer[offset + i] = frameData[i] ^ maskKey[i & 3] } return buffer } } module.exports = { WebsocketFrameSend } /***/ }), /***/ 9469: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __nccwpck_require__(8522) const { isValidClientWindowBits } = __nccwpck_require__(8625) const { MessageSizeExceededError } = __nccwpck_require__(8707) const tail = Buffer.from([0x00, 0x00, 0xff, 0xff]) const kBuffer = Symbol('kBuffer') const kLength = Symbol('kLength') // Default maximum decompressed message size: 4 MB const kDefaultMaxDecompressedSize = 4 * 1024 * 1024 class PerMessageDeflate { /** @type {import('node:zlib').InflateRaw} */ #inflate #options = {} /** @type {boolean} */ #aborted = false /** @type {Function|null} */ #currentCallback = null /** * @param {Map} extensions */ constructor (extensions) { this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover') this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits') } decompress (chunk, fin, callback) { // An endpoint uses the following algorithm to decompress a message. // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the // payload of the message. // 2. Decompress the resulting data using DEFLATE. if (this.#aborted) { callback(new MessageSizeExceededError()) return } if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) { callback(new Error('Invalid server_max_window_bits')) return } windowBits = Number.parseInt(this.#options.serverMaxWindowBits) } try { this.#inflate = createInflateRaw({ windowBits }) } catch (err) { callback(err) return } this.#inflate[kBuffer] = [] this.#inflate[kLength] = 0 this.#inflate.on('data', (data) => { if (this.#aborted) { return } this.#inflate[kLength] += data.length if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) { this.#aborted = true this.#inflate.removeAllListeners() this.#inflate.destroy() this.#inflate = null if (this.#currentCallback) { const cb = this.#currentCallback this.#currentCallback = null cb(new MessageSizeExceededError()) } return } this.#inflate[kBuffer].push(data) }) this.#inflate.on('error', (err) => { this.#inflate = null callback(err) }) } this.#currentCallback = callback this.#inflate.write(chunk) if (fin) { this.#inflate.write(tail) } this.#inflate.flush(() => { if (this.#aborted || !this.#inflate) { return } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]) this.#inflate[kBuffer].length = 0 this.#inflate[kLength] = 0 this.#currentCallback = null callback(null, full) }) } } module.exports = { PerMessageDeflate } /***/ }), /***/ 1652: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Writable } = __nccwpck_require__(7075) const assert = __nccwpck_require__(4589) const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = __nccwpck_require__(736) const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(1216) const { channels } = __nccwpck_require__(2414) const { isValidStatusCode, isValidOpcode, failWebsocketConnection, websocketMessageReceived, utf8Decode, isControlFrame, isTextBinaryFrame, isContinuationFrame } = __nccwpck_require__(8625) const { WebsocketFrameSend } = __nccwpck_require__(3264) const { closeWebSocketConnection } = __nccwpck_require__(6897) const { PerMessageDeflate } = __nccwpck_require__(9469) // This code was influenced by ws released under the MIT license. // Copyright (c) 2011 Einar Otto Stangvik // Copyright (c) 2013 Arnout Kazemier and contributors // Copyright (c) 2016 Luigi Pinca and contributors class ByteParser extends Writable { #buffers = [] #byteOffset = 0 #loop = false #state = parserStates.INFO #info = {} #fragments = [] /** @type {Map} */ #extensions /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions */ constructor (ws, extensions) { super() this.ws = ws this.#extensions = extensions == null ? new Map() : extensions if (this.#extensions.has('permessage-deflate')) { this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions)) } } /** * @param {Buffer} chunk * @param {() => void} callback */ _write (chunk, _, callback) { this.#buffers.push(chunk) this.#byteOffset += chunk.length this.#loop = true this.run(callback) } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, * or not enough bytes are buffered to parse. */ run (callback) { while (this.#loop) { if (this.#state === parserStates.INFO) { // If there aren't enough bytes to parse the payload length, etc. if (this.#byteOffset < 2) { return callback() } const buffer = this.consume(2) const fin = (buffer[0] & 0x80) !== 0 const opcode = buffer[0] & 0x0F const masked = (buffer[1] & 0x80) === 0x80 const fragmented = !fin && opcode !== opcodes.CONTINUATION const payloadLength = buffer[1] & 0x7F const rsv1 = buffer[0] & 0x40 const rsv2 = buffer[0] & 0x20 const rsv3 = buffer[0] & 0x10 if (!isValidOpcode(opcode)) { failWebsocketConnection(this.ws, 'Invalid opcode received') return callback() } if (masked) { failWebsocketConnection(this.ws, 'Frame cannot be masked') return callback() } // MUST be 0 unless an extension is negotiated that defines meanings // for non-zero values. If a nonzero value is received and none of // the negotiated extensions defines the meaning of such a nonzero // value, the receiving endpoint MUST _Fail the WebSocket // Connection_. // This document allocates the RSV1 bit of the WebSocket header for // PMCEs and calls the bit the "Per-Message Compressed" bit. On a // WebSocket connection where a PMCE is in use, this bit indicates // whether a message is compressed or not. if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) { failWebsocketConnection(this.ws, 'Expected RSV1 to be clear.') return } if (rsv2 !== 0 || rsv3 !== 0) { failWebsocketConnection(this.ws, 'RSV1, RSV2, RSV3 must be clear') return } if (fragmented && !isTextBinaryFrame(opcode)) { // Only text and binary frames can be fragmented failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') return } // If we are already parsing a text/binary frame and do not receive either // a continuation frame or close frame, fail the connection. if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) { failWebsocketConnection(this.ws, 'Expected continuation frame') return } if (this.#info.fragmented && fragmented) { // A fragmented frame can't be fragmented itself failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') return } // "All control frames MUST have a payload length of 125 bytes or less // and MUST NOT be fragmented." if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) { failWebsocketConnection(this.ws, 'Control frame either too large or fragmented') return } if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) { failWebsocketConnection(this.ws, 'Unexpected continuation frame') return } if (payloadLength <= 125) { this.#info.payloadLength = payloadLength this.#state = parserStates.READ_DATA } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16 } else if (payloadLength === 127) { this.#state = parserStates.PAYLOADLENGTH_64 } if (isTextBinaryFrame(opcode)) { this.#info.binaryType = opcode this.#info.compressed = rsv1 !== 0 } this.#info.opcode = opcode this.#info.masked = masked this.#info.fin = fin this.#info.fragmented = fragmented } else if (this.#state === parserStates.PAYLOADLENGTH_16) { if (this.#byteOffset < 2) { return callback() } const buffer = this.consume(2) this.#info.payloadLength = buffer.readUInt16BE(0) this.#state = parserStates.READ_DATA } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback() } const buffer = this.consume(8) const upper = buffer.readUInt32BE(0) const lower = buffer.readUInt32BE(4) // 2^31 is the maximum bytes an arraybuffer can contain // on 32-bit systems. Although, on 64-bit systems, this is // 2^53-1 bytes. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e if (upper !== 0 || lower > 2 ** 31 - 1) { failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') return } this.#info.payloadLength = lower this.#state = parserStates.READ_DATA } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback() } const body = this.consume(this.#info.payloadLength) if (isControlFrame(this.#info.opcode)) { this.#loop = this.parseControlFrame(body) this.#state = parserStates.INFO } else { if (!this.#info.compressed) { this.#fragments.push(body) // If the frame is not fragmented, a message has been received. // If the frame is fragmented, it will terminate with a fin bit set // and an opcode of 0 (continuation), therefore we handle that when // parsing continuation frames, not here. if (!this.#info.fragmented && this.#info.fin) { const fullMessage = Buffer.concat(this.#fragments) websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage) this.#fragments.length = 0 } this.#state = parserStates.INFO } else { this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => { if (error) { failWebsocketConnection(this.ws, error.message) return } this.#fragments.push(data) if (!this.#info.fin) { this.#state = parserStates.INFO this.#loop = true this.run(callback) return } websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments)) this.#loop = true this.#state = parserStates.INFO this.#fragments.length = 0 this.run(callback) }) this.#loop = false break } } } } } /** * Take n bytes from the buffered Buffers * @param {number} n * @returns {Buffer} */ consume (n) { if (n > this.#byteOffset) { throw new Error('Called consume() before buffers satiated.') } else if (n === 0) { return emptyBuffer } if (this.#buffers[0].length === n) { this.#byteOffset -= this.#buffers[0].length return this.#buffers.shift() } const buffer = Buffer.allocUnsafe(n) let offset = 0 while (offset !== n) { const next = this.#buffers[0] const { length } = next if (length + offset === n) { buffer.set(this.#buffers.shift(), offset) break } else if (length + offset > n) { buffer.set(next.subarray(0, n - offset), offset) this.#buffers[0] = next.subarray(n - offset) break } else { buffer.set(this.#buffers.shift(), offset) offset += next.length } } this.#byteOffset -= n return buffer } parseCloseBody (data) { assert(data.length !== 1) // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 /** @type {number|undefined} */ let code if (data.length >= 2) { // _The WebSocket Connection Close Code_ is // defined as the status code (Section 7.4) contained in the first Close // control frame received by the application code = data.readUInt16BE(0) } if (code !== undefined && !isValidStatusCode(code)) { return { code: 1002, reason: 'Invalid status code', error: true } } // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 /** @type {Buffer} */ let reason = data.subarray(2) // Remove BOM if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { reason = reason.subarray(3) } try { reason = utf8Decode(reason) } catch { return { code: 1007, reason: 'Invalid UTF-8', error: true } } return { code, reason, error: false } } /** * Parses control frames. * @param {Buffer} body */ parseControlFrame (body) { const { opcode, payloadLength } = this.#info if (opcode === opcodes.CLOSE) { if (payloadLength === 1) { failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') return false } this.#info.closeInfo = this.parseCloseBody(body) if (this.#info.closeInfo.error) { const { code, reason } = this.#info.closeInfo closeWebSocketConnection(this.ws, code, reason, reason.length) failWebsocketConnection(this.ws, reason) return false } if (this.ws[kSentClose] !== sentCloseFrameState.SENT) { // If an endpoint receives a Close frame and did not previously send a // Close frame, the endpoint MUST send a Close frame in response. (When // sending a Close frame in response, the endpoint typically echos the // status code it received.) let body = emptyBuffer if (this.#info.closeInfo.code) { body = Buffer.allocUnsafe(2) body.writeUInt16BE(this.#info.closeInfo.code, 0) } const closeFrame = new WebsocketFrameSend(body) this.ws[kResponse].socket.write( closeFrame.createFrame(opcodes.CLOSE), (err) => { if (!err) { this.ws[kSentClose] = sentCloseFrameState.SENT } } ) } // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. this.ws[kReadyState] = states.CLOSING this.ws[kReceivedClose] = true return false } else if (opcode === opcodes.PING) { // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in // response, unless it already received a Close frame. // A Pong frame sent in response to a Ping frame must have identical // "Application data" if (!this.ws[kReceivedClose]) { const frame = new WebsocketFrameSend(body) this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) if (channels.ping.hasSubscribers) { channels.ping.publish({ payload: body }) } } } else if (opcode === opcodes.PONG) { // A Pong frame MAY be sent unsolicited. This serves as a // unidirectional heartbeat. A response to an unsolicited Pong frame is // not expected. if (channels.pong.hasSubscribers) { channels.pong.publish({ payload: body }) } } return true } get closingInfo () { return this.#info.closeInfo } } module.exports = { ByteParser } /***/ }), /***/ 3900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { WebsocketFrameSend } = __nccwpck_require__(3264) const { opcodes, sendHints } = __nccwpck_require__(736) const FixedQueue = __nccwpck_require__(4660) /** @type {typeof Uint8Array} */ const FastBuffer = Buffer[Symbol.species] /** * @typedef {object} SendQueueNode * @property {Promise | null} promise * @property {((...args: any[]) => any)} callback * @property {Buffer | null} frame */ class SendQueue { /** * @type {FixedQueue} */ #queue = new FixedQueue() /** * @type {boolean} */ #running = false /** @type {import('node:net').Socket} */ #socket constructor (socket) { this.#socket = socket } add (item, cb, hint) { if (hint !== sendHints.blob) { const frame = createFrame(item, hint) if (!this.#running) { // fast-path this.#socket.write(frame, cb) } else { /** @type {SendQueueNode} */ const node = { promise: null, callback: cb, frame } this.#queue.push(node) } return } /** @type {SendQueueNode} */ const node = { promise: item.arrayBuffer().then((ab) => { node.promise = null node.frame = createFrame(ab, hint) }), callback: cb, frame: null } this.#queue.push(node) if (!this.#running) { this.#run() } } async #run () { this.#running = true const queue = this.#queue while (!queue.isEmpty()) { const node = queue.shift() // wait pending promise if (node.promise !== null) { await node.promise } // write this.#socket.write(node.frame, node.callback) // cleanup node.callback = node.frame = null } this.#running = false } } function createFrame (data, hint) { return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.string ? opcodes.TEXT : opcodes.BINARY) } function toBuffer (data, hint) { switch (hint) { case sendHints.string: return Buffer.from(data) case sendHints.arrayBuffer: case sendHints.blob: return new FastBuffer(data) case sendHints.typedArray: return new FastBuffer(data.buffer, data.byteOffset, data.byteLength) } } module.exports = { SendQueue } /***/ }), /***/ 1216: /***/ ((module) => { "use strict"; module.exports = { kWebSocketURL: Symbol('url'), kReadyState: Symbol('ready state'), kController: Symbol('controller'), kResponse: Symbol('response'), kBinaryType: Symbol('binary type'), kSentClose: Symbol('sent close'), kReceivedClose: Symbol('received close'), kByteParser: Symbol('byte parser') } /***/ }), /***/ 8625: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(1216) const { states, opcodes } = __nccwpck_require__(736) const { ErrorEvent, createFastMessageEvent } = __nccwpck_require__(5188) const { isUtf8 } = __nccwpck_require__(4573) const { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = __nccwpck_require__(1900) /* globals Blob */ /** * @param {import('./websocket').WebSocket} ws * @returns {boolean} */ function isConnecting (ws) { // If the WebSocket connection is not yet established, and the connection // is not yet closed, then the WebSocket connection is in the CONNECTING state. return ws[kReadyState] === states.CONNECTING } /** * @param {import('./websocket').WebSocket} ws * @returns {boolean} */ function isEstablished (ws) { // If the server's response is validated as provided for above, it is // said that _The WebSocket Connection is Established_ and that the // WebSocket Connection is in the OPEN state. return ws[kReadyState] === states.OPEN } /** * @param {import('./websocket').WebSocket} ws * @returns {boolean} */ function isClosing (ws) { // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. return ws[kReadyState] === states.CLOSING } /** * @param {import('./websocket').WebSocket} ws * @returns {boolean} */ function isClosed (ws) { return ws[kReadyState] === states.CLOSED } /** * @see https://dom.spec.whatwg.org/#concept-event-fire * @param {string} e * @param {EventTarget} target * @param {(...args: ConstructorParameters) => Event} eventFactory * @param {EventInit | undefined} eventInitDict */ function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) { // 1. If eventConstructor is not given, then let eventConstructor be Event. // 2. Let event be the result of creating an event given eventConstructor, // in the relevant realm of target. // 3. Initialize event’s type attribute to e. const event = eventFactory(e, eventInitDict) // 4. Initialize any other IDL attributes of event as described in the // invocation of this algorithm. // 5. Return the result of dispatching event at target, with legacy target // override flag set if set. target.dispatchEvent(event) } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol * @param {import('./websocket').WebSocket} ws * @param {number} type Opcode * @param {Buffer} data application data */ function websocketMessageReceived (ws, type, data) { // 1. If ready state is not OPEN (1), then return. if (ws[kReadyState] !== states.OPEN) { return } // 2. Let dataForEvent be determined by switching on type and binary type: let dataForEvent if (type === opcodes.TEXT) { // -> type indicates that the data is Text // a new DOMString containing data try { dataForEvent = utf8Decode(data) } catch { failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') return } } else if (type === opcodes.BINARY) { if (ws[kBinaryType] === 'blob') { // -> type indicates that the data is Binary and binary type is "blob" // a new Blob object, created in the relevant Realm of the WebSocket // object, that represents data as its raw data dataForEvent = new Blob([data]) } else { // -> type indicates that the data is Binary and binary type is "arraybuffer" // a new ArrayBuffer object, created in the relevant Realm of the // WebSocket object, whose contents are data dataForEvent = toArrayBuffer(data) } } // 3. Fire an event named message at the WebSocket object, using MessageEvent, // with the origin attribute initialized to the serialization of the WebSocket // object’s url's origin, and the data attribute initialized to dataForEvent. fireEvent('message', ws, createFastMessageEvent, { origin: ws[kWebSocketURL].origin, data: dataForEvent }) } function toArrayBuffer (buffer) { if (buffer.byteLength === buffer.buffer.byteLength) { return buffer.buffer } return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) } /** * @see https://datatracker.ietf.org/doc/html/rfc6455 * @see https://datatracker.ietf.org/doc/html/rfc2616 * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 * @param {string} protocol */ function isValidSubprotocol (protocol) { // If present, this value indicates one // or more comma-separated subprotocol the client wishes to speak, // ordered by preference. The elements that comprise this value // MUST be non-empty strings with characters in the range U+0021 to // U+007E not including separator characters as defined in // [RFC2616] and MUST all be unique strings. if (protocol.length === 0) { return false } for (let i = 0; i < protocol.length; ++i) { const code = protocol.charCodeAt(i) if ( code < 0x21 || // CTL, contains SP (0x20) and HT (0x09) code > 0x7E || code === 0x22 || // " code === 0x28 || // ( code === 0x29 || // ) code === 0x2C || // , code === 0x2F || // / code === 0x3A || // : code === 0x3B || // ; code === 0x3C || // < code === 0x3D || // = code === 0x3E || // > code === 0x3F || // ? code === 0x40 || // @ code === 0x5B || // [ code === 0x5C || // \ code === 0x5D || // ] code === 0x7B || // { code === 0x7D // } ) { return false } } return true } /** * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 * @param {number} code */ function isValidStatusCode (code) { if (code >= 1000 && code < 1015) { return ( code !== 1004 && // reserved code !== 1005 && // "MUST NOT be set as a status code" code !== 1006 // "MUST NOT be set as a status code" ) } return code >= 3000 && code <= 4999 } /** * @param {import('./websocket').WebSocket} ws * @param {string|undefined} reason */ function failWebsocketConnection (ws, reason) { const { [kController]: controller, [kResponse]: response } = ws controller.abort() if (response?.socket && !response.socket.destroyed) { response.socket.destroy() } if (reason) { // TODO: process.nextTick fireEvent('error', ws, (type, init) => new ErrorEvent(type, init), { error: new Error(reason), message: reason }) } } /** * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5 * @param {number} opcode */ function isControlFrame (opcode) { return ( opcode === opcodes.CLOSE || opcode === opcodes.PING || opcode === opcodes.PONG ) } function isContinuationFrame (opcode) { return opcode === opcodes.CONTINUATION } function isTextBinaryFrame (opcode) { return opcode === opcodes.TEXT || opcode === opcodes.BINARY } function isValidOpcode (opcode) { return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode) } /** * Parses a Sec-WebSocket-Extensions header value. * @param {string} extensions * @returns {Map} */ // TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 function parseExtensions (extensions) { const position = { position: 0 } const extensionList = new Map() while (position.position < extensions.length) { const pair = collectASequenceOfCodePointsFast(';', extensions, position) const [name, value = ''] = pair.split('=') extensionList.set( removeHTTPWhitespace(name, true, false), removeHTTPWhitespace(value, false, true) ) position.position++ } return extensionList } /** * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2 * @description "client-max-window-bits = 1*DIGIT" * @param {string} value */ function isValidClientWindowBits (value) { // Must have at least one character if (value.length === 0) { return false } // Check all characters are ASCII digits for (let i = 0; i < value.length; i++) { const byte = value.charCodeAt(i) if (byte < 0x30 || byte > 0x39) { return false } } // Check numeric range: zlib requires windowBits in range 8-15 const num = Number.parseInt(value, 10) return num >= 8 && num <= 15 } // https://nodejs.org/api/intl.html#detecting-internationalization-support const hasIntl = typeof process.versions.icu === 'string' const fatalDecoder = hasIntl ? new TextDecoder('utf-8', { fatal: true }) : undefined /** * Converts a Buffer to utf-8, even on platforms without icu. * @param {Buffer} buffer */ const utf8Decode = hasIntl ? fatalDecoder.decode.bind(fatalDecoder) : function (buffer) { if (isUtf8(buffer)) { return buffer.toString('utf-8') } throw new TypeError('Invalid utf-8 received.') } module.exports = { isConnecting, isEstablished, isClosing, isClosed, fireEvent, isValidSubprotocol, isValidStatusCode, failWebsocketConnection, websocketMessageReceived, utf8Decode, isControlFrame, isContinuationFrame, isTextBinaryFrame, isValidOpcode, parseExtensions, isValidClientWindowBits } /***/ }), /***/ 3726: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { webidl } = __nccwpck_require__(5893) const { URLSerializer } = __nccwpck_require__(1900) const { environmentSettingsObject } = __nccwpck_require__(3168) const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = __nccwpck_require__(736) const { kWebSocketURL, kReadyState, kController, kBinaryType, kResponse, kSentClose, kByteParser } = __nccwpck_require__(1216) const { isConnecting, isEstablished, isClosing, isValidSubprotocol, fireEvent } = __nccwpck_require__(8625) const { establishWebSocketConnection, closeWebSocketConnection } = __nccwpck_require__(6897) const { ByteParser } = __nccwpck_require__(1652) const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3440) const { getGlobalDispatcher } = __nccwpck_require__(2581) const { types } = __nccwpck_require__(7975) const { ErrorEvent, CloseEvent } = __nccwpck_require__(5188) const { SendQueue } = __nccwpck_require__(3900) // https://websockets.spec.whatwg.org/#interface-definition class WebSocket extends EventTarget { #events = { open: null, error: null, close: null, message: null } #bufferedAmount = 0 #protocol = '' #extensions = '' /** @type {SendQueue} */ #sendQueue /** * @param {string} url * @param {string|string[]} protocols */ constructor (url, protocols = []) { super() webidl.util.markAsUncloneable(this) const prefix = 'WebSocket constructor' webidl.argumentLengthCheck(arguments, 1, prefix) const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options') url = webidl.converters.USVString(url, prefix, 'url') protocols = options.protocols // 1. Let baseURL be this's relevant settings object's API base URL. const baseURL = environmentSettingsObject.settingsObject.baseUrl // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. let urlRecord try { urlRecord = new URL(url, baseURL) } catch (e) { // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. throw new DOMException(e, 'SyntaxError') } // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". if (urlRecord.protocol === 'http:') { urlRecord.protocol = 'ws:' } else if (urlRecord.protocol === 'https:') { // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". urlRecord.protocol = 'wss:' } // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { throw new DOMException( `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, 'SyntaxError' ) } // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" // DOMException. if (urlRecord.hash || urlRecord.href.endsWith('#')) { throw new DOMException('Got fragment', 'SyntaxError') } // 8. If protocols is a string, set protocols to a sequence consisting // of just that string. if (typeof protocols === 'string') { protocols = [protocols] } // 9. If any of the values in protocols occur more than once or otherwise // fail to match the requirements for elements that comprise the value // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket // protocol, then throw a "SyntaxError" DOMException. if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } // 10. Set this's url to urlRecord. this[kWebSocketURL] = new URL(urlRecord.href) // 11. Let client be this's relevant settings object. const client = environmentSettingsObject.settingsObject // 12. Run this step in parallel: // 1. Establish a WebSocket connection given urlRecord, protocols, // and client. this[kController] = establishWebSocketConnection( urlRecord, protocols, client, this, (response, extensions) => this.#onConnectionEstablished(response, extensions), options ) // Each WebSocket object has an associated ready state, which is a // number representing the state of the connection. Initially it must // be CONNECTING (0). this[kReadyState] = WebSocket.CONNECTING this[kSentClose] = sentCloseFrameState.NOT_SENT // The extensions attribute must initially return the empty string. // The protocol attribute must initially return the empty string. // Each WebSocket object has an associated binary type, which is a // BinaryType. Initially it must be "blob". this[kBinaryType] = 'blob' } /** * @see https://websockets.spec.whatwg.org/#dom-websocket-close * @param {number|undefined} code * @param {string|undefined} reason */ close (code = undefined, reason = undefined) { webidl.brandCheck(this, WebSocket) const prefix = 'WebSocket.close' if (code !== undefined) { code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true }) } if (reason !== undefined) { reason = webidl.converters.USVString(reason, prefix, 'reason') } // 1. If code is present, but is neither an integer equal to 1000 nor an // integer in the range 3000 to 4999, inclusive, throw an // "InvalidAccessError" DOMException. if (code !== undefined) { if (code !== 1000 && (code < 3000 || code > 4999)) { throw new DOMException('invalid code', 'InvalidAccessError') } } let reasonByteLength = 0 // 2. If reason is present, then run these substeps: if (reason !== undefined) { // 1. Let reasonBytes be the result of encoding reason. // 2. If reasonBytes is longer than 123 bytes, then throw a // "SyntaxError" DOMException. reasonByteLength = Buffer.byteLength(reason) if (reasonByteLength > 123) { throw new DOMException( `Reason must be less than 123 bytes; received ${reasonByteLength}`, 'SyntaxError' ) } } // 3. Run the first matching steps from the following list: closeWebSocketConnection(this, code, reason, reasonByteLength) } /** * @see https://websockets.spec.whatwg.org/#dom-websocket-send * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data */ send (data) { webidl.brandCheck(this, WebSocket) const prefix = 'WebSocket.send' webidl.argumentLengthCheck(arguments, 1, prefix) data = webidl.converters.WebSocketSendData(data, prefix, 'data') // 1. If this's ready state is CONNECTING, then throw an // "InvalidStateError" DOMException. if (isConnecting(this)) { throw new DOMException('Sent before connected.', 'InvalidStateError') } // 2. Run the appropriate set of steps from the following list: // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 if (!isEstablished(this) || isClosing(this)) { return } // If data is a string if (typeof data === 'string') { // If the WebSocket connection is established and the WebSocket // closing handshake has not yet started, then the user agent // must send a WebSocket Message comprised of the data argument // using a text frame opcode; if the data cannot be sent, e.g. // because it would need to be buffered but the buffer is full, // the user agent must flag the WebSocket as full and then close // the WebSocket connection. Any invocation of this method with a // string argument that does not throw an exception must increase // the bufferedAmount attribute by the number of bytes needed to // express the argument as UTF-8. const length = Buffer.byteLength(data) this.#bufferedAmount += length this.#sendQueue.add(data, () => { this.#bufferedAmount -= length }, sendHints.string) } else if (types.isArrayBuffer(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need // to be buffered but the buffer is full, the user agent must flag // the WebSocket as full and then close the WebSocket connection. // The data to be sent is the data stored in the buffer described // by the ArrayBuffer object. Any invocation of this method with an // ArrayBuffer argument that does not throw an exception must // increase the bufferedAmount attribute by the length of the // ArrayBuffer in bytes. this.#bufferedAmount += data.byteLength this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.byteLength }, sendHints.arrayBuffer) } else if (ArrayBuffer.isView(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need to // be buffered but the buffer is full, the user agent must flag the // WebSocket as full and then close the WebSocket connection. The // data to be sent is the data stored in the section of the buffer // described by the ArrayBuffer object that data references. Any // invocation of this method with this kind of argument that does // not throw an exception must increase the bufferedAmount attribute // by the length of data’s buffer in bytes. this.#bufferedAmount += data.byteLength this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.byteLength }, sendHints.typedArray) } else if (isBlobLike(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need to // be buffered but the buffer is full, the user agent must flag the // WebSocket as full and then close the WebSocket connection. The data // to be sent is the raw data represented by the Blob object. Any // invocation of this method with a Blob argument that does not throw // an exception must increase the bufferedAmount attribute by the size // of the Blob object’s raw data, in bytes. this.#bufferedAmount += data.size this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.size }, sendHints.blob) } } get readyState () { webidl.brandCheck(this, WebSocket) // The readyState getter steps are to return this's ready state. return this[kReadyState] } get bufferedAmount () { webidl.brandCheck(this, WebSocket) return this.#bufferedAmount } get url () { webidl.brandCheck(this, WebSocket) // The url getter steps are to return this's url, serialized. return URLSerializer(this[kWebSocketURL]) } get extensions () { webidl.brandCheck(this, WebSocket) return this.#extensions } get protocol () { webidl.brandCheck(this, WebSocket) return this.#protocol } get onopen () { webidl.brandCheck(this, WebSocket) return this.#events.open } set onopen (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.open) { this.removeEventListener('open', this.#events.open) } if (typeof fn === 'function') { this.#events.open = fn this.addEventListener('open', fn) } else { this.#events.open = null } } get onerror () { webidl.brandCheck(this, WebSocket) return this.#events.error } set onerror (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.error) { this.removeEventListener('error', this.#events.error) } if (typeof fn === 'function') { this.#events.error = fn this.addEventListener('error', fn) } else { this.#events.error = null } } get onclose () { webidl.brandCheck(this, WebSocket) return this.#events.close } set onclose (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.close) { this.removeEventListener('close', this.#events.close) } if (typeof fn === 'function') { this.#events.close = fn this.addEventListener('close', fn) } else { this.#events.close = null } } get onmessage () { webidl.brandCheck(this, WebSocket) return this.#events.message } set onmessage (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.message) { this.removeEventListener('message', this.#events.message) } if (typeof fn === 'function') { this.#events.message = fn this.addEventListener('message', fn) } else { this.#events.message = null } } get binaryType () { webidl.brandCheck(this, WebSocket) return this[kBinaryType] } set binaryType (type) { webidl.brandCheck(this, WebSocket) if (type !== 'blob' && type !== 'arraybuffer') { this[kBinaryType] = 'blob' } else { this[kBinaryType] = type } } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol */ #onConnectionEstablished (response, parsedExtensions) { // processResponse is called when the "response's header list has been received and initialized." // once this happens, the connection is open this[kResponse] = response const parser = new ByteParser(this, parsedExtensions) parser.on('drain', onParserDrain) parser.on('error', onParserError.bind(this)) response.socket.ws = this this[kByteParser] = parser this.#sendQueue = new SendQueue(response.socket) // 1. Change the ready state to OPEN (1). this[kReadyState] = states.OPEN // 2. Change the extensions attribute’s value to the extensions in use, if // it is not the null value. // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 const extensions = response.headersList.get('sec-websocket-extensions') if (extensions !== null) { this.#extensions = extensions } // 3. Change the protocol attribute’s value to the subprotocol in use, if // it is not the null value. // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 const protocol = response.headersList.get('sec-websocket-protocol') if (protocol !== null) { this.#protocol = protocol } // 4. Fire an event named open at the WebSocket object. fireEvent('open', this) } } // https://websockets.spec.whatwg.org/#dom-websocket-connecting WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING // https://websockets.spec.whatwg.org/#dom-websocket-open WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN // https://websockets.spec.whatwg.org/#dom-websocket-closing WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING // https://websockets.spec.whatwg.org/#dom-websocket-closed WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED Object.defineProperties(WebSocket.prototype, { CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, CLOSED: staticPropertyDescriptors, url: kEnumerableProperty, readyState: kEnumerableProperty, bufferedAmount: kEnumerableProperty, onopen: kEnumerableProperty, onerror: kEnumerableProperty, onclose: kEnumerableProperty, close: kEnumerableProperty, onmessage: kEnumerableProperty, binaryType: kEnumerableProperty, send: kEnumerableProperty, extensions: kEnumerableProperty, protocol: kEnumerableProperty, [Symbol.toStringTag]: { value: 'WebSocket', writable: false, enumerable: false, configurable: true } }) Object.defineProperties(WebSocket, { CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, CLOSED: staticPropertyDescriptors }) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.DOMString ) webidl.converters['DOMString or sequence'] = function (V, prefix, argument) { if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { return webidl.converters['sequence'](V) } return webidl.converters.DOMString(V, prefix, argument) } // This implements the proposal made in https://github.com/whatwg/websockets/issues/42 webidl.converters.WebSocketInit = webidl.dictionaryConverter([ { key: 'protocols', converter: webidl.converters['DOMString or sequence'], defaultValue: () => new Array(0) }, { key: 'dispatcher', converter: webidl.converters.any, defaultValue: () => getGlobalDispatcher() }, { key: 'headers', converter: webidl.nullableConverter(webidl.converters.HeadersInit) } ]) webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { return webidl.converters.WebSocketInit(V) } return { protocols: webidl.converters['DOMString or sequence'](V) } } webidl.converters.WebSocketSendData = function (V) { if (webidl.util.Type(V) === 'Object') { if (isBlobLike(V)) { return webidl.converters.Blob(V, { strict: false }) } if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { return webidl.converters.BufferSource(V) } } return webidl.converters.USVString(V) } function onParserDrain () { this.ws[kResponse].socket.resume() } function onParserError (err) { let message let code if (err instanceof CloseEvent) { message = err.reason code = err.code } else { message = err.message } fireEvent('error', this, () => new ErrorEvent('error', { error: err, message })) closeWebSocketConnection(this, code) } module.exports = { WebSocket } /***/ }), /***/ 5243: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = require(__nccwpck_require__.ab + "build/Release/cpufeatures.node") /***/ }), /***/ 8440: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = require(__nccwpck_require__.ab + "lib/protocol/crypto/build/Release/sshcrypto.node") /***/ }), /***/ 2613: /***/ ((module) => { "use strict"; module.exports = require("assert"); /***/ }), /***/ 181: /***/ ((module) => { "use strict"; module.exports = require("buffer"); /***/ }), /***/ 5317: /***/ ((module) => { "use strict"; module.exports = require("child_process"); /***/ }), /***/ 6982: /***/ ((module) => { "use strict"; module.exports = require("crypto"); /***/ }), /***/ 2250: /***/ ((module) => { "use strict"; module.exports = require("dns"); /***/ }), /***/ 4434: /***/ ((module) => { "use strict"; module.exports = require("events"); /***/ }), /***/ 9896: /***/ ((module) => { "use strict"; module.exports = require("fs"); /***/ }), /***/ 8611: /***/ ((module) => { "use strict"; module.exports = require("http"); /***/ }), /***/ 5692: /***/ ((module) => { "use strict"; module.exports = require("https"); /***/ }), /***/ 9278: /***/ ((module) => { "use strict"; module.exports = require("net"); /***/ }), /***/ 4589: /***/ ((module) => { "use strict"; module.exports = require("node:assert"); /***/ }), /***/ 6698: /***/ ((module) => { "use strict"; module.exports = require("node:async_hooks"); /***/ }), /***/ 4573: /***/ ((module) => { "use strict"; module.exports = require("node:buffer"); /***/ }), /***/ 7540: /***/ ((module) => { "use strict"; module.exports = require("node:console"); /***/ }), /***/ 7598: /***/ ((module) => { "use strict"; module.exports = require("node:crypto"); /***/ }), /***/ 3053: /***/ ((module) => { "use strict"; module.exports = require("node:diagnostics_channel"); /***/ }), /***/ 610: /***/ ((module) => { "use strict"; module.exports = require("node:dns"); /***/ }), /***/ 8474: /***/ ((module) => { "use strict"; module.exports = require("node:events"); /***/ }), /***/ 7067: /***/ ((module) => { "use strict"; module.exports = require("node:http"); /***/ }), /***/ 2467: /***/ ((module) => { "use strict"; module.exports = require("node:http2"); /***/ }), /***/ 7030: /***/ ((module) => { "use strict"; module.exports = require("node:net"); /***/ }), /***/ 643: /***/ ((module) => { "use strict"; module.exports = require("node:perf_hooks"); /***/ }), /***/ 1792: /***/ ((module) => { "use strict"; module.exports = require("node:querystring"); /***/ }), /***/ 7075: /***/ ((module) => { "use strict"; module.exports = require("node:stream"); /***/ }), /***/ 1692: /***/ ((module) => { "use strict"; module.exports = require("node:tls"); /***/ }), /***/ 3136: /***/ ((module) => { "use strict"; module.exports = require("node:url"); /***/ }), /***/ 7975: /***/ ((module) => { "use strict"; module.exports = require("node:util"); /***/ }), /***/ 3429: /***/ ((module) => { "use strict"; module.exports = require("node:util/types"); /***/ }), /***/ 5919: /***/ ((module) => { "use strict"; module.exports = require("node:worker_threads"); /***/ }), /***/ 8522: /***/ ((module) => { "use strict"; module.exports = require("node:zlib"); /***/ }), /***/ 857: /***/ ((module) => { "use strict"; module.exports = require("os"); /***/ }), /***/ 6928: /***/ ((module) => { "use strict"; module.exports = require("path"); /***/ }), /***/ 2203: /***/ ((module) => { "use strict"; module.exports = require("stream"); /***/ }), /***/ 3193: /***/ ((module) => { "use strict"; module.exports = require("string_decoder"); /***/ }), /***/ 3557: /***/ ((module) => { "use strict"; module.exports = require("timers"); /***/ }), /***/ 4756: /***/ ((module) => { "use strict"; module.exports = require("tls"); /***/ }), /***/ 9023: /***/ ((module) => { "use strict"; module.exports = require("util"); /***/ }), /***/ 3106: /***/ ((module) => { "use strict"; module.exports = require("zlib"); /***/ }), /***/ 1227: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeSSH = exports.SSHError = void 0; const assert_1 = __importStar(__nccwpck_require__(2613)); const fs_1 = __importDefault(__nccwpck_require__(9896)); const is_stream_1 = __importDefault(__nccwpck_require__(6543)); const make_dir_1 = __importDefault(__nccwpck_require__(6512)); const path_1 = __importDefault(__nccwpck_require__(6928)); const sb_promise_queue_1 = __nccwpck_require__(6339); const sb_scandir_1 = __importDefault(__nccwpck_require__(9700)); const shell_escape_1 = __importDefault(__nccwpck_require__(4646)); const ssh2_1 = __importDefault(__nccwpck_require__(5472)); const DEFAULT_CONCURRENCY = 1; const DEFAULT_VALIDATE = (path) => !path_1.default.basename(path).startsWith('.'); const DEFAULT_TICK = () => { /* No Op */ }; class SSHError extends Error { constructor(message, code = null) { super(message); this.code = code; } } exports.SSHError = SSHError; function unixifyPath(path) { if (path.includes('\\')) { return path.split('\\').join('/'); } return path; } async function readFile(filePath) { return new Promise((resolve, reject) => { fs_1.default.readFile(filePath, 'utf8', (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } const SFTP_MKDIR_ERR_CODE_REGEXP = /Error: (E[\S]+): /; async function makeDirectoryWithSftp(path, sftp) { let stats = null; try { stats = await new Promise((resolve, reject) => { sftp.stat(path, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } catch (_) { /* No Op */ } if (stats) { if (stats.isDirectory()) { // Already exists, nothing to worry about return; } throw new Error('mkdir() failed, target already exists and is not a directory'); } try { await new Promise((resolve, reject) => { sftp.mkdir(path, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } catch (err) { if (err != null && typeof err.stack === 'string') { const matches = SFTP_MKDIR_ERR_CODE_REGEXP.exec(err.stack); if (matches != null) { throw new SSHError(err.message, matches[1]); } throw err; } } } class NodeSSH { constructor() { this.connection = null; } getConnection() { const { connection } = this; if (connection == null) { throw new Error('Not connected to server'); } return connection; } async connect(givenConfig) { (0, assert_1.default)(givenConfig != null && typeof givenConfig === 'object', 'config must be a valid object'); const config = { ...givenConfig }; (0, assert_1.default)(config.username != null && typeof config.username === 'string', 'config.username must be a valid string'); if (config.host != null) { (0, assert_1.default)(typeof config.host === 'string', 'config.host must be a valid string'); } else if (config.sock != null) { (0, assert_1.default)(typeof config.sock === 'object', 'config.sock must be a valid object'); } else { throw new assert_1.AssertionError({ message: 'Either config.host or config.sock must be provided' }); } if (config.privateKey != null || config.privateKeyPath != null) { if (config.privateKey != null) { (0, assert_1.default)(typeof config.privateKey === 'string', 'config.privateKey must be a valid string'); (0, assert_1.default)(config.privateKeyPath == null, 'config.privateKeyPath must not be specified when config.privateKey is specified'); } else if (config.privateKeyPath != null) { (0, assert_1.default)(typeof config.privateKeyPath === 'string', 'config.privateKeyPath must be a valid string'); (0, assert_1.default)(config.privateKey == null, 'config.privateKey must not be specified when config.privateKeyPath is specified'); } (0, assert_1.default)(config.passphrase == null || typeof config.passphrase === 'string', 'config.passphrase must be null or a valid string'); if (config.privateKeyPath != null) { // Must be an fs path try { config.privateKey = await readFile(config.privateKeyPath); } catch (err) { if (err != null && err.code === 'ENOENT') { throw new assert_1.AssertionError({ message: 'config.privateKeyPath does not exist at given fs path' }); } throw err; } } } else if (config.password != null) { (0, assert_1.default)(typeof config.password === 'string', 'config.password must be a valid string'); } if (config.tryKeyboard != null) { (0, assert_1.default)(typeof config.tryKeyboard === 'boolean', 'config.tryKeyboard must be a valid boolean'); } if (config.tryKeyboard) { const { password } = config; if (config.onKeyboardInteractive != null) { (0, assert_1.default)(typeof config.onKeyboardInteractive === 'function', 'config.onKeyboardInteractive must be a valid function'); } else if (password != null) { config.onKeyboardInteractive = (name, instructions, instructionsLang, prompts, finish) => { if (prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password')) { finish([password]); } }; } } const connection = new ssh2_1.default.Client(); this.connection = connection; await new Promise((resolve, reject) => { connection.on('error', reject); if (config.onKeyboardInteractive) { connection.on('keyboard-interactive', config.onKeyboardInteractive); } connection.on('ready', () => { connection.removeListener('error', reject); resolve(); }); connection.on('end', () => { if (this.connection === connection) { this.connection = null; } }); connection.on('close', () => { if (this.connection === connection) { this.connection = null; } reject(new SSHError('No response from server', 'ETIMEDOUT')); }); connection.connect(config); }); return this; } isConnected() { return this.connection != null; } async requestShell(options) { const connection = this.getConnection(); return new Promise((resolve, reject) => { connection.on('error', reject); const callback = (err, res) => { connection.removeListener('error', reject); if (err) { reject(err); } else { resolve(res); } }; if (options == null) { connection.shell(callback); } else { connection.shell(options, callback); } }); } async withShell(callback, options) { (0, assert_1.default)(typeof callback === 'function', 'callback must be a valid function'); const shell = await this.requestShell(options); try { await callback(shell); } finally { shell.destroy(); } } async requestSFTP() { const connection = this.getConnection(); return new Promise((resolve, reject) => { connection.on('error', reject); connection.sftp((err, res) => { connection.removeListener('error', reject); if (err) { reject(err); } else { resolve(res); } }); }); } async withSFTP(callback) { (0, assert_1.default)(typeof callback === 'function', 'callback must be a valid function'); const sftp = await this.requestSFTP(); try { await callback(sftp); } finally { sftp.end(); } } async execCommand(givenCommand, options = {}) { (0, assert_1.default)(typeof givenCommand === 'string', 'command must be a valid string'); (0, assert_1.default)(options != null && typeof options === 'object', 'options must be a valid object'); (0, assert_1.default)(options.cwd == null || typeof options.cwd === 'string', 'options.cwd must be a valid string'); (0, assert_1.default)(options.stdin == null || typeof options.stdin === 'string' || is_stream_1.default.readable(options.stdin), 'options.stdin must be a valid string or readable stream'); (0, assert_1.default)(options.execOptions == null || typeof options.execOptions === 'object', 'options.execOptions must be a valid object'); (0, assert_1.default)(options.encoding == null || typeof options.encoding === 'string', 'options.encoding must be a valid string'); (0, assert_1.default)(options.onChannel == null || typeof options.onChannel === 'function', 'options.onChannel must be a valid function'); (0, assert_1.default)(options.onStdout == null || typeof options.onStdout === 'function', 'options.onStdout must be a valid function'); (0, assert_1.default)(options.onStderr == null || typeof options.onStderr === 'function', 'options.onStderr must be a valid function'); (0, assert_1.default)(options.noTrim == null || typeof options.noTrim === 'boolean', 'options.noTrim must be a boolean'); let command = givenCommand; if (options.cwd) { command = `cd ${(0, shell_escape_1.default)([options.cwd])} ; ${command}`; } const connection = this.getConnection(); const output = { stdout: [], stderr: [] }; return new Promise((resolve, reject) => { connection.on('error', reject); connection.exec(command, options.execOptions != null ? options.execOptions : {}, (err, channel) => { connection.removeListener('error', reject); if (err) { reject(err); return; } if (options.onChannel) { options.onChannel(channel); } channel.on('data', (chunk) => { if (options.onStdout) options.onStdout(chunk); output.stdout.push(chunk.toString(options.encoding)); }); channel.stderr.on('data', (chunk) => { if (options.onStderr) options.onStderr(chunk); output.stderr.push(chunk.toString(options.encoding)); }); if (options.stdin != null) { if (is_stream_1.default.readable(options.stdin)) { options.stdin.pipe(channel, { end: true, }); } else { channel.write(options.stdin); channel.end(); } } else { channel.end(); } let code = null; let signal = null; channel.on('exit', (code_, signal_) => { code = code_ !== null && code_ !== void 0 ? code_ : null; signal = signal_ !== null && signal_ !== void 0 ? signal_ : null; }); channel.on('close', () => { let stdout = output.stdout.join(''); let stderr = output.stderr.join(''); if (options.noTrim !== true) { stdout = stdout.trim(); stderr = stderr.trim(); } resolve({ code: code != null ? code : null, signal: signal != null ? signal : null, stdout, stderr, }); }); }); }); } async exec(command, parameters, options = {}) { (0, assert_1.default)(typeof command === 'string', 'command must be a valid string'); (0, assert_1.default)(Array.isArray(parameters), 'parameters must be a valid array'); (0, assert_1.default)(options != null && typeof options === 'object', 'options must be a valid object'); (0, assert_1.default)(options.stream == null || ['both', 'stdout', 'stderr'].includes(options.stream), 'options.stream must be one of both, stdout, stderr'); for (let i = 0, { length } = parameters; i < length; i += 1) { (0, assert_1.default)(typeof parameters[i] === 'string', `parameters[${i}] must be a valid string`); } const completeCommand = `${command}${parameters.length > 0 ? ` ${(0, shell_escape_1.default)(parameters)}` : ''}`; const response = await this.execCommand(completeCommand, options); if (options.stream == null || options.stream === 'stdout') { if (response.stderr) { throw new Error(response.stderr); } return response.stdout; } if (options.stream === 'stderr') { return response.stderr; } return response; } async mkdir(path, method = 'sftp', givenSftp = null) { (0, assert_1.default)(typeof path === 'string', 'path must be a valid string'); (0, assert_1.default)(typeof method === 'string' && (method === 'sftp' || method === 'exec'), 'method must be either sftp or exec'); (0, assert_1.default)(givenSftp == null || typeof givenSftp === 'object', 'sftp must be a valid object'); if (method === 'exec') { await this.exec('mkdir', ['-p', unixifyPath(path)]); return; } const sftp = givenSftp || (await this.requestSFTP()); const makeSftpDirectory = async (retry) => makeDirectoryWithSftp(unixifyPath(path), sftp).catch(async (error) => { if (!retry || error == null || (error.message !== 'No such file' && error.code !== 'ENOENT')) { throw error; } await this.mkdir(path_1.default.dirname(path), 'sftp', sftp); await makeSftpDirectory(false); }); try { await makeSftpDirectory(true); } finally { if (!givenSftp) { sftp.end(); } } } async getFile(localFile, remoteFile, givenSftp = null, transferOptions = null) { (0, assert_1.default)(typeof localFile === 'string', 'localFile must be a valid string'); (0, assert_1.default)(typeof remoteFile === 'string', 'remoteFile must be a valid string'); (0, assert_1.default)(givenSftp == null || typeof givenSftp === 'object', 'sftp must be a valid object'); (0, assert_1.default)(transferOptions == null || typeof transferOptions === 'object', 'transferOptions must be a valid object'); const sftp = givenSftp || (await this.requestSFTP()); try { await new Promise((resolve, reject) => { sftp.fastGet(unixifyPath(remoteFile), localFile, transferOptions || {}, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } finally { if (!givenSftp) { sftp.end(); } } } async putFile(localFile, remoteFile, givenSftp = null, transferOptions = null) { (0, assert_1.default)(typeof localFile === 'string', 'localFile must be a valid string'); (0, assert_1.default)(typeof remoteFile === 'string', 'remoteFile must be a valid string'); (0, assert_1.default)(givenSftp == null || typeof givenSftp === 'object', 'sftp must be a valid object'); (0, assert_1.default)(transferOptions == null || typeof transferOptions === 'object', 'transferOptions must be a valid object'); (0, assert_1.default)(await new Promise((resolve) => { fs_1.default.access(localFile, fs_1.default.constants.R_OK, (err) => { resolve(err === null); }); }), `localFile does not exist at ${localFile}`); const sftp = givenSftp || (await this.requestSFTP()); const putFile = (retry) => { return new Promise((resolve, reject) => { sftp.fastPut(localFile, unixifyPath(remoteFile), transferOptions || {}, (err) => { if (err == null) { resolve(); return; } if (err.message === 'No such file' && retry) { resolve(this.mkdir(path_1.default.dirname(remoteFile), 'sftp', sftp).then(() => putFile(false))); } else { reject(err); } }); }); }; try { await putFile(true); } finally { if (!givenSftp) { sftp.end(); } } } async putFiles(files, { concurrency = DEFAULT_CONCURRENCY, sftp: givenSftp = null, transferOptions = {} } = {}) { (0, assert_1.default)(Array.isArray(files), 'files must be an array'); for (let i = 0, { length } = files; i < length; i += 1) { const file = files[i]; (0, assert_1.default)(file, 'files items must be valid objects'); (0, assert_1.default)(file.local && typeof file.local === 'string', `files[${i}].local must be a string`); (0, assert_1.default)(file.remote && typeof file.remote === 'string', `files[${i}].remote must be a string`); } const transferred = []; const sftp = givenSftp || (await this.requestSFTP()); const queue = new sb_promise_queue_1.PromiseQueue({ concurrency }); try { await new Promise((resolve, reject) => { files.forEach((file) => { queue .add(async () => { await this.putFile(file.local, file.remote, sftp, transferOptions); transferred.push(file); }) .catch(reject); }); queue.waitTillIdle().then(resolve); }); } catch (error) { if (error != null) { error.transferred = transferred; } throw error; } finally { if (!givenSftp) { sftp.end(); } } } async putDirectory(localDirectory, remoteDirectory, { concurrency = DEFAULT_CONCURRENCY, sftp: givenSftp = null, transferOptions = {}, recursive = true, tick = DEFAULT_TICK, validate = DEFAULT_VALIDATE, } = {}) { (0, assert_1.default)(typeof localDirectory === 'string' && localDirectory, 'localDirectory must be a string'); (0, assert_1.default)(typeof remoteDirectory === 'string' && remoteDirectory, 'remoteDirectory must be a string'); const localDirectoryStat = await new Promise((resolve) => { fs_1.default.stat(localDirectory, (err, stat) => { resolve(stat || null); }); }); (0, assert_1.default)(localDirectoryStat != null, `localDirectory does not exist at ${localDirectory}`); (0, assert_1.default)(localDirectoryStat.isDirectory(), `localDirectory is not a directory at ${localDirectory}`); const sftp = givenSftp || (await this.requestSFTP()); const scanned = await (0, sb_scandir_1.default)(localDirectory, { recursive, validate, }); const files = scanned.files.map((item) => path_1.default.relative(localDirectory, item)); const directories = scanned.directories.map((item) => path_1.default.relative(localDirectory, item)); // Sort shortest to longest directories.sort((a, b) => a.length - b.length); let failed = false; try { // Do the directories first. await new Promise((resolve, reject) => { const queue = new sb_promise_queue_1.PromiseQueue({ concurrency }); directories.forEach((directory) => { queue .add(async () => { await this.mkdir(path_1.default.join(remoteDirectory, directory), 'sftp', sftp); }) .catch(reject); }); resolve(queue.waitTillIdle()); }); // and now the files await new Promise((resolve, reject) => { const queue = new sb_promise_queue_1.PromiseQueue({ concurrency }); files.forEach((file) => { queue .add(async () => { const localFile = path_1.default.join(localDirectory, file); const remoteFile = path_1.default.join(remoteDirectory, file); try { await this.putFile(localFile, remoteFile, sftp, transferOptions); tick(localFile, remoteFile, null); } catch (_) { failed = true; tick(localFile, remoteFile, _); } }) .catch(reject); }); resolve(queue.waitTillIdle()); }); } finally { if (!givenSftp) { sftp.end(); } } return !failed; } async getDirectory(localDirectory, remoteDirectory, { concurrency = DEFAULT_CONCURRENCY, sftp: givenSftp = null, transferOptions = {}, recursive = true, tick = DEFAULT_TICK, validate = DEFAULT_VALIDATE, } = {}) { (0, assert_1.default)(typeof localDirectory === 'string' && localDirectory, 'localDirectory must be a string'); (0, assert_1.default)(typeof remoteDirectory === 'string' && remoteDirectory, 'remoteDirectory must be a string'); const localDirectoryStat = await new Promise((resolve) => { fs_1.default.stat(localDirectory, (err, stat) => { resolve(stat || null); }); }); (0, assert_1.default)(localDirectoryStat != null, `localDirectory does not exist at ${localDirectory}`); (0, assert_1.default)(localDirectoryStat.isDirectory(), `localDirectory is not a directory at ${localDirectory}`); const sftp = givenSftp || (await this.requestSFTP()); const scanned = await (0, sb_scandir_1.default)(remoteDirectory, { recursive, validate, concurrency, fileSystem: { basename(path) { return path_1.default.posix.basename(path); }, join(pathA, pathB) { return path_1.default.posix.join(pathA, pathB); }, readdir(path) { return new Promise((resolve, reject) => { sftp.readdir(path, (err, res) => { if (err) { reject(err); } else { resolve(res.map((item) => item.filename)); } }); }); }, stat(path) { return new Promise((resolve, reject) => { sftp.stat(path, (err, res) => { if (err) { reject(err); } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any resolve(res); } }); }); }, }, }); const files = scanned.files.map((item) => path_1.default.relative(remoteDirectory, item)); const directories = scanned.directories.map((item) => path_1.default.relative(remoteDirectory, item)); // Sort shortest to longest directories.sort((a, b) => a.length - b.length); let failed = false; try { // Do the directories first. await new Promise((resolve, reject) => { const queue = new sb_promise_queue_1.PromiseQueue({ concurrency }); directories.forEach((directory) => { queue .add(async () => { await (0, make_dir_1.default)(path_1.default.join(localDirectory, directory)); }) .catch(reject); }); resolve(queue.waitTillIdle()); }); // and now the files await new Promise((resolve, reject) => { const queue = new sb_promise_queue_1.PromiseQueue({ concurrency }); files.forEach((file) => { queue .add(async () => { const localFile = path_1.default.join(localDirectory, file); const remoteFile = path_1.default.join(remoteDirectory, file); try { await this.getFile(localFile, remoteFile, sftp, transferOptions); tick(localFile, remoteFile, null); } catch (_) { failed = true; tick(localFile, remoteFile, _); } }) .catch(reject); }); resolve(queue.waitTillIdle()); }); } finally { if (!givenSftp) { sftp.end(); } } return !failed; } forwardIn(remoteAddr, remotePort, onConnection) { const connection = this.getConnection(); return new Promise((resolve, reject) => { connection.forwardIn(remoteAddr, remotePort, (error, port) => { if (error) { reject(error); return; } const handler = (details, acceptConnection, rejectConnection) => { if (details.destIP === remoteAddr && details.destPort === port) { onConnection === null || onConnection === void 0 ? void 0 : onConnection(details, acceptConnection, rejectConnection); } }; if (onConnection) { connection.on('tcp connection', handler); } const dispose = () => { return new Promise((_resolve, _reject) => { connection.off('tcp connection', handler); connection.unforwardIn(remoteAddr, port, (_error) => { if (_error) { _reject(error); } _resolve(); }); }); }; resolve({ port, dispose }); }); }); } forwardOut(srcIP, srcPort, dstIP, dstPort) { const connection = this.getConnection(); return new Promise((resolve, reject) => { connection.forwardOut(srcIP, srcPort, dstIP, dstPort, (error, channel) => { if (error) { reject(error); return; } resolve(channel); }); }); } forwardInStreamLocal(socketPath, onConnection) { const connection = this.getConnection(); return new Promise((resolve, reject) => { connection.openssh_forwardInStreamLocal(socketPath, (error) => { if (error) { reject(error); return; } const handler = (details, acceptConnection, rejectConnection) => { if (details.socketPath === socketPath) { onConnection === null || onConnection === void 0 ? void 0 : onConnection(details, acceptConnection, rejectConnection); } }; if (onConnection) { connection.on('unix connection', handler); } const dispose = () => { return new Promise((_resolve, _reject) => { connection.off('unix connection', handler); connection.openssh_unforwardInStreamLocal(socketPath, (_error) => { if (_error) { _reject(_error); } _resolve(); }); }); }; resolve({ dispose }); }); }); } forwardOutStreamLocal(socketPath) { const connection = this.getConnection(); return new Promise((resolve, reject) => { connection.openssh_forwardOutStreamLocal(socketPath, (error, channel) => { if (error) { reject(error); return; } resolve(channel); }); }); } dispose() { if (this.connection) { this.connection.end(); this.connection = null; } } } exports.NodeSSH = NodeSSH; /***/ }), /***/ 6339: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var PromiseQueue = /** @class */ (function () { function PromiseQueue(_a) { var _b = (_a === void 0 ? {} : _a).concurrency, concurrency = _b === void 0 ? 1 : _b; this.options = { concurrency: concurrency }; this.running = 0; this.queue = []; this.idleCallbacks = []; } PromiseQueue.prototype.clear = function () { this.queue = []; }; PromiseQueue.prototype.onIdle = function (callback) { var _this = this; this.idleCallbacks.push(callback); return function () { var index = _this.idleCallbacks.indexOf(callback); if (index !== -1) { _this.idleCallbacks.splice(index, 1); } }; }; PromiseQueue.prototype.waitTillIdle = function () { var _this = this; return new Promise(function (resolve) { if (_this.running === 0) { resolve(); return; } var dispose = _this.onIdle(function () { dispose(); resolve(); }); }); }; PromiseQueue.prototype.add = function (callback) { var _this = this; return new Promise(function (resolve, reject) { var runCallback = function () { _this.running += 1; try { Promise.resolve(callback()).then(function (val) { resolve(val); _this.processNext(); }, function (err) { reject(err); _this.processNext(); }); } catch (err) { reject(err); _this.processNext(); } }; if (_this.running >= _this.options.concurrency) { _this.queue.push(runCallback); } else { runCallback(); } }); }; // Internal function, don't use PromiseQueue.prototype.processNext = function () { this.running -= 1; var callback = this.queue.shift(); if (callback) { callback(); } else if (this.running === 0) { this.idleCallbacks.forEach(function (item) { return item(); }); } }; return PromiseQueue; }()); exports.PromiseQueue = PromiseQueue; /***/ }), /***/ 9700: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* @flow */ var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultFilesystem = void 0; var fs_1 = __importDefault(__nccwpck_require__(9896)); var path_1 = __importDefault(__nccwpck_require__(6928)); var assert_1 = __importDefault(__nccwpck_require__(2613)); var sb_promise_queue_1 = __nccwpck_require__(6339); exports.defaultFilesystem = { join: function (pathA, pathB) { return path_1.default.join(pathA, pathB); }, basename: function (path) { return path_1.default.basename(path); }, stat: function (path) { return new Promise(function (resolve, reject) { fs_1.default.stat(path, function (err, res) { if (err) { reject(err); } else { resolve(res); } }); }); }, readdir: function (path) { return new Promise(function (resolve, reject) { fs_1.default.readdir(path, function (err, res) { if (err) { reject(err); } else { resolve(res); } }); }); }, }; function scanDirectoryInternal(_a) { var path = _a.path, recursive = _a.recursive, validate = _a.validate, result = _a.result, fileSystem = _a.fileSystem, queue = _a.queue, reject = _a.reject; return __awaiter(this, void 0, void 0, function () { var itemStat, contents; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, fileSystem.stat(path)]; case 1: itemStat = _b.sent(); if (itemStat.isFile()) { result.files.push(path); } else if (itemStat.isDirectory()) { result.directories.push(path); } if (!itemStat.isDirectory() || recursive === 'none') { return [2 /*return*/]; } return [4 /*yield*/, fileSystem.readdir(path)]; case 2: contents = _b.sent(); contents.forEach(function (item) { var itemPath = fileSystem.join(path, item); if (!validate(itemPath)) { return; } queue .add(function () { return scanDirectoryInternal({ path: itemPath, recursive: recursive === 'shallow' ? 'none' : 'deep', validate: validate, result: result, fileSystem: fileSystem, queue: queue, reject: reject, }); }) .catch(reject); }); return [2 /*return*/]; } }); }); } function scanDirectory(path, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.recursive, recursive = _c === void 0 ? true : _c, _d = _b.validate, validate = _d === void 0 ? null : _d, _e = _b.concurrency, concurrency = _e === void 0 ? Infinity : _e, _f = _b.fileSystem, fileSystem = _f === void 0 ? exports.defaultFilesystem : _f; return __awaiter(this, void 0, void 0, function () { var queue, result, mergedFileSystem; return __generator(this, function (_g) { switch (_g.label) { case 0: assert_1.default(path && typeof path === 'string', 'path must be a valid string'); assert_1.default(typeof recursive === 'boolean', 'options.recursive must be a valid boolean'); assert_1.default(validate === null || typeof validate === 'function', 'options.validate must be a valid function'); assert_1.default(typeof concurrency === 'number', 'options.concurrency must be a valid number'); assert_1.default(fileSystem !== null && typeof fileSystem === 'object', 'options.fileSystem must be a valid object'); queue = new sb_promise_queue_1.PromiseQueue({ concurrency: concurrency, }); result = { files: [], directories: [] }; mergedFileSystem = __assign(__assign({}, exports.defaultFilesystem), fileSystem); return [4 /*yield*/, new Promise(function (resolve, reject) { scanDirectoryInternal({ path: path, recursive: recursive ? 'deep' : 'shallow', validate: validate != null ? validate : function (item) { return mergedFileSystem.basename(item).slice(0, 1) !== '.'; }, result: result, fileSystem: mergedFileSystem, queue: queue, reject: reject, }) .then(function () { return queue.waitTillIdle(); }) .then(resolve, reject); })]; case 1: _g.sent(); return [2 /*return*/, result]; } }); }); } exports["default"] = scanDirectory; /***/ }), /***/ 6914: /***/ ((module) => { "use strict"; module.exports = {"rE":"0.4.10"}; /***/ }), /***/ 8342: /***/ ((module) => { "use strict"; module.exports = {"rE":"1.17.0"}; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __nccwpck_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ var threw = true; /******/ try { /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); /******/ threw = false; /******/ } finally { /******/ if(threw) delete __webpack_module_cache__[moduleId]; /******/ } /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat */ /******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined /******/ var __webpack_exports__ = __nccwpck_require__(1188); /******/ module.exports = __webpack_exports__; /******/ /******/ })() ; ================================================ FILE: lib/index.js ================================================ "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(require("@actions/core")); const node_ssh_1 = require("node-ssh"); const path_1 = __importDefault(require("path")); const ssh2_streams_1 = require("ssh2-streams"); const fs_1 = __importDefault(require("fs")); const keyboard_1 = require("./keyboard"); const path_2 = __importDefault(require("path")); function run() { return __awaiter(this, void 0, void 0, function* () { const host = core.getInput('host') || 'localhost'; const username = core.getInput('username'); const port = +core.getInput('port') || 22; const privateKey = core.getInput('privateKey'); const password = core.getInput('password'); const passphrase = core.getInput('passphrase'); const tryKeyboard = !!core.getInput('tryKeyboard'); const verbose = !!core.getInput('verbose') || true; const recursive = !!core.getInput('recursive') || true; const concurrency = +core.getInput('concurrency') || 1; const local = core.getInput('local'); const dotfiles = !!core.getInput('dotfiles') || true; const remote = core.getInput('remote'); const rmRemote = !!core.getInput('rmRemote') || false; const atomicPut = core.getInput('atomicPut'); if (atomicPut) { // patch SFTPStream to atomically rename files const originalFastPut = ssh2_streams_1.SFTPStream.prototype.fastPut; ssh2_streams_1.SFTPStream.prototype.fastPut = function (localPath, remotePath, opts, cb) { const parsedPath = path_2.default.posix.parse(remotePath); parsedPath.base = '.' + parsedPath.base; const tmpRemotePath = path_2.default.posix.format(parsedPath); const that = this; originalFastPut.apply(this, [ localPath, tmpRemotePath, opts, function (error, result) { if (error) { cb(error, result); } else { that.ext_openssh_rename(tmpRemotePath, remotePath, cb); } } ]); }; } try { const ssh = yield connect(host, username, port, privateKey, password, passphrase, tryKeyboard); yield scp(ssh, local, remote, dotfiles, concurrency, verbose, recursive, rmRemote); ssh.dispose(); } catch (err) { core.setFailed(err); } }); } function connect() { return __awaiter(this, arguments, void 0, function* (host = 'localhost', username, port = 22, privateKey, password, passphrase, tryKeyboard) { const ssh = new node_ssh_1.NodeSSH(); console.log(`Establishing a SSH connection to ${host}.`); try { const config = { host: host, port: port, username: username, password: password, passphrase: passphrase, tryKeyboard: tryKeyboard, onKeyboardInteractive: tryKeyboard ? (0, keyboard_1.keyboardFunction)(password) : null }; if (privateKey) { console.log('using provided private key'); config.privateKey = privateKey; } yield ssh.connect(config); console.log(`🤝 Connected to ${host}.`); } catch (err) { console.error(`⚠️ The GitHub Action couldn't connect to ${host}.`, err); core.setFailed(err.message); } return ssh; }); } function scp(ssh_1, local_1, remote_1) { return __awaiter(this, arguments, void 0, function* (ssh, local, remote, dotfiles = false, concurrency, verbose = true, recursive = true, rmRemote = false) { console.log(`Starting scp Action: ${local} to ${remote}`); try { if (isDirectory(local)) { if (rmRemote) { yield cleanDirectory(ssh, remote); } yield putDirectory(ssh, local, remote, dotfiles, concurrency, verbose, recursive); } else { yield putFile(ssh, local, remote, verbose); } ssh.dispose(); console.log('✅ scp Action finished.'); } catch (err) { console.error(`⚠️ An error happened:(.`, err.message, err.stack); ssh.dispose(); process.abort(); core.setFailed(err.message); } }); } function putDirectory(ssh_1, local_1, remote_1) { return __awaiter(this, arguments, void 0, function* (ssh, local, remote, dotfiles = false, concurrency = 3, verbose = false, recursive = true) { const failed = []; const successful = []; const status = yield ssh.putDirectory(local, remote, { recursive: recursive, concurrency: concurrency, validate: (path) => !path_1.default.basename(path).startsWith('.') || dotfiles, tick: function (localPath, remotePath, error) { if (error) { if (verbose) { console.log(`❕copy failed for ${localPath}.`); } failed.push({ local: localPath, remote: remotePath }); } else { if (verbose) { console.log(`✔ successfully copied ${localPath}.`); } successful.push({ local: localPath, remote: remotePath }); } } }); console.log(`The copy of directory ${local} was ${status ? 'successful' : 'unsuccessful'}.`); if (failed.length > 0) { console.log('failed transfers', failed.join(', ')); yield putMany(failed, (failed) => __awaiter(this, void 0, void 0, function* () { console.log(`Retrying to copy ${failed.local} to ${failed.remote}.`); yield putFile(ssh, failed.local, failed.remote, true); })); } }); } function cleanDirectory(ssh_1, remote_1) { return __awaiter(this, arguments, void 0, function* (ssh, remote, verbose = true) { try { yield ssh.execCommand(`rm -rf ${remote}/*`); if (verbose) { console.log(`✔ Successfully deleted all files of ${remote}.`); } } catch (error) { console.error(`⚠️ An error happened:(.`, error.message, error.stack); ssh.dispose(); core.setFailed(error.message); } }); } function putFile(ssh_1, local_1, remote_1) { return __awaiter(this, arguments, void 0, function* (ssh, local, remote, verbose = true) { try { yield ssh.putFile(local, remote); if (verbose) { console.log(`✔ Successfully copied file ${local} to remote ${remote}.`); } } catch (error) { console.error(`⚠️ An error happened:(.`, error.message, error.stack); ssh.dispose(); core.setFailed(error.message); } }); } function isDirectory(path) { return fs_1.default.existsSync(path) && fs_1.default.lstatSync(path).isDirectory(); } function putMany(array, asyncFunction) { return __awaiter(this, void 0, void 0, function* () { for (const el of array) { yield asyncFunction(el); } }); } process.on('uncaughtException', (err) => { if (err['code'] !== 'ECONNRESET') throw err; }); run(); ================================================ FILE: lib/keyboard.js ================================================ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.keyboardFunction = void 0; const keyboardFunction = password => (name, instructions, instructionsLang, prompts, finish) => { if (prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password')) { finish([password]); } }; exports.keyboardFunction = keyboardFunction; ================================================ FILE: package.json ================================================ { "name": "@garygrossgarten/github-action-scp", "version": "0.9.0", "description": "Copy a folder to a remote server using SSH.", "repository": { "type": "git", "url": "https://github.com/garygrossgarten/github-action-ssh" }, "main": "lib/index.js", "scripts": { "build": "tsc", "format": "prettier --write **/*.ts", "format-check": "prettier --check **/*.ts", "pack": "ncc build" }, "bin": { "github-action-ssh": "dist/index.js" }, "preferGlobal": false, "keywords": [ "typescript", "github", "github-actions", "actions", "ssh" ], "author": "garygrossgarten", "license": "MIT", "dependencies": { "@actions/core": "^2.0.0", "node-ssh": "^13.2.1", "ssh2-streams": "^0.4.10" }, "devDependencies": { "@types/node": "^24.12.0", "@vercel/ncc": "^0.38.4", "prettier": "^3.8.1", "typescript": "5.9.3" } } ================================================ FILE: readme.md ================================================ # GitHub Action SCP Simple GitHub Action to copy a folder or single file to a remote server using SSH. This is working with the latest [GitHub Actions](https://github.com/features/actions). ## ✨ Example Usage **Copy a folder recursively to a remote server** ```yml - name: Copy folder content recursively to remote uses: garygrossgarten/github-action-scp@release with: local: test remote: scp/directory host: ${{ secrets.HOST }} username: ${{ secrets.SSH_USER }} password: ${{ secrets.PASSWORD }} ``` **Copy a single file to a remote server** ```yml - name: Copy single file to remote uses: garygrossgarten/github-action-scp@release with: local: test/oof.txt remote: scp/single/oof.txt host: ${{ secrets.HOST }} username: ${{ secrets.SSH_USER }} password: ${{ secrets.PASSWORD }} ``` 🔐 Set your secrets here: `https://github.com/USERNAME/REPO/settings/secrets`. Check out [the workflow example](.github/workflows/scp-example-workflow.yml) for a minimalistic yaml workflow in GitHub Actions. **Result** ![result of example ssh workflow](result.png) ## Options - **local** - _string_ - Path to local folder you want to copy. **required** - **remote** - _string_ - Path to folder to copy the contents to. **required** - **concurrency** - _number_ - Number of concurrent file transfers. **Default:** `1` - **recursive** - _boolean_ - Copy directory contents recursively. **Default:** `true` - **verbose** - _boolean_ - Output every single file transfer status. **Default:** `true` - **host** - _string_ - Hostname or IP address of the server. **Default:** `'localhost'` - **port** - _integer_ - Port number of the server. **Default:** `22` - **username** - _string_ - Username for authentication. **Default:** (none) - **password** - _string_ - Password for password-based user authentication. **Default:** (none) - **dotfiles** - _boolean_ - Include files with a leading `.` e.g. `.htaccess` **Default:** `false` - **privateKey** - _mixed_ - _Buffer_ or _string_ that contains a private key for either key-based or hostbased user authentication (OpenSSH format). **Default:** (none) - **passphrase** - _string_ - For an encrypted private key, this is the passphrase used to decrypt it. **Default:** (none) - **tryKeyboard** - _boolean_ - Try keyboard-interactive user authentication if primary user authentication method fails. **Default:** `false` - **atomicPut** - _boolean_ - Upload files to temporary file first, then rename once upload completed. **Default:** `false` - **rmRemote** - _boolean_ - Clean directory before uploading. **Default:** `false` ## Development --- This thing is build using Typescript and [ssh2](https://github.com/mscdex/ssh2) (via [node-ssh](https://github.com/steelbrain/node-ssh)). 🚀 ================================================ FILE: src/index.ts ================================================ import * as core from '@actions/core'; import {Config, NodeSSH} from 'node-ssh'; import fsPath from 'path'; import {SFTPStream} from 'ssh2-streams'; import fs from 'fs'; import {keyboardFunction} from './keyboard'; import path from 'path'; async function run() { const host: string = core.getInput('host') || 'localhost'; const username: string = core.getInput('username'); const port: number = +core.getInput('port') || 22; const privateKey: string = core.getInput('privateKey'); const password: string = core.getInput('password'); const passphrase: string = core.getInput('passphrase'); const tryKeyboard: boolean = !!core.getInput('tryKeyboard'); const verbose: boolean = !!core.getInput('verbose') || true; const recursive: boolean = !!core.getInput('recursive') || true; const concurrency: number = +core.getInput('concurrency') || 1; const local: string = core.getInput('local'); const dotfiles: boolean = !!core.getInput('dotfiles') || true; const remote: string = core.getInput('remote'); const rmRemote: boolean = !!core.getInput('rmRemote') || false; const atomicPut: string = core.getInput('atomicPut'); if (atomicPut) { // patch SFTPStream to atomically rename files const originalFastPut = SFTPStream.prototype.fastPut; SFTPStream.prototype.fastPut = function (localPath, remotePath, opts, cb) { const parsedPath = path.posix.parse(remotePath); parsedPath.base = '.' + parsedPath.base; const tmpRemotePath = path.posix.format(parsedPath); const that = this; originalFastPut.apply(this, [ localPath, tmpRemotePath, opts, function (error, result) { if (error) { cb(error, result); } else { that.ext_openssh_rename(tmpRemotePath, remotePath, cb); } } ]); }; } try { const ssh = await connect( host, username, port, privateKey, password, passphrase, tryKeyboard ); await scp( ssh, local, remote, dotfiles, concurrency, verbose, recursive, rmRemote ); ssh.dispose(); } catch (err) { core.setFailed(err); } } async function connect( host = 'localhost', username: string, port = 22, privateKey: string, password: string, passphrase: string, tryKeyboard: boolean ) { const ssh = new NodeSSH(); console.log(`Establishing a SSH connection to ${host}.`); try { const config: Config = { host: host, port: port, username: username, password: password, passphrase: passphrase, tryKeyboard: tryKeyboard, onKeyboardInteractive: tryKeyboard ? keyboardFunction(password) : null }; if (privateKey) { console.log('using provided private key'); config.privateKey = privateKey; } await ssh.connect(config); console.log(`🤝 Connected to ${host}.`); } catch (err) { console.error(`⚠️ The GitHub Action couldn't connect to ${host}.`, err); core.setFailed(err.message); } return ssh; } async function scp( ssh: NodeSSH, local: string, remote: string, dotfiles = false, concurrency: number, verbose = true, recursive = true, rmRemote = false ) { console.log(`Starting scp Action: ${local} to ${remote}`); try { if (isDirectory(local)) { if (rmRemote) { await cleanDirectory(ssh, remote); } await putDirectory( ssh, local, remote, dotfiles, concurrency, verbose, recursive ); } else { await putFile(ssh, local, remote, verbose); } ssh.dispose(); console.log('✅ scp Action finished.'); } catch (err) { console.error(`⚠️ An error happened:(.`, err.message, err.stack); ssh.dispose(); process.abort(); core.setFailed(err.message); } } async function putDirectory( ssh: NodeSSH, local: string, remote: string, dotfiles = false, concurrency = 3, verbose = false, recursive = true ) { const failed: {local: string; remote: string}[] = []; const successful = []; const status = await ssh.putDirectory(local, remote, { recursive: recursive, concurrency: concurrency, validate: (path: string) => !fsPath.basename(path).startsWith('.') || dotfiles, tick: function (localPath, remotePath, error) { if (error) { if (verbose) { console.log(`❕copy failed for ${localPath}.`); } failed.push({local: localPath, remote: remotePath}); } else { if (verbose) { console.log(`✔ successfully copied ${localPath}.`); } successful.push({local: localPath, remote: remotePath}); } } }); console.log( `The copy of directory ${local} was ${ status ? 'successful' : 'unsuccessful' }.` ); if (failed.length > 0) { console.log('failed transfers', failed.join(', ')); await putMany(failed, async failed => { console.log(`Retrying to copy ${failed.local} to ${failed.remote}.`); await putFile(ssh, failed.local, failed.remote, true); }); } } async function cleanDirectory(ssh: NodeSSH, remote: string, verbose = true) { try { await ssh.execCommand(`rm -rf ${remote}/*`); if (verbose) { console.log(`✔ Successfully deleted all files of ${remote}.`); } } catch (error) { console.error(`⚠️ An error happened:(.`, error.message, error.stack); ssh.dispose(); core.setFailed(error.message); } } async function putFile( ssh: NodeSSH, local: string, remote: string, verbose = true ) { try { await ssh.putFile(local, remote); if (verbose) { console.log(`✔ Successfully copied file ${local} to remote ${remote}.`); } } catch (error) { console.error(`⚠️ An error happened:(.`, error.message, error.stack); ssh.dispose(); core.setFailed(error.message); } } function isDirectory(path: string) { return fs.existsSync(path) && fs.lstatSync(path).isDirectory(); } async function putMany( array: T[], asyncFunction: (item: T) => Promise ) { for (const el of array) { await asyncFunction(el); } } process.on('uncaughtException', (err) => { if (err['code'] !== 'ECONNRESET') throw err }) run(); ================================================ FILE: src/keyboard.ts ================================================ export const keyboardFunction = password => ( name, instructions, instructionsLang, prompts, finish ) => { if ( prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password') ) { finish([password]); } }; ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "outDir": "./lib", /* Redirect output structure to the directory. */ "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ }, "exclude": ["node_modules", "**/*.test.ts"] }