How to use s method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

index.js

Source:index.js Github

copy

Full Screen

...56 this.message = message;57 }58 toString() {59 let cmdStr = CMD_STRING + this.command;60 if (this.properties && Object.keys(this.properties).length > 0) {61 cmdStr += ' ';62 let first = true;63 for (const key in this.properties) {64 if (this.properties.hasOwnProperty(key)) {65 const val = this.properties[key];66 if (val) {67 if (first) {68 first = false;69 }70 else {71 cmdStr += ',';72 }73 cmdStr += `${key}=${escapeProperty(val)}`;74 }75 }76 }77 }78 cmdStr += `${CMD_STRING}${escapeData(this.message)}`;79 return cmdStr;80 }81}82function escapeData(s) {83 return utils_1.toCommandValue(s)84 .replace(/%/g, '%25')85 .replace(/\r/g, '%0D')86 .replace(/\n/g, '%0A');87}88function escapeProperty(s) {89 return utils_1.toCommandValue(s)90 .replace(/%/g, '%25')91 .replace(/\r/g, '%0D')92 .replace(/\n/g, '%0A')93 .replace(/:/g, '%3A')94 .replace(/,/g, '%2C');95}96//# sourceMappingURL=command.js.map97/***/ }),98/***/ 2186:99/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {100"use strict";101var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {102 if (k2 === undefined) k2 = k;103 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });104}) : (function(o, m, k, k2) {105 if (k2 === undefined) k2 = k;106 o[k2] = m[k];107}));108var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {109 Object.defineProperty(o, "default", { enumerable: true, value: v });110}) : function(o, v) {111 o["default"] = v;112});113var __importStar = (this && this.__importStar) || function (mod) {114 if (mod && mod.__esModule) return mod;115 var result = {};116 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);117 __setModuleDefault(result, mod);118 return result;119};120var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {121 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }122 return new (P || (P = Promise))(function (resolve, reject) {123 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }124 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }125 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }126 step((generator = generator.apply(thisArg, _arguments || [])).next());127 });128};129Object.defineProperty(exports, "__esModule", ({ value: true }));130exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;131const command_1 = __nccwpck_require__(7351);132const file_command_1 = __nccwpck_require__(717);133const utils_1 = __nccwpck_require__(5278);134const os = __importStar(__nccwpck_require__(2037));135const path = __importStar(__nccwpck_require__(1017));136const oidc_utils_1 = __nccwpck_require__(8041);137/**138 * The code to exit an action139 */140var ExitCode;141(function (ExitCode) {142 /**143 * A code indicating that the action was successful144 */145 ExitCode[ExitCode["Success"] = 0] = "Success";146 /**147 * A code indicating that the action was a failure148 */149 ExitCode[ExitCode["Failure"] = 1] = "Failure";150})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));151//-----------------------------------------------------------------------152// Variables153//-----------------------------------------------------------------------154/**155 * Sets env variable for this action and future actions in the job156 * @param name the name of the variable to set157 * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify158 */159// eslint-disable-next-line @typescript-eslint/no-explicit-any160function exportVariable(name, val) {161 const convertedVal = utils_1.toCommandValue(val);162 process.env[name] = convertedVal;163 const filePath = process.env['GITHUB_ENV'] || '';164 if (filePath) {165 return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val));166 }167 command_1.issueCommand('set-env', { name }, convertedVal);168}169exports.exportVariable = exportVariable;170/**171 * Registers a secret which will get masked from logs172 * @param secret value of the secret173 */174function setSecret(secret) {175 command_1.issueCommand('add-mask', {}, secret);176}177exports.setSecret = setSecret;178/**179 * Prepends inputPath to the PATH (for this action and future actions)180 * @param inputPath181 */182function addPath(inputPath) {183 const filePath = process.env['GITHUB_PATH'] || '';184 if (filePath) {185 file_command_1.issueFileCommand('PATH', inputPath);186 }187 else {188 command_1.issueCommand('add-path', {}, inputPath);189 }190 process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;191}192exports.addPath = addPath;193/**194 * Gets the value of an input.195 * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.196 * Returns an empty string if the value is not defined.197 *198 * @param name name of the input to get199 * @param options optional. See InputOptions.200 * @returns string201 */202function getInput(name, options) {203 const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';204 if (options && options.required && !val) {205 throw new Error(`Input required and not supplied: ${name}`);206 }207 if (options && options.trimWhitespace === false) {208 return val;209 }210 return val.trim();211}212exports.getInput = getInput;213/**214 * Gets the values of an multiline input. Each value is also trimmed.215 *216 * @param name name of the input to get217 * @param options optional. See InputOptions.218 * @returns string[]219 *220 */221function getMultilineInput(name, options) {222 const inputs = getInput(name, options)223 .split('\n')224 .filter(x => x !== '');225 if (options && options.trimWhitespace === false) {226 return inputs;227 }228 return inputs.map(input => input.trim());229}230exports.getMultilineInput = getMultilineInput;231/**232 * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.233 * Support boolean input list: `true | True | TRUE | false | False | FALSE` .234 * The return value is also in boolean type.235 * ref: https://yaml.org/spec/1.2/spec.html#id2804923236 *237 * @param name name of the input to get238 * @param options optional. See InputOptions.239 * @returns boolean240 */241function getBooleanInput(name, options) {242 const trueValue = ['true', 'True', 'TRUE'];243 const falseValue = ['false', 'False', 'FALSE'];244 const val = getInput(name, options);245 if (trueValue.includes(val))246 return true;247 if (falseValue.includes(val))248 return false;249 throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +250 `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);251}252exports.getBooleanInput = getBooleanInput;253/**254 * Sets the value of an output.255 *256 * @param name name of the output to set257 * @param value value to store. Non-string values will be converted to a string via JSON.stringify258 */259// eslint-disable-next-line @typescript-eslint/no-explicit-any260function setOutput(name, value) {261 const filePath = process.env['GITHUB_OUTPUT'] || '';262 if (filePath) {263 return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value));264 }265 process.stdout.write(os.EOL);266 command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value));267}268exports.setOutput = setOutput;269/**270 * Enables or disables the echoing of commands into stdout for the rest of the step.271 * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.272 *273 */274function setCommandEcho(enabled) {275 command_1.issue('echo', enabled ? 'on' : 'off');276}277exports.setCommandEcho = setCommandEcho;278//-----------------------------------------------------------------------279// Results280//-----------------------------------------------------------------------281/**282 * Sets the action status to failed.283 * When the action exits it will be with an exit code of 1284 * @param message add error issue message285 */286function setFailed(message) {287 process.exitCode = ExitCode.Failure;288 error(message);289}290exports.setFailed = setFailed;291//-----------------------------------------------------------------------292// Logging Commands293//-----------------------------------------------------------------------294/**295 * Gets whether Actions Step Debug is on or not296 */297function isDebug() {298 return process.env['RUNNER_DEBUG'] === '1';299}300exports.isDebug = isDebug;301/**302 * Writes debug message to user log303 * @param message debug message304 */305function debug(message) {306 command_1.issueCommand('debug', {}, message);307}308exports.debug = debug;309/**310 * Adds an error issue311 * @param message error issue message. Errors will be converted to string via toString()312 * @param properties optional properties to add to the annotation.313 */314function error(message, properties = {}) {315 command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);316}317exports.error = error;318/**319 * Adds a warning issue320 * @param message warning issue message. Errors will be converted to string via toString()321 * @param properties optional properties to add to the annotation.322 */323function warning(message, properties = {}) {324 command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);325}326exports.warning = warning;327/**328 * Adds a notice issue329 * @param message notice issue message. Errors will be converted to string via toString()330 * @param properties optional properties to add to the annotation.331 */332function notice(message, properties = {}) {333 command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);334}335exports.notice = notice;336/**337 * Writes info to log with console.log.338 * @param message info message339 */340function info(message) {341 process.stdout.write(message + os.EOL);342}343exports.info = info;344/**345 * Begin an output group.346 *347 * Output until the next `groupEnd` will be foldable in this group348 *349 * @param name The name of the output group350 */351function startGroup(name) {352 command_1.issue('group', name);353}354exports.startGroup = startGroup;355/**356 * End an output group.357 */358function endGroup() {359 command_1.issue('endgroup');360}361exports.endGroup = endGroup;362/**363 * Wrap an asynchronous function call in a group.364 *365 * Returns the same type as the function itself.366 *367 * @param name The name of the group368 * @param fn The function to wrap in the group369 */370function group(name, fn) {371 return __awaiter(this, void 0, void 0, function* () {372 startGroup(name);373 let result;374 try {375 result = yield fn();376 }377 finally {378 endGroup();379 }380 return result;381 });382}383exports.group = group;384//-----------------------------------------------------------------------385// Wrapper action state386//-----------------------------------------------------------------------387/**388 * Saves state for current action, the state can only be retrieved by this action's post job execution.389 *390 * @param name name of the state to store391 * @param value value to store. Non-string values will be converted to a string via JSON.stringify392 */393// eslint-disable-next-line @typescript-eslint/no-explicit-any394function saveState(name, value) {395 const filePath = process.env['GITHUB_STATE'] || '';396 if (filePath) {397 return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value));398 }399 command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value));400}401exports.saveState = saveState;402/**403 * Gets the value of an state set by this action's main execution.404 *405 * @param name name of the state to get406 * @returns string407 */408function getState(name) {409 return process.env[`STATE_${name}`] || '';410}411exports.getState = getState;412function getIDToken(aud) {413 return __awaiter(this, void 0, void 0, function* () {414 return yield oidc_utils_1.OidcClient.getIDToken(aud);415 });416}417exports.getIDToken = getIDToken;418/**419 * Summary exports420 */421var summary_1 = __nccwpck_require__(1327);422Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } }));423/**424 * @deprecated use core.summary425 */426var summary_2 = __nccwpck_require__(1327);427Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } }));428/**429 * Path exports430 */431var path_utils_1 = __nccwpck_require__(2981);432Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } }));433Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } }));434Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } }));435//# sourceMappingURL=core.js.map436/***/ }),437/***/ 717:438/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {439"use strict";440// For internal use, subject to change.441var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {442 if (k2 === undefined) k2 = k;443 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });444}) : (function(o, m, k, k2) {445 if (k2 === undefined) k2 = k;446 o[k2] = m[k];447}));448var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {449 Object.defineProperty(o, "default", { enumerable: true, value: v });450}) : function(o, v) {451 o["default"] = v;452});453var __importStar = (this && this.__importStar) || function (mod) {454 if (mod && mod.__esModule) return mod;455 var result = {};456 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);457 __setModuleDefault(result, mod);458 return result;459};460Object.defineProperty(exports, "__esModule", ({ value: true }));461exports.prepareKeyValueMessage = exports.issueFileCommand = void 0;462// We use any as a valid input type463/* eslint-disable @typescript-eslint/no-explicit-any */464const fs = __importStar(__nccwpck_require__(7147));465const os = __importStar(__nccwpck_require__(2037));466const uuid_1 = __nccwpck_require__(5840);467const utils_1 = __nccwpck_require__(5278);468function issueFileCommand(command, message) {469 const filePath = process.env[`GITHUB_${command}`];470 if (!filePath) {471 throw new Error(`Unable to find environment variable for file command ${command}`);472 }473 if (!fs.existsSync(filePath)) {474 throw new Error(`Missing file at path: ${filePath}`);475 }476 fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {477 encoding: 'utf8'478 });479}480exports.issueFileCommand = issueFileCommand;481function prepareKeyValueMessage(key, value) {482 const delimiter = `ghadelimiter_${uuid_1.v4()}`;483 const convertedValue = utils_1.toCommandValue(value);484 // These should realistically never happen, but just in case someone finds a485 // way to exploit uuid generation let's not allow keys or values that contain486 // the delimiter.487 if (key.includes(delimiter)) {488 throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);489 }490 if (convertedValue.includes(delimiter)) {491 throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);492 }493 return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;494}495exports.prepareKeyValueMessage = prepareKeyValueMessage;496//# sourceMappingURL=file-command.js.map497/***/ }),498/***/ 8041:499/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {500"use strict";501var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {502 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }503 return new (P || (P = Promise))(function (resolve, reject) {504 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }505 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }506 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }507 step((generator = generator.apply(thisArg, _arguments || [])).next());508 });509};510Object.defineProperty(exports, "__esModule", ({ value: true }));511exports.OidcClient = void 0;512const http_client_1 = __nccwpck_require__(6255);513const auth_1 = __nccwpck_require__(5526);514const core_1 = __nccwpck_require__(2186);515class OidcClient {516 static createHttpClient(allowRetry = true, maxRetry = 10) {517 const requestOptions = {518 allowRetries: allowRetry,519 maxRetries: maxRetry520 };521 return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);522 }523 static getRequestToken() {524 const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];525 if (!token) {526 throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');527 }528 return token;529 }530 static getIDTokenUrl() {531 const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];532 if (!runtimeUrl) {533 throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');534 }535 return runtimeUrl;536 }537 static getCall(id_token_url) {538 var _a;539 return __awaiter(this, void 0, void 0, function* () {540 const httpclient = OidcClient.createHttpClient();541 const res = yield httpclient542 .getJson(id_token_url)543 .catch(error => {544 throw new Error(`Failed to get ID Token. \n 545 Error Code : ${error.statusCode}\n 546 Error Message: ${error.result.message}`);547 });548 const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;549 if (!id_token) {550 throw new Error('Response json body do not have ID Token field');551 }552 return id_token;553 });554 }555 static getIDToken(audience) {556 return __awaiter(this, void 0, void 0, function* () {557 try {558 // New ID Token is requested from action service559 let id_token_url = OidcClient.getIDTokenUrl();560 if (audience) {561 const encodedAudience = encodeURIComponent(audience);562 id_token_url = `${id_token_url}&audience=${encodedAudience}`;563 }564 core_1.debug(`ID token url is ${id_token_url}`);565 const id_token = yield OidcClient.getCall(id_token_url);566 core_1.setSecret(id_token);567 return id_token;568 }569 catch (error) {570 throw new Error(`Error message: ${error.message}`);571 }572 });573 }574}575exports.OidcClient = OidcClient;576//# sourceMappingURL=oidc-utils.js.map577/***/ }),578/***/ 2981:579/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {580"use strict";581var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {582 if (k2 === undefined) k2 = k;583 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });584}) : (function(o, m, k, k2) {585 if (k2 === undefined) k2 = k;586 o[k2] = m[k];587}));588var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {589 Object.defineProperty(o, "default", { enumerable: true, value: v });590}) : function(o, v) {591 o["default"] = v;592});593var __importStar = (this && this.__importStar) || function (mod) {594 if (mod && mod.__esModule) return mod;595 var result = {};596 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);597 __setModuleDefault(result, mod);598 return result;599};600Object.defineProperty(exports, "__esModule", ({ value: true }));601exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;602const path = __importStar(__nccwpck_require__(1017));603/**604 * toPosixPath converts the given path to the posix form. On Windows, \\ will be605 * replaced with /.606 *607 * @param pth. Path to transform.608 * @return string Posix path.609 */610function toPosixPath(pth) {611 return pth.replace(/[\\]/g, '/');612}613exports.toPosixPath = toPosixPath;614/**615 * toWin32Path converts the given path to the win32 form. On Linux, / will be616 * replaced with \\.617 *618 * @param pth. Path to transform.619 * @return string Win32 path.620 */621function toWin32Path(pth) {622 return pth.replace(/[/]/g, '\\');623}624exports.toWin32Path = toWin32Path;625/**626 * toPlatformPath converts the given path to a platform-specific path. It does627 * this by replacing instances of / and \ with the platform-specific path628 * separator.629 *630 * @param pth The path to platformize.631 * @return string The platform-specific path.632 */633function toPlatformPath(pth) {634 return pth.replace(/[/\\]/g, path.sep);635}636exports.toPlatformPath = toPlatformPath;637//# sourceMappingURL=path-utils.js.map638/***/ }),639/***/ 1327:640/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {641"use strict";642var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {643 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }644 return new (P || (P = Promise))(function (resolve, reject) {645 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }646 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }647 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }648 step((generator = generator.apply(thisArg, _arguments || [])).next());649 });650};651Object.defineProperty(exports, "__esModule", ({ value: true }));652exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;653const os_1 = __nccwpck_require__(2037);654const fs_1 = __nccwpck_require__(7147);655const { access, appendFile, writeFile } = fs_1.promises;656exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';657exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';658class Summary {659 constructor() {660 this._buffer = '';661 }662 /**663 * Finds the summary file path from the environment, rejects if env var is not found or file does not exist664 * Also checks r/w permissions.665 *666 * @returns step summary file path667 */668 filePath() {669 return __awaiter(this, void 0, void 0, function* () {670 if (this._filePath) {671 return this._filePath;672 }673 const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];674 if (!pathFromEnv) {675 throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);676 }677 try {678 yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);679 }680 catch (_a) {681 throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);682 }683 this._filePath = pathFromEnv;684 return this._filePath;685 });686 }687 /**688 * Wraps content in an HTML tag, adding any HTML attributes689 *690 * @param {string} tag HTML tag to wrap691 * @param {string | null} content content within the tag692 * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add693 *694 * @returns {string} content wrapped in HTML element695 */696 wrap(tag, content, attrs = {}) {697 const htmlAttrs = Object.entries(attrs)698 .map(([key, value]) => ` ${key}="${value}"`)699 .join('');700 if (!content) {701 return `<${tag}${htmlAttrs}>`;702 }703 return `<${tag}${htmlAttrs}>${content}</${tag}>`;704 }705 /**706 * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.707 *708 * @param {SummaryWriteOptions} [options] (optional) options for write operation709 *710 * @returns {Promise<Summary>} summary instance711 */712 write(options) {713 return __awaiter(this, void 0, void 0, function* () {714 const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);715 const filePath = yield this.filePath();716 const writeFunc = overwrite ? writeFile : appendFile;717 yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });718 return this.emptyBuffer();719 });720 }721 /**722 * Clears the summary buffer and wipes the summary file723 *724 * @returns {Summary} summary instance725 */726 clear() {727 return __awaiter(this, void 0, void 0, function* () {728 return this.emptyBuffer().write({ overwrite: true });729 });730 }731 /**732 * Returns the current summary buffer as a string733 *734 * @returns {string} string of summary buffer735 */736 stringify() {737 return this._buffer;738 }739 /**740 * If the summary buffer is empty741 *742 * @returns {boolen} true if the buffer is empty743 */744 isEmptyBuffer() {745 return this._buffer.length === 0;746 }747 /**748 * Resets the summary buffer without writing to summary file749 *750 * @returns {Summary} summary instance751 */752 emptyBuffer() {753 this._buffer = '';754 return this;755 }756 /**757 * Adds raw text to the summary buffer758 *759 * @param {string} text content to add760 * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)761 *762 * @returns {Summary} summary instance763 */764 addRaw(text, addEOL = false) {765 this._buffer += text;766 return addEOL ? this.addEOL() : this;767 }768 /**769 * Adds the operating system-specific end-of-line marker to the buffer770 *771 * @returns {Summary} summary instance772 */773 addEOL() {774 return this.addRaw(os_1.EOL);775 }776 /**777 * Adds an HTML codeblock to the summary buffer778 *779 * @param {string} code content to render within fenced code block780 * @param {string} lang (optional) language to syntax highlight code781 *782 * @returns {Summary} summary instance783 */784 addCodeBlock(code, lang) {785 const attrs = Object.assign({}, (lang && { lang }));786 const element = this.wrap('pre', this.wrap('code', code), attrs);787 return this.addRaw(element).addEOL();788 }789 /**790 * Adds an HTML list to the summary buffer791 *792 * @param {string[]} items list of items to render793 * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)794 *795 * @returns {Summary} summary instance796 */797 addList(items, ordered = false) {798 const tag = ordered ? 'ol' : 'ul';799 const listItems = items.map(item => this.wrap('li', item)).join('');800 const element = this.wrap(tag, listItems);801 return this.addRaw(element).addEOL();802 }803 /**804 * Adds an HTML table to the summary buffer805 *806 * @param {SummaryTableCell[]} rows table rows807 *808 * @returns {Summary} summary instance809 */810 addTable(rows) {811 const tableBody = rows812 .map(row => {813 const cells = row814 .map(cell => {815 if (typeof cell === 'string') {816 return this.wrap('td', cell);817 }818 const { header, data, colspan, rowspan } = cell;819 const tag = header ? 'th' : 'td';820 const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));821 return this.wrap(tag, data, attrs);822 })823 .join('');824 return this.wrap('tr', cells);825 })826 .join('');827 const element = this.wrap('table', tableBody);828 return this.addRaw(element).addEOL();829 }830 /**831 * Adds a collapsable HTML details element to the summary buffer832 *833 * @param {string} label text for the closed state834 * @param {string} content collapsable content835 *836 * @returns {Summary} summary instance837 */838 addDetails(label, content) {839 const element = this.wrap('details', this.wrap('summary', label) + content);840 return this.addRaw(element).addEOL();841 }842 /**843 * Adds an HTML image tag to the summary buffer844 *845 * @param {string} src path to the image you to embed846 * @param {string} alt text description of the image847 * @param {SummaryImageOptions} options (optional) addition image attributes848 *849 * @returns {Summary} summary instance850 */851 addImage(src, alt, options) {852 const { width, height } = options || {};853 const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));854 const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));855 return this.addRaw(element).addEOL();856 }857 /**858 * Adds an HTML section heading element859 *860 * @param {string} text heading text861 * @param {number | string} [level=1] (optional) the heading level, default: 1862 *863 * @returns {Summary} summary instance864 */865 addHeading(text, level) {866 const tag = `h${level}`;867 const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)868 ? tag869 : 'h1';870 const element = this.wrap(allowedTag, text);871 return this.addRaw(element).addEOL();872 }873 /**874 * Adds an HTML thematic break (<hr>) to the summary buffer875 *876 * @returns {Summary} summary instance877 */878 addSeparator() {879 const element = this.wrap('hr', null);880 return this.addRaw(element).addEOL();881 }882 /**883 * Adds an HTML line break (<br>) to the summary buffer884 *885 * @returns {Summary} summary instance886 */887 addBreak() {888 const element = this.wrap('br', null);889 return this.addRaw(element).addEOL();890 }891 /**892 * Adds an HTML blockquote to the summary buffer893 *894 * @param {string} text quote text895 * @param {string} cite (optional) citation url896 *897 * @returns {Summary} summary instance898 */899 addQuote(text, cite) {900 const attrs = Object.assign({}, (cite && { cite }));901 const element = this.wrap('blockquote', text, attrs);902 return this.addRaw(element).addEOL();903 }904 /**905 * Adds an HTML anchor tag to the summary buffer906 *907 * @param {string} text link text/content908 * @param {string} href hyperlink909 *910 * @returns {Summary} summary instance911 */912 addLink(text, href) {913 const element = this.wrap('a', text, { href });914 return this.addRaw(element).addEOL();915 }916}917const _summary = new Summary();918/**919 * @deprecated use `core.summary`920 */921exports.markdownSummary = _summary;922exports.summary = _summary;923//# sourceMappingURL=summary.js.map924/***/ }),925/***/ 5278:926/***/ ((__unused_webpack_module, exports) => {927"use strict";928// We use any as a valid input type929/* eslint-disable @typescript-eslint/no-explicit-any */930Object.defineProperty(exports, "__esModule", ({ value: true }));931exports.toCommandProperties = exports.toCommandValue = void 0;932/**933 * Sanitizes an input into a string so it can be passed into issueCommand safely934 * @param input input to sanitize into a string935 */936function toCommandValue(input) {937 if (input === null || input === undefined) {938 return '';939 }940 else if (typeof input === 'string' || input instanceof String) {941 return input;942 }943 return JSON.stringify(input);944}945exports.toCommandValue = toCommandValue;946/**947 *948 * @param annotationProperties949 * @returns The command properties to send with the actual annotation command950 * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646951 */952function toCommandProperties(annotationProperties) {953 if (!Object.keys(annotationProperties).length) {954 return {};955 }956 return {957 title: annotationProperties.title,958 file: annotationProperties.file,959 line: annotationProperties.startLine,960 endLine: annotationProperties.endLine,961 col: annotationProperties.startColumn,962 endColumn: annotationProperties.endColumn963 };964}965exports.toCommandProperties = toCommandProperties;966//# sourceMappingURL=utils.js.map967/***/ }),968/***/ 5526:969/***/ (function(__unused_webpack_module, exports) {970"use strict";971var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {972 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }973 return new (P || (P = Promise))(function (resolve, reject) {974 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }975 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }976 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }977 step((generator = generator.apply(thisArg, _arguments || [])).next());978 });979};980Object.defineProperty(exports, "__esModule", ({ value: true }));981exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;982class BasicCredentialHandler {983 constructor(username, password) {984 this.username = username;985 this.password = password;986 }987 prepareRequest(options) {988 if (!options.headers) {989 throw Error('The request has no headers');990 }991 options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;992 }993 // This handler cannot handle 401994 canHandleAuthentication() {995 return false;996 }997 handleAuthentication() {998 return __awaiter(this, void 0, void 0, function* () {999 throw new Error('not implemented');1000 });1001 }1002}1003exports.BasicCredentialHandler = BasicCredentialHandler;1004class BearerCredentialHandler {1005 constructor(token) {1006 this.token = token;1007 }1008 // currently implements pre-authorization1009 // TODO: support preAuth = false where it hooks on 4011010 prepareRequest(options) {1011 if (!options.headers) {1012 throw Error('The request has no headers');1013 }1014 options.headers['Authorization'] = `Bearer ${this.token}`;1015 }1016 // This handler cannot handle 4011017 canHandleAuthentication() {1018 return false;1019 }1020 handleAuthentication() {1021 return __awaiter(this, void 0, void 0, function* () {1022 throw new Error('not implemented');1023 });1024 }1025}1026exports.BearerCredentialHandler = BearerCredentialHandler;1027class PersonalAccessTokenCredentialHandler {1028 constructor(token) {1029 this.token = token;1030 }1031 // currently implements pre-authorization1032 // TODO: support preAuth = false where it hooks on 4011033 prepareRequest(options) {1034 if (!options.headers) {1035 throw Error('The request has no headers');1036 }1037 options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;1038 }1039 // This handler cannot handle 4011040 canHandleAuthentication() {1041 return false;1042 }1043 handleAuthentication() {1044 return __awaiter(this, void 0, void 0, function* () {1045 throw new Error('not implemented');1046 });1047 }1048}1049exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;1050//# sourceMappingURL=auth.js.map1051/***/ }),1052/***/ 6255:1053/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {1054"use strict";1055/* eslint-disable @typescript-eslint/no-explicit-any */1056var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {1057 if (k2 === undefined) k2 = k;1058 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });1059}) : (function(o, m, k, k2) {1060 if (k2 === undefined) k2 = k;1061 o[k2] = m[k];1062}));1063var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {1064 Object.defineProperty(o, "default", { enumerable: true, value: v });1065}) : function(o, v) {1066 o["default"] = v;1067});1068var __importStar = (this && this.__importStar) || function (mod) {1069 if (mod && mod.__esModule) return mod;1070 var result = {};1071 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);1072 __setModuleDefault(result, mod);1073 return result;1074};1075var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {1076 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }1077 return new (P || (P = Promise))(function (resolve, reject) {1078 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }1079 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }1080 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }1081 step((generator = generator.apply(thisArg, _arguments || [])).next());1082 });1083};1084Object.defineProperty(exports, "__esModule", ({ value: true }));1085exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;1086const http = __importStar(__nccwpck_require__(3685));1087const https = __importStar(__nccwpck_require__(5687));1088const pm = __importStar(__nccwpck_require__(9835));1089const tunnel = __importStar(__nccwpck_require__(4294));1090var HttpCodes;1091(function (HttpCodes) {1092 HttpCodes[HttpCodes["OK"] = 200] = "OK";1093 HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";1094 HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";1095 HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";1096 HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";1097 HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";1098 HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";1099 HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";1100 HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";1101 HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";1102 HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";1103 HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";1104 HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";1105 HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";1106 HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";1107 HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";1108 HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";1109 HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";1110 HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";1111 HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";1112 HttpCodes[HttpCodes["Gone"] = 410] = "Gone";1113 HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";1114 HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";1115 HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";1116 HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";1117 HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";1118 HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";1119})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));1120var Headers;1121(function (Headers) {1122 Headers["Accept"] = "accept";1123 Headers["ContentType"] = "content-type";1124})(Headers = exports.Headers || (exports.Headers = {}));1125var MediaTypes;1126(function (MediaTypes) {1127 MediaTypes["ApplicationJson"] = "application/json";1128})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));1129/**1130 * Returns the proxy URL, depending upon the supplied url and proxy environment variables.1131 * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com1132 */1133function getProxyUrl(serverUrl) {1134 const proxyUrl = pm.getProxyUrl(new URL(serverUrl));1135 return proxyUrl ? proxyUrl.href : '';1136}1137exports.getProxyUrl = getProxyUrl;1138const HttpRedirectCodes = [1139 HttpCodes.MovedPermanently,1140 HttpCodes.ResourceMoved,1141 HttpCodes.SeeOther,1142 HttpCodes.TemporaryRedirect,1143 HttpCodes.PermanentRedirect1144];1145const HttpResponseRetryCodes = [1146 HttpCodes.BadGateway,1147 HttpCodes.ServiceUnavailable,1148 HttpCodes.GatewayTimeout1149];1150const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];1151const ExponentialBackoffCeiling = 10;1152const ExponentialBackoffTimeSlice = 5;1153class HttpClientError extends Error {1154 constructor(message, statusCode) {1155 super(message);1156 this.name = 'HttpClientError';1157 this.statusCode = statusCode;1158 Object.setPrototypeOf(this, HttpClientError.prototype);1159 }1160}1161exports.HttpClientError = HttpClientError;1162class HttpClientResponse {1163 constructor(message) {1164 this.message = message;1165 }1166 readBody() {1167 return __awaiter(this, void 0, void 0, function* () {1168 return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {1169 let output = Buffer.alloc(0);1170 this.message.on('data', (chunk) => {1171 output = Buffer.concat([output, chunk]);1172 });1173 this.message.on('end', () => {1174 resolve(output.toString());1175 });1176 }));1177 });1178 }1179}1180exports.HttpClientResponse = HttpClientResponse;1181function isHttps(requestUrl) {1182 const parsedUrl = new URL(requestUrl);1183 return parsedUrl.protocol === 'https:';1184}1185exports.isHttps = isHttps;1186class HttpClient {1187 constructor(userAgent, handlers, requestOptions) {1188 this._ignoreSslError = false;1189 this._allowRedirects = true;1190 this._allowRedirectDowngrade = false;1191 this._maxRedirects = 50;1192 this._allowRetries = false;1193 this._maxRetries = 1;1194 this._keepAlive = false;1195 this._disposed = false;1196 this.userAgent = userAgent;1197 this.handlers = handlers || [];1198 this.requestOptions = requestOptions;1199 if (requestOptions) {1200 if (requestOptions.ignoreSslError != null) {1201 this._ignoreSslError = requestOptions.ignoreSslError;1202 }1203 this._socketTimeout = requestOptions.socketTimeout;1204 if (requestOptions.allowRedirects != null) {1205 this._allowRedirects = requestOptions.allowRedirects;1206 }1207 if (requestOptions.allowRedirectDowngrade != null) {1208 this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;1209 }1210 if (requestOptions.maxRedirects != null) {1211 this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);1212 }1213 if (requestOptions.keepAlive != null) {1214 this._keepAlive = requestOptions.keepAlive;1215 }1216 if (requestOptions.allowRetries != null) {1217 this._allowRetries = requestOptions.allowRetries;1218 }1219 if (requestOptions.maxRetries != null) {1220 this._maxRetries = requestOptions.maxRetries;1221 }1222 }1223 }1224 options(requestUrl, additionalHeaders) {1225 return __awaiter(this, void 0, void 0, function* () {1226 return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});1227 });1228 }1229 get(requestUrl, additionalHeaders) {1230 return __awaiter(this, void 0, void 0, function* () {1231 return this.request('GET', requestUrl, null, additionalHeaders || {});1232 });1233 }1234 del(requestUrl, additionalHeaders) {1235 return __awaiter(this, void 0, void 0, function* () {1236 return this.request('DELETE', requestUrl, null, additionalHeaders || {});1237 });1238 }1239 post(requestUrl, data, additionalHeaders) {1240 return __awaiter(this, void 0, void 0, function* () {1241 return this.request('POST', requestUrl, data, additionalHeaders || {});1242 });1243 }1244 patch(requestUrl, data, additionalHeaders) {1245 return __awaiter(this, void 0, void 0, function* () {1246 return this.request('PATCH', requestUrl, data, additionalHeaders || {});1247 });1248 }1249 put(requestUrl, data, additionalHeaders) {1250 return __awaiter(this, void 0, void 0, function* () {1251 return this.request('PUT', requestUrl, data, additionalHeaders || {});1252 });1253 }1254 head(requestUrl, additionalHeaders) {1255 return __awaiter(this, void 0, void 0, function* () {1256 return this.request('HEAD', requestUrl, null, additionalHeaders || {});1257 });1258 }1259 sendStream(verb, requestUrl, stream, additionalHeaders) {1260 return __awaiter(this, void 0, void 0, function* () {1261 return this.request(verb, requestUrl, stream, additionalHeaders);1262 });1263 }1264 /**1265 * Gets a typed object from an endpoint1266 * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise1267 */1268 getJson(requestUrl, additionalHeaders = {}) {1269 return __awaiter(this, void 0, void 0, function* () {1270 additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);1271 const res = yield this.get(requestUrl, additionalHeaders);1272 return this._processResponse(res, this.requestOptions);1273 });1274 }1275 postJson(requestUrl, obj, additionalHeaders = {}) {1276 return __awaiter(this, void 0, void 0, function* () {1277 const data = JSON.stringify(obj, null, 2);1278 additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);1279 additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);1280 const res = yield this.post(requestUrl, data, additionalHeaders);1281 return this._processResponse(res, this.requestOptions);1282 });1283 }1284 putJson(requestUrl, obj, additionalHeaders = {}) {1285 return __awaiter(this, void 0, void 0, function* () {1286 const data = JSON.stringify(obj, null, 2);1287 additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);1288 additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);1289 const res = yield this.put(requestUrl, data, additionalHeaders);1290 return this._processResponse(res, this.requestOptions);1291 });1292 }1293 patchJson(requestUrl, obj, additionalHeaders = {}) {1294 return __awaiter(this, void 0, void 0, function* () {1295 const data = JSON.stringify(obj, null, 2);1296 additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);1297 additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);1298 const res = yield this.patch(requestUrl, data, additionalHeaders);1299 return this._processResponse(res, this.requestOptions);1300 });1301 }1302 /**1303 * Makes a raw http request.1304 * All other methods such as get, post, patch, and request ultimately call this.1305 * Prefer get, del, post and patch1306 */1307 request(verb, requestUrl, data, headers) {1308 return __awaiter(this, void 0, void 0, function* () {1309 if (this._disposed) {1310 throw new Error('Client has already been disposed.');1311 }1312 const parsedUrl = new URL(requestUrl);1313 let info = this._prepareRequest(verb, parsedUrl, headers);1314 // Only perform retries on reads since writes may not be idempotent.1315 const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)1316 ? this._maxRetries + 11317 : 1;1318 let numTries = 0;1319 let response;1320 do {1321 response = yield this.requestRaw(info, data);1322 // Check if it's an authentication challenge1323 if (response &&1324 response.message &&1325 response.message.statusCode === HttpCodes.Unauthorized) {1326 let authenticationHandler;1327 for (const handler of this.handlers) {1328 if (handler.canHandleAuthentication(response)) {1329 authenticationHandler = handler;1330 break;1331 }1332 }1333 if (authenticationHandler) {1334 return authenticationHandler.handleAuthentication(this, info, data);1335 }1336 else {1337 // We have received an unauthorized response but have no handlers to handle it.1338 // Let the response return to the caller.1339 return response;1340 }1341 }1342 let redirectsRemaining = this._maxRedirects;1343 while (response.message.statusCode &&1344 HttpRedirectCodes.includes(response.message.statusCode) &&1345 this._allowRedirects &&1346 redirectsRemaining > 0) {1347 const redirectUrl = response.message.headers['location'];1348 if (!redirectUrl) {1349 // if there's no location to redirect to, we won't1350 break;1351 }1352 const parsedRedirectUrl = new URL(redirectUrl);1353 if (parsedUrl.protocol === 'https:' &&1354 parsedUrl.protocol !== parsedRedirectUrl.protocol &&1355 !this._allowRedirectDowngrade) {1356 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.');1357 }1358 // we need to finish reading the response before reassigning response1359 // which will leak the open socket.1360 yield response.readBody();1361 // strip authorization header if redirected to a different hostname1362 if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {1363 for (const header in headers) {1364 // header names are case insensitive1365 if (header.toLowerCase() === 'authorization') {1366 delete headers[header];1367 }1368 }1369 }1370 // let's make the request with the new redirectUrl1371 info = this._prepareRequest(verb, parsedRedirectUrl, headers);1372 response = yield this.requestRaw(info, data);1373 redirectsRemaining--;1374 }1375 if (!response.message.statusCode ||1376 !HttpResponseRetryCodes.includes(response.message.statusCode)) {1377 // If not a retry code, return immediately instead of retrying1378 return response;1379 }1380 numTries += 1;1381 if (numTries < maxTries) {1382 yield response.readBody();1383 yield this._performExponentialBackoff(numTries);1384 }1385 } while (numTries < maxTries);1386 return response;1387 });1388 }1389 /**1390 * Needs to be called if keepAlive is set to true in request options.1391 */1392 dispose() {1393 if (this._agent) {1394 this._agent.destroy();1395 }1396 this._disposed = true;1397 }1398 /**1399 * Raw request.1400 * @param info1401 * @param data1402 */1403 requestRaw(info, data) {1404 return __awaiter(this, void 0, void 0, function* () {1405 return new Promise((resolve, reject) => {1406 function callbackForResult(err, res) {1407 if (err) {1408 reject(err);1409 }1410 else if (!res) {1411 // If `err` is not passed, then `res` must be passed.1412 reject(new Error('Unknown error'));1413 }1414 else {1415 resolve(res);1416 }1417 }1418 this.requestRawWithCallback(info, data, callbackForResult);1419 });1420 });1421 }1422 /**1423 * Raw request with callback.1424 * @param info1425 * @param data1426 * @param onResult1427 */1428 requestRawWithCallback(info, data, onResult) {1429 if (typeof data === 'string') {1430 if (!info.options.headers) {1431 info.options.headers = {};1432 }1433 info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');1434 }1435 let callbackCalled = false;1436 function handleResult(err, res) {1437 if (!callbackCalled) {1438 callbackCalled = true;1439 onResult(err, res);1440 }1441 }1442 const req = info.httpModule.request(info.options, (msg) => {1443 const res = new HttpClientResponse(msg);1444 handleResult(undefined, res);1445 });1446 let socket;1447 req.on('socket', sock => {1448 socket = sock;1449 });1450 // If we ever get disconnected, we want the socket to timeout eventually1451 req.setTimeout(this._socketTimeout || 3 * 60000, () => {1452 if (socket) {1453 socket.end();1454 }1455 handleResult(new Error(`Request timeout: ${info.options.path}`));1456 });1457 req.on('error', function (err) {1458 // err has statusCode property1459 // res should have headers1460 handleResult(err);1461 });1462 if (data && typeof data === 'string') {1463 req.write(data, 'utf8');1464 }1465 if (data && typeof data !== 'string') {1466 data.on('close', function () {1467 req.end();1468 });1469 data.pipe(req);1470 }1471 else {1472 req.end();1473 }1474 }1475 /**1476 * Gets an http agent. This function is useful when you need an http agent that handles1477 * routing through a proxy server - depending upon the url and proxy environment variables.1478 * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com1479 */1480 getAgent(serverUrl) {1481 const parsedUrl = new URL(serverUrl);1482 return this._getAgent(parsedUrl);1483 }1484 _prepareRequest(method, requestUrl, headers) {1485 const info = {};1486 info.parsedUrl = requestUrl;1487 const usingSsl = info.parsedUrl.protocol === 'https:';1488 info.httpModule = usingSsl ? https : http;1489 const defaultPort = usingSsl ? 443 : 80;1490 info.options = {};1491 info.options.host = info.parsedUrl.hostname;1492 info.options.port = info.parsedUrl.port1493 ? parseInt(info.parsedUrl.port)1494 : defaultPort;1495 info.options.path =1496 (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');1497 info.options.method = method;1498 info.options.headers = this._mergeHeaders(headers);1499 if (this.userAgent != null) {1500 info.options.headers['user-agent'] = this.userAgent;1501 }1502 info.options.agent = this._getAgent(info.parsedUrl);1503 // gives handlers an opportunity to participate1504 if (this.handlers) {1505 for (const handler of this.handlers) {1506 handler.prepareRequest(info.options);1507 }1508 }1509 return info;1510 }1511 _mergeHeaders(headers) {1512 if (this.requestOptions && this.requestOptions.headers) {1513 return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));1514 }1515 return lowercaseKeys(headers || {});1516 }1517 _getExistingOrDefaultHeader(additionalHeaders, header, _default) {1518 let clientHeader;1519 if (this.requestOptions && this.requestOptions.headers) {1520 clientHeader = lowercaseKeys(this.requestOptions.headers)[header];1521 }1522 return additionalHeaders[header] || clientHeader || _default;1523 }1524 _getAgent(parsedUrl) {1525 let agent;1526 const proxyUrl = pm.getProxyUrl(parsedUrl);1527 const useProxy = proxyUrl && proxyUrl.hostname;1528 if (this._keepAlive && useProxy) {1529 agent = this._proxyAgent;1530 }1531 if (this._keepAlive && !useProxy) {1532 agent = this._agent;1533 }1534 // if agent is already assigned use that agent.1535 if (agent) {1536 return agent;1537 }1538 const usingSsl = parsedUrl.protocol === 'https:';1539 let maxSockets = 100;1540 if (this.requestOptions) {1541 maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;1542 }1543 // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.1544 if (proxyUrl && proxyUrl.hostname) {1545 const agentOptions = {1546 maxSockets,1547 keepAlive: this._keepAlive,1548 proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {1549 proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`1550 })), { host: proxyUrl.hostname, port: proxyUrl.port })1551 };1552 let tunnelAgent;1553 const overHttps = proxyUrl.protocol === 'https:';1554 if (usingSsl) {1555 tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;1556 }1557 else {1558 tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;1559 }1560 agent = tunnelAgent(agentOptions);1561 this._proxyAgent = agent;1562 }1563 // if reusing agent across request and tunneling agent isn't assigned create a new agent1564 if (this._keepAlive && !agent) {1565 const options = { keepAlive: this._keepAlive, maxSockets };1566 agent = usingSsl ? new https.Agent(options) : new http.Agent(options);1567 this._agent = agent;1568 }1569 // if not using private agent and tunnel agent isn't setup then use global agent1570 if (!agent) {1571 agent = usingSsl ? https.globalAgent : http.globalAgent;1572 }1573 if (usingSsl && this._ignoreSslError) {1574 // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process1575 // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options1576 // we have to cast it to any and change it directly1577 agent.options = Object.assign(agent.options || {}, {1578 rejectUnauthorized: false1579 });1580 }1581 return agent;1582 }1583 _performExponentialBackoff(retryNumber) {1584 return __awaiter(this, void 0, void 0, function* () {1585 retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);1586 const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);1587 return new Promise(resolve => setTimeout(() => resolve(), ms));1588 });1589 }1590 _processResponse(res, options) {1591 return __awaiter(this, void 0, void 0, function* () {1592 return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {1593 const statusCode = res.message.statusCode || 0;1594 const response = {1595 statusCode,1596 result: null,1597 headers: {}1598 };1599 // not found leads to null obj returned1600 if (statusCode === HttpCodes.NotFound) {1601 resolve(response);1602 }1603 // get the result from the body1604 function dateTimeDeserializer(key, value) {1605 if (typeof value === 'string') {1606 const a = new Date(value);1607 if (!isNaN(a.valueOf())) {1608 return a;1609 }1610 }1611 return value;1612 }1613 let obj;1614 let contents;1615 try {1616 contents = yield res.readBody();1617 if (contents && contents.length > 0) {1618 if (options && options.deserializeDates) {1619 obj = JSON.parse(contents, dateTimeDeserializer);1620 }1621 else {1622 obj = JSON.parse(contents);1623 }1624 response.result = obj;1625 }1626 response.headers = res.message.headers;1627 }1628 catch (err) {1629 // Invalid resource (contents not json); leaving result obj null1630 }1631 // note that 3xx redirects are handled by the http layer.1632 if (statusCode > 299) {1633 let msg;1634 // if exception/error in body, attempt to get better error1635 if (obj && obj.message) {1636 msg = obj.message;1637 }1638 else if (contents && contents.length > 0) {1639 // it may be the case that the exception is in the body message as string1640 msg = contents;1641 }1642 else {1643 msg = `Failed request: (${statusCode})`;1644 }1645 const err = new HttpClientError(msg, statusCode);1646 err.result = response.result;1647 reject(err);1648 }1649 else {1650 resolve(response);1651 }1652 }));1653 });1654 }1655}1656exports.HttpClient = HttpClient;1657const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});1658//# sourceMappingURL=index.js.map1659/***/ }),1660/***/ 9835:1661/***/ ((__unused_webpack_module, exports) => {1662"use strict";1663Object.defineProperty(exports, "__esModule", ({ value: true }));1664exports.checkBypass = exports.getProxyUrl = void 0;1665function getProxyUrl(reqUrl) {1666 const usingSsl = reqUrl.protocol === 'https:';1667 if (checkBypass(reqUrl)) {1668 return undefined;1669 }1670 const proxyVar = (() => {1671 if (usingSsl) {1672 return process.env['https_proxy'] || process.env['HTTPS_PROXY'];1673 }1674 else {1675 return process.env['http_proxy'] || process.env['HTTP_PROXY'];1676 }1677 })();1678 if (proxyVar) {1679 return new URL(proxyVar);1680 }1681 else {1682 return undefined;1683 }1684}1685exports.getProxyUrl = getProxyUrl;1686function checkBypass(reqUrl) {1687 if (!reqUrl.hostname) {1688 return false;1689 }1690 const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';1691 if (!noProxy) {1692 return false;1693 }1694 // Determine the request port1695 let reqPort;1696 if (reqUrl.port) {1697 reqPort = Number(reqUrl.port);1698 }1699 else if (reqUrl.protocol === 'http:') {1700 reqPort = 80;1701 }1702 else if (reqUrl.protocol === 'https:') {1703 reqPort = 443;1704 }1705 // Format the request hostname and hostname with port1706 const upperReqHosts = [reqUrl.hostname.toUpperCase()];1707 if (typeof reqPort === 'number') {1708 upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);1709 }1710 // Compare request host against noproxy1711 for (const upperNoProxyItem of noProxy1712 .split(',')1713 .map(x => x.trim().toUpperCase())1714 .filter(x => x)) {1715 if (upperReqHosts.some(x => x === upperNoProxyItem)) {1716 return true;1717 }1718 }1719 return false;1720}1721exports.checkBypass = checkBypass;1722//# sourceMappingURL=proxy.js.map1723/***/ }),1724/***/ 308:1725/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {1726(()=>{"use strict";var e={3497:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true});t.isExternalAccount=t.isServiceAccountKey=t.parseCredential=void 0;const s=n(6976);const i=n(3102);function parseCredential(e){e=(e||"").trim();if(!e){throw new Error(`Missing service account key JSON (got empty value)`)}if(!e.startsWith("{")){e=(0,i.fromBase64)(e)}try{const t=JSON.parse(e);return t}catch(e){const t=(0,s.errorMessage)(e);throw new SyntaxError(`Failed to parse service account key JSON credentials: ${t}`)}}t.parseCredential=parseCredential;function isServiceAccountKey(e){return e.type==="service_account"}t.isServiceAccountKey=isServiceAccountKey;function isExternalAccount(e){return e.type!=="external_account"}t.isExternalAccount=isExternalAccount;t["default"]={parseCredential:parseCredential,isServiceAccountKey:isServiceAccountKey,isExternalAccount:isExternalAccount}},1848:function(e,t,n){var s=this&&this.__createBinding||(Object.create?function(e,t,n,s){if(s===undefined)s=n;var i=Object.getOwnPropertyDescriptor(t,n);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable)){i={enumerable:true,get:function(){return t[n]}}}Object.defineProperty(e,s,i)}:function(e,t,n,s){if(s===undefined)s=n;e[s]=t[n]});var i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)if(n!=="default"&&Object.prototype.hasOwnProperty.call(e,n))s(t,e,n);i(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.deepClone=void 0;const o=r(n(4655));function deepClone(e,t=true){if(t&&typeof structuredClone==="function"){return structuredClone(e)}return o.deserialize(o.serialize(e))}t.deepClone=deepClone},7962:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.parseCSV=void 0;function parseCSV(e){e=(e||"").trim();if(!e){return[]}const t=e.split(/(?<!\\),/gi);for(let e=0;e<t.length;e++){t[e]=t[e].trim().replace(/\\,/gi,",")}return t}t.parseCSV=parseCSV},3102:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.fromBase64=t.toBase64=void 0;function toBase64(e){return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}t.toBase64=toBase64;function fromBase64(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");while(t.length%4)t+="=";return Buffer.from(t,"base64").toString("utf8")}t.fromBase64=fromBase64},6976:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.isNotFoundError=t.errorMessage=void 0;function errorMessage(e){let t;if(e===null){t="null"}else if(e===undefined||typeof e==="undefined"){t="undefined"}else if(typeof e==="bigint"||e instanceof BigInt){t=e.toString()}else if(typeof e==="boolean"||e instanceof Boolean){t=e.toString()}else if(e instanceof Error){t=e.message}else if(typeof e==="function"||e instanceof Function){t=errorMessage(e())}else if(typeof e==="number"||e instanceof Number){t=e.toString()}else if(typeof e==="string"||e instanceof String){t=e.toString()}else if(typeof e==="symbol"||e instanceof Symbol){t=e.toString()}else if(typeof e==="object"||e instanceof Object){t=JSON.stringify(e)}else{t=String(`[${typeof e}] ${e}`)}const n=t.trim().replace("Error: ","").trim();if(!n)return"";if(n.length>1&&isUpper(n[0])&&!isUpper(n[1])){return n[0].toLowerCase()+n.slice(1)}return n}t.errorMessage=errorMessage;function isNotFoundError(e){const t=errorMessage(e);return t.toUpperCase().includes("ENOENT")}t.isNotFoundError=isNotFoundError;function isUpper(e){return e===e.toUpperCase()}},3252:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.readUntil=t.parseFlags=void 0;function parseFlags(e){const t=[];let n="";let s=false;for(let i=0;i<e.length;i++){const r=e[i];if(r===`'`){const t=readUntil(e.slice(i+1),`'`);if(t===null){throw new Error(`Unterminated single quote in ${e} at position ${i}`)}n+=r+t;i+=t.length;continue}if(r===`"`){const t=readUntil(e.slice(i+1),`"`);if(t===null){throw new Error(`Unterminated double quote in ${e} at position ${i}`)}n+=r+t;i+=t.length;continue}if(r==="\r"||r===`\n`||r===` `){s=false;if(n!==``){t.push(n);n=``}continue}if(r===`=`){if(!s&&n[0]===`-`){t.push(n);n=``;s=true;continue}}n+=r}if(n!==""){t.push(n)}return t}t.parseFlags=parseFlags;function readUntil(e,t){let n=false;let s="";for(let i=0;i<e.length;i++){const r=e[i];s+=r;if(r===`\\`){n=true;continue}if(r===t&&!n){return s}n=false}return null}t.readUntil=readUntil},9219:function(e,t,n){var s=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.removeFile=t.writeSecureFile=t.isEmptyDir=t.forceRemove=void 0;const i=n(7147);const r=n(6976);function forceRemove(e){return s(this,void 0,void 0,(function*(){try{yield i.promises.rm(e,{force:true,recursive:true})}catch(t){if(!(0,r.isNotFoundError)(t)){const n=(0,r.errorMessage)(t);throw new Error(`Failed to remove "${e}": ${n}`)}}}))}t.forceRemove=forceRemove;function isEmptyDir(e){return s(this,void 0,void 0,(function*(){try{const t=yield i.promises.readdir(e);return t.length<=0}catch(e){return true}}))}t.isEmptyDir=isEmptyDir;function writeSecureFile(e,t){return s(this,void 0,void 0,(function*(){yield i.promises.writeFile(e,t,{mode:416,flag:"wx"});return e}))}t.writeSecureFile=writeSecureFile;function removeFile(e){return s(this,void 0,void 0,(function*(){try{yield i.promises.unlink(e);return true}catch(t){if((0,r.isNotFoundError)(t)){return false}const n=(0,r.errorMessage)(t);throw new Error(`Failed to remove "${e}": ${n}`)}}))}t.removeFile=removeFile},546:function(e,t,n){var s=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.parseGcloudIgnore=void 0;const i=n(7147);const r=n(1017);const o=n(6976);function parseGcloudIgnore(e){return s(this,void 0,void 0,(function*(){const t=(0,r.dirname)(e);let n=[];try{n=(yield i.promises.readFile(e,{encoding:"utf-8"})).toString().split(/\r?\n/).filter(shouldKeepIgnoreLine).map((e=>e.trim()))}catch(e){if(!(0,o.isNotFoundError)(e)){throw e}}for(let e=0;e<n.length;e++){const s=n[e];if(s.startsWith("#!include:")){const o=s.substring(10).trim();const a=(0,r.join)(t,o);const c=(yield i.promises.readFile(a,{encoding:"utf-8"})).toString().split(/\r?\n/).filter(shouldKeepIgnoreLine).map((e=>e.trim()));n.splice(e,1,...c);e+=c.length}}return n}))}t.parseGcloudIgnore=parseGcloudIgnore;function shouldKeepIgnoreLine(e){const t=(e||"").trim();if(t===""){return false}if(t.startsWith("#")&&!t.startsWith("#!")){return false}return true}},6144:function(e,t,n){var s=this&&this.__createBinding||(Object.create?function(e,t,n,s){if(s===undefined)s=n;var i=Object.getOwnPropertyDescriptor(t,n);if(!i||("get"in i?!t.__esModule:i.writable||i.configurable)){i={enumerable:true,get:function(){return t[n]}}}Object.defineProperty(e,s,i)}:function(e,t,n,s){if(s===undefined)s=n;e[s]=t[n]});var i=this&&this.__exportStar||function(e,t){for(var n in e)if(n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n))s(t,e,n)};Object.defineProperty(t,"__esModule",{value:true});i(n(3497),t);i(n(1848),t);i(n(7962),t);i(n(3102),t);i(n(6976),t);i(n(3252),t);i(n(9219),t);i(n(546),t);i(n(575),t);i(n(9497),t);i(n(5737),t);i(n(570),t);i(n(1043),t);i(n(9017),t);i(n(7575),t);i(n(596),t);i(n(9324),t)},575:function(e,t,n){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.parseKVStringAndFile=t.parseKVYAML=t.parseKVJSON=t.parseKVFile=t.parseKVString=void 0;const i=s(n(4083));const r=n(7147);const o=n(6976);function parseKVString(e){e=(e||"").trim();if(!e){return{}}const t={};const n=e.split(/(?<!\\)[,\n]/gi);for(let e=0;e<n.length;e++){const s=(n[e]||"").trim();if(!s){continue}const i=s.indexOf("=");if(!i||i===-1){throw new SyntaxError(`Failed to parse KEY=VALUE pair "${s}": missing "="`)}const r=s.slice(0,i).trim().replace(/\\([,\n])/gi,"$1");const o=s.slice(i+1).trim().replace(/\\([,\n])/gi,"$1");if(!r||!o){throw new SyntaxError(`Failed to parse KEY=VALUE pair "${s}": no value`)}t[r]=o}return t}t.parseKVString=parseKVString;function parseKVFile(e){try{const t=(0,r.readFileSync)(e,"utf-8");if(t&&t.trim()&&t.trim()[0]==="{"){return parseKVJSON(t)}return parseKVYAML(t)}catch(t){const n=(0,o.errorMessage)(t);throw new Error(`Failed to read file '${e}': ${n}`)}}t.parseKVFile=parseKVFile;function parseKVJSON(e){e=(e||"").trim();if(!e){return{}}try{const t=JSON.parse(e);const n={};for(const[e,s]of Object.entries(t)){if(typeof e!=="string"){throw new SyntaxError(`Failed to parse key "${e}", expected string, got ${typeof e}`)}if(e.trim()===""){throw new SyntaxError(`Failed to parse key "${e}", expected at least one character`)}if(typeof s!=="string"){const t=JSON.stringify(s);throw new SyntaxError(`Failed to parse value "${t}" for "${e}", expected string, got ${typeof s}`)}if(s.trim()===""){throw new SyntaxError(`Value for key "${e}" cannot be empty (got "${s}")`)}n[e]=s}return n}catch(e){const t=(0,o.errorMessage)(e);throw new Error(`Failed to parse KV pairs as JSON: ${t}`)}}t.parseKVJSON=parseKVJSON;function parseKVYAML(e){if(!e||e.trim().length===0){return{}}const t=i.default.parse(e);const n={};for(const[e,s]of Object.entries(t)){if(typeof e!=="string"||typeof s!=="string"){throw new SyntaxError(`env_vars_file must contain only KEY: VALUE strings. Error parsing key ${e} of type ${typeof e} with value ${s} of type ${typeof s}`)}n[e.trim()]=s.trim()}return n}t.parseKVYAML=parseKVYAML;function parseKVStringAndFile(e,t){e=(e||"").trim();t=(t||"").trim();let n={};if(t){const e=parseKVFile(t);n=Object.assign(Object.assign({},n),e)}if(e){const t=parseKVString(e);n=Object.assign(Object.assign({},n),t)}return n}t.parseKVStringAndFile=parseKVStringAndFile},9497:function(e,t,n){var s=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.inParallel=void 0;const i=n(2037);function inParallel(e,t,n){return s(this,void 0,void 0,(function*(){const r=Math.min((n===null||n===void 0?void 0:n.concurrency)||(0,i.cpus)().length-1);if(r<1){throw new Error(`concurrency must be at least 1`)}const o=t.map(((e,t)=>({args:e,idx:t})));const a=new Array(t.length);const c=new Array(r).fill(Promise.resolve());const sub=t=>s(this,void 0,void 0,(function*(){const n=o.pop();if(n===undefined){return t}yield t;const s=e.apply(e,n.args);s.then((e=>{a[n.idx]=e}));return sub(s)}));yield Promise.all(c.map(sub));return a}))}t.inParallel=inParallel},5737:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true});t.toPlatformPath=t.toWin32Path=t.toPosixPath=void 0;const s=n(1017);function toPosixPath(e){return e.replace(/[\\]/g,"/")}t.toPosixPath=toPosixPath;function toWin32Path(e){return e.replace(/[/]/g,"\\")}t.toWin32Path=toWin32Path;function toPlatformPath(e){return e.replace(/[/\\]/g,s.sep)}t.toPlatformPath=toPlatformPath},570:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true});t.randomFilepath=t.randomFilename=void 0;const s=n(1017);const i=n(6113);const r=n(2037);function randomFilename(e=12){return(0,i.randomBytes)(e).toString("hex")}t.randomFilename=randomFilename;function randomFilepath(e=(0,r.tmpdir)(),t=12){return(0,s.join)(e,randomFilename(t))}t.randomFilepath=randomFilepath;t["default"]={randomFilename:randomFilename,randomFilepath:randomFilepath}},1043:function(e,t,n){var s=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.withRetries=void 0;const i=n(6976);const r=n(7575);const o=100;function withRetries(e,t){var n;const a=t.retries;const c=typeof(t===null||t===void 0?void 0:t.backoffLimit)!=="undefined"?Math.max(t.backoffLimit,0):undefined;let l=(n=t.backoff)!==null&&n!==void 0?n:o;if(typeof c!=="undefined"){l=Math.min(l,c)}return function(){return s(this,void 0,void 0,(function*(){let n=a+1;let s=l;const o=c;let f=0;let u="unknown";do{try{return yield e()}catch(e){u=(0,i.errorMessage)(e);--n;if(n>0){yield(0,r.sleep)(s);let e=f+s;if(typeof o!=="undefined"){e=Math.min(e,Number(o))}f=s;s=e}}}while(n>0);const d=t.retries+1;const h=d===1?`1 attempt`:`${d} attempts`;throw new Error(`retry function failed after ${h}: ${u}`)}))}}t.withRetries=withRetries},9017:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.clearEnv=t.clearInputs=t.setInputs=t.setInput=void 0;function setInput(e,t){const n=`INPUT_${e.replace(/ /g,"_").toUpperCase()}`;process.env[n]=t}t.setInput=setInput;function setInputs(e){Object.entries(e).forEach((([e,t])=>setInput(e,t)))}t.setInputs=setInputs;function clearInputs(){clearEnv((e=>e.startsWith(`INPUT_`)))}t.clearInputs=clearInputs;function clearEnv(e){Object.keys(process.env).forEach((t=>{if(e(t,process.env[t])){delete process.env[t]}}))}t.clearEnv=clearEnv},7575:function(e,t){var n=this&&this.__awaiter||function(e,t,n,s){function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}return new(n||(n=Promise))((function(n,i){function fulfilled(e){try{step(s.next(e))}catch(e){i(e)}}function rejected(e){try{step(s["throw"](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.sleep=t.parseDuration=void 0;function parseDuration(e){e=(e||"").trim();if(!e){return 0}let t=0;let n="";for(let s=0;s<e.length;s++){const i=e[s];switch(i){case" ":continue;case",":continue;case"s":{t+=+n;n="";break}case"m":{t+=+n*60;n="";break}case"h":{t+=+n*60*60;n="";break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n+=i;break;default:throw new SyntaxError(`Unsupported character "${i}" at position ${s}`)}}if(n){t+=+n}return t}t.parseDuration=parseDuration;function sleep(e=0){return n(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}t.sleep=sleep},596:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.allOf=t.exactlyOneOf=t.presence=void 0;function presence(e){return(e||"").trim()||undefined}t.presence=presence;function exactlyOneOf(...e){e=e||[];let t=false;for(let n=0;n<e.length;n++){if(e[n]){if(t){return false}else{t=true}}}if(!t){return false}return true}t.exactlyOneOf=exactlyOneOf;function allOf(...e){e=e||[];for(let t=0;t<e.length;t++){if(!e[t])return false}return true}t.allOf=allOf},9324:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.pinnedToHeadWarning=t.isPinnedToHead=void 0;function isPinnedToHead(){const e=process.env.GITHUB_ACTION_REF;return e==="master"||e==="main"}t.isPinnedToHead=isPinnedToHead;function pinnedToHeadWarning(e){const t=process.env.GITHUB_ACTION_REF;const n=process.env.GITHUB_ACTION_REPOSITORY;return`${n} is pinned at "${t}". We strongly advise against `+`pinning to "@${t}" as it may be unstable. Please update your `+`GitHub Action YAML from:\n`+`\n`+` uses: '${n}@${t}'\n`+`\n`+`to:\n`+`\n`+` uses: '${n}@${e}'\n`+`\n`+`Alternatively, you can pin to any git tag or git SHA in the repository.`}t.pinnedToHeadWarning=pinnedToHeadWarning},6113:e=>{e.exports=__nccwpck_require__(6113)},7147:e=>{e.exports=__nccwpck_require__(7147)},2037:e=>{e.exports=__nccwpck_require__(2037)},1017:e=>{e.exports=__nccwpck_require__(1017)},4655:e=>{e.exports=__nccwpck_require__(4655)},8109:(e,t,n)=>{var s=n(1399);var i=n(9338);var r=n(2986);var o=n(2289);var a=n(45);function composeCollection(e,t,n,c,l){let f;switch(n.type){case"block-map":{f=r.resolveBlockMap(e,t,n,l);break}case"block-seq":{f=o.resolveBlockSeq(e,t,n,l);break}case"flow-collection":{f=a.resolveFlowCollection(e,t,n,l);break}}if(!c)return f;const u=t.directives.tagName(c.source,(e=>l(c,"TAG_RESOLVE_FAILED",e)));if(!u)return f;const d=f.constructor;if(u==="!"||u===d.tagName){f.tag=d.tagName;return f}const h=s.isMap(f)?"map":"seq";let p=t.schema.tags.find((e=>e.collection===h&&e.tag===u));if(!p){const e=t.schema.knownTags[u];if(e&&e.collection===h){t.schema.tags.push(Object.assign({},e,{default:false}));p=e}else{l(c,"TAG_RESOLVE_FAILED",`Unresolved tag: ${u}`,true);f.tag=u;return f}}const m=p.resolve(f,(e=>l(c,"TAG_RESOLVE_FAILED",e)),t.options);const y=s.isNode(m)?m:new i.Scalar(m);y.range=f.range;y.tag=u;if(p?.format)y.format=p.format;return y}t.composeCollection=composeCollection},5050:(e,t,n)=>{var s=n(42);var i=n(8676);var r=n(1250);var o=n(6985);function composeDoc(e,t,{offset:n,start:a,value:c,end:l},f){const u=Object.assign({_directives:t},e);const d=new s.Document(undefined,u);const h={atRoot:true,directives:d.directives,options:d.options,schema:d.schema};const p=o.resolveProps(a,{indicator:"doc-start",next:c??l?.[0],offset:n,onError:f,startOnNewline:true});if(p.found){d.directives.docStart=true;if(c&&(c.type==="block-map"||c.type==="block-seq")&&!p.hasNewline)f(p.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}d.contents=c?i.composeNode(h,c,p,f):i.composeEmptyNode(h,p.end,a,null,p,f);const m=d.contents.range[2];const y=r.resolveEnd(l,m,false,f);if(y.comment)d.comment=y.comment;d.range=[n,m,y.offset];return d}t.composeDoc=composeDoc},8676:(e,t,n)=>{var s=n(5639);var i=n(8109);var r=n(4766);var o=n(1250);var a=n(8781);const c={composeNode:composeNode,composeEmptyNode:composeEmptyNode};function composeNode(e,t,n,s){const{spaceBefore:o,comment:a,anchor:l,tag:f}=n;let u;let d=true;switch(t.type){case"alias":u=composeAlias(e,t,s);if(l||f)s(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=r.composeScalar(e,t,f,s);if(l)u.anchor=l.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":u=i.composeCollection(c,e,t,f,s);if(l)u.anchor=l.source.substring(1);break;default:{const i=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;s(t,"UNEXPECTED_TOKEN",i);u=composeEmptyNode(e,t.offset,undefined,null,n,s);d=false}}if(l&&u.anchor==="")s(l,"BAD_ALIAS","Anchor cannot be an empty string");if(o)u.spaceBefore=true;if(a){if(t.type==="scalar"&&t.source==="")u.comment=a;else u.commentBefore=a}if(e.options.keepSourceTokens&&d)u.srcToken=t;return u}function composeEmptyNode(e,t,n,s,{spaceBefore:i,comment:o,anchor:c,tag:l,end:f},u){const d={type:"scalar",offset:a.emptyScalarPosition(t,n,s),indent:-1,source:""};const h=r.composeScalar(e,d,l,u);if(c){h.anchor=c.source.substring(1);if(h.anchor==="")u(c,"BAD_ALIAS","Anchor cannot be an empty string")}if(i)h.spaceBefore=true;if(o){h.comment=o;h.range[2]=f}return h}function composeAlias({options:e},{offset:t,source:n,end:i},r){const a=new s.Alias(n.substring(1));if(a.source==="")r(t,"BAD_ALIAS","Alias cannot be an empty string");if(a.source.endsWith(":"))r(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",true);const c=t+n.length;const l=o.resolveEnd(i,c,e.strict,r);a.range=[t,c,l.offset];if(l.comment)a.comment=l.comment;return a}t.composeEmptyNode=composeEmptyNode;t.composeNode=composeNode},4766:(e,t,n)=>{var s=n(1399);var i=n(9338);var r=n(9485);var o=n(7578);function composeScalar(e,t,n,a){const{value:c,type:l,comment:f,range:u}=t.type==="block-scalar"?r.resolveBlockScalar(t,e.options.strict,a):o.resolveFlowScalar(t,e.options.strict,a);const d=n?e.directives.tagName(n.source,(e=>a(n,"TAG_RESOLVE_FAILED",e))):null;const h=n&&d?findScalarTagByName(e.schema,c,d,n,a):t.type==="scalar"?findScalarTagByTest(e,c,t,a):e.schema[s.SCALAR];let p;try{const r=h.resolve(c,(e=>a(n??t,"TAG_RESOLVE_FAILED",e)),e.options);p=s.isScalar(r)?r:new i.Scalar(r)}catch(e){const s=e instanceof Error?e.message:String(e);a(n??t,"TAG_RESOLVE_FAILED",s);p=new i.Scalar(c)}p.range=u;p.source=c;if(l)p.type=l;if(d)p.tag=d;if(h.format)p.format=h.format;if(f)p.comment=f;return p}function findScalarTagByName(e,t,n,i,r){if(n==="!")return e[s.SCALAR];const o=[];for(const t of e.tags){if(!t.collection&&t.tag===n){if(t.default&&t.test)o.push(t);else return t}}for(const e of o)if(e.test?.test(t))return e;const a=e.knownTags[n];if(a&&!a.collection){e.tags.push(Object.assign({},a,{default:false,test:undefined}));return a}r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str");return e[s.SCALAR]}function findScalarTagByTest({directives:e,schema:t},n,i,r){const o=t.tags.find((e=>e.default&&e.test?.test(n)))||t[s.SCALAR];if(t.compat){const a=t.compat.find((e=>e.default&&e.test?.test(n)))??t[s.SCALAR];if(o.tag!==a.tag){const t=e.tagString(o.tag);const n=e.tagString(a.tag);const s=`Value may be parsed as either ${t} or ${n}`;r(i,"TAG_RESOLVE_FAILED",s,true)}}return o}t.composeScalar=composeScalar},9493:(e,t,n)=>{var s=n(5400);var i=n(42);var r=n(4236);var o=n(1399);var a=n(5050);var c=n(1250);function getErrorPos(e){if(typeof e==="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];const{offset:t,source:n}=e;return[t,t+(typeof n==="string"?n.length:1)]}function parsePrelude(e){let t="";let n=false;let s=false;for(let i=0;i<e.length;++i){const r=e[i];switch(r[0]){case"#":t+=(t===""?"":s?"\n\n":"\n")+(r.substring(1)||" ");n=true;s=false;break;case"%":if(e[i+1]?.[0]!=="#")i+=1;n=false;break;default:if(!n)s=true;n=false}}return{comment:t,afterEmptyLine:s}}class Composer{constructor(e={}){this.doc=null;this.atDirectives=false;this.prelude=[];this.errors=[];this.warnings=[];this.onError=(e,t,n,s)=>{const i=getErrorPos(e);if(s)this.warnings.push(new r.YAMLWarning(i,t,n));else this.errors.push(new r.YAMLParseError(i,t,n))};this.directives=new s.Directives({version:e.version||"1.2"});this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:s}=parsePrelude(this.prelude);if(n){const i=e.contents;if(t){e.comment=e.comment?`${e.comment}\n${n}`:n}else if(s||e.directives.docStart||!i){e.commentBefore=n}else if(o.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];if(o.isPair(e))e=e.key;const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){Array.prototype.push.apply(e.errors,this.errors);Array.prototype.push.apply(e.warnings,this.warnings)}else{e.errors=this.errors;e.warnings=this.warnings}this.prelude=[];this.errors=[];this.warnings=[]}streamInfo(){return{comment:parsePrelude(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=false,n=-1){for(const t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){if(process.env.LOG_STREAM)console.dir(e,{depth:null});switch(e.type){case"directive":this.directives.add(e.source,((t,n,s)=>{const i=getErrorPos(e);i[0]+=t;this.onError(i,"BAD_DIRECTIVE",n,s)}));this.prelude.push(e.source);this.atDirectives=true;break;case"document":{const t=a.composeDoc(this.options,this.directives,e,this.onError);if(this.atDirectives&&!t.directives.docStart)this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line");this.decorate(t,false);if(this.doc)yield this.doc;this.doc=t;this.atDirectives=false;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message;const n=new r.YAMLParseError(getErrorPos(e),"UNEXPECTED_TOKEN",t);if(this.atDirectives||!this.doc)this.errors.push(n);else this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const t="Unexpected doc-end without preceding document";this.errors.push(new r.YAMLParseError(getErrorPos(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=true;const t=c.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);this.decorate(this.doc,true);if(t.comment){const e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new r.YAMLParseError(getErrorPos(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=false,t=-1){if(this.doc){this.decorate(this.doc,true);yield this.doc;this.doc=null}else if(e){const e=Object.assign({_directives:this.directives},this.options);const n=new i.Document(undefined,e);if(this.atDirectives)this.onError(t,"MISSING_CHAR","Missing directives-end indicator line");n.range=[0,t,t];this.decorate(n,false);yield n}}}t.Composer=Composer},2986:(e,t,n)=>{var s=n(246);var i=n(6011);var r=n(6985);var o=n(976);var a=n(3669);var c=n(6899);const l="All mapping items must start at the same column";function resolveBlockMap({composeNode:e,composeEmptyNode:t},n,f,u){const d=new i.YAMLMap(n.schema);if(n.atRoot)n.atRoot=false;let h=f.offset;let p=null;for(const i of f.items){const{start:m,key:y,sep:g,value:v}=i;const b=r.resolveProps(m,{indicator:"explicit-key-ind",next:y??g?.[0],offset:h,onError:u,startOnNewline:true});const S=!b.found;if(S){if(y){if(y.type==="block-seq")u(h,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in y&&y.indent!==f.indent)u(h,"BAD_INDENT",l)}if(!b.anchor&&!b.tag&&!g){p=b.end;if(b.comment){if(d.comment)d.comment+="\n"+b.comment;else d.comment=b.comment}continue}if(b.hasNewlineAfterProp||o.containsNewline(y)){u(y??m[m.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}}else if(b.found?.indent!==f.indent){u(h,"BAD_INDENT",l)}const w=b.end;const k=y?e(n,y,b,u):t(n,w,m,null,b,u);if(n.schema.compat)a.flowIndentCheck(f.indent,y,u);if(c.mapIncludes(n,d.items,k))u(w,"DUPLICATE_KEY","Map keys must be unique");const E=r.resolveProps(g??[],{indicator:"map-value-ind",next:v,offset:k.range[2],onError:u,startOnNewline:!y||y.type==="block-scalar"});h=E.end;if(E.found){if(S){if(v?.type==="block-map"&&!E.hasNewline)u(h,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(n.options.strict&&b.start<E.found.offset-1024)u(k.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}const r=v?e(n,v,E,u):t(n,h,g,null,E,u);if(n.schema.compat)a.flowIndentCheck(f.indent,v,u);h=r.range[2];const o=new s.Pair(k,r);if(n.options.keepSourceTokens)o.srcToken=i;d.items.push(o)}else{if(S)u(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(E.comment){if(k.comment)k.comment+="\n"+E.comment;else k.comment=E.comment}const e=new s.Pair(k);if(n.options.keepSourceTokens)e.srcToken=i;d.items.push(e)}}if(p&&p<h)u(p,"IMPOSSIBLE","Map comment with trailing content");d.range=[f.offset,h,p??h];return d}t.resolveBlockMap=resolveBlockMap},9485:(e,t,n)=>{var s=n(9338);function resolveBlockScalar(e,t,n){const i=e.offset;const r=parseBlockScalarHeader(e,t,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};const o=r.mode===">"?s.Scalar.BLOCK_FOLDED:s.Scalar.BLOCK_LITERAL;const a=e.source?splitLines(e.source):[];let c=a.length;for(let e=a.length-1;e>=0;--e){const t=a[e][1];if(t===""||t==="\r")c=e;else break}if(c===0){const t=r.chomp==="+"&&a.length>0?"\n".repeat(Math.max(1,a.length-1)):"";let n=i+r.length;if(e.source)n+=e.source.length;return{value:t,type:o,comment:r.comment,range:[i,n,n]}}let l=e.indent+r.indent;let f=e.offset+r.length;let u=0;for(let e=0;e<c;++e){const[t,s]=a[e];if(s===""||s==="\r"){if(r.indent===0&&t.length>l)l=t.length}else{if(t.length<l){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";n(f+t.length,"MISSING_CHAR",e)}if(r.indent===0)l=t.length;u=e;break}f+=t.length+s.length+1}for(let e=a.length-1;e>=c;--e){if(a[e][0].length>l)c=e+1}let d="";let h="";let p=false;for(let e=0;e<u;++e)d+=a[e][0].slice(l)+"\n";for(let e=u;e<c;++e){let[t,i]=a[e];f+=t.length+i.length+1;const c=i[i.length-1]==="\r";if(c)i=i.slice(0,-1);if(i&&t.length<l){const e=r.indent?"explicit indentation indicator":"first line";const s=`Block scalar lines must not be less indented than their ${e}`;n(f-i.length-(c?2:1),"BAD_INDENT",s);t=""}if(o===s.Scalar.BLOCK_LITERAL){d+=h+t.slice(l)+i;h="\n"}else if(t.length>l||i[0]==="\t"){if(h===" ")h="\n";else if(!p&&h==="\n")h="\n\n";d+=h+t.slice(l)+i;h="\n";p=true}else if(i===""){if(h==="\n")d+="\n";else h="\n"}else{d+=h+i;h=" ";p=false}}switch(r.chomp){case"-":break;case"+":for(let e=c;e<a.length;++e)d+="\n"+a[e][0].slice(l);if(d[d.length-1]!=="\n")d+="\n";break;default:d+="\n"}const m=i+r.length+e.source.length;return{value:d,type:o,comment:r.comment,range:[i,m,m]}}function parseBlockScalarHeader({offset:e,props:t},n,s){if(t[0].type!=="block-scalar-header"){s(t[0],"IMPOSSIBLE","Block scalar header not found");return null}const{source:i}=t[0];const r=i[0];let o=0;let a="";let c=-1;for(let t=1;t<i.length;++t){const n=i[t];if(!a&&(n==="-"||n==="+"))a=n;else{const s=Number(n);if(!o&&s)o=s;else if(c===-1)c=e+t}}if(c!==-1)s(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=false;let f="";let u=i.length;for(let e=1;e<t.length;++e){const i=t[e];switch(i.type){case"space":l=true;case"newline":u+=i.source.length;break;case"comment":if(n&&!l){const e="Comments must be separated from other tokens by white space characters";s(i,"MISSING_CHAR",e)}u+=i.source.length;f=i.source.substring(1);break;case"error":s(i,"UNEXPECTED_TOKEN",i.message);u+=i.source.length;break;default:{const e=`Unexpected token in block scalar header: ${i.type}`;s(i,"UNEXPECTED_TOKEN",e);const t=i.source;if(t&&typeof t==="string")u+=t.length}}}return{mode:r,indent:o,chomp:a,comment:f,length:u}}function splitLines(e){const t=e.split(/\n( *)/);const n=t[0];const s=n.match(/^( *)/);const i=s?.[1]?[s[1],n.slice(s[1].length)]:["",n];const r=[i];for(let e=1;e<t.length;e+=2)r.push([t[e],t[e+1]]);return r}t.resolveBlockScalar=resolveBlockScalar},2289:(e,t,n)=>{var s=n(5161);var i=n(6985);var r=n(3669);function resolveBlockSeq({composeNode:e,composeEmptyNode:t},n,o,a){const c=new s.YAMLSeq(n.schema);if(n.atRoot)n.atRoot=false;let l=o.offset;let f=null;for(const{start:s,value:u}of o.items){const d=i.resolveProps(s,{indicator:"seq-item-ind",next:u,offset:l,onError:a,startOnNewline:true});if(!d.found){if(d.anchor||d.tag||u){if(u&&u.type==="block-seq")a(d.end,"BAD_INDENT","All sequence items must start at the same column");else a(l,"MISSING_CHAR","Sequence item without - indicator")}else{f=d.end;if(d.comment)c.comment=d.comment;continue}}const h=u?e(n,u,d,a):t(n,d.end,s,null,d,a);if(n.schema.compat)r.flowIndentCheck(o.indent,u,a);l=h.range[2];c.items.push(h)}c.range=[o.offset,l,f??l];return c}t.resolveBlockSeq=resolveBlockSeq},1250:(e,t)=>{function resolveEnd(e,t,n,s){let i="";if(e){let r=false;let o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":r=true;break;case"comment":{if(n&&!r)s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";if(!i)i=t;else i+=o+t;o="";break}case"newline":if(i)o+=e;r=true;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}t.resolveEnd=resolveEnd},45:(e,t,n)=>{var s=n(1399);var i=n(246);var r=n(6011);var o=n(5161);var a=n(1250);var c=n(6985);var l=n(976);var f=n(6899);const u="Block collections are not allowed within flow collections";const isBlock=e=>e&&(e.type==="block-map"||e.type==="block-seq");function resolveFlowCollection({composeNode:e,composeEmptyNode:t},n,d,h){const p=d.start.source==="{";const m=p?"flow map":"flow sequence";const y=p?new r.YAMLMap(n.schema):new o.YAMLSeq(n.schema);y.flow=true;const g=n.atRoot;if(g)n.atRoot=false;let v=d.offset+d.start.source.length;for(let o=0;o<d.items.length;++o){const a=d.items[o];const{start:g,key:b,sep:S,value:w}=a;const k=c.resolveProps(g,{flow:m,indicator:"explicit-key-ind",next:b??S?.[0],offset:v,onError:h,startOnNewline:false});if(!k.found){if(!k.anchor&&!k.tag&&!S&&!w){if(o===0&&k.comma)h(k.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${m}`);else if(o<d.items.length-1)h(k.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${m}`);if(k.comment){if(y.comment)y.comment+="\n"+k.comment;else y.comment=k.comment}v=k.end;continue}if(!p&&n.options.strict&&l.containsNewline(b))h(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(o===0){if(k.comma)h(k.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${m}`)}else{if(!k.comma)h(k.start,"MISSING_CHAR",`Missing , between ${m} items`);if(k.comment){let e="";e:for(const t of g){switch(t.type){case"comma":case"space":break;case"comment":e=t.source.substring(1);break e;default:break e}}if(e){let t=y.items[y.items.length-1];if(s.isPair(t))t=t.value??t.key;if(t.comment)t.comment+="\n"+e;else t.comment=e;k.comment=k.comment.substring(e.length+1)}}}if(!p&&!S&&!k.found){const s=w?e(n,w,k,h):t(n,k.end,S,null,k,h);y.items.push(s);v=s.range[2];if(isBlock(w))h(s.range,"BLOCK_IN_FLOW",u)}else{const s=k.end;const o=b?e(n,b,k,h):t(n,s,g,null,k,h);if(isBlock(b))h(o.range,"BLOCK_IN_FLOW",u);const l=c.resolveProps(S??[],{flow:m,indicator:"map-value-ind",next:w,offset:o.range[2],onError:h,startOnNewline:false});if(l.found){if(!p&&!k.found&&n.options.strict){if(S)for(const e of S){if(e===l.found)break;if(e.type==="newline"){h(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(k.start<l.found.offset-1024)h(l.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(w){if("source"in w&&w.source&&w.source[0]===":")h(w,"MISSING_CHAR",`Missing space after : in ${m}`);else h(l.start,"MISSING_CHAR",`Missing , or : between ${m} items`)}const d=w?e(n,w,l,h):l.found?t(n,l.end,S,null,l,h):null;if(d){if(isBlock(w))h(d.range,"BLOCK_IN_FLOW",u)}else if(l.comment){if(o.comment)o.comment+="\n"+l.comment;else o.comment=l.comment}const E=new i.Pair(o,d);if(n.options.keepSourceTokens)E.srcToken=a;if(p){const e=y;if(f.mapIncludes(n,e.items,o))h(s,"DUPLICATE_KEY","Map keys must be unique");e.items.push(E)}else{const e=new r.YAMLMap(n.schema);e.flow=true;e.items.push(E);y.items.push(e)}v=d?d.range[2]:l.end}}const b=p?"}":"]";const[S,...w]=d.end;let k=v;if(S&&S.source===b)k=S.offset+S.source.length;else{const e=m[0].toUpperCase()+m.substring(1);const t=g?`${e} must end with a ${b}`:`${e} in block collection must be sufficiently indented and end with a ${b}`;h(v,g?"MISSING_CHAR":"BAD_INDENT",t);if(S&&S.source.length!==1)w.unshift(S)}if(w.length>0){const e=a.resolveEnd(w,k,n.options.strict,h);if(e.comment){if(y.comment)y.comment+="\n"+e.comment;else y.comment=e.comment}y.range=[d.offset,k,e.offset]}else{y.range=[d.offset,k,k]}return y}t.resolveFlowCollection=resolveFlowCollection},7578:(e,t,n)=>{var s=n(9338);var i=n(1250);function resolveFlowScalar(e,t,n){const{offset:r,type:o,source:a,end:c}=e;let l;let f;const _onError=(e,t,s)=>n(r+e,t,s);switch(o){case"scalar":l=s.Scalar.PLAIN;f=plainValue(a,_onError);break;case"single-quoted-scalar":l=s.Scalar.QUOTE_SINGLE;f=singleQuotedValue(a,_onError);break;case"double-quoted-scalar":l=s.Scalar.QUOTE_DOUBLE;f=doubleQuotedValue(a,_onError);break;default:n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`);return{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}const u=r+a.length;const d=i.resolveEnd(c,u,t,n);return{value:f,type:l,comment:d.comment,range:[r,u,d.offset]}}function plainValue(e,t){let n="";switch(e[0]){case"\t":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}if(n)t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`);return foldLines(e)}function singleQuotedValue(e,t){if(e[e.length-1]!=="'"||e.length===1)t(e.length,"MISSING_CHAR","Missing closing 'quote");return foldLines(e.slice(1,-1)).replace(/''/g,"'")}function foldLines(e){let t,n;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy");n=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch(e){t=/(.*?)[ \t]*\r?\n/ys;n=/[ \t]*(.*?)[ \t]*\r?\n/ys}let s=t.exec(e);if(!s)return e;let i=s[1];let r=" ";let o=t.lastIndex;n.lastIndex=o;while(s=n.exec(e)){if(s[1]===""){if(r==="\n")i+=r;else r="\n"}else{i+=r+s[1];r=" "}o=n.lastIndex}const a=/[ \t]*(.*)/ys;a.lastIndex=o;s=a.exec(e);return i+r+(s?.[1]??"")}function doubleQuotedValue(e,t){let n="";for(let s=1;s<e.length-1;++s){const i=e[s];if(i==="\r"&&e[s+1]==="\n")continue;if(i==="\n"){const{fold:t,offset:i}=foldNewline(e,s);n+=t;s=i}else if(i==="\\"){let i=e[++s];const o=r[i];if(o)n+=o;else if(i==="\n"){i=e[s+1];while(i===" "||i==="\t")i=e[++s+1]}else if(i==="\r"&&e[s+1]==="\n"){i=e[++s+1];while(i===" "||i==="\t")i=e[++s+1]}else if(i==="x"||i==="u"||i==="U"){const r={x:2,u:4,U:8}[i];n+=parseCharCode(e,s+1,r,t);s+=r}else{const i=e.substr(s-1,2);t(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`);n+=i}}else if(i===" "||i==="\t"){const t=s;let r=e[s+1];while(r===" "||r==="\t")r=e[++s+1];if(r!=="\n"&&!(r==="\r"&&e[s+2]==="\n"))n+=s>t?e.slice(t,s+1):i}else{n+=i}}if(e[e.length-1]!=='"'||e.length===1)t(e.length,"MISSING_CHAR",'Missing closing "quote');return n}function foldNewline(e,t){let n="";let s=e[t+1];while(s===" "||s==="\t"||s==="\n"||s==="\r"){if(s==="\r"&&e[t+2]!=="\n")break;if(s==="\n")n+="\n";t+=1;s=e[t+1]}if(!n)n=" ";return{fold:n,offset:t}}const r={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function parseCharCode(e,t,n,s){const i=e.substr(t,n);const r=i.length===n&&/^[0-9a-fA-F]+$/.test(i);const o=r?parseInt(i,16):NaN;if(isNaN(o)){const i=e.substr(t-2,n+2);s(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`);return i}return String.fromCodePoint(o)}t.resolveFlowScalar=resolveFlowScalar},6985:(e,t)=>{function resolveProps(e,{flow:t,indicator:n,next:s,offset:i,onError:r,startOnNewline:o}){let a=false;let c=o;let l=o;let f="";let u="";let d=false;let h=false;let p=false;let m=null;let y=null;let g=null;let v=null;let b=null;for(const s of e){if(p){if(s.type!=="space"&&s.type!=="newline"&&s.type!=="comma")r(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");p=false}switch(s.type){case"space":if(!t&&c&&n!=="doc-start"&&s.source[0]==="\t")r(s,"TAB_AS_INDENT","Tabs are not allowed as indentation");l=true;break;case"comment":{if(!l)r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=s.source.substring(1)||" ";if(!f)f=e;else f+=u+e;u="";c=false;break}case"newline":if(c){if(f)f+=s.source;else a=true}else u+=s.source;c=true;d=true;if(m||y)h=true;l=true;break;case"anchor":if(m)r(s,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(s.source.endsWith(":"))r(s.offset+s.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",true);m=s;if(b===null)b=s.offset;c=false;l=false;p=true;break;case"tag":{if(y)r(s,"MULTIPLE_TAGS","A node can have at most one tag");y=s;if(b===null)b=s.offset;c=false;l=false;p=true;break}case n:if(m||y)r(s,"BAD_PROP_ORDER",`Anchors and tags must be after the ${s.source} indicator`);if(v)r(s,"UNEXPECTED_TOKEN",`Unexpected ${s.source} in ${t??"collection"}`);v=s;c=false;l=false;break;case"comma":if(t){if(g)r(s,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`);g=s;c=false;l=false;break}default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${s.type} token`);c=false;l=false}}const S=e[e.length-1];const w=S?S.offset+S.source.length:i;if(p&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!==""))r(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");return{comma:g,found:v,spaceBefore:a,comment:f,hasNewline:d,hasNewlineAfterProp:h,anchor:m,tag:y,end:w,start:b??w}}t.resolveProps=resolveProps},976:(e,t)=>{function containsNewline(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes("\n"))return true;if(e.end)for(const t of e.end)if(t.type==="newline")return true;return false;case"flow-collection":for(const t of e.items){for(const e of t.start)if(e.type==="newline")return true;if(t.sep)for(const e of t.sep)if(e.type==="newline")return true;if(containsNewline(t.key)||containsNewline(t.value))return true}return false;default:return true}}t.containsNewline=containsNewline},8781:(e,t)=>{function emptyScalarPosition(e,t,n){if(t){if(n===null)n=t.length;for(let s=n-1;s>=0;--s){let n=t[s];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}n=t[++s];while(n?.type==="space"){e+=n.source.length;n=t[++s]}break}}return e}t.emptyScalarPosition=emptyScalarPosition},3669:(e,t,n)=>{var s=n(976);function flowIndentCheck(e,t,n){if(t?.type==="flow-collection"){const i=t.end[0];if(i.indent===e&&(i.source==="]"||i.source==="}")&&s.containsNewline(t)){const e="Flow end indicator should be more indented than parent";n(i,"BAD_INDENT",e,true)}}}t.flowIndentCheck=flowIndentCheck},6899:(e,t,n)=>{var s=n(1399);function mapIncludes(e,t,n){const{uniqueKeys:i}=e.options;if(i===false)return false;const r=typeof i==="function"?i:(t,n)=>t===n||s.isScalar(t)&&s.isScalar(n)&&t.value===n.value&&!(t.value==="<<"&&e.schema.merge);return t.some((e=>r(e.key,n)))}t.mapIncludes=mapIncludes},42:(e,t,n)=>{var s=n(5639);var i=n(3466);var r=n(1399);var o=n(246);var a=n(2463);var c=n(6831);var l=n(8409);var f=n(5225);var u=n(8459);var d=n(3412);var h=n(9652);var p=n(5400);class Document{constructor(e,t,n){this.commentBefore=null;this.comment=null;this.errors=[];this.warnings=[];Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let s=null;if(typeof t==="function"||Array.isArray(t)){s=t}else if(n===undefined&&t){n=t;t=undefined}const i=Object.assign({intAsBigInt:false,keepSourceTokens:false,logLevel:"warn",prettyErrors:true,strict:true,uniqueKeys:true,version:"1.2"},n);this.options=i;let{version:o}=i;if(n?._directives){this.directives=n._directives.atDocument();if(this.directives.yaml.explicit)o=this.directives.yaml.version}else this.directives=new p.Directives({version:o});this.setSchema(o,n);if(e===undefined)this.contents=null;else{this.contents=this.createNode(e,s,n)}}clone(){const e=Object.create(Document.prototype,{[r.NODE_TYPE]:{value:r.DOC}});e.commentBefore=this.commentBefore;e.comment=this.comment;e.errors=this.errors.slice();e.warnings=this.warnings.slice();e.options=Object.assign({},this.options);if(this.directives)e.directives=this.directives.clone();e.schema=this.schema.clone();e.contents=r.isNode(this.contents)?this.contents.clone(e.schema):this.contents;if(this.range)e.range=this.range.slice();return e}add(e){if(assertCollection(this.contents))this.contents.add(e)}addIn(e,t){if(assertCollection(this.contents))this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=u.anchorNames(this);e.anchor=!t||n.has(t)?u.findNewAnchor(t||"a",n):t}return new s.Alias(e.anchor)}createNode(e,t,n){let s=undefined;if(typeof t==="function"){e=t.call({"":e},"",e);s=t}else if(Array.isArray(t)){const keyToStr=e=>typeof e==="number"||e instanceof String||e instanceof Number;const e=t.filter(keyToStr).map(String);if(e.length>0)t=t.concat(e);s=t}else if(n===undefined&&t){n=t;t=undefined}const{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=n??{};const{onAnchor:d,setAnchors:p,sourceObjects:m}=u.createNodeAnchors(this,o||"a");const y={aliasDuplicateObjects:i??true,keepUndefined:c??false,onAnchor:d,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:m};const g=h.createNode(e,f,y);if(a&&r.isCollection(g))g.flow=true;p();return g}createPair(e,t,n={}){const s=this.createNode(e,null,n);const i=this.createNode(t,null,n);return new o.Pair(s,i)}delete(e){return assertCollection(this.contents)?this.contents.delete(e):false}deleteIn(e){if(i.isEmptyPath(e)){if(this.contents==null)return false;this.contents=null;return true}return assertCollection(this.contents)?this.contents.deleteIn(e):false}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):undefined}getIn(e,t){if(i.isEmptyPath(e))return!t&&r.isScalar(this.contents)?this.contents.value:this.contents;return r.isCollection(this.contents)?this.contents.getIn(e,t):undefined}has(e){return r.isCollection(this.contents)?this.contents.has(e):false}hasIn(e){if(i.isEmptyPath(e))return this.contents!==undefined;return r.isCollection(this.contents)?this.contents.hasIn(e):false}set(e,t){if(this.contents==null){this.contents=i.collectionFromPath(this.schema,[e],t)}else if(assertCollection(this.contents)){this.contents.set(e,t)}}setIn(e,t){if(i.isEmptyPath(e))this.contents=t;else if(this.contents==null){this.contents=i.collectionFromPath(this.schema,Array.from(e),t)}else if(assertCollection(this.contents)){this.contents.setIn(e,t)}}setSchema(e,t={}){if(typeof e==="number")e=String(e);let n;switch(e){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new p.Directives({version:"1.1"});n={merge:true,resolveKnownTags:false,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=e;else this.directives=new p.Directives({version:e});n={merge:false,resolveKnownTags:true,schema:"core"};break;case null:if(this.directives)delete this.directives;n=null;break;default:{const t=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new c.Schema(Object.assign(n,t));else throw new Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:s,onAnchor:i,reviver:r}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===true,mapKeyWarned:false,maxAliasCount:typeof s==="number"?s:100,stringify:l.stringify};const c=a.toJS(this.contents,t??"",o);if(typeof i==="function")for(const{count:e,res:t}of o.anchors.values())i(t,e);return typeof r==="function"?d.applyReviver(r,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:true,jsonArg:e,mapAsMap:false,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return f.stringifyDocument(this,e)}}function assertCollection(e){if(r.isCollection(e))return true;throw new Error("Expected a YAML collection as document contents")}t.Document=Document},8459:(e,t,n)=>{var s=n(1399);var i=n(6796);function anchorIsValid(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=JSON.stringify(e);const n=`Anchor must not contain whitespace or control characters: ${t}`;throw new Error(n)}return true}function anchorNames(e){const t=new Set;i.visit(e,{Value(e,n){if(n.anchor)t.add(n.anchor)}});return t}function findNewAnchor(e,t){for(let n=1;true;++n){const s=`${e}${n}`;if(!t.has(s))return s}}function createNodeAnchors(e,t){const n=[];const i=new Map;let r=null;return{onAnchor:s=>{n.push(s);if(!r)r=anchorNames(e);const i=findNewAnchor(t,r);r.add(i);return i},setAnchors:()=>{for(const e of n){const t=i.get(e);if(typeof t==="object"&&t.anchor&&(s.isScalar(t.node)||s.isCollection(t.node))){t.node.anchor=t.anchor}else{const t=new Error("Failed to resolve repeated object (this should not happen)");t.source=e;throw t}}},sourceObjects:i}}t.anchorIsValid=anchorIsValid;t.anchorNames=anchorNames;t.createNodeAnchors=createNodeAnchors;t.findNewAnchor=findNewAnchor},3412:(e,t)=>{function applyReviver(e,t,n,s){if(s&&typeof s==="object"){if(Array.isArray(s)){for(let t=0,n=s.length;t<n;++t){const n=s[t];const i=applyReviver(e,s,String(t),n);if(i===undefined)delete s[t];else if(i!==n)s[t]=i}}else if(s instanceof Map){for(const t of Array.from(s.keys())){const n=s.get(t);const i=applyReviver(e,s,t,n);if(i===undefined)s.delete(t);else if(i!==n)s.set(t,i)}}else if(s instanceof Set){for(const t of Array.from(s)){const n=applyReviver(e,s,t,t);if(n===undefined)s.delete(t);else if(n!==t){s.delete(t);s.add(n)}}}else{for(const[t,n]of Object.entries(s)){const i=applyReviver(e,s,t,n);if(i===undefined)delete s[t];else if(i!==n)s[t]=i}}}return e.call(t,n,s)}t.applyReviver=applyReviver},9652:(e,t,n)=>{var s=n(5639);var i=n(1399);var r=n(9338);const o="tag:yaml.org,2002:";function findTagObject(e,t,n){if(t){const e=n.filter((e=>e.tag===t));const s=e.find((e=>!e.format))??e[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find((t=>t.identify?.(e)&&!t.format))}function createNode(e,t,n){if(i.isDocument(e))e=e.contents;if(i.isNode(e))return e;if(i.isPair(e)){const t=n.schema[i.MAP].createNode?.(n.schema,null,n);t.items.push(e);return t}if(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt!=="undefined"&&e instanceof BigInt){e=e.valueOf()}const{aliasDuplicateObjects:a,onAnchor:c,onTagObj:l,schema:f,sourceObjects:u}=n;let d=undefined;if(a&&e&&typeof e==="object"){d=u.get(e);if(d){if(!d.anchor)d.anchor=c(e);return new s.Alias(d.anchor)}else{d={anchor:null,node:null};u.set(e,d)}}if(t?.startsWith("!!"))t=o+t.slice(2);let h=findTagObject(e,t,f.tags);if(!h){if(e&&typeof e.toJSON==="function"){e=e.toJSON()}if(!e||typeof e!=="object"){const t=new r.Scalar(e);if(d)d.node=t;return t}h=e instanceof Map?f[i.MAP]:Symbol.iterator in Object(e)?f[i.SEQ]:f[i.MAP]}if(l){l(h);delete n.onTagObj}const p=h?.createNode?h.createNode(n.schema,e,n):new r.Scalar(e);if(t)p.tag=t;if(d)d.node=p;return p}t.createNode=createNode},5400:(e,t,n)=>{var s=n(1399);var i=n(6796);const r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"};const escapeTagName=e=>e.replace(/[!,[\]{}]/g,(e=>r[e]));class Directives{constructor(e,t){this.docStart=null;this.docEnd=false;this.yaml=Object.assign({},Directives.defaultYaml,e);this.tags=Object.assign({},Directives.defaultTags,t)}clone(){const e=new Directives(this.yaml,this.tags);e.docStart=this.docStart;return e}atDocument(){const e=new Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=true;break;case"1.2":this.atNextDocument=false;this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.2"};this.tags=Object.assign({},Directives.defaultTags);break}return e}add(e,t){if(this.atNextDocument){this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.1"};this.tags=Object.assign({},Directives.defaultTags);this.atNextDocument=false}const n=e.trim().split(/[ \t]+/);const s=n.shift();switch(s){case"%TAG":{if(n.length!==2){t(0,"%TAG directive should contain exactly two parts");if(n.length<2)return false}const[e,s]=n;this.tags[e]=s;return true}case"%YAML":{this.yaml.explicit=true;if(n.length!==1){t(0,"%YAML directive should contain exactly one part");return false}const[e]=n;if(e==="1.1"||e==="1.2"){this.yaml.version=e;return true}else{const n=/^\d+\.\d+$/.test(e);t(6,`Unsupported YAML version ${e}`,n);return false}}default:t(0,`Unknown directive ${s}`,true);return false}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!"){t(`Not a valid tag: ${e}`);return null}if(e[1]==="<"){const n=e.slice(2,-1);if(n==="!"||n==="!!"){t(`Verbatim tags aren't resolved, so ${e} is invalid.`);return null}if(e[e.length-1]!==">")t("Verbatim tags must end with a >");return n}const[,n,s]=e.match(/^(.*!)([^!]*)$/);if(!s)t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)return i+decodeURIComponent(s);if(n==="!")return e;t(`Could not resolve tag: ${e}`);return null}tagString(e){for(const[t,n]of Object.entries(this.tags)){if(e.startsWith(n))return t+escapeTagName(e.substring(n.length))}return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[];const n=Object.entries(this.tags);let r;if(e&&n.length>0&&s.isNode(e.contents)){const t={};i.visit(e.contents,((e,n)=>{if(s.isNode(n)&&n.tag)t[n.tag]=true}));r=Object.keys(t)}else r=[];for(const[s,i]of n){if(s==="!!"&&i==="tag:yaml.org,2002:")continue;if(!e||r.some((e=>e.startsWith(i))))t.push(`%TAG ${s} ${i}`)}return t.join("\n")}}Directives.defaultYaml={explicit:false,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};t.Directives=Directives},4236:(e,t)=>{class YAMLError extends Error{constructor(e,t,n,s){super();this.name=e;this.code=n;this.message=s;this.pos=t}}class YAMLParseError extends YAMLError{constructor(e,t,n){super("YAMLParseError",e,t,n)}}class YAMLWarning extends YAMLError{constructor(e,t,n){super("YAMLWarning",e,t,n)}}const prettifyError=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map((e=>t.linePos(e)));const{line:s,col:i}=n.linePos[0];n.message+=` at line ${s}, column ${i}`;let r=i-1;let o=e.substring(t.lineStarts[s-1],t.lineStarts[s]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const e=Math.min(r-39,o.length-79);o="…"+o.substring(e);r-=e-1}if(o.length>80)o=o.substring(0,79)+"…";if(s>1&&/^ *$/.test(o.substring(0,r))){let n=e.substring(t.lineStarts[s-2],t.lineStarts[s-1]);if(n.length>80)n=n.substring(0,79)+"…\n";o=n+o}if(/[^ ]/.test(o)){let e=1;const t=n.linePos[1];if(t&&t.line===s&&t.col>i){e=Math.min(t.col-i,80-r)}const a=" ".repeat(r)+"^".repeat(e);n.message+=`:\n\n${o}\n${a}\n`}};t.YAMLError=YAMLError;t.YAMLParseError=YAMLParseError;t.YAMLWarning=YAMLWarning;t.prettifyError=prettifyError},4083:(e,t,n)=>{var s=n(9493);var i=n(42);var r=n(6831);var o=n(4236);var a=n(5639);var c=n(1399);var l=n(246);var f=n(9338);var u=n(6011);var d=n(5161);var h=n(9169);var p=n(5976);var m=n(1929);var y=n(3328);var g=n(8649);var v=n(6796);t.Composer=s.Composer;t.Document=i.Document;t.Schema=r.Schema;t.YAMLError=o.YAMLError;t.YAMLParseError=o.YAMLParseError;t.YAMLWarning=o.YAMLWarning;t.Alias=a.Alias;t.isAlias=c.isAlias;t.isCollection=c.isCollection;t.isDocument=c.isDocument;t.isMap=c.isMap;t.isNode=c.isNode;t.isPair=c.isPair;t.isScalar=c.isScalar;t.isSeq=c.isSeq;t.Pair=l.Pair;t.Scalar=f.Scalar;t.YAMLMap=u.YAMLMap;t.YAMLSeq=d.YAMLSeq;t.CST=h;t.Lexer=p.Lexer;t.LineCounter=m.LineCounter;t.Parser=y.Parser;t.parse=g.parse;t.parseAllDocuments=g.parseAllDocuments;t.parseDocument=g.parseDocument;t.stringify=g.stringify;t.visit=v.visit;t.visitAsync=v.visitAsync},6909:(e,t)=>{function debug(e,...t){if(e==="debug")console.log(...t)}function warn(e,t){if(e==="debug"||e==="warn"){if(typeof process!=="undefined"&&process.emitWarning)process.emitWarning(t);else console.warn(t)}}t.debug=debug;t.warn=warn},5639:(e,t,n)=>{var s=n(8459);var i=n(6796);var r=n(1399);class Alias extends r.NodeBase{constructor(e){super(r.ALIAS);this.source=e;Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t=undefined;i.visit(e,{Node:(e,n)=>{if(n===this)return i.visit.BREAK;if(n.anchor===this.source)t=n}});return t}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:s,maxAliasCount:i}=t;const r=this.resolve(s);if(!r){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}const o=n.get(r);if(!o||o.res===undefined){const e="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(e)}if(i>=0){o.count+=1;if(o.aliasCount===0)o.aliasCount=getAliasCount(s,r,n);if(o.count*o.aliasCount>i){const e="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(e)}}return o.res}toString(e,t,n){const i=`*${this.source}`;if(e){s.anchorIsValid(this.source);if(e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(e)}if(e.implicitKey)return`${i} `}return i}}function getAliasCount(e,t,n){if(r.isAlias(t)){const s=t.resolve(e);const i=n&&s&&n.get(s);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let s=0;for(const i of t.items){const t=getAliasCount(e,i,n);if(t>s)s=t}return s}else if(r.isPair(t)){const s=getAliasCount(e,t.key,n);const i=getAliasCount(e,t.value,n);return Math.max(s,i)}return 1}t.Alias=Alias},3466:(e,t,n)=>{var s=n(9652);var i=n(1399);function collectionFromPath(e,t,n){let i=n;for(let e=t.length-1;e>=0;--e){const n=t[e];if(typeof n==="number"&&Number.isInteger(n)&&n>=0){const e=[];e[n]=i;i=e}else{i=new Map([[n,i]])}}return s.createNode(i,undefined,{aliasDuplicateObjects:false,keepUndefined:false,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}const isEmptyPath=e=>e==null||typeof e==="object"&&!!e[Symbol.iterator]().next().done;class Collection extends i.NodeBase{constructor(e,t){super(e);Object.defineProperty(this,"schema",{value:t,configurable:true,enumerable:false,writable:true})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(e)t.schema=e;t.items=t.items.map((t=>i.isNode(t)||i.isPair(t)?t.clone(e):t));if(this.range)t.range=this.range.slice();return t}addIn(e,t){if(isEmptyPath(e))this.add(t);else{const[n,...s]=e;const r=this.get(n,true);if(i.isCollection(r))r.addIn(s,t);else if(r===undefined&&this.schema)this.set(n,collectionFromPath(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const s=this.get(t,true);if(i.isCollection(s))return s.deleteIn(n);else throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...s]=e;const r=this.get(n,true);if(s.length===0)return!t&&i.isScalar(r)?r.value:r;else return i.isCollection(r)?r.getIn(s,t):undefined}hasAllNullValues(e){return this.items.every((t=>{if(!i.isPair(t))return false;const n=t.value;return n==null||e&&i.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag}))}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const s=this.get(t,true);return i.isCollection(s)?s.hasIn(n):false}setIn(e,t){const[n,...s]=e;if(s.length===0){this.set(n,t)}else{const e=this.get(n,true);if(i.isCollection(e))e.setIn(s,t);else if(e===undefined&&this.schema)this.set(n,collectionFromPath(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}}Collection.maxFlowStringSingleLineLength=60;t.Collection=Collection;t.collectionFromPath=collectionFromPath;t.isEmptyPath=isEmptyPath},1399:(e,t)=>{const n=Symbol.for("yaml.alias");const s=Symbol.for("yaml.document");const i=Symbol.for("yaml.map");const r=Symbol.for("yaml.pair");const o=Symbol.for("yaml.scalar");const a=Symbol.for("yaml.seq");const c=Symbol.for("yaml.node.type");const isAlias=e=>!!e&&typeof e==="object"&&e[c]===n;const isDocument=e=>!!e&&typeof e==="object"&&e[c]===s;const isMap=e=>!!e&&typeof e==="object"&&e[c]===i;const isPair=e=>!!e&&typeof e==="object"&&e[c]===r;const isScalar=e=>!!e&&typeof e==="object"&&e[c]===o;const isSeq=e=>!!e&&typeof e==="object"&&e[c]===a;function isCollection(e){if(e&&typeof e==="object")switch(e[c]){case i:case a:return true}return false}function isNode(e){if(e&&typeof e==="object")switch(e[c]){case n:case i:case o:case a:return true}return false}const hasAnchor=e=>(isScalar(e)||isCollection(e))&&!!e.anchor;class NodeBase{constructor(e){Object.defineProperty(this,c,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)e.range=this.range.slice();return e}}t.ALIAS=n;t.DOC=s;t.MAP=i;t.NODE_TYPE=c;t.NodeBase=NodeBase;t.PAIR=r;t.SCALAR=o;t.SEQ=a;t.hasAnchor=hasAnchor;t.isAlias=isAlias;t.isCollection=isCollection;t.isDocument=isDocument;t.isMap=isMap;t.isNode=isNode;t.isPair=isPair;t.isScalar=isScalar;t.isSeq=isSeq},246:(e,t,n)=>{var s=n(9652);var i=n(4875);var r=n(4676);var o=n(1399);function createPair(e,t,n){const i=s.createNode(e,undefined,n);const r=s.createNode(t,undefined,n);return new Pair(i,r)}class Pair{constructor(e,t=null){Object.defineProperty(this,o.NODE_TYPE,{value:o.PAIR});this.key=e;this.value=t}clone(e){let{key:t,value:n}=this;if(o.isNode(t))t=t.clone(e);if(o.isNode(n))n=n.clone(e);return new Pair(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?i.stringifyPair(this,e,t,n):JSON.stringify(this)}}t.Pair=Pair;t.createPair=createPair},9338:(e,t,n)=>{var s=n(1399);var i=n(2463);const isScalarValue=e=>!e||typeof e!=="function"&&typeof e!=="object";class Scalar extends s.NodeBase{constructor(e){super(s.SCALAR);this.value=e}toJSON(e,t){return t?.keep?this.value:i.toJS(this.value,e,t)}toString(){return String(this.value)}}Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";t.Scalar=Scalar;t.isScalarValue=isScalarValue},6011:(e,t,n)=>{var s=n(2466);var i=n(4676);var r=n(3466);var o=n(1399);var a=n(246);var c=n(9338);function findPair(e,t){const n=o.isScalar(t)?t.value:t;for(const s of e){if(o.isPair(s)){if(s.key===t||s.key===n)return s;if(o.isScalar(s.key)&&s.key.value===n)return s}}return undefined}class YAMLMap extends r.Collection{constructor(e){super(o.MAP,e);this.items=[]}static get tagName(){return"tag:yaml.org,2002:map"}add(e,t){let n;if(o.isPair(e))n=e;else if(!e||typeof e!=="object"||!("key"in e)){n=new a.Pair(e,e?.value)}else n=new a.Pair(e.key,e.value);const s=findPair(this.items,n.key);const i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);if(o.isScalar(s.value)&&c.isScalarValue(n.value))s.value.value=n.value;else s.value=n.value}else if(i){const e=this.items.findIndex((e=>i(n,e)<0));if(e===-1)this.items.push(n);else this.items.splice(e,0,n)}else{this.items.push(n)}}delete(e){const t=findPair(this.items,e);if(!t)return false;const n=this.items.splice(this.items.indexOf(t),1);return n.length>0}get(e,t){const n=findPair(this.items,e);const s=n?.value;return(!t&&o.isScalar(s)?s.value:s)??undefined}has(e){return!!findPair(this.items,e)}set(e,t){this.add(new a.Pair(e,t),true)}toJSON(e,t,n){const s=n?new n:t?.mapAsMap?new Map:{};if(t?.onCreate)t.onCreate(s);for(const e of this.items)i.addPairToJSMap(t,s,e);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(const e of this.items){if(!o.isPair(e))throw new Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`)}if(!e.allNullValues&&this.hasAllNullValues(false))e=Object.assign({},e,{allNullValues:true});return s.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}t.YAMLMap=YAMLMap;t.findPair=findPair},5161:(e,t,n)=>{var s=n(2466);var i=n(3466);var r=n(1399);var o=n(9338);var a=n(2463);class YAMLSeq extends i.Collection{constructor(e){super(r.SEQ,e);this.items=[]}static get tagName(){return"tag:yaml.org,2002:seq"}add(e){this.items.push(e)}delete(e){const t=asItemIndex(e);if(typeof t!=="number")return false;const n=this.items.splice(t,1);return n.length>0}get(e,t){const n=asItemIndex(e);if(typeof n!=="number")return undefined;const s=this.items[n];return!t&&r.isScalar(s)?s.value:s}has(e){const t=asItemIndex(e);return typeof t==="number"&&t<this.items.length}set(e,t){const n=asItemIndex(e);if(typeof n!=="number")throw new Error(`Expected a valid index, not ${e}.`);const s=this.items[n];if(r.isScalar(s)&&o.isScalarValue(t))s.value=t;else this.items[n]=t}toJSON(e,t){const n=[];if(t?.onCreate)t.onCreate(n);let s=0;for(const e of this.items)n.push(a.toJS(e,String(s++),t));return n}toString(e,t,n){if(!e)return JSON.stringify(this);return s.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t})}}function asItemIndex(e){let t=r.isScalar(e)?e.value:e;if(t&&typeof t==="string")t=Number(t);return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:null}t.YAMLSeq=YAMLSeq},4676:(e,t,n)=>{var s=n(6909);var i=n(8409);var r=n(1399);var o=n(9338);var a=n(2463);const c="<<";function addPairToJSMap(e,t,{key:n,value:s}){if(e?.doc.schema.merge&&isMergeKey(n)){s=r.isAlias(s)?s.resolve(e.doc):s;if(r.isSeq(s))for(const n of s.items)mergeToJSMap(e,t,n);else if(Array.isArray(s))for(const n of s)mergeToJSMap(e,t,n);else mergeToJSMap(e,t,s)}else{const i=a.toJS(n,"",e);if(t instanceof Map){t.set(i,a.toJS(s,i,e))}else if(t instanceof Set){t.add(i)}else{const r=stringifyKey(n,i,e);const o=a.toJS(s,r,e);if(r in t)Object.defineProperty(t,r,{value:o,writable:true,enumerable:true,configurable:true});else t[r]=o}}return t}const isMergeKey=e=>e===c||r.isScalar(e)&&e.value===c&&(!e.type||e.type===o.Scalar.PLAIN);function mergeToJSMap(e,t,n){const s=e&&r.isAlias(n)?n.resolve(e.doc):n;if(!r.isMap(s))throw new Error("Merge sources must be maps or map aliases");const i=s.toJSON(null,e,Map);for(const[e,n]of i){if(t instanceof Map){if(!t.has(e))t.set(e,n)}else if(t instanceof Set){t.add(e)}else if(!Object.prototype.hasOwnProperty.call(t,e)){Object.defineProperty(t,e,{value:n,writable:true,enumerable:true,configurable:true})}}return t}function stringifyKey(e,t,n){if(t===null)return"";if(typeof t!=="object")return String(t);if(r.isNode(e)&&n&&n.doc){const t=i.createStringifyContext(n.doc,{});t.anchors=new Set;for(const e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=true;t.inStringifyKey=true;const r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);if(e.length>40)e=e.substring(0,36)+'..."';s.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`);n.mapKeyWarned=true}return r}return JSON.stringify(t)}t.addPairToJSMap=addPairToJSMap},2463:(e,t,n)=>{var s=n(1399);function toJS(e,t,n){if(Array.isArray(e))return e.map(((e,t)=>toJS(e,String(t),n)));if(e&&typeof e.toJSON==="function"){if(!n||!s.hasAnchor(e))return e.toJSON(t,n);const i={aliasCount:0,count:1,res:undefined};n.anchors.set(e,i);n.onCreate=e=>{i.res=e;delete n.onCreate};const r=e.toJSON(t,n);if(n.onCreate)n.onCreate(r);return r}if(typeof e==="bigint"&&!n?.keep)return Number(e);return e}t.toJS=toJS},9027:(e,t,n)=>{var s=n(9485);var i=n(7578);var r=n(4236);var o=n(6226);function resolveAsScalar(e,t=true,n){if(e){const _onError=(e,t,s)=>{const i=typeof e==="number"?e:Array.isArray(e)?e[0]:e.offset;if(n)n(i,t,s);else throw new r.YAMLParseError([i,i+1],t,s)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return i.resolveFlowScalar(e,t,_onError);case"block-scalar":return s.resolveBlockScalar(e,t,_onError)}}return null}function createScalarToken(e,t){const{implicitKey:n=false,indent:s,inFlow:i=false,offset:r=-1,type:a="PLAIN"}=t;const c=o.stringifyString({type:a,value:e},{implicitKey:n,indent:s>0?" ".repeat(s):"",inFlow:i,options:{blockQuote:true,lineWidth:-1}});const l=t.end??[{type:"newline",offset:-1,indent:s,source:"\n"}];switch(c[0]){case"|":case">":{const e=c.indexOf("\n");const t=c.substring(0,e);const n=c.substring(e+1)+"\n";const i=[{type:"block-scalar-header",offset:r,indent:s,source:t}];if(!addEndtoBlockProps(i,l))i.push({type:"newline",offset:-1,indent:s,source:"\n"});return{type:"block-scalar",offset:r,indent:s,props:i,source:n}}case'"':return{type:"double-quoted-scalar",offset:r,indent:s,source:c,end:l};case"'":return{type:"single-quoted-scalar",offset:r,indent:s,source:c,end:l};default:return{type:"scalar",offset:r,indent:s,source:c,end:l}}}function setScalarValue(e,t,n={}){let{afterKey:s=false,implicitKey:i=false,inFlow:r=false,type:a}=n;let c="indent"in e?e.indent:null;if(s&&typeof c==="number")c+=2;if(!a)switch(e.type){case"single-quoted-scalar":a="QUOTE_SINGLE";break;case"double-quoted-scalar":a="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if(t.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a=t.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:a="PLAIN"}const l=o.stringifyString({type:a,value:t},{implicitKey:i||c===null,indent:c!==null&&c>0?" ".repeat(c):"",inFlow:r,options:{blockQuote:true,lineWidth:-1}});switch(l[0]){case"|":case">":setBlockScalarValue(e,l);break;case'"':setFlowScalarValue(e,l,"double-quoted-scalar");break;case"'":setFlowScalarValue(e,l,"single-quoted-scalar");break;default:setFlowScalarValue(e,l,"scalar")}}function setBlockScalarValue(e,t){const n=t.indexOf("\n");const s=t.substring(0,n);const i=t.substring(n+1)+"\n";if(e.type==="block-scalar"){const t=e.props[0];if(t.type!=="block-scalar-header")throw new Error("Invalid block scalar header");t.source=s;e.source=i}else{const{offset:t}=e;const n="indent"in e?e.indent:-1;const r=[{type:"block-scalar-header",offset:t,indent:n,source:s}];if(!addEndtoBlockProps(r,"end"in e?e.end:undefined))r.push({type:"newline",offset:-1,indent:n,source:"\n"});for(const t of Object.keys(e))if(t!=="type"&&t!=="offset")delete e[t];Object.assign(e,{type:"block-scalar",indent:n,props:r,source:i})}}function addEndtoBlockProps(e,t){if(t)for(const n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":e.push(n);return true}return false}function setFlowScalarValue(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n;e.source=t;break;case"block-scalar":{const s=e.props.slice(1);let i=t.length;if(e.props[0].type==="block-scalar-header")i-=e.props[0].source.length;for(const e of s)e.offset+=i;delete e.props;Object.assign(e,{type:n,source:t,end:s});break}case"block-map":case"block-seq":{const s=e.offset+t.length;const i={type:"newline",offset:s,indent:e.indent,source:"\n"};delete e.items;Object.assign(e,{type:n,source:t,end:[i]});break}default:{const s="indent"in e?e.indent:-1;const i="end"in e&&Array.isArray(e.end)?e.end.filter((e=>e.type==="space"||e.type==="comment"||e.type==="newline")):[];for(const t of Object.keys(e))if(t!=="type"&&t!=="offset")delete e[t];Object.assign(e,{type:n,indent:s,source:t,end:i})}}}t.createScalarToken=createScalarToken;t.resolveAsScalar=resolveAsScalar;t.setScalarValue=setScalarValue},6307:(e,t)=>{const stringify=e=>"type"in e?stringifyToken(e):stringifyItem(e);function stringifyToken(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=stringifyToken(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=stringifyItem(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=stringifyItem(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=stringifyItem(e);if(e.end)for(const n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(const n of e.end)t+=n.source;return t}}}function stringifyItem({start:e,key:t,sep:n,value:s}){let i="";for(const t of e)i+=t.source;if(t)i+=stringifyToken(t);if(n)for(const e of n)i+=e.source;if(s)i+=stringifyToken(s);return i}t.stringify=stringify},8497:(e,t)=>{const n=Symbol("break visit");const s=Symbol("skip children");const i=Symbol("remove item");function visit(e,t){if("type"in e&&e.type==="document")e={start:e.start,value:e.value};_visit(Object.freeze([]),e,t)}visit.BREAK=n;visit.SKIP=s;visit.REMOVE=i;visit.itemAtPath=(e,t)=>{let n=e;for(const[e,s]of t){const t=n?.[e];if(t&&"items"in t){n=t.items[s]}else return undefined}return n};visit.parentCollection=(e,t)=>{const n=visit.itemAtPath(e,t.slice(0,-1));const s=t[t.length-1][0];const i=n?.[s];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function _visit(e,t,s){let r=s(t,e);if(typeof r==="symbol")return r;for(const o of["key","value"]){const a=t[o];if(a&&"items"in a){for(let t=0;t<a.items.length;++t){const r=_visit(Object.freeze(e.concat([[o,t]])),a.items[t],s);if(typeof r==="number")t=r-1;else if(r===n)return n;else if(r===i){a.items.splice(t,1);t-=1}}if(typeof r==="function"&&o==="key")r=r(t,e)}}return typeof r==="function"?r(t,e):r}t.visit=visit},9169:(e,t,n)=>{var s=n(9027);var i=n(6307);var r=n(8497);const o="\ufeff";const a="";const c="";const l="";const isCollection=e=>!!e&&"items"in e;const isScalar=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function prettyToken(e){switch(e){case o:return"<BOM>";case a:return"<DOC>";case c:return"<FLOW_END>";case l:return"<SCALAR>";default:return JSON.stringify(e)}}function tokenType(e){switch(e){case o:return"byte-order-mark";case a:return"doc-mode";case c:return"flow-error-end";case l:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}t.createScalarToken=s.createScalarToken;t.resolveAsScalar=s.resolveAsScalar;t.setScalarValue=s.setScalarValue;t.stringify=i.stringify;t.visit=r.visit;t.BOM=o;t.DOCUMENT=a;t.FLOW_END=c;t.SCALAR=l;t.isCollection=isCollection;t.isScalar=isScalar;t.prettyToken=prettyToken;t.tokenType=tokenType},5976:(e,t,n)=>{var s=n(9169);function isEmpty(e){switch(e){case undefined:case" ":case"\n":case"\r":case"\t":return true;default:return false}}const i="0123456789ABCDEFabcdef".split("");const r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()".split("");const o=",[]{}".split("");const a=" ,[]{}\n\r\t".split("");const isNotAnchorChar=e=>!e||a.includes(e);class Lexer{constructor(){this.atEnd=false;this.blockScalarIndent=-1;this.blockScalarKeep=false;this.buffer="";this.flowKey=false;this.flowLevel=0;this.indentNext=0;this.indentValue=0;this.lineEndPos=null;this.next=null;this.pos=0}*lex(e,t=false){if(e){this.buffer=this.buffer?this.buffer+e:e;this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";while(n&&(t||this.hasChars(1)))n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos;let t=this.buffer[e];while(t===" "||t==="\t")t=this.buffer[++e];if(!t||t==="#"||t==="\n")return true;if(t==="\r")return this.buffer[e+1]==="\n";return false}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;while(t===" ")t=this.buffer[++n+e];if(t==="\r"){const t=this.buffer[n+e+1];if(t==="\n"||!t&&!this.atEnd)return e+n+1}return t==="\n"||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const t=this.buffer.substr(e,3);if((t==="---"||t==="...")&&isEmpty(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;if(typeof e!=="number"||e!==-1&&e<this.pos){e=this.buffer.indexOf("\n",this.pos);this.lineEndPos=e}if(e===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[e-1]==="\r")e-=1;return this.buffer.substring(this.pos,e)}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){this.buffer=this.buffer.substring(this.pos);this.pos=0;this.lineEndPos=null;this.next=e;return null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===s.BOM){yield*this.pushCount(1);e=e.substring(1)}if(e[0]==="%"){let t=e.length;const n=e.indexOf("#");if(n!==-1){const s=e[n-1];if(s===" "||s==="\t")t=n-1}while(true){const n=e[t-1];if(n===" "||n==="\t")t-=1;else break}const s=(yield*this.pushCount(t))+(yield*this.pushSpaces(true));yield*this.pushCount(e.length-s);this.pushNewline();return"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(true);yield*this.pushCount(e.length-t);yield*this.pushNewline();return"stream"}yield s.DOCUMENT;return yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const e=this.peek(3);if(e==="---"&&isEmpty(this.charAt(3))){yield*this.pushCount(3);this.indentValue=0;this.indentNext=0;return"doc"}else if(e==="..."&&isEmpty(this.charAt(3))){yield*this.pushCount(3);return"stream"}}this.indentValue=yield*this.pushSpaces(false);if(this.indentNext>this.indentValue&&!isEmpty(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&isEmpty(t)){const e=(yield*this.pushCount(1))+(yield*this.pushSpaces(true));this.indentNext=this.indentValue+1;this.indentValue+=e;return yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(true);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case undefined:yield*this.pushNewline();return yield*this.parseLineStart();case"{":case"[":yield*this.pushCount(1);this.flowKey=false;this.flowLevel=1;return"flow";case"}":case"]":yield*this.pushCount(1);return"doc";case"*":yield*this.pushUntil(isNotAnchorChar);return"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":t+=(yield*this.parseBlockScalarHeader());t+=(yield*this.pushSpaces(true));yield*this.pushCount(e.length-t);yield*this.pushNewline();return yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t;let n=-1;do{e=yield*this.pushNewline();if(e>0){t=yield*this.pushSpaces(false);this.indentValue=n=t}else{t=0}t+=(yield*this.pushSpaces(true))}while(e+t>0);const i=this.getLine();if(i===null)return this.setNext("flow");if(n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&isEmpty(i[3])){const e=n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}");if(!e){this.flowLevel=0;yield s.FLOW_END;return yield*this.parseLineStart()}}let r=0;while(i[r]===","){r+=(yield*this.pushCount(1));r+=(yield*this.pushSpaces(true));this.flowKey=false}r+=(yield*this.pushIndicators());switch(i[r]){case undefined:return"flow";case"#":yield*this.pushCount(i.length-r);return"flow";case"{":case"[":yield*this.pushCount(1);this.flowKey=false;this.flowLevel+=1;return"flow";case"}":case"]":yield*this.pushCount(1);this.flowKey=true;this.flowLevel-=1;return this.flowLevel?"flow":"doc";case"*":yield*this.pushUntil(isNotAnchorChar);return"flow";case'"':case"'":this.flowKey=true;return yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||isEmpty(e)||e===","){this.flowKey=false;yield*this.pushCount(1);yield*this.pushSpaces(true);return"flow"}}default:this.flowKey=false;return yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'"){while(t!==-1&&this.buffer[t+1]==="'")t=this.buffer.indexOf("'",t+2)}else{while(t!==-1){let e=0;while(this.buffer[t-1-e]==="\\")e+=1;if(e%2===0)break;t=this.buffer.indexOf('"',t+1)}}const n=this.buffer.substring(0,t);let s=n.indexOf("\n",this.pos);if(s!==-1){while(s!==-1){const e=this.continueScalar(s+1);if(e===-1)break;s=n.indexOf("\n",e)}if(s!==-1){t=s-(n[s-1]==="\r"?2:1)}}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}yield*this.pushToIndex(t+1,false);return this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1;this.blockScalarKeep=false;let e=this.pos;while(true){const t=this.buffer[++e];if(t==="+")this.blockScalarKeep=true;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil((e=>isEmpty(e)||e==="#"))}*parseBlockScalar(){let e=this.pos-1;let t=0;let n;e:for(let s=this.pos;n=this.buffer[s];++s){switch(n){case" ":t+=1;break;case"\n":e=s;t=0;break;case"\r":{const e=this.buffer[s+1];if(!e&&!this.atEnd)return this.setNext("block-scalar");if(e==="\n")break}default:break e}}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=t;else this.indentNext+=this.blockScalarIndent;do{const t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf("\n",t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}if(!this.blockScalarKeep){do{let n=e-1;let s=this.buffer[n];if(s==="\r")s=this.buffer[--n];const i=n;while(s===" "||s==="\t")s=this.buffer[--n];if(s==="\n"&&n>=this.pos&&n+1+t>i)e=n;else break}while(true)}yield s.SCALAR;yield*this.pushToIndex(e+1,true);return yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t=this.pos-1;let n=this.pos-1;let i;while(i=this.buffer[++n]){if(i===":"){const s=this.buffer[n+1];if(isEmpty(s)||e&&s===",")break;t=n}else if(isEmpty(i)){let s=this.buffer[n+1];if(i==="\r"){if(s==="\n"){n+=1;i="\n";s=this.buffer[n+1]}else t=n}if(s==="#"||e&&o.includes(s))break;if(i==="\n"){const e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&o.includes(i))break;t=n}}if(!i&&!this.atEnd)return this.setNext("plain-scalar");yield s.SCALAR;yield*this.pushToIndex(t+1,true);return e?"flow":"doc"}*pushCount(e){if(e>0){yield this.buffer.substr(this.pos,e);this.pos+=e;return e}return 0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);if(n){yield n;this.pos+=n.length;return n.length}else if(t)yield"";return 0}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(true))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(isNotAnchorChar))+(yield*this.pushSpaces(true))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0;const t=this.charAt(1);if(isEmpty(t)||e&&o.includes(t)){if(!e)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=false;return(yield*this.pushCount(1))+(yield*this.pushSpaces(true))+(yield*this.pushIndicators())}}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2;let t=this.buffer[e];while(!isEmpty(t)&&t!==">")t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,false)}else{let e=this.pos+1;let t=this.buffer[e];while(t){if(r.includes(t))t=this.buffer[++e];else if(t==="%"&&i.includes(this.buffer[e+1])&&i.includes(this.buffer[e+2])){t=this.buffer[e+=3]}else break}return yield*this.pushToIndex(e,false)}}*pushNewline(){const e=this.buffer[this.pos];if(e==="\n")return yield*this.pushCount(1);else if(e==="\r"&&this.charAt(1)==="\n")return yield*this.pushCount(2);else return 0}*pushSpaces(e){let t=this.pos-1;let n;do{n=this.buffer[++t]}while(n===" "||e&&n==="\t");const s=t-this.pos;if(s>0){yield this.buffer.substr(this.pos,s);this.pos=t}return s}*pushUntil(e){let t=this.pos;let n=this.buffer[t];while(!e(n))n=this.buffer[++t];return yield*this.pushToIndex(t,false)}}t.Lexer=Lexer},1929:(e,t)=>{class LineCounter{constructor(){this.lineStarts=[];this.addNewLine=e=>this.lineStarts.push(e);this.linePos=e=>{let t=0;let n=this.lineStarts.length;while(t<n){const s=t+n>>1;if(this.lineStarts[s]<e)t=s+1;else n=s}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const s=this.lineStarts[t-1];return{line:t,col:e-s+1}}}}t.LineCounter=LineCounter},3328:(e,t,n)=>{var s=n(9169);var i=n(5976);function includesToken(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return true;return false}function findNonEmptyIndex(e){for(let t=0;t<e.length;++t){switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}}return-1}function isFlowToken(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return true;default:return false}}function getPrevProps(e){switch(e.type){case"document":return e.start;case"block-map":{const t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function getFirstKeyStartProps(e){if(e.length===0)return[];let t=e.length;e:while(--t>=0){switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}}while(e[++t]?.type==="space"){}return e.splice(t,e.length)}function fixFlowSeqItems(e){if(e.start.type==="flow-seq-start"){for(const t of e.items){if(t.sep&&!t.value&&!includesToken(t.start,"explicit-key-ind")&&!includesToken(t.sep,"map-value-ind")){if(t.key)t.value=t.key;delete t.key;if(isFlowToken(t.value)){if(t.value.end)Array.prototype.push.apply(t.value.end,t.sep);else t.value.end=t.sep}else Array.prototype.push.apply(t.start,t.sep);delete t.sep}}}}class Parser{constructor(e){this.atNewLine=true;this.atScalar=false;this.indent=0;this.offset=0;this.onKeyLine=false;this.stack=[];this.source="";this.type="";this.lexer=new i.Lexer;this.onNewLine=e}*parse(e,t=false){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);if(!t)yield*this.end()}*next(e){this.source=e;if(process.env.LOG_TOKENS)console.log("|",s.prettyToken(e));if(this.atScalar){this.atScalar=false;yield*this.step();this.offset+=e.length;return}const t=s.tokenType(e);if(!t){const t=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:t,source:e});this.offset+=e.length}else if(t==="scalar"){this.atNewLine=false;this.atScalar=true;this.type="scalar"}else{this.type=t;yield*this.step();switch(t){case"newline":this.atNewLine=true;this.indent=0;if(this.onNewLine)this.onNewLine(this.offset+e.length);break;case"space":if(this.atNewLine&&e[0]===" ")this.indent+=e.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=e.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=false}this.offset+=e.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){const e={type:this.type,offset:this.offset,indent:this.indent,source:this.source};return e}*step(){const e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(!t){const e="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message:e}}else if(this.stack.length===0){yield t}else{const e=this.peek(1);if(t.type==="block-scalar"){t.indent="indent"in e?e.indent:0}else if(t.type==="flow-collection"&&e.type==="document"){t.indent=0}if(t.type==="flow-collection")fixFlowSeqItems(t);switch(e.type){case"document":e.value=t;break;case"block-scalar":e.props.push(t);break;case"block-map":{const n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]});this.onKeyLine=true;return}else if(n.sep){n.value=t}else{Object.assign(n,{key:t,sep:[]});this.onKeyLine=!includesToken(n.start,"explicit-key-ind");return}break}case"block-seq":{const n=e.items[e.items.length-1];if(n.value)e.items.push({start:[],value:t});else n.value=t;break}case"flow-collection":{const n=e.items[e.items.length-1];if(!n||n.value)e.items.push({start:[],key:t,sep:[]});else if(n.sep)n.value=t;else Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop();yield*this.pop(t)}if((e.type==="document"||e.type==="block-map"||e.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){const n=t.items[t.items.length-1];if(n&&!n.sep&&!n.value&&n.start.length>0&&findNonEmptyIndex(n.start)===-1&&(t.indent===0||n.start.every((e=>e.type!=="comment"||e.indent<t.indent)))){if(e.type==="document")e.end=n.start;else e.items.push({start:n.start});t.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")e.start.push(this.sourceToken);this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{if(findNonEmptyIndex(e.start)!==-1){yield*this.pop();yield*this.step()}else e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}const t=this.startBlockValue(e);if(t)this.stack.push(t);else{yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}}*scalar(e){if(this.type==="map-value-ind"){const t=getPrevProps(this.peek(2));const n=getFirstKeyStartProps(t);let s;if(e.end){s=e.end;s.push(this.sourceToken);delete e.end}else s=[this.sourceToken];const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=true;this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":e.source=this.source;this.atNewLine=true;this.indent=0;if(this.onNewLine){let e=this.source.indexOf("\n")+1;while(e!==0){this.onNewLine(this.offset+e);e=this.source.indexOf("\n",e)+1}}yield*this.pop();break;default:yield*this.pop();yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":this.onKeyLine=false;if(t.value){const n="end"in t.value?t.value.end:undefined;const s=Array.isArray(n)?n[n.length-1]:undefined;if(s?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep){t.sep.push(this.sourceToken)}else{t.start.push(this.sourceToken)}return;case"space":case"comment":if(t.value){e.items.push({start:[this.sourceToken]})}else if(t.sep){t.sep.push(this.sourceToken)}else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2];const s=n?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start);s.push(this.sourceToken);e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent&&t.sep;let s=[];if(n&&t.sep&&!t.value){const n=[];for(let s=0;s<t.sep.length;++s){const i=t.sep[s];switch(i.type){case"newline":n.push(s);break;case"space":break;case"comment":if(i.indent>e.indent)n.length=0;break;default:n.length=0}}if(n.length>=2)s=t.sep.splice(n[1])}switch(this.type){case"anchor":case"tag":if(n||t.value){s.push(this.sourceToken);e.items.push({start:s});this.onKeyLine=true}else if(t.sep){t.sep.push(this.sourceToken)}else{t.start.push(this.sourceToken)}return;case"explicit-key-ind":if(!t.sep&&!includesToken(t.start,"explicit-key-ind")){t.start.push(this.sourceToken)}else if(n||t.value){s.push(this.sourceToken);e.items.push({start:s})}else{this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]})}this.onKeyLine=true;return;case"map-value-ind":if(includesToken(t.start,"explicit-key-ind")){if(!t.sep){if(includesToken(t.start,"newline")){Object.assign(t,{key:null,sep:[this.sourceToken]})}else{const e=getFirstKeyStartProps(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value){e.items.push({start:[],key:null,sep:[this.sourceToken]})}else if(includesToken(t.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else if(isFlowToken(t.key)&&!includesToken(t.sep,"newline")){const e=getFirstKeyStartProps(t.start);const n=t.key;const s=t.sep;s.push(this.sourceToken);delete t.key,delete t.sep;this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:s}]})}else if(s.length>0){t.sep=t.sep.concat(s,this.sourceToken)}else{t.sep.push(this.sourceToken)}}else{if(!t.sep){Object.assign(t,{key:null,sep:[this.sourceToken]})}else if(t.value||n){e.items.push({start:s,key:null,sep:[this.sourceToken]})}else if(includesToken(t.sep,"map-value-ind")){this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]})}else{t.sep.push(this.sourceToken)}}this.onKeyLine=true;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const i=this.flowScalar(this.type);if(n||t.value){e.items.push({start:s,key:i,sep:[]});this.onKeyLine=true}else if(t.sep){this.stack.push(i)}else{Object.assign(t,{key:i,sep:[]});this.onKeyLine=true}return}default:{const i=this.startBlockValue(e);if(i){if(n&&i.type!=="block-seq"&&includesToken(t.start,"explicit-key-ind")){e.items.push({start:s})}this.stack.push(i);return}}}}yield*this.pop();yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:undefined;const s=Array.isArray(n)?n[n.length-1]:undefined;if(s?.type==="comment")n?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2];const s=n?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start);s.push(this.sourceToken);e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||includesToken(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){const t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop();yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let e;do{yield*this.pop();e=this.peek(1)}while(e&&e.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:n,sep:[]});else if(t.sep)this.stack.push(n);else Object.assign(t,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);if(n)this.stack.push(n);else{yield*this.pop();yield*this.step()}}else{const t=this.peek(2);if(t.type==="block-map"&&(this.type==="map-value-ind"&&t.indent===e.indent||this.type==="newline"&&!t.items[t.items.length-1].sep)){yield*this.pop();yield*this.step()}else if(this.type==="map-value-ind"&&t.type!=="flow-collection"){const n=getPrevProps(t);const s=getFirstKeyStartProps(n);fixFlowSeqItems(e);const i=e.end.splice(1,e.end.length);i.push(this.sourceToken);const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};this.onKeyLine=true;this.stack[this.stack.length-1]=r}else{yield*this.lineEnd(e)}}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;while(e!==0){this.onNewLine(this.offset+e);e=this.source.indexOf("\n",e)+1}}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=true;const t=getPrevProps(e);const n=getFirstKeyStartProps(t);n.push(this.sourceToken);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n}]}}case"map-value-ind":{this.onKeyLine=true;const t=getPrevProps(e);const n=getFirstKeyStartProps(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return false;if(this.indent<=t)return false;return e.every((e=>e.type==="newline"||e.type==="space"))}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop();yield*this.step();break;case"newline":this.onKeyLine=false;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}t.Parser=Parser},8649:(e,t,n)=>{var s=n(9493);var i=n(42);var r=n(4236);var o=n(6909);var a=n(1929);var c=n(3328);function parseOptions(e){const t=e.prettyErrors!==false;const n=e.lineCounter||t&&new a.LineCounter||null;return{lineCounter:n,prettyErrors:t}}function parseAllDocuments(e,t={}){const{lineCounter:n,prettyErrors:i}=parseOptions(t);const o=new c.Parser(n?.addNewLine);const a=new s.Composer(t);const l=Array.from(a.compose(o.parse(e)));if(i&&n)for(const t of l){t.errors.forEach(r.prettifyError(e,n));t.warnings.forEach(r.prettifyError(e,n))}if(l.length>0)return l;return Object.assign([],{empty:true},a.streamInfo())}function parseDocument(e,t={}){const{lineCounter:n,prettyErrors:i}=parseOptions(t);const o=new c.Parser(n?.addNewLine);const a=new s.Composer(t);let l=null;for(const t of a.compose(o.parse(e),true,e.length)){if(!l)l=t;else if(l.options.logLevel!=="silent"){l.errors.push(new r.YAMLParseError(t.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}if(i&&n){l.errors.forEach(r.prettifyError(e,n));l.warnings.forEach(r.prettifyError(e,n))}return l}function parse(e,t,n){let s=undefined;if(typeof t==="function"){s=t}else if(n===undefined&&t&&typeof t==="object"){n=t}const i=parseDocument(e,n);if(!i)return null;i.warnings.forEach((e=>o.warn(i.options.logLevel,e)));if(i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];else i.errors=[]}return i.toJS(Object.assign({reviver:s},n))}function stringify(e,t,n){let s=null;if(typeof t==="function"||Array.isArray(t)){s=t}else if(n===undefined&&t){n=t}if(typeof n==="string")n=n.length;if(typeof n==="number"){const e=Math.round(n);n=e<1?undefined:e>8?{indent:8}:{indent:e}}if(e===undefined){const{keepUndefined:e}=n??t??{};if(!e)return undefined}return new i.Document(e,s,n).toString(n)}t.parse=parse;t.parseAllDocuments=parseAllDocuments;t.parseDocument=parseDocument;t.stringify=stringify},6831:(e,t,n)=>{var s=n(1399);var i=n(83);var r=n(1693);var o=n(2201);var a=n(4138);const sortMapEntriesByKey=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;class Schema{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:c,schema:l,sortMapEntries:f,toStringDefaults:u}){this.compat=Array.isArray(e)?a.getTags(e,"compat"):e?a.getTags(null,e):null;this.merge=!!n;this.name=typeof l==="string"&&l||"core";this.knownTags=c?a.coreKnownTags:{};this.tags=a.getTags(t,this.name);this.toStringOptions=u??null;Object.defineProperty(this,s.MAP,{value:i.map});Object.defineProperty(this,s.SCALAR,{value:o.string});Object.defineProperty(this,s.SEQ,{value:r.seq});this.sortMapEntries=typeof f==="function"?f:f===true?sortMapEntriesByKey:null}clone(){const e=Object.create(Schema.prototype,Object.getOwnPropertyDescriptors(this));e.tags=this.tags.slice();return e}}t.Schema=Schema},83:(e,t,n)=>{var s=n(1399);var i=n(246);var r=n(6011);function createMap(e,t,n){const{keepUndefined:s,replacer:o}=n;const a=new r.YAMLMap(e);const add=(e,r)=>{if(typeof o==="function")r=o.call(t,e,r);else if(Array.isArray(o)&&!o.includes(e))return;if(r!==undefined||s)a.items.push(i.createPair(e,r,n))};if(t instanceof Map){for(const[e,n]of t)add(e,n)}else if(t&&typeof t==="object"){for(const e of Object.keys(t))add(e,t[e])}if(typeof e.sortMapEntries==="function"){a.items.sort(e.sortMapEntries)}return a}const o={collection:"map",createNode:createMap,default:true,nodeClass:r.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){if(!s.isMap(e))t("Expected a mapping for this tag");return e}};t.map=o},6703:(e,t,n)=>{var s=n(9338);const i={identify:e=>e==null,createNode:()=>new s.Scalar(null),default:true,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new s.Scalar(null),stringify:({source:e},t)=>typeof e==="string"&&i.test.test(e)?e:t.options.nullStr};t.nullTag=i},1693:(e,t,n)=>{var s=n(9652);var i=n(1399);var r=n(5161);function createSeq(e,t,n){const{replacer:i}=n;const o=new r.YAMLSeq(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let r of t){if(typeof i==="function"){const n=t instanceof Set?r:String(e++);r=i.call(t,n,r)}o.items.push(s.createNode(r,undefined,n))}}return o}const o={collection:"seq",createNode:createSeq,default:true,nodeClass:r.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){if(!i.isSeq(e))t("Expected a sequence for this tag");return e}};t.seq=o},2201:(e,t,n)=>{var s=n(6226);const i={identify:e=>typeof e==="string",default:true,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,i){t=Object.assign({actualString:true},t);return s.stringifyString(e,t,n,i)}};t.string=i},2045:(e,t,n)=>{var s=n(9338);const i={identify:e=>typeof e==="boolean",default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new s.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&i.test.test(e)){const n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?n.options.trueStr:n.options.falseStr}};t.boolTag=i},6810:(e,t,n)=>{var s=n(9338);var i=n(4174);const r={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN))$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:i.stringifyNumber};const o={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():i.stringifyNumber(e)}};const a={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){const t=new s.Scalar(parseFloat(e));const n=e.indexOf(".");if(n!==-1&&e[e.length-1]==="0")t.minFractionDigits=e.length-n-1;return t},stringify:i.stringifyNumber};t.float=a;t.floatExp=o;t.floatNaN=r},3019:(e,t,n)=>{var s=n(4174);const intIdentify=e=>typeof e==="bigint"||Number.isInteger(e);const intResolve=(e,t,n,{intAsBigInt:s})=>s?BigInt(e):parseInt(e.substring(t),n);function intStringify(e,t,n){const{value:i}=e;if(intIdentify(i)&&i>=0)return n+i.toString(t);return s.stringifyNumber(e)}const i={identify:e=>intIdentify(e)&&e>=0,default:true,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>intResolve(e,2,8,n),stringify:e=>intStringify(e,8,"0o")};const r={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:s.stringifyNumber};const o={identify:e=>intIdentify(e)&&e>=0,default:true,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,"0x")};t.int=r;t.intHex=o;t.intOct=i},27:(e,t,n)=>{var s=n(83);var i=n(6703);var r=n(1693);var o=n(2201);var a=n(2045);var c=n(6810);var l=n(3019);const f=[s.map,r.seq,o.string,i.nullTag,a.boolTag,l.intOct,l.int,l.intHex,c.floatNaN,c.floatExp,c.float];t.schema=f},4545:(e,t,n)=>{var s=n(9338);var i=n(83);var r=n(1693);function intIdentify(e){return typeof e==="bigint"||Number.isInteger(e)}const stringifyJSON=({value:e})=>JSON.stringify(e);const o=[{identify:e=>typeof e==="string",default:true,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:stringifyJSON},{identify:e=>e==null,createNode:()=>new s.Scalar(null),default:true,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:stringifyJSON},{identify:e=>typeof e==="boolean",default:true,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>e==="true",stringify:stringifyJSON},{identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>intIdentify(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:stringifyJSON}];const a={default:true,tag:"",test:/^/,resolve(e,t){t(`Unresolved plain scalar ${JSON.stringify(e)}`);return e}};const c=[i.map,r.seq].concat(o,a);t.schema=c},4138:(e,t,n)=>{var s=n(83);var i=n(6703);var r=n(1693);var o=n(2201);var a=n(2045);var c=n(6810);var l=n(3019);var f=n(27);var u=n(4545);var d=n(5724);var h=n(8974);var p=n(9841);var m=n(5389);var y=n(7847);var g=n(1156);const v=new Map([["core",f.schema],["failsafe",[s.map,r.seq,o.string]],["json",u.schema],["yaml11",m.schema],["yaml-1.1",m.schema]]);const b={binary:d.binary,bool:a.boolTag,float:c.float,floatExp:c.floatExp,floatNaN:c.floatNaN,floatTime:g.floatTime,int:l.int,intHex:l.intHex,intOct:l.intOct,intTime:g.intTime,map:s.map,null:i.nullTag,omap:h.omap,pairs:p.pairs,seq:r.seq,set:y.set,timestamp:g.timestamp};const S={"tag:yaml.org,2002:binary":d.binary,"tag:yaml.org,2002:omap":h.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":y.set,"tag:yaml.org,2002:timestamp":g.timestamp};function getTags(e,t){let n=v.get(t);if(!n){if(Array.isArray(e))n=[];else{const e=Array.from(v.keys()).filter((e=>e!=="yaml11")).map((e=>JSON.stringify(e))).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e)){for(const t of e)n=n.concat(t)}else if(typeof e==="function"){n=e(n.slice())}return n.map((e=>{if(typeof e!=="string")return e;const t=b[e];if(t)return t;const n=Object.keys(b).map((e=>JSON.stringify(e))).join(", ");throw new Error(`Unknown custom tag "${e}"; use one of ${n}`)}))}t.coreKnownTags=S;t.getTags=getTags},5724:(e,t,n)=>{var s=n(9338);var i=n(6226);const r={identify:e=>e instanceof Uint8Array,default:false,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Buffer==="function"){return Buffer.from(e,"base64")}else if(typeof atob==="function"){const t=atob(e.replace(/[\n\r]/g,""));const n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}else{t("This environment does not support reading binary tags; either Buffer or atob is required");return e}},stringify({comment:e,type:t,value:n},r,o,a){const c=n;let l;if(typeof Buffer==="function"){l=c instanceof Buffer?c.toString("base64"):Buffer.from(c.buffer).toString("base64")}else if(typeof btoa==="function"){let e="";for(let t=0;t<c.length;++t)e+=String.fromCharCode(c[t]);l=btoa(e)}else{throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required")}if(!t)t=s.Scalar.BLOCK_LITERAL;if(t!==s.Scalar.QUOTE_DOUBLE){const e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth);const n=Math.ceil(l.length/e);const i=new Array(n);for(let t=0,s=0;t<n;++t,s+=e){i[t]=l.substr(s,e)}l=i.join(t===s.Scalar.BLOCK_LITERAL?"\n":" ")}return i.stringifyString({comment:e,type:t,value:l},r,o,a)}};t.binary=r},2631:(e,t,n)=>{var s=n(9338);function boolStringify({value:e,source:t},n){const s=e?i:r;if(t&&s.test.test(t))return t;return e?n.options.trueStr:n.options.falseStr}const i={identify:e=>e===true,default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new s.Scalar(true),stringify:boolStringify};const r={identify:e=>e===false,default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>new s.Scalar(false),stringify:boolStringify};t.falseTag=r;t.trueTag=i},8035:(e,t,n)=>{var s=n(9338);var i=n(4174);const r={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:i.stringifyNumber};const o={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():i.stringifyNumber(e)}};const a={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){const t=new s.Scalar(parseFloat(e.replace(/_/g,"")));const n=e.indexOf(".");if(n!==-1){const s=e.substring(n+1).replace(/_/g,"");if(s[s.length-1]==="0")t.minFractionDigits=s.length}return t},stringify:i.stringifyNumber};t.float=a;t.floatExp=o;t.floatNaN=r},9503:(e,t,n)=>{var s=n(4174);const intIdentify=e=>typeof e==="bigint"||Number.isInteger(e);function intResolve(e,t,n,{intAsBigInt:s}){const i=e[0];if(i==="-"||i==="+")t+=1;e=e.substring(t).replace(/_/g,"");if(s){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}const t=BigInt(e);return i==="-"?BigInt(-1)*t:t}const r=parseInt(e,n);return i==="-"?-1*r:r}function intStringify(e,t,n){const{value:i}=e;if(intIdentify(i)){const e=i.toString(t);return i<0?"-"+n+e.substr(1):n+e}return s.stringifyNumber(e)}const i={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>intResolve(e,2,2,n),stringify:e=>intStringify(e,2,"0b")};const r={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>intResolve(e,1,8,n),stringify:e=>intStringify(e,8,"0")};const o={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:s.stringifyNumber};const a={identify:intIdentify,default:true,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,"0x")};t.int=o;t.intBin=i;t.intHex=a;t.intOct=r},8974:(e,t,n)=>{var s=n(5161);var i=n(2463);var r=n(1399);var o=n(6011);var a=n(9841);class YAMLOMap extends s.YAMLSeq{constructor(){super();this.add=o.YAMLMap.prototype.add.bind(this);this.delete=o.YAMLMap.prototype.delete.bind(this);this.get=o.YAMLMap.prototype.get.bind(this);this.has=o.YAMLMap.prototype.has.bind(this);this.set=o.YAMLMap.prototype.set.bind(this);this.tag=YAMLOMap.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;if(t?.onCreate)t.onCreate(n);for(const e of this.items){let s,o;if(r.isPair(e)){s=i.toJS(e.key,"",t);o=i.toJS(e.value,s,t)}else{s=i.toJS(e,"",t)}if(n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}}YAMLOMap.tag="tag:yaml.org,2002:omap";const c={collection:"seq",identify:e=>e instanceof Map,nodeClass:YAMLOMap,default:false,tag:"tag:yaml.org,2002:omap",resolve(e,t){const n=a.resolvePairs(e,t);const s=[];for(const{key:e}of n.items){if(r.isScalar(e)){if(s.includes(e.value)){t(`Ordered maps must not include duplicate keys: ${e.value}`)}else{s.push(e.value)}}}return Object.assign(new YAMLOMap,n)},createNode(e,t,n){const s=a.createPairs(e,t,n);const i=new YAMLOMap;i.items=s.items;return i}};t.YAMLOMap=YAMLOMap;t.omap=c},9841:(e,t,n)=>{var s=n(1399);var i=n(246);var r=n(9338);var o=n(5161);function resolvePairs(e,t){if(s.isSeq(e)){for(let n=0;n<e.items.length;++n){let o=e.items[n];if(s.isPair(o))continue;else if(s.isMap(o)){if(o.items.length>1)t("Each pair must have its own sequence indicator");const e=o.items[0]||new i.Pair(new r.Scalar(null));if(o.commentBefore)e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore;if(o.comment){const t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[n]=s.isPair(o)?o:new i.Pair(o)}}else t("Expected a sequence for this tag");return e}function createPairs(e,t,n){const{replacer:s}=n;const r=new o.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){if(typeof s==="function")e=s.call(t,String(a++),e);let o,c;if(Array.isArray(e)){if(e.length===2){o=e[0];c=e[1]}else throw new TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){const t=Object.keys(e);if(t.length===1){o=t[0];c=e[o]}else throw new TypeError(`Expected { key: value } tuple: ${e}`)}else{o=e}r.items.push(i.createPair(o,c,n))}return r}const a={collection:"seq",default:false,tag:"tag:yaml.org,2002:pairs",resolve:resolvePairs,createNode:createPairs};t.createPairs=createPairs;t.pairs=a;t.resolvePairs=resolvePairs},5389:(e,t,n)=>{var s=n(83);var i=n(6703);var r=n(1693);var o=n(2201);var a=n(5724);var c=n(2631);var l=n(8035);var f=n(9503);var u=n(8974);var d=n(9841);var h=n(7847);var p=n(1156);const m=[s.map,r.seq,o.string,i.nullTag,c.trueTag,c.falseTag,f.intBin,f.intOct,f.int,f.intHex,l.floatNaN,l.floatExp,l.float,a.binary,u.omap,d.pairs,h.set,p.intTime,p.floatTime,p.timestamp];t.schema=m},7847:(e,t,n)=>{var s=n(1399);var i=n(246);var r=n(6011);class YAMLSet extends r.YAMLMap{constructor(e){super(e);this.tag=YAMLSet.tag}add(e){let t;if(s.isPair(e))t=e;else if(e&&typeof e==="object"&&"key"in e&&"value"in e&&e.value===null)t=new i.Pair(e.key,null);else t=new i.Pair(e,null);const n=r.findPair(this.items,t.key);if(!n)this.items.push(t)}get(e,t){const n=r.findPair(this.items,e);return!t&&s.isPair(n)?s.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=r.findPair(this.items,e);if(n&&!t){this.items.splice(this.items.indexOf(n),1)}else if(!n&&t){this.items.push(new i.Pair(e))}}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(true))return super.toString(Object.assign({},e,{allNullValues:true}),t,n);else throw new Error("Set items must all have null values")}}YAMLSet.tag="tag:yaml.org,2002:set";const o={collection:"map",identify:e=>e instanceof Set,nodeClass:YAMLSet,default:false,tag:"tag:yaml.org,2002:set",resolve(e,t){if(s.isMap(e)){if(e.hasAllNullValues(true))return Object.assign(new YAMLSet,e);else t("Set items must all have null values")}else t("Expected a mapping for this tag");return e},createNode(e,t,n){const{replacer:s}=n;const r=new YAMLSet(e);if(t&&Symbol.iterator in Object(t))for(let e of t){if(typeof s==="function")e=s.call(t,e,e);r.items.push(i.createPair(e,null,n))}return r}};t.YAMLSet=YAMLSet;t.set=o},1156:(e,t,n)=>{var s=n(4174);function parseSexagesimal(e,t){const n=e[0];const s=n==="-"||n==="+"?e.substring(1):e;const num=e=>t?BigInt(e):Number(e);const i=s.replace(/_/g,"").split(":").reduce(((e,t)=>e*num(60)+num(t)),num(0));return n==="-"?num(-1)*i:i}function stringifySexagesimal(e){let{value:t}=e;let num=e=>e;if(typeof t==="bigint")num=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return s.stringifyNumber(e);let n="";if(t<0){n="-";t*=num(-1)}const i=num(60);const r=[t%i];if(t<60){r.unshift(0)}else{t=(t-r[0])/i;r.unshift(t%i);if(t>=60){t=(t-r[0])/i;r.unshift(t)}}return n+r.map((e=>e<10?"0"+String(e):String(e))).join(":").replace(/000000\d*$/,"")}const i={identify:e=>typeof e==="bigint"||Number.isInteger(e),default:true,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>parseSexagesimal(e,n),stringify:stringifySexagesimal};const r={identify:e=>typeof e==="number",default:true,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>parseSexagesimal(e,false),stringify:stringifySexagesimal};const o={identify:e=>e instanceof Date,default:true,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"+"(?:"+"(?:t|T|[ \\t]+)"+"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)"+"(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?"+")?$"),resolve(e){const t=e.match(o.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,s,i,r,a,c]=t.map(Number);const l=t[7]?Number((t[7]+"00").substr(1,3)):0;let f=Date.UTC(n,s-1,i,r||0,a||0,c||0,l);const u=t[8];if(u&&u!=="Z"){let e=parseSexagesimal(u,false);if(Math.abs(e)<30)e*=60;f-=6e4*e}return new Date(f)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};t.floatTime=r;t.intTime=i;t.timestamp=o},2889:(e,t)=>{const n="flow";const s="block";const i="quoted";function foldFlowLines(e,t,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:a=20,onFold:c,onOverflow:l}={}){if(!o||o<0)return e;const f=Math.max(1+a,1+o-t.length);if(e.length<=f)return e;const u=[];const d={};let h=o-t.length;if(typeof r==="number"){if(r>o-Math.max(2,a))u.push(0);else h=o-r}let p=undefined;let m=undefined;let y=false;let g=-1;let v=-1;let b=-1;if(n===s){g=consumeMoreIndentedLines(e,g);if(g!==-1)h=g+f}for(let t;t=e[g+=1];){if(n===i&&t==="\\"){v=g;switch(e[g+1]){case"x":g+=3;break;case"u":g+=5;break;case"U":g+=9;break;default:g+=1}b=g}if(t==="\n"){if(n===s)g=consumeMoreIndentedLines(e,g);h=g+f;p=undefined}else{if(t===" "&&m&&m!==" "&&m!=="\n"&&m!=="\t"){const t=e[g+1];if(t&&t!==" "&&t!=="\n"&&t!=="\t")p=g}if(g>=h){if(p){u.push(p);h=p+f;p=undefined}else if(n===i){while(m===" "||m==="\t"){m=t;t=e[g+=1];y=true}const n=g>b+1?g-2:v-1;if(d[n])return e;u.push(n);d[n]=true;h=n+f;p=undefined}else{y=true}}}m=t}if(y&&l)l();if(u.length===0)return e;if(c)c();let S=e.slice(0,u[0]);for(let s=0;s<u.length;++s){const r=u[s];const o=u[s+1]||e.length;if(r===0)S=`\n${t}${e.slice(0,o)}`;else{if(n===i&&d[r])S+=`${e[r]}\\`;S+=`\n${t}${e.slice(r+1,o)}`}}return S}function consumeMoreIndentedLines(e,t){let n=e[t+1];while(n===" "||n==="\t"){do{n=e[t+=1]}while(n&&n!=="\n");n=e[t+1]}return t}t.FOLD_BLOCK=s;t.FOLD_FLOW=n;t.FOLD_QUOTED=i;t.foldFlowLines=foldFlowLines},8409:(e,t,n)=>{var s=n(8459);var i=n(1399);var r=n(5182);var o=n(6226);function createStringifyContext(e,t){const n=Object.assign({blockQuote:true,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:false,doubleQuotedMinMultiLineLength:40,falseStr:"false",indentSeq:true,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:false,singleQuote:null,trueStr:"true",verifyAliasOrder:true},e.schema.toStringOptions,t);let s;switch(n.collectionStyle){case"block":s=false;break;case"flow":s=true;break;default:s=null}return{anchors:new Set,doc:e,indent:"",indentStep:typeof n.indent==="number"?" ".repeat(n.indent):" ",inFlow:s,options:n}}function getTagObject(e,t){if(t.tag){const n=e.filter((e=>e.tag===t.tag));if(n.length>0)return n.find((e=>e.format===t.format))??n[0]}let n=undefined;let s;if(i.isScalar(t)){s=t.value;const i=e.filter((e=>e.identify?.(s)));n=i.find((e=>e.format===t.format))??i.find((e=>!e.format))}else{s=t;n=e.find((e=>e.nodeClass&&s instanceof e.nodeClass))}if(!n){const e=s?.constructor?.name??typeof s;throw new Error(`Tag not resolved for ${e} value`)}return n}function stringifyProps(e,t,{anchors:n,doc:r}){if(!r.directives)return"";const o=[];const a=(i.isScalar(e)||i.isCollection(e))&&e.anchor;if(a&&s.anchorIsValid(a)){n.add(a);o.push(`&${a}`)}const c=e.tag?e.tag:t.default?null:t.tag;if(c)o.push(r.directives.tagString(c));return o.join(" ")}function stringify(e,t,n,s){if(i.isPair(e))return e.toString(t,n,s);if(i.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e)){throw new TypeError(`Cannot stringify circular structure without alias nodes`)}else{if(t.resolvedAliases)t.resolvedAliases.add(e);else t.resolvedAliases=new Set([e]);e=e.resolve(t.doc)}}let r=undefined;const a=i.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>r=e});if(!r)r=getTagObject(t.doc.schema.tags,a);const c=stringifyProps(a,r,t);if(c.length>0)t.indentAtStart=(t.indentAtStart??0)+c.length+1;const l=typeof r.stringify==="function"?r.stringify(a,t,n,s):i.isScalar(a)?o.stringifyString(a,t,n,s):a.toString(t,n,s);if(!c)return l;return i.isScalar(a)||l[0]==="{"||l[0]==="["?`${c} ${l}`:`${c}\n${t.indent}${l}`}t.createStringifyContext=createStringifyContext;t.stringify=stringify},2466:(e,t,n)=>{var s=n(3466);var i=n(1399);var r=n(8409);var o=n(5182);function stringifyCollection(e,t,n){const s=t.inFlow??e.flow;const i=s?stringifyFlowCollection:stringifyBlockCollection;return i(e,t,n)}function stringifyBlockCollection({comment:e,items:t},n,{blockItemPrefix:s,flowChars:a,itemIndent:c,onChompKeep:l,onComment:f}){const{indent:u,options:{commentString:d}}=n;const h=Object.assign({},n,{indent:c,type:null});let p=false;const m=[];for(let e=0;e<t.length;++e){const a=t[e];let l=null;if(i.isNode(a)){if(!p&&a.spaceBefore)m.push("");addCommentBefore(n,m,a.commentBefore,p);if(a.comment)l=a.comment}else if(i.isPair(a)){const e=i.isNode(a.key)?a.key:null;if(e){if(!p&&e.spaceBefore)m.push("");addCommentBefore(n,m,e.commentBefore,p)}}p=false;let f=r.stringify(a,h,(()=>l=null),(()=>p=true));if(l)f+=o.lineComment(f,c,d(l));if(p&&l)p=false;m.push(s+f)}let y;if(m.length===0){y=a.start+a.end}else{y=m[0];for(let e=1;e<m.length;++e){const t=m[e];y+=t?`\n${u}${t}`:"\n"}}if(e){y+="\n"+o.indentComment(d(e),u);if(f)f()}else if(p&&l)l();return y}function stringifyFlowCollection({comment:e,items:t},n,{flowChars:a,itemIndent:c,onComment:l}){const{indent:f,indentStep:u,options:{commentString:d}}=n;c+=u;const h=Object.assign({},n,{indent:c,inFlow:true,type:null});let p=false;let m=0;const y=[];for(let e=0;e<t.length;++e){const s=t[e];let a=null;if(i.isNode(s)){if(s.spaceBefore)y.push("");addCommentBefore(n,y,s.commentBefore,false);if(s.comment)a=s.comment}else if(i.isPair(s)){const e=i.isNode(s.key)?s.key:null;if(e){if(e.spaceBefore)y.push("");addCommentBefore(n,y,e.commentBefore,false);if(e.comment)p=true}const t=i.isNode(s.value)?s.value:null;if(t){if(t.comment)a=t.comment;if(t.commentBefore)p=true}else if(s.value==null&&e&&e.comment){a=e.comment}}if(a)p=true;let l=r.stringify(s,h,(()=>a=null));if(e<t.length-1)l+=",";if(a)l+=o.lineComment(l,c,d(a));if(!p&&(y.length>m||l.includes("\n")))p=true;y.push(l);m=y.length}let g;const{start:v,end:b}=a;if(y.length===0){g=v+b}else{if(!p){const e=y.reduce(((e,t)=>e+t.length+2),2);p=e>s.Collection.maxFlowStringSingleLineLength}if(p){g=v;for(const e of y)g+=e?`\n${u}${f}${e}`:"\n";g+=`\n${f}${b}`}else{g=`${v} ${y.join(" ")} ${b}`}}if(e){g+=o.lineComment(g,d(e),f);if(l)l()}return g}function addCommentBefore({indent:e,options:{commentString:t}},n,s,i){if(s&&i)s=s.replace(/^\n+/,"");if(s){const i=o.indentComment(t(s),e);n.push(i.trimStart())}}t.stringifyCollection=stringifyCollection},5182:(e,t)=>{const stringifyComment=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(e,t){if(/^\n+$/.test(e))return e.substring(1);return t?e.replace(/^(?! *$)/gm,t):e}const lineComment=(e,t,n)=>e.endsWith("\n")?indentComment(n,t):n.includes("\n")?"\n"+indentComment(n,t):(e.endsWith(" ")?"":" ")+n;t.indentComment=indentComment;t.lineComment=lineComment;t.stringifyComment=stringifyComment},5225:(e,t,n)=>{var s=n(1399);var i=n(8409);var r=n(5182);function stringifyDocument(e,t){const n=[];let o=t.directives===true;if(t.directives!==false&&e.directives){const t=e.directives.toString(e);if(t){n.push(t);o=true}else if(e.directives.docStart)o=true}if(o)n.push("---");const a=i.createStringifyContext(e,t);const{commentString:c}=a.options;if(e.commentBefore){if(n.length!==1)n.unshift("");const t=c(e.commentBefore);n.unshift(r.indentComment(t,""))}let l=false;let f=null;if(e.contents){if(s.isNode(e.contents)){if(e.contents.spaceBefore&&o)n.push("");if(e.contents.commentBefore){const t=c(e.contents.commentBefore);n.push(r.indentComment(t,""))}a.forceBlockIndent=!!e.comment;f=e.contents.comment}const t=f?undefined:()=>l=true;let u=i.stringify(e.contents,a,(()=>f=null),t);if(f)u+=r.lineComment(u,"",c(f));if((u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"){n[n.length-1]=`--- ${u}`}else n.push(u)}else{n.push(i.stringify(e.contents,a))}if(e.directives?.docEnd){if(e.comment){const t=c(e.comment);if(t.includes("\n")){n.push("...");n.push(r.indentComment(t,""))}else{n.push(`... ${t}`)}}else{n.push("...")}}else{let t=e.comment;if(t&&l)t=t.replace(/^\n+/,"");if(t){if((!l||f)&&n[n.length-1]!=="")n.push("");n.push(r.indentComment(c(t),""))}}return n.join("\n")+"\n"}t.stringifyDocument=stringifyDocument},4174:(e,t)=>{function stringifyNumber({format:e,minFractionDigits:t,tag:n,value:s}){if(typeof s==="bigint")return String(s);const i=typeof s==="number"?s:Number(s);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(s);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let e=r.indexOf(".");if(e<0){e=r.length;r+="."}let n=t-(r.length-e-1);while(n-- >0)r+="0"}return r}t.stringifyNumber=stringifyNumber},4875:(e,t,n)=>{var s=n(1399);var i=n(9338);var r=n(8409);var o=n(5182);function stringifyPair({key:e,value:t},n,a,c){const{allNullValues:l,doc:f,indent:u,indentStep:d,options:{commentString:h,indentSeq:p,simpleKeys:m}}=n;let y=s.isNode(e)&&e.comment||null;if(m){if(y){throw new Error("With simple keys, key nodes cannot have comments")}if(s.isCollection(e)){const e="With simple keys, collection cannot be used as a key value";throw new Error(e)}}let g=!m&&(!e||y&&t==null&&!n.inFlow||s.isCollection(e)||(s.isScalar(e)?e.type===i.Scalar.BLOCK_FOLDED||e.type===i.Scalar.BLOCK_LITERAL:typeof e==="object"));n=Object.assign({},n,{allNullValues:false,implicitKey:!g&&(m||!l),indent:u+d});let v=false;let b=false;let S=r.stringify(e,n,(()=>v=true),(()=>b=true));if(!g&&!n.inFlow&&S.length>1024){if(m)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=true}if(n.inFlow){if(l||t==null){if(v&&a)a();return S===""?"?":g?`? ${S}`:S}}else if(l&&!m||t==null&&g){S=`? ${S}`;if(y&&!v){S+=o.lineComment(S,n.indent,h(y))}else if(b&&c)c();return S}if(v)y=null;if(g){if(y)S+=o.lineComment(S,n.indent,h(y));S=`? ${S}\n${u}:`}else{S=`${S}:`;if(y)S+=o.lineComment(S,n.indent,h(y))}let w="";let k=null;if(s.isNode(t)){if(t.spaceBefore)w="\n";if(t.commentBefore){const e=h(t.commentBefore);w+=`\n${o.indentComment(e,n.indent)}`}k=t.comment}else if(t&&typeof t==="object"){t=f.createNode(t)}n.implicitKey=false;if(!g&&!y&&s.isScalar(t))n.indentAtStart=S.length+1;b=false;if(!p&&d.length>=2&&!n.inFlow&&!g&&s.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor){n.indent=n.indent.substr(2)}let E=false;const A=r.stringify(t,n,(()=>E=true),(()=>b=true));let N=" ";if(w||y){if(A===""&&!n.inFlow)N=w==="\n"?"\n\n":w;else N=`${w}\n${n.indent}`}else if(!g&&s.isCollection(t)){const e=A[0]==="["||A[0]==="{";if(!e||A.includes("\n"))N=`\n${n.indent}`}else if(A===""||A[0]==="\n")N="";S+=N+A;if(n.inFlow){if(E&&a)a()}else if(k&&!E){S+=o.lineComment(S,n.indent,h(k))}else if(b&&c){c()}return S}t.stringifyPair=stringifyPair},6226:(e,t,n)=>{var s=n(9338);var i=n(2889);const getFoldOptions=e=>({indentAtStart:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth});const containsDocumentMarker=e=>/^(%|---|\.\.\.)/m.test(e);function lineLengthOverLimit(e,t,n){if(!t||t<0)return false;const s=t-n;const i=e.length;if(i<=s)return false;for(let t=0,n=0;t<i;++t){if(e[t]==="\n"){if(t-n>s)return true;n=t+1;if(i-n<=s)return false}}return true}function doubleQuotedString(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:s}=t;const r=t.options.doubleQuotedMinMultiLineLength;const o=t.indent||(containsDocumentMarker(e)?" ":"");let a="";let c=0;for(let e=0,t=n[e];t;t=n[++e]){if(t===" "&&n[e+1]==="\\"&&n[e+2]==="n"){a+=n.slice(c,e)+"\\ ";e+=1;c=e;t="\\"}if(t==="\\")switch(n[e+1]){case"u":{a+=n.slice(c,e);const t=n.substr(e+2,4);switch(t){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:if(t.substr(0,2)==="00")a+="\\x"+t.substr(2);else a+=n.substr(e,6)}e+=5;c=e+1}break;case"n":if(s||n[e+2]==='"'||n.length<r){e+=1}else{a+=n.slice(c,e)+"\n\n";while(n[e+2]==="\\"&&n[e+3]==="n"&&n[e+4]!=='"'){a+="\n";e+=2}a+=o;if(n[e+2]===" ")a+="\\";e+=1;c=e+1}break;default:e+=1}}a=c?a+n.slice(c):n;return s?a:i.foldFlowLines(a,o,i.FOLD_QUOTED,getFoldOptions(t))}function singleQuotedString(e,t){if(t.options.singleQuote===false||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return doubleQuotedString(e,t);const n=t.indent||(containsDocumentMarker(e)?" ":"");const s="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?s:i.foldFlowLines(s,n,i.FOLD_FLOW,getFoldOptions(t))}function quotedString(e,t){const{singleQuote:n}=t.options;let s;if(n===false)s=doubleQuotedString;else{const t=e.includes('"');const i=e.includes("'");if(t&&!i)s=singleQuotedString;else if(i&&!t)s=doubleQuotedString;else s=n?singleQuotedString:doubleQuotedString}return s(e,t)}function blockString({comment:e,type:t,value:n},r,o,a){const{blockQuote:c,commentString:l,lineWidth:f}=r.options;if(!c||/\n[\t ]+$/.test(n)||/^\s*$/.test(n)){return quotedString(n,r)}const u=r.indent||(r.forceBlockIndent||containsDocumentMarker(n)?" ":"");const d=c==="literal"?true:c==="folded"||t===s.Scalar.BLOCK_FOLDED?false:t===s.Scalar.BLOCK_LITERAL?true:!lineLengthOverLimit(n,f,u.length);if(!n)return d?"|\n":">\n";let h;let p;for(p=n.length;p>0;--p){const e=n[p-1];if(e!=="\n"&&e!=="\t"&&e!==" ")break}let m=n.substring(p);const y=m.indexOf("\n");if(y===-1){h="-"}else if(n===m||y!==m.length-1){h="+";if(a)a()}else{h=""}if(m){n=n.slice(0,-m.length);if(m[m.length-1]==="\n")m=m.slice(0,-1);m=m.replace(/\n+(?!\n|$)/g,`$&${u}`)}let g=false;let v;let b=-1;for(v=0;v<n.length;++v){const e=n[v];if(e===" ")g=true;else if(e==="\n")b=v;else break}let S=n.substring(0,b<v?b+1:v);if(S){n=n.substring(S.length);S=S.replace(/\n+/g,`$&${u}`)}const w=u?"2":"1";let k=(d?"|":">")+(g?w:"")+h;if(e){k+=" "+l(e.replace(/ ?[\r\n]+/g," "));if(o)o()}if(d){n=n.replace(/\n+/g,`$&${u}`);return`${k}\n${u}${S}${n}${m}`}n=n.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);const E=i.foldFlowLines(`${S}${n}${m}`,u,i.FOLD_BLOCK,getFoldOptions(r));return`${k}\n${u}${E}`}function plainString(e,t,n,r){const{type:o,value:a}=e;const{actualString:c,implicitKey:l,indent:f,inFlow:u}=t;if(l&&/[\n[\]{},]/.test(a)||u&&/[[\]{},]/.test(a)){return quotedString(a,t)}if(!a||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a)){return l||u||!a.includes("\n")?quotedString(a,t):blockString(e,t,n,r)}if(!l&&!u&&o!==s.Scalar.PLAIN&&a.includes("\n")){return blockString(e,t,n,r)}if(f===""&&containsDocumentMarker(a)){t.forceBlockIndent=true;return blockString(e,t,n,r)}const d=a.replace(/\n+/g,`$&\n${f}`);if(c){const test=e=>e.default&&e.tag!=="tag:yaml.org,2002:str"&&e.test?.test(d);const{compat:e,tags:n}=t.doc.schema;if(n.some(test)||e?.some(test))return quotedString(a,t)}return l?d:i.foldFlowLines(d,f,i.FOLD_FLOW,getFoldOptions(t))}function stringifyString(e,t,n,i){const{implicitKey:r,inFlow:o}=t;const a=typeof e.value==="string"?e:Object.assign({},e,{value:String(e.value)});let{type:c}=e;if(c!==s.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(a.value))c=s.Scalar.QUOTE_DOUBLE}const _stringify=e=>{switch(e){case s.Scalar.BLOCK_FOLDED:case s.Scalar.BLOCK_LITERAL:return r||o?quotedString(a.value,t):blockString(a,t,n,i);case s.Scalar.QUOTE_DOUBLE:return doubleQuotedString(a.value,t);case s.Scalar.QUOTE_SINGLE:return singleQuotedString(a.value,t);case s.Scalar.PLAIN:return plainString(a,t,n,i);default:return null}};let l=_stringify(c);if(l===null){const{defaultKeyType:e,defaultStringType:n}=t.options;const s=r&&e||n;l=_stringify(s);if(l===null)throw new Error(`Unsupported default string type ${s}`)}return l}t.stringifyString=stringifyString},6796:(e,t,n)=>{var s=n(1399);const i=Symbol("break visit");const r=Symbol("skip children");const o=Symbol("remove node");function visit(e,t){const n=initVisitor(t);if(s.isDocument(e)){const t=visit_(null,e.contents,n,Object.freeze([e]));if(t===o)e.contents=null}else visit_(null,e,n,Object.freeze([]))}visit.BREAK=i;visit.SKIP=r;visit.REMOVE=o;function visit_(e,t,n,r){const a=callVisitor(e,t,n,r);if(s.isNode(a)||s.isPair(a)){replaceNode(e,r,a);return visit_(e,a,n,r)}if(typeof a!=="symbol"){if(s.isCollection(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const s=visit_(e,t.items[e],n,r);if(typeof s==="number")e=s-1;else if(s===i)return i;else if(s===o){t.items.splice(e,1);e-=1}}}else if(s.isPair(t)){r=Object.freeze(r.concat(t));const e=visit_("key",t.key,n,r);if(e===i)return i;else if(e===o)t.key=null;const s=visit_("value",t.value,n,r);if(s===i)return i;else if(s===o)t.value=null}}return a}async function visitAsync(e,t){const n=initVisitor(t);if(s.isDocument(e)){const t=await visitAsync_(null,e.contents,n,Object.freeze([e]));if(t===o)e.contents=null}else await visitAsync_(null,e,n,Object.freeze([]))}visitAsync.BREAK=i;visitAsync.SKIP=r;visitAsync.REMOVE=o;async function visitAsync_(e,t,n,r){const a=await callVisitor(e,t,n,r);if(s.isNode(a)||s.isPair(a)){replaceNode(e,r,a);return visitAsync_(e,a,n,r)}if(typeof a!=="symbol"){if(s.isCollection(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){const s=await visitAsync_(e,t.items[e],n,r);if(typeof s==="number")e=s-1;else if(s===i)return i;else if(s===o){t.items.splice(e,1);e-=1}}}else if(s.isPair(t)){r=Object.freeze(r.concat(t));const e=await visitAsync_("key",t.key,n,r);if(e===i)return i;else if(e===o)t.key=null;const s=await visitAsync_("value",t.value,n,r);if(s===i)return i;else if(s===o)t.value=null}}return a}function initVisitor(e){if(typeof e==="object"&&(e.Collection||e.Node||e.Value)){return Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e)}return e}function callVisitor(e,t,n,i){if(typeof n==="function")return n(e,t,i);if(s.isMap(t))return n.Map?.(e,t,i);if(s.isSeq(t))return n.Seq?.(e,t,i);if(s.isPair(t))return n.Pair?.(e,t,i);if(s.isScalar(t))return n.Scalar?.(e,t,i);if(s.isAlias(t))return n.Alias?.(e,t,i);return undefined}function replaceNode(e,t,n){const i=t[t.length-1];if(s.isCollection(i)){i.items[e]=n}else if(s.isPair(i)){if(e==="key")i.key=n;else i.value=n}else if(s.isDocument(i)){i.contents=n}else{const e=s.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}}t.visit=visit;t.visitAsync=visitAsync}};var t={};function __nccwpck_require2_(n){var s=t[n];if(s!==undefined){return s.exports}var i=t[n]={exports:{}};var r=true;try{e[n].call(i.exports,i,i.exports,__nccwpck_require2_);r=false}finally{if(r)delete t[n]}return i.exports}if(typeof __nccwpck_require2_!=="undefined")__nccwpck_require2_.ab=__dirname+"/";var n=__nccwpck_require2_(6144);module.exports=n})();1727//# sourceMappingURL=index.js.map1728/***/ }),1729/***/ 9690:1730/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) {1731"use strict";1732var __importDefault = (this && this.__importDefault) || function (mod) {1733 return (mod && mod.__esModule) ? mod : { "default": mod };1734};1735const events_1 = __nccwpck_require__(2361);1736const debug_1 = __importDefault(__nccwpck_require__(8237));1737const promisify_1 = __importDefault(__nccwpck_require__(6570));1738const debug = debug_1.default('agent-base');1739function isAgent(v) {1740 return Boolean(v) && typeof v.addRequest === 'function';1741}1742function isSecureEndpoint() {1743 const { stack } = new Error();1744 if (typeof stack !== 'string')1745 return false;1746 return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);1747}1748function createAgent(callback, opts) {1749 return new createAgent.Agent(callback, opts);1750}1751(function (createAgent) {1752 /**1753 * Base `http.Agent` implementation.1754 * No pooling/keep-alive is implemented by default.1755 *1756 * @param {Function} callback1757 * @api public1758 */1759 class Agent extends events_1.EventEmitter {1760 constructor(callback, _opts) {1761 super();1762 let opts = _opts;1763 if (typeof callback === 'function') {1764 this.callback = callback;1765 }1766 else if (callback) {1767 opts = callback;1768 }1769 // Timeout for the socket to be returned from the callback1770 this.timeout = null;1771 if (opts && typeof opts.timeout === 'number') {1772 this.timeout = opts.timeout;1773 }1774 // These aren't actually used by `agent-base`, but are required1775 // for the TypeScript definition files in `@types/node` :/1776 this.maxFreeSockets = 1;1777 this.maxSockets = 1;1778 this.maxTotalSockets = Infinity;1779 this.sockets = {};1780 this.freeSockets = {};1781 this.requests = {};1782 this.options = {};1783 }1784 get defaultPort() {1785 if (typeof this.explicitDefaultPort === 'number') {1786 return this.explicitDefaultPort;1787 }1788 return isSecureEndpoint() ? 443 : 80;1789 }1790 set defaultPort(v) {1791 this.explicitDefaultPort = v;1792 }1793 get protocol() {1794 if (typeof this.explicitProtocol === 'string') {1795 return this.explicitProtocol;1796 }1797 return isSecureEndpoint() ? 'https:' : 'http:';1798 }1799 set protocol(v) {1800 this.explicitProtocol = v;1801 }1802 callback(req, opts, fn) {1803 throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`');1804 }1805 /**1806 * Called by node-core's "_http_client.js" module when creating1807 * a new HTTP request with this Agent instance.1808 *1809 * @api public1810 */1811 addRequest(req, _opts) {1812 const opts = Object.assign({}, _opts);1813 if (typeof opts.secureEndpoint !== 'boolean') {1814 opts.secureEndpoint = isSecureEndpoint();1815 }1816 if (opts.host == null) {1817 opts.host = 'localhost';1818 }1819 if (opts.port == null) {1820 opts.port = opts.secureEndpoint ? 443 : 80;1821 }1822 if (opts.protocol == null) {1823 opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';1824 }1825 if (opts.host && opts.path) {1826 // If both a `host` and `path` are specified then it's most1827 // likely the result of a `url.parse()` call... we need to1828 // remove the `path` portion so that `net.connect()` doesn't1829 // attempt to open that as a unix socket file.1830 delete opts.path;1831 }1832 delete opts.agent;1833 delete opts.hostname;1834 delete opts._defaultAgent;1835 delete opts.defaultPort;1836 delete opts.createConnection;1837 // Hint to use "Connection: close"1838 // XXX: non-documented `http` module API :(1839 req._last = true;1840 req.shouldKeepAlive = false;1841 let timedOut = false;1842 let timeoutId = null;1843 const timeoutMs = opts.timeout || this.timeout;1844 const onerror = (err) => {1845 if (req._hadError)1846 return;1847 req.emit('error', err);1848 // For Safety. Some additional errors might fire later on1849 // and we need to make sure we don't double-fire the error event.1850 req._hadError = true;1851 };1852 const ontimeout = () => {1853 timeoutId = null;1854 timedOut = true;1855 const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`);1856 err.code = 'ETIMEOUT';1857 onerror(err);1858 };1859 const callbackError = (err) => {1860 if (timedOut)1861 return;1862 if (timeoutId !== null) {1863 clearTimeout(timeoutId);1864 timeoutId = null;1865 }1866 onerror(err);1867 };1868 const onsocket = (socket) => {1869 if (timedOut)1870 return;1871 if (timeoutId != null) {1872 clearTimeout(timeoutId);1873 timeoutId = null;1874 }1875 if (isAgent(socket)) {1876 // `socket` is actually an `http.Agent` instance, so1877 // relinquish responsibility for this `req` to the Agent1878 // from here on1879 debug('Callback returned another Agent instance %o', socket.constructor.name);1880 socket.addRequest(req, opts);1881 return;1882 }1883 if (socket) {1884 socket.once('free', () => {1885 this.freeSocket(socket, opts);1886 });1887 req.onSocket(socket);1888 return;1889 }1890 const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``);1891 onerror(err);1892 };1893 if (typeof this.callback !== 'function') {1894 onerror(new Error('`callback` is not defined'));1895 return;1896 }1897 if (!this.promisifiedCallback) {1898 if (this.callback.length >= 3) {1899 debug('Converting legacy callback function to promise');1900 this.promisifiedCallback = promisify_1.default(this.callback);1901 }1902 else {1903 this.promisifiedCallback = this.callback;1904 }1905 }1906 if (typeof timeoutMs === 'number' && timeoutMs > 0) {1907 timeoutId = setTimeout(ontimeout, timeoutMs);1908 }1909 if ('port' in opts && typeof opts.port !== 'number') {1910 opts.port = Number(opts.port);1911 }1912 try {1913 debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`);1914 Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError);1915 }1916 catch (err) {1917 Promise.reject(err).catch(callbackError);1918 }1919 }1920 freeSocket(socket, opts) {1921 debug('Freeing socket %o %o', socket.constructor.name, opts);1922 socket.destroy();1923 }1924 destroy() {1925 debug('Destroying agent %o', this.constructor.name);1926 }1927 }1928 createAgent.Agent = Agent;1929 // So that `instanceof` works correctly1930 createAgent.prototype = createAgent.Agent.prototype;1931})(createAgent || (createAgent = {}));1932module.exports = createAgent;1933//# sourceMappingURL=index.js.map1934/***/ }),1935/***/ 6570:1936/***/ ((__unused_webpack_module, exports) => {1937"use strict";1938Object.defineProperty(exports, "__esModule", ({ value: true }));1939function promisify(fn) {1940 return function (req, opts) {1941 return new Promise((resolve, reject) => {1942 fn.call(this, req, opts, (err, rtn) => {1943 if (err) {1944 reject(err);1945 }1946 else {1947 resolve(rtn);1948 }1949 });1950 });1951 };1952}1953exports["default"] = promisify;1954//# sourceMappingURL=promisify.js.map1955/***/ }),1956/***/ 1546:1957/***/ ((module) => {1958"use strict";1959const arrify = value => {1960 if (value === null || value === undefined) {1961 return [];1962 }1963 if (Array.isArray(value)) {1964 return value;1965 }1966 if (typeof value === 'string') {1967 return [value];1968 }1969 if (typeof value[Symbol.iterator] === 'function') {1970 return [...value];1971 }1972 return [value];1973};1974module.exports = arrify;1975/***/ }),1976/***/ 6463:1977/***/ ((__unused_webpack_module, exports) => {1978"use strict";1979exports.byteLength = byteLength1980exports.toByteArray = toByteArray1981exports.fromByteArray = fromByteArray1982var lookup = []1983var revLookup = []1984var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array1985var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'1986for (var i = 0, len = code.length; i < len; ++i) {1987 lookup[i] = code[i]1988 revLookup[code.charCodeAt(i)] = i1989}1990// Support decoding URL-safe base64 strings, as Node.js does.1991// See: https://en.wikipedia.org/wiki/Base64#URL_applications1992revLookup['-'.charCodeAt(0)] = 621993revLookup['_'.charCodeAt(0)] = 631994function getLens (b64) {1995 var len = b64.length1996 if (len % 4 > 0) {1997 throw new Error('Invalid string. Length must be a multiple of 4')1998 }1999 // Trim off extra bytes after placeholder bytes are found2000 // See: https://github.com/beatgammit/base64-js/issues/422001 var validLen = b64.indexOf('=')2002 if (validLen === -1) validLen = len2003 var placeHoldersLen = validLen === len2004 ? 02005 : 4 - (validLen % 4)2006 return [validLen, placeHoldersLen]2007}2008// base64 is 4/3 + up to two characters of the original data2009function byteLength (b64) {2010 var lens = getLens(b64)2011 var validLen = lens[0]2012 var placeHoldersLen = lens[1]2013 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen2014}2015function _byteLength (b64, validLen, placeHoldersLen) {2016 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen2017}2018function toByteArray (b64) {2019 var tmp2020 var lens = getLens(b64)2021 var validLen = lens[0]2022 var placeHoldersLen = lens[1]2023 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))2024 var curByte = 02025 // if there are placeholders, only get up to the last complete 4 chars2026 var len = placeHoldersLen > 02027 ? validLen - 42028 : validLen2029 var i2030 for (i = 0; i < len; i += 4) {2031 tmp =2032 (revLookup[b64.charCodeAt(i)] << 18) |2033 (revLookup[b64.charCodeAt(i + 1)] << 12) |2034 (revLookup[b64.charCodeAt(i + 2)] << 6) |2035 revLookup[b64.charCodeAt(i + 3)]2036 arr[curByte++] = (tmp >> 16) & 0xFF2037 arr[curByte++] = (tmp >> 8) & 0xFF2038 arr[curByte++] = tmp & 0xFF2039 }2040 if (placeHoldersLen === 2) {2041 tmp =2042 (revLookup[b64.charCodeAt(i)] << 2) |2043 (revLookup[b64.charCodeAt(i + 1)] >> 4)2044 arr[curByte++] = tmp & 0xFF2045 }2046 if (placeHoldersLen === 1) {2047 tmp =2048 (revLookup[b64.charCodeAt(i)] << 10) |2049 (revLookup[b64.charCodeAt(i + 1)] << 4) |2050 (revLookup[b64.charCodeAt(i + 2)] >> 2)2051 arr[curByte++] = (tmp >> 8) & 0xFF2052 arr[curByte++] = tmp & 0xFF2053 }2054 return arr2055}2056function tripletToBase64 (num) {2057 return lookup[num >> 18 & 0x3F] +2058 lookup[num >> 12 & 0x3F] +2059 lookup[num >> 6 & 0x3F] +2060 lookup[num & 0x3F]2061}2062function encodeChunk (uint8, start, end) {2063 var tmp2064 var output = []2065 for (var i = start; i < end; i += 3) {2066 tmp =2067 ((uint8[i] << 16) & 0xFF0000) +2068 ((uint8[i + 1] << 8) & 0xFF00) +2069 (uint8[i + 2] & 0xFF)2070 output.push(tripletToBase64(tmp))2071 }2072 return output.join('')2073}2074function fromByteArray (uint8) {2075 var tmp2076 var len = uint8.length2077 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes2078 var parts = []2079 var maxChunkLength = 16383 // must be multiple of 32080 // go through the array every three bytes, we'll deal with trailing stuff later2081 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {2082 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))2083 }2084 // pad the end with zeros, but make sure to not forget the extra bytes2085 if (extraBytes === 1) {2086 tmp = uint8[len - 1]2087 parts.push(2088 lookup[tmp >> 2] +2089 lookup[(tmp << 4) & 0x3F] +2090 '=='2091 )2092 } else if (extraBytes === 2) {2093 tmp = (uint8[len - 2] << 8) + uint8[len - 1]2094 parts.push(2095 lookup[tmp >> 10] +2096 lookup[(tmp >> 4) & 0x3F] +2097 lookup[(tmp << 2) & 0x3F] +2098 '='2099 )2100 }2101 return parts.join('')2102}2103/***/ }),2104/***/ 7558:2105/***/ (function(module) {2106;(function (globalObject) {2107 'use strict';2108/*2109 * bignumber.js v9.1.02110 * A JavaScript library for arbitrary-precision arithmetic.2111 * https://github.com/MikeMcl/bignumber.js2112 * Copyright (c) 2022 Michael Mclaughlin <M8ch88l@gmail.com>2113 * MIT Licensed.2114 *2115 * BigNumber.prototype methods | BigNumber methods2116 * |2117 * absoluteValue abs | clone2118 * comparedTo | config set2119 * decimalPlaces dp | DECIMAL_PLACES2120 * dividedBy div | ROUNDING_MODE2121 * dividedToIntegerBy idiv | EXPONENTIAL_AT2122 * exponentiatedBy pow | RANGE2123 * integerValue | CRYPTO2124 * isEqualTo eq | MODULO_MODE2125 * isFinite | POW_PRECISION2126 * isGreaterThan gt | FORMAT2127 * isGreaterThanOrEqualTo gte | ALPHABET2128 * isInteger | isBigNumber2129 * isLessThan lt | maximum max2130 * isLessThanOrEqualTo lte | minimum min2131 * isNaN | random2132 * isNegative | sum2133 * isPositive |2134 * isZero |2135 * minus |2136 * modulo mod |2137 * multipliedBy times |2138 * negated |2139 * plus |2140 * precision sd |2141 * shiftedBy |2142 * squareRoot sqrt |2143 * toExponential |2144 * toFixed |2145 * toFormat |2146 * toFraction |2147 * toJSON |2148 * toNumber |2149 * toPrecision |2150 * toString |2151 * valueOf |2152 *2153 */2154 var BigNumber,2155 isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,2156 mathceil = Math.ceil,2157 mathfloor = Math.floor,2158 bignumberError = '[BigNumber Error] ',2159 tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',2160 BASE = 1e14,2161 LOG_BASE = 14,2162 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 12163 // MAX_INT32 = 0x7fffffff, // 2^31 - 12164 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],2165 SQRT_BASE = 1e7,2166 // EDITABLE2167 // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and2168 // the arguments to toExponential, toFixed, toFormat, and toPrecision.2169 MAX = 1E9; // 0 to MAX_INT322170 /*2171 * Create and return a BigNumber constructor.2172 */2173 function clone(configObject) {2174 var div, convertBase, parseNumeric,2175 P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },2176 ONE = new BigNumber(1),2177 //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------2178 // The default values below must be integers within the inclusive ranges stated.2179 // The values can also be changed at run-time using BigNumber.set.2180 // The maximum number of decimal places for operations involving division.2181 DECIMAL_PLACES = 20, // 0 to MAX2182 // The rounding mode used when rounding to the above decimal places, and when using2183 // toExponential, toFixed, toFormat and toPrecision, and round (default value).2184 // UP 0 Away from zero.2185 // DOWN 1 Towards zero.2186 // CEIL 2 Towards +Infinity.2187 // FLOOR 3 Towards -Infinity.2188 // HALF_UP 4 Towards nearest neighbour. If equidistant, up.2189 // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.2190 // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.2191 // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.2192 // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.2193 ROUNDING_MODE = 4, // 0 to 82194 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]2195 // The exponent value at and beneath which toString returns exponential notation.2196 // Number type: -72197 TO_EXP_NEG = -7, // 0 to -MAX2198 // The exponent value at and above which toString returns exponential notation.2199 // Number type: 212200 TO_EXP_POS = 21, // 0 to MAX2201 // RANGE : [MIN_EXP, MAX_EXP]2202 // The minimum exponent value, beneath which underflow to zero occurs.2203 // Number type: -324 (5e-324)2204 MIN_EXP = -1e7, // -1 to -MAX2205 // The maximum exponent value, above which overflow to Infinity occurs.2206 // Number type: 308 (1.7976931348623157e+308)2207 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.2208 MAX_EXP = 1e7, // 1 to MAX2209 // Whether to use cryptographically-secure random number generation, if available.2210 CRYPTO = false, // true or false2211 // The modulo mode used when calculating the modulus: a mod n.2212 // The quotient (q = a / n) is calculated according to the corresponding rounding mode.2213 // The remainder (r) is calculated as: r = a - n * q.2214 //2215 // UP 0 The remainder is positive if the dividend is negative, else is negative.2216 // DOWN 1 The remainder has the same sign as the dividend.2217 // This modulo mode is commonly known as 'truncated division' and is2218 // equivalent to (a % n) in JavaScript.2219 // FLOOR 3 The remainder has the same sign as the divisor (Python %).2220 // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.2221 // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).2222 // The remainder is always positive.2223 //2224 // The truncated division, floored division, Euclidian division and IEEE 754 remainder2225 // modes are commonly used for the modulus operation.2226 // Although the other rounding modes can also be used, they may not give useful results.2227 MODULO_MODE = 1, // 0 to 92228 // The maximum number of significant digits of the result of the exponentiatedBy operation.2229 // If POW_PRECISION is 0, there will be unlimited significant digits.2230 POW_PRECISION = 0, // 0 to MAX2231 // The format specification used by the BigNumber.prototype.toFormat method.2232 FORMAT = {2233 prefix: '',2234 groupSize: 3,2235 secondaryGroupSize: 0,2236 groupSeparator: ',',2237 decimalSeparator: '.',2238 fractionGroupSize: 0,2239 fractionGroupSeparator: '\xA0', // non-breaking space2240 suffix: ''2241 },2242 // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',2243 // '-', '.', whitespace, or repeated character.2244 // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'2245 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz',2246 alphabetHasNormalDecimalDigits = true;2247 //------------------------------------------------------------------------------------------2248 // CONSTRUCTOR2249 /*2250 * The BigNumber constructor and exported function.2251 * Create and return a new instance of a BigNumber object.2252 *2253 * v {number|string|BigNumber} A numeric value.2254 * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.2255 */2256 function BigNumber(v, b) {2257 var alphabet, c, caseChanged, e, i, isNum, len, str,2258 x = this;2259 // Enable constructor call without `new`.2260 if (!(x instanceof BigNumber)) return new BigNumber(v, b);2261 if (b == null) {2262 if (v && v._isBigNumber === true) {2263 x.s = v.s;2264 if (!v.c || v.e > MAX_EXP) {2265 x.c = x.e = null;2266 } else if (v.e < MIN_EXP) {2267 x.c = [x.e = 0];2268 } else {2269 x.e = v.e;2270 x.c = v.c.slice();2271 }2272 return;2273 }2274 if ((isNum = typeof v == 'number') && v * 0 == 0) {2275 // Use `1 / n` to handle minus zero also.2276 x.s = 1 / v < 0 ? (v = -v, -1) : 1;2277 // Fast path for integers, where n < 2147483648 (2**31).2278 if (v === ~~v) {2279 for (e = 0, i = v; i >= 10; i /= 10, e++);2280 if (e > MAX_EXP) {2281 x.c = x.e = null;2282 } else {2283 x.e = e;2284 x.c = [v];2285 }2286 return;2287 }2288 str = String(v);2289 } else {2290 if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);2291 x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;2292 }2293 // Decimal point?2294 if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');2295 // Exponential form?2296 if ((i = str.search(/e/i)) > 0) {2297 // Determine exponent.2298 if (e < 0) e = i;2299 e += +str.slice(i + 1);2300 str = str.substring(0, i);2301 } else if (e < 0) {2302 // Integer.2303 e = str.length;2304 }2305 } else {2306 // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'2307 intCheck(b, 2, ALPHABET.length, 'Base');2308 // Allow exponential notation to be used with base 10 argument, while2309 // also rounding to DECIMAL_PLACES as with other bases.2310 if (b == 10 && alphabetHasNormalDecimalDigits) {2311 x = new BigNumber(v);2312 return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);2313 }2314 str = String(v);2315 if (isNum = typeof v == 'number') {2316 // Avoid potential interpretation of Infinity and NaN as base 44+ values.2317 if (v * 0 != 0) return parseNumeric(x, str, isNum, b);2318 x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;2319 // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'2320 if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) {2321 throw Error2322 (tooManyDigits + v);2323 }2324 } else {2325 x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;2326 }2327 alphabet = ALPHABET.slice(0, b);2328 e = i = 0;2329 // Check that str is a valid base b number.2330 // Don't use RegExp, so alphabet can contain special characters.2331 for (len = str.length; i < len; i++) {2332 if (alphabet.indexOf(c = str.charAt(i)) < 0) {2333 if (c == '.') {2334 // If '.' is not the first character and it has not be found before.2335 if (i > e) {2336 e = len;2337 continue;2338 }2339 } else if (!caseChanged) {2340 // Allow e.g. hexadecimal 'FF' as well as 'ff'.2341 if (str == str.toUpperCase() && (str = str.toLowerCase()) ||2342 str == str.toLowerCase() && (str = str.toUpperCase())) {2343 caseChanged = true;2344 i = -1;2345 e = 0;2346 continue;2347 }2348 }2349 return parseNumeric(x, String(v), isNum, b);2350 }2351 }2352 // Prevent later check for length on converted number.2353 isNum = false;2354 str = convertBase(str, b, 10, x.s);2355 // Decimal point?2356 if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');2357 else e = str.length;2358 }2359 // Determine leading zeros.2360 for (i = 0; str.charCodeAt(i) === 48; i++);2361 // Determine trailing zeros.2362 for (len = str.length; str.charCodeAt(--len) === 48;);2363 if (str = str.slice(i, ++len)) {2364 len -= i;2365 // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'2366 if (isNum && BigNumber.DEBUG &&2367 len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {2368 throw Error2369 (tooManyDigits + (x.s * v));2370 }2371 // Overflow?2372 if ((e = e - i - 1) > MAX_EXP) {2373 // Infinity.2374 x.c = x.e = null;2375 // Underflow?2376 } else if (e < MIN_EXP) {2377 // Zero.2378 x.c = [x.e = 0];2379 } else {2380 x.e = e;2381 x.c = [];2382 // Transform base2383 // e is the base 10 exponent.2384 // i is where to slice str to get the first element of the coefficient array.2385 i = (e + 1) % LOG_BASE;2386 if (e < 0) i += LOG_BASE; // i < 12387 if (i < len) {2388 if (i) x.c.push(+str.slice(0, i));2389 for (len -= LOG_BASE; i < len;) {2390 x.c.push(+str.slice(i, i += LOG_BASE));2391 }2392 i = LOG_BASE - (str = str.slice(i)).length;2393 } else {2394 i -= len;2395 }2396 for (; i--; str += '0');2397 x.c.push(+str);2398 }2399 } else {2400 // Zero.2401 x.c = [x.e = 0];2402 }2403 }2404 // CONSTRUCTOR PROPERTIES2405 BigNumber.clone = clone;2406 BigNumber.ROUND_UP = 0;2407 BigNumber.ROUND_DOWN = 1;2408 BigNumber.ROUND_CEIL = 2;2409 BigNumber.ROUND_FLOOR = 3;2410 BigNumber.ROUND_HALF_UP = 4;2411 BigNumber.ROUND_HALF_DOWN = 5;2412 BigNumber.ROUND_HALF_EVEN = 6;2413 BigNumber.ROUND_HALF_CEIL = 7;2414 BigNumber.ROUND_HALF_FLOOR = 8;2415 BigNumber.EUCLID = 9;2416 /*2417 * Configure infrequently-changing library-wide settings.2418 *2419 * Accept an object with the following optional properties (if the value of a property is2420 * a number, it must be an integer within the inclusive range stated):2421 *2422 * DECIMAL_PLACES {number} 0 to MAX2423 * ROUNDING_MODE {number} 0 to 82424 * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]2425 * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]2426 * CRYPTO {boolean} true or false2427 * MODULO_MODE {number} 0 to 92428 * POW_PRECISION {number} 0 to MAX2429 * ALPHABET {string} A string of two or more unique characters which does2430 * not contain '.'.2431 * FORMAT {object} An object with some of the following properties:2432 * prefix {string}2433 * groupSize {number}2434 * secondaryGroupSize {number}2435 * groupSeparator {string}2436 * decimalSeparator {string}2437 * fractionGroupSize {number}2438 * fractionGroupSeparator {string}2439 * suffix {string}2440 *2441 * (The values assigned to the above FORMAT object properties are not checked for validity.)2442 *2443 * E.g.2444 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })2445 *2446 * Ignore properties/parameters set to null or undefined, except for ALPHABET.2447 *2448 * Return an object with the properties current values.2449 */2450 BigNumber.config = BigNumber.set = function (obj) {2451 var p, v;2452 if (obj != null) {2453 if (typeof obj == 'object') {2454 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.2455 // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'2456 if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {2457 v = obj[p];2458 intCheck(v, 0, MAX, p);2459 DECIMAL_PLACES = v;2460 }2461 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.2462 // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'2463 if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {2464 v = obj[p];2465 intCheck(v, 0, 8, p);2466 ROUNDING_MODE = v;2467 }2468 // EXPONENTIAL_AT {number|number[]}2469 // Integer, -MAX to MAX inclusive or2470 // [integer -MAX to 0 inclusive, 0 to MAX inclusive].2471 // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'2472 if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {2473 v = obj[p];2474 if (v && v.pop) {2475 intCheck(v[0], -MAX, 0, p);2476 intCheck(v[1], 0, MAX, p);2477 TO_EXP_NEG = v[0];2478 TO_EXP_POS = v[1];2479 } else {2480 intCheck(v, -MAX, MAX, p);2481 TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);2482 }2483 }2484 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or2485 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].2486 // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'2487 if (obj.hasOwnProperty(p = 'RANGE')) {2488 v = obj[p];2489 if (v && v.pop) {2490 intCheck(v[0], -MAX, -1, p);2491 intCheck(v[1], 1, MAX, p);2492 MIN_EXP = v[0];2493 MAX_EXP = v[1];2494 } else {2495 intCheck(v, -MAX, MAX, p);2496 if (v) {2497 MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);2498 } else {2499 throw Error2500 (bignumberError + p + ' cannot be zero: ' + v);2501 }2502 }2503 }2504 // CRYPTO {boolean} true or false.2505 // '[BigNumber Error] CRYPTO not true or false: {v}'2506 // '[BigNumber Error] crypto unavailable'2507 if (obj.hasOwnProperty(p = 'CRYPTO')) {2508 v = obj[p];2509 if (v === !!v) {2510 if (v) {2511 if (typeof crypto != 'undefined' && crypto &&2512 (crypto.getRandomValues || crypto.randomBytes)) {2513 CRYPTO = v;2514 } else {2515 CRYPTO = !v;2516 throw Error2517 (bignumberError + 'crypto unavailable');2518 }2519 } else {2520 CRYPTO = v;2521 }2522 } else {2523 throw Error2524 (bignumberError + p + ' not true or false: ' + v);2525 }2526 }2527 // MODULO_MODE {number} Integer, 0 to 9 inclusive.2528 // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'2529 if (obj.hasOwnProperty(p = 'MODULO_MODE')) {2530 v = obj[p];2531 intCheck(v, 0, 9, p);2532 MODULO_MODE = v;2533 }2534 // POW_PRECISION {number} Integer, 0 to MAX inclusive.2535 // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'2536 if (obj.hasOwnProperty(p = 'POW_PRECISION')) {2537 v = obj[p];2538 intCheck(v, 0, MAX, p);2539 POW_PRECISION = v;2540 }2541 // FORMAT {object}2542 // '[BigNumber Error] FORMAT not an object: {v}'2543 if (obj.hasOwnProperty(p = 'FORMAT')) {2544 v = obj[p];2545 if (typeof v == 'object') FORMAT = v;2546 else throw Error2547 (bignumberError + p + ' not an object: ' + v);2548 }2549 // ALPHABET {string}2550 // '[BigNumber Error] ALPHABET invalid: {v}'2551 if (obj.hasOwnProperty(p = 'ALPHABET')) {2552 v = obj[p];2553 // Disallow if less than two characters,2554 // or if it contains '+', '-', '.', whitespace, or a repeated character.2555 if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) {2556 alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';2557 ALPHABET = v;2558 } else {2559 throw Error2560 (bignumberError + p + ' invalid: ' + v);2561 }2562 }2563 } else {2564 // '[BigNumber Error] Object expected: {v}'2565 throw Error2566 (bignumberError + 'Object expected: ' + obj);2567 }2568 }2569 return {2570 DECIMAL_PLACES: DECIMAL_PLACES,2571 ROUNDING_MODE: ROUNDING_MODE,2572 EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],2573 RANGE: [MIN_EXP, MAX_EXP],2574 CRYPTO: CRYPTO,2575 MODULO_MODE: MODULO_MODE,2576 POW_PRECISION: POW_PRECISION,2577 FORMAT: FORMAT,2578 ALPHABET: ALPHABET2579 };2580 };2581 /*2582 * Return true if v is a BigNumber instance, otherwise return false.2583 *2584 * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.2585 *2586 * v {any}2587 *2588 * '[BigNumber Error] Invalid BigNumber: {v}'2589 */2590 BigNumber.isBigNumber = function (v) {2591 if (!v || v._isBigNumber !== true) return false;2592 if (!BigNumber.DEBUG) return true;2593 var i, n,2594 c = v.c,2595 e = v.e,2596 s = v.s;2597 out: if ({}.toString.call(c) == '[object Array]') {2598 if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {2599 // If the first element is zero, the BigNumber value must be zero.2600 if (c[0] === 0) {2601 if (e === 0 && c.length === 1) return true;2602 break out;2603 }2604 // Calculate number of digits that c[0] should have, based on the exponent.2605 i = (e + 1) % LOG_BASE;2606 if (i < 1) i += LOG_BASE;2607 // Calculate number of digits of c[0].2608 //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {2609 if (String(c[0]).length == i) {2610 for (i = 0; i < c.length; i++) {2611 n = c[i];2612 if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;2613 }2614 // Last element cannot be zero, unless it is the only element.2615 if (n !== 0) return true;2616 }2617 }2618 // Infinity/NaN2619 } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {2620 return true;2621 }2622 throw Error2623 (bignumberError + 'Invalid BigNumber: ' + v);2624 };2625 /*2626 * Return a new BigNumber whose value is the maximum of the arguments.2627 *2628 * arguments {number|string|BigNumber}2629 */2630 BigNumber.maximum = BigNumber.max = function () {2631 return maxOrMin(arguments, P.lt);2632 };2633 /*2634 * Return a new BigNumber whose value is the minimum of the arguments.2635 *2636 * arguments {number|string|BigNumber}2637 */2638 BigNumber.minimum = BigNumber.min = function () {2639 return maxOrMin(arguments, P.gt);2640 };2641 /*2642 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,2643 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing2644 * zeros are produced).2645 *2646 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.2647 *2648 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'2649 * '[BigNumber Error] crypto unavailable'2650 */2651 BigNumber.random = (function () {2652 var pow2_53 = 0x20000000000000;2653 // Return a 53 bit integer n, where 0 <= n < 9007199254740992.2654 // Check if Math.random() produces more than 32 bits of randomness.2655 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.2656 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.2657 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff2658 ? function () { return mathfloor(Math.random() * pow2_53); }2659 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +2660 (Math.random() * 0x800000 | 0); };2661 return function (dp) {2662 var a, b, e, k, v,2663 i = 0,2664 c = [],2665 rand = new BigNumber(ONE);2666 if (dp == null) dp = DECIMAL_PLACES;2667 else intCheck(dp, 0, MAX);2668 k = mathceil(dp / LOG_BASE);2669 if (CRYPTO) {2670 // Browsers supporting crypto.getRandomValues.2671 if (crypto.getRandomValues) {2672 a = crypto.getRandomValues(new Uint32Array(k *= 2));2673 for (; i < k;) {2674 // 53 bits:2675 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)2676 // 11111 11111111 11111111 11111111 11100000 00000000 000000002677 // ((Math.pow(2, 32) - 1) >>> 11).toString(2)2678 // 11111 11111111 111111112679 // 0x20000 is 2^21.2680 v = a[i] * 0x20000 + (a[i + 1] >>> 11);2681 // Rejection sampling:2682 // 0 <= v < 90071992547409922683 // Probability that v >= 9e15, is2684 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 12512685 if (v >= 9e15) {2686 b = crypto.getRandomValues(new Uint32Array(2));2687 a[i] = b[0];2688 a[i + 1] = b[1];2689 } else {2690 // 0 <= v <= 89999999999999992691 // 0 <= (v % 1e14) <= 999999999999992692 c.push(v % 1e14);2693 i += 2;2694 }2695 }2696 i = k / 2;2697 // Node.js supporting crypto.randomBytes.2698 } else if (crypto.randomBytes) {2699 // buffer2700 a = crypto.randomBytes(k *= 7);2701 for (; i < k;) {2702 // 0x1000000000000 is 2^48, 0x10000000000 is 2^402703 // 0x100000000 is 2^32, 0x1000000 is 2^242704 // 11111 11111111 11111111 11111111 11111111 11111111 111111112705 // 0 <= v < 90071992547409922706 v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +2707 (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +2708 (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];2709 if (v >= 9e15) {2710 crypto.randomBytes(7).copy(a, i);2711 } else {2712 // 0 <= (v % 1e14) <= 999999999999992713 c.push(v % 1e14);2714 i += 7;2715 }2716 }2717 i = k / 7;2718 } else {2719 CRYPTO = false;2720 throw Error2721 (bignumberError + 'crypto unavailable');2722 }2723 }2724 // Use Math.random.2725 if (!CRYPTO) {2726 for (; i < k;) {2727 v = random53bitInt();2728 if (v < 9e15) c[i++] = v % 1e14;2729 }2730 }2731 k = c[--i];2732 dp %= LOG_BASE;2733 // Convert trailing digits to zeros according to dp.2734 if (k && dp) {2735 v = POWS_TEN[LOG_BASE - dp];2736 c[i] = mathfloor(k / v) * v;2737 }2738 // Remove trailing elements which are zero.2739 for (; c[i] === 0; c.pop(), i--);2740 // Zero?2741 if (i < 0) {2742 c = [e = 0];2743 } else {2744 // Remove leading elements which are zero and adjust exponent accordingly.2745 for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);2746 // Count the digits of the first element of c to determine leading zeros, and...2747 for (i = 1, v = c[0]; v >= 10; v /= 10, i++);2748 // adjust the exponent accordingly.2749 if (i < LOG_BASE) e -= LOG_BASE - i;2750 }2751 rand.e = e;2752 rand.c = c;2753 return rand;2754 };2755 })();2756 /*2757 * Return a BigNumber whose value is the sum of the arguments.2758 *2759 * arguments {number|string|BigNumber}2760 */2761 BigNumber.sum = function () {2762 var i = 1,2763 args = arguments,2764 sum = new BigNumber(args[0]);2765 for (; i < args.length;) sum = sum.plus(args[i++]);2766 return sum;2767 };2768 // PRIVATE FUNCTIONS2769 // Called by BigNumber and BigNumber.prototype.toString.2770 convertBase = (function () {2771 var decimal = '0123456789';2772 /*2773 * Convert string of baseIn to an array of numbers of baseOut.2774 * Eg. toBaseOut('255', 10, 16) returns [15, 15].2775 * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].2776 */2777 function toBaseOut(str, baseIn, baseOut, alphabet) {2778 var j,2779 arr = [0],2780 arrL,2781 i = 0,2782 len = str.length;2783 for (; i < len;) {2784 for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);2785 arr[0] += alphabet.indexOf(str.charAt(i++));2786 for (j = 0; j < arr.length; j++) {2787 if (arr[j] > baseOut - 1) {2788 if (arr[j + 1] == null) arr[j + 1] = 0;2789 arr[j + 1] += arr[j] / baseOut | 0;2790 arr[j] %= baseOut;2791 }2792 }2793 }2794 return arr.reverse();2795 }2796 // Convert a numeric string of baseIn to a numeric string of baseOut.2797 // If the caller is toString, we are converting from base 10 to baseOut.2798 // If the caller is BigNumber, we are converting from baseIn to base 10.2799 return function (str, baseIn, baseOut, sign, callerIsToString) {2800 var alphabet, d, e, k, r, x, xc, y,2801 i = str.indexOf('.'),2802 dp = DECIMAL_PLACES,2803 rm = ROUNDING_MODE;2804 // Non-integer.2805 if (i >= 0) {2806 k = POW_PRECISION;2807 // Unlimited precision.2808 POW_PRECISION = 0;2809 str = str.replace('.', '');2810 y = new BigNumber(baseIn);2811 x = y.pow(str.length - i);2812 POW_PRECISION = k;2813 // Convert str as if an integer, then restore the fraction part by dividing the2814 // result by its base raised to a power.2815 y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),2816 10, baseOut, decimal);2817 y.e = y.c.length;2818 }2819 // Convert the number as integer.2820 xc = toBaseOut(str, baseIn, baseOut, callerIsToString2821 ? (alphabet = ALPHABET, decimal)2822 : (alphabet = decimal, ALPHABET));2823 // xc now represents str as an integer and converted to baseOut. e is the exponent.2824 e = k = xc.length;2825 // Remove trailing zeros.2826 for (; xc[--k] == 0; xc.pop());2827 // Zero?2828 if (!xc[0]) return alphabet.charAt(0);2829 // Does str represent an integer? If so, no need for the division.2830 if (i < 0) {2831 --e;2832 } else {2833 x.c = xc;2834 x.e = e;2835 // The sign is needed for correct rounding.2836 x.s = sign;2837 x = div(x, y, dp, rm, baseOut);2838 xc = x.c;2839 r = x.r;2840 e = x.e;2841 }2842 // xc now represents str converted to baseOut.2843 // THe index of the rounding digit.2844 d = e + dp + 1;2845 // The rounding digit: the digit to the right of the digit that may be rounded up.2846 i = xc[d];2847 // Look at the rounding digits and mode to determine whether to round up.2848 k = baseOut / 2;2849 r = r || d < 0 || xc[d + 1] != null;2850 r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))2851 : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||2852 rm == (x.s < 0 ? 8 : 7));2853 // If the index of the rounding digit is not greater than zero, or xc represents2854 // zero, then the result of the base conversion is zero or, if rounding up, a value2855 // such as 0.00001.2856 if (d < 1 || !xc[0]) {2857 // 1^-dp or 02858 str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);2859 } else {2860 // Truncate xc to the required number of decimal places.2861 xc.length = d;2862 // Round up?2863 if (r) {2864 // Rounding up may mean the previous digit has to be rounded up and so on.2865 for (--baseOut; ++xc[--d] > baseOut;) {2866 xc[d] = 0;2867 if (!d) {2868 ++e;2869 xc = [1].concat(xc);2870 }2871 }2872 }2873 // Determine trailing zeros.2874 for (k = xc.length; !xc[--k];);2875 // E.g. [4, 11, 15] becomes 4bf.2876 for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));2877 // Add leading zeros, decimal point and trailing zeros as required.2878 str = toFixedPoint(str, e, alphabet.charAt(0));2879 }2880 // The caller will add the sign.2881 return str;2882 };2883 })();2884 // Perform division in the specified base. Called by div and convertBase.2885 div = (function () {2886 // Assume non-zero x and k.2887 function multiply(x, k, base) {2888 var m, temp, xlo, xhi,2889 carry = 0,2890 i = x.length,2891 klo = k % SQRT_BASE,2892 khi = k / SQRT_BASE | 0;2893 for (x = x.slice(); i--;) {2894 xlo = x[i] % SQRT_BASE;2895 xhi = x[i] / SQRT_BASE | 0;2896 m = khi * xlo + xhi * klo;2897 temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;2898 carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;2899 x[i] = temp % base;2900 }2901 if (carry) x = [carry].concat(x);2902 return x;2903 }2904 function compare(a, b, aL, bL) {2905 var i, cmp;2906 if (aL != bL) {2907 cmp = aL > bL ? 1 : -1;2908 } else {2909 for (i = cmp = 0; i < aL; i++) {2910 if (a[i] != b[i]) {2911 cmp = a[i] > b[i] ? 1 : -1;2912 break;2913 }2914 }2915 }2916 return cmp;2917 }2918 function subtract(a, b, aL, base) {2919 var i = 0;2920 // Subtract b from a.2921 for (; aL--;) {2922 a[aL] -= i;2923 i = a[aL] < b[aL] ? 1 : 0;2924 a[aL] = i * base + a[aL] - b[aL];2925 }2926 // Remove leading zeros.2927 for (; !a[0] && a.length > 1; a.splice(0, 1));2928 }2929 // x: dividend, y: divisor.2930 return function (x, y, dp, rm, base) {2931 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,2932 yL, yz,2933 s = x.s == y.s ? 1 : -1,2934 xc = x.c,2935 yc = y.c;2936 // Either NaN, Infinity or 0?2937 if (!xc || !xc[0] || !yc || !yc[0]) {2938 return new BigNumber(2939 // Return NaN if either NaN, or both Infinity or 0.2940 !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :2941 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.2942 xc && xc[0] == 0 || !yc ? s * 0 : s / 02943 );2944 }2945 q = new BigNumber(s);2946 qc = q.c = [];2947 e = x.e - y.e;2948 s = dp + e + 1;2949 if (!base) {2950 base = BASE;2951 e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);2952 s = s / LOG_BASE | 0;2953 }2954 // Result exponent may be one less then the current value of e.2955 // The coefficients of the BigNumbers from convertBase may have trailing zeros.2956 for (i = 0; yc[i] == (xc[i] || 0); i++);2957 if (yc[i] > (xc[i] || 0)) e--;2958 if (s < 0) {2959 qc.push(1);2960 more = true;2961 } else {2962 xL = xc.length;2963 yL = yc.length;2964 i = 0;2965 s += 2;2966 // Normalise xc and yc so highest order digit of yc is >= base / 2.2967 n = mathfloor(base / (yc[0] + 1));2968 // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.2969 // if (n > 1 || n++ == 1 && yc[0] < base / 2) {2970 if (n > 1) {2971 yc = multiply(yc, n, base);2972 xc = multiply(xc, n, base);2973 yL = yc.length;2974 xL = xc.length;2975 }2976 xi = yL;2977 rem = xc.slice(0, yL);2978 remL = rem.length;2979 // Add zeros to make remainder as long as divisor.2980 for (; remL < yL; rem[remL++] = 0);2981 yz = yc.slice();2982 yz = [0].concat(yz);2983 yc0 = yc[0];2984 if (yc[1] >= base / 2) yc0++;2985 // Not necessary, but to prevent trial digit n > base, when using base 3.2986 // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;2987 do {2988 n = 0;2989 // Compare divisor and remainder.2990 cmp = compare(yc, rem, yL, remL);2991 // If divisor < remainder.2992 if (cmp < 0) {2993 // Calculate trial digit, n.2994 rem0 = rem[0];2995 if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);2996 // n is how many times the divisor goes into the current remainder.2997 n = mathfloor(rem0 / yc0);2998 // Algorithm:2999 // product = divisor multiplied by trial digit (n).3000 // Compare product and remainder.3001 // If product is greater than remainder:3002 // Subtract divisor from product, decrement trial digit.3003 // Subtract product from remainder.3004 // If product was less than remainder at the last compare:3005 // Compare new remainder and divisor.3006 // If remainder is greater than divisor:3007 // Subtract divisor from remainder, increment trial digit.3008 if (n > 1) {3009 // n may be > base only when base is 3.3010 if (n >= base) n = base - 1;3011 // product = divisor * trial digit.3012 prod = multiply(yc, n, base);3013 prodL = prod.length;3014 remL = rem.length;3015 // Compare product and remainder.3016 // If product > remainder then trial digit n too high.3017 // n is 1 too high about 5% of the time, and is not known to have3018 // ever been more than 1 too high.3019 while (compare(prod, rem, prodL, remL) == 1) {3020 n--;3021 // Subtract divisor from product.3022 subtract(prod, yL < prodL ? yz : yc, prodL, base);3023 prodL = prod.length;3024 cmp = 1;3025 }3026 } else {3027 // n is 0 or 1, cmp is -1.3028 // If n is 0, there is no need to compare yc and rem again below,3029 // so change cmp to 1 to avoid it.3030 // If n is 1, leave cmp as -1, so yc and rem are compared again.3031 if (n == 0) {3032 // divisor < remainder, so n must be at least 1.3033 cmp = n = 1;3034 }3035 // product = divisor3036 prod = yc.slice();3037 prodL = prod.length;3038 }3039 if (prodL < remL) prod = [0].concat(prod);3040 // Subtract product from remainder.3041 subtract(rem, prod, remL, base);3042 remL = rem.length;3043 // If product was < remainder.3044 if (cmp == -1) {3045 // Compare divisor and new remainder.3046 // If divisor < new remainder, subtract divisor from remainder.3047 // Trial digit n too low.3048 // n is 1 too low about 5% of the time, and very rarely 2 too low.3049 while (compare(yc, rem, yL, remL) < 1) {3050 n++;3051 // Subtract divisor from remainder.3052 subtract(rem, yL < remL ? yz : yc, remL, base);3053 remL = rem.length;3054 }3055 }3056 } else if (cmp === 0) {3057 n++;3058 rem = [0];3059 } // else cmp === 1 and n will be 03060 // Add the next digit, n, to the result array.3061 qc[i++] = n;3062 // Update the remainder.3063 if (rem[0]) {3064 rem[remL++] = xc[xi] || 0;3065 } else {3066 rem = [xc[xi]];3067 remL = 1;3068 }3069 } while ((xi++ < xL || rem[0] != null) && s--);3070 more = rem[0] != null;3071 // Leading zero?3072 if (!qc[0]) qc.splice(0, 1);3073 }3074 if (base == BASE) {3075 // To calculate q.e, first get the number of digits of qc[0].3076 for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);3077 round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);3078 // Caller is convertBase.3079 } else {3080 q.e = e;3081 q.r = +more;3082 }3083 return q;3084 };3085 })();3086 /*3087 * Return a string representing the value of BigNumber n in fixed-point or exponential3088 * notation rounded to the specified decimal places or significant digits.3089 *3090 * n: a BigNumber.3091 * i: the index of the last digit required (i.e. the digit that may be rounded up).3092 * rm: the rounding mode.3093 * id: 1 (toExponential) or 2 (toPrecision).3094 */3095 function format(n, i, rm, id) {3096 var c0, e, ne, len, str;3097 if (rm == null) rm = ROUNDING_MODE;3098 else intCheck(rm, 0, 8);3099 if (!n.c) return n.toString();3100 c0 = n.c[0];3101 ne = n.e;3102 if (i == null) {3103 str = coeffToString(n.c);3104 str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)3105 ? toExponential(str, ne)3106 : toFixedPoint(str, ne, '0');3107 } else {3108 n = round(new BigNumber(n), i, rm);3109 // n.e may have changed if the value was rounded up.3110 e = n.e;3111 str = coeffToString(n.c);3112 len = str.length;3113 // toPrecision returns exponential notation if the number of significant digits3114 // specified is less than the number of digits necessary to represent the integer3115 // part of the value in fixed-point notation.3116 // Exponential notation.3117 if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {3118 // Append zeros?3119 for (; len < i; str += '0', len++);3120 str = toExponential(str, e);3121 // Fixed-point notation.3122 } else {3123 i -= ne;3124 str = toFixedPoint(str, e, '0');3125 // Append zeros?3126 if (e + 1 > len) {3127 if (--i > 0) for (str += '.'; i--; str += '0');3128 } else {3129 i += e - len;3130 if (i > 0) {3131 if (e + 1 == len) str += '.';3132 for (; i--; str += '0');3133 }3134 }3135 }3136 }3137 return n.s < 0 && c0 ? '-' + str : str;3138 }3139 // Handle BigNumber.max and BigNumber.min.3140 function maxOrMin(args, method) {3141 var n,3142 i = 1,3143 m = new BigNumber(args[0]);3144 for (; i < args.length; i++) {3145 n = new BigNumber(args[i]);3146 // If any number is NaN, return NaN.3147 if (!n.s) {3148 m = n;3149 break;3150 } else if (method.call(m, n)) {3151 m = n;3152 }3153 }3154 return m;3155 }3156 /*3157 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.3158 * Called by minus, plus and times.3159 */3160 function normalise(n, c, e) {3161 var i = 1,3162 j = c.length;3163 // Remove trailing zeros.3164 for (; !c[--j]; c.pop());3165 // Calculate the base 10 exponent. First get the number of digits of c[0].3166 for (j = c[0]; j >= 10; j /= 10, i++);3167 // Overflow?3168 if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {3169 // Infinity.3170 n.c = n.e = null;3171 // Underflow?3172 } else if (e < MIN_EXP) {3173 // Zero.3174 n.c = [n.e = 0];3175 } else {3176 n.e = e;3177 n.c = c;3178 }3179 return n;3180 }3181 // Handle values that fail the validity test in BigNumber.3182 parseNumeric = (function () {3183 var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,3184 dotAfter = /^([^.]+)\.$/,3185 dotBefore = /^\.([^.]+)$/,3186 isInfinityOrNaN = /^-?(Infinity|NaN)$/,3187 whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;3188 return function (x, str, isNum, b) {3189 var base,3190 s = isNum ? str : str.replace(whitespaceOrPlus, '');3191 // No exception on ±Infinity or NaN.3192 if (isInfinityOrNaN.test(s)) {3193 x.s = isNaN(s) ? null : s < 0 ? -1 : 1;3194 } else {3195 if (!isNum) {3196 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i3197 s = s.replace(basePrefix, function (m, p1, p2) {3198 base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;3199 return !b || b == base ? p1 : m;3200 });3201 if (b) {3202 base = b;3203 // E.g. '1.' to '1', '.1' to '0.1'3204 s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');3205 }3206 if (str != s) return new BigNumber(s, base);3207 }3208 // '[BigNumber Error] Not a number: {n}'3209 // '[BigNumber Error] Not a base {b} number: {n}'3210 if (BigNumber.DEBUG) {3211 throw Error3212 (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);3213 }3214 // NaN3215 x.s = null;3216 }3217 x.c = x.e = null;3218 }3219 })();3220 /*3221 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.3222 * If r is truthy, it is known that there are more digits after the rounding digit.3223 */3224 function round(x, sd, rm, r) {3225 var d, i, j, k, n, ni, rd,3226 xc = x.c,3227 pows10 = POWS_TEN;3228 // if x is not Infinity or NaN...3229 if (xc) {3230 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.3231 // n is a base 1e14 number, the value of the element of array x.c containing rd.3232 // ni is the index of n within x.c.3233 // d is the number of digits of n.3234 // i is the index of rd within n including leading zeros.3235 // j is the actual index of rd within n (if < 0, rd is a leading zero).3236 out: {3237 // Get the number of digits of the first element of xc.3238 for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);3239 i = sd - d;3240 // If the rounding digit is in the first element of xc...3241 if (i < 0) {3242 i += LOG_BASE;3243 j = sd;3244 n = xc[ni = 0];3245 // Get the rounding digit at index j of n.3246 rd = n / pows10[d - j - 1] % 10 | 0;3247 } else {3248 ni = mathceil((i + 1) / LOG_BASE);3249 if (ni >= xc.length) {3250 if (r) {3251 // Needed by sqrt.3252 for (; xc.length <= ni; xc.push(0));3253 n = rd = 0;3254 d = 1;3255 i %= LOG_BASE;3256 j = i - LOG_BASE + 1;3257 } else {3258 break out;3259 }3260 } else {3261 n = k = xc[ni];3262 // Get the number of digits of n.3263 for (d = 1; k >= 10; k /= 10, d++);3264 // Get the index of rd within n.3265 i %= LOG_BASE;3266 // Get the index of rd within n, adjusted for leading zeros.3267 // The number of leading zeros of n is given by LOG_BASE - d.3268 j = i - LOG_BASE + d;3269 // Get the rounding digit at index j of n.3270 rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0;3271 }3272 }3273 r = r || sd < 0 ||3274 // Are there any non-zero digits after the rounding digit?3275 // The expression n % pows10[d - j - 1] returns all digits of n to the right3276 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.3277 xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);3278 r = rm < 43279 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))3280 : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&3281 // Check whether the digit to the left of the rounding digit is odd.3282 ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||3283 rm == (x.s < 0 ? 8 : 7));3284 if (sd < 1 || !xc[0]) {3285 xc.length = 0;3286 if (r) {3287 // Convert sd to decimal places.3288 sd -= x.e + 1;3289 // 1, 0.1, 0.01, 0.001, 0.0001 etc.3290 xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];3291 x.e = -sd || 0;3292 } else {3293 // Zero.3294 xc[0] = x.e = 0;3295 }3296 return x;3297 }3298 // Remove excess digits.3299 if (i == 0) {3300 xc.length = ni;3301 k = 1;3302 ni--;3303 } else {3304 xc.length = ni + 1;3305 k = pows10[LOG_BASE - i];3306 // E.g. 56700 becomes 56000 if 7 is the rounding digit.3307 // j > 0 means i > number of leading zeros of n.3308 xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;3309 }3310 // Round up?3311 if (r) {3312 for (; ;) {3313 // If the digit to be rounded up is in the first element of xc...3314 if (ni == 0) {3315 // i will be the length of xc[0] before k is added.3316 for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);3317 j = xc[0] += k;3318 for (k = 1; j >= 10; j /= 10, k++);3319 // if i != k the length has increased.3320 if (i != k) {3321 x.e++;3322 if (xc[0] == BASE) xc[0] = 1;3323 }3324 break;3325 } else {3326 xc[ni] += k;3327 if (xc[ni] != BASE) break;3328 xc[ni--] = 0;3329 k = 1;3330 }3331 }3332 }3333 // Remove trailing zeros.3334 for (i = xc.length; xc[--i] === 0; xc.pop());3335 }3336 // Overflow? Infinity.3337 if (x.e > MAX_EXP) {3338 x.c = x.e = null;3339 // Underflow? Zero.3340 } else if (x.e < MIN_EXP) {3341 x.c = [x.e = 0];3342 }3343 }3344 return x;3345 }3346 function valueOf(n) {3347 var str,3348 e = n.e;3349 if (e === null) return n.toString();3350 str = coeffToString(n.c);3351 str = e <= TO_EXP_NEG || e >= TO_EXP_POS3352 ? toExponential(str, e)3353 : toFixedPoint(str, e, '0');3354 return n.s < 0 ? '-' + str : str;3355 }3356 // PROTOTYPE/INSTANCE METHODS3357 /*3358 * Return a new BigNumber whose value is the absolute value of this BigNumber.3359 */3360 P.absoluteValue = P.abs = function () {3361 var x = new BigNumber(this);3362 if (x.s < 0) x.s = 1;3363 return x;3364 };3365 /*3366 * Return3367 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),3368 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),3369 * 0 if they have the same value,3370 * or null if the value of either is NaN.3371 */3372 P.comparedTo = function (y, b) {3373 return compare(this, new BigNumber(y, b));3374 };3375 /*3376 * If dp is undefined or null or true or false, return the number of decimal places of the3377 * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.3378 *3379 * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this3380 * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or3381 * ROUNDING_MODE if rm is omitted.3382 *3383 * [dp] {number} Decimal places: integer, 0 to MAX inclusive.3384 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.3385 *3386 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'3387 */3388 P.decimalPlaces = P.dp = function (dp, rm) {3389 var c, n, v,3390 x = this;3391 if (dp != null) {3392 intCheck(dp, 0, MAX);3393 if (rm == null) rm = ROUNDING_MODE;3394 else intCheck(rm, 0, 8);3395 return round(new BigNumber(x), dp + x.e + 1, rm);3396 }3397 if (!(c = x.c)) return null;3398 n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;3399 // Subtract the number of trailing zeros of the last number.3400 if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);3401 if (n < 0) n = 0;3402 return n;3403 };3404 /*3405 * n / 0 = I3406 * n / N = N3407 * n / I = 03408 * 0 / n = 03409 * 0 / 0 = N3410 * 0 / N = N3411 * 0 / I = 03412 * N / n = N3413 * N / 0 = N3414 * N / N = N3415 * N / I = N3416 * I / n = I3417 * I / 0 = I3418 * I / N = N3419 * I / I = N3420 *3421 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of3422 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.3423 */3424 P.dividedBy = P.div = function (y, b) {3425 return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);3426 };3427 /*3428 * Return a new BigNumber whose value is the integer part of dividing the value of this3429 * BigNumber by the value of BigNumber(y, b).3430 */3431 P.dividedToIntegerBy = P.idiv = function (y, b) {3432 return div(this, new BigNumber(y, b), 0, 1);3433 };3434 /*3435 * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.3436 *3437 * If m is present, return the result modulo m.3438 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.3439 * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.3440 *3441 * The modular power operation works efficiently when x, n, and m are integers, otherwise it3442 * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.3443 *3444 * n {number|string|BigNumber} The exponent. An integer.3445 * [m] {number|string|BigNumber} The modulus.3446 *3447 * '[BigNumber Error] Exponent not an integer: {n}'3448 */3449 P.exponentiatedBy = P.pow = function (n, m) {3450 var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,3451 x = this;3452 n = new BigNumber(n);3453 // Allow NaN and ±Infinity, but not other non-integers.3454 if (n.c && !n.isInteger()) {3455 throw Error3456 (bignumberError + 'Exponent not an integer: ' + valueOf(n));3457 }3458 if (m != null) m = new BigNumber(m);3459 // Exponent of MAX_SAFE_INTEGER is 15.3460 nIsBig = n.e > 14;3461 // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.3462 if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {3463 // The sign of the result of pow when x is negative depends on the evenness of n.3464 // If +n overflows to ±Infinity, the evenness of n would be not be known.3465 y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n)));3466 return m ? y.mod(m) : y;3467 }3468 nIsNeg = n.s < 0;3469 if (m) {3470 // x % m returns NaN if abs(m) is zero, or m is NaN.3471 if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);3472 isModExp = !nIsNeg && x.isInteger() && m.isInteger();3473 if (isModExp) x = x.mod(m);3474 // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.3475 // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.3476 } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 03477 // [1, 240000000]3478 ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e73479 // [80000000000000] [99999750000000]3480 : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {3481 // If x is negative and n is odd, k = -0, else k = 0.3482 k = x.s < 0 && isOdd(n) ? -0 : 0;3483 // If x >= 1, k = ±Infinity.3484 if (x.e > -1) k = 1 / k;3485 // If n is negative return ±0, else return ±Infinity.3486 return new BigNumber(nIsNeg ? 1 / k : k);3487 } else if (POW_PRECISION) {3488 // Truncating each coefficient array to a length of k after each multiplication3489 // equates to truncating significant digits to POW_PRECISION + [28, 41],3490 // i.e. there will be a minimum of 28 guard digits retained.3491 k = mathceil(POW_PRECISION / LOG_BASE + 2);3492 }3493 if (nIsBig) {3494 half = new BigNumber(0.5);3495 if (nIsNeg) n.s = 1;3496 nIsOdd = isOdd(n);3497 } else {3498 i = Math.abs(+valueOf(n));3499 nIsOdd = i % 2;3500 }3501 y = new BigNumber(ONE);3502 // Performs 54 loop iterations for n of 9007199254740991.3503 for (; ;) {3504 if (nIsOdd) {3505 y = y.times(x);3506 if (!y.c) break;3507 if (k) {3508 if (y.c.length > k) y.c.length = k;3509 } else if (isModExp) {3510 y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));3511 }3512 }3513 if (i) {3514 i = mathfloor(i / 2);3515 if (i === 0) break;3516 nIsOdd = i % 2;3517 } else {3518 n = n.times(half);3519 round(n, n.e + 1, 1);3520 if (n.e > 14) {3521 nIsOdd = isOdd(n);3522 } else {3523 i = +valueOf(n);3524 if (i === 0) break;3525 nIsOdd = i % 2;3526 }3527 }3528 x = x.times(x);3529 if (k) {3530 if (x.c && x.c.length > k) x.c.length = k;3531 } else if (isModExp) {3532 x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));3533 }3534 }3535 if (isModExp) return y;3536 if (nIsNeg) y = ONE.div(y);3537 return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;3538 };3539 /*3540 * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer3541 * using rounding mode rm, or ROUNDING_MODE if rm is omitted.3542 *3543 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.3544 *3545 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'3546 */3547 P.integerValue = function (rm) {3548 var n = new BigNumber(this);3549 if (rm == null) rm = ROUNDING_MODE;3550 else intCheck(rm, 0, 8);3551 return round(n, n.e + 1, rm);3552 };3553 /*3554 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),3555 * otherwise return false.3556 */3557 P.isEqualTo = P.eq = function (y, b) {3558 return compare(this, new BigNumber(y, b)) === 0;3559 };3560 /*3561 * Return true if the value of this BigNumber is a finite number, otherwise return false.3562 */3563 P.isFinite = function () {3564 return !!this.c;3565 };3566 /*3567 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),3568 * otherwise return false.3569 */3570 P.isGreaterThan = P.gt = function (y, b) {3571 return compare(this, new BigNumber(y, b)) > 0;3572 };3573 /*3574 * Return true if the value of this BigNumber is greater than or equal to the value of3575 * BigNumber(y, b), otherwise return false.3576 */3577 P.isGreaterThanOrEqualTo = P.gte = function (y, b) {3578 return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;3579 };3580 /*3581 * Return true if the value of this BigNumber is an integer, otherwise return false.3582 */3583 P.isInteger = function () {3584 return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;3585 };3586 /*3587 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),3588 * otherwise return false.3589 */3590 P.isLessThan = P.lt = function (y, b) {3591 return compare(this, new BigNumber(y, b)) < 0;3592 };3593 /*3594 * Return true if the value of this BigNumber is less than or equal to the value of3595 * BigNumber(y, b), otherwise return false.3596 */3597 P.isLessThanOrEqualTo = P.lte = function (y, b) {3598 return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;3599 };3600 /*3601 * Return true if the value of this BigNumber is NaN, otherwise return false.3602 */3603 P.isNaN = function () {3604 return !this.s;3605 };3606 /*3607 * Return true if the value of this BigNumber is negative, otherwise return false.3608 */3609 P.isNegative = function () {3610 return this.s < 0;3611 };3612 /*3613 * Return true if the value of this BigNumber is positive, otherwise return false.3614 */3615 P.isPositive = function () {3616 return this.s > 0;3617 };3618 /*3619 * Return true if the value of this BigNumber is 0 or -0, otherwise return false.3620 */3621 P.isZero = function () {3622 return !!this.c && this.c[0] == 0;3623 };3624 /*3625 * n - 0 = n3626 * n - N = N3627 * n - I = -I3628 * 0 - n = -n3629 * 0 - 0 = 03630 * 0 - N = N3631 * 0 - I = -I3632 * N - n = N3633 * N - 0 = N3634 * N - N = N3635 * N - I = N3636 * I - n = I3637 * I - 0 = I3638 * I - N = N3639 * I - I = N3640 *3641 * Return a new BigNumber whose value is the value of this BigNumber minus the value of3642 * BigNumber(y, b).3643 */3644 P.minus = function (y, b) {3645 var i, j, t, xLTy,3646 x = this,3647 a = x.s;3648 y = new BigNumber(y, b);3649 b = y.s;3650 // Either NaN?3651 if (!a || !b) return new BigNumber(NaN);3652 // Signs differ?3653 if (a != b) {3654 y.s = -b;3655 return x.plus(y);3656 }3657 var xe = x.e / LOG_BASE,3658 ye = y.e / LOG_BASE,3659 xc = x.c,3660 yc = y.c;3661 if (!xe || !ye) {3662 // Either Infinity?3663 if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);3664 // Either zero?3665 if (!xc[0] || !yc[0]) {3666 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.3667 return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :3668 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity3669 ROUNDING_MODE == 3 ? -0 : 0);3670 }3671 }3672 xe = bitFloor(xe);3673 ye = bitFloor(ye);3674 xc = xc.slice();3675 // Determine which is the bigger number.3676 if (a = xe - ye) {3677 if (xLTy = a < 0) {3678 a = -a;3679 t = xc;3680 } else {3681 ye = xe;3682 t = yc;3683 }3684 t.reverse();3685 // Prepend zeros to equalise exponents.3686 for (b = a; b--; t.push(0));3687 t.reverse();3688 } else {3689 // Exponents equal. Check digit by digit.3690 j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;3691 for (a = b = 0; b < j; b++) {3692 if (xc[b] != yc[b]) {3693 xLTy = xc[b] < yc[b];3694 break;3695 }3696 }3697 }3698 // x < y? Point xc to the array of the bigger number.3699 if (xLTy) {3700 t = xc;3701 xc = yc;3702 yc = t;3703 y.s = -y.s;3704 } 3705 b = (j = yc.length) - (i = xc.length);3706 // Append zeros to xc if shorter.3707 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.3708 if (b > 0) for (; b--; xc[i++] = 0);3709 b = BASE - 1;3710 // Subtract yc from xc.3711 for (; j > a;) {3712 if (xc[--j] < yc[j]) {3713 for (i = j; i && !xc[--i]; xc[i] = b);3714 --xc[i];3715 xc[j] += BASE;3716 }3717 xc[j] -= yc[j];3718 }3719 // Remove leading zeros and adjust exponent accordingly.3720 for (; xc[0] == 0; xc.splice(0, 1), --ye);3721 // Zero?3722 if (!xc[0]) {3723 // Following IEEE 754 (2008) 6.3,3724 // n - n = +0 but n - n = -0 when rounding towards -Infinity.3725 y.s = ROUNDING_MODE == 3 ? -1 : 1;3726 y.c = [y.e = 0];3727 return y;3728 }3729 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity3730 // for finite x and y.3731 return normalise(y, xc, ye);3732 };3733 /*3734 * n % 0 = N3735 * n % N = N3736 * n % I = n3737 * 0 % n = 03738 * -0 % n = -03739 * 0 % 0 = N3740 * 0 % N = N3741 * 0 % I = 03742 * N % n = N3743 * N % 0 = N3744 * N % N = N3745 * N % I = N3746 * I % n = N3747 * I % 0 = N3748 * I % N = N3749 * I % I = N3750 *3751 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of3752 * BigNumber(y, b). The result depends on the value of MODULO_MODE.3753 */3754 P.modulo = P.mod = function (y, b) {3755 var q, s,3756 x = this;3757 y = new BigNumber(y, b);3758 // Return NaN if x is Infinity or NaN, or y is NaN or zero.3759 if (!x.c || !y.s || y.c && !y.c[0]) {3760 return new BigNumber(NaN);3761 // Return x if y is Infinity or x is zero.3762 } else if (!y.c || x.c && !x.c[0]) {3763 return new BigNumber(x);3764 }3765 if (MODULO_MODE == 9) {3766 // Euclidian division: q = sign(y) * floor(x / abs(y))3767 // r = x - qy where 0 <= r < abs(y)3768 s = y.s;3769 y.s = 1;3770 q = div(x, y, 0, 3);3771 y.s = s;3772 q.s *= s;3773 } else {3774 q = div(x, y, 0, MODULO_MODE);3775 }3776 y = x.minus(q.times(y));3777 // To match JavaScript %, ensure sign of zero is sign of dividend.3778 if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;3779 return y;3780 };3781 /*3782 * n * 0 = 03783 * n * N = N3784 * n * I = I3785 * 0 * n = 03786 * 0 * 0 = 03787 * 0 * N = N3788 * 0 * I = N3789 * N * n = N3790 * N * 0 = N3791 * N * N = N3792 * N * I = N3793 * I * n = I3794 * I * 0 = N3795 * I * N = N3796 * I * I = I3797 *3798 * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value3799 * of BigNumber(y, b).3800 */3801 P.multipliedBy = P.times = function (y, b) {3802 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,3803 base, sqrtBase,3804 x = this,3805 xc = x.c,3806 yc = (y = new BigNumber(y, b)).c;3807 // Either NaN, ±Infinity or ±0?3808 if (!xc || !yc || !xc[0] || !yc[0]) {3809 // Return NaN if either is NaN, or one is 0 and the other is Infinity.3810 if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {3811 y.c = y.e = y.s = null;3812 } else {3813 y.s *= x.s;3814 // Return ±Infinity if either is ±Infinity.3815 if (!xc || !yc) {3816 y.c = y.e = null;3817 // Return ±0 if either is ±0.3818 } else {3819 y.c = [0];3820 y.e = 0;3821 }3822 }3823 return y;3824 }3825 e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);3826 y.s *= x.s;3827 xcL = xc.length;3828 ycL = yc.length;3829 // Ensure xc points to longer array and xcL to its length.3830 if (xcL < ycL) {3831 zc = xc;3832 xc = yc;3833 yc = zc;3834 i = xcL;3835 xcL = ycL;3836 ycL = i;3837 } 3838 // Initialise the result array with zeros.3839 for (i = xcL + ycL, zc = []; i--; zc.push(0));3840 base = BASE;3841 sqrtBase = SQRT_BASE;3842 for (i = ycL; --i >= 0;) {3843 c = 0;3844 ylo = yc[i] % sqrtBase;3845 yhi = yc[i] / sqrtBase | 0;3846 for (k = xcL, j = i + k; j > i;) {3847 xlo = xc[--k] % sqrtBase;3848 xhi = xc[k] / sqrtBase | 0;3849 m = yhi * xlo + xhi * ylo;3850 xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;3851 c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;3852 zc[j--] = xlo % base;3853 }3854 zc[j] = c;3855 }3856 if (c) {3857 ++e;3858 } else {3859 zc.splice(0, 1);3860 }3861 return normalise(y, zc, e);3862 };3863 /*3864 * Return a new BigNumber whose value is the value of this BigNumber negated,3865 * i.e. multiplied by -1.3866 */3867 P.negated = function () {3868 var x = new BigNumber(this);3869 x.s = -x.s || null;3870 return x;3871 };3872 /*3873 * n + 0 = n3874 * n + N = N3875 * n + I = I3876 * 0 + n = n3877 * 0 + 0 = 03878 * 0 + N = N3879 * 0 + I = I3880 * N + n = N3881 * N + 0 = N3882 * N + N = N3883 * N + I = N3884 * I + n = I3885 * I + 0 = I3886 * I + N = N3887 * I + I = I3888 *3889 * Return a new BigNumber whose value is the value of this BigNumber plus the value of3890 * BigNumber(y, b).3891 */3892 P.plus = function (y, b) {3893 var t,3894 x = this,3895 a = x.s;3896 y = new BigNumber(y, b);3897 b = y.s;3898 // Either NaN?3899 if (!a || !b) return new BigNumber(NaN);3900 // Signs differ?3901 if (a != b) {3902 y.s = -b;3903 return x.minus(y);3904 }3905 var xe = x.e / LOG_BASE,3906 ye = y.e / LOG_BASE,3907 xc = x.c,3908 yc = y.c;3909 if (!xe || !ye) {3910 // Return ±Infinity if either ±Infinity.3911 if (!xc || !yc) return new BigNumber(a / 0);3912 // Either zero?3913 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.3914 if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);3915 }3916 xe = bitFloor(xe);3917 ye = bitFloor(ye);3918 xc = xc.slice();3919 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.3920 if (a = xe - ye) {3921 if (a > 0) {3922 ye = xe;3923 t = yc;3924 } else {3925 a = -a;3926 t = xc;3927 }3928 t.reverse();3929 for (; a--; t.push(0));3930 t.reverse();3931 }3932 a = xc.length;3933 b = yc.length;3934 // Point xc to the longer array, and b to the shorter length.3935 if (a - b < 0) {3936 t = yc;3937 yc = xc;3938 xc = t;3939 b = a;3940 } 3941 // Only start adding at yc.length - 1 as the further digits of xc can be ignored.3942 for (a = 0; b;) {3943 a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;3944 xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;3945 }3946 if (a) {3947 xc = [a].concat(xc);3948 ++ye;3949 }3950 // No need to check for zero, as +x + +y != 0 && -x + -y != 03951 // ye = MAX_EXP + 1 possible3952 return normalise(y, xc, ye);3953 };3954 /*3955 * If sd is undefined or null or true or false, return the number of significant digits of3956 * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.3957 * If sd is true include integer-part trailing zeros in the count.3958 *3959 * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this3960 * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or3961 * ROUNDING_MODE if rm is omitted.3962 *3963 * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.3964 * boolean: whether to count integer-part trailing zeros: true or false.3965 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.3966 *3967 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'3968 */3969 P.precision = P.sd = function (sd, rm) {3970 var c, n, v,3971 x = this;3972 if (sd != null && sd !== !!sd) {3973 intCheck(sd, 1, MAX);3974 if (rm == null) rm = ROUNDING_MODE;3975 else intCheck(rm, 0, 8);3976 return round(new BigNumber(x), sd, rm);3977 }3978 if (!(c = x.c)) return null;3979 v = c.length - 1;3980 n = v * LOG_BASE + 1;3981 if (v = c[v]) {3982 // Subtract the number of trailing zeros of the last element.3983 for (; v % 10 == 0; v /= 10, n--);3984 // Add the number of digits of the first element.3985 for (v = c[0]; v >= 10; v /= 10, n++);3986 }3987 if (sd && x.e + 1 > n) n = x.e + 1;3988 return n;3989 };3990 /*3991 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places3992 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.3993 *3994 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.3995 *3996 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'3997 */3998 P.shiftedBy = function (k) {3999 intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);4000 return this.times('1e' + k);4001 };4002 /*4003 * sqrt(-n) = N4004 * sqrt(N) = N4005 * sqrt(-I) = N4006 * sqrt(I) = I4007 * sqrt(0) = 04008 * sqrt(-0) = -04009 *4010 * Return a new BigNumber whose value is the square root of the value of this BigNumber,4011 * rounded according to DECIMAL_PLACES and ROUNDING_MODE.4012 */4013 P.squareRoot = P.sqrt = function () {4014 var m, n, r, rep, t,4015 x = this,4016 c = x.c,4017 s = x.s,4018 e = x.e,4019 dp = DECIMAL_PLACES + 4,4020 half = new BigNumber('0.5');4021 // Negative/NaN/Infinity/zero?4022 if (s !== 1 || !c || !c[0]) {4023 return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);4024 }4025 // Initial estimate.4026 s = Math.sqrt(+valueOf(x));4027 // Math.sqrt underflow/overflow?4028 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.4029 if (s == 0 || s == 1 / 0) {4030 n = coeffToString(c);4031 if ((n.length + e) % 2 == 0) n += '0';4032 s = Math.sqrt(+n);4033 e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);4034 if (s == 1 / 0) {4035 n = '5e' + e;4036 } else {4037 n = s.toExponential();4038 n = n.slice(0, n.indexOf('e') + 1) + e;4039 }4040 r = new BigNumber(n);4041 } else {4042 r = new BigNumber(s + '');4043 }4044 // Check for zero.4045 // r could be zero if MIN_EXP is changed after the this value was created.4046 // This would cause a division by zero (x/t) and hence Infinity below, which would cause4047 // coeffToString to throw.4048 if (r.c[0]) {4049 e = r.e;4050 s = e + dp;4051 if (s < 3) s = 0;4052 // Newton-Raphson iteration.4053 for (; ;) {4054 t = r;4055 r = half.times(t.plus(div(x, t, dp, 1)));4056 if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {4057 // The exponent of r may here be one less than the final result exponent,4058 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits4059 // are indexed correctly.4060 if (r.e < e) --s;4061 n = n.slice(s - 3, s + 1);4062 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits4063 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the4064 // iteration.4065 if (n == '9999' || !rep && n == '4999') {4066 // On the first iteration only, check to see if rounding up gives the4067 // exact result as the nines may infinitely repeat.4068 if (!rep) {4069 round(t, t.e + DECIMAL_PLACES + 2, 0);4070 if (t.times(t).eq(x)) {4071 r = t;4072 break;4073 }4074 }4075 dp += 4;4076 s += 4;4077 rep = 1;4078 } else {4079 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact4080 // result. If not, then there are further digits and m will be truthy.4081 if (!+n || !+n.slice(1) && n.charAt(0) == '5') {4082 // Truncate to the first rounding digit.4083 round(r, r.e + DECIMAL_PLACES + 2, 1);4084 m = !r.times(r).eq(x);4085 }4086 break;4087 }4088 }4089 }4090 }4091 return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);4092 };4093 /*4094 * Return a string representing the value of this BigNumber in exponential notation and4095 * rounded using ROUNDING_MODE to dp fixed decimal places.4096 *4097 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.4098 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.4099 *4100 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'4101 */4102 P.toExponential = function (dp, rm) {4103 if (dp != null) {4104 intCheck(dp, 0, MAX);4105 dp++;4106 }4107 return format(this, dp, rm, 1);4108 };4109 /*4110 * Return a string representing the value of this BigNumber in fixed-point notation rounding4111 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.4112 *4113 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',4114 * but e.g. (-0.00001).toFixed(0) is '-0'.4115 *4116 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.4117 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.4118 *4119 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'4120 */4121 P.toFixed = function (dp, rm) {4122 if (dp != null) {4123 intCheck(dp, 0, MAX);4124 dp = dp + this.e + 1;4125 }4126 return format(this, dp, rm);4127 };4128 /*4129 * Return a string representing the value of this BigNumber in fixed-point notation rounded4130 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties4131 * of the format or FORMAT object (see BigNumber.set).4132 *4133 * The formatting object may contain some or all of the properties shown below.4134 *4135 * FORMAT = {4136 * prefix: '',4137 * groupSize: 3,4138 * secondaryGroupSize: 0,4139 * groupSeparator: ',',4140 * decimalSeparator: '.',4141 * fractionGroupSize: 0,4142 * fractionGroupSeparator: '\xA0', // non-breaking space4143 * suffix: ''4144 * };4145 *4146 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.4147 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.4148 * [format] {object} Formatting options. See FORMAT pbject above.4149 *4150 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'4151 * '[BigNumber Error] Argument not an object: {format}'4152 */4153 P.toFormat = function (dp, rm, format) {4154 var str,4155 x = this;4156 if (format == null) {4157 if (dp != null && rm && typeof rm == 'object') {4158 format = rm;4159 rm = null;4160 } else if (dp && typeof dp == 'object') {4161 format = dp;4162 dp = rm = null;4163 } else {4164 format = FORMAT;4165 }4166 } else if (typeof format != 'object') {4167 throw Error4168 (bignumberError + 'Argument not an object: ' + format);4169 }4170 str = x.toFixed(dp, rm);4171 if (x.c) {4172 var i,4173 arr = str.split('.'),4174 g1 = +format.groupSize,4175 g2 = +format.secondaryGroupSize,4176 groupSeparator = format.groupSeparator || '',4177 intPart = arr[0],4178 fractionPart = arr[1],4179 isNeg = x.s < 0,4180 intDigits = isNeg ? intPart.slice(1) : intPart,4181 len = intDigits.length;4182 if (g2) {4183 i = g1;4184 g1 = g2;4185 g2 = i;4186 len -= i;4187 } 4188 if (g1 > 0 && len > 0) {4189 i = len % g1 || g1;4190 intPart = intDigits.substr(0, i);4191 for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);4192 if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);4193 if (isNeg) intPart = '-' + intPart;4194 }4195 str = fractionPart4196 ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)4197 ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'),4198 '$&' + (format.fractionGroupSeparator || ''))4199 : fractionPart)4200 : intPart;4201 }4202 return (format.prefix || '') + str + (format.suffix || '');4203 };4204 /*4205 * Return an array of two BigNumbers representing the value of this BigNumber as a simple4206 * fraction with an integer numerator and an integer denominator.4207 * The denominator will be a positive non-zero value less than or equal to the specified4208 * maximum denominator. If a maximum denominator is not specified, the denominator will be4209 * the lowest value necessary to represent the number exactly.4210 *4211 * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.4212 *4213 * '[BigNumber Error] Argument {not an integer|out of range} : {md}'4214 */4215 P.toFraction = function (md) {4216 var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,4217 x = this,4218 xc = x.c;4219 if (md != null) {4220 n = new BigNumber(md);4221 // Throw if md is less than one or is not an integer, unless it is Infinity.4222 if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {4223 throw Error4224 (bignumberError + 'Argument ' +4225 (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));4226 }4227 }4228 if (!xc) return new BigNumber(x);4229 d = new BigNumber(ONE);4230 n1 = d0 = new BigNumber(ONE);4231 d1 = n0 = new BigNumber(ONE);4232 s = coeffToString(xc);4233 // Determine initial denominator.4234 // d is a power of 10 and the minimum max denominator that specifies the value exactly.4235 e = d.e = s.length - x.e - 1;4236 d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];4237 md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;4238 exp = MAX_EXP;4239 MAX_EXP = 1 / 0;4240 n = new BigNumber(s);4241 // n0 = d1 = 04242 n0.c[0] = 0;4243 for (; ;) {4244 q = div(n, d, 0, 1);4245 d2 = d0.plus(q.times(d1));4246 if (d2.comparedTo(md) == 1) break;4247 d0 = d1;4248 d1 = d2;4249 n1 = n0.plus(q.times(d2 = n1));4250 n0 = d2;4251 d = n.minus(q.times(d2 = d));4252 n = d2;4253 }4254 d2 = div(md.minus(d0), d1, 0, 1);4255 n0 = n0.plus(d2.times(n1));4256 d0 = d0.plus(d2.times(d1));4257 n0.s = n1.s = x.s;4258 e = e * 2;4259 // Determine which fraction is closer to x, n0/d0 or n1/d14260 r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(4261 div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];4262 MAX_EXP = exp;4263 return r;4264 };4265 /*4266 * Return the value of this BigNumber converted to a number primitive.4267 */4268 P.toNumber = function () {4269 return +valueOf(this);4270 };4271 /*4272 * Return a string representing the value of this BigNumber rounded to sd significant digits4273 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits4274 * necessary to represent the integer part of the value in fixed-point notation, then use4275 * exponential notation.4276 *4277 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.4278 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.4279 *4280 * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'4281 */4282 P.toPrecision = function (sd, rm) {4283 if (sd != null) intCheck(sd, 1, MAX);4284 return format(this, sd, rm, 2);4285 };4286 /*4287 * Return a string representing the value of this BigNumber in base b, or base 10 if b is4288 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and4289 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent4290 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than4291 * TO_EXP_NEG, return exponential notation.4292 *4293 * [b] {number} Integer, 2 to ALPHABET.length inclusive.4294 *4295 * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'4296 */4297 P.toString = function (b) {4298 var str,4299 n = this,4300 s = n.s,4301 e = n.e;4302 // Infinity or NaN?4303 if (e === null) {4304 if (s) {4305 str = 'Infinity';4306 if (s < 0) str = '-' + str;4307 } else {4308 str = 'NaN';4309 }4310 } else {4311 if (b == null) {4312 str = e <= TO_EXP_NEG || e >= TO_EXP_POS4313 ? toExponential(coeffToString(n.c), e)4314 : toFixedPoint(coeffToString(n.c), e, '0');4315 } else if (b === 10 && alphabetHasNormalDecimalDigits) {4316 n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);4317 str = toFixedPoint(coeffToString(n.c), n.e, '0');4318 } else {4319 intCheck(b, 2, ALPHABET.length, 'Base');4320 str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);4321 }4322 if (s < 0 && n.c[0]) str = '-' + str;4323 }4324 return str;4325 };4326 /*4327 * Return as toString, but do not accept a base argument, and include the minus sign for4328 * negative zero.4329 */4330 P.valueOf = P.toJSON = function () {4331 return valueOf(this);4332 };4333 P._isBigNumber = true;4334 if (configObject != null) BigNumber.set(configObject);4335 return BigNumber;4336 }4337 // PRIVATE HELPER FUNCTIONS4338 // These functions don't need access to variables,4339 // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.4340 function bitFloor(n) {4341 var i = n | 0;4342 return n > 0 || n === i ? i : i - 1;4343 }4344 // Return a coefficient array as a string of base 10 digits.4345 function coeffToString(a) {4346 var s, z,4347 i = 1,4348 j = a.length,4349 r = a[0] + '';4350 for (; i < j;) {4351 s = a[i++] + '';4352 z = LOG_BASE - s.length;4353 for (; z--; s = '0' + s);4354 r += s;4355 }4356 // Determine trailing zeros.4357 for (j = r.length; r.charCodeAt(--j) === 48;);4358 return r.slice(0, j + 1 || 1);4359 }4360 // Compare the value of BigNumbers x and y.4361 function compare(x, y) {4362 var a, b,4363 xc = x.c,4364 yc = y.c,4365 i = x.s,4366 j = y.s,4367 k = x.e,4368 l = y.e;4369 // Either NaN?4370 if (!i || !j) return null;4371 a = xc && !xc[0];4372 b = yc && !yc[0];4373 // Either zero?4374 if (a || b) return a ? b ? 0 : -j : i;4375 // Signs differ?4376 if (i != j) return i;4377 a = i < 0;4378 b = k == l;4379 // Either Infinity?4380 if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;4381 // Compare exponents.4382 if (!b) return k > l ^ a ? 1 : -1;4383 j = (k = xc.length) < (l = yc.length) ? k : l;4384 // Compare digit by digit.4385 for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;4386 // Compare lengths.4387 return k == l ? 0 : k > l ^ a ? 1 : -1;4388 }4389 /*4390 * Check that n is a primitive number, an integer, and in range, otherwise throw.4391 */4392 function intCheck(n, min, max, name) {4393 if (n < min || n > max || n !== mathfloor(n)) {4394 throw Error4395 (bignumberError + (name || 'Argument') + (typeof n == 'number'4396 ? n < min || n > max ? ' out of range: ' : ' not an integer: '4397 : ' not a primitive number: ') + String(n));4398 }4399 }4400 // Assumes finite n.4401 function isOdd(n) {4402 var k = n.c.length - 1;4403 return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;4404 }4405 function toExponential(str, e) {4406 return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +4407 (e < 0 ? 'e' : 'e+') + e;4408 }4409 function toFixedPoint(str, e, z) {4410 var len, zs;4411 // Negative exponent?4412 if (e < 0) {4413 // Prepend zeros.4414 for (zs = z + '.'; ++e; zs += z);4415 str = zs + str;4416 // Positive exponent4417 } else {4418 len = str.length;4419 // Append zeros.4420 if (++e > len) {4421 for (zs = z, e -= len; --e; zs += z);4422 str += zs;4423 } else if (e < len) {4424 str = str.slice(0, e) + '.' + str.slice(e);4425 }4426 }4427 return str;4428 }4429 // EXPORT4430 BigNumber = clone();4431 BigNumber['default'] = BigNumber.BigNumber = BigNumber;4432 // AMD.4433 if (typeof define == 'function' && define.amd) {4434 define(function () { return BigNumber; });4435 // Node.js and other environments that support module.exports.4436 } else if ( true && module.exports) {4437 module.exports = BigNumber;4438 // Browser.4439 } else {4440 if (!globalObject) {4441 globalObject = typeof self != 'undefined' && self ? self : window;4442 }4443 globalObject.BigNumber = BigNumber;4444 }4445})(this);4446/***/ }),4447/***/ 9239:4448/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {4449"use strict";4450/*jshint node:true */4451var Buffer = (__nccwpck_require__(4300).Buffer); // browserify4452var SlowBuffer = (__nccwpck_require__(4300).SlowBuffer);4453module.exports = bufferEq;4454function bufferEq(a, b) {4455 // shortcutting on type is necessary for correctness4456 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {4457 return false;4458 }4459 // buffer sizes should be well-known information, so despite this4460 // shortcutting, it doesn't leak any information about the *contents* of the4461 // buffers.4462 if (a.length !== b.length) {4463 return false;4464 }4465 var c = 0;4466 for (var i = 0; i < a.length; i++) {4467 /*jshint bitwise:false */4468 c |= a[i] ^ b[i]; // XOR4469 }4470 return c === 0;4471}4472bufferEq.install = function() {4473 Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {4474 return bufferEq(this, that);4475 };4476};4477var origBufEqual = Buffer.prototype.equal;4478var origSlowBufEqual = SlowBuffer.prototype.equal;4479bufferEq.restore = function() {4480 Buffer.prototype.equal = origBufEqual;4481 SlowBuffer.prototype.equal = origSlowBufEqual;4482};4483/***/ }),4484/***/ 8222:4485/***/ ((module, exports, __nccwpck_require__) => {4486/* eslint-env browser */4487/**4488 * This is the web browser implementation of `debug()`.4489 */4490exports.formatArgs = formatArgs;4491exports.save = save;4492exports.load = load;4493exports.useColors = useColors;4494exports.storage = localstorage();4495exports.destroy = (() => {4496 let warned = false;4497 return () => {4498 if (!warned) {4499 warned = true;4500 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');4501 }4502 };4503})();4504/**4505 * Colors.4506 */4507exports.colors = [4508 '#0000CC',4509 '#0000FF',4510 '#0033CC',4511 '#0033FF',4512 '#0066CC',4513 '#0066FF',4514 '#0099CC',4515 '#0099FF',4516 '#00CC00',4517 '#00CC33',4518 '#00CC66',4519 '#00CC99',4520 '#00CCCC',4521 '#00CCFF',4522 '#3300CC',4523 '#3300FF',4524 '#3333CC',4525 '#3333FF',4526 '#3366CC',4527 '#3366FF',4528 '#3399CC',4529 '#3399FF',4530 '#33CC00',4531 '#33CC33',4532 '#33CC66',4533 '#33CC99',4534 '#33CCCC',4535 '#33CCFF',4536 '#6600CC',4537 '#6600FF',4538 '#6633CC',4539 '#6633FF',4540 '#66CC00',4541 '#66CC33',4542 '#9900CC',4543 '#9900FF',4544 '#9933CC',4545 '#9933FF',4546 '#99CC00',4547 '#99CC33',4548 '#CC0000',4549 '#CC0033',4550 '#CC0066',4551 '#CC0099',4552 '#CC00CC',4553 '#CC00FF',4554 '#CC3300',4555 '#CC3333',4556 '#CC3366',4557 '#CC3399',4558 '#CC33CC',4559 '#CC33FF',4560 '#CC6600',4561 '#CC6633',4562 '#CC9900',4563 '#CC9933',4564 '#CCCC00',4565 '#CCCC33',4566 '#FF0000',4567 '#FF0033',4568 '#FF0066',4569 '#FF0099',4570 '#FF00CC',4571 '#FF00FF',4572 '#FF3300',4573 '#FF3333',4574 '#FF3366',4575 '#FF3399',4576 '#FF33CC',4577 '#FF33FF',4578 '#FF6600',4579 '#FF6633',4580 '#FF9900',4581 '#FF9933',4582 '#FFCC00',4583 '#FFCC33'4584];4585/**4586 * Currently only WebKit-based Web Inspectors, Firefox >= v31,4587 * and the Firebug extension (any Firefox version) are known4588 * to support "%c" CSS customizations.4589 *4590 * TODO: add a `localStorage` variable to explicitly enable/disable colors4591 */4592// eslint-disable-next-line complexity4593function useColors() {4594 // NB: In an Electron preload script, document will be defined but not fully4595 // initialized. Since we know we're in Chrome, we'll just detect this case4596 // explicitly4597 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {4598 return true;4599 }4600 // Internet Explorer and Edge do not support colors.4601 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {4602 return false;4603 }4604 // Is webkit? http://stackoverflow.com/a/16459606/3767734605 // document is undefined in react-native: https://github.com/facebook/react-native/pull/16324606 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||4607 // Is firebug? http://stackoverflow.com/a/398120/3767734608 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||4609 // Is firefox >= v31?4610 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages4611 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||4612 // Double check webkit in userAgent just in case we are in a worker4613 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));4614}4615/**4616 * Colorize log arguments if enabled.4617 *4618 * @api public4619 */4620function formatArgs(args) {4621 args[0] = (this.useColors ? '%c' : '') +4622 this.namespace +4623 (this.useColors ? ' %c' : ' ') +4624 args[0] +4625 (this.useColors ? '%c ' : ' ') +4626 '+' + module.exports.humanize(this.diff);4627 if (!this.useColors) {4628 return;4629 }4630 const c = 'color: ' + this.color;4631 args.splice(1, 0, c, 'color: inherit');4632 // The final "%c" is somewhat tricky, because there could be other4633 // arguments passed either before or after the %c, so we need to4634 // figure out the correct index to insert the CSS into4635 let index = 0;4636 let lastC = 0;4637 args[0].replace(/%[a-zA-Z%]/g, match => {4638 if (match === '%%') {4639 return;4640 }4641 index++;4642 if (match === '%c') {4643 // We only are interested in the *last* %c4644 // (the user may have provided their own)4645 lastC = index;4646 }4647 });4648 args.splice(lastC, 0, c);4649}4650/**4651 * Invokes `console.debug()` when available.4652 * No-op when `console.debug` is not a "function".4653 * If `console.debug` is not available, falls back4654 * to `console.log`.4655 *4656 * @api public4657 */4658exports.log = console.debug || console.log || (() => {});4659/**4660 * Save `namespaces`.4661 *4662 * @param {String} namespaces4663 * @api private4664 */4665function save(namespaces) {4666 try {4667 if (namespaces) {4668 exports.storage.setItem('debug', namespaces);4669 } else {4670 exports.storage.removeItem('debug');4671 }4672 } catch (error) {4673 // Swallow4674 // XXX (@Qix-) should we be logging these?4675 }4676}4677/**4678 * Load `namespaces`.4679 *4680 * @return {String} returns the previously persisted debug modes4681 * @api private4682 */4683function load() {4684 let r;4685 try {4686 r = exports.storage.getItem('debug');4687 } catch (error) {4688 // Swallow4689 // XXX (@Qix-) should we be logging these?4690 }4691 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG4692 if (!r && typeof process !== 'undefined' && 'env' in process) {4693 r = process.env.DEBUG;4694 }4695 return r;4696}4697/**4698 * Localstorage attempts to return the localstorage.4699 *4700 * This is necessary because safari throws4701 * when a user disables cookies/localstorage4702 * and you attempt to access it.4703 *4704 * @return {LocalStorage}4705 * @api private4706 */4707function localstorage() {4708 try {4709 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context4710 // The Browser also has localStorage in the global context.4711 return localStorage;4712 } catch (error) {4713 // Swallow4714 // XXX (@Qix-) should we be logging these?4715 }4716}4717module.exports = __nccwpck_require__(6243)(exports);4718const {formatters} = module.exports;4719/**4720 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.4721 */4722formatters.j = function (v) {4723 try {4724 return JSON.stringify(v);4725 } catch (error) {4726 return '[UnexpectedJSONParseError]: ' + error.message;4727 }4728};4729/***/ }),4730/***/ 6243:4731/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {4732/**4733 * This is the common logic for both the Node.js and web browser4734 * implementations of `debug()`.4735 */4736function setup(env) {4737 createDebug.debug = createDebug;4738 createDebug.default = createDebug;4739 createDebug.coerce = coerce;4740 createDebug.disable = disable;4741 createDebug.enable = enable;4742 createDebug.enabled = enabled;4743 createDebug.humanize = __nccwpck_require__(900);4744 createDebug.destroy = destroy;4745 Object.keys(env).forEach(key => {4746 createDebug[key] = env[key];4747 });4748 /**4749 * The currently active debug mode names, and names to skip.4750 */4751 createDebug.names = [];4752 createDebug.skips = [];4753 /**4754 * Map of special "%n" handling functions, for the debug "format" argument.4755 *4756 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".4757 */4758 createDebug.formatters = {};4759 /**4760 * Selects a color for a debug namespace4761 * @param {String} namespace The namespace string for the debug instance to be colored4762 * @return {Number|String} An ANSI color code for the given namespace4763 * @api private4764 */4765 function selectColor(namespace) {4766 let hash = 0;4767 for (let i = 0; i < namespace.length; i++) {4768 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);4769 hash |= 0; // Convert to 32bit integer4770 }4771 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];4772 }4773 createDebug.selectColor = selectColor;4774 /**4775 * Create a debugger with the given `namespace`.4776 *4777 * @param {String} namespace4778 * @return {Function}4779 * @api public4780 */4781 function createDebug(namespace) {4782 let prevTime;4783 let enableOverride = null;4784 let namespacesCache;4785 let enabledCache;4786 function debug(...args) {4787 // Disabled?4788 if (!debug.enabled) {4789 return;4790 }4791 const self = debug;4792 // Set `diff` timestamp4793 const curr = Number(new Date());4794 const ms = curr - (prevTime || curr);4795 self.diff = ms;4796 self.prev = prevTime;4797 self.curr = curr;4798 prevTime = curr;4799 args[0] = createDebug.coerce(args[0]);4800 if (typeof args[0] !== 'string') {4801 // Anything else let's inspect with %O4802 args.unshift('%O');4803 }4804 // Apply any `formatters` transformations4805 let index = 0;4806 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {4807 // If we encounter an escaped % then don't increase the array index4808 if (match === '%%') {4809 return '%';4810 }4811 index++;4812 const formatter = createDebug.formatters[format];4813 if (typeof formatter === 'function') {4814 const val = args[index];4815 match = formatter.call(self, val);4816 // Now we need to remove `args[index]` since it's inlined in the `format`4817 args.splice(index, 1);4818 index--;4819 }4820 return match;4821 });4822 // Apply env-specific formatting (colors, etc.)4823 createDebug.formatArgs.call(self, args);4824 const logFn = self.log || createDebug.log;4825 logFn.apply(self, args);4826 }4827 debug.namespace = namespace;4828 debug.useColors = createDebug.useColors();4829 debug.color = createDebug.selectColor(namespace);4830 debug.extend = extend;4831 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.4832 Object.defineProperty(debug, 'enabled', {4833 enumerable: true,4834 configurable: false,4835 get: () => {4836 if (enableOverride !== null) {4837 return enableOverride;4838 }4839 if (namespacesCache !== createDebug.namespaces) {4840 namespacesCache = createDebug.namespaces;4841 enabledCache = createDebug.enabled(namespace);4842 }4843 return enabledCache;4844 },4845 set: v => {4846 enableOverride = v;4847 }4848 });4849 // Env-specific initialization logic for debug instances4850 if (typeof createDebug.init === 'function') {4851 createDebug.init(debug);4852 }4853 return debug;4854 }4855 function extend(namespace, delimiter) {4856 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);4857 newDebug.log = this.log;4858 return newDebug;4859 }4860 /**4861 * Enables a debug mode by namespaces. This can include modes4862 * separated by a colon and wildcards.4863 *4864 * @param {String} namespaces4865 * @api public4866 */4867 function enable(namespaces) {4868 createDebug.save(namespaces);4869 createDebug.namespaces = namespaces;4870 createDebug.names = [];4871 createDebug.skips = [];4872 let i;4873 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);4874 const len = split.length;4875 for (i = 0; i < len; i++) {4876 if (!split[i]) {4877 // ignore empty strings4878 continue;4879 }4880 namespaces = split[i].replace(/\*/g, '.*?');4881 if (namespaces[0] === '-') {4882 createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));4883 } else {4884 createDebug.names.push(new RegExp('^' + namespaces + '$'));4885 }4886 }4887 }4888 /**4889 * Disable debug output.4890 *4891 * @return {String} namespaces4892 * @api public4893 */4894 function disable() {4895 const namespaces = [4896 ...createDebug.names.map(toNamespace),4897 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)4898 ].join(',');4899 createDebug.enable('');4900 return namespaces;4901 }4902 /**4903 * Returns true if the given mode name is enabled, false otherwise.4904 *4905 * @param {String} name4906 * @return {Boolean}4907 * @api public4908 */4909 function enabled(name) {4910 if (name[name.length - 1] === '*') {4911 return true;4912 }4913 let i;4914 let len;4915 for (i = 0, len = createDebug.skips.length; i < len; i++) {4916 if (createDebug.skips[i].test(name)) {4917 return false;4918 }4919 }4920 for (i = 0, len = createDebug.names.length; i < len; i++) {4921 if (createDebug.names[i].test(name)) {4922 return true;4923 }4924 }4925 return false;4926 }4927 /**4928 * Convert regexp to namespace4929 *4930 * @param {RegExp} regxep4931 * @return {String} namespace4932 * @api private4933 */4934 function toNamespace(regexp) {4935 return regexp.toString()4936 .substring(2, regexp.toString().length - 2)4937 .replace(/\.\*\?$/, '*');4938 }4939 /**4940 * Coerce `val`.4941 *4942 * @param {Mixed} val4943 * @return {Mixed}4944 * @api private4945 */4946 function coerce(val) {4947 if (val instanceof Error) {4948 return val.stack || val.message;4949 }4950 return val;4951 }4952 /**4953 * XXX DO NOT USE. This is a temporary stub function.4954 * XXX It WILL be removed in the next major release.4955 */4956 function destroy() {4957 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');4958 }4959 createDebug.enable(createDebug.load());4960 return createDebug;4961}4962module.exports = setup;4963/***/ }),4964/***/ 8237:4965/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {4966/**4967 * Detect Electron renderer / nwjs process, which is node, but we should4968 * treat as a browser.4969 */4970if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {4971 module.exports = __nccwpck_require__(8222);4972} else {4973 module.exports = __nccwpck_require__(4874);4974}4975/***/ }),4976/***/ 4874:4977/***/ ((module, exports, __nccwpck_require__) => {4978/**4979 * Module dependencies.4980 */4981const tty = __nccwpck_require__(6224);4982const util = __nccwpck_require__(3837);4983/**4984 * This is the Node.js implementation of `debug()`.4985 */4986exports.init = init;4987exports.log = log;4988exports.formatArgs = formatArgs;4989exports.save = save;4990exports.load = load;4991exports.useColors = useColors;4992exports.destroy = util.deprecate(4993 () => {},4994 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'4995);4996/**4997 * Colors.4998 */4999exports.colors = [6, 2, 3, 4, 5, 1];5000try {5001 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)5002 // eslint-disable-next-line import/no-extraneous-dependencies5003 const supportsColor = __nccwpck_require__(132);5004 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {5005 exports.colors = [5006 20,5007 21,5008 26,5009 27,5010 32,5011 33,5012 38,5013 39,5014 40,5015 41,5016 42,5017 43,5018 44,5019 45,5020 56,5021 57,5022 62,5023 63,5024 68,5025 69,5026 74,5027 75,5028 76,5029 77,5030 78,5031 79,5032 80,5033 81,5034 92,5035 93,5036 98,5037 99,5038 112,5039 113,5040 128,5041 129,5042 134,5043 135,5044 148,5045 149,5046 160,5047 161,5048 162,5049 163,5050 164,5051 165,5052 166,5053 167,5054 168,5055 169,5056 170,5057 171,5058 172,5059 173,5060 178,5061 179,5062 184,5063 185,5064 196,5065 197,5066 198,5067 199,5068 200,5069 201,5070 202,5071 203,5072 204,5073 205,5074 206,5075 207,5076 208,5077 209,5078 214,5079 215,5080 220,5081 2215082 ];5083 }5084} catch (error) {5085 // Swallow - we only care if `supports-color` is available; it doesn't have to be.5086}5087/**5088 * Build up the default `inspectOpts` object from the environment variables.5089 *5090 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js5091 */5092exports.inspectOpts = Object.keys(process.env).filter(key => {5093 return /^debug_/i.test(key);5094}).reduce((obj, key) => {5095 // Camel-case5096 const prop = key5097 .substring(6)5098 .toLowerCase()5099 .replace(/_([a-z])/g, (_, k) => {5100 return k.toUpperCase();5101 });5102 // Coerce string value into JS value5103 let val = process.env[key];5104 if (/^(yes|on|true|enabled)$/i.test(val)) {5105 val = true;5106 } else if (/^(no|off|false|disabled)$/i.test(val)) {5107 val = false;5108 } else if (val === 'null') {5109 val = null;5110 } else {5111 val = Number(val);5112 }5113 obj[prop] = val;5114 return obj;5115}, {});5116/**5117 * Is stdout a TTY? Colored output is enabled when `true`.5118 */5119function useColors() {5120 return 'colors' in exports.inspectOpts ?5121 Boolean(exports.inspectOpts.colors) :5122 tty.isatty(process.stderr.fd);5123}5124/**5125 * Adds ANSI color escape codes if enabled.5126 *5127 * @api public5128 */5129function formatArgs(args) {5130 const {namespace: name, useColors} = this;5131 if (useColors) {5132 const c = this.color;5133 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);5134 const prefix = ` ${colorCode};1m${name} \u001B[0m`;5135 args[0] = prefix + args[0].split('\n').join('\n' + prefix);5136 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');5137 } else {5138 args[0] = getDate() + name + ' ' + args[0];5139 }5140}5141function getDate() {5142 if (exports.inspectOpts.hideDate) {5143 return '';5144 }5145 return new Date().toISOString() + ' ';5146}5147/**5148 * Invokes `util.format()` with the specified arguments and writes to stderr.5149 */5150function log(...args) {5151 return process.stderr.write(util.format(...args) + '\n');5152}5153/**5154 * Save `namespaces`.5155 *5156 * @param {String} namespaces5157 * @api private5158 */5159function save(namespaces) {5160 if (namespaces) {5161 process.env.DEBUG = namespaces;5162 } else {5163 // If you set a process.env field to null or undefined, it gets cast to the5164 // string 'null' or 'undefined'. Just delete instead.5165 delete process.env.DEBUG;5166 }5167}5168/**5169 * Load `namespaces`.5170 *5171 * @return {String} returns the previously persisted debug modes5172 * @api private5173 */5174function load() {5175 return process.env.DEBUG;5176}5177/**5178 * Init logic for `debug` instances.5179 *5180 * Create a new `inspectOpts` object in case `useColors` is set5181 * differently for a particular `debug` instance.5182 */5183function init(debug) {5184 debug.inspectOpts = {};5185 const keys = Object.keys(exports.inspectOpts);5186 for (let i = 0; i < keys.length; i++) {5187 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];5188 }5189}5190module.exports = __nccwpck_require__(6243)(exports);5191const {formatters} = module.exports;5192/**5193 * Map %o to `util.inspect()`, all on a single line.5194 */5195formatters.o = function (v) {5196 this.inspectOpts.colors = this.useColors;5197 return util.inspect(v, this.inspectOpts)5198 .split('\n')5199 .map(str => str.trim())5200 .join(' ');5201};5202/**5203 * Map %O to `util.inspect()`, allowing multiple lines if needed.5204 */5205formatters.O = function (v) {5206 this.inspectOpts.colors = this.useColors;5207 return util.inspect(v, this.inspectOpts);5208};5209/***/ }),5210/***/ 2437:5211/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {5212const fs = __nccwpck_require__(7147)5213const path = __nccwpck_require__(1017)5214const os = __nccwpck_require__(2037)5215const packageJson = __nccwpck_require__(9968)5216const version = packageJson.version5217const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg5218// Parser src into an Object5219function parse (src) {5220 const obj = {}5221 // Convert buffer to string5222 let lines = src.toString()5223 // Convert line breaks to same format5224 lines = lines.replace(/\r\n?/mg, '\n')5225 let match5226 while ((match = LINE.exec(lines)) != null) {5227 const key = match[1]5228 // Default undefined or null to empty string5229 let value = (match[2] || '')5230 // Remove whitespace5231 value = value.trim()5232 // Check if double quoted5233 const maybeQuote = value[0]5234 // Remove surrounding quotes5235 value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2')5236 // Expand newlines if double quoted5237 if (maybeQuote === '"') {5238 value = value.replace(/\\n/g, '\n')5239 value = value.replace(/\\r/g, '\r')5240 }5241 // Add to object5242 obj[key] = value5243 }5244 return obj5245}5246function _log (message) {5247 console.log(`[dotenv@${version}][DEBUG] ${message}`)5248}5249function _resolveHome (envPath) {5250 return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath5251}5252// Populates process.env from .env file5253function config (options) {5254 let dotenvPath = path.resolve(process.cwd(), '.env')5255 let encoding = 'utf8'5256 const debug = Boolean(options && options.debug)5257 const override = Boolean(options && options.override)5258 if (options) {5259 if (options.path != null) {5260 dotenvPath = _resolveHome(options.path)5261 }5262 if (options.encoding != null) {5263 encoding = options.encoding5264 }5265 }5266 try {5267 // Specifying an encoding returns a string instead of a buffer5268 const parsed = DotenvModule.parse(fs.readFileSync(dotenvPath, { encoding }))5269 Object.keys(parsed).forEach(function (key) {5270 if (!Object.prototype.hasOwnProperty.call(process.env, key)) {5271 process.env[key] = parsed[key]5272 } else {5273 if (override === true) {5274 process.env[key] = parsed[key]5275 }5276 if (debug) {5277 if (override === true) {5278 _log(`"${key}" is already defined in \`process.env\` and WAS overwritten`)5279 } else {5280 _log(`"${key}" is already defined in \`process.env\` and was NOT overwritten`)5281 }5282 }5283 }5284 })5285 return { parsed }5286 } catch (e) {5287 if (debug) {5288 _log(`Failed to load ${dotenvPath} ${e.message}`)5289 }5290 return { error: e }5291 }5292}5293const DotenvModule = {5294 config,5295 parse5296}5297module.exports.config = DotenvModule.config5298module.exports.parse = DotenvModule.parse5299module.exports = DotenvModule5300/***/ }),5301/***/ 1728:5302/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {5303"use strict";5304var Buffer = (__nccwpck_require__(1867).Buffer);5305var getParamBytesForAlg = __nccwpck_require__(528);5306var MAX_OCTET = 0x80,5307 CLASS_UNIVERSAL = 0,5308 PRIMITIVE_BIT = 0x20,5309 TAG_SEQ = 0x10,5310 TAG_INT = 0x02,5311 ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6),5312 ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6);5313function base64Url(base64) {5314 return base645315 .replace(/=/g, '')5316 .replace(/\+/g, '-')5317 .replace(/\//g, '_');5318}5319function signatureAsBuffer(signature) {5320 if (Buffer.isBuffer(signature)) {5321 return signature;5322 } else if ('string' === typeof signature) {5323 return Buffer.from(signature, 'base64');5324 }5325 throw new TypeError('ECDSA signature must be a Base64 string or a Buffer');5326}5327function derToJose(signature, alg) {5328 signature = signatureAsBuffer(signature);5329 var paramBytes = getParamBytesForAlg(alg);5330 // the DER encoded param should at most be the param size, plus a padding5331 // zero, since due to being a signed integer5332 var maxEncodedParamLength = paramBytes + 1;5333 var inputLength = signature.length;5334 var offset = 0;5335 if (signature[offset++] !== ENCODED_TAG_SEQ) {5336 throw new Error('Could not find expected "seq"');5337 }5338 var seqLength = signature[offset++];5339 if (seqLength === (MAX_OCTET | 1)) {5340 seqLength = signature[offset++];5341 }5342 if (inputLength - offset < seqLength) {5343 throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining');5344 }5345 if (signature[offset++] !== ENCODED_TAG_INT) {5346 throw new Error('Could not find expected "int" for "r"');5347 }5348 var rLength = signature[offset++];5349 if (inputLength - offset - 2 < rLength) {5350 throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available');5351 }5352 if (maxEncodedParamLength < rLength) {5353 throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable');5354 }5355 var rOffset = offset;5356 offset += rLength;5357 if (signature[offset++] !== ENCODED_TAG_INT) {5358 throw new Error('Could not find expected "int" for "s"');5359 }5360 var sLength = signature[offset++];5361 if (inputLength - offset !== sLength) {5362 throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"');5363 }5364 if (maxEncodedParamLength < sLength) {5365 throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable');5366 }5367 var sOffset = offset;5368 offset += sLength;5369 if (offset !== inputLength) {5370 throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain');5371 }5372 var rPadding = paramBytes - rLength,5373 sPadding = paramBytes - sLength;5374 var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);5375 for (offset = 0; offset < rPadding; ++offset) {5376 dst[offset] = 0;5377 }5378 signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);5379 offset = paramBytes;5380 for (var o = offset; offset < o + sPadding; ++offset) {5381 dst[offset] = 0;5382 }5383 signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);5384 dst = dst.toString('base64');5385 dst = base64Url(dst);5386 return dst;5387}5388function countPadding(buf, start, stop) {5389 var padding = 0;5390 while (start + padding < stop && buf[start + padding] === 0) {5391 ++padding;5392 }5393 var needsSign = buf[start + padding] >= MAX_OCTET;5394 if (needsSign) {5395 --padding;5396 }5397 return padding;5398}5399function joseToDer(signature, alg) {5400 signature = signatureAsBuffer(signature);5401 var paramBytes = getParamBytesForAlg(alg);5402 var signatureBytes = signature.length;5403 if (signatureBytes !== paramBytes * 2) {5404 throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"');5405 }5406 var rPadding = countPadding(signature, 0, paramBytes);5407 var sPadding = countPadding(signature, paramBytes, signature.length);5408 var rLength = paramBytes - rPadding;5409 var sLength = paramBytes - sPadding;5410 var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;5411 var shortLength = rsBytes < MAX_OCTET;5412 var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);5413 var offset = 0;5414 dst[offset++] = ENCODED_TAG_SEQ;5415 if (shortLength) {5416 // Bit 8 has value "0"5417 // bits 7-1 give the length.5418 dst[offset++] = rsBytes;5419 } else {5420 // Bit 8 of first octet has value "1"5421 // bits 7-1 give the number of additional length octets.5422 dst[offset++] = MAX_OCTET | 1;5423 // length, base 2565424 dst[offset++] = rsBytes & 0xff;5425 }5426 dst[offset++] = ENCODED_TAG_INT;5427 dst[offset++] = rLength;5428 if (rPadding < 0) {5429 dst[offset++] = 0;5430 offset += signature.copy(dst, offset, 0, paramBytes);5431 } else {5432 offset += signature.copy(dst, offset, rPadding, paramBytes);5433 }5434 dst[offset++] = ENCODED_TAG_INT;5435 dst[offset++] = sLength;5436 if (sPadding < 0) {5437 dst[offset++] = 0;5438 signature.copy(dst, offset, paramBytes);5439 } else {5440 signature.copy(dst, offset, paramBytes + sPadding);5441 }5442 return dst;5443}5444module.exports = {5445 derToJose: derToJose,5446 joseToDer: joseToDer5447};5448/***/ }),5449/***/ 528:5450/***/ ((module) => {5451"use strict";5452function getParamSize(keySize) {5453 var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1);5454 return result;5455}5456var paramBytesForAlg = {5457 ES256: getParamSize(256),5458 ES384: getParamSize(384),5459 ES512: getParamSize(521)5460};5461function getParamBytesForAlg(alg) {5462 var paramBytes = paramBytesForAlg[alg];5463 if (paramBytes) {5464 return paramBytes;5465 }5466 throw new Error('Unknown algorithm "' + alg + '"');5467}5468module.exports = getParamBytesForAlg;5469/***/ }),5470/***/ 8171:5471/***/ ((module) => {5472"use strict";5473var hasOwn = Object.prototype.hasOwnProperty;5474var toStr = Object.prototype.toString;5475var defineProperty = Object.defineProperty;5476var gOPD = Object.getOwnPropertyDescriptor;5477var isArray = function isArray(arr) {5478 if (typeof Array.isArray === 'function') {5479 return Array.isArray(arr);5480 }5481 return toStr.call(arr) === '[object Array]';5482};5483var isPlainObject = function isPlainObject(obj) {5484 if (!obj || toStr.call(obj) !== '[object Object]') {5485 return false;5486 }5487 var hasOwnConstructor = hasOwn.call(obj, 'constructor');5488 var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');5489 // Not own constructor property must be Object5490 if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {5491 return false;5492 }5493 // Own properties are enumerated firstly, so to speed up,5494 // if last one is own, then all properties are own.5495 var key;5496 for (key in obj) { /**/ }5497 return typeof key === 'undefined' || hasOwn.call(obj, key);5498};5499// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target5500var setProperty = function setProperty(target, options) {5501 if (defineProperty && options.name === '__proto__') {5502 defineProperty(target, options.name, {5503 enumerable: true,5504 configurable: true,5505 value: options.newValue,5506 writable: true5507 });5508 } else {5509 target[options.name] = options.newValue;5510 }5511};5512// Return undefined instead of __proto__ if '__proto__' is not an own property5513var getProperty = function getProperty(obj, name) {5514 if (name === '__proto__') {5515 if (!hasOwn.call(obj, name)) {5516 return void 0;5517 } else if (gOPD) {5518 // In early versions of node, obj['__proto__'] is buggy when obj has5519 // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.5520 return gOPD(obj, name).value;5521 }5522 }5523 return obj[name];5524};5525module.exports = function extend() {5526 var options, name, src, copy, copyIsArray, clone;5527 var target = arguments[0];5528 var i = 1;5529 var length = arguments.length;5530 var deep = false;5531 // Handle a deep copy situation5532 if (typeof target === 'boolean') {5533 deep = target;5534 target = arguments[1] || {};5535 // skip the boolean and the target5536 i = 2;5537 }5538 if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {5539 target = {};5540 }5541 for (; i < length; ++i) {5542 options = arguments[i];5543 // Only deal with non-null/undefined values5544 if (options != null) {5545 // Extend the base object5546 for (name in options) {5547 src = getProperty(target, name);5548 copy = getProperty(options, name);5549 // Prevent never-ending loop5550 if (target !== copy) {5551 // Recurse if we're merging plain objects or arrays5552 if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {5553 if (copyIsArray) {5554 copyIsArray = false;5555 clone = src && isArray(src) ? src : [];5556 } else {5557 clone = src && isPlainObject(src) ? src : {};5558 }5559 // Never move original objects, clone them5560 setProperty(target, { name: name, newValue: extend(deep, clone, copy) });5561 // Don't bring in undefined values5562 } else if (typeof copy !== 'undefined') {5563 setProperty(target, { name: name, newValue: copy });5564 }5565 }5566 }5567 }5568 }5569 // Return the modified object5570 return target;5571};5572/***/ }),5573/***/ 1917:5574/***/ (function() {5575(function(scope) {'use strict';5576function B(r,e){var f;return r instanceof Buffer?f=r:f=Buffer.from(r.buffer,r.byteOffset,r.byteLength),f.toString(e)}var w=function(r){return Buffer.from(r)};function h(r){for(var e=0,f=Math.min(256*256,r.length+1),n=new Uint16Array(f),i=[],o=0;;){var t=e<r.length;if(!t||o>=f-1){var s=n.subarray(0,o),m=s;if(i.push(String.fromCharCode.apply(null,m)),!t)return i.join("");r=r.subarray(e),e=0,o=0}var a=r[e++];if((a&128)===0)n[o++]=a;else if((a&224)===192){var d=r[e++]&63;n[o++]=(a&31)<<6|d}else if((a&240)===224){var d=r[e++]&63,l=r[e++]&63;n[o++]=(a&31)<<12|d<<6|l}else if((a&248)===240){var d=r[e++]&63,l=r[e++]&63,R=r[e++]&63,c=(a&7)<<18|d<<12|l<<6|R;c>65535&&(c-=65536,n[o++]=c>>>10&1023|55296,c=56320|c&1023),n[o++]=c}}}function F(r){for(var e=0,f=r.length,n=0,i=Math.max(32,f+(f>>>1)+7),o=new Uint8Array(i>>>3<<3);e<f;){var t=r.charCodeAt(e++);if(t>=55296&&t<=56319){if(e<f){var s=r.charCodeAt(e);(s&64512)===56320&&(++e,t=((t&1023)<<10)+(s&1023)+65536)}if(t>=55296&&t<=56319)continue}if(n+4>o.length){i+=8,i*=1+e/r.length*2,i=i>>>3<<3;var m=new Uint8Array(i);m.set(o),o=m}if((t&4294967168)===0){o[n++]=t;continue}else if((t&4294965248)===0)o[n++]=t>>>6&31|192;else if((t&4294901760)===0)o[n++]=t>>>12&15|224,o[n++]=t>>>6&63|128;else if((t&4292870144)===0)o[n++]=t>>>18&7|240,o[n++]=t>>>12&63|128,o[n++]=t>>>6&63|128;else continue;o[n++]=t&63|128}return o.slice?o.slice(0,n):o.subarray(0,n)}var u="Failed to ",p=function(r,e,f){if(r)throw new Error("".concat(u).concat(e,": the '").concat(f,"' option is unsupported."))};var x=typeof Buffer=="function"&&Buffer.from;var A=x?w:F;function v(){this.encoding="utf-8"}v.prototype.encode=function(r,e){return p(e&&e.stream,"encode","stream"),A(r)};function U(r){var e;try{var f=new Blob([r],{type:"text/plain;charset=UTF-8"});e=URL.createObjectURL(f);var n=new XMLHttpRequest;return n.open("GET",e,!1),n.send(),n.responseText}finally{e&&URL.revokeObjectURL(e)}}var O=!x&&typeof Blob=="function"&&typeof URL=="function"&&typeof URL.createObjectURL=="function",S=["utf-8","utf8","unicode-1-1-utf-8"],T=h;x?T=B:O&&(T=function(r){try{return U(r)}catch(e){return h(r)}});var y="construct 'TextDecoder'",E="".concat(u," ").concat(y,": the ");function g(r,e){p(e&&e.fatal,y,"fatal"),r=r||"utf-8";var f;if(x?f=Buffer.isEncoding(r):f=S.indexOf(r.toLowerCase())!==-1,!f)throw new RangeError("".concat(E," encoding label provided ('").concat(r,"') is invalid."));this.encoding=r,this.fatal=!1,this.ignoreBOM=!1}g.prototype.decode=function(r,e){p(e&&e.stream,"decode","stream");var f;return r instanceof Uint8Array?f=r:r.buffer instanceof ArrayBuffer?f=new Uint8Array(r.buffer):f=new Uint8Array(r),T(f,this.encoding)};scope.TextEncoder=scope.TextEncoder||v;scope.TextDecoder=scope.TextDecoder||g;5577}(typeof window !== 'undefined' ? window : (typeof global !== 'undefined' ? global : this)));5578/***/ }),5579/***/ 6129:5580/***/ ((__unused_webpack_module, exports) => {5581"use strict";5582// Copyright 2018 Google LLC5583// Licensed under the Apache License, Version 2.0 (the "License");5584// you may not use this file except in compliance with the License.5585// You may obtain a copy of the License at5586//5587// http://www.apache.org/licenses/LICENSE-2.05588//5589// Unless required by applicable law or agreed to in writing, software5590// distributed under the License is distributed on an "AS IS" BASIS,5591// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.5592// See the License for the specific language governing permissions and5593// limitations under the License.5594Object.defineProperty(exports, "__esModule", ({ value: true }));5595exports.GaxiosError = void 0;5596/* eslint-disable @typescript-eslint/no-explicit-any */5597class GaxiosError extends Error {5598 constructor(message, options, response) {5599 super(message);5600 this.response = response;5601 this.config = options;5602 this.code = response.status.toString();5603 }5604}5605exports.GaxiosError = GaxiosError;5606//# sourceMappingURL=common.js.map5607/***/ }),5608/***/ 8133:5609/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {5610"use strict";5611// Copyright 2018 Google LLC5612// Licensed under the Apache License, Version 2.0 (the "License");5613// you may not use this file except in compliance with the License.5614// You may obtain a copy of the License at5615//5616// http://www.apache.org/licenses/LICENSE-2.05617//5618// Unless required by applicable law or agreed to in writing, software5619// distributed under the License is distributed on an "AS IS" BASIS,5620// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.5621// See the License for the specific language governing permissions and5622// limitations under the License.5623var __importDefault = (this && this.__importDefault) || function (mod) {5624 return (mod && mod.__esModule) ? mod : { "default": mod };5625};5626Object.defineProperty(exports, "__esModule", ({ value: true }));5627exports.Gaxios = void 0;5628const extend_1 = __importDefault(__nccwpck_require__(8171));5629const https_1 = __nccwpck_require__(5687);5630const node_fetch_1 = __importDefault(__nccwpck_require__(467));5631const querystring_1 = __importDefault(__nccwpck_require__(3477));5632const is_stream_1 = __importDefault(__nccwpck_require__(1554));5633const url_1 = __nccwpck_require__(7310);5634const common_1 = __nccwpck_require__(6129);5635const retry_1 = __nccwpck_require__(1052);5636/* eslint-disable @typescript-eslint/no-explicit-any */5637const fetch = hasFetch() ? window.fetch : node_fetch_1.default;5638function hasWindow() {5639 return typeof window !== 'undefined' && !!window;5640}5641function hasFetch() {5642 return hasWindow() && !!window.fetch;5643}5644function hasBuffer() {5645 return typeof Buffer !== 'undefined';5646}5647function hasHeader(options, header) {5648 return !!getHeader(options, header);5649}5650function getHeader(options, header) {5651 header = header.toLowerCase();5652 for (const key of Object.keys((options === null || options === void 0 ? void 0 : options.headers) || {})) {5653 if (header === key.toLowerCase()) {5654 return options.headers[key];5655 }5656 }5657 return undefined;5658}5659let HttpsProxyAgent;5660function loadProxy() {5661 var _a, _b, _c, _d;5662 const proxy = ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.HTTPS_PROXY) ||5663 ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.https_proxy) ||5664 ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c.HTTP_PROXY) ||5665 ((_d = process === null || process === void 0 ? void 0 : process.env) === null || _d === void 0 ? void 0 : _d.http_proxy);5666 if (proxy) {5667 HttpsProxyAgent = __nccwpck_require__(7219);5668 }5669 return proxy;5670}5671loadProxy();5672function skipProxy(url) {5673 var _a;5674 const noProxyEnv = (_a = process.env.NO_PROXY) !== null && _a !== void 0 ? _a : process.env.no_proxy;5675 if (!noProxyEnv) {5676 return false;5677 }5678 const noProxyUrls = noProxyEnv.split(',');5679 const parsedURL = new url_1.URL(url);5680 return !!noProxyUrls.find(url => {5681 if (url.startsWith('*.') || url.startsWith('.')) {5682 url = url.replace(/^\*\./, '.');5683 return parsedURL.hostname.endsWith(url);5684 }5685 else {5686 return url === parsedURL.origin || url === parsedURL.hostname;5687 }5688 });5689}5690// Figure out if we should be using a proxy. Only if it's required, load5691// the https-proxy-agent module as it adds startup cost.5692function getProxy(url) {5693 // If there is a match between the no_proxy env variables and the url, then do not proxy5694 if (skipProxy(url)) {5695 return undefined;5696 // If there is not a match between the no_proxy env variables and the url, check to see if there should be a proxy5697 }5698 else {5699 return loadProxy();5700 }5701}5702class Gaxios {5703 /**5704 * The Gaxios class is responsible for making HTTP requests.5705 * @param defaults The default set of options to be used for this instance.5706 */5707 constructor(defaults) {5708 this.agentCache = new Map();5709 this.defaults = defaults || {};5710 }5711 /**5712 * Perform an HTTP request with the given options.5713 * @param opts Set of HTTP options that will be used for this HTTP request.5714 */5715 async request(opts = {}) {5716 opts = this.validateOpts(opts);5717 return this._request(opts);5718 }5719 async _defaultAdapter(opts) {5720 const fetchImpl = opts.fetchImplementation || fetch;5721 const res = (await fetchImpl(opts.url, opts));5722 const data = await this.getResponseData(opts, res);5723 return this.translateResponse(opts, res, data);5724 }5725 /**5726 * Internal, retryable version of the `request` method.5727 * @param opts Set of HTTP options that will be used for this HTTP request.5728 */5729 async _request(opts = {}) {5730 try {5731 let translatedResponse;5732 if (opts.adapter) {5733 translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this));5734 }5735 else {5736 translatedResponse = await this._defaultAdapter(opts);5737 }5738 if (!opts.validateStatus(translatedResponse.status)) {5739 throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse);5740 }5741 return translatedResponse;5742 }5743 catch (e) {5744 const err = e;5745 err.config = opts;5746 const { shouldRetry, config } = await (0, retry_1.getRetryConfig)(err);5747 if (shouldRetry && config) {5748 err.config.retryConfig.currentRetryAttempt =5749 config.retryConfig.currentRetryAttempt;5750 return this._request(err.config);5751 }5752 throw err;5753 }5754 }5755 async getResponseData(opts, res) {5756 switch (opts.responseType) {5757 case 'stream':5758 return res.body;5759 case 'json': {5760 let data = await res.text();5761 try {5762 data = JSON.parse(data);5763 }5764 catch (_a) {5765 // continue5766 }5767 return data;5768 }5769 case 'arraybuffer':5770 return res.arrayBuffer();5771 case 'blob':5772 return res.blob();5773 default:5774 return res.text();5775 }5776 }5777 /**5778 * Validates the options, and merges them with defaults.5779 * @param opts The original options passed from the client.5780 */5781 validateOpts(options) {5782 const opts = (0, extend_1.default)(true, {}, this.defaults, options);5783 if (!opts.url) {5784 throw new Error('URL is required.');5785 }5786 // baseUrl has been deprecated, remove in 2.05787 const baseUrl = opts.baseUrl || opts.baseURL;5788 if (baseUrl) {5789 opts.url = baseUrl + opts.url;5790 }5791 opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer;5792 if (opts.params && Object.keys(opts.params).length > 0) {5793 let additionalQueryParams = opts.paramsSerializer(opts.params);5794 if (additionalQueryParams.startsWith('?')) {5795 additionalQueryParams = additionalQueryParams.slice(1);5796 }5797 const prefix = opts.url.includes('?') ? '&' : '?';5798 opts.url = opts.url + prefix + additionalQueryParams;5799 }5800 if (typeof options.maxContentLength === 'number') {5801 opts.size = options.maxContentLength;5802 }5803 if (typeof options.maxRedirects === 'number') {5804 opts.follow = options.maxRedirects;5805 }5806 opts.headers = opts.headers || {};5807 if (opts.data) {5808 const isFormData = typeof FormData === 'undefined'5809 ? false5810 : (opts === null || opts === void 0 ? void 0 : opts.data) instanceof FormData;5811 if (is_stream_1.default.readable(opts.data)) {5812 opts.body = opts.data;5813 }5814 else if (hasBuffer() && Buffer.isBuffer(opts.data)) {5815 // Do not attempt to JSON.stringify() a Buffer:5816 opts.body = opts.data;5817 if (!hasHeader(opts, 'Content-Type')) {5818 opts.headers['Content-Type'] = 'application/json';5819 }5820 }5821 else if (typeof opts.data === 'object') {5822 // If www-form-urlencoded content type has been set, but data is5823 // provided as an object, serialize the content using querystring:5824 if (!isFormData) {5825 if (getHeader(opts, 'content-type') ===5826 'application/x-www-form-urlencoded') {5827 opts.body = opts.paramsSerializer(opts.data);5828 }5829 else {5830 // } else if (!(opts.data instanceof FormData)) {5831 if (!hasHeader(opts, 'Content-Type')) {5832 opts.headers['Content-Type'] = 'application/json';5833 }5834 opts.body = JSON.stringify(opts.data);5835 }5836 }5837 }5838 else {5839 opts.body = opts.data;5840 }5841 }5842 opts.validateStatus = opts.validateStatus || this.validateStatus;5843 opts.responseType = opts.responseType || 'json';5844 if (!opts.headers['Accept'] && opts.responseType === 'json') {5845 opts.headers['Accept'] = 'application/json';5846 }5847 opts.method = opts.method || 'GET';5848 const proxy = getProxy(opts.url);5849 if (proxy) {5850 if (this.agentCache.has(proxy)) {5851 opts.agent = this.agentCache.get(proxy);5852 }5853 else {5854 // Proxy is being used in conjunction with mTLS.5855 if (opts.cert && opts.key) {5856 const parsedURL = new url_1.URL(proxy);5857 opts.agent = new HttpsProxyAgent({5858 port: parsedURL.port,5859 host: parsedURL.host,5860 protocol: parsedURL.protocol,5861 cert: opts.cert,5862 key: opts.key,5863 });5864 }5865 else {5866 opts.agent = new HttpsProxyAgent(proxy);5867 }5868 this.agentCache.set(proxy, opts.agent);5869 }5870 }5871 else if (opts.cert && opts.key) {5872 // Configure client for mTLS:5873 if (this.agentCache.has(opts.key)) {5874 opts.agent = this.agentCache.get(opts.key);5875 }5876 else {5877 opts.agent = new https_1.Agent({5878 cert: opts.cert,5879 key: opts.key,5880 });5881 this.agentCache.set(opts.key, opts.agent);5882 }5883 }5884 return opts;5885 }5886 /**5887 * By default, throw for any non-2xx status code5888 * @param status status code from the HTTP response5889 */5890 validateStatus(status) {5891 return status >= 200 && status < 300;5892 }5893 /**5894 * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo)5895 * @param params key value pars to encode5896 */5897 paramsSerializer(params) {5898 return querystring_1.default.stringify(params);5899 }5900 translateResponse(opts, res, data) {5901 // headers need to be converted from a map to an obj5902 const headers = {};5903 res.headers.forEach((value, key) => {5904 headers[key] = value;5905 });5906 return {5907 config: opts,5908 data: data,5909 headers,5910 status: res.status,5911 statusText: res.statusText,5912 // XMLHttpRequestLike5913 request: {5914 responseURL: res.url,5915 },5916 };5917 }5918}5919exports.Gaxios = Gaxios;5920//# sourceMappingURL=gaxios.js.map5921/***/ }),5922/***/ 9555:5923/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {5924"use strict";5925// Copyright 2018 Google LLC5926// Licensed under the Apache License, Version 2.0 (the "License");5927// you may not use this file except in compliance with the License.5928// You may obtain a copy of the License at5929//5930// http://www.apache.org/licenses/LICENSE-2.05931//5932// Unless required by applicable law or agreed to in writing, software5933// distributed under the License is distributed on an "AS IS" BASIS,5934// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.5935// See the License for the specific language governing permissions and5936// limitations under the License.5937Object.defineProperty(exports, "__esModule", ({ value: true }));5938exports.request = exports.instance = exports.Gaxios = exports.GaxiosError = void 0;5939const gaxios_1 = __nccwpck_require__(8133);5940Object.defineProperty(exports, "Gaxios", ({ enumerable: true, get: function () { return gaxios_1.Gaxios; } }));5941var common_1 = __nccwpck_require__(6129);5942Object.defineProperty(exports, "GaxiosError", ({ enumerable: true, get: function () { return common_1.GaxiosError; } }));5943/**5944 * The default instance used when the `request` method is directly5945 * invoked.5946 */5947exports.instance = new gaxios_1.Gaxios();5948/**5949 * Make an HTTP request using the given options.5950 * @param opts Options for the request5951 */5952async function request(opts) {5953 return exports.instance.request(opts);5954}5955exports.request = request;5956//# sourceMappingURL=index.js.map5957/***/ }),5958/***/ 1052:5959/***/ ((__unused_webpack_module, exports) => {5960"use strict";5961// Copyright 2018 Google LLC5962// Licensed under the Apache License, Version 2.0 (the "License");5963// you may not use this file except in compliance with the License.5964// You may obtain a copy of the License at5965//5966// http://www.apache.org/licenses/LICENSE-2.05967//5968// Unless required by applicable law or agreed to in writing, software5969// distributed under the License is distributed on an "AS IS" BASIS,5970// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.5971// See the License for the specific language governing permissions and5972// limitations under the License.5973Object.defineProperty(exports, "__esModule", ({ value: true }));5974exports.getRetryConfig = void 0;5975async function getRetryConfig(err) {5976 var _a;5977 let config = getConfig(err);5978 if (!err || !err.config || (!config && !err.config.retry)) {5979 return { shouldRetry: false };5980 }5981 config = config || {};5982 config.currentRetryAttempt = config.currentRetryAttempt || 0;5983 config.retry =5984 config.retry === undefined || config.retry === null ? 3 : config.retry;5985 config.httpMethodsToRetry = config.httpMethodsToRetry || [5986 'GET',5987 'HEAD',5988 'PUT',5989 'OPTIONS',5990 'DELETE',5991 ];5992 config.noResponseRetries =5993 config.noResponseRetries === undefined || config.noResponseRetries === null5994 ? 25995 : config.noResponseRetries;5996 // If this wasn't in the list of status codes where we want5997 // to automatically retry, return.5998 const retryRanges = [5999 // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes6000 // 1xx - Retry (Informational, request still processing)6001 // 2xx - Do not retry (Success)6002 // 3xx - Do not retry (Redirect)6003 // 4xx - Do not retry (Client errors)6004 // 429 - Retry ("Too Many Requests")6005 // 5xx - Retry (Server errors)6006 [100, 199],6007 [429, 429],6008 [500, 599],6009 ];6010 config.statusCodesToRetry = config.statusCodesToRetry || retryRanges;6011 // Put the config back into the err6012 err.config.retryConfig = config;6013 // Determine if we should retry the request6014 const shouldRetryFn = config.shouldRetry || shouldRetryRequest;6015 if (!(await shouldRetryFn(err))) {6016 return { shouldRetry: false, config: err.config };6017 }6018 // Calculate time to wait with exponential backoff.6019 // If this is the first retry, look for a configured retryDelay.6020 const retryDelay = config.currentRetryAttempt ? 0 : (_a = config.retryDelay) !== null && _a !== void 0 ? _a : 100;6021 // Formula: retryDelay + ((2^c - 1 / 2) * 1000)6022 const delay = retryDelay + ((Math.pow(2, config.currentRetryAttempt) - 1) / 2) * 1000;6023 // We're going to retry! Incremenent the counter.6024 err.config.retryConfig.currentRetryAttempt += 1;6025 // Create a promise that invokes the retry after the backOffDelay6026 const backoff = new Promise(resolve => {6027 setTimeout(resolve, delay);6028 });6029 // Notify the user if they added an `onRetryAttempt` handler6030 if (config.onRetryAttempt) {6031 config.onRetryAttempt(err);6032 }6033 // Return the promise in which recalls Gaxios to retry the request6034 await backoff;6035 return { shouldRetry: true, config: err.config };6036}6037exports.getRetryConfig = getRetryConfig;6038/**6039 * Determine based on config if we should retry the request.6040 * @param err The GaxiosError passed to the interceptor.6041 */6042function shouldRetryRequest(err) {6043 const config = getConfig(err);6044 // node-fetch raises an AbortError if signaled:6045 // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal6046 if (err.name === 'AbortError') {6047 return false;6048 }6049 // If there's no config, or retries are disabled, return.6050 if (!config || config.retry === 0) {6051 return false;6052 }6053 // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc)6054 if (!err.response &&6055 (config.currentRetryAttempt || 0) >= config.noResponseRetries) {6056 return false;6057 }6058 // Only retry with configured HttpMethods.6059 if (!err.config.method ||6060 config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) {6061 return false;6062 }6063 // If this wasn't in the list of status codes where we want6064 // to automatically retry, return.6065 if (err.response && err.response.status) {6066 let isInRange = false;6067 for (const [min, max] of config.statusCodesToRetry) {6068 const status = err.response.status;6069 if (status >= min && status <= max) {6070 isInRange = true;6071 break;6072 }6073 }6074 if (!isInRange) {6075 return false;6076 }6077 }6078 // If we are out of retry attempts, return6079 config.currentRetryAttempt = config.currentRetryAttempt || 0;6080 if (config.currentRetryAttempt >= config.retry) {6081 return false;6082 }6083 return true;6084}6085/**6086 * Acquire the raxConfig object from an GaxiosError if available.6087 * @param err The Gaxios error with a config object.6088 */6089function getConfig(err) {6090 if (err && err.config && err.config.retryConfig) {6091 return err.config.retryConfig;6092 }6093 return;6094}6095//# sourceMappingURL=retry.js.map6096/***/ }),6097/***/ 3563:6098/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6099"use strict";6100/**6101 * Copyright 2018 Google LLC6102 *6103 * Distributed under MIT license.6104 * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT6105 */6106Object.defineProperty(exports, "__esModule", ({ value: true }));6107exports.requestTimeout = exports.resetIsAvailableCache = exports.isAvailable = exports.project = exports.instance = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0;6108const gaxios_1 = __nccwpck_require__(9555);6109const jsonBigint = __nccwpck_require__(5031);6110exports.BASE_PATH = '/computeMetadata/v1';6111exports.HOST_ADDRESS = 'http://169.254.169.254';6112exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.';6113exports.HEADER_NAME = 'Metadata-Flavor';6114exports.HEADER_VALUE = 'Google';6115exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE });6116/**6117 * Returns the base URL while taking into account the GCE_METADATA_HOST6118 * environment variable if it exists.6119 *6120 * @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1.6121 */6122function getBaseUrl(baseUrl) {6123 if (!baseUrl) {6124 baseUrl =6125 process.env.GCE_METADATA_IP ||6126 process.env.GCE_METADATA_HOST ||6127 exports.HOST_ADDRESS;6128 }6129 // If no scheme is provided default to HTTP:6130 if (!/^https?:\/\//.test(baseUrl)) {6131 baseUrl = `http://${baseUrl}`;6132 }6133 return new URL(exports.BASE_PATH, baseUrl).href;6134}6135// Accepts an options object passed from the user to the API. In previous6136// versions of the API, it referred to a `Request` or an `Axios` request6137// options object. Now it refers to an object with very limited property6138// names. This is here to help ensure users don't pass invalid options when6139// they upgrade from 0.4 to 0.5 to 0.8.6140function validate(options) {6141 Object.keys(options).forEach(key => {6142 switch (key) {6143 case 'params':6144 case 'property':6145 case 'headers':6146 break;6147 case 'qs':6148 throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");6149 default:6150 throw new Error(`'${key}' is not a valid configuration option.`);6151 }6152 });6153}6154async function metadataAccessor(type, options, noResponseRetries = 3, fastFail = false) {6155 options = options || {};6156 if (typeof options === 'string') {6157 options = { property: options };6158 }6159 let property = '';6160 if (typeof options === 'object' && options.property) {6161 property = '/' + options.property;6162 }6163 validate(options);6164 try {6165 const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request;6166 const res = await requestMethod({6167 url: `${getBaseUrl()}/${type}${property}`,6168 headers: Object.assign({}, exports.HEADERS, options.headers),6169 retryConfig: { noResponseRetries },6170 params: options.params,6171 responseType: 'text',6172 timeout: requestTimeout(),6173 });6174 // NOTE: node.js converts all incoming headers to lower case.6175 if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) {6176 throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header.`);6177 }6178 else if (!res.data) {6179 throw new Error('Invalid response from the metadata service');6180 }6181 if (typeof res.data === 'string') {6182 try {6183 return jsonBigint.parse(res.data);6184 }6185 catch (_a) {6186 /* ignore */6187 }6188 }6189 return res.data;6190 }6191 catch (e) {6192 const err = e;6193 if (err.response && err.response.status !== 200) {6194 err.message = `Unsuccessful response status code. ${err.message}`;6195 }6196 throw e;6197 }6198}6199async function fastFailMetadataRequest(options) {6200 const secondaryOptions = {6201 ...options,6202 url: options.url.replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)),6203 };6204 // We race a connection between DNS/IP to metadata server. There are a couple6205 // reasons for this:6206 //6207 // 1. the DNS is slow in some GCP environments; by checking both, we might6208 // detect the runtime environment signficantly faster.6209 // 2. we can't just check the IP, which is tarpitted and slow to respond6210 // on a user's local machine.6211 //6212 // Additional logic has been added to make sure that we don't create an6213 // unhandled rejection in scenarios where a failure happens sometime6214 // after a success.6215 //6216 // Note, however, if a failure happens prior to a success, a rejection should6217 // occur, this is for folks running locally.6218 //6219 let responded = false;6220 const r1 = (0, gaxios_1.request)(options)6221 .then(res => {6222 responded = true;6223 return res;6224 })6225 .catch(err => {6226 if (responded) {6227 return r2;6228 }6229 else {6230 responded = true;6231 throw err;6232 }6233 });6234 const r2 = (0, gaxios_1.request)(secondaryOptions)6235 .then(res => {6236 responded = true;6237 return res;6238 })6239 .catch(err => {6240 if (responded) {6241 return r1;6242 }6243 else {6244 responded = true;6245 throw err;6246 }6247 });6248 return Promise.race([r1, r2]);6249}6250/**6251 * Obtain metadata for the current GCE instance6252 */6253// eslint-disable-next-line @typescript-eslint/no-explicit-any6254function instance(options) {6255 return metadataAccessor('instance', options);6256}6257exports.instance = instance;6258/**6259 * Obtain metadata for the current GCP Project.6260 */6261// eslint-disable-next-line @typescript-eslint/no-explicit-any6262function project(options) {6263 return metadataAccessor('project', options);6264}6265exports.project = project;6266/*6267 * How many times should we retry detecting GCP environment.6268 */6269function detectGCPAvailableRetries() {6270 return process.env.DETECT_GCP_RETRIES6271 ? Number(process.env.DETECT_GCP_RETRIES)6272 : 0;6273}6274let cachedIsAvailableResponse;6275/**6276 * Determine if the metadata server is currently available.6277 */6278async function isAvailable() {6279 try {6280 // If a user is instantiating several GCP libraries at the same time,6281 // this may result in multiple calls to isAvailable(), to detect the6282 // runtime environment. We use the same promise for each of these calls6283 // to reduce the network load.6284 if (cachedIsAvailableResponse === undefined) {6285 cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), 6286 // If the default HOST_ADDRESS has been overridden, we should not6287 // make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in6288 // a non-GCP environment):6289 !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST));6290 }6291 await cachedIsAvailableResponse;6292 return true;6293 }6294 catch (e) {6295 const err = e;6296 if (process.env.DEBUG_AUTH) {6297 console.info(err);6298 }6299 if (err.type === 'request-timeout') {6300 // If running in a GCP environment, metadata endpoint should return6301 // within ms.6302 return false;6303 }6304 if (err.response && err.response.status === 404) {6305 return false;6306 }6307 else {6308 if (!(err.response && err.response.status === 404) &&6309 // A warning is emitted if we see an unexpected err.code, or err.code6310 // is not populated:6311 (!err.code ||6312 ![6313 'EHOSTDOWN',6314 'EHOSTUNREACH',6315 'ENETUNREACH',6316 'ENOENT',6317 'ENOTFOUND',6318 'ECONNREFUSED',6319 ].includes(err.code))) {6320 let code = 'UNKNOWN';6321 if (err.code)6322 code = err.code;6323 process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning');6324 }6325 // Failure to resolve the metadata service means that it is not available.6326 return false;6327 }6328 }6329}6330exports.isAvailable = isAvailable;6331/**6332 * reset the memoized isAvailable() lookup.6333 */6334function resetIsAvailableCache() {6335 cachedIsAvailableResponse = undefined;6336}6337exports.resetIsAvailableCache = resetIsAvailableCache;6338/**6339 * Obtain the timeout for requests to the metadata server.6340 */6341function requestTimeout() {6342 // In testing, we were able to reproduce behavior similar to6343 // https://github.com/googleapis/google-auth-library-nodejs/issues/7986344 // by making many concurrent network requests. Requests do not actually fail,6345 // rather they take significantly longer to complete (and we hit our6346 // default 3000ms timeout).6347 //6348 // This logic detects a GCF environment, using the documented environment6349 // variables K_SERVICE and FUNCTION_NAME:6350 // https://cloud.google.com/functions/docs/env-var and, in a GCF environment6351 // eliminates timeouts (by setting the value to 0 to disable).6352 return process.env.K_SERVICE || process.env.FUNCTION_NAME ? 0 : 3000;6353}6354exports.requestTimeout = requestTimeout;6355//# sourceMappingURL=index.js.map6356/***/ }),6357/***/ 4627:6358/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6359"use strict";6360// Copyright 2012 Google LLC6361//6362// Licensed under the Apache License, Version 2.0 (the "License");6363// you may not use this file except in compliance with the License.6364// You may obtain a copy of the License at6365//6366// http://www.apache.org/licenses/LICENSE-2.06367//6368// Unless required by applicable law or agreed to in writing, software6369// distributed under the License is distributed on an "AS IS" BASIS,6370// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.6371// See the License for the specific language governing permissions and6372// limitations under the License.6373Object.defineProperty(exports, "__esModule", ({ value: true }));6374exports.AuthClient = void 0;6375const events_1 = __nccwpck_require__(2361);6376const transporters_1 = __nccwpck_require__(2649);6377class AuthClient extends events_1.EventEmitter {6378 constructor() {6379 super(...arguments);6380 this.transporter = new transporters_1.DefaultTransporter();6381 this.credentials = {};6382 this.eagerRefreshThresholdMillis = 5 * 60 * 1000;6383 this.forceRefreshOnFailure = false;6384 }6385 /**6386 * Sets the auth credentials.6387 */6388 setCredentials(credentials) {6389 this.credentials = credentials;6390 }6391 /**6392 * Append additional headers, e.g., x-goog-user-project, shared across the6393 * classes inheriting AuthClient. This method should be used by any method6394 * that overrides getRequestMetadataAsync(), which is a shared helper for6395 * setting request information in both gRPC and HTTP API calls.6396 *6397 * @param headers object to append additional headers to.6398 */6399 addSharedMetadataHeaders(headers) {6400 // quota_project_id, stored in application_default_credentials.json, is set in6401 // the x-goog-user-project header, to indicate an alternate account for6402 // billing and quota:6403 if (!headers['x-goog-user-project'] && // don't override a value the user sets.6404 this.quotaProjectId) {6405 headers['x-goog-user-project'] = this.quotaProjectId;6406 }6407 return headers;6408 }6409}6410exports.AuthClient = AuthClient;6411//# sourceMappingURL=authclient.js.map6412/***/ }),6413/***/ 1569:6414/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6415"use strict";6416// Copyright 2021 Google LLC6417//6418// Licensed under the Apache License, Version 2.0 (the "License");6419// you may not use this file except in compliance with the License.6420// You may obtain a copy of the License at6421//6422// http://www.apache.org/licenses/LICENSE-2.06423//6424// Unless required by applicable law or agreed to in writing, software6425// distributed under the License is distributed on an "AS IS" BASIS,6426// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.6427// See the License for the specific language governing permissions and6428// limitations under the License.6429Object.defineProperty(exports, "__esModule", ({ value: true }));6430exports.AwsClient = void 0;6431const awsrequestsigner_1 = __nccwpck_require__(1754);6432const baseexternalclient_1 = __nccwpck_require__(7391);6433/**6434 * AWS external account client. This is used for AWS workloads, where6435 * AWS STS GetCallerIdentity serialized signed requests are exchanged for6436 * GCP access token.6437 */6438class AwsClient extends baseexternalclient_1.BaseExternalAccountClient {6439 /**6440 * Instantiates an AwsClient instance using the provided JSON6441 * object loaded from an external account credentials file.6442 * An error is thrown if the credential is not a valid AWS credential.6443 * @param options The external account options object typically loaded6444 * from the external account JSON credential file.6445 * @param additionalOptions Optional additional behavior customization6446 * options. These currently customize expiration threshold time and6447 * whether to retry on 401/403 API request errors.6448 */6449 constructor(options, additionalOptions) {6450 var _a;6451 super(options, additionalOptions);6452 this.environmentId = options.credential_source.environment_id;6453 // This is only required if the AWS region is not available in the6454 // AWS_REGION or AWS_DEFAULT_REGION environment variables.6455 this.regionUrl = options.credential_source.region_url;6456 // This is only required if AWS security credentials are not available in6457 // environment variables.6458 this.securityCredentialsUrl = options.credential_source.url;6459 this.regionalCredVerificationUrl =6460 options.credential_source.regional_cred_verification_url;6461 this.imdsV2SessionTokenUrl =6462 options.credential_source.imdsv2_session_token_url;6463 const match = (_a = this.environmentId) === null || _a === void 0 ? void 0 : _a.match(/^(aws)(\d+)$/);6464 if (!match || !this.regionalCredVerificationUrl) {6465 throw new Error('No valid AWS "credential_source" provided');6466 }6467 else if (parseInt(match[2], 10) !== 1) {6468 throw new Error(`aws version "${match[2]}" is not supported in the current build.`);6469 }6470 this.awsRequestSigner = null;6471 this.region = '';6472 }6473 /**6474 * Triggered when an external subject token is needed to be exchanged for a6475 * GCP access token via GCP STS endpoint.6476 * This uses the `options.credential_source` object to figure out how6477 * to retrieve the token using the current environment. In this case,6478 * this uses a serialized AWS signed request to the STS GetCallerIdentity6479 * endpoint.6480 * The logic is summarized as:6481 * 1. If imdsv2_session_token_url is provided in the credential source, then6482 * fetch the aws session token and include it in the headers of the6483 * metadata requests. This is a requirement for IDMSv2 but optional6484 * for IDMSv1.6485 * 2. Retrieve AWS region from availability-zone.6486 * 3a. Check AWS credentials in environment variables. If not found, get6487 * from security-credentials endpoint.6488 * 3b. Get AWS credentials from security-credentials endpoint. In order6489 * to retrieve this, the AWS role needs to be determined by calling6490 * security-credentials endpoint without any argument. Then the6491 * credentials can be retrieved via: security-credentials/role_name6492 * 4. Generate the signed request to AWS STS GetCallerIdentity action.6493 * 5. Inject x-goog-cloud-target-resource into header and serialize the6494 * signed request. This will be the subject-token to pass to GCP STS.6495 * @return A promise that resolves with the external subject token.6496 */6497 async retrieveSubjectToken() {6498 // Initialize AWS request signer if not already initialized.6499 if (!this.awsRequestSigner) {6500 const metadataHeaders = {};6501 if (this.imdsV2SessionTokenUrl) {6502 metadataHeaders['x-aws-ec2-metadata-token'] =6503 await this.getImdsV2SessionToken();6504 }6505 this.region = await this.getAwsRegion(metadataHeaders);6506 this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => {6507 // Check environment variables for permanent credentials first.6508 // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html6509 if (process.env['AWS_ACCESS_KEY_ID'] &&6510 process.env['AWS_SECRET_ACCESS_KEY']) {6511 return {6512 accessKeyId: process.env['AWS_ACCESS_KEY_ID'],6513 secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'],6514 // This is normally not available for permanent credentials.6515 token: process.env['AWS_SESSION_TOKEN'],6516 };6517 }6518 // Since the role on a VM can change, we don't need to cache it.6519 const roleName = await this.getAwsRoleName(metadataHeaders);6520 // Temporary credentials typically last for several hours.6521 // Expiration is returned in response.6522 // Consider future optimization of this logic to cache AWS tokens6523 // until their natural expiration.6524 const awsCreds = await this.getAwsSecurityCredentials(roleName, metadataHeaders);6525 return {6526 accessKeyId: awsCreds.AccessKeyId,6527 secretAccessKey: awsCreds.SecretAccessKey,6528 token: awsCreds.Token,6529 };6530 }, this.region);6531 }6532 // Generate signed request to AWS STS GetCallerIdentity API.6533 // Use the required regional endpoint. Otherwise, the request will fail.6534 const options = await this.awsRequestSigner.getRequestOptions({6535 url: this.regionalCredVerificationUrl.replace('{region}', this.region),6536 method: 'POST',6537 });6538 // The GCP STS endpoint expects the headers to be formatted as:6539 // [6540 // {key: 'x-amz-date', value: '...'},6541 // {key: 'Authorization', value: '...'},6542 // ...6543 // ]6544 // And then serialized as:6545 // encodeURIComponent(JSON.stringify({6546 // url: '...',6547 // method: 'POST',6548 // headers: [{key: 'x-amz-date', value: '...'}, ...]6549 // }))6550 const reformattedHeader = [];6551 const extendedHeaders = Object.assign({6552 // The full, canonical resource name of the workload identity pool6553 // provider, with or without the HTTPS prefix.6554 // Including this header as part of the signature is recommended to6555 // ensure data integrity.6556 'x-goog-cloud-target-resource': this.audience,6557 }, options.headers);6558 // Reformat header to GCP STS expected format.6559 for (const key in extendedHeaders) {6560 reformattedHeader.push({6561 key,6562 value: extendedHeaders[key],6563 });6564 }6565 // Serialize the reformatted signed request.6566 return encodeURIComponent(JSON.stringify({6567 url: options.url,6568 method: options.method,6569 headers: reformattedHeader,6570 }));6571 }6572 /**6573 * @return A promise that resolves with the IMDSv2 Session Token.6574 */6575 async getImdsV2SessionToken() {6576 const opts = {6577 url: this.imdsV2SessionTokenUrl,6578 method: 'PUT',6579 responseType: 'text',6580 headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' },6581 };6582 const response = await this.transporter.request(opts);6583 return response.data;6584 }6585 /**6586 * @param headers The headers to be used in the metadata request.6587 * @return A promise that resolves with the current AWS region.6588 */6589 async getAwsRegion(headers) {6590 // Priority order for region determination:6591 // AWS_REGION > AWS_DEFAULT_REGION > metadata server.6592 if (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION']) {6593 return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION']);6594 }6595 if (!this.regionUrl) {6596 throw new Error('Unable to determine AWS region due to missing ' +6597 '"options.credential_source.region_url"');6598 }6599 const opts = {6600 url: this.regionUrl,6601 method: 'GET',6602 responseType: 'text',6603 headers: headers,6604 };6605 const response = await this.transporter.request(opts);6606 // Remove last character. For example, if us-east-2b is returned,6607 // the region would be us-east-2.6608 return response.data.substr(0, response.data.length - 1);6609 }6610 /**6611 * @param headers The headers to be used in the metadata request.6612 * @return A promise that resolves with the assigned role to the current6613 * AWS VM. This is needed for calling the security-credentials endpoint.6614 */6615 async getAwsRoleName(headers) {6616 if (!this.securityCredentialsUrl) {6617 throw new Error('Unable to determine AWS role name due to missing ' +6618 '"options.credential_source.url"');6619 }6620 const opts = {6621 url: this.securityCredentialsUrl,6622 method: 'GET',6623 responseType: 'text',6624 headers: headers,6625 };6626 const response = await this.transporter.request(opts);6627 return response.data;6628 }6629 /**6630 * Retrieves the temporary AWS credentials by calling the security-credentials6631 * endpoint as specified in the `credential_source` object.6632 * @param roleName The role attached to the current VM.6633 * @param headers The headers to be used in the metadata request.6634 * @return A promise that resolves with the temporary AWS credentials6635 * needed for creating the GetCallerIdentity signed request.6636 */6637 async getAwsSecurityCredentials(roleName, headers) {6638 const response = await this.transporter.request({6639 url: `${this.securityCredentialsUrl}/${roleName}`,6640 responseType: 'json',6641 headers: headers,6642 });6643 return response.data;6644 }6645}6646exports.AwsClient = AwsClient;6647//# sourceMappingURL=awsclient.js.map6648/***/ }),6649/***/ 1754:6650/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6651"use strict";6652// Copyright 2021 Google LLC6653//6654// Licensed under the Apache License, Version 2.0 (the "License");6655// you may not use this file except in compliance with the License.6656// You may obtain a copy of the License at6657//6658// http://www.apache.org/licenses/LICENSE-2.06659//6660// Unless required by applicable law or agreed to in writing, software6661// distributed under the License is distributed on an "AS IS" BASIS,6662// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.6663// See the License for the specific language governing permissions and6664// limitations under the License.6665Object.defineProperty(exports, "__esModule", ({ value: true }));6666exports.AwsRequestSigner = void 0;6667const crypto_1 = __nccwpck_require__(8043);6668/** AWS Signature Version 4 signing algorithm identifier. */6669const AWS_ALGORITHM = 'AWS4-HMAC-SHA256';6670/**6671 * The termination string for the AWS credential scope value as defined in6672 * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html6673 */6674const AWS_REQUEST_TYPE = 'aws4_request';6675/**6676 * Implements an AWS API request signer based on the AWS Signature Version 46677 * signing process.6678 * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html6679 */6680class AwsRequestSigner {6681 /**6682 * Instantiates an AWS API request signer used to send authenticated signed6683 * requests to AWS APIs based on the AWS Signature Version 4 signing process.6684 * This also provides a mechanism to generate the signed request without6685 * sending it.6686 * @param getCredentials A mechanism to retrieve AWS security credentials6687 * when needed.6688 * @param region The AWS region to use.6689 */6690 constructor(getCredentials, region) {6691 this.getCredentials = getCredentials;6692 this.region = region;6693 this.crypto = (0, crypto_1.createCrypto)();6694 }6695 /**6696 * Generates the signed request for the provided HTTP request for calling6697 * an AWS API. This follows the steps described at:6698 * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html6699 * @param amzOptions The AWS request options that need to be signed.6700 * @return A promise that resolves with the GaxiosOptions containing the6701 * signed HTTP request parameters.6702 */6703 async getRequestOptions(amzOptions) {6704 if (!amzOptions.url) {6705 throw new Error('"url" is required in "amzOptions"');6706 }6707 // Stringify JSON requests. This will be set in the request body of the6708 // generated signed request.6709 const requestPayloadData = typeof amzOptions.data === 'object'6710 ? JSON.stringify(amzOptions.data)6711 : amzOptions.data;6712 const url = amzOptions.url;6713 const method = amzOptions.method || 'GET';6714 const requestPayload = amzOptions.body || requestPayloadData;6715 const additionalAmzHeaders = amzOptions.headers;6716 const awsSecurityCredentials = await this.getCredentials();6717 const uri = new URL(url);6718 const headerMap = await generateAuthenticationHeaderMap({6719 crypto: this.crypto,6720 host: uri.host,6721 canonicalUri: uri.pathname,6722 canonicalQuerystring: uri.search.substr(1),6723 method,6724 region: this.region,6725 securityCredentials: awsSecurityCredentials,6726 requestPayload,6727 additionalAmzHeaders,6728 });6729 // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc.6730 const headers = Object.assign(6731 // Add x-amz-date if available.6732 headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, {6733 Authorization: headerMap.authorizationHeader,6734 host: uri.host,6735 }, additionalAmzHeaders || {});6736 if (awsSecurityCredentials.token) {6737 Object.assign(headers, {6738 'x-amz-security-token': awsSecurityCredentials.token,6739 });6740 }6741 const awsSignedReq = {6742 url,6743 method: method,6744 headers,6745 };6746 if (typeof requestPayload !== 'undefined') {6747 awsSignedReq.body = requestPayload;6748 }6749 return awsSignedReq;6750 }6751}6752exports.AwsRequestSigner = AwsRequestSigner;6753/**6754 * Creates the HMAC-SHA256 hash of the provided message using the6755 * provided key.6756 *6757 * @param crypto The crypto instance used to facilitate cryptographic6758 * operations.6759 * @param key The HMAC-SHA256 key to use.6760 * @param msg The message to hash.6761 * @return The computed hash bytes.6762 */6763async function sign(crypto, key, msg) {6764 return await crypto.signWithHmacSha256(key, msg);6765}6766/**6767 * Calculates the signing key used to calculate the signature for6768 * AWS Signature Version 4 based on:6769 * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html6770 *6771 * @param crypto The crypto instance used to facilitate cryptographic6772 * operations.6773 * @param key The AWS secret access key.6774 * @param dateStamp The '%Y%m%d' date format.6775 * @param region The AWS region.6776 * @param serviceName The AWS service name, eg. sts.6777 * @return The signing key bytes.6778 */6779async function getSigningKey(crypto, key, dateStamp, region, serviceName) {6780 const kDate = await sign(crypto, `AWS4${key}`, dateStamp);6781 const kRegion = await sign(crypto, kDate, region);6782 const kService = await sign(crypto, kRegion, serviceName);6783 const kSigning = await sign(crypto, kService, 'aws4_request');6784 return kSigning;6785}6786/**6787 * Generates the authentication header map needed for generating the AWS6788 * Signature Version 4 signed request.6789 *6790 * @param option The options needed to compute the authentication header map.6791 * @return The AWS authentication header map which constitutes of the following6792 * components: amz-date, authorization header and canonical query string.6793 */6794async function generateAuthenticationHeaderMap(options) {6795 const additionalAmzHeaders = options.additionalAmzHeaders || {};6796 const requestPayload = options.requestPayload || '';6797 // iam.amazonaws.com host => iam service.6798 // sts.us-east-2.amazonaws.com => sts service.6799 const serviceName = options.host.split('.')[0];6800 const now = new Date();6801 // Format: '%Y%m%dT%H%M%SZ'.6802 const amzDate = now6803 .toISOString()6804 .replace(/[-:]/g, '')6805 .replace(/\.[0-9]+/, '');6806 // Format: '%Y%m%d'.6807 const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, '');6808 // Change all additional headers to be lower case.6809 const reformattedAdditionalAmzHeaders = {};6810 Object.keys(additionalAmzHeaders).forEach(key => {6811 reformattedAdditionalAmzHeaders[key.toLowerCase()] =6812 additionalAmzHeaders[key];6813 });6814 // Add AWS token if available.6815 if (options.securityCredentials.token) {6816 reformattedAdditionalAmzHeaders['x-amz-security-token'] =6817 options.securityCredentials.token;6818 }6819 // Header keys need to be sorted alphabetically.6820 const amzHeaders = Object.assign({6821 host: options.host,6822 }, 6823 // Previously the date was not fixed with x-amz- and could be provided manually.6824 // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req6825 reformattedAdditionalAmzHeaders.date ? {} : { 'x-amz-date': amzDate }, reformattedAdditionalAmzHeaders);6826 let canonicalHeaders = '';6827 const signedHeadersList = Object.keys(amzHeaders).sort();6828 signedHeadersList.forEach(key => {6829 canonicalHeaders += `${key}:${amzHeaders[key]}\n`;6830 });6831 const signedHeaders = signedHeadersList.join(';');6832 const payloadHash = await options.crypto.sha256DigestHex(requestPayload);6833 // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html6834 const canonicalRequest = `${options.method}\n` +6835 `${options.canonicalUri}\n` +6836 `${options.canonicalQuerystring}\n` +6837 `${canonicalHeaders}\n` +6838 `${signedHeaders}\n` +6839 `${payloadHash}`;6840 const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`;6841 // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html6842 const stringToSign = `${AWS_ALGORITHM}\n` +6843 `${amzDate}\n` +6844 `${credentialScope}\n` +6845 (await options.crypto.sha256DigestHex(canonicalRequest));6846 // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html6847 const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName);6848 const signature = await sign(options.crypto, signingKey, stringToSign);6849 // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html6850 const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` +6851 `${credentialScope}, SignedHeaders=${signedHeaders}, ` +6852 `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`;6853 return {6854 // Do not return x-amz-date if date is available.6855 amzDate: reformattedAdditionalAmzHeaders.date ? undefined : amzDate,6856 authorizationHeader,6857 canonicalQuerystring: options.canonicalQuerystring,6858 };6859}6860//# sourceMappingURL=awsrequestsigner.js.map6861/***/ }),6862/***/ 7391:6863/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {6864"use strict";6865// Copyright 2021 Google LLC6866//6867// Licensed under the Apache License, Version 2.0 (the "License");6868// you may not use this file except in compliance with the License.6869// You may obtain a copy of the License at6870//6871// http://www.apache.org/licenses/LICENSE-2.06872//6873// Unless required by applicable law or agreed to in writing, software6874// distributed under the License is distributed on an "AS IS" BASIS,6875// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.6876// See the License for the specific language governing permissions and6877// limitations under the License.6878Object.defineProperty(exports, "__esModule", ({ value: true }));6879exports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0;6880const stream = __nccwpck_require__(2781);6881const authclient_1 = __nccwpck_require__(4627);6882const sts = __nccwpck_require__(6308);6883/**6884 * The required token exchange grant_type: rfc8693#section-2.16885 */6886const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';6887/**6888 * The requested token exchange requested_token_type: rfc8693#section-2.16889 */6890const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';6891/** The default OAuth scope to request when none is provided. */6892const DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';6893/** The google apis domain pattern. */6894const GOOGLE_APIS_DOMAIN_PATTERN = '\\.googleapis\\.com$';6895/** The variable portion pattern in a Google APIs domain. */6896const VARIABLE_PORTION_PATTERN = '[^\\.\\s\\/\\\\]+';6897/** Default impersonated token lifespan in seconds.*/6898const DEFAULT_TOKEN_LIFESPAN = 3600;6899/**6900 * Offset to take into account network delays and server clock skews.6901 */6902exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;6903/**6904 * The credentials JSON file type for external account clients.6905 * There are 3 types of JSON configs:6906 * 1. authorized_user => Google end user credential6907 * 2. service_account => Google service account credential6908 * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s)6909 */6910exports.EXTERNAL_ACCOUNT_TYPE = 'external_account';6911/** Cloud resource manager URL used to retrieve project information. */6912exports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/';6913/** The workforce audience pattern. */6914const WORKFORCE_AUDIENCE_PATTERN = '//iam.googleapis.com/locations/[^/]+/workforcePools/[^/]+/providers/.+';6915/**6916 * Base external account client. This is used to instantiate AuthClients for6917 * exchanging external account credentials for GCP access token and authorizing6918 * requests to GCP APIs.6919 * The base class implements common logic for exchanging various type of6920 * external credentials for GCP access token. The logic of determining and6921 * retrieving the external credential based on the environment and6922 * credential_source will be left for the subclasses.6923 */6924class BaseExternalAccountClient extends authclient_1.AuthClient {6925 /**6926 * Instantiate a BaseExternalAccountClient instance using the provided JSON6927 * object loaded from an external account credentials file.6928 * @param options The external account options object typically loaded6929 * from the external account JSON credential file.6930 * @param additionalOptions Optional additional behavior customization6931 * options. These currently customize expiration threshold time and6932 * whether to retry on 401/403 API request errors.6933 */6934 constructor(options, additionalOptions) {6935 var _a, _b;6936 super();6937 if (options.type !== exports.EXTERNAL_ACCOUNT_TYPE) {6938 throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` +6939 `received "${options.type}"`);6940 }6941 this.clientAuth = options.client_id6942 ? {6943 confidentialClientType: 'basic',6944 clientId: options.client_id,6945 clientSecret: options.client_secret,6946 }6947 : undefined;6948 if (!this.validateGoogleAPIsUrl('sts', options.token_url)) {6949 throw new Error(`"${options.token_url}" is not a valid token url.`);6950 }6951 this.stsCredential = new sts.StsCredentials(options.token_url, this.clientAuth);6952 // Default OAuth scope. This could be overridden via public property.6953 this.scopes = [DEFAULT_OAUTH_SCOPE];6954 this.cachedAccessToken = null;6955 this.audience = options.audience;6956 this.subjectTokenType = options.subject_token_type;6957 this.quotaProjectId = options.quota_project_id;6958 this.workforcePoolUserProject = options.workforce_pool_user_project;6959 const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN);6960 if (this.workforcePoolUserProject &&6961 !this.audience.match(workforceAudiencePattern)) {6962 throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' +6963 'credentials.');6964 }6965 if (typeof options.service_account_impersonation_url !== 'undefined' &&6966 !this.validateGoogleAPIsUrl('iamcredentials', options.service_account_impersonation_url)) {6967 throw new Error(`"${options.service_account_impersonation_url}" is ` +6968 'not a valid service account impersonation url.');6969 }6970 this.serviceAccountImpersonationUrl =6971 options.service_account_impersonation_url;6972 this.serviceAccountImpersonationLifetime =6973 (_b = (_a = options.service_account_impersonation) === null || _a === void 0 ? void 0 : _a.token_lifetime_seconds) !== null && _b !== void 0 ? _b : DEFAULT_TOKEN_LIFESPAN;6974 // As threshold could be zero,6975 // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the6976 // zero value.6977 if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') {6978 this.eagerRefreshThresholdMillis = exports.EXPIRATION_TIME_OFFSET;6979 }6980 else {6981 this.eagerRefreshThresholdMillis = additionalOptions6982 .eagerRefreshThresholdMillis;6983 }6984 this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure);6985 this.projectId = null;6986 this.projectNumber = this.getProjectNumber(this.audience);6987 }6988 /** The service account email to be impersonated, if available. */6989 getServiceAccountEmail() {6990 var _a;6991 if (this.serviceAccountImpersonationUrl) {6992 // Parse email from URL. The formal looks as follows:6993 // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken6994 const re = /serviceAccounts\/(?<email>[^:]+):generateAccessToken$/;6995 const result = re.exec(this.serviceAccountImpersonationUrl);6996 return ((_a = result === null || result === void 0 ? void 0 : result.groups) === null || _a === void 0 ? void 0 : _a.email) || null;6997 }6998 return null;6999 }7000 /**7001 * Provides a mechanism to inject GCP access tokens directly.7002 * When the provided credential expires, a new credential, using the7003 * external account options, is retrieved.7004 * @param credentials The Credentials object to set on the current client.7005 */7006 setCredentials(credentials) {7007 super.setCredentials(credentials);7008 this.cachedAccessToken = credentials;7009 }7010 /**7011 * @return A promise that resolves with the current GCP access token7012 * response. If the current credential is expired, a new one is retrieved.7013 */7014 async getAccessToken() {7015 // If cached access token is unavailable or expired, force refresh.7016 if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {7017 await this.refreshAccessTokenAsync();7018 }7019 // Return GCP access token in GetAccessTokenResponse format.7020 return {7021 token: this.cachedAccessToken.access_token,7022 res: this.cachedAccessToken.res,7023 };7024 }7025 /**7026 * The main authentication interface. It takes an optional url which when7027 * present is the endpoint being accessed, and returns a Promise which7028 * resolves with authorization header fields.7029 *7030 * The result has the form:7031 * { Authorization: 'Bearer <access_token_value>' }7032 */7033 async getRequestHeaders() {7034 const accessTokenResponse = await this.getAccessToken();7035 const headers = {7036 Authorization: `Bearer ${accessTokenResponse.token}`,7037 };7038 return this.addSharedMetadataHeaders(headers);7039 }7040 request(opts, callback) {7041 if (callback) {7042 this.requestAsync(opts).then(r => callback(null, r), e => {7043 return callback(e, e.response);7044 });7045 }7046 else {7047 return this.requestAsync(opts);7048 }7049 }7050 /**7051 * @return A promise that resolves with the project ID corresponding to the7052 * current workload identity pool or current workforce pool if7053 * determinable. For workforce pool credential, it returns the project ID7054 * corresponding to the workforcePoolUserProject.7055 * This is introduced to match the current pattern of using the Auth7056 * library:7057 * const projectId = await auth.getProjectId();7058 * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;7059 * const res = await client.request({ url });7060 * The resource may not have permission7061 * (resourcemanager.projects.get) to call this API or the required7062 * scopes may not be selected:7063 * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes7064 */7065 async getProjectId() {7066 const projectNumber = this.projectNumber || this.workforcePoolUserProject;7067 if (this.projectId) {7068 // Return previously determined project ID.7069 return this.projectId;7070 }7071 else if (projectNumber) {7072 // Preferable not to use request() to avoid retrial policies.7073 const headers = await this.getRequestHeaders();7074 const response = await this.transporter.request({7075 headers,7076 url: `${exports.CLOUD_RESOURCE_MANAGER}${projectNumber}`,7077 responseType: 'json',7078 });7079 this.projectId = response.data.projectId;7080 return this.projectId;7081 }7082 return null;7083 }7084 /**7085 * Authenticates the provided HTTP request, processes it and resolves with the7086 * returned response.7087 * @param opts The HTTP request options.7088 * @param retry Whether the current attempt is a retry after a failed attempt.7089 * @return A promise that resolves with the successful response.7090 */7091 async requestAsync(opts, retry = false) {7092 let response;7093 try {7094 const requestHeaders = await this.getRequestHeaders();7095 opts.headers = opts.headers || {};7096 if (requestHeaders && requestHeaders['x-goog-user-project']) {7097 opts.headers['x-goog-user-project'] =7098 requestHeaders['x-goog-user-project'];7099 }7100 if (requestHeaders && requestHeaders.Authorization) {7101 opts.headers.Authorization = requestHeaders.Authorization;7102 }7103 response = await this.transporter.request(opts);7104 }7105 catch (e) {7106 const res = e.response;7107 if (res) {7108 const statusCode = res.status;7109 // Retry the request for metadata if the following criteria are true:7110 // - We haven't already retried. It only makes sense to retry once.7111 // - The response was a 401 or a 4037112 // - The request didn't send a readableStream7113 // - forceRefreshOnFailure is true7114 const isReadableStream = res.config.data instanceof stream.Readable;7115 const isAuthErr = statusCode === 401 || statusCode === 403;7116 if (!retry &&7117 isAuthErr &&7118 !isReadableStream &&7119 this.forceRefreshOnFailure) {7120 await this.refreshAccessTokenAsync();7121 return await this.requestAsync(opts, true);7122 }7123 }7124 throw e;7125 }7126 return response;7127 }7128 /**7129 * Forces token refresh, even if unexpired tokens are currently cached.7130 * External credentials are exchanged for GCP access tokens via the token7131 * exchange endpoint and other settings provided in the client options7132 * object.7133 * If the service_account_impersonation_url is provided, an additional7134 * step to exchange the external account GCP access token for a service7135 * account impersonated token is performed.7136 * @return A promise that resolves with the fresh GCP access tokens.7137 */7138 async refreshAccessTokenAsync() {7139 // Retrieve the external credential.7140 const subjectToken = await this.retrieveSubjectToken();7141 // Construct the STS credentials options.7142 const stsCredentialsOptions = {7143 grantType: STS_GRANT_TYPE,7144 audience: this.audience,7145 requestedTokenType: STS_REQUEST_TOKEN_TYPE,7146 subjectToken,7147 subjectTokenType: this.subjectTokenType,7148 // generateAccessToken requires the provided access token to have7149 // scopes:7150 // https://www.googleapis.com/auth/iam or7151 // https://www.googleapis.com/auth/cloud-platform7152 // The new service account access token scopes will match the user7153 // provided ones.7154 scope: this.serviceAccountImpersonationUrl7155 ? [DEFAULT_OAUTH_SCOPE]7156 : this.getScopesArray(),7157 };7158 // Exchange the external credentials for a GCP access token.7159 // Client auth is prioritized over passing the workforcePoolUserProject7160 // parameter for STS token exchange.7161 const additionalOptions = !this.clientAuth && this.workforcePoolUserProject7162 ? { userProject: this.workforcePoolUserProject }7163 : undefined;7164 const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, additionalOptions);7165 if (this.serviceAccountImpersonationUrl) {7166 this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token);7167 }7168 else if (stsResponse.expires_in) {7169 // Save response in cached access token.7170 this.cachedAccessToken = {7171 access_token: stsResponse.access_token,7172 expiry_date: new Date().getTime() + stsResponse.expires_in * 1000,7173 res: stsResponse.res,7174 };7175 }7176 else {7177 // Save response in cached access token.7178 this.cachedAccessToken = {7179 access_token: stsResponse.access_token,7180 res: stsResponse.res,7181 };7182 }7183 // Save credentials.7184 this.credentials = {};7185 Object.assign(this.credentials, this.cachedAccessToken);7186 delete this.credentials.res;7187 // Trigger tokens event to notify external listeners.7188 this.emit('tokens', {7189 refresh_token: null,7190 expiry_date: this.cachedAccessToken.expiry_date,7191 access_token: this.cachedAccessToken.access_token,7192 token_type: 'Bearer',7193 id_token: null,7194 });7195 // Return the cached access token.7196 return this.cachedAccessToken;7197 }7198 /**7199 * Returns the workload identity pool project number if it is determinable7200 * from the audience resource name.7201 * @param audience The STS audience used to determine the project number.7202 * @return The project number associated with the workload identity pool, if7203 * this can be determined from the STS audience field. Otherwise, null is7204 * returned.7205 */7206 getProjectNumber(audience) {7207 // STS audience pattern:7208 // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/...7209 const match = audience.match(/\/projects\/([^/]+)/);7210 if (!match) {7211 return null;7212 }7213 return match[1];7214 }7215 /**7216 * Exchanges an external account GCP access token for a service7217 * account impersonated access token using iamcredentials7218 * GenerateAccessToken API.7219 * @param token The access token to exchange for a service account access7220 * token.7221 * @return A promise that resolves with the service account impersonated7222 * credentials response.7223 */7224 async getImpersonatedAccessToken(token) {7225 const opts = {7226 url: this.serviceAccountImpersonationUrl,7227 method: 'POST',7228 headers: {7229 'Content-Type': 'application/json',7230 Authorization: `Bearer ${token}`,7231 },7232 data: {7233 scope: this.getScopesArray(),7234 lifetime: this.serviceAccountImpersonationLifetime + 's',7235 },7236 responseType: 'json',7237 };7238 const response = await this.transporter.request(opts);7239 const successResponse = response.data;7240 return {7241 access_token: successResponse.accessToken,7242 // Convert from ISO format to timestamp.7243 expiry_date: new Date(successResponse.expireTime).getTime(),7244 res: response,7245 };7246 }7247 /**7248 * Returns whether the provided credentials are expired or not.7249 * If there is no expiry time, assumes the token is not expired or expiring.7250 * @param accessToken The credentials to check for expiration.7251 * @return Whether the credentials are expired or not.7252 */7253 isExpired(accessToken) {7254 const now = new Date().getTime();7255 return accessToken.expiry_date7256 ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis7257 : false;7258 }7259 /**7260 * @return The list of scopes for the requested GCP access token.7261 */7262 getScopesArray() {7263 // Since scopes can be provided as string or array, the type should7264 // be normalized.7265 if (typeof this.scopes === 'string') {7266 return [this.scopes];7267 }7268 else if (typeof this.scopes === 'undefined') {7269 return [DEFAULT_OAUTH_SCOPE];7270 }7271 else {7272 return this.scopes;7273 }7274 }7275 /**7276 * Checks whether Google APIs URL is valid.7277 * @param apiName The apiName of url.7278 * @param url The Google API URL to validate.7279 * @return Whether the URL is valid or not.7280 */7281 validateGoogleAPIsUrl(apiName, url) {7282 let parsedUrl;7283 // Return false if error is thrown during parsing URL.7284 try {7285 parsedUrl = new URL(url);7286 }7287 catch (e) {7288 return false;7289 }7290 const urlDomain = parsedUrl.hostname;7291 // Check the protocol is https.7292 if (parsedUrl.protocol !== 'https:') {7293 return false;7294 }7295 const googleAPIsDomainPatterns = [7296 new RegExp('^' +7297 VARIABLE_PORTION_PATTERN +7298 '\\.' +7299 apiName +7300 GOOGLE_APIS_DOMAIN_PATTERN),7301 new RegExp('^' + apiName + GOOGLE_APIS_DOMAIN_PATTERN),7302 new RegExp('^' +7303 apiName +7304 '\\.' +7305 VARIABLE_PORTION_PATTERN +7306 GOOGLE_APIS_DOMAIN_PATTERN),7307 new RegExp('^' +7308 VARIABLE_PORTION_PATTERN +7309 '\\-' +7310 apiName +7311 GOOGLE_APIS_DOMAIN_PATTERN),7312 ];7313 for (const googleAPIsDomainPattern of googleAPIsDomainPatterns) {7314 if (urlDomain.match(googleAPIsDomainPattern)) {7315 return true;7316 }7317 }7318 return false;7319 }7320}7321exports.BaseExternalAccountClient = BaseExternalAccountClient;7322//# sourceMappingURL=baseexternalclient.js.map7323/***/ }),7324/***/ 6875:7325/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {7326"use strict";7327// Copyright 2013 Google LLC7328//7329// Licensed under the Apache License, Version 2.0 (the "License");7330// you may not use this file except in compliance with the License.7331// You may obtain a copy of the License at7332//7333// http://www.apache.org/licenses/LICENSE-2.07334//7335// Unless required by applicable law or agreed to in writing, software7336// distributed under the License is distributed on an "AS IS" BASIS,7337// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7338// See the License for the specific language governing permissions and7339// limitations under the License.7340Object.defineProperty(exports, "__esModule", ({ value: true }));7341exports.Compute = void 0;7342const arrify = __nccwpck_require__(1546);7343const gaxios_1 = __nccwpck_require__(9555);7344const gcpMetadata = __nccwpck_require__(3563);7345const oauth2client_1 = __nccwpck_require__(3936);7346class Compute extends oauth2client_1.OAuth2Client {7347 /**7348 * Google Compute Engine service account credentials.7349 *7350 * Retrieve access token from the metadata server.7351 * See: https://developers.google.com/compute/docs/authentication7352 */7353 constructor(options = {}) {7354 super(options);7355 // Start with an expired refresh token, which will automatically be7356 // refreshed before the first API call is made.7357 this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' };7358 this.serviceAccountEmail = options.serviceAccountEmail || 'default';7359 this.scopes = arrify(options.scopes);7360 }7361 /**7362 * Refreshes the access token.7363 * @param refreshToken Unused parameter7364 */7365 async refreshTokenNoCache(7366 // eslint-disable-next-line @typescript-eslint/no-unused-vars7367 refreshToken) {7368 const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;7369 let data;7370 try {7371 const instanceOptions = {7372 property: tokenPath,7373 };7374 if (this.scopes.length > 0) {7375 instanceOptions.params = {7376 scopes: this.scopes.join(','),7377 };7378 }7379 data = await gcpMetadata.instance(instanceOptions);7380 }7381 catch (e) {7382 if (e instanceof gaxios_1.GaxiosError) {7383 e.message = `Could not refresh access token: ${e.message}`;7384 this.wrapError(e);7385 }7386 throw e;7387 }7388 const tokens = data;7389 if (data && data.expires_in) {7390 tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;7391 delete tokens.expires_in;7392 }7393 this.emit('tokens', tokens);7394 return { tokens, res: null };7395 }7396 /**7397 * Fetches an ID token.7398 * @param targetAudience the audience for the fetched ID token.7399 */7400 async fetchIdToken(targetAudience) {7401 const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` +7402 `?format=full&audience=${targetAudience}`;7403 let idToken;7404 try {7405 const instanceOptions = {7406 property: idTokenPath,7407 };7408 idToken = await gcpMetadata.instance(instanceOptions);7409 }7410 catch (e) {7411 if (e instanceof Error) {7412 e.message = `Could not fetch ID token: ${e.message}`;7413 }7414 throw e;7415 }7416 return idToken;7417 }7418 wrapError(e) {7419 const res = e.response;7420 if (res && res.status) {7421 e.code = res.status.toString();7422 if (res.status === 403) {7423 e.message =7424 'A Forbidden error was returned while attempting to retrieve an access ' +7425 'token for the Compute Engine built-in service account. This may be because the Compute ' +7426 'Engine instance does not have the correct permission scopes specified: ' +7427 e.message;7428 }7429 else if (res.status === 404) {7430 e.message =7431 'A Not Found error was returned while attempting to retrieve an access' +7432 'token for the Compute Engine built-in service account. This may be because the Compute ' +7433 'Engine instance does not have any permission scopes specified: ' +7434 e.message;7435 }7436 }7437 }7438}7439exports.Compute = Compute;7440//# sourceMappingURL=computeclient.js.map7441/***/ }),7442/***/ 6270:7443/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {7444"use strict";7445// Copyright 2021 Google LLC7446//7447// Licensed under the Apache License, Version 2.0 (the "License");7448// you may not use this file except in compliance with the License.7449// You may obtain a copy of the License at7450//7451// http://www.apache.org/licenses/LICENSE-2.07452//7453// Unless required by applicable law or agreed to in writing, software7454// distributed under the License is distributed on an "AS IS" BASIS,7455// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7456// See the License for the specific language governing permissions and7457// limitations under the License.7458Object.defineProperty(exports, "__esModule", ({ value: true }));7459exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0;7460const stream = __nccwpck_require__(2781);7461const authclient_1 = __nccwpck_require__(4627);7462const sts = __nccwpck_require__(6308);7463/**7464 * The required token exchange grant_type: rfc8693#section-2.17465 */7466const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';7467/**7468 * The requested token exchange requested_token_type: rfc8693#section-2.17469 */7470const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';7471/**7472 * The requested token exchange subject_token_type: rfc8693#section-2.17473 */7474const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';7475/** The STS access token exchange end point. */7476const STS_ACCESS_TOKEN_URL = 'https://sts.googleapis.com/v1/token';7477/**7478 * The maximum number of access boundary rules a Credential Access Boundary7479 * can contain.7480 */7481exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;7482/**7483 * Offset to take into account network delays and server clock skews.7484 */7485exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;7486/**7487 * Defines a set of Google credentials that are downscoped from an existing set7488 * of Google OAuth2 credentials. This is useful to restrict the Identity and7489 * Access Management (IAM) permissions that a short-lived credential can use.7490 * The common pattern of usage is to have a token broker with elevated access7491 * generate these downscoped credentials from higher access source credentials7492 * and pass the downscoped short-lived access tokens to a token consumer via7493 * some secure authenticated channel for limited access to Google Cloud Storage7494 * resources.7495 */7496class DownscopedClient extends authclient_1.AuthClient {7497 /**7498 * Instantiates a downscoped client object using the provided source7499 * AuthClient and credential access boundary rules.7500 * To downscope permissions of a source AuthClient, a Credential Access7501 * Boundary that specifies which resources the new credential can access, as7502 * well as an upper bound on the permissions that are available on each7503 * resource, has to be defined. A downscoped client can then be instantiated7504 * using the source AuthClient and the Credential Access Boundary.7505 * @param authClient The source AuthClient to be downscoped based on the7506 * provided Credential Access Boundary rules.7507 * @param credentialAccessBoundary The Credential Access Boundary which7508 * contains a list of access boundary rules. Each rule contains information7509 * on the resource that the rule applies to, the upper bound of the7510 * permissions that are available on that resource and an optional7511 * condition to further restrict permissions.7512 * @param additionalOptions Optional additional behavior customization7513 * options. These currently customize expiration threshold time and7514 * whether to retry on 401/403 API request errors.7515 * @param quotaProjectId Optional quota project id for setting up in the7516 * x-goog-user-project header.7517 */7518 constructor(authClient, credentialAccessBoundary, additionalOptions, quotaProjectId) {7519 super();7520 this.authClient = authClient;7521 this.credentialAccessBoundary = credentialAccessBoundary;7522 // Check 1-10 Access Boundary Rules are defined within Credential Access7523 // Boundary.7524 if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) {7525 throw new Error('At least one access boundary rule needs to be defined.');7526 }7527 else if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length >7528 exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) {7529 throw new Error('The provided access boundary has more than ' +7530 `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);7531 }7532 // Check at least one permission should be defined in each Access Boundary7533 // Rule.7534 for (const rule of credentialAccessBoundary.accessBoundary7535 .accessBoundaryRules) {7536 if (rule.availablePermissions.length === 0) {7537 throw new Error('At least one permission should be defined in access boundary rules.');7538 }7539 }7540 this.stsCredential = new sts.StsCredentials(STS_ACCESS_TOKEN_URL);7541 this.cachedDownscopedAccessToken = null;7542 // As threshold could be zero,7543 // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the7544 // zero value.7545 if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') {7546 this.eagerRefreshThresholdMillis = exports.EXPIRATION_TIME_OFFSET;7547 }7548 else {7549 this.eagerRefreshThresholdMillis = additionalOptions7550 .eagerRefreshThresholdMillis;7551 }7552 this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure);7553 this.quotaProjectId = quotaProjectId;7554 }7555 /**7556 * Provides a mechanism to inject Downscoped access tokens directly.7557 * The expiry_date field is required to facilitate determination of the token7558 * expiration which would make it easier for the token consumer to handle.7559 * @param credentials The Credentials object to set on the current client.7560 */7561 setCredentials(credentials) {7562 if (!credentials.expiry_date) {7563 throw new Error('The access token expiry_date field is missing in the provided ' +7564 'credentials.');7565 }7566 super.setCredentials(credentials);7567 this.cachedDownscopedAccessToken = credentials;7568 }7569 async getAccessToken() {7570 // If the cached access token is unavailable or expired, force refresh.7571 // The Downscoped access token will be returned in7572 // DownscopedAccessTokenResponse format.7573 if (!this.cachedDownscopedAccessToken ||7574 this.isExpired(this.cachedDownscopedAccessToken)) {7575 await this.refreshAccessTokenAsync();7576 }7577 // Return Downscoped access token in DownscopedAccessTokenResponse format.7578 return {7579 token: this.cachedDownscopedAccessToken.access_token,7580 expirationTime: this.cachedDownscopedAccessToken.expiry_date,7581 res: this.cachedDownscopedAccessToken.res,7582 };7583 }7584 /**7585 * The main authentication interface. It takes an optional url which when7586 * present is the endpoint being accessed, and returns a Promise which7587 * resolves with authorization header fields.7588 *7589 * The result has the form:7590 * { Authorization: 'Bearer <access_token_value>' }7591 */7592 async getRequestHeaders() {7593 const accessTokenResponse = await this.getAccessToken();7594 const headers = {7595 Authorization: `Bearer ${accessTokenResponse.token}`,7596 };7597 return this.addSharedMetadataHeaders(headers);7598 }7599 request(opts, callback) {7600 if (callback) {7601 this.requestAsync(opts).then(r => callback(null, r), e => {7602 return callback(e, e.response);7603 });7604 }7605 else {7606 return this.requestAsync(opts);7607 }7608 }7609 /**7610 * Authenticates the provided HTTP request, processes it and resolves with the7611 * returned response.7612 * @param opts The HTTP request options.7613 * @param retry Whether the current attempt is a retry after a failed attempt.7614 * @return A promise that resolves with the successful response.7615 */7616 async requestAsync(opts, retry = false) {7617 let response;7618 try {7619 const requestHeaders = await this.getRequestHeaders();7620 opts.headers = opts.headers || {};7621 if (requestHeaders && requestHeaders['x-goog-user-project']) {7622 opts.headers['x-goog-user-project'] =7623 requestHeaders['x-goog-user-project'];7624 }7625 if (requestHeaders && requestHeaders.Authorization) {7626 opts.headers.Authorization = requestHeaders.Authorization;7627 }7628 response = await this.transporter.request(opts);7629 }7630 catch (e) {7631 const res = e.response;7632 if (res) {7633 const statusCode = res.status;7634 // Retry the request for metadata if the following criteria are true:7635 // - We haven't already retried. It only makes sense to retry once.7636 // - The response was a 401 or a 4037637 // - The request didn't send a readableStream7638 // - forceRefreshOnFailure is true7639 const isReadableStream = res.config.data instanceof stream.Readable;7640 const isAuthErr = statusCode === 401 || statusCode === 403;7641 if (!retry &&7642 isAuthErr &&7643 !isReadableStream &&7644 this.forceRefreshOnFailure) {7645 await this.refreshAccessTokenAsync();7646 return await this.requestAsync(opts, true);7647 }7648 }7649 throw e;7650 }7651 return response;7652 }7653 /**7654 * Forces token refresh, even if unexpired tokens are currently cached.7655 * GCP access tokens are retrieved from authclient object/source credential.7656 * Then GCP access tokens are exchanged for downscoped access tokens via the7657 * token exchange endpoint.7658 * @return A promise that resolves with the fresh downscoped access token.7659 */7660 async refreshAccessTokenAsync() {7661 var _a;7662 // Retrieve GCP access token from source credential.7663 const subjectToken = (await this.authClient.getAccessToken()).token;7664 // Construct the STS credentials options.7665 const stsCredentialsOptions = {7666 grantType: STS_GRANT_TYPE,7667 requestedTokenType: STS_REQUEST_TOKEN_TYPE,7668 subjectToken: subjectToken,7669 subjectTokenType: STS_SUBJECT_TOKEN_TYPE,7670 };7671 // Exchange the source AuthClient access token for a Downscoped access7672 // token.7673 const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary);7674 /**7675 * The STS endpoint will only return the expiration time for the downscoped7676 * access token if the original access token represents a service account.7677 * The downscoped token's expiration time will always match the source7678 * credential expiration. When no expires_in is returned, we can copy the7679 * source credential's expiration time.7680 */7681 const sourceCredExpireDate = ((_a = this.authClient.credentials) === null || _a === void 0 ? void 0 : _a.expiry_date) || null;7682 const expiryDate = stsResponse.expires_in7683 ? new Date().getTime() + stsResponse.expires_in * 10007684 : sourceCredExpireDate;7685 // Save response in cached access token.7686 this.cachedDownscopedAccessToken = {7687 access_token: stsResponse.access_token,7688 expiry_date: expiryDate,7689 res: stsResponse.res,7690 };7691 // Save credentials.7692 this.credentials = {};7693 Object.assign(this.credentials, this.cachedDownscopedAccessToken);7694 delete this.credentials.res;7695 // Trigger tokens event to notify external listeners.7696 this.emit('tokens', {7697 refresh_token: null,7698 expiry_date: this.cachedDownscopedAccessToken.expiry_date,7699 access_token: this.cachedDownscopedAccessToken.access_token,7700 token_type: 'Bearer',7701 id_token: null,7702 });7703 // Return the cached access token.7704 return this.cachedDownscopedAccessToken;7705 }7706 /**7707 * Returns whether the provided credentials are expired or not.7708 * If there is no expiry time, assumes the token is not expired or expiring.7709 * @param downscopedAccessToken The credentials to check for expiration.7710 * @return Whether the credentials are expired or not.7711 */7712 isExpired(downscopedAccessToken) {7713 const now = new Date().getTime();7714 return downscopedAccessToken.expiry_date7715 ? now >=7716 downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis7717 : false;7718 }7719}7720exports.DownscopedClient = DownscopedClient;7721//# sourceMappingURL=downscopedclient.js.map7722/***/ }),7723/***/ 1380:7724/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {7725"use strict";7726// Copyright 2018 Google LLC7727//7728// Licensed under the Apache License, Version 2.0 (the "License");7729// you may not use this file except in compliance with the License.7730// You may obtain a copy of the License at7731//7732// http://www.apache.org/licenses/LICENSE-2.07733//7734// Unless required by applicable law or agreed to in writing, software7735// distributed under the License is distributed on an "AS IS" BASIS,7736// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7737// See the License for the specific language governing permissions and7738// limitations under the License.7739Object.defineProperty(exports, "__esModule", ({ value: true }));7740exports.getEnv = exports.clear = exports.GCPEnv = void 0;7741const gcpMetadata = __nccwpck_require__(3563);7742var GCPEnv;7743(function (GCPEnv) {7744 GCPEnv["APP_ENGINE"] = "APP_ENGINE";7745 GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE";7746 GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS";7747 GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE";7748 GCPEnv["CLOUD_RUN"] = "CLOUD_RUN";7749 GCPEnv["NONE"] = "NONE";7750})(GCPEnv = exports.GCPEnv || (exports.GCPEnv = {}));7751let envPromise;7752function clear() {7753 envPromise = undefined;7754}7755exports.clear = clear;7756async function getEnv() {7757 if (envPromise) {7758 return envPromise;7759 }7760 envPromise = getEnvMemoized();7761 return envPromise;7762}7763exports.getEnv = getEnv;7764async function getEnvMemoized() {7765 let env = GCPEnv.NONE;7766 if (isAppEngine()) {7767 env = GCPEnv.APP_ENGINE;7768 }7769 else if (isCloudFunction()) {7770 env = GCPEnv.CLOUD_FUNCTIONS;7771 }7772 else if (await isComputeEngine()) {7773 if (await isKubernetesEngine()) {7774 env = GCPEnv.KUBERNETES_ENGINE;7775 }7776 else if (isCloudRun()) {7777 env = GCPEnv.CLOUD_RUN;7778 }7779 else {7780 env = GCPEnv.COMPUTE_ENGINE;7781 }7782 }7783 else {7784 env = GCPEnv.NONE;7785 }7786 return env;7787}7788function isAppEngine() {7789 return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);7790}7791function isCloudFunction() {7792 return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);7793}7794/**7795 * This check only verifies that the environment is running knative.7796 * This must be run *after* checking for Kubernetes, otherwise it will7797 * return a false positive.7798 */7799function isCloudRun() {7800 return !!process.env.K_CONFIGURATION;7801}7802async function isKubernetesEngine() {7803 try {7804 await gcpMetadata.instance('attributes/cluster-name');7805 return true;7806 }7807 catch (e) {7808 return false;7809 }7810}7811async function isComputeEngine() {7812 return gcpMetadata.isAvailable();7813}7814//# sourceMappingURL=envDetect.js.map7815/***/ }),7816/***/ 8749:7817/***/ ((__unused_webpack_module, exports) => {7818"use strict";7819// Copyright 2022 Google LLC7820//7821// Licensed under the Apache License, Version 2.0 (the "License");7822// you may not use this file except in compliance with the License.7823// You may obtain a copy of the License at7824//7825// http://www.apache.org/licenses/LICENSE-2.07826//7827// Unless required by applicable law or agreed to in writing, software7828// distributed under the License is distributed on an "AS IS" BASIS,7829// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7830// See the License for the specific language governing permissions and7831// limitations under the License.7832Object.defineProperty(exports, "__esModule", ({ value: true }));7833exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0;7834const SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2';7835const OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token';7836const OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt';7837/**7838 * Defines the response of a 3rd party executable run by the pluggable auth client.7839 */7840class ExecutableResponse {7841 /**7842 * Instantiates an ExecutableResponse instance using the provided JSON object7843 * from the output of the executable.7844 * @param responseJson Response from a 3rd party executable, loaded from a7845 * run of the executable or a cached output file.7846 */7847 constructor(responseJson) {7848 // Check that the required fields exist in the json response.7849 if (!responseJson.version) {7850 throw new InvalidVersionFieldError("Executable response must contain a 'version' field.");7851 }7852 if (responseJson.success === undefined) {7853 throw new InvalidSuccessFieldError("Executable response must contain a 'success' field.");7854 }7855 this.version = responseJson.version;7856 this.success = responseJson.success;7857 // Validate required fields for a successful response.7858 if (this.success) {7859 this.expirationTime = responseJson.expiration_time;7860 this.tokenType = responseJson.token_type;7861 // Validate token type field.7862 if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE &&7863 this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 &&7864 this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) {7865 throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " +7866 `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`);7867 }7868 // Validate subject token.7869 if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) {7870 if (!responseJson.saml_response) {7871 throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`);7872 }7873 this.subjectToken = responseJson.saml_response;7874 }7875 else {7876 if (!responseJson.id_token) {7877 throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " +7878 `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`);7879 }7880 this.subjectToken = responseJson.id_token;7881 }7882 }7883 else {7884 // Both code and message must be provided for unsuccessful responses.7885 if (!responseJson.code) {7886 throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful.");7887 }7888 if (!responseJson.message) {7889 throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful.");7890 }7891 this.errorCode = responseJson.code;7892 this.errorMessage = responseJson.message;7893 }7894 }7895 /**7896 * @return A boolean representing if the response has a valid token. Returns7897 * true when the response was successful and the token is not expired.7898 */7899 isValid() {7900 return !this.isExpired() && this.success;7901 }7902 /**7903 * @return A boolean representing if the response is expired. Returns true if the7904 * provided timeout has passed.7905 */7906 isExpired() {7907 return (this.expirationTime !== undefined &&7908 this.expirationTime < Math.round(Date.now() / 1000));7909 }7910}7911exports.ExecutableResponse = ExecutableResponse;7912/**7913 * An error thrown by the ExecutableResponse class.7914 */7915class ExecutableResponseError extends Error {7916 constructor(message) {7917 super(message);7918 Object.setPrototypeOf(this, new.target.prototype);7919 }7920}7921exports.ExecutableResponseError = ExecutableResponseError;7922/**7923 * An error thrown when the 'version' field in an executable response is missing or invalid.7924 */7925class InvalidVersionFieldError extends ExecutableResponseError {7926}7927exports.InvalidVersionFieldError = InvalidVersionFieldError;7928/**7929 * An error thrown when the 'success' field in an executable response is missing or invalid.7930 */7931class InvalidSuccessFieldError extends ExecutableResponseError {7932}7933exports.InvalidSuccessFieldError = InvalidSuccessFieldError;7934/**7935 * An error thrown when the 'expiration_time' field in an executable response is missing or invalid.7936 */7937class InvalidExpirationTimeFieldError extends ExecutableResponseError {7938}7939exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError;7940/**7941 * An error thrown when the 'token_type' field in an executable response is missing or invalid.7942 */7943class InvalidTokenTypeFieldError extends ExecutableResponseError {7944}7945exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError;7946/**7947 * An error thrown when the 'code' field in an executable response is missing or invalid.7948 */7949class InvalidCodeFieldError extends ExecutableResponseError {7950}7951exports.InvalidCodeFieldError = InvalidCodeFieldError;7952/**7953 * An error thrown when the 'message' field in an executable response is missing or invalid.7954 */7955class InvalidMessageFieldError extends ExecutableResponseError {7956}7957exports.InvalidMessageFieldError = InvalidMessageFieldError;7958/**7959 * An error thrown when the subject token in an executable response is missing or invalid.7960 */7961class InvalidSubjectTokenError extends ExecutableResponseError {7962}7963exports.InvalidSubjectTokenError = InvalidSubjectTokenError;7964//# sourceMappingURL=executable-response.js.map7965/***/ }),7966/***/ 4381:7967/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {7968"use strict";7969// Copyright 2021 Google LLC7970//7971// Licensed under the Apache License, Version 2.0 (the "License");7972// you may not use this file except in compliance with the License.7973// You may obtain a copy of the License at7974//7975// http://www.apache.org/licenses/LICENSE-2.07976//7977// Unless required by applicable law or agreed to in writing, software7978// distributed under the License is distributed on an "AS IS" BASIS,7979// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.7980// See the License for the specific language governing permissions and7981// limitations under the License.7982Object.defineProperty(exports, "__esModule", ({ value: true }));7983exports.ExternalAccountClient = void 0;7984const baseexternalclient_1 = __nccwpck_require__(7391);7985const identitypoolclient_1 = __nccwpck_require__(117);7986const awsclient_1 = __nccwpck_require__(1569);7987const pluggable_auth_client_1 = __nccwpck_require__(4782);7988/**7989 * Dummy class with no constructor. Developers are expected to use fromJSON.7990 */7991class ExternalAccountClient {7992 constructor() {7993 throw new Error('ExternalAccountClients should be initialized via: ' +7994 'ExternalAccountClient.fromJSON(), ' +7995 'directly via explicit constructors, eg. ' +7996 'new AwsClient(options), new IdentityPoolClient(options), new' +7997 'PluggableAuthClientOptions, or via ' +7998 'new GoogleAuth(options).getClient()');7999 }8000 /**8001 * This static method will instantiate the8002 * corresponding type of external account credential depending on the8003 * underlying credential source.8004 * @param options The external account options object typically loaded8005 * from the external account JSON credential file.8006 * @param additionalOptions Optional additional behavior customization8007 * options. These currently customize expiration threshold time and8008 * whether to retry on 401/403 API request errors.8009 * @return A BaseExternalAccountClient instance or null if the options8010 * provided do not correspond to an external account credential.8011 */8012 static fromJSON(options, additionalOptions) {8013 var _a, _b;8014 if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {8015 if ((_a = options.credential_source) === null || _a === void 0 ? void 0 : _a.environment_id) {8016 return new awsclient_1.AwsClient(options, additionalOptions);8017 }8018 else if ((_b = options.credential_source) === null || _b === void 0 ? void 0 : _b.executable) {8019 return new pluggable_auth_client_1.PluggableAuthClient(options, additionalOptions);8020 }8021 else {8022 return new identitypoolclient_1.IdentityPoolClient(options, additionalOptions);8023 }8024 }8025 else {8026 return null;8027 }8028 }8029}8030exports.ExternalAccountClient = ExternalAccountClient;8031//# sourceMappingURL=externalclient.js.map8032/***/ }),8033/***/ 695:8034/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {8035"use strict";8036// Copyright 2019 Google LLC8037//8038// Licensed under the Apache License, Version 2.0 (the "License");8039// you may not use this file except in compliance with the License.8040// You may obtain a copy of the License at8041//8042// http://www.apache.org/licenses/LICENSE-2.08043//8044// Unless required by applicable law or agreed to in writing, software8045// distributed under the License is distributed on an "AS IS" BASIS,8046// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.8047// See the License for the specific language governing permissions and8048// limitations under the License.8049Object.defineProperty(exports, "__esModule", ({ value: true }));8050exports.GoogleAuth = exports.CLOUD_SDK_CLIENT_ID = void 0;8051const child_process_1 = __nccwpck_require__(2081);8052const fs = __nccwpck_require__(7147);8053const gcpMetadata = __nccwpck_require__(3563);8054const os = __nccwpck_require__(2037);8055const path = __nccwpck_require__(1017);8056const crypto_1 = __nccwpck_require__(8043);8057const transporters_1 = __nccwpck_require__(2649);8058const computeclient_1 = __nccwpck_require__(6875);8059const idtokenclient_1 = __nccwpck_require__(298);8060const envDetect_1 = __nccwpck_require__(1380);8061const jwtclient_1 = __nccwpck_require__(3959);8062const refreshclient_1 = __nccwpck_require__(8790);8063const impersonated_1 = __nccwpck_require__(1103);8064const externalclient_1 = __nccwpck_require__(4381);8065const baseexternalclient_1 = __nccwpck_require__(7391);8066exports.CLOUD_SDK_CLIENT_ID = '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com';8067const GoogleAuthExceptionMessages = {8068 NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \n' +8069 'To learn more about authentication and Google APIs, visit: \n' +8070 'https://cloud.google.com/docs/authentication/getting-started',8071};8072class GoogleAuth {8073 constructor(opts) {8074 /**8075 * Caches a value indicating whether the auth layer is running on Google8076 * Compute Engine.8077 * @private8078 */8079 this.checkIsGCE = undefined;8080 // To save the contents of the JSON credential file8081 this.jsonContent = null;8082 this.cachedCredential = null;8083 opts = opts || {};8084 this._cachedProjectId = opts.projectId || null;8085 this.cachedCredential = opts.authClient || null;8086 this.keyFilename = opts.keyFilename || opts.keyFile;8087 this.scopes = opts.scopes;8088 this.jsonContent = opts.credentials || null;8089 this.clientOptions = opts.clientOptions;8090 }8091 // Note: this properly is only public to satisify unit tests.8092 // https://github.com/Microsoft/TypeScript/issues/52288093 get isGCE() {8094 return this.checkIsGCE;8095 }8096 // GAPIC client libraries should always use self-signed JWTs. The following8097 // variables are set on the JWT client in order to indicate the type of library,8098 // and sign the JWT with the correct audience and scopes (if not supplied).8099 setGapicJWTValues(client) {8100 client.defaultServicePath = this.defaultServicePath;8101 client.useJWTAccessWithScope = this.useJWTAccessWithScope;8102 client.defaultScopes = this.defaultScopes;8103 }8104 getProjectId(callback) {8105 if (callback) {8106 this.getProjectIdAsync().then(r => callback(null, r), callback);8107 }8108 else {8109 return this.getProjectIdAsync();8110 }8111 }8112 /**8113 * A temporary method for internal `getProjectId` usages where `null` is8114 * acceptable. In a future major release, `getProjectId` should return `null`8115 * (as the `Promise<string | null>` base signature describes) and this private8116 * method should be removed.8117 *8118 * @returns Promise that resolves with project id (or `null`)8119 */8120 async getProjectIdOptional() {8121 try {8122 return await this.getProjectId();8123 }8124 catch (e) {8125 if (e instanceof Error &&8126 e.message === GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {8127 return null;8128 }8129 else {8130 throw e;8131 }8132 }8133 }8134 /*8135 * A private method for finding and caching a projectId.8136 *8137 * Supports environments in order of precedence:8138 * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable8139 * - GOOGLE_APPLICATION_CREDENTIALS JSON file8140 * - Cloud SDK: `gcloud config config-helper --format json`8141 * - GCE project ID from metadata server8142 *8143 * @returns projectId8144 */8145 async findAndCacheProjectId() {8146 let projectId = null;8147 projectId || (projectId = await this.getProductionProjectId());8148 projectId || (projectId = await this.getFileProjectId());8149 projectId || (projectId = await this.getDefaultServiceProjectId());8150 projectId || (projectId = await this.getGCEProjectId());8151 projectId || (projectId = await this.getExternalAccountClientProjectId());8152 if (projectId) {8153 this._cachedProjectId = projectId;8154 return projectId;8155 }8156 else {8157 throw new Error(GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND);8158 }8159 }8160 async getProjectIdAsync() {8161 if (this._cachedProjectId) {8162 return this._cachedProjectId;8163 }8164 if (!this._findProjectIdPromise) {8165 this._findProjectIdPromise = this.findAndCacheProjectId();8166 }8167 return this._findProjectIdPromise;8168 }8169 /**8170 * @returns Any scopes (user-specified or default scopes specified by the8171 * client library) that need to be set on the current Auth client.8172 */8173 getAnyScopes() {8174 return this.scopes || this.defaultScopes;8175 }8176 getApplicationDefault(optionsOrCallback = {}, callback) {8177 let options;8178 if (typeof optionsOrCallback === 'function') {8179 callback = optionsOrCallback;8180 }8181 else {8182 options = optionsOrCallback;8183 }8184 if (callback) {8185 this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback);8186 }8187 else {8188 return this.getApplicationDefaultAsync(options);8189 }8190 }8191 async getApplicationDefaultAsync(options = {}) {8192 // If we've already got a cached credential, just return it.8193 if (this.cachedCredential) {8194 return {8195 credential: this.cachedCredential,8196 projectId: await this.getProjectIdOptional(),8197 };8198 }8199 let credential;8200 let projectId;8201 // Check for the existence of a local environment variable pointing to the8202 // location of the credential file. This is typically used in local8203 // developer scenarios.8204 credential =8205 await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);8206 if (credential) {8207 if (credential instanceof jwtclient_1.JWT) {8208 credential.scopes = this.scopes;8209 }8210 else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {8211 credential.scopes = this.getAnyScopes();8212 }8213 this.cachedCredential = credential;8214 projectId = await this.getProjectIdOptional();8215 return { credential, projectId };8216 }8217 // Look in the well-known credential file location.8218 credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options);8219 if (credential) {8220 if (credential instanceof jwtclient_1.JWT) {8221 credential.scopes = this.scopes;8222 }8223 else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {8224 credential.scopes = this.getAnyScopes();8225 }8226 this.cachedCredential = credential;8227 projectId = await this.getProjectIdOptional();8228 return { credential, projectId };8229 }8230 // Determine if we're running on GCE.8231 let isGCE;8232 try {8233 isGCE = await this._checkIsGCE();8234 }8235 catch (e) {8236 if (e instanceof Error) {8237 e.message = `Unexpected error determining execution environment: ${e.message}`;8238 }8239 throw e;8240 }8241 if (!isGCE) {8242 // We failed to find the default credentials. Bail out with an error.8243 throw new Error('Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.');8244 }8245 // For GCE, just return a default ComputeClient. It will take care of8246 // the rest.8247 options.scopes = this.getAnyScopes();8248 this.cachedCredential = new computeclient_1.Compute(options);8249 projectId = await this.getProjectIdOptional();8250 return { projectId, credential: this.cachedCredential };8251 }8252 /**8253 * Determines whether the auth layer is running on Google Compute Engine.8254 * @returns A promise that resolves with the boolean.8255 * @api private8256 */8257 async _checkIsGCE() {8258 if (this.checkIsGCE === undefined) {8259 this.checkIsGCE = await gcpMetadata.isAvailable();8260 }8261 return this.checkIsGCE;8262 }8263 /**8264 * Attempts to load default credentials from the environment variable path..8265 * @returns Promise that resolves with the OAuth2Client or null.8266 * @api private8267 */8268 async _tryGetApplicationCredentialsFromEnvironmentVariable(options) {8269 const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] ||8270 process.env['google_application_credentials'];8271 if (!credentialsPath || credentialsPath.length === 0) {8272 return null;8273 }8274 try {8275 return this._getApplicationCredentialsFromFilePath(credentialsPath, options);8276 }8277 catch (e) {8278 if (e instanceof Error) {8279 e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`;8280 }8281 throw e;8282 }8283 }8284 /**8285 * Attempts to load default credentials from a well-known file location8286 * @return Promise that resolves with the OAuth2Client or null.8287 * @api private8288 */8289 async _tryGetApplicationCredentialsFromWellKnownFile(options) {8290 // First, figure out the location of the file, depending upon the OS type.8291 let location = null;8292 if (this._isWindows()) {8293 // Windows8294 location = process.env['APPDATA'];8295 }8296 else {8297 // Linux or Mac8298 const home = process.env['HOME'];8299 if (home) {8300 location = path.join(home, '.config');8301 }8302 }8303 // If we found the root path, expand it.8304 if (location) {8305 location = path.join(location, 'gcloud', 'application_default_credentials.json');8306 if (!fs.existsSync(location)) {8307 location = null;8308 }8309 }8310 // The file does not exist.8311 if (!location) {8312 return null;8313 }8314 // The file seems to exist. Try to use it.8315 const client = await this._getApplicationCredentialsFromFilePath(location, options);8316 return client;8317 }8318 /**8319 * Attempts to load default credentials from a file at the given path..8320 * @param filePath The path to the file to read.8321 * @returns Promise that resolves with the OAuth2Client8322 * @api private8323 */8324 async _getApplicationCredentialsFromFilePath(filePath, options = {}) {8325 // Make sure the path looks like a string.8326 if (!filePath || filePath.length === 0) {8327 throw new Error('The file path is invalid.');8328 }8329 // Make sure there is a file at the path. lstatSync will throw if there is8330 // nothing there.8331 try {8332 // Resolve path to actual file in case of symlink. Expect a thrown error8333 // if not resolvable.8334 filePath = fs.realpathSync(filePath);8335 if (!fs.lstatSync(filePath).isFile()) {8336 throw new Error();8337 }8338 }8339 catch (err) {8340 if (err instanceof Error) {8341 err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;8342 }8343 throw err;8344 }8345 // Now open a read stream on the file, and parse it.8346 const readStream = fs.createReadStream(filePath);8347 return this.fromStream(readStream, options);8348 }8349 /**8350 * Create a credentials instance using a given impersonated input options.8351 * @param json The impersonated input object.8352 * @returns JWT or UserRefresh Client with data8353 */8354 fromImpersonatedJSON(json) {8355 var _a, _b, _c, _d;8356 if (!json) {8357 throw new Error('Must pass in a JSON object containing an impersonated refresh token');8358 }8359 if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {8360 throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);8361 }8362 if (!json.source_credentials) {8363 throw new Error('The incoming JSON object does not contain a source_credentials field');8364 }8365 if (!json.service_account_impersonation_url) {8366 throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field');8367 }8368 // Create source client for impersonation8369 const sourceClient = new refreshclient_1.UserRefreshClient(json.source_credentials.client_id, json.source_credentials.client_secret, json.source_credentials.refresh_token);8370 // Extreact service account from service_account_impersonation_url8371 const targetPrincipal = (_b = (_a = /(?<target>[^/]+):generateAccessToken$/.exec(json.service_account_impersonation_url)) === null || _a === void 0 ? void 0 : _a.groups) === null || _b === void 0 ? void 0 : _b.target;8372 if (!targetPrincipal) {8373 throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`);8374 }8375 const targetScopes = (_c = this.getAnyScopes()) !== null && _c !== void 0 ? _c : [];8376 const client = new impersonated_1.Impersonated({8377 delegates: (_d = json.delegates) !== null && _d !== void 0 ? _d : [],8378 sourceClient: sourceClient,8379 targetPrincipal: targetPrincipal,8380 targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes],8381 });8382 return client;8383 }8384 /**8385 * Create a credentials instance using the given input options.8386 * @param json The input object.8387 * @param options The JWT or UserRefresh options for the client8388 * @returns JWT or UserRefresh Client with data8389 */8390 fromJSON(json, options) {8391 let client;8392 if (!json) {8393 throw new Error('Must pass in a JSON object containing the Google auth settings.');8394 }8395 options = options || {};8396 if (json.type === 'authorized_user') {8397 client = new refreshclient_1.UserRefreshClient(options);8398 client.fromJSON(json);8399 }8400 else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {8401 client = this.fromImpersonatedJSON(json);8402 }8403 else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {8404 client = externalclient_1.ExternalAccountClient.fromJSON(json, options);8405 client.scopes = this.getAnyScopes();8406 }8407 else {8408 options.scopes = this.scopes;8409 client = new jwtclient_1.JWT(options);8410 this.setGapicJWTValues(client);8411 client.fromJSON(json);8412 }8413 return client;8414 }8415 /**8416 * Return a JWT or UserRefreshClient from JavaScript object, caching both the8417 * object used to instantiate and the client.8418 * @param json The input object.8419 * @param options The JWT or UserRefresh options for the client8420 * @returns JWT or UserRefresh Client with data8421 */8422 _cacheClientFromJSON(json, options) {8423 let client;8424 // create either a UserRefreshClient or JWT client.8425 options = options || {};8426 if (json.type === 'authorized_user') {8427 client = new refreshclient_1.UserRefreshClient(options);8428 client.fromJSON(json);8429 }8430 else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {8431 client = this.fromImpersonatedJSON(json);8432 }8433 else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {8434 client = externalclient_1.ExternalAccountClient.fromJSON(json, options);8435 client.scopes = this.getAnyScopes();8436 }8437 else {8438 options.scopes = this.scopes;8439 client = new jwtclient_1.JWT(options);8440 this.setGapicJWTValues(client);8441 client.fromJSON(json);8442 }8443 // cache both raw data used to instantiate client and client itself.8444 this.jsonContent = json;8445 this.cachedCredential = client;8446 return client;8447 }8448 fromStream(inputStream, optionsOrCallback = {}, callback) {8449 let options = {};8450 if (typeof optionsOrCallback === 'function') {8451 callback = optionsOrCallback;8452 }8453 else {8454 options = optionsOrCallback;8455 }8456 if (callback) {8457 this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback);8458 }8459 else {8460 return this.fromStreamAsync(inputStream, options);8461 }8462 }8463 fromStreamAsync(inputStream, options) {8464 return new Promise((resolve, reject) => {8465 if (!inputStream) {8466 throw new Error('Must pass in a stream containing the Google auth settings.');8467 }8468 let s = '';8469 inputStream8470 .setEncoding('utf8')8471 .on('error', reject)8472 .on('data', chunk => (s += chunk))8473 .on('end', () => {8474 try {8475 try {8476 const data = JSON.parse(s);8477 const r = this._cacheClientFromJSON(data, options);8478 return resolve(r);8479 }8480 catch (err) {8481 // If we failed parsing this.keyFileName, assume that it8482 // is a PEM or p12 certificate:8483 if (!this.keyFilename)8484 throw err;8485 const client = new jwtclient_1.JWT({8486 ...this.clientOptions,8487 keyFile: this.keyFilename,8488 });8489 this.cachedCredential = client;8490 this.setGapicJWTValues(client);8491 return resolve(client);8492 }8493 }8494 catch (err) {8495 return reject(err);8496 }8497 });8498 });8499 }8500 /**8501 * Create a credentials instance using the given API key string.8502 * @param apiKey The API key string8503 * @param options An optional options object.8504 * @returns A JWT loaded from the key8505 */8506 fromAPIKey(apiKey, options) {8507 options = options || {};8508 const client = new jwtclient_1.JWT(options);8509 client.fromAPIKey(apiKey);8510 return client;8511 }8512 /**8513 * Determines whether the current operating system is Windows.8514 * @api private8515 */8516 _isWindows() {8517 const sys = os.platform();8518 if (sys && sys.length >= 3) {8519 if (sys.substring(0, 3).toLowerCase() === 'win') {8520 return true;8521 }8522 }8523 return false;8524 }8525 /**8526 * Run the Google Cloud SDK command that prints the default project ID8527 */8528 async getDefaultServiceProjectId() {8529 return new Promise(resolve => {8530 (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => {8531 if (!err && stdout) {8532 try {8533 const projectId = JSON.parse(stdout).configuration.properties.core.project;8534 resolve(projectId);8535 return;8536 }8537 catch (e) {8538 // ignore errors8539 }8540 }8541 resolve(null);8542 });8543 });8544 }8545 /**8546 * Loads the project id from environment variables.8547 * @api private8548 */8549 getProductionProjectId() {8550 return (process.env['GCLOUD_PROJECT'] ||8551 process.env['GOOGLE_CLOUD_PROJECT'] ||8552 process.env['gcloud_project'] ||8553 process.env['google_cloud_project']);8554 }8555 /**8556 * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.8557 * @api private8558 */8559 async getFileProjectId() {8560 if (this.cachedCredential) {8561 // Try to read the project ID from the cached credentials file8562 return this.cachedCredential.projectId;8563 }8564 // Ensure the projectId is loaded from the keyFile if available.8565 if (this.keyFilename) {8566 const creds = await this.getClient();8567 if (creds && creds.projectId) {8568 return creds.projectId;8569 }8570 }8571 // Try to load a credentials file and read its project ID8572 const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable();8573 if (r) {8574 return r.projectId;8575 }8576 else {8577 return null;8578 }8579 }8580 /**8581 * Gets the project ID from external account client if available.8582 */8583 async getExternalAccountClientProjectId() {8584 if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {8585 return null;8586 }8587 const creds = await this.getClient();8588 // Do not suppress the underlying error, as the error could contain helpful8589 // information for debugging and fixing. This is especially true for8590 // external account creds as in order to get the project ID, the following8591 // operations have to succeed:8592 // 1. Valid credentials file should be supplied.8593 // 2. Ability to retrieve access tokens from STS token exchange API.8594 // 3. Ability to exchange for service account impersonated credentials (if8595 // enabled).8596 // 4. Ability to get project info using the access token from step 2 or 3.8597 // Without surfacing the error, it is harder for developers to determine8598 // which step went wrong.8599 return await creds.getProjectId();8600 }8601 /**8602 * Gets the Compute Engine project ID if it can be inferred.8603 */8604 async getGCEProjectId() {8605 try {8606 const r = await gcpMetadata.project('project-id');8607 return r;8608 }8609 catch (e) {8610 // Ignore any errors8611 return null;8612 }8613 }8614 getCredentials(callback) {8615 if (callback) {8616 this.getCredentialsAsync().then(r => callback(null, r), callback);8617 }8618 else {8619 return this.getCredentialsAsync();8620 }8621 }8622 async getCredentialsAsync() {8623 const client = await this.getClient();8624 if (client instanceof baseexternalclient_1.BaseExternalAccountClient) {8625 const serviceAccountEmail = client.getServiceAccountEmail();8626 if (serviceAccountEmail) {8627 return { client_email: serviceAccountEmail };8628 }8629 }8630 if (this.jsonContent) {8631 const credential = {8632 client_email: this.jsonContent.client_email,8633 private_key: this.jsonContent.private_key,8634 };8635 return credential;8636 }8637 const isGCE = await this._checkIsGCE();8638 if (!isGCE) {8639 throw new Error('Unknown error.');8640 }8641 // For GCE, return the service account details from the metadata server8642 // NOTE: The trailing '/' at the end of service-accounts/ is very important!8643 // The GCF metadata server doesn't respect querystring params if this / is8644 // not included.8645 const data = await gcpMetadata.instance({8646 property: 'service-accounts/',8647 params: { recursive: 'true' },8648 });8649 if (!data || !data.default || !data.default.email) {8650 throw new Error('Failure from metadata server.');8651 }8652 return { client_email: data.default.email };8653 }8654 /**8655 * Automatically obtain a client based on the provided configuration. If no8656 * options were passed, use Application Default Credentials.8657 */8658 async getClient() {8659 if (!this.cachedCredential) {8660 if (this.jsonContent) {8661 this._cacheClientFromJSON(this.jsonContent, this.clientOptions);8662 }8663 else if (this.keyFilename) {8664 const filePath = path.resolve(this.keyFilename);8665 const stream = fs.createReadStream(filePath);8666 await this.fromStreamAsync(stream, this.clientOptions);8667 }8668 else {8669 await this.getApplicationDefaultAsync(this.clientOptions);8670 }8671 }8672 return this.cachedCredential;8673 }8674 /**8675 * Creates a client which will fetch an ID token for authorization.8676 * @param targetAudience the audience for the fetched ID token.8677 * @returns IdTokenClient for making HTTP calls authenticated with ID tokens.8678 */8679 async getIdTokenClient(targetAudience) {8680 const client = await this.getClient();8681 if (!('fetchIdToken' in client)) {8682 throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.');8683 }8684 return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client });8685 }8686 /**8687 * Automatically obtain application default credentials, and return8688 * an access token for making requests.8689 */8690 async getAccessToken() {8691 const client = await this.getClient();8692 return (await client.getAccessToken()).token;8693 }8694 /**8695 * Obtain the HTTP headers that will provide authorization for a given8696 * request.8697 */8698 async getRequestHeaders(url) {8699 const client = await this.getClient();8700 return client.getRequestHeaders(url);8701 }8702 /**8703 * Obtain credentials for a request, then attach the appropriate headers to8704 * the request options.8705 * @param opts Axios or Request options on which to attach the headers8706 */8707 async authorizeRequest(opts) {8708 opts = opts || {};8709 const url = opts.url || opts.uri;8710 const client = await this.getClient();8711 const headers = await client.getRequestHeaders(url);8712 opts.headers = Object.assign(opts.headers || {}, headers);8713 return opts;8714 }8715 /**8716 * Automatically obtain application default credentials, and make an8717 * HTTP request using the given options.8718 * @param opts Axios request options for the HTTP request.8719 */8720 // eslint-disable-next-line @typescript-eslint/no-explicit-any8721 async request(opts) {8722 const client = await this.getClient();8723 return client.request(opts);8724 }8725 /**8726 * Determine the compute environment in which the code is running.8727 */8728 getEnv() {8729 return (0, envDetect_1.getEnv)();8730 }8731 /**8732 * Sign the given data with the current private key, or go out8733 * to the IAM API to sign it.8734 * @param data The data to be signed.8735 */8736 async sign(data) {8737 const client = await this.getClient();8738 const crypto = (0, crypto_1.createCrypto)();8739 if (client instanceof jwtclient_1.JWT && client.key) {8740 const sign = await crypto.sign(client.key, data);8741 return sign;8742 }8743 const creds = await this.getCredentials();8744 if (!creds.client_email) {8745 throw new Error('Cannot sign data without `client_email`.');8746 }8747 return this.signBlob(crypto, creds.client_email, data);8748 }8749 async signBlob(crypto, emailOrUniqueId, data) {8750 const url = 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' +8751 `${emailOrUniqueId}:signBlob`;8752 const res = await this.request({8753 method: 'POST',8754 url,8755 data: {8756 payload: crypto.encodeBase64StringUtf8(data),8757 },8758 });8759 return res.data.signedBlob;8760 }8761}8762exports.GoogleAuth = GoogleAuth;8763/**8764 * Export DefaultTransporter as a static property of the class.8765 */8766GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter;8767//# sourceMappingURL=googleauth.js.map8768/***/ }),8769/***/ 9735:8770/***/ ((__unused_webpack_module, exports) => {8771"use strict";8772// Copyright 2014 Google LLC8773//8774// Licensed under the Apache License, Version 2.0 (the "License");8775// you may not use this file except in compliance with the License.8776// You may obtain a copy of the License at8777//8778// http://www.apache.org/licenses/LICENSE-2.08779//8780// Unless required by applicable law or agreed to in writing, software8781// distributed under the License is distributed on an "AS IS" BASIS,8782// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.8783// See the License for the specific language governing permissions and8784// limitations under the License.8785Object.defineProperty(exports, "__esModule", ({ value: true }));8786exports.IAMAuth = void 0;8787class IAMAuth {8788 /**8789 * IAM credentials.8790 *8791 * @param selector the iam authority selector8792 * @param token the token8793 * @constructor8794 */8795 constructor(selector, token) {8796 this.selector = selector;8797 this.token = token;8798 this.selector = selector;8799 this.token = token;8800 }8801 /**8802 * Acquire the HTTP headers required to make an authenticated request.8803 */8804 getRequestHeaders() {8805 return {8806 'x-goog-iam-authority-selector': this.selector,8807 'x-goog-iam-authorization-token': this.token,8808 };8809 }8810}8811exports.IAMAuth = IAMAuth;8812//# sourceMappingURL=iam.js.map8813/***/ }),8814/***/ 117:8815/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {8816"use strict";8817// Copyright 2021 Google LLC8818//8819// Licensed under the Apache License, Version 2.0 (the "License");8820// you may not use this file except in compliance with the License.8821// You may obtain a copy of the License at8822//8823// http://www.apache.org/licenses/LICENSE-2.08824//8825// Unless required by applicable law or agreed to in writing, software8826// distributed under the License is distributed on an "AS IS" BASIS,8827// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.8828// See the License for the specific language governing permissions and8829// limitations under the License.8830var _a, _b, _c;8831Object.defineProperty(exports, "__esModule", ({ value: true }));8832exports.IdentityPoolClient = void 0;8833const fs = __nccwpck_require__(7147);8834const util_1 = __nccwpck_require__(3837);8835const baseexternalclient_1 = __nccwpck_require__(7391);8836// fs.readfile is undefined in browser karma tests causing8837// `npm run browser-test` to fail as test.oauth2.ts imports this file via8838// src/index.ts.8839// Fallback to void function to avoid promisify throwing a TypeError.8840const readFile = (0, util_1.promisify)((_a = fs.readFile) !== null && _a !== void 0 ? _a : (() => { }));8841const realpath = (0, util_1.promisify)((_b = fs.realpath) !== null && _b !== void 0 ? _b : (() => { }));8842const lstat = (0, util_1.promisify)((_c = fs.lstat) !== null && _c !== void 0 ? _c : (() => { }));8843/**8844 * Defines the Url-sourced and file-sourced external account clients mainly8845 * used for K8s and Azure workloads.8846 */8847class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {8848 /**8849 * Instantiate an IdentityPoolClient instance using the provided JSON8850 * object loaded from an external account credentials file.8851 * An error is thrown if the credential is not a valid file-sourced or8852 * url-sourced credential or a workforce pool user project is provided8853 * with a non workforce audience.8854 * @param options The external account options object typically loaded8855 * from the external account JSON credential file.8856 * @param additionalOptions Optional additional behavior customization8857 * options. These currently customize expiration threshold time and8858 * whether to retry on 401/403 API request errors.8859 */8860 constructor(options, additionalOptions) {8861 var _a, _b;8862 super(options, additionalOptions);8863 this.file = options.credential_source.file;8864 this.url = options.credential_source.url;8865 this.headers = options.credential_source.headers;8866 if (!this.file && !this.url) {8867 throw new Error('No valid Identity Pool "credential_source" provided');8868 }8869 // Text is the default format type.8870 this.formatType = ((_a = options.credential_source.format) === null || _a === void 0 ? void 0 : _a.type) || 'text';8871 this.formatSubjectTokenFieldName =8872 (_b = options.credential_source.format) === null || _b === void 0 ? void 0 : _b.subject_token_field_name;8873 if (this.formatType !== 'json' && this.formatType !== 'text') {8874 throw new Error(`Invalid credential_source format "${this.formatType}"`);8875 }8876 if (this.formatType === 'json' && !this.formatSubjectTokenFieldName) {8877 throw new Error('Missing subject_token_field_name for JSON credential_source format');8878 }8879 }8880 /**8881 * Triggered when a external subject token is needed to be exchanged for a GCP8882 * access token via GCP STS endpoint.8883 * This uses the `options.credential_source` object to figure out how8884 * to retrieve the token using the current environment. In this case,8885 * this either retrieves the local credential from a file location (k8s8886 * workload) or by sending a GET request to a local metadata server (Azure8887 * workloads).8888 * @return A promise that resolves with the external subject token.8889 */8890 async retrieveSubjectToken() {8891 if (this.file) {8892 return await this.getTokenFromFile(this.file, this.formatType, this.formatSubjectTokenFieldName);8893 }8894 return await this.getTokenFromUrl(this.url, this.formatType, this.formatSubjectTokenFieldName, this.headers);8895 }8896 /**8897 * Looks up the external subject token in the file path provided and8898 * resolves with that token.8899 * @param file The file path where the external credential is located.8900 * @param formatType The token file or URL response type (JSON or text).8901 * @param formatSubjectTokenFieldName For JSON response types, this is the8902 * subject_token field name. For Azure, this is access_token. For text8903 * response types, this is ignored.8904 * @return A promise that resolves with the external subject token.8905 */8906 async getTokenFromFile(filePath, formatType, formatSubjectTokenFieldName) {8907 // Make sure there is a file at the path. lstatSync will throw if there is8908 // nothing there.8909 try {8910 // Resolve path to actual file in case of symlink. Expect a thrown error8911 // if not resolvable.8912 filePath = await realpath(filePath);8913 if (!(await lstat(filePath)).isFile()) {8914 throw new Error();8915 }8916 }8917 catch (err) {8918 if (err instanceof Error) {8919 err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;8920 }8921 throw err;8922 }8923 let subjectToken;8924 const rawText = await readFile(filePath, { encoding: 'utf8' });8925 if (formatType === 'text') {8926 subjectToken = rawText;8927 }8928 else if (formatType === 'json' && formatSubjectTokenFieldName) {8929 const json = JSON.parse(rawText);8930 subjectToken = json[formatSubjectTokenFieldName];8931 }8932 if (!subjectToken) {8933 throw new Error('Unable to parse the subject_token from the credential_source file');8934 }8935 return subjectToken;8936 }8937 /**8938 * Sends a GET request to the URL provided and resolves with the returned8939 * external subject token.8940 * @param url The URL to call to retrieve the subject token. This is typically8941 * a local metadata server.8942 * @param formatType The token file or URL response type (JSON or text).8943 * @param formatSubjectTokenFieldName For JSON response types, this is the8944 * subject_token field name. For Azure, this is access_token. For text8945 * response types, this is ignored.8946 * @param headers The optional additional headers to send with the request to8947 * the metadata server url.8948 * @return A promise that resolves with the external subject token.8949 */8950 async getTokenFromUrl(url, formatType, formatSubjectTokenFieldName, headers) {8951 const opts = {8952 url,8953 method: 'GET',8954 headers,8955 responseType: formatType,8956 };8957 let subjectToken;8958 if (formatType === 'text') {8959 const response = await this.transporter.request(opts);8960 subjectToken = response.data;8961 }8962 else if (formatType === 'json' && formatSubjectTokenFieldName) {8963 const response = await this.transporter.request(opts);8964 subjectToken = response.data[formatSubjectTokenFieldName];8965 }8966 if (!subjectToken) {8967 throw new Error('Unable to parse the subject_token from the credential_source URL');8968 }8969 return subjectToken;8970 }8971}8972exports.IdentityPoolClient = IdentityPoolClient;8973//# sourceMappingURL=identitypoolclient.js.map8974/***/ }),8975/***/ 298:8976/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {8977"use strict";8978// Copyright 2020 Google LLC8979//8980// Licensed under the Apache License, Version 2.0 (the "License");8981// you may not use this file except in compliance with the License.8982// You may obtain a copy of the License at8983//8984// http://www.apache.org/licenses/LICENSE-2.08985//8986// Unless required by applicable law or agreed to in writing, software8987// distributed under the License is distributed on an "AS IS" BASIS,8988// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.8989// See the License for the specific language governing permissions and8990// limitations under the License.8991Object.defineProperty(exports, "__esModule", ({ value: true }));8992exports.IdTokenClient = void 0;8993const oauth2client_1 = __nccwpck_require__(3936);8994class IdTokenClient extends oauth2client_1.OAuth2Client {8995 /**8996 * Google ID Token client8997 *8998 * Retrieve access token from the metadata server.8999 * See: https://developers.google.com/compute/docs/authentication9000 */9001 constructor(options) {9002 super();9003 this.targetAudience = options.targetAudience;9004 this.idTokenProvider = options.idTokenProvider;9005 }9006 async getRequestMetadataAsync(9007 // eslint-disable-next-line @typescript-eslint/no-unused-vars9008 url) {9009 if (!this.credentials.id_token ||9010 (this.credentials.expiry_date || 0) < Date.now()) {9011 const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);9012 this.credentials = {9013 id_token: idToken,9014 expiry_date: this.getIdTokenExpiryDate(idToken),9015 };9016 }9017 const headers = {9018 Authorization: 'Bearer ' + this.credentials.id_token,9019 };9020 return { headers };9021 }9022 getIdTokenExpiryDate(idToken) {9023 const payloadB64 = idToken.split('.')[1];9024 if (payloadB64) {9025 const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii'));9026 return payload.exp * 1000;9027 }9028 }9029}9030exports.IdTokenClient = IdTokenClient;9031//# sourceMappingURL=idtokenclient.js.map9032/***/ }),9033/***/ 1103:9034/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {9035"use strict";9036/**9037 * Copyright 2021 Google LLC9038 *9039 * Licensed under the Apache License, Version 2.0 (the "License");9040 * you may not use this file except in compliance with the License.9041 * You may obtain a copy of the License at9042 *9043 * http://www.apache.org/licenses/LICENSE-2.09044 *9045 * Unless required by applicable law or agreed to in writing, software9046 * distributed under the License is distributed on an "AS IS" BASIS,9047 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9048 * See the License for the specific language governing permissions and9049 * limitations under the License.9050 */9051Object.defineProperty(exports, "__esModule", ({ value: true }));9052exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0;9053const oauth2client_1 = __nccwpck_require__(3936);9054const gaxios_1 = __nccwpck_require__(9555);9055exports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account';9056class Impersonated extends oauth2client_1.OAuth2Client {9057 /**9058 * Impersonated service account credentials.9059 *9060 * Create a new access token by impersonating another service account.9061 *9062 * Impersonated Credentials allowing credentials issued to a user or9063 * service account to impersonate another. The source project using9064 * Impersonated Credentials must enable the "IAMCredentials" API.9065 * Also, the target service account must grant the orginating principal9066 * the "Service Account Token Creator" IAM role.9067 *9068 * @param {object} options - The configuration object.9069 * @param {object} [options.sourceClient] the source credential used as to9070 * acquire the impersonated credentials.9071 * @param {string} [options.targetPrincipal] the service account to9072 * impersonate.9073 * @param {string[]} [options.delegates] the chained list of delegates9074 * required to grant the final access_token. If set, the sequence of9075 * identities must have "Service Account Token Creator" capability granted to9076 * the preceding identity. For example, if set to [serviceAccountB,9077 * serviceAccountC], the sourceCredential must have the Token Creator role on9078 * serviceAccountB. serviceAccountB must have the Token Creator on9079 * serviceAccountC. Finally, C must have Token Creator on target_principal.9080 * If left unset, sourceCredential must have that role on targetPrincipal.9081 * @param {string[]} [options.targetScopes] scopes to request during the9082 * authorization grant.9083 * @param {number} [options.lifetime] number of seconds the delegated9084 * credential should be valid for up to 3600 seconds by default, or 43,2009085 * seconds by extending the token's lifetime, see:9086 * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth9087 * @param {string} [options.endpoint] api endpoint override.9088 */9089 constructor(options = {}) {9090 var _a, _b, _c, _d, _e, _f;9091 super(options);9092 this.credentials = {9093 expiry_date: 1,9094 refresh_token: 'impersonated-placeholder',9095 };9096 this.sourceClient = (_a = options.sourceClient) !== null && _a !== void 0 ? _a : new oauth2client_1.OAuth2Client();9097 this.targetPrincipal = (_b = options.targetPrincipal) !== null && _b !== void 0 ? _b : '';9098 this.delegates = (_c = options.delegates) !== null && _c !== void 0 ? _c : [];9099 this.targetScopes = (_d = options.targetScopes) !== null && _d !== void 0 ? _d : [];9100 this.lifetime = (_e = options.lifetime) !== null && _e !== void 0 ? _e : 3600;9101 this.endpoint = (_f = options.endpoint) !== null && _f !== void 0 ? _f : 'https://iamcredentials.googleapis.com';9102 }9103 /**9104 * Refreshes the access token.9105 * @param refreshToken Unused parameter9106 */9107 async refreshToken(refreshToken) {9108 var _a, _b, _c, _d, _e, _f;9109 try {9110 await this.sourceClient.getAccessToken();9111 const name = 'projects/-/serviceAccounts/' + this.targetPrincipal;9112 const u = `${this.endpoint}/v1/${name}:generateAccessToken`;9113 const body = {9114 delegates: this.delegates,9115 scope: this.targetScopes,9116 lifetime: this.lifetime + 's',9117 };9118 const res = await this.sourceClient.request({9119 url: u,9120 data: body,9121 method: 'POST',9122 });9123 const tokenResponse = res.data;9124 this.credentials.access_token = tokenResponse.accessToken;9125 this.credentials.expiry_date = Date.parse(tokenResponse.expireTime);9126 return {9127 tokens: this.credentials,9128 res,9129 };9130 }9131 catch (error) {9132 if (!(error instanceof Error))9133 throw error;9134 let status = 0;9135 let message = '';9136 if (error instanceof gaxios_1.GaxiosError) {9137 status = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.status;9138 message = (_f = (_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message;9139 }9140 if (status && message) {9141 error.message = `${status}: unable to impersonate: ${message}`;9142 throw error;9143 }9144 else {9145 error.message = `unable to impersonate: ${error}`;9146 throw error;9147 }9148 }9149 }9150 /**9151 * Generates an OpenID Connect ID token for a service account.9152 *9153 * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation}9154 *9155 * @param targetAudience the audience for the fetched ID token.9156 * @param options the for the request9157 * @return an OpenID Connect ID token9158 */9159 async fetchIdToken(targetAudience, options) {9160 var _a;9161 await this.sourceClient.getAccessToken();9162 const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;9163 const u = `${this.endpoint}/v1/${name}:generateIdToken`;9164 const body = {9165 delegates: this.delegates,9166 audience: targetAudience,9167 includeEmail: (_a = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _a !== void 0 ? _a : true,9168 };9169 const res = await this.sourceClient.request({9170 url: u,9171 data: body,9172 method: 'POST',9173 });9174 return res.data.token;9175 }9176}9177exports.Impersonated = Impersonated;9178//# sourceMappingURL=impersonated.js.map9179/***/ }),9180/***/ 8740:9181/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {9182"use strict";9183// Copyright 2015 Google LLC9184//9185// Licensed under the Apache License, Version 2.0 (the "License");9186// you may not use this file except in compliance with the License.9187// You may obtain a copy of the License at9188//9189// http://www.apache.org/licenses/LICENSE-2.09190//9191// Unless required by applicable law or agreed to in writing, software9192// distributed under the License is distributed on an "AS IS" BASIS,9193// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9194// See the License for the specific language governing permissions and9195// limitations under the License.9196Object.defineProperty(exports, "__esModule", ({ value: true }));9197exports.JWTAccess = void 0;9198const jws = __nccwpck_require__(4636);9199const LRU = __nccwpck_require__(7129);9200const DEFAULT_HEADER = {9201 alg: 'RS256',9202 typ: 'JWT',9203};9204class JWTAccess {9205 /**9206 * JWTAccess service account credentials.9207 *9208 * Create a new access token by using the credential to create a new JWT token9209 * that's recognized as the access token.9210 *9211 * @param email the service account email address.9212 * @param key the private key that will be used to sign the token.9213 * @param keyId the ID of the private key used to sign the token.9214 */9215 constructor(email, key, keyId, eagerRefreshThresholdMillis) {9216 this.cache = new LRU({9217 max: 500,9218 maxAge: 60 * 60 * 1000,9219 });9220 this.email = email;9221 this.key = key;9222 this.keyId = keyId;9223 this.eagerRefreshThresholdMillis =9224 eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000;9225 }9226 /**9227 * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url9228 *9229 * @param url The URI being authorized.9230 * @param scopes The scope or scopes being authorized9231 * @returns A string that returns the cached key.9232 */9233 getCachedKey(url, scopes) {9234 let cacheKey = url;9235 if (scopes && Array.isArray(scopes) && scopes.length) {9236 cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`;9237 }9238 else if (typeof scopes === 'string') {9239 cacheKey = url ? `${url}_${scopes}` : scopes;9240 }9241 if (!cacheKey) {9242 throw Error('Scopes or url must be provided');9243 }9244 return cacheKey;9245 }9246 /**9247 * Get a non-expired access token, after refreshing if necessary.9248 *9249 * @param url The URI being authorized.9250 * @param additionalClaims An object with a set of additional claims to9251 * include in the payload.9252 * @returns An object that includes the authorization header.9253 */9254 getRequestHeaders(url, additionalClaims, scopes) {9255 // Return cached authorization headers, unless we are within9256 // eagerRefreshThresholdMillis ms of them expiring:9257 const key = this.getCachedKey(url, scopes);9258 const cachedToken = this.cache.get(key);9259 const now = Date.now();9260 if (cachedToken &&9261 cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {9262 return cachedToken.headers;9263 }9264 const iat = Math.floor(Date.now() / 1000);9265 const exp = JWTAccess.getExpirationTime(iat);9266 let defaultClaims;9267 // Turn scopes into space-separated string9268 if (Array.isArray(scopes)) {9269 scopes = scopes.join(' ');9270 }9271 // If scopes are specified, sign with scopes9272 if (scopes) {9273 defaultClaims = {9274 iss: this.email,9275 sub: this.email,9276 scope: scopes,9277 exp,9278 iat,9279 };9280 }9281 else {9282 defaultClaims = {9283 iss: this.email,9284 sub: this.email,9285 aud: url,9286 exp,9287 iat,9288 };9289 }9290 // if additionalClaims are provided, ensure they do not collide with9291 // other required claims.9292 if (additionalClaims) {9293 for (const claim in defaultClaims) {9294 if (additionalClaims[claim]) {9295 throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);9296 }9297 }9298 }9299 const header = this.keyId9300 ? { ...DEFAULT_HEADER, kid: this.keyId }9301 : DEFAULT_HEADER;9302 const payload = Object.assign(defaultClaims, additionalClaims);9303 // Sign the jwt and add it to the cache9304 const signedJWT = jws.sign({ header, payload, secret: this.key });9305 const headers = { Authorization: `Bearer ${signedJWT}` };9306 this.cache.set(key, {9307 expiration: exp * 1000,9308 headers,9309 });9310 return headers;9311 }9312 /**9313 * Returns an expiration time for the JWT token.9314 *9315 * @param iat The issued at time for the JWT.9316 * @returns An expiration time for the JWT.9317 */9318 static getExpirationTime(iat) {9319 const exp = iat + 3600; // 3600 seconds = 1 hour9320 return exp;9321 }9322 /**9323 * Create a JWTAccess credentials instance using the given input options.9324 * @param json The input object.9325 */9326 fromJSON(json) {9327 if (!json) {9328 throw new Error('Must pass in a JSON object containing the service account auth settings.');9329 }9330 if (!json.client_email) {9331 throw new Error('The incoming JSON object does not contain a client_email field');9332 }9333 if (!json.private_key) {9334 throw new Error('The incoming JSON object does not contain a private_key field');9335 }9336 // Extract the relevant information from the json key file.9337 this.email = json.client_email;9338 this.key = json.private_key;9339 this.keyId = json.private_key_id;9340 this.projectId = json.project_id;9341 }9342 fromStream(inputStream, callback) {9343 if (callback) {9344 this.fromStreamAsync(inputStream).then(() => callback(), callback);9345 }9346 else {9347 return this.fromStreamAsync(inputStream);9348 }9349 }9350 fromStreamAsync(inputStream) {9351 return new Promise((resolve, reject) => {9352 if (!inputStream) {9353 reject(new Error('Must pass in a stream containing the service account auth settings.'));9354 }9355 let s = '';9356 inputStream9357 .setEncoding('utf8')9358 .on('data', chunk => (s += chunk))9359 .on('error', reject)9360 .on('end', () => {9361 try {9362 const data = JSON.parse(s);9363 this.fromJSON(data);9364 resolve();9365 }9366 catch (err) {9367 reject(err);9368 }9369 });9370 });9371 }9372}9373exports.JWTAccess = JWTAccess;9374//# sourceMappingURL=jwtaccess.js.map9375/***/ }),9376/***/ 3959:9377/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {9378"use strict";9379// Copyright 2013 Google LLC9380//9381// Licensed under the Apache License, Version 2.0 (the "License");9382// you may not use this file except in compliance with the License.9383// You may obtain a copy of the License at9384//9385// http://www.apache.org/licenses/LICENSE-2.09386//9387// Unless required by applicable law or agreed to in writing, software9388// distributed under the License is distributed on an "AS IS" BASIS,9389// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9390// See the License for the specific language governing permissions and9391// limitations under the License.9392Object.defineProperty(exports, "__esModule", ({ value: true }));9393exports.JWT = void 0;9394const gtoken_1 = __nccwpck_require__(6031);9395const jwtaccess_1 = __nccwpck_require__(8740);9396const oauth2client_1 = __nccwpck_require__(3936);9397class JWT extends oauth2client_1.OAuth2Client {9398 constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) {9399 const opts = optionsOrEmail && typeof optionsOrEmail === 'object'9400 ? optionsOrEmail9401 : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject };9402 super({9403 eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis,9404 forceRefreshOnFailure: opts.forceRefreshOnFailure,9405 });9406 this.email = opts.email;9407 this.keyFile = opts.keyFile;9408 this.key = opts.key;9409 this.keyId = opts.keyId;9410 this.scopes = opts.scopes;9411 this.subject = opts.subject;9412 this.additionalClaims = opts.additionalClaims;9413 this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 };9414 }9415 /**9416 * Creates a copy of the credential with the specified scopes.9417 * @param scopes List of requested scopes or a single scope.9418 * @return The cloned instance.9419 */9420 createScoped(scopes) {9421 return new JWT({9422 email: this.email,9423 keyFile: this.keyFile,9424 key: this.key,9425 keyId: this.keyId,9426 scopes,9427 subject: this.subject,9428 additionalClaims: this.additionalClaims,9429 });9430 }9431 /**9432 * Obtains the metadata to be sent with the request.9433 *9434 * @param url the URI being authorized.9435 */9436 async getRequestMetadataAsync(url) {9437 url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url;9438 const useSelfSignedJWT = (!this.hasUserScopes() && url) ||9439 (this.useJWTAccessWithScope && this.hasAnyScopes());9440 if (!this.apiKey && useSelfSignedJWT) {9441 if (this.additionalClaims &&9442 this.additionalClaims.target_audience) {9443 const { tokens } = await this.refreshToken();9444 return {9445 headers: this.addSharedMetadataHeaders({9446 Authorization: `Bearer ${tokens.id_token}`,9447 }),9448 };9449 }9450 else {9451 // no scopes have been set, but a uri has been provided. Use JWTAccess9452 // credentials.9453 if (!this.access) {9454 this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);9455 }9456 let scopes;9457 if (this.hasUserScopes()) {9458 scopes = this.scopes;9459 }9460 else if (!url) {9461 scopes = this.defaultScopes;9462 }9463 const headers = await this.access.getRequestHeaders(url !== null && url !== void 0 ? url : undefined, this.additionalClaims, 9464 // Scopes take precedent over audience for signing,9465 // so we only provide them if useJWTAccessWithScope is on9466 this.useJWTAccessWithScope ? scopes : undefined);9467 return { headers: this.addSharedMetadataHeaders(headers) };9468 }9469 }9470 else if (this.hasAnyScopes() || this.apiKey) {9471 return super.getRequestMetadataAsync(url);9472 }9473 else {9474 // If no audience, apiKey, or scopes are provided, we should not attempt9475 // to populate any headers:9476 return { headers: {} };9477 }9478 }9479 /**9480 * Fetches an ID token.9481 * @param targetAudience the audience for the fetched ID token.9482 */9483 async fetchIdToken(targetAudience) {9484 // Create a new gToken for fetching an ID token9485 const gtoken = new gtoken_1.GoogleToken({9486 iss: this.email,9487 sub: this.subject,9488 scope: this.scopes || this.defaultScopes,9489 keyFile: this.keyFile,9490 key: this.key,9491 additionalClaims: { target_audience: targetAudience },9492 transporter: this.transporter,9493 });9494 await gtoken.getToken({9495 forceRefresh: true,9496 });9497 if (!gtoken.idToken) {9498 throw new Error('Unknown error: Failed to fetch ID token');9499 }9500 return gtoken.idToken;9501 }9502 /**9503 * Determine if there are currently scopes available.9504 */9505 hasUserScopes() {9506 if (!this.scopes) {9507 return false;9508 }9509 return this.scopes.length > 0;9510 }9511 /**9512 * Are there any default or user scopes defined.9513 */9514 hasAnyScopes() {9515 if (this.scopes && this.scopes.length > 0)9516 return true;9517 if (this.defaultScopes && this.defaultScopes.length > 0)9518 return true;9519 return false;9520 }9521 authorize(callback) {9522 if (callback) {9523 this.authorizeAsync().then(r => callback(null, r), callback);9524 }9525 else {9526 return this.authorizeAsync();9527 }9528 }9529 async authorizeAsync() {9530 const result = await this.refreshToken();9531 if (!result) {9532 throw new Error('No result returned');9533 }9534 this.credentials = result.tokens;9535 this.credentials.refresh_token = 'jwt-placeholder';9536 this.key = this.gtoken.key;9537 this.email = this.gtoken.iss;9538 return result.tokens;9539 }9540 /**9541 * Refreshes the access token.9542 * @param refreshToken ignored9543 * @private9544 */9545 async refreshTokenNoCache(9546 // eslint-disable-next-line @typescript-eslint/no-unused-vars9547 refreshToken) {9548 const gtoken = this.createGToken();9549 const token = await gtoken.getToken({9550 forceRefresh: this.isTokenExpiring(),9551 });9552 const tokens = {9553 access_token: token.access_token,9554 token_type: 'Bearer',9555 expiry_date: gtoken.expiresAt,9556 id_token: gtoken.idToken,9557 };9558 this.emit('tokens', tokens);9559 return { res: null, tokens };9560 }9561 /**9562 * Create a gToken if it doesn't already exist.9563 */9564 createGToken() {9565 if (!this.gtoken) {9566 this.gtoken = new gtoken_1.GoogleToken({9567 iss: this.email,9568 sub: this.subject,9569 scope: this.scopes || this.defaultScopes,9570 keyFile: this.keyFile,9571 key: this.key,9572 additionalClaims: this.additionalClaims,9573 transporter: this.transporter,9574 });9575 }9576 return this.gtoken;9577 }9578 /**9579 * Create a JWT credentials instance using the given input options.9580 * @param json The input object.9581 */9582 fromJSON(json) {9583 if (!json) {9584 throw new Error('Must pass in a JSON object containing the service account auth settings.');9585 }9586 if (!json.client_email) {9587 throw new Error('The incoming JSON object does not contain a client_email field');9588 }9589 if (!json.private_key) {9590 throw new Error('The incoming JSON object does not contain a private_key field');9591 }9592 // Extract the relevant information from the json key file.9593 this.email = json.client_email;9594 this.key = json.private_key;9595 this.keyId = json.private_key_id;9596 this.projectId = json.project_id;9597 this.quotaProjectId = json.quota_project_id;9598 }9599 fromStream(inputStream, callback) {9600 if (callback) {9601 this.fromStreamAsync(inputStream).then(() => callback(), callback);9602 }9603 else {9604 return this.fromStreamAsync(inputStream);9605 }9606 }9607 fromStreamAsync(inputStream) {9608 return new Promise((resolve, reject) => {9609 if (!inputStream) {9610 throw new Error('Must pass in a stream containing the service account auth settings.');9611 }9612 let s = '';9613 inputStream9614 .setEncoding('utf8')9615 .on('error', reject)9616 .on('data', chunk => (s += chunk))9617 .on('end', () => {9618 try {9619 const data = JSON.parse(s);9620 this.fromJSON(data);9621 resolve();9622 }9623 catch (e) {9624 reject(e);9625 }9626 });9627 });9628 }9629 /**9630 * Creates a JWT credentials instance using an API Key for authentication.9631 * @param apiKey The API Key in string form.9632 */9633 fromAPIKey(apiKey) {9634 if (typeof apiKey !== 'string') {9635 throw new Error('Must provide an API Key string.');9636 }9637 this.apiKey = apiKey;9638 }9639 /**9640 * Using the key or keyFile on the JWT client, obtain an object that contains9641 * the key and the client email.9642 */9643 async getCredentials() {9644 if (this.key) {9645 return { private_key: this.key, client_email: this.email };9646 }9647 else if (this.keyFile) {9648 const gtoken = this.createGToken();9649 const creds = await gtoken.getCredentials(this.keyFile);9650 return { private_key: creds.privateKey, client_email: creds.clientEmail };9651 }9652 throw new Error('A key or a keyFile must be provided to getCredentials.');9653 }9654}9655exports.JWT = JWT;9656//# sourceMappingURL=jwtclient.js.map9657/***/ }),9658/***/ 4524:9659/***/ ((__unused_webpack_module, exports) => {9660"use strict";9661// Copyright 2014 Google LLC9662//9663// Licensed under the Apache License, Version 2.0 (the "License");9664// you may not use this file except in compliance with the License.9665// You may obtain a copy of the License at9666//9667// http://www.apache.org/licenses/LICENSE-2.09668//9669// Unless required by applicable law or agreed to in writing, software9670// distributed under the License is distributed on an "AS IS" BASIS,9671// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9672// See the License for the specific language governing permissions and9673// limitations under the License.9674Object.defineProperty(exports, "__esModule", ({ value: true }));9675exports.LoginTicket = void 0;9676class LoginTicket {9677 /**9678 * Create a simple class to extract user ID from an ID Token9679 *9680 * @param {string} env Envelope of the jwt9681 * @param {TokenPayload} pay Payload of the jwt9682 * @constructor9683 */9684 constructor(env, pay) {9685 this.envelope = env;9686 this.payload = pay;9687 }9688 getEnvelope() {9689 return this.envelope;9690 }9691 getPayload() {9692 return this.payload;9693 }9694 /**9695 * Create a simple class to extract user ID from an ID Token9696 *9697 * @return The user ID9698 */9699 getUserId() {9700 const payload = this.getPayload();9701 if (payload && payload.sub) {9702 return payload.sub;9703 }9704 return null;9705 }9706 /**9707 * Returns attributes from the login ticket. This can contain9708 * various information about the user session.9709 *9710 * @return The envelope and payload9711 */9712 getAttributes() {9713 return { envelope: this.getEnvelope(), payload: this.getPayload() };9714 }9715}9716exports.LoginTicket = LoginTicket;9717//# sourceMappingURL=loginticket.js.map9718/***/ }),9719/***/ 3936:9720/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {9721"use strict";9722// Copyright 2019 Google LLC9723//9724// Licensed under the Apache License, Version 2.0 (the "License");9725// you may not use this file except in compliance with the License.9726// You may obtain a copy of the License at9727//9728// http://www.apache.org/licenses/LICENSE-2.09729//9730// Unless required by applicable law or agreed to in writing, software9731// distributed under the License is distributed on an "AS IS" BASIS,9732// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9733// See the License for the specific language governing permissions and9734// limitations under the License.9735Object.defineProperty(exports, "__esModule", ({ value: true }));9736exports.OAuth2Client = exports.CertificateFormat = exports.CodeChallengeMethod = void 0;9737const gaxios_1 = __nccwpck_require__(9555);9738const querystring = __nccwpck_require__(3477);9739const stream = __nccwpck_require__(2781);9740const formatEcdsa = __nccwpck_require__(1728);9741const crypto_1 = __nccwpck_require__(8043);9742const authclient_1 = __nccwpck_require__(4627);9743const loginticket_1 = __nccwpck_require__(4524);9744var CodeChallengeMethod;9745(function (CodeChallengeMethod) {9746 CodeChallengeMethod["Plain"] = "plain";9747 CodeChallengeMethod["S256"] = "S256";9748})(CodeChallengeMethod = exports.CodeChallengeMethod || (exports.CodeChallengeMethod = {}));9749var CertificateFormat;9750(function (CertificateFormat) {9751 CertificateFormat["PEM"] = "PEM";9752 CertificateFormat["JWK"] = "JWK";9753})(CertificateFormat = exports.CertificateFormat || (exports.CertificateFormat = {}));9754class OAuth2Client extends authclient_1.AuthClient {9755 constructor(optionsOrClientId, clientSecret, redirectUri) {9756 super();9757 this.certificateCache = {};9758 this.certificateExpiry = null;9759 this.certificateCacheFormat = CertificateFormat.PEM;9760 this.refreshTokenPromises = new Map();9761 const opts = optionsOrClientId && typeof optionsOrClientId === 'object'9762 ? optionsOrClientId9763 : { clientId: optionsOrClientId, clientSecret, redirectUri };9764 this._clientId = opts.clientId;9765 this._clientSecret = opts.clientSecret;9766 this.redirectUri = opts.redirectUri;9767 this.eagerRefreshThresholdMillis =9768 opts.eagerRefreshThresholdMillis || 5 * 60 * 1000;9769 this.forceRefreshOnFailure = !!opts.forceRefreshOnFailure;9770 }9771 /**9772 * Generates URL for consent page landing.9773 * @param opts Options.9774 * @return URL to consent page.9775 */9776 generateAuthUrl(opts = {}) {9777 if (opts.code_challenge_method && !opts.code_challenge) {9778 throw new Error('If a code_challenge_method is provided, code_challenge must be included.');9779 }9780 opts.response_type = opts.response_type || 'code';9781 opts.client_id = opts.client_id || this._clientId;9782 opts.redirect_uri = opts.redirect_uri || this.redirectUri;9783 // Allow scopes to be passed either as array or a string9784 if (Array.isArray(opts.scope)) {9785 opts.scope = opts.scope.join(' ');9786 }9787 const rootUrl = OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_;9788 return (rootUrl +9789 '?' +9790 querystring.stringify(opts));9791 }9792 generateCodeVerifier() {9793 // To make the code compatible with browser SubtleCrypto we need to make9794 // this method async.9795 throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.');9796 }9797 /**9798 * Convenience method to automatically generate a code_verifier, and its9799 * resulting SHA256. If used, this must be paired with a S2569800 * code_challenge_method.9801 *9802 * For a full example see:9803 * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js9804 */9805 async generateCodeVerifierAsync() {9806 // base64 encoding uses 6 bits per character, and we want to generate1289807 // characters. 6*128/8 = 96.9808 const crypto = (0, crypto_1.createCrypto)();9809 const randomString = crypto.randomBytesBase64(96);9810 // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/9811 // "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just9812 // swapping out a few chars.9813 const codeVerifier = randomString9814 .replace(/\+/g, '~')9815 .replace(/=/g, '_')9816 .replace(/\//g, '-');9817 // Generate the base64 encoded SHA2569818 const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier);9819 // We need to use base64UrlEncoding instead of standard base649820 const codeChallenge = unencodedCodeChallenge9821 .split('=')[0]9822 .replace(/\+/g, '-')9823 .replace(/\//g, '_');9824 return { codeVerifier, codeChallenge };9825 }9826 getToken(codeOrOptions, callback) {9827 const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions;9828 if (callback) {9829 this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response));9830 }9831 else {9832 return this.getTokenAsync(options);9833 }9834 }9835 async getTokenAsync(options) {9836 const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;9837 const values = {9838 code: options.code,9839 client_id: options.client_id || this._clientId,9840 client_secret: this._clientSecret,9841 redirect_uri: options.redirect_uri || this.redirectUri,9842 grant_type: 'authorization_code',9843 code_verifier: options.codeVerifier,9844 };9845 const res = await this.transporter.request({9846 method: 'POST',9847 url,9848 data: querystring.stringify(values),9849 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },9850 });9851 const tokens = res.data;9852 if (res.data && res.data.expires_in) {9853 tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;9854 delete tokens.expires_in;9855 }9856 this.emit('tokens', tokens);9857 return { tokens, res };9858 }9859 /**9860 * Refreshes the access token.9861 * @param refresh_token Existing refresh token.9862 * @private9863 */9864 async refreshToken(refreshToken) {9865 if (!refreshToken) {9866 return this.refreshTokenNoCache(refreshToken);9867 }9868 // If a request to refresh using the same token has started,9869 // return the same promise.9870 if (this.refreshTokenPromises.has(refreshToken)) {9871 return this.refreshTokenPromises.get(refreshToken);9872 }9873 const p = this.refreshTokenNoCache(refreshToken).then(r => {9874 this.refreshTokenPromises.delete(refreshToken);9875 return r;9876 }, e => {9877 this.refreshTokenPromises.delete(refreshToken);9878 throw e;9879 });9880 this.refreshTokenPromises.set(refreshToken, p);9881 return p;9882 }9883 async refreshTokenNoCache(refreshToken) {9884 var _a;9885 if (!refreshToken) {9886 throw new Error('No refresh token is set.');9887 }9888 const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;9889 const data = {9890 refresh_token: refreshToken,9891 client_id: this._clientId,9892 client_secret: this._clientSecret,9893 grant_type: 'refresh_token',9894 };9895 let res;9896 try {9897 // request for new token9898 res = await this.transporter.request({9899 method: 'POST',9900 url,9901 data: querystring.stringify(data),9902 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },9903 });9904 }9905 catch (e) {9906 if (e instanceof gaxios_1.GaxiosError &&9907 e.message === 'invalid_grant' &&9908 ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) &&9909 /ReAuth/i.test(e.response.data.error_description)) {9910 e.message = JSON.stringify(e.response.data);9911 }9912 throw e;9913 }9914 const tokens = res.data;9915 // TODO: de-duplicate this code from a few spots9916 if (res.data && res.data.expires_in) {9917 tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;9918 delete tokens.expires_in;9919 }9920 this.emit('tokens', tokens);9921 return { tokens, res };9922 }9923 refreshAccessToken(callback) {9924 if (callback) {9925 this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback);9926 }9927 else {9928 return this.refreshAccessTokenAsync();9929 }9930 }9931 async refreshAccessTokenAsync() {9932 const r = await this.refreshToken(this.credentials.refresh_token);9933 const tokens = r.tokens;9934 tokens.refresh_token = this.credentials.refresh_token;9935 this.credentials = tokens;9936 return { credentials: this.credentials, res: r.res };9937 }9938 getAccessToken(callback) {9939 if (callback) {9940 this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback);9941 }9942 else {9943 return this.getAccessTokenAsync();9944 }9945 }9946 async getAccessTokenAsync() {9947 const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();9948 if (shouldRefresh) {9949 if (!this.credentials.refresh_token) {9950 if (this.refreshHandler) {9951 const refreshedAccessToken = await this.processAndValidateRefreshHandler();9952 if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {9953 this.setCredentials(refreshedAccessToken);9954 return { token: this.credentials.access_token };9955 }9956 }9957 else {9958 throw new Error('No refresh token or refresh handler callback is set.');9959 }9960 }9961 const r = await this.refreshAccessTokenAsync();9962 if (!r.credentials || (r.credentials && !r.credentials.access_token)) {9963 throw new Error('Could not refresh access token.');9964 }9965 return { token: r.credentials.access_token, res: r.res };9966 }9967 else {9968 return { token: this.credentials.access_token };9969 }9970 }9971 /**9972 * The main authentication interface. It takes an optional url which when9973 * present is the endpoint being accessed, and returns a Promise which9974 * resolves with authorization header fields.9975 *9976 * In OAuth2Client, the result has the form:9977 * { Authorization: 'Bearer <access_token_value>' }9978 * @param url The optional url being authorized9979 */9980 async getRequestHeaders(url) {9981 const headers = (await this.getRequestMetadataAsync(url)).headers;9982 return headers;9983 }9984 async getRequestMetadataAsync(9985 // eslint-disable-next-line @typescript-eslint/no-unused-vars9986 url) {9987 const thisCreds = this.credentials;9988 if (!thisCreds.access_token &&9989 !thisCreds.refresh_token &&9990 !this.apiKey &&9991 !this.refreshHandler) {9992 throw new Error('No access, refresh token, API key or refresh handler callback is set.');9993 }9994 if (thisCreds.access_token && !this.isTokenExpiring()) {9995 thisCreds.token_type = thisCreds.token_type || 'Bearer';9996 const headers = {9997 Authorization: thisCreds.token_type + ' ' + thisCreds.access_token,9998 };9999 return { headers: this.addSharedMetadataHeaders(headers) };10000 }10001 // If refreshHandler exists, call processAndValidateRefreshHandler().10002 if (this.refreshHandler) {10003 const refreshedAccessToken = await this.processAndValidateRefreshHandler();10004 if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {10005 this.setCredentials(refreshedAccessToken);10006 const headers = {10007 Authorization: 'Bearer ' + this.credentials.access_token,10008 };10009 return { headers: this.addSharedMetadataHeaders(headers) };10010 }10011 }10012 if (this.apiKey) {10013 return { headers: { 'X-Goog-Api-Key': this.apiKey } };10014 }10015 let r = null;10016 let tokens = null;10017 try {10018 r = await this.refreshToken(thisCreds.refresh_token);10019 tokens = r.tokens;10020 }10021 catch (err) {10022 const e = err;10023 if (e.response &&10024 (e.response.status === 403 || e.response.status === 404)) {10025 e.message = `Could not refresh access token: ${e.message}`;10026 }10027 throw e;10028 }10029 const credentials = this.credentials;10030 credentials.token_type = credentials.token_type || 'Bearer';10031 tokens.refresh_token = credentials.refresh_token;10032 this.credentials = tokens;10033 const headers = {10034 Authorization: credentials.token_type + ' ' + tokens.access_token,10035 };10036 return { headers: this.addSharedMetadataHeaders(headers), res: r.res };10037 }10038 /**10039 * Generates an URL to revoke the given token.10040 * @param token The existing token to be revoked.10041 */10042 static getRevokeTokenUrl(token) {10043 const parameters = querystring.stringify({ token });10044 return `${OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_}?${parameters}`;10045 }10046 revokeToken(token, callback) {10047 const opts = {10048 url: OAuth2Client.getRevokeTokenUrl(token),10049 method: 'POST',10050 };10051 if (callback) {10052 this.transporter10053 .request(opts)10054 .then(r => callback(null, r), callback);10055 }10056 else {10057 return this.transporter.request(opts);10058 }10059 }10060 revokeCredentials(callback) {10061 if (callback) {10062 this.revokeCredentialsAsync().then(res => callback(null, res), callback);10063 }10064 else {10065 return this.revokeCredentialsAsync();10066 }10067 }10068 async revokeCredentialsAsync() {10069 const token = this.credentials.access_token;10070 this.credentials = {};10071 if (token) {10072 return this.revokeToken(token);10073 }10074 else {10075 throw new Error('No access token to revoke.');10076 }10077 }10078 request(opts, callback) {10079 if (callback) {10080 this.requestAsync(opts).then(r => callback(null, r), e => {10081 return callback(e, e.response);10082 });10083 }10084 else {10085 return this.requestAsync(opts);10086 }10087 }10088 async requestAsync(opts, retry = false) {10089 let r2;10090 try {10091 const r = await this.getRequestMetadataAsync(opts.url);10092 opts.headers = opts.headers || {};10093 if (r.headers && r.headers['x-goog-user-project']) {10094 opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project'];10095 }10096 if (r.headers && r.headers.Authorization) {10097 opts.headers.Authorization = r.headers.Authorization;10098 }10099 if (this.apiKey) {10100 opts.headers['X-Goog-Api-Key'] = this.apiKey;10101 }10102 r2 = await this.transporter.request(opts);10103 }10104 catch (e) {10105 const res = e.response;10106 if (res) {10107 const statusCode = res.status;10108 // Retry the request for metadata if the following criteria are true:10109 // - We haven't already retried. It only makes sense to retry once.10110 // - The response was a 401 or a 40310111 // - The request didn't send a readableStream10112 // - An access_token and refresh_token were available, but either no10113 // expiry_date was available or the forceRefreshOnFailure flag is set.10114 // The absent expiry_date case can happen when developers stash the10115 // access_token and refresh_token for later use, but the access_token10116 // fails on the first try because it's expired. Some developers may10117 // choose to enable forceRefreshOnFailure to mitigate time-related10118 // errors.10119 // Or the following criteria are true:10120 // - We haven't already retried. It only makes sense to retry once.10121 // - The response was a 401 or a 40310122 // - The request didn't send a readableStream10123 // - No refresh_token was available10124 // - An access_token and a refreshHandler callback were available, but10125 // either no expiry_date was available or the forceRefreshOnFailure10126 // flag is set. The access_token fails on the first try because it's10127 // expired. Some developers may choose to enable forceRefreshOnFailure10128 // to mitigate time-related errors.10129 const mayRequireRefresh = this.credentials &&10130 this.credentials.access_token &&10131 this.credentials.refresh_token &&10132 (!this.credentials.expiry_date || this.forceRefreshOnFailure);10133 const mayRequireRefreshWithNoRefreshToken = this.credentials &&10134 this.credentials.access_token &&10135 !this.credentials.refresh_token &&10136 (!this.credentials.expiry_date || this.forceRefreshOnFailure) &&10137 this.refreshHandler;10138 const isReadableStream = res.config.data instanceof stream.Readable;10139 const isAuthErr = statusCode === 401 || statusCode === 403;10140 if (!retry && isAuthErr && !isReadableStream && mayRequireRefresh) {10141 await this.refreshAccessTokenAsync();10142 return this.requestAsync(opts, true);10143 }10144 else if (!retry &&10145 isAuthErr &&10146 !isReadableStream &&10147 mayRequireRefreshWithNoRefreshToken) {10148 const refreshedAccessToken = await this.processAndValidateRefreshHandler();10149 if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) {10150 this.setCredentials(refreshedAccessToken);10151 }10152 return this.requestAsync(opts, true);10153 }10154 }10155 throw e;10156 }10157 return r2;10158 }10159 verifyIdToken(options, callback) {10160 // This function used to accept two arguments instead of an options object.10161 // Check the types to help users upgrade with less pain.10162 // This check can be removed after a 2.0 release.10163 if (callback && typeof callback !== 'function') {10164 throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.');10165 }10166 if (callback) {10167 this.verifyIdTokenAsync(options).then(r => callback(null, r), callback);10168 }10169 else {10170 return this.verifyIdTokenAsync(options);10171 }10172 }10173 async verifyIdTokenAsync(options) {10174 if (!options.idToken) {10175 throw new Error('The verifyIdToken method requires an ID Token');10176 }10177 const response = await this.getFederatedSignonCertsAsync();10178 const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, OAuth2Client.ISSUERS_, options.maxExpiry);10179 return login;10180 }10181 /**10182 * Obtains information about the provisioned access token. Especially useful10183 * if you want to check the scopes that were provisioned to a given token.10184 *10185 * @param accessToken Required. The Access Token for which you want to get10186 * user info.10187 */10188 async getTokenInfo(accessToken) {10189 const { data } = await this.transporter.request({10190 method: 'POST',10191 headers: {10192 'Content-Type': 'application/x-www-form-urlencoded',10193 Authorization: `Bearer ${accessToken}`,10194 },10195 url: OAuth2Client.GOOGLE_TOKEN_INFO_URL,10196 });10197 const info = Object.assign({10198 expiry_date: new Date().getTime() + data.expires_in * 1000,10199 scopes: data.scope.split(' '),10200 }, data);10201 delete info.expires_in;10202 delete info.scope;10203 return info;10204 }10205 getFederatedSignonCerts(callback) {10206 if (callback) {10207 this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback);10208 }10209 else {10210 return this.getFederatedSignonCertsAsync();10211 }10212 }10213 async getFederatedSignonCertsAsync() {10214 const nowTime = new Date().getTime();10215 const format = (0, crypto_1.hasBrowserCrypto)()10216 ? CertificateFormat.JWK10217 : CertificateFormat.PEM;10218 if (this.certificateExpiry &&10219 nowTime < this.certificateExpiry.getTime() &&10220 this.certificateCacheFormat === format) {10221 return { certs: this.certificateCache, format };10222 }10223 let res;10224 let url;10225 switch (format) {10226 case CertificateFormat.PEM:10227 url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_;10228 break;10229 case CertificateFormat.JWK:10230 url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_;10231 break;10232 default:10233 throw new Error(`Unsupported certificate format ${format}`);10234 }10235 try {10236 res = await this.transporter.request({ url });10237 }10238 catch (e) {10239 if (e instanceof Error) {10240 e.message = `Failed to retrieve verification certificates: ${e.message}`;10241 }10242 throw e;10243 }10244 const cacheControl = res ? res.headers['cache-control'] : undefined;10245 let cacheAge = -1;10246 if (cacheControl) {10247 const pattern = new RegExp('max-age=([0-9]*)');10248 const regexResult = pattern.exec(cacheControl);10249 if (regexResult && regexResult.length === 2) {10250 // Cache results with max-age (in seconds)10251 cacheAge = Number(regexResult[1]) * 1000; // milliseconds10252 }10253 }10254 let certificates = {};10255 switch (format) {10256 case CertificateFormat.PEM:10257 certificates = res.data;10258 break;10259 case CertificateFormat.JWK:10260 for (const key of res.data.keys) {10261 certificates[key.kid] = key;10262 }10263 break;10264 default:10265 throw new Error(`Unsupported certificate format ${format}`);10266 }10267 const now = new Date();10268 this.certificateExpiry =10269 cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);10270 this.certificateCache = certificates;10271 this.certificateCacheFormat = format;10272 return { certs: certificates, format, res };10273 }10274 getIapPublicKeys(callback) {10275 if (callback) {10276 this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback);10277 }10278 else {10279 return this.getIapPublicKeysAsync();10280 }10281 }10282 async getIapPublicKeysAsync() {10283 let res;10284 const url = OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_;10285 try {10286 res = await this.transporter.request({ url });10287 }10288 catch (e) {10289 if (e instanceof Error) {10290 e.message = `Failed to retrieve verification certificates: ${e.message}`;10291 }10292 throw e;10293 }10294 return { pubkeys: res.data, res };10295 }10296 verifySignedJwtWithCerts() {10297 // To make the code compatible with browser SubtleCrypto we need to make10298 // this method async.10299 throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.');10300 }10301 /**10302 * Verify the id token is signed with the correct certificate10303 * and is from the correct audience.10304 * @param jwt The jwt to verify (The ID Token in this case).10305 * @param certs The array of certs to test the jwt against.10306 * @param requiredAudience The audience to test the jwt against.10307 * @param issuers The allowed issuers of the jwt (Optional).10308 * @param maxExpiry The max expiry the certificate can be (Optional).10309 * @return Returns a promise resolving to LoginTicket on verification.10310 */10311 async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) {10312 const crypto = (0, crypto_1.createCrypto)();10313 if (!maxExpiry) {10314 maxExpiry = OAuth2Client.MAX_TOKEN_LIFETIME_SECS_;10315 }10316 const segments = jwt.split('.');10317 if (segments.length !== 3) {10318 throw new Error('Wrong number of segments in token: ' + jwt);10319 }10320 const signed = segments[0] + '.' + segments[1];10321 let signature = segments[2];10322 let envelope;10323 let payload;10324 try {10325 envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0]));10326 }10327 catch (err) {10328 if (err instanceof Error) {10329 err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`;10330 }10331 throw err;10332 }10333 if (!envelope) {10334 throw new Error("Can't parse token envelope: " + segments[0]);10335 }10336 try {10337 payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1]));10338 }10339 catch (err) {10340 if (err instanceof Error) {10341 err.message = `Can't parse token payload '${segments[0]}`;10342 }10343 throw err;10344 }10345 if (!payload) {10346 throw new Error("Can't parse token payload: " + segments[1]);10347 }10348 if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {10349 // If this is not present, then there's no reason to attempt verification10350 throw new Error('No pem found for envelope: ' + JSON.stringify(envelope));10351 }10352 const cert = certs[envelope.kid];10353 if (envelope.alg === 'ES256') {10354 signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64');10355 }10356 const verified = await crypto.verify(cert, signed, signature);10357 if (!verified) {10358 throw new Error('Invalid token signature: ' + jwt);10359 }10360 if (!payload.iat) {10361 throw new Error('No issue time in token: ' + JSON.stringify(payload));10362 }10363 if (!payload.exp) {10364 throw new Error('No expiration time in token: ' + JSON.stringify(payload));10365 }10366 const iat = Number(payload.iat);10367 if (isNaN(iat))10368 throw new Error('iat field using invalid format');10369 const exp = Number(payload.exp);10370 if (isNaN(exp))10371 throw new Error('exp field using invalid format');10372 const now = new Date().getTime() / 1000;10373 if (exp >= now + maxExpiry) {10374 throw new Error('Expiration time too far in future: ' + JSON.stringify(payload));10375 }10376 const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_;10377 const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_;10378 if (now < earliest) {10379 throw new Error('Token used too early, ' +10380 now +10381 ' < ' +10382 earliest +10383 ': ' +10384 JSON.stringify(payload));10385 }10386 if (now > latest) {10387 throw new Error('Token used too late, ' +10388 now +10389 ' > ' +10390 latest +10391 ': ' +10392 JSON.stringify(payload));10393 }10394 if (issuers && issuers.indexOf(payload.iss) < 0) {10395 throw new Error('Invalid issuer, expected one of [' +10396 issuers +10397 '], but got ' +10398 payload.iss);10399 }10400 // Check the audience matches if we have one10401 if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) {10402 const aud = payload.aud;10403 let audVerified = false;10404 // If the requiredAudience is an array, check if it contains token10405 // audience10406 if (requiredAudience.constructor === Array) {10407 audVerified = requiredAudience.indexOf(aud) > -1;10408 }10409 else {10410 audVerified = aud === requiredAudience;10411 }10412 if (!audVerified) {10413 throw new Error('Wrong recipient, payload audience != requiredAudience');10414 }10415 }10416 return new loginticket_1.LoginTicket(envelope, payload);10417 }10418 /**10419 * Returns a promise that resolves with AccessTokenResponse type if10420 * refreshHandler is defined.10421 * If not, nothing is returned.10422 */10423 async processAndValidateRefreshHandler() {10424 if (this.refreshHandler) {10425 const accessTokenResponse = await this.refreshHandler();10426 if (!accessTokenResponse.access_token) {10427 throw new Error('No access token is returned by the refreshHandler callback.');10428 }10429 return accessTokenResponse;10430 }10431 return;10432 }10433 /**10434 * Returns true if a token is expired or will expire within10435 * eagerRefreshThresholdMillismilliseconds.10436 * If there is no expiry time, assumes the token is not expired or expiring.10437 */10438 isTokenExpiring() {10439 const expiryDate = this.credentials.expiry_date;10440 return expiryDate10441 ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis10442 : false;10443 }10444}10445exports.OAuth2Client = OAuth2Client;10446OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo';10447/**10448 * The base URL for auth endpoints.10449 */10450OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_ = 'https://accounts.google.com/o/oauth2/v2/auth';10451/**10452 * The base endpoint for token retrieval.10453 */10454OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_ = 'https://oauth2.googleapis.com/token';10455/**10456 * The base endpoint to revoke tokens.10457 */10458OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_ = 'https://oauth2.googleapis.com/revoke';10459/**10460 * Google Sign on certificates in PEM format.10461 */10462OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v1/certs';10463/**10464 * Google Sign on certificates in JWK format.10465 */10466OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v3/certs';10467/**10468 * Google Sign on certificates in JWK format.10469 */10470OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_ = 'https://www.gstatic.com/iap/verify/public_key';10471/**10472 * Clock skew - five minutes in seconds10473 */10474OAuth2Client.CLOCK_SKEW_SECS_ = 300;10475/**10476 * Max Token Lifetime is one day in seconds10477 */10478OAuth2Client.MAX_TOKEN_LIFETIME_SECS_ = 86400;10479/**10480 * The allowed oauth token issuers.10481 */10482OAuth2Client.ISSUERS_ = [10483 'accounts.google.com',10484 'https://accounts.google.com',10485];10486//# sourceMappingURL=oauth2client.js.map10487/***/ }),10488/***/ 9510:10489/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {10490"use strict";10491// Copyright 2021 Google LLC10492//10493// Licensed under the Apache License, Version 2.0 (the "License");10494// you may not use this file except in compliance with the License.10495// You may obtain a copy of the License at10496//10497// http://www.apache.org/licenses/LICENSE-2.010498//10499// Unless required by applicable law or agreed to in writing, software10500// distributed under the License is distributed on an "AS IS" BASIS,10501// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10502// See the License for the specific language governing permissions and10503// limitations under the License.10504Object.defineProperty(exports, "__esModule", ({ value: true }));10505exports.getErrorFromOAuthErrorResponse = exports.OAuthClientAuthHandler = void 0;10506const querystring = __nccwpck_require__(3477);10507const crypto_1 = __nccwpck_require__(8043);10508/** List of HTTP methods that accept request bodies. */10509const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH'];10510/**10511 * Abstract class for handling client authentication in OAuth-based10512 * operations.10513 * When request-body client authentication is used, only application/json and10514 * application/x-www-form-urlencoded content types for HTTP methods that support10515 * request bodies are supported.10516 */10517class OAuthClientAuthHandler {10518 /**10519 * Instantiates an OAuth client authentication handler.10520 * @param clientAuthentication The client auth credentials.10521 */10522 constructor(clientAuthentication) {10523 this.clientAuthentication = clientAuthentication;10524 this.crypto = (0, crypto_1.createCrypto)();10525 }10526 /**10527 * Applies client authentication on the OAuth request's headers or POST10528 * body but does not process the request.10529 * @param opts The GaxiosOptions whose headers or data are to be modified10530 * depending on the client authentication mechanism to be used.10531 * @param bearerToken The optional bearer token to use for authentication.10532 * When this is used, no client authentication credentials are needed.10533 */10534 applyClientAuthenticationOptions(opts, bearerToken) {10535 // Inject authenticated header.10536 this.injectAuthenticatedHeaders(opts, bearerToken);10537 // Inject authenticated request body.10538 if (!bearerToken) {10539 this.injectAuthenticatedRequestBody(opts);10540 }10541 }10542 /**10543 * Applies client authentication on the request's header if either10544 * basic authentication or bearer token authentication is selected.10545 *10546 * @param opts The GaxiosOptions whose headers or data are to be modified10547 * depending on the client authentication mechanism to be used.10548 * @param bearerToken The optional bearer token to use for authentication.10549 * When this is used, no client authentication credentials are needed.10550 */10551 injectAuthenticatedHeaders(opts, bearerToken) {10552 var _a;10553 // Bearer token prioritized higher than basic Auth.10554 if (bearerToken) {10555 opts.headers = opts.headers || {};10556 Object.assign(opts.headers, {10557 Authorization: `Bearer ${bearerToken}}`,10558 });10559 }10560 else if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'basic') {10561 opts.headers = opts.headers || {};10562 const clientId = this.clientAuthentication.clientId;10563 const clientSecret = this.clientAuthentication.clientSecret || '';10564 const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);10565 Object.assign(opts.headers, {10566 Authorization: `Basic ${base64EncodedCreds}`,10567 });10568 }10569 }10570 /**10571 * Applies client authentication on the request's body if request-body10572 * client authentication is selected.10573 *10574 * @param opts The GaxiosOptions whose headers or data are to be modified10575 * depending on the client authentication mechanism to be used.10576 */10577 injectAuthenticatedRequestBody(opts) {10578 var _a;10579 if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'request-body') {10580 const method = (opts.method || 'GET').toUpperCase();10581 // Inject authenticated request body.10582 if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) {10583 // Get content-type.10584 let contentType;10585 const headers = opts.headers || {};10586 for (const key in headers) {10587 if (key.toLowerCase() === 'content-type' && headers[key]) {10588 contentType = headers[key].toLowerCase();10589 break;10590 }10591 }10592 if (contentType === 'application/x-www-form-urlencoded') {10593 opts.data = opts.data || '';10594 const data = querystring.parse(opts.data);10595 Object.assign(data, {10596 client_id: this.clientAuthentication.clientId,10597 client_secret: this.clientAuthentication.clientSecret || '',10598 });10599 opts.data = querystring.stringify(data);10600 }10601 else if (contentType === 'application/json') {10602 opts.data = opts.data || {};10603 Object.assign(opts.data, {10604 client_id: this.clientAuthentication.clientId,10605 client_secret: this.clientAuthentication.clientSecret || '',10606 });10607 }10608 else {10609 throw new Error(`${contentType} content-types are not supported with ` +10610 `${this.clientAuthentication.confidentialClientType} ` +10611 'client authentication');10612 }10613 }10614 else {10615 throw new Error(`${method} HTTP method does not support ` +10616 `${this.clientAuthentication.confidentialClientType} ` +10617 'client authentication');10618 }10619 }10620 }10621}10622exports.OAuthClientAuthHandler = OAuthClientAuthHandler;10623/**10624 * Converts an OAuth error response to a native JavaScript Error.10625 * @param resp The OAuth error response to convert to a native Error object.10626 * @param err The optional original error. If provided, the error properties10627 * will be copied to the new error.10628 * @return The converted native Error object.10629 */10630function getErrorFromOAuthErrorResponse(resp, err) {10631 // Error response.10632 const errorCode = resp.error;10633 const errorDescription = resp.error_description;10634 const errorUri = resp.error_uri;10635 let message = `Error code ${errorCode}`;10636 if (typeof errorDescription !== 'undefined') {10637 message += `: ${errorDescription}`;10638 }10639 if (typeof errorUri !== 'undefined') {10640 message += ` - ${errorUri}`;10641 }10642 const newError = new Error(message);10643 // Copy properties from original error to newly generated error.10644 if (err) {10645 const keys = Object.keys(err);10646 if (err.stack) {10647 // Copy error.stack if available.10648 keys.push('stack');10649 }10650 keys.forEach(key => {10651 // Do not overwrite the message field.10652 if (key !== 'message') {10653 Object.defineProperty(newError, key, {10654 // eslint-disable-next-line @typescript-eslint/no-explicit-any10655 value: err[key],10656 writable: false,10657 enumerable: true,10658 });10659 }10660 });10661 }10662 return newError;10663}10664exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse;10665//# sourceMappingURL=oauth2common.js.map10666/***/ }),10667/***/ 4782:10668/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {10669"use strict";10670// Copyright 2022 Google LLC10671//10672// Licensed under the Apache License, Version 2.0 (the "License");10673// you may not use this file except in compliance with the License.10674// You may obtain a copy of the License at10675//10676// http://www.apache.org/licenses/LICENSE-2.010677//10678// Unless required by applicable law or agreed to in writing, software10679// distributed under the License is distributed on an "AS IS" BASIS,10680// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10681// See the License for the specific language governing permissions and10682// limitations under the License.10683Object.defineProperty(exports, "__esModule", ({ value: true }));10684exports.PluggableAuthClient = exports.ExecutableError = void 0;10685const baseexternalclient_1 = __nccwpck_require__(7391);10686const executable_response_1 = __nccwpck_require__(8749);10687const pluggable_auth_handler_1 = __nccwpck_require__(8941);10688/**10689 * Error thrown from the executable run by PluggableAuthClient.10690 */10691class ExecutableError extends Error {10692 constructor(message, code) {10693 super(`The executable failed with exit code: ${code} and error message: ${message}.`);10694 this.code = code;10695 Object.setPrototypeOf(this, new.target.prototype);10696 }10697}10698exports.ExecutableError = ExecutableError;10699/**10700 * The default executable timeout when none is provided, in milliseconds.10701 */10702const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000;10703/**10704 * The minimum allowed executable timeout in milliseconds.10705 */10706const MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000;10707/**10708 * The maximum allowed executable timeout in milliseconds.10709 */10710const MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000;10711/**10712 * The environment variable to check to see if executable can be run.10713 * Value must be set to '1' for the executable to run.10714 */10715const GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES';10716/**10717 * The maximum currently supported executable version.10718 */10719const MAXIMUM_EXECUTABLE_VERSION = 1;10720/**10721 * PluggableAuthClient enables the exchange of workload identity pool external credentials for10722 * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These10723 * scripts/executables are completely independent of the Google Cloud Auth libraries. These10724 * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token10725 * to be exchanged for a Google access token.10726 *10727 * <p>To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable10728 * must be set to '1'. This is for security reasons.10729 *10730 * <p>Both OIDC and SAML are supported. The executable must adhere to a specific response format10731 * defined below.10732 *10733 * <p>The executable must print out the 3rd party token to STDOUT in JSON format. When an10734 * output_file is specified in the credential configuration, the executable must also handle writing the10735 * JSON response to this file.10736 *10737 * <pre>10738 * OIDC response sample:10739 * {10740 * "version": 1,10741 * "success": true,10742 * "token_type": "urn:ietf:params:oauth:token-type:id_token",10743 * "id_token": "HEADER.PAYLOAD.SIGNATURE",10744 * "expiration_time": 162043334110745 * }10746 *10747 * SAML2 response sample:10748 * {10749 * "version": 1,10750 * "success": true,10751 * "token_type": "urn:ietf:params:oauth:token-type:saml2",10752 * "saml_response": "...",10753 * "expiration_time": 162043334110754 * }10755 *10756 * Error response sample:10757 * {10758 * "version": 1,10759 * "success": false,10760 * "code": "401",10761 * "message": "Error message."10762 * }10763 * </pre>10764 *10765 * <p>The "expiration_time" field in the JSON response is only required for successful10766 * responses when an output file was specified in the credential configuration10767 *10768 * <p>The auth libraries will populate certain environment variables that will be accessible by the10769 * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE,10770 * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and10771 * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.10772 *10773 * <p>Please see this repositories README for a complete executable request/response specification.10774 */10775class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient {10776 /**10777 * Instantiates a PluggableAuthClient instance using the provided JSON10778 * object loaded from an external account credentials file.10779 * An error is thrown if the credential is not a valid pluggable auth credential.10780 * @param options The external account options object typically loaded from10781 * the external account JSON credential file.10782 * @param additionalOptions Optional additional behavior customization10783 * options. These currently customize expiration threshold time and10784 * whether to retry on 401/403 API request errors.10785 */10786 constructor(options, additionalOptions) {10787 super(options, additionalOptions);10788 if (!options.credential_source.executable) {10789 throw new Error('No valid Pluggable Auth "credential_source" provided.');10790 }10791 this.command = options.credential_source.executable.command;10792 if (!this.command) {10793 throw new Error('No valid Pluggable Auth "credential_source" provided.');10794 }10795 // Check if the provided timeout exists and if it is valid.10796 if (options.credential_source.executable.timeout_millis === undefined) {10797 this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;10798 }10799 else {10800 this.timeoutMillis = options.credential_source.executable.timeout_millis;10801 if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS ||10802 this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) {10803 throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` +10804 `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`);10805 }10806 }10807 this.outputFile = options.credential_source.executable.output_file;10808 this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({10809 command: this.command,10810 timeoutMillis: this.timeoutMillis,10811 outputFile: this.outputFile,10812 });10813 }10814 /**10815 * Triggered when an external subject token is needed to be exchanged for a10816 * GCP access token via GCP STS endpoint.10817 * This uses the `options.credential_source` object to figure out how10818 * to retrieve the token using the current environment. In this case,10819 * this calls a user provided executable which returns the subject token.10820 * The logic is summarized as:10821 * 1. Validated that the executable is allowed to run. The10822 * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to10823 * 1 for security reasons.10824 * 2. If an output file is specified by the user, check the file location10825 * for a response. If the file exists and contains a valid response,10826 * return the subject token from the file.10827 * 3. Call the provided executable and return response.10828 * @return A promise that resolves with the external subject token.10829 */10830 async retrieveSubjectToken() {10831 // Check if the executable is allowed to run.10832 if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') {10833 throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' +10834 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' +10835 'Variable to 1.');10836 }10837 let executableResponse = undefined;10838 // Try to get cached executable response from output file.10839 if (this.outputFile) {10840 executableResponse = await this.handler.retrieveCachedResponse();10841 }10842 // If no response from output file, call the executable.10843 if (!executableResponse) {10844 // Set up environment map with required values for the executable.10845 const envMap = new Map();10846 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience);10847 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType);10848 // Always set to 0 because interactive mode is not supported.10849 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0');10850 if (this.outputFile) {10851 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile);10852 }10853 const serviceAccountEmail = this.getServiceAccountEmail();10854 if (serviceAccountEmail) {10855 envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail);10856 }10857 executableResponse = await this.handler.retrieveResponseFromExecutable(envMap);10858 }10859 if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) {10860 throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`);10861 }10862 // Check that response was successful.10863 if (!executableResponse.success) {10864 throw new ExecutableError(executableResponse.errorMessage, executableResponse.errorCode);10865 }10866 // Check that response contains expiration time if output file was specified.10867 if (this.outputFile) {10868 if (!executableResponse.expirationTime) {10869 throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.');10870 }10871 }10872 // Check that response is not expired.10873 if (executableResponse.isExpired()) {10874 throw new Error('Executable response is expired.');10875 }10876 // Return subject token from response.10877 return executableResponse.subjectToken;10878 }10879}10880exports.PluggableAuthClient = PluggableAuthClient;10881//# sourceMappingURL=pluggable-auth-client.js.map10882/***/ }),10883/***/ 8941:10884/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {10885"use strict";10886// Copyright 2022 Google LLC10887//10888// Licensed under the Apache License, Version 2.0 (the "License");10889// you may not use this file except in compliance with the License.10890// You may obtain a copy of the License at10891//10892// http://www.apache.org/licenses/LICENSE-2.010893//10894// Unless required by applicable law or agreed to in writing, software10895// distributed under the License is distributed on an "AS IS" BASIS,10896// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10897// See the License for the specific language governing permissions and10898// limitations under the License.10899Object.defineProperty(exports, "__esModule", ({ value: true }));10900exports.PluggableAuthHandler = void 0;10901const pluggable_auth_client_1 = __nccwpck_require__(4782);10902const executable_response_1 = __nccwpck_require__(8749);10903const childProcess = __nccwpck_require__(2081);10904const fs = __nccwpck_require__(7147);10905/**10906 * A handler used to retrieve 3rd party token responses from user defined10907 * executables and cached file output for the PluggableAuthClient class.10908 */10909class PluggableAuthHandler {10910 /**10911 * Instantiates a PluggableAuthHandler instance using the provided10912 * PluggableAuthHandlerOptions object.10913 */10914 constructor(options) {10915 if (!options.command) {10916 throw new Error('No command provided.');10917 }10918 this.commandComponents = PluggableAuthHandler.parseCommand(options.command);10919 this.timeoutMillis = options.timeoutMillis;10920 if (!this.timeoutMillis) {10921 throw new Error('No timeoutMillis provided.');10922 }10923 this.outputFile = options.outputFile;10924 }10925 /**10926 * Calls user provided executable to get a 3rd party subject token and10927 * returns the response.10928 * @param envMap a Map of additional Environment Variables required for10929 * the executable.10930 * @return A promise that resolves with the executable response.10931 */10932 retrieveResponseFromExecutable(envMap) {10933 return new Promise((resolve, reject) => {10934 // Spawn process to run executable using added environment variables.10935 const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), {10936 env: { ...process.env, ...Object.fromEntries(envMap) },10937 });10938 let output = '';10939 // Append stdout to output as executable runs.10940 child.stdout.on('data', (data) => {10941 output += data;10942 });10943 // Append stderr as executable runs.10944 child.stderr.on('data', (err) => {10945 output += err;10946 });10947 // Set up a timeout to end the child process and throw an error.10948 const timeout = setTimeout(() => {10949 // Kill child process and remove listeners so 'close' event doesn't get10950 // read after child process is killed.10951 child.removeAllListeners();10952 child.kill();10953 return reject(new Error('The executable failed to finish within the timeout specified.'));10954 }, this.timeoutMillis);10955 child.on('close', (code) => {10956 // Cancel timeout if executable closes before timeout is reached.10957 clearTimeout(timeout);10958 if (code === 0) {10959 // If the executable completed successfully, try to return the parsed response.10960 try {10961 const responseJson = JSON.parse(output);10962 const response = new executable_response_1.ExecutableResponse(responseJson);10963 return resolve(response);10964 }10965 catch (error) {10966 if (error instanceof executable_response_1.ExecutableResponseError) {10967 return reject(error);10968 }10969 return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));10970 }10971 }10972 else {10973 return reject(new pluggable_auth_client_1.ExecutableError(output, code.toString()));10974 }10975 });10976 });10977 }10978 /**10979 * Checks user provided output file for response from previous run of10980 * executable and return the response if it exists, is formatted correctly, and is not expired.10981 */10982 async retrieveCachedResponse() {10983 if (!this.outputFile || this.outputFile.length === 0) {10984 return undefined;10985 }10986 let filePath;10987 try {10988 filePath = await fs.promises.realpath(this.outputFile);10989 }10990 catch (_a) {10991 // If file path cannot be resolved, return undefined.10992 return undefined;10993 }10994 if (!(await fs.promises.lstat(filePath)).isFile()) {10995 // If path does not lead to file, return undefined.10996 return undefined;10997 }10998 const responseString = await fs.promises.readFile(filePath, {10999 encoding: 'utf8',11000 });11001 if (responseString === '') {11002 return undefined;11003 }11004 try {11005 const responseJson = JSON.parse(responseString);11006 const response = new executable_response_1.ExecutableResponse(responseJson);11007 // Check if response is successful and unexpired.11008 if (response.isValid()) {11009 return new executable_response_1.ExecutableResponse(responseJson);11010 }11011 return undefined;11012 }11013 catch (error) {11014 if (error instanceof executable_response_1.ExecutableResponseError) {11015 throw error;11016 }11017 throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`);11018 }11019 }11020 /**11021 * Parses given command string into component array, splitting on spaces unless11022 * spaces are between quotation marks.11023 */11024 static parseCommand(command) {11025 // Split the command into components by splitting on spaces,11026 // unless spaces are contained in quotation marks.11027 const components = command.match(/(?:[^\s"]+|"[^"]*")+/g);11028 if (!components) {11029 throw new Error(`Provided command: "${command}" could not be parsed.`);11030 }11031 // Remove quotation marks from the beginning and end of each component if they are present.11032 for (let i = 0; i < components.length; i++) {11033 if (components[i][0] === '"' && components[i].slice(-1) === '"') {11034 components[i] = components[i].slice(1, -1);11035 }11036 }11037 return components;11038 }11039}11040exports.PluggableAuthHandler = PluggableAuthHandler;11041//# sourceMappingURL=pluggable-auth-handler.js.map11042/***/ }),11043/***/ 8790:11044/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11045"use strict";11046// Copyright 2015 Google LLC11047//11048// Licensed under the Apache License, Version 2.0 (the "License");11049// you may not use this file except in compliance with the License.11050// You may obtain a copy of the License at11051//11052// http://www.apache.org/licenses/LICENSE-2.011053//11054// Unless required by applicable law or agreed to in writing, software11055// distributed under the License is distributed on an "AS IS" BASIS,11056// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11057// See the License for the specific language governing permissions and11058// limitations under the License.11059Object.defineProperty(exports, "__esModule", ({ value: true }));11060exports.UserRefreshClient = void 0;11061const oauth2client_1 = __nccwpck_require__(3936);11062class UserRefreshClient extends oauth2client_1.OAuth2Client {11063 constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) {11064 const opts = optionsOrClientId && typeof optionsOrClientId === 'object'11065 ? optionsOrClientId11066 : {11067 clientId: optionsOrClientId,11068 clientSecret,11069 refreshToken,11070 eagerRefreshThresholdMillis,11071 forceRefreshOnFailure,11072 };11073 super({11074 clientId: opts.clientId,11075 clientSecret: opts.clientSecret,11076 eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis,11077 forceRefreshOnFailure: opts.forceRefreshOnFailure,11078 });11079 this._refreshToken = opts.refreshToken;11080 this.credentials.refresh_token = opts.refreshToken;11081 }11082 /**11083 * Refreshes the access token.11084 * @param refreshToken An ignored refreshToken..11085 * @param callback Optional callback.11086 */11087 async refreshTokenNoCache(11088 // eslint-disable-next-line @typescript-eslint/no-unused-vars11089 refreshToken) {11090 return super.refreshTokenNoCache(this._refreshToken);11091 }11092 /**11093 * Create a UserRefreshClient credentials instance using the given input11094 * options.11095 * @param json The input object.11096 */11097 fromJSON(json) {11098 if (!json) {11099 throw new Error('Must pass in a JSON object containing the user refresh token');11100 }11101 if (json.type !== 'authorized_user') {11102 throw new Error('The incoming JSON object does not have the "authorized_user" type');11103 }11104 if (!json.client_id) {11105 throw new Error('The incoming JSON object does not contain a client_id field');11106 }11107 if (!json.client_secret) {11108 throw new Error('The incoming JSON object does not contain a client_secret field');11109 }11110 if (!json.refresh_token) {11111 throw new Error('The incoming JSON object does not contain a refresh_token field');11112 }11113 this._clientId = json.client_id;11114 this._clientSecret = json.client_secret;11115 this._refreshToken = json.refresh_token;11116 this.credentials.refresh_token = json.refresh_token;11117 this.quotaProjectId = json.quota_project_id;11118 }11119 fromStream(inputStream, callback) {11120 if (callback) {11121 this.fromStreamAsync(inputStream).then(() => callback(), callback);11122 }11123 else {11124 return this.fromStreamAsync(inputStream);11125 }11126 }11127 async fromStreamAsync(inputStream) {11128 return new Promise((resolve, reject) => {11129 if (!inputStream) {11130 return reject(new Error('Must pass in a stream containing the user refresh token.'));11131 }11132 let s = '';11133 inputStream11134 .setEncoding('utf8')11135 .on('error', reject)11136 .on('data', chunk => (s += chunk))11137 .on('end', () => {11138 try {11139 const data = JSON.parse(s);11140 this.fromJSON(data);11141 return resolve();11142 }11143 catch (err) {11144 return reject(err);11145 }11146 });11147 });11148 }11149}11150exports.UserRefreshClient = UserRefreshClient;11151//# sourceMappingURL=refreshclient.js.map11152/***/ }),11153/***/ 6308:11154/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11155"use strict";11156// Copyright 2021 Google LLC11157//11158// Licensed under the Apache License, Version 2.0 (the "License");11159// you may not use this file except in compliance with the License.11160// You may obtain a copy of the License at11161//11162// http://www.apache.org/licenses/LICENSE-2.011163//11164// Unless required by applicable law or agreed to in writing, software11165// distributed under the License is distributed on an "AS IS" BASIS,11166// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11167// See the License for the specific language governing permissions and11168// limitations under the License.11169Object.defineProperty(exports, "__esModule", ({ value: true }));11170exports.StsCredentials = void 0;11171const gaxios_1 = __nccwpck_require__(9555);11172const querystring = __nccwpck_require__(3477);11173const transporters_1 = __nccwpck_require__(2649);11174const oauth2common_1 = __nccwpck_require__(9510);11175/**11176 * Implements the OAuth 2.0 token exchange based on11177 * https://tools.ietf.org/html/rfc869311178 */11179class StsCredentials extends oauth2common_1.OAuthClientAuthHandler {11180 /**11181 * Initializes an STS credentials instance.11182 * @param tokenExchangeEndpoint The token exchange endpoint.11183 * @param clientAuthentication The client authentication credentials if11184 * available.11185 */11186 constructor(tokenExchangeEndpoint, clientAuthentication) {11187 super(clientAuthentication);11188 this.tokenExchangeEndpoint = tokenExchangeEndpoint;11189 this.transporter = new transporters_1.DefaultTransporter();11190 }11191 /**11192 * Exchanges the provided token for another type of token based on the11193 * rfc8693 spec.11194 * @param stsCredentialsOptions The token exchange options used to populate11195 * the token exchange request.11196 * @param additionalHeaders Optional additional headers to pass along the11197 * request.11198 * @param options Optional additional GCP-specific non-spec defined options11199 * to send with the request.11200 * Example: `&options=${encodeUriComponent(JSON.stringified(options))}`11201 * @return A promise that resolves with the token exchange response containing11202 * the requested token and its expiration time.11203 */11204 async exchangeToken(stsCredentialsOptions, additionalHeaders, 11205 // eslint-disable-next-line @typescript-eslint/no-explicit-any11206 options) {11207 var _a, _b, _c;11208 const values = {11209 grant_type: stsCredentialsOptions.grantType,11210 resource: stsCredentialsOptions.resource,11211 audience: stsCredentialsOptions.audience,11212 scope: (_a = stsCredentialsOptions.scope) === null || _a === void 0 ? void 0 : _a.join(' '),11213 requested_token_type: stsCredentialsOptions.requestedTokenType,11214 subject_token: stsCredentialsOptions.subjectToken,11215 subject_token_type: stsCredentialsOptions.subjectTokenType,11216 actor_token: (_b = stsCredentialsOptions.actingParty) === null || _b === void 0 ? void 0 : _b.actorToken,11217 actor_token_type: (_c = stsCredentialsOptions.actingParty) === null || _c === void 0 ? void 0 : _c.actorTokenType,11218 // Non-standard GCP-specific options.11219 options: options && JSON.stringify(options),11220 };11221 // Remove undefined fields.11222 Object.keys(values).forEach(key => {11223 // eslint-disable-next-line @typescript-eslint/no-explicit-any11224 if (typeof values[key] === 'undefined') {11225 // eslint-disable-next-line @typescript-eslint/no-explicit-any11226 delete values[key];11227 }11228 });11229 const headers = {11230 'Content-Type': 'application/x-www-form-urlencoded',11231 };11232 // Inject additional STS headers if available.11233 Object.assign(headers, additionalHeaders || {});11234 const opts = {11235 url: this.tokenExchangeEndpoint,11236 method: 'POST',11237 headers,11238 data: querystring.stringify(values),11239 responseType: 'json',11240 };11241 // Apply OAuth client authentication.11242 this.applyClientAuthenticationOptions(opts);11243 try {11244 const response = await this.transporter.request(opts);11245 // Successful response.11246 const stsSuccessfulResponse = response.data;11247 stsSuccessfulResponse.res = response;11248 return stsSuccessfulResponse;11249 }11250 catch (error) {11251 // Translate error to OAuthError.11252 if (error instanceof gaxios_1.GaxiosError && error.response) {11253 throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, 11254 // Preserve other fields from the original error.11255 error);11256 }11257 // Request could fail before the server responds.11258 throw error;11259 }11260 }11261}11262exports.StsCredentials = StsCredentials;11263//# sourceMappingURL=stscredentials.js.map11264/***/ }),11265/***/ 4693:11266/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11267"use strict";11268// Copyright 2019 Google LLC11269//11270// Licensed under the Apache License, Version 2.0 (the "License");11271// you may not use this file except in compliance with the License.11272// You may obtain a copy of the License at11273//11274// http://www.apache.org/licenses/LICENSE-2.011275//11276// Unless required by applicable law or agreed to in writing, software11277// distributed under the License is distributed on an "AS IS" BASIS,11278// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11279// See the License for the specific language governing permissions and11280// limitations under the License.11281/* global window */11282Object.defineProperty(exports, "__esModule", ({ value: true }));11283exports.BrowserCrypto = void 0;11284// This file implements crypto functions we need using in-browser11285// SubtleCrypto interface `window.crypto.subtle`.11286const base64js = __nccwpck_require__(6463);11287// Not all browsers support `TextEncoder`. The following `require` will11288// provide a fast UTF8-only replacement for those browsers that don't support11289// text encoding natively.11290// eslint-disable-next-line node/no-unsupported-features/node-builtins11291if (typeof process === 'undefined' && typeof TextEncoder === 'undefined') {11292 __nccwpck_require__(1917);11293}11294const crypto_1 = __nccwpck_require__(8043);11295class BrowserCrypto {11296 constructor() {11297 if (typeof window === 'undefined' ||11298 window.crypto === undefined ||11299 window.crypto.subtle === undefined) {11300 throw new Error("SubtleCrypto not found. Make sure it's an https:// website.");11301 }11302 }11303 async sha256DigestBase64(str) {11304 // SubtleCrypto digest() method is async, so we must make11305 // this method async as well.11306 // To calculate SHA256 digest using SubtleCrypto, we first11307 // need to convert an input string to an ArrayBuffer:11308 // eslint-disable-next-line node/no-unsupported-features/node-builtins11309 const inputBuffer = new TextEncoder().encode(str);11310 // Result is ArrayBuffer as well.11311 const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);11312 return base64js.fromByteArray(new Uint8Array(outputBuffer));11313 }11314 randomBytesBase64(count) {11315 const array = new Uint8Array(count);11316 window.crypto.getRandomValues(array);11317 return base64js.fromByteArray(array);11318 }11319 static padBase64(base64) {11320 // base64js requires padding, so let's add some '='11321 while (base64.length % 4 !== 0) {11322 base64 += '=';11323 }11324 return base64;11325 }11326 async verify(pubkey, data, signature) {11327 const algo = {11328 name: 'RSASSA-PKCS1-v1_5',11329 hash: { name: 'SHA-256' },11330 };11331 // eslint-disable-next-line node/no-unsupported-features/node-builtins11332 const dataArray = new TextEncoder().encode(data);11333 const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));11334 const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);11335 // SubtleCrypto's verify method is async so we must make11336 // this method async as well.11337 const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);11338 return result;11339 }11340 async sign(privateKey, data) {11341 const algo = {11342 name: 'RSASSA-PKCS1-v1_5',11343 hash: { name: 'SHA-256' },11344 };11345 // eslint-disable-next-line node/no-unsupported-features/node-builtins11346 const dataArray = new TextEncoder().encode(data);11347 const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);11348 // SubtleCrypto's sign method is async so we must make11349 // this method async as well.11350 const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);11351 return base64js.fromByteArray(new Uint8Array(result));11352 }11353 decodeBase64StringUtf8(base64) {11354 const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));11355 // eslint-disable-next-line node/no-unsupported-features/node-builtins11356 const result = new TextDecoder().decode(uint8array);11357 return result;11358 }11359 encodeBase64StringUtf8(text) {11360 // eslint-disable-next-line node/no-unsupported-features/node-builtins11361 const uint8array = new TextEncoder().encode(text);11362 const result = base64js.fromByteArray(uint8array);11363 return result;11364 }11365 /**11366 * Computes the SHA-256 hash of the provided string.11367 * @param str The plain text string to hash.11368 * @return A promise that resolves with the SHA-256 hash of the provided11369 * string in hexadecimal encoding.11370 */11371 async sha256DigestHex(str) {11372 // SubtleCrypto digest() method is async, so we must make11373 // this method async as well.11374 // To calculate SHA256 digest using SubtleCrypto, we first11375 // need to convert an input string to an ArrayBuffer:11376 // eslint-disable-next-line node/no-unsupported-features/node-builtins11377 const inputBuffer = new TextEncoder().encode(str);11378 // Result is ArrayBuffer as well.11379 const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);11380 return (0, crypto_1.fromArrayBufferToHex)(outputBuffer);11381 }11382 /**11383 * Computes the HMAC hash of a message using the provided crypto key and the11384 * SHA-256 algorithm.11385 * @param key The secret crypto key in utf-8 or ArrayBuffer format.11386 * @param msg The plain text message.11387 * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer11388 * format.11389 */11390 async signWithHmacSha256(key, msg) {11391 // Convert key, if provided in ArrayBuffer format, to string.11392 const rawKey = typeof key === 'string'11393 ? key11394 : String.fromCharCode(...new Uint16Array(key));11395 // eslint-disable-next-line node/no-unsupported-features/node-builtins11396 const enc = new TextEncoder();11397 const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), {11398 name: 'HMAC',11399 hash: {11400 name: 'SHA-256',11401 },11402 }, false, ['sign']);11403 return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg));11404 }11405}11406exports.BrowserCrypto = BrowserCrypto;11407//# sourceMappingURL=crypto.js.map11408/***/ }),11409/***/ 8043:11410/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11411"use strict";11412// Copyright 2019 Google LLC11413//11414// Licensed under the Apache License, Version 2.0 (the "License");11415// you may not use this file except in compliance with the License.11416// You may obtain a copy of the License at11417//11418// http://www.apache.org/licenses/LICENSE-2.011419//11420// Unless required by applicable law or agreed to in writing, software11421// distributed under the License is distributed on an "AS IS" BASIS,11422// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11423// See the License for the specific language governing permissions and11424// limitations under the License.11425/* global window */11426Object.defineProperty(exports, "__esModule", ({ value: true }));11427exports.fromArrayBufferToHex = exports.hasBrowserCrypto = exports.createCrypto = void 0;11428const crypto_1 = __nccwpck_require__(4693);11429const crypto_2 = __nccwpck_require__(757);11430function createCrypto() {11431 if (hasBrowserCrypto()) {11432 return new crypto_1.BrowserCrypto();11433 }11434 return new crypto_2.NodeCrypto();11435}11436exports.createCrypto = createCrypto;11437function hasBrowserCrypto() {11438 return (typeof window !== 'undefined' &&11439 typeof window.crypto !== 'undefined' &&11440 typeof window.crypto.subtle !== 'undefined');11441}11442exports.hasBrowserCrypto = hasBrowserCrypto;11443/**11444 * Converts an ArrayBuffer to a hexadecimal string.11445 * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string.11446 * @return The hexadecimal encoding of the ArrayBuffer.11447 */11448function fromArrayBufferToHex(arrayBuffer) {11449 // Convert buffer to byte array.11450 const byteArray = Array.from(new Uint8Array(arrayBuffer));11451 // Convert bytes to hex string.11452 return byteArray11453 .map(byte => {11454 return byte.toString(16).padStart(2, '0');11455 })11456 .join('');11457}11458exports.fromArrayBufferToHex = fromArrayBufferToHex;11459//# sourceMappingURL=crypto.js.map11460/***/ }),11461/***/ 757:11462/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11463"use strict";11464// Copyright 2019 Google LLC11465//11466// Licensed under the Apache License, Version 2.0 (the "License");11467// you may not use this file except in compliance with the License.11468// You may obtain a copy of the License at11469//11470// http://www.apache.org/licenses/LICENSE-2.011471//11472// Unless required by applicable law or agreed to in writing, software11473// distributed under the License is distributed on an "AS IS" BASIS,11474// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11475// See the License for the specific language governing permissions and11476// limitations under the License.11477Object.defineProperty(exports, "__esModule", ({ value: true }));11478exports.NodeCrypto = void 0;11479const crypto = __nccwpck_require__(6113);11480class NodeCrypto {11481 async sha256DigestBase64(str) {11482 return crypto.createHash('sha256').update(str).digest('base64');11483 }11484 randomBytesBase64(count) {11485 return crypto.randomBytes(count).toString('base64');11486 }11487 async verify(pubkey, data, signature) {11488 const verifier = crypto.createVerify('sha256');11489 verifier.update(data);11490 verifier.end();11491 return verifier.verify(pubkey, signature, 'base64');11492 }11493 async sign(privateKey, data) {11494 const signer = crypto.createSign('RSA-SHA256');11495 signer.update(data);11496 signer.end();11497 return signer.sign(privateKey, 'base64');11498 }11499 decodeBase64StringUtf8(base64) {11500 return Buffer.from(base64, 'base64').toString('utf-8');11501 }11502 encodeBase64StringUtf8(text) {11503 return Buffer.from(text, 'utf-8').toString('base64');11504 }11505 /**11506 * Computes the SHA-256 hash of the provided string.11507 * @param str The plain text string to hash.11508 * @return A promise that resolves with the SHA-256 hash of the provided11509 * string in hexadecimal encoding.11510 */11511 async sha256DigestHex(str) {11512 return crypto.createHash('sha256').update(str).digest('hex');11513 }11514 /**11515 * Computes the HMAC hash of a message using the provided crypto key and the11516 * SHA-256 algorithm.11517 * @param key The secret crypto key in utf-8 or ArrayBuffer format.11518 * @param msg The plain text message.11519 * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer11520 * format.11521 */11522 async signWithHmacSha256(key, msg) {11523 const cryptoKey = typeof key === 'string' ? key : toBuffer(key);11524 return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest());11525 }11526}11527exports.NodeCrypto = NodeCrypto;11528/**11529 * Converts a Node.js Buffer to an ArrayBuffer.11530 * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer11531 * @param buffer The Buffer input to covert.11532 * @return The ArrayBuffer representation of the input.11533 */11534function toArrayBuffer(buffer) {11535 return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);11536}11537/**11538 * Converts an ArrayBuffer to a Node.js Buffer.11539 * @param arrayBuffer The ArrayBuffer input to covert.11540 * @return The Buffer representation of the input.11541 */11542function toBuffer(arrayBuffer) {11543 return Buffer.from(arrayBuffer);11544}11545//# sourceMappingURL=crypto.js.map11546/***/ }),11547/***/ 810:11548/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11549"use strict";11550Object.defineProperty(exports, "__esModule", ({ value: true }));11551exports.GoogleAuth = exports.auth = exports.DefaultTransporter = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.AuthClient = void 0;11552// Copyright 2017 Google LLC11553//11554// Licensed under the Apache License, Version 2.0 (the "License");11555// you may not use this file except in compliance with the License.11556// You may obtain a copy of the License at11557//11558// http://www.apache.org/licenses/LICENSE-2.011559//11560// Unless required by applicable law or agreed to in writing, software11561// distributed under the License is distributed on an "AS IS" BASIS,11562// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11563// See the License for the specific language governing permissions and11564// limitations under the License.11565const googleauth_1 = __nccwpck_require__(695);11566Object.defineProperty(exports, "GoogleAuth", ({ enumerable: true, get: function () { return googleauth_1.GoogleAuth; } }));11567var authclient_1 = __nccwpck_require__(4627);11568Object.defineProperty(exports, "AuthClient", ({ enumerable: true, get: function () { return authclient_1.AuthClient; } }));11569var computeclient_1 = __nccwpck_require__(6875);11570Object.defineProperty(exports, "Compute", ({ enumerable: true, get: function () { return computeclient_1.Compute; } }));11571var envDetect_1 = __nccwpck_require__(1380);11572Object.defineProperty(exports, "GCPEnv", ({ enumerable: true, get: function () { return envDetect_1.GCPEnv; } }));11573var iam_1 = __nccwpck_require__(9735);11574Object.defineProperty(exports, "IAMAuth", ({ enumerable: true, get: function () { return iam_1.IAMAuth; } }));11575var idtokenclient_1 = __nccwpck_require__(298);11576Object.defineProperty(exports, "IdTokenClient", ({ enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } }));11577var jwtaccess_1 = __nccwpck_require__(8740);11578Object.defineProperty(exports, "JWTAccess", ({ enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } }));11579var jwtclient_1 = __nccwpck_require__(3959);11580Object.defineProperty(exports, "JWT", ({ enumerable: true, get: function () { return jwtclient_1.JWT; } }));11581var impersonated_1 = __nccwpck_require__(1103);11582Object.defineProperty(exports, "Impersonated", ({ enumerable: true, get: function () { return impersonated_1.Impersonated; } }));11583var oauth2client_1 = __nccwpck_require__(3936);11584Object.defineProperty(exports, "CodeChallengeMethod", ({ enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } }));11585Object.defineProperty(exports, "OAuth2Client", ({ enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } }));11586var loginticket_1 = __nccwpck_require__(4524);11587Object.defineProperty(exports, "LoginTicket", ({ enumerable: true, get: function () { return loginticket_1.LoginTicket; } }));11588var refreshclient_1 = __nccwpck_require__(8790);11589Object.defineProperty(exports, "UserRefreshClient", ({ enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } }));11590var awsclient_1 = __nccwpck_require__(1569);11591Object.defineProperty(exports, "AwsClient", ({ enumerable: true, get: function () { return awsclient_1.AwsClient; } }));11592var identitypoolclient_1 = __nccwpck_require__(117);11593Object.defineProperty(exports, "IdentityPoolClient", ({ enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } }));11594var externalclient_1 = __nccwpck_require__(4381);11595Object.defineProperty(exports, "ExternalAccountClient", ({ enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } }));11596var baseexternalclient_1 = __nccwpck_require__(7391);11597Object.defineProperty(exports, "BaseExternalAccountClient", ({ enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } }));11598var downscopedclient_1 = __nccwpck_require__(6270);11599Object.defineProperty(exports, "DownscopedClient", ({ enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } }));11600var pluggable_auth_client_1 = __nccwpck_require__(4782);11601Object.defineProperty(exports, "PluggableAuthClient", ({ enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } }));11602var transporters_1 = __nccwpck_require__(2649);11603Object.defineProperty(exports, "DefaultTransporter", ({ enumerable: true, get: function () { return transporters_1.DefaultTransporter; } }));11604const auth = new googleauth_1.GoogleAuth();11605exports.auth = auth;11606//# sourceMappingURL=index.js.map11607/***/ }),11608/***/ 6608:11609/***/ ((__unused_webpack_module, exports) => {11610"use strict";11611// Copyright 2017 Google LLC11612//11613// Licensed under the Apache License, Version 2.0 (the "License");11614// you may not use this file except in compliance with the License.11615// You may obtain a copy of the License at11616//11617// http://www.apache.org/licenses/LICENSE-2.011618//11619// Unless required by applicable law or agreed to in writing, software11620// distributed under the License is distributed on an "AS IS" BASIS,11621// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11622// See the License for the specific language governing permissions and11623// limitations under the License.11624Object.defineProperty(exports, "__esModule", ({ value: true }));11625exports.validate = void 0;11626// Accepts an options object passed from the user to the API. In the11627// previous version of the API, it referred to a `Request` options object.11628// Now it refers to an Axiox Request Config object. This is here to help11629// ensure users don't pass invalid options when they upgrade from 0.x to 1.x.11630// eslint-disable-next-line @typescript-eslint/no-explicit-any11631function validate(options) {11632 const vpairs = [11633 { invalid: 'uri', expected: 'url' },11634 { invalid: 'json', expected: 'data' },11635 { invalid: 'qs', expected: 'params' },11636 ];11637 for (const pair of vpairs) {11638 if (options[pair.invalid]) {11639 const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`;11640 throw new Error(e);11641 }11642 }11643}11644exports.validate = validate;11645//# sourceMappingURL=options.js.map11646/***/ }),11647/***/ 2649:11648/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11649"use strict";11650// Copyright 2019 Google LLC11651//11652// Licensed under the Apache License, Version 2.0 (the "License");11653// you may not use this file except in compliance with the License.11654// You may obtain a copy of the License at11655//11656// http://www.apache.org/licenses/LICENSE-2.011657//11658// Unless required by applicable law or agreed to in writing, software11659// distributed under the License is distributed on an "AS IS" BASIS,11660// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11661// See the License for the specific language governing permissions and11662// limitations under the License.11663Object.defineProperty(exports, "__esModule", ({ value: true }));11664exports.DefaultTransporter = void 0;11665const gaxios_1 = __nccwpck_require__(9555);11666const options_1 = __nccwpck_require__(6608);11667// eslint-disable-next-line @typescript-eslint/no-var-requires11668const pkg = __nccwpck_require__(1402);11669const PRODUCT_NAME = 'google-api-nodejs-client';11670class DefaultTransporter {11671 /**11672 * Configures request options before making a request.11673 * @param opts GaxiosOptions options.11674 * @return Configured options.11675 */11676 configure(opts = {}) {11677 opts.headers = opts.headers || {};11678 if (typeof window === 'undefined') {11679 // set transporter user agent if not in browser11680 const uaValue = opts.headers['User-Agent'];11681 if (!uaValue) {11682 opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT;11683 }11684 else if (!uaValue.includes(`${PRODUCT_NAME}/`)) {11685 opts.headers['User-Agent'] = `${uaValue} ${DefaultTransporter.USER_AGENT}`;11686 }11687 // track google-auth-library-nodejs version:11688 const authVersion = `auth/${pkg.version}`;11689 if (opts.headers['x-goog-api-client'] &&11690 !opts.headers['x-goog-api-client'].includes(authVersion)) {11691 opts.headers['x-goog-api-client'] = `${opts.headers['x-goog-api-client']} ${authVersion}`;11692 }11693 else if (!opts.headers['x-goog-api-client']) {11694 const nodeVersion = process.version.replace(/^v/, '');11695 opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion} ${authVersion}`;11696 }11697 }11698 return opts;11699 }11700 request(opts, callback) {11701 // ensure the user isn't passing in request-style options11702 opts = this.configure(opts);11703 try {11704 (0, options_1.validate)(opts);11705 }11706 catch (e) {11707 if (callback) {11708 return callback(e);11709 }11710 else {11711 throw e;11712 }11713 }11714 if (callback) {11715 (0, gaxios_1.request)(opts).then(r => {11716 callback(null, r);11717 }, e => {11718 callback(this.processError(e));11719 });11720 }11721 else {11722 return (0, gaxios_1.request)(opts).catch(e => {11723 throw this.processError(e);11724 });11725 }11726 }11727 /**11728 * Changes the error to include details from the body.11729 */11730 processError(e) {11731 const res = e.response;11732 const err = e;11733 const body = res ? res.data : null;11734 if (res && body && body.error && res.status !== 200) {11735 if (typeof body.error === 'string') {11736 err.message = body.error;11737 err.code = res.status.toString();11738 }11739 else if (Array.isArray(body.error.errors)) {11740 err.message = body.error.errors11741 .map((err2) => err2.message)11742 .join('\n');11743 err.code = body.error.code;11744 err.errors = body.error.errors;11745 }11746 else {11747 err.message = body.error.message;11748 err.code = body.error.code || res.status;11749 }11750 }11751 else if (res && res.status >= 400) {11752 // Consider all 4xx and 5xx responses errors.11753 err.message = body;11754 err.code = res.status.toString();11755 }11756 return err;11757 }11758}11759exports.DefaultTransporter = DefaultTransporter;11760/**11761 * Default user agent.11762 */11763DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`;11764//# sourceMappingURL=transporters.js.map11765/***/ }),11766/***/ 2098:11767/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11768"use strict";11769/**11770 * Copyright 2018 Google LLC11771 *11772 * Distributed under MIT license.11773 * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT11774 */11775Object.defineProperty(exports, "__esModule", ({ value: true }));11776exports.getPem = void 0;11777const fs = __nccwpck_require__(7147);11778const forge = __nccwpck_require__(7655);11779const util_1 = __nccwpck_require__(3837);11780const readFile = (0, util_1.promisify)(fs.readFile);11781function getPem(filename, callback) {11782 if (callback) {11783 getPemAsync(filename)11784 .then(pem => callback(null, pem))11785 .catch(err => callback(err, null));11786 }11787 else {11788 return getPemAsync(filename);11789 }11790}11791exports.getPem = getPem;11792function getPemAsync(filename) {11793 return readFile(filename, { encoding: 'base64' }).then(keyp12 => {11794 return convertToPem(keyp12);11795 });11796}11797/**11798 * Converts a P12 in base64 encoding to a pem.11799 * @param p12base64 String containing base64 encoded p12.11800 * @returns a string containing the pem.11801 */11802function convertToPem(p12base64) {11803 const p12Der = forge.util.decode64(p12base64);11804 const p12Asn1 = forge.asn1.fromDer(p12Der);11805 const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'notasecret');11806 const bags = p12.getBags({ friendlyName: 'privatekey' });11807 if (bags.friendlyName) {11808 const privateKey = bags.friendlyName[0].key;11809 const pem = forge.pki.privateKeyToPem(privateKey);11810 return pem.replace(/\r\n/g, '\n');11811 }11812 else {11813 throw new Error('Unable to get friendly name.');11814 }11815}11816//# sourceMappingURL=index.js.map11817/***/ }),11818/***/ 6031:11819/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {11820"use strict";11821/**11822 * Copyright 2018 Google LLC11823 *11824 * Distributed under MIT license.11825 * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT11826 */11827Object.defineProperty(exports, "__esModule", ({ value: true }));11828exports.GoogleToken = void 0;11829const fs = __nccwpck_require__(7147);11830const gaxios_1 = __nccwpck_require__(9555);11831const jws = __nccwpck_require__(4636);11832const path = __nccwpck_require__(1017);11833const util_1 = __nccwpck_require__(3837);11834const readFile = fs.readFile11835 ? (0, util_1.promisify)(fs.readFile)11836 : async () => {11837 // if running in the web-browser, fs.readFile may not have been shimmed.11838 throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS');11839 };11840const GOOGLE_TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token';11841const GOOGLE_REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke?token=';11842class ErrorWithCode extends Error {11843 constructor(message, code) {11844 super(message);11845 this.code = code;11846 }11847}11848let getPem;11849class GoogleToken {11850 /**11851 * Create a GoogleToken.11852 *11853 * @param options Configuration object.11854 */11855 constructor(options) {11856 this.transporter = {11857 request: opts => (0, gaxios_1.request)(opts),11858 };11859 this.configure(options);11860 }11861 get accessToken() {11862 return this.rawToken ? this.rawToken.access_token : undefined;11863 }11864 get idToken() {11865 return this.rawToken ? this.rawToken.id_token : undefined;11866 }11867 get tokenType() {11868 return this.rawToken ? this.rawToken.token_type : undefined;11869 }11870 get refreshToken() {11871 return this.rawToken ? this.rawToken.refresh_token : undefined;11872 }11873 /**11874 * Returns whether the token has expired.11875 *11876 * @return true if the token has expired, false otherwise.11877 */11878 hasExpired() {11879 const now = new Date().getTime();11880 if (this.rawToken && this.expiresAt) {11881 return now >= this.expiresAt;11882 }11883 else {11884 return true;11885 }11886 }11887 /**11888 * Returns whether the token will expire within eagerRefreshThresholdMillis11889 *11890 * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise.11891 */11892 isTokenExpiring() {11893 var _a;11894 const now = new Date().getTime();11895 const eagerRefreshThresholdMillis = (_a = this.eagerRefreshThresholdMillis) !== null && _a !== void 0 ? _a : 0;11896 if (this.rawToken && this.expiresAt) {11897 return this.expiresAt <= now + eagerRefreshThresholdMillis;11898 }11899 else {11900 return true;11901 }11902 }11903 getToken(callback, opts = {}) {11904 if (typeof callback === 'object') {11905 opts = callback;11906 callback = undefined;11907 }11908 opts = Object.assign({11909 forceRefresh: false,11910 }, opts);11911 if (callback) {11912 const cb = callback;11913 this.getTokenAsync(opts).then(t => cb(null, t), callback);11914 return;11915 }11916 return this.getTokenAsync(opts);11917 }11918 /**11919 * Given a keyFile, extract the key and client email if available11920 * @param keyFile Path to a json, pem, or p12 file that contains the key.11921 * @returns an object with privateKey and clientEmail properties11922 */11923 async getCredentials(keyFile) {11924 const ext = path.extname(keyFile);11925 switch (ext) {11926 case '.json': {11927 const key = await readFile(keyFile, 'utf8');11928 const body = JSON.parse(key);11929 const privateKey = body.private_key;11930 const clientEmail = body.client_email;11931 if (!privateKey || !clientEmail) {11932 throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS');11933 }11934 return { privateKey, clientEmail };11935 }11936 case '.der':11937 case '.crt':11938 case '.pem': {11939 const privateKey = await readFile(keyFile, 'utf8');11940 return { privateKey };11941 }11942 case '.p12':11943 case '.pfx': {11944 // NOTE: The loading of `google-p12-pem` is deferred for performance11945 // reasons. The `node-forge` npm module in `google-p12-pem` adds a fair11946 // bit time to overall module loading, and is likely not frequently11947 // used. In a future release, p12 support will be entirely removed.11948 if (!getPem) {11949 getPem = (await Promise.resolve().then(() => __nccwpck_require__(2098))).getPem;11950 }11951 const privateKey = await getPem(keyFile);11952 return { privateKey };11953 }11954 default:11955 throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' +11956 'Current supported extensions are *.json, *.pem, and *.p12.', 'UNKNOWN_CERTIFICATE_TYPE');11957 }11958 }11959 async getTokenAsync(opts) {11960 if (this.inFlightRequest && !opts.forceRefresh) {11961 return this.inFlightRequest;11962 }11963 try {11964 return await (this.inFlightRequest = this.getTokenAsyncInner(opts));11965 }11966 finally {11967 this.inFlightRequest = undefined;11968 }11969 }11970 async getTokenAsyncInner(opts) {11971 if (this.isTokenExpiring() === false && opts.forceRefresh === false) {11972 return Promise.resolve(this.rawToken);11973 }11974 if (!this.key && !this.keyFile) {11975 throw new Error('No key or keyFile set.');11976 }11977 if (!this.key && this.keyFile) {11978 const creds = await this.getCredentials(this.keyFile);11979 this.key = creds.privateKey;11980 this.iss = creds.clientEmail || this.iss;11981 if (!creds.clientEmail) {11982 this.ensureEmail();11983 }11984 }11985 return this.requestToken();11986 }11987 ensureEmail() {11988 if (!this.iss) {11989 throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS');11990 }11991 }11992 revokeToken(callback) {11993 if (callback) {11994 this.revokeTokenAsync().then(() => callback(), callback);11995 return;11996 }11997 return this.revokeTokenAsync();11998 }11999 async revokeTokenAsync() {12000 if (!this.accessToken) {12001 throw new Error('No token to revoke.');12002 }12003 const url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;12004 await this.transporter.request({ url });12005 this.configure({12006 email: this.iss,12007 sub: this.sub,12008 key: this.key,12009 keyFile: this.keyFile,12010 scope: this.scope,12011 additionalClaims: this.additionalClaims,12012 });12013 }12014 /**12015 * Configure the GoogleToken for re-use.12016 * @param {object} options Configuration object.12017 */12018 configure(options = {}) {12019 this.keyFile = options.keyFile;12020 this.key = options.key;12021 this.rawToken = undefined;12022 this.iss = options.email || options.iss;12023 this.sub = options.sub;12024 this.additionalClaims = options.additionalClaims;12025 if (typeof options.scope === 'object') {12026 this.scope = options.scope.join(' ');12027 }12028 else {12029 this.scope = options.scope;12030 }12031 this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis;12032 if (options.transporter) {12033 this.transporter = options.transporter;12034 }12035 }12036 /**12037 * Request the token from Google.12038 */12039 async requestToken() {12040 var _a, _b;12041 const iat = Math.floor(new Date().getTime() / 1000);12042 const additionalClaims = this.additionalClaims || {};12043 const payload = Object.assign({12044 iss: this.iss,12045 scope: this.scope,12046 aud: GOOGLE_TOKEN_URL,12047 exp: iat + 3600,12048 iat,12049 sub: this.sub,12050 }, additionalClaims);12051 const signedJWT = jws.sign({12052 header: { alg: 'RS256' },12053 payload,12054 secret: this.key,12055 });12056 try {12057 const r = await this.transporter.request({12058 method: 'POST',12059 url: GOOGLE_TOKEN_URL,12060 data: {12061 grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',12062 assertion: signedJWT,12063 },12064 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },12065 responseType: 'json',12066 });12067 this.rawToken = r.data;12068 this.expiresAt =12069 r.data.expires_in === null || r.data.expires_in === undefined12070 ? undefined12071 : (iat + r.data.expires_in) * 1000;12072 return this.rawToken;12073 }12074 catch (e) {12075 this.rawToken = undefined;12076 this.tokenExpires = undefined;12077 const body = e.response && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data)12078 ? (_b = e.response) === null || _b === void 0 ? void 0 : _b.data12079 : {};12080 if (body.error) {12081 const desc = body.error_description12082 ? `: ${body.error_description}`12083 : '';12084 e.message = `${body.error}${desc}`;12085 }12086 throw e;12087 }12088 }12089}12090exports.GoogleToken = GoogleToken;12091//# sourceMappingURL=index.js.map12092/***/ }),12093/***/ 5098:12094/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {12095"use strict";12096var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {12097 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }12098 return new (P || (P = Promise))(function (resolve, reject) {12099 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }12100 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }12101 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }12102 step((generator = generator.apply(thisArg, _arguments || [])).next());12103 });12104};12105var __importDefault = (this && this.__importDefault) || function (mod) {12106 return (mod && mod.__esModule) ? mod : { "default": mod };12107};12108Object.defineProperty(exports, "__esModule", ({ value: true }));12109const net_1 = __importDefault(__nccwpck_require__(1808));12110const tls_1 = __importDefault(__nccwpck_require__(4404));12111const url_1 = __importDefault(__nccwpck_require__(7310));12112const assert_1 = __importDefault(__nccwpck_require__(9491));12113const debug_1 = __importDefault(__nccwpck_require__(8237));12114const agent_base_1 = __nccwpck_require__(9690);12115const parse_proxy_response_1 = __importDefault(__nccwpck_require__(595));12116const debug = debug_1.default('https-proxy-agent:agent');12117/**12118 * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to12119 * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.12120 *12121 * Outgoing HTTP requests are first tunneled through the proxy server using the12122 * `CONNECT` HTTP request method to establish a connection to the proxy server,12123 * and then the proxy server connects to the destination target and issues the12124 * HTTP request from the proxy server.12125 *12126 * `https:` requests have their socket connection upgraded to TLS once12127 * the connection to the proxy server has been established.12128 *12129 * @api public12130 */12131class HttpsProxyAgent extends agent_base_1.Agent {12132 constructor(_opts) {12133 let opts;12134 if (typeof _opts === 'string') {12135 opts = url_1.default.parse(_opts);12136 }12137 else {12138 opts = _opts;12139 }12140 if (!opts) {12141 throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');12142 }12143 debug('creating new HttpsProxyAgent instance: %o', opts);12144 super(opts);12145 const proxy = Object.assign({}, opts);12146 // If `true`, then connect to the proxy server over TLS.12147 // Defaults to `false`.12148 this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol);12149 // Prefer `hostname` over `host`, and set the `port` if needed.12150 proxy.host = proxy.hostname || proxy.host;12151 if (typeof proxy.port === 'string') {12152 proxy.port = parseInt(proxy.port, 10);12153 }12154 if (!proxy.port && proxy.host) {12155 proxy.port = this.secureProxy ? 443 : 80;12156 }12157 // ALPN is supported by Node.js >= v5.12158 // attempt to negotiate http/1.1 for proxy servers that support http/212159 if (this.secureProxy && !('ALPNProtocols' in proxy)) {12160 proxy.ALPNProtocols = ['http 1.1'];12161 }12162 if (proxy.host && proxy.path) {12163 // If both a `host` and `path` are specified then it's most likely12164 // the result of a `url.parse()` call... we need to remove the12165 // `path` portion so that `net.connect()` doesn't attempt to open12166 // that as a Unix socket file.12167 delete proxy.path;12168 delete proxy.pathname;12169 }12170 this.proxy = proxy;12171 }12172 /**12173 * Called when the node-core HTTP client library is creating a12174 * new HTTP request.12175 *12176 * @api protected12177 */12178 callback(req, opts) {12179 return __awaiter(this, void 0, void 0, function* () {12180 const { proxy, secureProxy } = this;12181 // Create a socket connection to the proxy server.12182 let socket;12183 if (secureProxy) {12184 debug('Creating `tls.Socket`: %o', proxy);12185 socket = tls_1.default.connect(proxy);12186 }12187 else {12188 debug('Creating `net.Socket`: %o', proxy);12189 socket = net_1.default.connect(proxy);12190 }12191 const headers = Object.assign({}, proxy.headers);12192 const hostname = `${opts.host}:${opts.port}`;12193 let payload = `CONNECT ${hostname} HTTP/1.1\r\n`;12194 // Inject the `Proxy-Authorization` header if necessary.12195 if (proxy.auth) {12196 headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;12197 }12198 // The `Host` header should only include the port12199 // number when it is not the default port.12200 let { host, port, secureEndpoint } = opts;12201 if (!isDefaultPort(port, secureEndpoint)) {12202 host += `:${port}`;12203 }12204 headers.Host = host;12205 headers.Connection = 'close';12206 for (const name of Object.keys(headers)) {12207 payload += `${name}: ${headers[name]}\r\n`;12208 }12209 const proxyResponsePromise = parse_proxy_response_1.default(socket);12210 socket.write(`${payload}\r\n`);12211 const { statusCode, buffered } = yield proxyResponsePromise;12212 if (statusCode === 200) {12213 req.once('socket', resume);12214 if (opts.secureEndpoint) {12215 // The proxy is connecting to a TLS server, so upgrade12216 // this socket connection to a TLS connection.12217 debug('Upgrading socket connection to TLS');12218 const servername = opts.servername || opts.host;12219 return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,12220 servername }));12221 }12222 return socket;12223 }12224 // Some other status code that's not 200... need to re-play the HTTP12225 // header "data" events onto the socket once the HTTP machinery is12226 // attached so that the node core `http` can parse and handle the12227 // error status code.12228 // Close the original socket, and a new "fake" socket is returned12229 // instead, so that the proxy doesn't get the HTTP request12230 // written to it (which may contain `Authorization` headers or other12231 // sensitive data).12232 //12233 // See: https://hackerone.com/reports/54150212234 socket.destroy();12235 const fakeSocket = new net_1.default.Socket({ writable: false });12236 fakeSocket.readable = true;12237 // Need to wait for the "socket" event to re-play the "data" events.12238 req.once('socket', (s) => {12239 debug('replaying proxy buffer for failed request');12240 assert_1.default(s.listenerCount('data') > 0);12241 // Replay the "buffered" Buffer onto the fake `socket`, since at12242 // this point the HTTP module machinery has been hooked up for12243 // the user.12244 s.push(buffered);12245 s.push(null);12246 });12247 return fakeSocket;12248 });12249 }12250}12251exports["default"] = HttpsProxyAgent;12252function resume(socket) {12253 socket.resume();12254}12255function isDefaultPort(port, secure) {12256 return Boolean((!secure && port === 80) || (secure && port === 443));12257}12258function isHTTPS(protocol) {12259 return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false;12260}12261function omit(obj, ...keys) {12262 const ret = {};12263 let key;12264 for (key in obj) {12265 if (!keys.includes(key)) {12266 ret[key] = obj[key];12267 }12268 }12269 return ret;12270}12271//# sourceMappingURL=agent.js.map12272/***/ }),12273/***/ 7219:12274/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) {12275"use strict";12276var __importDefault = (this && this.__importDefault) || function (mod) {12277 return (mod && mod.__esModule) ? mod : { "default": mod };12278};12279const agent_1 = __importDefault(__nccwpck_require__(5098));12280function createHttpsProxyAgent(opts) {12281 return new agent_1.default(opts);12282}12283(function (createHttpsProxyAgent) {12284 createHttpsProxyAgent.HttpsProxyAgent = agent_1.default;12285 createHttpsProxyAgent.prototype = agent_1.default.prototype;12286})(createHttpsProxyAgent || (createHttpsProxyAgent = {}));12287module.exports = createHttpsProxyAgent;12288//# sourceMappingURL=index.js.map12289/***/ }),12290/***/ 595:12291/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {12292"use strict";12293var __importDefault = (this && this.__importDefault) || function (mod) {12294 return (mod && mod.__esModule) ? mod : { "default": mod };12295};12296Object.defineProperty(exports, "__esModule", ({ value: true }));12297const debug_1 = __importDefault(__nccwpck_require__(8237));12298const debug = debug_1.default('https-proxy-agent:parse-proxy-response');12299function parseProxyResponse(socket) {12300 return new Promise((resolve, reject) => {12301 // we need to buffer any HTTP traffic that happens with the proxy before we get12302 // the CONNECT response, so that if the response is anything other than an "200"12303 // response code, then we can re-play the "data" events on the socket once the12304 // HTTP parser is hooked up...12305 let buffersLength = 0;12306 const buffers = [];12307 function read() {12308 const b = socket.read();12309 if (b)12310 ondata(b);12311 else12312 socket.once('readable', read);12313 }12314 function cleanup() {12315 socket.removeListener('end', onend);12316 socket.removeListener('error', onerror);12317 socket.removeListener('close', onclose);12318 socket.removeListener('readable', read);12319 }12320 function onclose(err) {12321 debug('onclose had error %o', err);12322 }12323 function onend() {12324 debug('onend');12325 }12326 function onerror(err) {12327 cleanup();12328 debug('onerror %o', err);12329 reject(err);12330 }12331 function ondata(b) {12332 buffers.push(b);12333 buffersLength += b.length;12334 const buffered = Buffer.concat(buffers, buffersLength);12335 const endOfHeaders = buffered.indexOf('\r\n\r\n');12336 if (endOfHeaders === -1) {12337 // keep buffering12338 debug('have not received end of HTTP headers yet...');12339 read();12340 return;12341 }12342 const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n'));12343 const statusCode = +firstLine.split(' ')[1];12344 debug('got proxy server response: %o', firstLine);12345 resolve({12346 statusCode,12347 buffered12348 });12349 }12350 socket.on('error', onerror);12351 socket.on('close', onclose);12352 socket.on('end', onend);12353 read();12354 });12355}12356exports["default"] = parseProxyResponse;12357//# sourceMappingURL=parse-proxy-response.js.map12358/***/ }),12359/***/ 1554:12360/***/ ((module) => {12361"use strict";12362const isStream = stream =>12363 stream !== null &&12364 typeof stream === 'object' &&12365 typeof stream.pipe === 'function';12366isStream.writable = stream =>12367 isStream(stream) &&12368 stream.writable !== false &&12369 typeof stream._write === 'function' &&12370 typeof stream._writableState === 'object';12371isStream.readable = stream =>12372 isStream(stream) &&12373 stream.readable !== false &&12374 typeof stream._read === 'function' &&12375 typeof stream._readableState === 'object';12376isStream.duplex = stream =>12377 isStream.writable(stream) &&12378 isStream.readable(stream);12379isStream.transform = stream =>12380 isStream.duplex(stream) &&12381 typeof stream._transform === 'function';12382module.exports = isStream;12383/***/ }),12384/***/ 5031:12385/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {12386var json_stringify = (__nccwpck_require__(8574).stringify);12387var json_parse = __nccwpck_require__(9099);12388module.exports = function(options) {12389 return {12390 parse: json_parse(options),12391 stringify: json_stringify12392 }12393};12394//create the default method members with no options applied for backwards compatibility12395module.exports.parse = json_parse();12396module.exports.stringify = json_stringify;12397/***/ }),12398/***/ 9099:12399/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {12400var BigNumber = null;12401// regexpxs extracted from12402// (c) BSD-3-Clause12403// https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors12404const suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/;12405const suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;12406/*12407 json_parse.js12408 2012-06-2012409 Public Domain.12410 NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.12411 This file creates a json_parse function.12412 During create you can (optionally) specify some behavioural switches12413 require('json-bigint')(options)12414 The optional options parameter holds switches that drive certain12415 aspects of the parsing process:12416 * options.strict = true will warn about duplicate-key usage in the json.12417 The default (strict = false) will silently ignore those and overwrite12418 values for keys that are in duplicate use.12419 The resulting function follows this signature:12420 json_parse(text, reviver)12421 This method parses a JSON text to produce an object or array.12422 It can throw a SyntaxError exception.12423 The optional reviver parameter is a function that can filter and12424 transform the results. It receives each of the keys and values,12425 and its return value is used instead of the original value.12426 If it returns what it received, then the structure is not modified.12427 If it returns undefined then the member is deleted.12428 Example:12429 // Parse the text. Values that look like ISO date strings will12430 // be converted to Date objects.12431 myData = json_parse(text, function (key, value) {12432 var a;12433 if (typeof value === 'string') {12434 a =12435/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);12436 if (a) {12437 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],12438 +a[5], +a[6]));12439 }12440 }12441 return value;12442 });12443 This is a reference implementation. You are free to copy, modify, or12444 redistribute.12445 This code should be minified before deployment.12446 See http://javascript.crockford.com/jsmin.html12447 USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO12448 NOT CONTROL.12449*/12450/*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode,12451 hasOwnProperty, message, n, name, prototype, push, r, t, text12452*/12453var json_parse = function (options) {12454 'use strict';12455 // This is a function that can parse a JSON text, producing a JavaScript12456 // data structure. It is a simple, recursive descent parser. It does not use12457 // eval or regular expressions, so it can be used as a model for implementing12458 // a JSON parser in other languages.12459 // We are defining the function inside of another function to avoid creating12460 // global variables.12461 // Default options one can override by passing options to the parse()12462 var _options = {12463 strict: false, // not being strict means do not generate syntax errors for "duplicate key"12464 storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string12465 alwaysParseAsBig: false, // toggles whether all numbers should be Big12466 useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js12467 protoAction: 'error',12468 constructorAction: 'error',12469 };12470 // If there are options, then use them to override the default _options12471 if (options !== undefined && options !== null) {12472 if (options.strict === true) {12473 _options.strict = true;12474 }12475 if (options.storeAsString === true) {12476 _options.storeAsString = true;12477 }12478 _options.alwaysParseAsBig =12479 options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false;12480 _options.useNativeBigInt =12481 options.useNativeBigInt === true ? options.useNativeBigInt : false;12482 if (typeof options.constructorAction !== 'undefined') {12483 if (12484 options.constructorAction === 'error' ||12485 options.constructorAction === 'ignore' ||12486 options.constructorAction === 'preserve'12487 ) {12488 _options.constructorAction = options.constructorAction;12489 } else {12490 throw new Error(12491 `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}`12492 );12493 }12494 }12495 if (typeof options.protoAction !== 'undefined') {12496 if (12497 options.protoAction === 'error' ||12498 options.protoAction === 'ignore' ||12499 options.protoAction === 'preserve'12500 ) {12501 _options.protoAction = options.protoAction;12502 } else {12503 throw new Error(12504 `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}`12505 );12506 }12507 }12508 }12509 var at, // The index of the current character12510 ch, // The current character12511 escapee = {12512 '"': '"',12513 '\\': '\\',12514 '/': '/',12515 b: '\b',12516 f: '\f',12517 n: '\n',12518 r: '\r',12519 t: '\t',12520 },12521 text,12522 error = function (m) {12523 // Call error when something is wrong.12524 throw {12525 name: 'SyntaxError',12526 message: m,12527 at: at,12528 text: text,12529 };12530 },12531 next = function (c) {12532 // If a c parameter is provided, verify that it matches the current character.12533 if (c && c !== ch) {12534 error("Expected '" + c + "' instead of '" + ch + "'");12535 }12536 // Get the next character. When there are no more characters,12537 // return the empty string.12538 ch = text.charAt(at);12539 at += 1;12540 return ch;12541 },12542 number = function () {12543 // Parse a number value.12544 var number,12545 string = '';12546 if (ch === '-') {12547 string = '-';12548 next('-');12549 }12550 while (ch >= '0' && ch <= '9') {12551 string += ch;12552 next();12553 }12554 if (ch === '.') {12555 string += '.';12556 while (next() && ch >= '0' && ch <= '9') {12557 string += ch;12558 }12559 }12560 if (ch === 'e' || ch === 'E') {12561 string += ch;12562 next();12563 if (ch === '-' || ch === '+') {12564 string += ch;12565 next();12566 }12567 while (ch >= '0' && ch <= '9') {12568 string += ch;12569 next();12570 }12571 }12572 number = +string;12573 if (!isFinite(number)) {12574 error('Bad number');12575 } else {12576 if (BigNumber == null) BigNumber = __nccwpck_require__(7558);12577 //if (number > 9007199254740992 || number < -9007199254740992)12578 // Bignumber has stricter check: everything with length > 15 digits disallowed12579 if (string.length > 15)12580 return _options.storeAsString12581 ? string12582 : _options.useNativeBigInt12583 ? BigInt(string)12584 : new BigNumber(string);12585 else12586 return !_options.alwaysParseAsBig12587 ? number12588 : _options.useNativeBigInt12589 ? BigInt(number)12590 : new BigNumber(number);12591 }12592 },12593 string = function () {12594 // Parse a string value.12595 var hex,12596 i,12597 string = '',12598 uffff;12599 // When parsing for string values, we must look for " and \ characters.12600 if (ch === '"') {12601 var startAt = at;12602 while (next()) {12603 if (ch === '"') {12604 if (at - 1 > startAt) string += text.substring(startAt, at - 1);12605 next();12606 return string;12607 }12608 if (ch === '\\') {12609 if (at - 1 > startAt) string += text.substring(startAt, at - 1);12610 next();12611 if (ch === 'u') {12612 uffff = 0;12613 for (i = 0; i < 4; i += 1) {12614 hex = parseInt(next(), 16);12615 if (!isFinite(hex)) {12616 break;12617 }12618 uffff = uffff * 16 + hex;12619 }12620 string += String.fromCharCode(uffff);12621 } else if (typeof escapee[ch] === 'string') {12622 string += escapee[ch];12623 } else {12624 break;12625 }12626 startAt = at;12627 }12628 }12629 }12630 error('Bad string');12631 },12632 white = function () {12633 // Skip whitespace.12634 while (ch && ch <= ' ') {12635 next();12636 }12637 },12638 word = function () {12639 // true, false, or null.12640 switch (ch) {12641 case 't':12642 next('t');12643 next('r');12644 next('u');12645 next('e');12646 return true;12647 case 'f':12648 next('f');12649 next('a');12650 next('l');12651 next('s');12652 next('e');12653 return false;12654 case 'n':12655 next('n');12656 next('u');12657 next('l');12658 next('l');12659 return null;12660 }12661 error("Unexpected '" + ch + "'");12662 },12663 value, // Place holder for the value function.12664 array = function () {12665 // Parse an array value.12666 var array = [];12667 if (ch === '[') {12668 next('[');12669 white();12670 if (ch === ']') {12671 next(']');12672 return array; // empty array12673 }12674 while (ch) {12675 array.push(value());12676 white();12677 if (ch === ']') {12678 next(']');12679 return array;12680 }12681 next(',');12682 white();12683 }12684 }12685 error('Bad array');12686 },12687 object = function () {12688 // Parse an object value.12689 var key,12690 object = Object.create(null);12691 if (ch === '{') {12692 next('{');12693 white();12694 if (ch === '}') {12695 next('}');12696 return object; // empty object12697 }12698 while (ch) {12699 key = string();12700 white();12701 next(':');12702 if (12703 _options.strict === true &&12704 Object.hasOwnProperty.call(object, key)12705 ) {12706 error('Duplicate key "' + key + '"');12707 }12708 if (suspectProtoRx.test(key) === true) {12709 if (_options.protoAction === 'error') {12710 error('Object contains forbidden prototype property');12711 } else if (_options.protoAction === 'ignore') {12712 value();12713 } else {12714 object[key] = value();12715 }12716 } else if (suspectConstructorRx.test(key) === true) {12717 if (_options.constructorAction === 'error') {12718 error('Object contains forbidden constructor property');12719 } else if (_options.constructorAction === 'ignore') {12720 value();12721 } else {12722 object[key] = value();12723 }12724 } else {12725 object[key] = value();12726 }12727 white();12728 if (ch === '}') {12729 next('}');12730 return object;12731 }12732 next(',');12733 white();12734 }12735 }12736 error('Bad object');12737 };12738 value = function () {12739 // Parse a JSON value. It could be an object, an array, a string, a number,12740 // or a word.12741 white();12742 switch (ch) {12743 case '{':12744 return object();12745 case '[':12746 return array();12747 case '"':12748 return string();12749 case '-':12750 return number();12751 default:12752 return ch >= '0' && ch <= '9' ? number() : word();12753 }12754 };12755 // Return the json_parse function. It will have access to all of the above12756 // functions and variables.12757 return function (source, reviver) {12758 var result;12759 text = source + '';12760 at = 0;12761 ch = ' ';12762 result = value();12763 white();12764 if (ch) {12765 error('Syntax error');12766 }12767 // If there is a reviver function, we recursively walk the new structure,12768 // passing each name/value pair to the reviver function for possible12769 // transformation, starting with a temporary root object that holds the result12770 // in an empty key. If there is not a reviver function, we simply return the12771 // result.12772 return typeof reviver === 'function'12773 ? (function walk(holder, key) {12774 var k,12775 v,12776 value = holder[key];12777 if (value && typeof value === 'object') {12778 Object.keys(value).forEach(function (k) {12779 v = walk(value, k);12780 if (v !== undefined) {12781 value[k] = v;12782 } else {12783 delete value[k];12784 }12785 });12786 }12787 return reviver.call(holder, key, value);12788 })({ '': result }, '')12789 : result;12790 };12791};12792module.exports = json_parse;12793/***/ }),12794/***/ 8574:12795/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {12796var BigNumber = __nccwpck_require__(7558);12797/*12798 json2.js12799 2013-05-2612800 Public Domain.12801 NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.12802 See http://www.JSON.org/js.html12803 This code should be minified before deployment.12804 See http://javascript.crockford.com/jsmin.html12805 USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO12806 NOT CONTROL.12807 This file creates a global JSON object containing two methods: stringify12808 and parse.12809 JSON.stringify(value, replacer, space)12810 value any JavaScript value, usually an object or array.12811 replacer an optional parameter that determines how object12812 values are stringified for objects. It can be a12813 function or an array of strings.12814 space an optional parameter that specifies the indentation12815 of nested structures. If it is omitted, the text will12816 be packed without extra whitespace. If it is a number,12817 it will specify the number of spaces to indent at each12818 level. If it is a string (such as '\t' or '&nbsp;'),12819 it contains the characters used to indent at each level.12820 This method produces a JSON text from a JavaScript value.12821 When an object value is found, if the object contains a toJSON12822 method, its toJSON method will be called and the result will be12823 stringified. A toJSON method does not serialize: it returns the12824 value represented by the name/value pair that should be serialized,12825 or undefined if nothing should be serialized. The toJSON method12826 will be passed the key associated with the value, and this will be12827 bound to the value12828 For example, this would serialize Dates as ISO strings.12829 Date.prototype.toJSON = function (key) {12830 function f(n) {12831 // Format integers to have at least two digits.12832 return n < 10 ? '0' + n : n;12833 }12834 return this.getUTCFullYear() + '-' +12835 f(this.getUTCMonth() + 1) + '-' +12836 f(this.getUTCDate()) + 'T' +12837 f(this.getUTCHours()) + ':' +12838 f(this.getUTCMinutes()) + ':' +12839 f(this.getUTCSeconds()) + 'Z';12840 };12841 You can provide an optional replacer method. It will be passed the12842 key and value of each member, with this bound to the containing12843 object. The value that is returned from your method will be12844 serialized. If your method returns undefined, then the member will12845 be excluded from the serialization.12846 If the replacer parameter is an array of strings, then it will be12847 used to select the members to be serialized. It filters the results12848 such that only members with keys listed in the replacer array are12849 stringified.12850 Values that do not have JSON representations, such as undefined or12851 functions, will not be serialized. Such values in objects will be12852 dropped; in arrays they will be replaced with null. You can use12853 a replacer function to replace those with JSON values.12854 JSON.stringify(undefined) returns undefined.12855 The optional space parameter produces a stringification of the12856 value that is filled with line breaks and indentation to make it12857 easier to read.12858 If the space parameter is a non-empty string, then that string will12859 be used for indentation. If the space parameter is a number, then12860 the indentation will be that many spaces.12861 Example:12862 text = JSON.stringify(['e', {pluribus: 'unum'}]);12863 // text is '["e",{"pluribus":"unum"}]'12864 text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');12865 // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'12866 text = JSON.stringify([new Date()], function (key, value) {12867 return this[key] instanceof Date ?12868 'Date(' + this[key] + ')' : value;12869 });12870 // text is '["Date(---current time---)"]'12871 JSON.parse(text, reviver)12872 This method parses a JSON text to produce an object or array.12873 It can throw a SyntaxError exception.12874 The optional reviver parameter is a function that can filter and12875 transform the results. It receives each of the keys and values,12876 and its return value is used instead of the original value.12877 If it returns what it received, then the structure is not modified.12878 If it returns undefined then the member is deleted.12879 Example:12880 // Parse the text. Values that look like ISO date strings will12881 // be converted to Date objects.12882 myData = JSON.parse(text, function (key, value) {12883 var a;12884 if (typeof value === 'string') {12885 a =12886/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);12887 if (a) {12888 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],12889 +a[5], +a[6]));12890 }12891 }12892 return value;12893 });12894 myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {12895 var d;12896 if (typeof value === 'string' &&12897 value.slice(0, 5) === 'Date(' &&12898 value.slice(-1) === ')') {12899 d = new Date(value.slice(5, -1));12900 if (d) {12901 return d;12902 }12903 }12904 return value;12905 });12906 This is a reference implementation. You are free to copy, modify, or12907 redistribute.12908*/12909/*jslint evil: true, regexp: true */12910/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,12911 call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,12912 getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,12913 lastIndex, length, parse, prototype, push, replace, slice, stringify,12914 test, toJSON, toString, valueOf12915*/12916// Create a JSON object only if one does not already exist. We create the12917// methods in a closure to avoid creating global variables.12918var JSON = module.exports;12919(function () {12920 'use strict';12921 function f(n) {12922 // Format integers to have at least two digits.12923 return n < 10 ? '0' + n : n;12924 }12925 var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,12926 escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,12927 gap,12928 indent,12929 meta = { // table of character substitutions12930 '\b': '\\b',12931 '\t': '\\t',12932 '\n': '\\n',12933 '\f': '\\f',12934 '\r': '\\r',12935 '"' : '\\"',12936 '\\': '\\\\'12937 },12938 rep;12939 function quote(string) {12940// If the string contains no control characters, no quote characters, and no12941// backslash characters, then we can safely slap some quotes around it.12942// Otherwise we must also replace the offending characters with safe escape12943// sequences.12944 escapable.lastIndex = 0;12945 return escapable.test(string) ? '"' + string.replace(escapable, function (a) {12946 var c = meta[a];12947 return typeof c === 'string'12948 ? c12949 : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);12950 }) + '"' : '"' + string + '"';12951 }12952 function str(key, holder) {12953// Produce a string from holder[key].12954 var i, // The loop counter.12955 k, // The member key.12956 v, // The member value.12957 length,12958 mind = gap,12959 partial,12960 value = holder[key],12961 isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));12962// If the value has a toJSON method, call it to obtain a replacement value.12963 if (value && typeof value === 'object' &&12964 typeof value.toJSON === 'function') {12965 value = value.toJSON(key);12966 }12967// If we were called with a replacer function, then call the replacer to12968// obtain a replacement value.12969 if (typeof rep === 'function') {12970 value = rep.call(holder, key, value);12971 }12972// What happens next depends on the value's type.12973 switch (typeof value) {12974 case 'string':12975 if (isBigNumber) {12976 return value;12977 } else {12978 return quote(value);12979 }12980 case 'number':12981// JSON numbers must be finite. Encode non-finite numbers as null.12982 return isFinite(value) ? String(value) : 'null';12983 case 'boolean':12984 case 'null':12985 case 'bigint':12986// If the value is a boolean or null, convert it to a string. Note:12987// typeof null does not produce 'null'. The case is included here in12988// the remote chance that this gets fixed someday.12989 return String(value);12990// If the type is 'object', we might be dealing with an object or an array or12991// null.12992 case 'object':12993// Due to a specification blunder in ECMAScript, typeof null is 'object',12994// so watch out for that case.12995 if (!value) {12996 return 'null';12997 }12998// Make an array to hold the partial results of stringifying this object value.12999 gap += indent;13000 partial = [];13001// Is the value an array?13002 if (Object.prototype.toString.apply(value) === '[object Array]') {13003// The value is an array. Stringify every element. Use null as a placeholder13004// for non-JSON values.13005 length = value.length;13006 for (i = 0; i < length; i += 1) {13007 partial[i] = str(i, value) || 'null';13008 }13009// Join all of the elements together, separated with commas, and wrap them in13010// brackets.13011 v = partial.length === 013012 ? '[]'13013 : gap13014 ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'13015 : '[' + partial.join(',') + ']';13016 gap = mind;13017 return v;13018 }13019// If the replacer is an array, use it to select the members to be stringified.13020 if (rep && typeof rep === 'object') {13021 length = rep.length;13022 for (i = 0; i < length; i += 1) {13023 if (typeof rep[i] === 'string') {13024 k = rep[i];13025 v = str(k, value);13026 if (v) {13027 partial.push(quote(k) + (gap ? ': ' : ':') + v);13028 }13029 }13030 }13031 } else {13032// Otherwise, iterate through all of the keys in the object.13033 Object.keys(value).forEach(function(k) {13034 var v = str(k, value);13035 if (v) {13036 partial.push(quote(k) + (gap ? ': ' : ':') + v);13037 }13038 });13039 }13040// Join all of the member texts together, separated with commas,13041// and wrap them in braces.13042 v = partial.length === 013043 ? '{}'13044 : gap13045 ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'13046 : '{' + partial.join(',') + '}';13047 gap = mind;13048 return v;13049 }13050 }13051// If the JSON object does not yet have a stringify method, give it one.13052 if (typeof JSON.stringify !== 'function') {13053 JSON.stringify = function (value, replacer, space) {13054// The stringify method takes a value and an optional replacer, and an optional13055// space parameter, and returns a JSON text. The replacer can be a function13056// that can replace values, or an array of strings that will select the keys.13057// A default replacer method can be provided. Use of the space parameter can13058// produce text that is more easily readable.13059 var i;13060 gap = '';13061 indent = '';13062// If the space parameter is a number, make an indent string containing that13063// many spaces.13064 if (typeof space === 'number') {13065 for (i = 0; i < space; i += 1) {13066 indent += ' ';13067 }13068// If the space parameter is a string, it will be used as the indent string.13069 } else if (typeof space === 'string') {13070 indent = space;13071 }13072// If there is a replacer, it must be a function or an array.13073// Otherwise, throw an error.13074 rep = replacer;13075 if (replacer && typeof replacer !== 'function' &&13076 (typeof replacer !== 'object' ||13077 typeof replacer.length !== 'number')) {13078 throw new Error('JSON.stringify');13079 }13080// Make a fake root object containing our value under the key of ''.13081// Return the result of stringifying the value.13082 return str('', {'': value});13083 };13084 }13085}());13086/***/ }),13087/***/ 6010:13088/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13089var bufferEqual = __nccwpck_require__(9239);13090var Buffer = (__nccwpck_require__(1867).Buffer);13091var crypto = __nccwpck_require__(6113);13092var formatEcdsa = __nccwpck_require__(1728);13093var util = __nccwpck_require__(3837);13094var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".'13095var MSG_INVALID_SECRET = 'secret must be a string or buffer';13096var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';13097var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';13098var supportsKeyObjects = typeof crypto.createPublicKey === 'function';13099if (supportsKeyObjects) {13100 MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';13101 MSG_INVALID_SECRET += 'or a KeyObject';13102}13103function checkIsPublicKey(key) {13104 if (Buffer.isBuffer(key)) {13105 return;13106 }13107 if (typeof key === 'string') {13108 return;13109 }13110 if (!supportsKeyObjects) {13111 throw typeError(MSG_INVALID_VERIFIER_KEY);13112 }13113 if (typeof key !== 'object') {13114 throw typeError(MSG_INVALID_VERIFIER_KEY);13115 }13116 if (typeof key.type !== 'string') {13117 throw typeError(MSG_INVALID_VERIFIER_KEY);13118 }13119 if (typeof key.asymmetricKeyType !== 'string') {13120 throw typeError(MSG_INVALID_VERIFIER_KEY);13121 }13122 if (typeof key.export !== 'function') {13123 throw typeError(MSG_INVALID_VERIFIER_KEY);13124 }13125};13126function checkIsPrivateKey(key) {13127 if (Buffer.isBuffer(key)) {13128 return;13129 }13130 if (typeof key === 'string') {13131 return;13132 }13133 if (typeof key === 'object') {13134 return;13135 }13136 throw typeError(MSG_INVALID_SIGNER_KEY);13137};13138function checkIsSecretKey(key) {13139 if (Buffer.isBuffer(key)) {13140 return;13141 }13142 if (typeof key === 'string') {13143 return key;13144 }13145 if (!supportsKeyObjects) {13146 throw typeError(MSG_INVALID_SECRET);13147 }13148 if (typeof key !== 'object') {13149 throw typeError(MSG_INVALID_SECRET);13150 }13151 if (key.type !== 'secret') {13152 throw typeError(MSG_INVALID_SECRET);13153 }13154 if (typeof key.export !== 'function') {13155 throw typeError(MSG_INVALID_SECRET);13156 }13157}13158function fromBase64(base64) {13159 return base6413160 .replace(/=/g, '')13161 .replace(/\+/g, '-')13162 .replace(/\//g, '_');13163}13164function toBase64(base64url) {13165 base64url = base64url.toString();13166 var padding = 4 - base64url.length % 4;13167 if (padding !== 4) {13168 for (var i = 0; i < padding; ++i) {13169 base64url += '=';13170 }13171 }13172 return base64url13173 .replace(/\-/g, '+')13174 .replace(/_/g, '/');13175}13176function typeError(template) {13177 var args = [].slice.call(arguments, 1);13178 var errMsg = util.format.bind(util, template).apply(null, args);13179 return new TypeError(errMsg);13180}13181function bufferOrString(obj) {13182 return Buffer.isBuffer(obj) || typeof obj === 'string';13183}13184function normalizeInput(thing) {13185 if (!bufferOrString(thing))13186 thing = JSON.stringify(thing);13187 return thing;13188}13189function createHmacSigner(bits) {13190 return function sign(thing, secret) {13191 checkIsSecretKey(secret);13192 thing = normalizeInput(thing);13193 var hmac = crypto.createHmac('sha' + bits, secret);13194 var sig = (hmac.update(thing), hmac.digest('base64'))13195 return fromBase64(sig);13196 }13197}13198function createHmacVerifier(bits) {13199 return function verify(thing, signature, secret) {13200 var computedSig = createHmacSigner(bits)(thing, secret);13201 return bufferEqual(Buffer.from(signature), Buffer.from(computedSig));13202 }13203}13204function createKeySigner(bits) {13205 return function sign(thing, privateKey) {13206 checkIsPrivateKey(privateKey);13207 thing = normalizeInput(thing);13208 // Even though we are specifying "RSA" here, this works with ECDSA13209 // keys as well.13210 var signer = crypto.createSign('RSA-SHA' + bits);13211 var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));13212 return fromBase64(sig);13213 }13214}13215function createKeyVerifier(bits) {13216 return function verify(thing, signature, publicKey) {13217 checkIsPublicKey(publicKey);13218 thing = normalizeInput(thing);13219 signature = toBase64(signature);13220 var verifier = crypto.createVerify('RSA-SHA' + bits);13221 verifier.update(thing);13222 return verifier.verify(publicKey, signature, 'base64');13223 }13224}13225function createPSSKeySigner(bits) {13226 return function sign(thing, privateKey) {13227 checkIsPrivateKey(privateKey);13228 thing = normalizeInput(thing);13229 var signer = crypto.createSign('RSA-SHA' + bits);13230 var sig = (signer.update(thing), signer.sign({13231 key: privateKey,13232 padding: crypto.constants.RSA_PKCS1_PSS_PADDING,13233 saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST13234 }, 'base64'));13235 return fromBase64(sig);13236 }13237}13238function createPSSKeyVerifier(bits) {13239 return function verify(thing, signature, publicKey) {13240 checkIsPublicKey(publicKey);13241 thing = normalizeInput(thing);13242 signature = toBase64(signature);13243 var verifier = crypto.createVerify('RSA-SHA' + bits);13244 verifier.update(thing);13245 return verifier.verify({13246 key: publicKey,13247 padding: crypto.constants.RSA_PKCS1_PSS_PADDING,13248 saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST13249 }, signature, 'base64');13250 }13251}13252function createECDSASigner(bits) {13253 var inner = createKeySigner(bits);13254 return function sign() {13255 var signature = inner.apply(null, arguments);13256 signature = formatEcdsa.derToJose(signature, 'ES' + bits);13257 return signature;13258 };13259}13260function createECDSAVerifer(bits) {13261 var inner = createKeyVerifier(bits);13262 return function verify(thing, signature, publicKey) {13263 signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');13264 var result = inner(thing, signature, publicKey);13265 return result;13266 };13267}13268function createNoneSigner() {13269 return function sign() {13270 return '';13271 }13272}13273function createNoneVerifier() {13274 return function verify(thing, signature) {13275 return signature === '';13276 }13277}13278module.exports = function jwa(algorithm) {13279 var signerFactories = {13280 hs: createHmacSigner,13281 rs: createKeySigner,13282 ps: createPSSKeySigner,13283 es: createECDSASigner,13284 none: createNoneSigner,13285 }13286 var verifierFactories = {13287 hs: createHmacVerifier,13288 rs: createKeyVerifier,13289 ps: createPSSKeyVerifier,13290 es: createECDSAVerifer,13291 none: createNoneVerifier,13292 }13293 var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);13294 if (!match)13295 throw typeError(MSG_INVALID_ALGORITHM, algorithm);13296 var algo = (match[1] || match[3]).toLowerCase();13297 var bits = match[2];13298 return {13299 sign: signerFactories[algo](bits),13300 verify: verifierFactories[algo](bits),13301 }13302};13303/***/ }),13304/***/ 4636:13305/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {13306/*global exports*/13307var SignStream = __nccwpck_require__(3334);13308var VerifyStream = __nccwpck_require__(5522);13309var ALGORITHMS = [13310 'HS256', 'HS384', 'HS512',13311 'RS256', 'RS384', 'RS512',13312 'PS256', 'PS384', 'PS512',13313 'ES256', 'ES384', 'ES512'13314];13315exports.ALGORITHMS = ALGORITHMS;13316exports.sign = SignStream.sign;13317exports.verify = VerifyStream.verify;13318exports.decode = VerifyStream.decode;13319exports.isValid = VerifyStream.isValid;13320exports.createSign = function createSign(opts) {13321 return new SignStream(opts);13322};13323exports.createVerify = function createVerify(opts) {13324 return new VerifyStream(opts);13325};13326/***/ }),13327/***/ 1868:13328/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13329/*global module, process*/13330var Buffer = (__nccwpck_require__(1867).Buffer);13331var Stream = __nccwpck_require__(2781);13332var util = __nccwpck_require__(3837);13333function DataStream(data) {13334 this.buffer = null;13335 this.writable = true;13336 this.readable = true;13337 // No input13338 if (!data) {13339 this.buffer = Buffer.alloc(0);13340 return this;13341 }13342 // Stream13343 if (typeof data.pipe === 'function') {13344 this.buffer = Buffer.alloc(0);13345 data.pipe(this);13346 return this;13347 }13348 // Buffer or String13349 // or Object (assumedly a passworded key)13350 if (data.length || typeof data === 'object') {13351 this.buffer = data;13352 this.writable = false;13353 process.nextTick(function () {13354 this.emit('end', data);13355 this.readable = false;13356 this.emit('close');13357 }.bind(this));13358 return this;13359 }13360 throw new TypeError('Unexpected data type ('+ typeof data + ')');13361}13362util.inherits(DataStream, Stream);13363DataStream.prototype.write = function write(data) {13364 this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]);13365 this.emit('data', data);13366};13367DataStream.prototype.end = function end(data) {13368 if (data)13369 this.write(data);13370 this.emit('end', data);13371 this.emit('close');13372 this.writable = false;13373 this.readable = false;13374};13375module.exports = DataStream;13376/***/ }),13377/***/ 3334:13378/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13379/*global module*/13380var Buffer = (__nccwpck_require__(1867).Buffer);13381var DataStream = __nccwpck_require__(1868);13382var jwa = __nccwpck_require__(6010);13383var Stream = __nccwpck_require__(2781);13384var toString = __nccwpck_require__(5292);13385var util = __nccwpck_require__(3837);13386function base64url(string, encoding) {13387 return Buffer13388 .from(string, encoding)13389 .toString('base64')13390 .replace(/=/g, '')13391 .replace(/\+/g, '-')13392 .replace(/\//g, '_');13393}13394function jwsSecuredInput(header, payload, encoding) {13395 encoding = encoding || 'utf8';13396 var encodedHeader = base64url(toString(header), 'binary');13397 var encodedPayload = base64url(toString(payload), encoding);13398 return util.format('%s.%s', encodedHeader, encodedPayload);13399}13400function jwsSign(opts) {13401 var header = opts.header;13402 var payload = opts.payload;13403 var secretOrKey = opts.secret || opts.privateKey;13404 var encoding = opts.encoding;13405 var algo = jwa(header.alg);13406 var securedInput = jwsSecuredInput(header, payload, encoding);13407 var signature = algo.sign(securedInput, secretOrKey);13408 return util.format('%s.%s', securedInput, signature);13409}13410function SignStream(opts) {13411 var secret = opts.secret||opts.privateKey||opts.key;13412 var secretStream = new DataStream(secret);13413 this.readable = true;13414 this.header = opts.header;13415 this.encoding = opts.encoding;13416 this.secret = this.privateKey = this.key = secretStream;13417 this.payload = new DataStream(opts.payload);13418 this.secret.once('close', function () {13419 if (!this.payload.writable && this.readable)13420 this.sign();13421 }.bind(this));13422 this.payload.once('close', function () {13423 if (!this.secret.writable && this.readable)13424 this.sign();13425 }.bind(this));13426}13427util.inherits(SignStream, Stream);13428SignStream.prototype.sign = function sign() {13429 try {13430 var signature = jwsSign({13431 header: this.header,13432 payload: this.payload.buffer,13433 secret: this.secret.buffer,13434 encoding: this.encoding13435 });13436 this.emit('done', signature);13437 this.emit('data', signature);13438 this.emit('end');13439 this.readable = false;13440 return signature;13441 } catch (e) {13442 this.readable = false;13443 this.emit('error', e);13444 this.emit('close');13445 }13446};13447SignStream.sign = jwsSign;13448module.exports = SignStream;13449/***/ }),13450/***/ 5292:13451/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13452/*global module*/13453var Buffer = (__nccwpck_require__(4300).Buffer);13454module.exports = function toString(obj) {13455 if (typeof obj === 'string')13456 return obj;13457 if (typeof obj === 'number' || Buffer.isBuffer(obj))13458 return obj.toString();13459 return JSON.stringify(obj);13460};13461/***/ }),13462/***/ 5522:13463/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13464/*global module*/13465var Buffer = (__nccwpck_require__(1867).Buffer);13466var DataStream = __nccwpck_require__(1868);13467var jwa = __nccwpck_require__(6010);13468var Stream = __nccwpck_require__(2781);13469var toString = __nccwpck_require__(5292);13470var util = __nccwpck_require__(3837);13471var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;13472function isObject(thing) {13473 return Object.prototype.toString.call(thing) === '[object Object]';13474}13475function safeJsonParse(thing) {13476 if (isObject(thing))13477 return thing;13478 try { return JSON.parse(thing); }13479 catch (e) { return undefined; }13480}13481function headerFromJWS(jwsSig) {13482 var encodedHeader = jwsSig.split('.', 1)[0];13483 return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));13484}13485function securedInputFromJWS(jwsSig) {13486 return jwsSig.split('.', 2).join('.');13487}13488function signatureFromJWS(jwsSig) {13489 return jwsSig.split('.')[2];13490}13491function payloadFromJWS(jwsSig, encoding) {13492 encoding = encoding || 'utf8';13493 var payload = jwsSig.split('.')[1];13494 return Buffer.from(payload, 'base64').toString(encoding);13495}13496function isValidJws(string) {13497 return JWS_REGEX.test(string) && !!headerFromJWS(string);13498}13499function jwsVerify(jwsSig, algorithm, secretOrKey) {13500 if (!algorithm) {13501 var err = new Error("Missing algorithm parameter for jws.verify");13502 err.code = "MISSING_ALGORITHM";13503 throw err;13504 }13505 jwsSig = toString(jwsSig);13506 var signature = signatureFromJWS(jwsSig);13507 var securedInput = securedInputFromJWS(jwsSig);13508 var algo = jwa(algorithm);13509 return algo.verify(securedInput, signature, secretOrKey);13510}13511function jwsDecode(jwsSig, opts) {13512 opts = opts || {};13513 jwsSig = toString(jwsSig);13514 if (!isValidJws(jwsSig))13515 return null;13516 var header = headerFromJWS(jwsSig);13517 if (!header)13518 return null;13519 var payload = payloadFromJWS(jwsSig);13520 if (header.typ === 'JWT' || opts.json)13521 payload = JSON.parse(payload, opts.encoding);13522 return {13523 header: header,13524 payload: payload,13525 signature: signatureFromJWS(jwsSig)13526 };13527}13528function VerifyStream(opts) {13529 opts = opts || {};13530 var secretOrKey = opts.secret||opts.publicKey||opts.key;13531 var secretStream = new DataStream(secretOrKey);13532 this.readable = true;13533 this.algorithm = opts.algorithm;13534 this.encoding = opts.encoding;13535 this.secret = this.publicKey = this.key = secretStream;13536 this.signature = new DataStream(opts.signature);13537 this.secret.once('close', function () {13538 if (!this.signature.writable && this.readable)13539 this.verify();13540 }.bind(this));13541 this.signature.once('close', function () {13542 if (!this.secret.writable && this.readable)13543 this.verify();13544 }.bind(this));13545}13546util.inherits(VerifyStream, Stream);13547VerifyStream.prototype.verify = function verify() {13548 try {13549 var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);13550 var obj = jwsDecode(this.signature.buffer, this.encoding);13551 this.emit('done', valid, obj);13552 this.emit('data', valid);13553 this.emit('end');13554 this.readable = false;13555 return valid;13556 } catch (e) {13557 this.readable = false;13558 this.emit('error', e);13559 this.emit('close');13560 }13561};13562VerifyStream.decode = jwsDecode;13563VerifyStream.isValid = isValidJws;13564VerifyStream.verify = jwsVerify;13565module.exports = VerifyStream;13566/***/ }),13567/***/ 7129:13568/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {13569"use strict";13570// A linked list to keep track of recently-used-ness13571const Yallist = __nccwpck_require__(665)13572const MAX = Symbol('max')13573const LENGTH = Symbol('length')13574const LENGTH_CALCULATOR = Symbol('lengthCalculator')13575const ALLOW_STALE = Symbol('allowStale')13576const MAX_AGE = Symbol('maxAge')13577const DISPOSE = Symbol('dispose')13578const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')13579const LRU_LIST = Symbol('lruList')13580const CACHE = Symbol('cache')13581const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')13582const naiveLength = () => 113583// lruList is a yallist where the head is the youngest13584// item, and the tail is the oldest. the list contains the Hit13585// objects as the entries.13586// Each Hit object has a reference to its Yallist.Node. This13587// never changes.13588//13589// cache is a Map (or PseudoMap) that matches the keys to13590// the Yallist.Node object.13591class LRUCache {13592 constructor (options) {13593 if (typeof options === 'number')13594 options = { max: options }13595 if (!options)13596 options = {}13597 if (options.max && (typeof options.max !== 'number' || options.max < 0))13598 throw new TypeError('max must be a non-negative number')13599 // Kind of weird to have a default max of Infinity, but oh well.13600 const max = this[MAX] = options.max || Infinity13601 const lc = options.length || naiveLength13602 this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc13603 this[ALLOW_STALE] = options.stale || false13604 if (options.maxAge && typeof options.maxAge !== 'number')13605 throw new TypeError('maxAge must be a number')13606 this[MAX_AGE] = options.maxAge || 013607 this[DISPOSE] = options.dispose13608 this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false13609 this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false13610 this.reset()13611 }13612 // resize the cache when the max changes.13613 set max (mL) {13614 if (typeof mL !== 'number' || mL < 0)13615 throw new TypeError('max must be a non-negative number')13616 this[MAX] = mL || Infinity13617 trim(this)13618 }13619 get max () {13620 return this[MAX]13621 }13622 set allowStale (allowStale) {13623 this[ALLOW_STALE] = !!allowStale13624 }13625 get allowStale () {13626 return this[ALLOW_STALE]13627 }13628 set maxAge (mA) {13629 if (typeof mA !== 'number')13630 throw new TypeError('maxAge must be a non-negative number')13631 this[MAX_AGE] = mA13632 trim(this)13633 }13634 get maxAge () {13635 return this[MAX_AGE]13636 }13637 // resize the cache when the lengthCalculator changes.13638 set lengthCalculator (lC) {13639 if (typeof lC !== 'function')13640 lC = naiveLength13641 if (lC !== this[LENGTH_CALCULATOR]) {13642 this[LENGTH_CALCULATOR] = lC13643 this[LENGTH] = 013644 this[LRU_LIST].forEach(hit => {13645 hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)13646 this[LENGTH] += hit.length13647 })13648 }13649 trim(this)13650 }13651 get lengthCalculator () { return this[LENGTH_CALCULATOR] }13652 get length () { return this[LENGTH] }13653 get itemCount () { return this[LRU_LIST].length }13654 rforEach (fn, thisp) {13655 thisp = thisp || this13656 for (let walker = this[LRU_LIST].tail; walker !== null;) {13657 const prev = walker.prev13658 forEachStep(this, fn, walker, thisp)13659 walker = prev13660 }13661 }13662 forEach (fn, thisp) {13663 thisp = thisp || this13664 for (let walker = this[LRU_LIST].head; walker !== null;) {13665 const next = walker.next13666 forEachStep(this, fn, walker, thisp)13667 walker = next13668 }13669 }13670 keys () {13671 return this[LRU_LIST].toArray().map(k => k.key)13672 }13673 values () {13674 return this[LRU_LIST].toArray().map(k => k.value)13675 }13676 reset () {13677 if (this[DISPOSE] &&13678 this[LRU_LIST] &&13679 this[LRU_LIST].length) {13680 this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))13681 }13682 this[CACHE] = new Map() // hash of items by key13683 this[LRU_LIST] = new Yallist() // list of items in order of use recency13684 this[LENGTH] = 0 // length of items in the list13685 }13686 dump () {13687 return this[LRU_LIST].map(hit =>13688 isStale(this, hit) ? false : {13689 k: hit.key,13690 v: hit.value,13691 e: hit.now + (hit.maxAge || 0)13692 }).toArray().filter(h => h)13693 }13694 dumpLru () {13695 return this[LRU_LIST]13696 }13697 set (key, value, maxAge) {13698 maxAge = maxAge || this[MAX_AGE]13699 if (maxAge && typeof maxAge !== 'number')13700 throw new TypeError('maxAge must be a number')13701 const now = maxAge ? Date.now() : 013702 const len = this[LENGTH_CALCULATOR](value, key)13703 if (this[CACHE].has(key)) {13704 if (len > this[MAX]) {13705 del(this, this[CACHE].get(key))13706 return false13707 }13708 const node = this[CACHE].get(key)13709 const item = node.value13710 // dispose of the old one before overwriting13711 // split out into 2 ifs for better coverage tracking13712 if (this[DISPOSE]) {13713 if (!this[NO_DISPOSE_ON_SET])13714 this[DISPOSE](key, item.value)13715 }13716 item.now = now13717 item.maxAge = maxAge13718 item.value = value13719 this[LENGTH] += len - item.length13720 item.length = len13721 this.get(key)13722 trim(this)13723 return true13724 }13725 const hit = new Entry(key, value, len, now, maxAge)13726 // oversized objects fall out of cache automatically.13727 if (hit.length > this[MAX]) {13728 if (this[DISPOSE])13729 this[DISPOSE](key, value)13730 return false13731 }13732 this[LENGTH] += hit.length13733 this[LRU_LIST].unshift(hit)13734 this[CACHE].set(key, this[LRU_LIST].head)13735 trim(this)13736 return true13737 }13738 has (key) {13739 if (!this[CACHE].has(key)) return false13740 const hit = this[CACHE].get(key).value13741 return !isStale(this, hit)13742 }13743 get (key) {13744 return get(this, key, true)13745 }13746 peek (key) {13747 return get(this, key, false)13748 }13749 pop () {13750 const node = this[LRU_LIST].tail13751 if (!node)13752 return null13753 del(this, node)13754 return node.value13755 }13756 del (key) {13757 del(this, this[CACHE].get(key))13758 }13759 load (arr) {13760 // reset the cache13761 this.reset()13762 const now = Date.now()13763 // A previous serialized cache has the most recent items first13764 for (let l = arr.length - 1; l >= 0; l--) {13765 const hit = arr[l]13766 const expiresAt = hit.e || 013767 if (expiresAt === 0)13768 // the item was created without expiration in a non aged cache13769 this.set(hit.k, hit.v)13770 else {13771 const maxAge = expiresAt - now13772 // dont add already expired items13773 if (maxAge > 0) {13774 this.set(hit.k, hit.v, maxAge)13775 }13776 }13777 }13778 }13779 prune () {13780 this[CACHE].forEach((value, key) => get(this, key, false))13781 }13782}13783const get = (self, key, doUse) => {13784 const node = self[CACHE].get(key)13785 if (node) {13786 const hit = node.value13787 if (isStale(self, hit)) {13788 del(self, node)13789 if (!self[ALLOW_STALE])13790 return undefined13791 } else {13792 if (doUse) {13793 if (self[UPDATE_AGE_ON_GET])13794 node.value.now = Date.now()13795 self[LRU_LIST].unshiftNode(node)13796 }13797 }13798 return hit.value13799 }13800}13801const isStale = (self, hit) => {13802 if (!hit || (!hit.maxAge && !self[MAX_AGE]))13803 return false13804 const diff = Date.now() - hit.now13805 return hit.maxAge ? diff > hit.maxAge13806 : self[MAX_AGE] && (diff > self[MAX_AGE])13807}13808const trim = self => {13809 if (self[LENGTH] > self[MAX]) {13810 for (let walker = self[LRU_LIST].tail;13811 self[LENGTH] > self[MAX] && walker !== null;) {13812 // We know that we're about to delete this one, and also13813 // what the next least recently used key will be, so just13814 // go ahead and set it now.13815 const prev = walker.prev13816 del(self, walker)13817 walker = prev13818 }13819 }13820}13821const del = (self, node) => {13822 if (node) {13823 const hit = node.value13824 if (self[DISPOSE])13825 self[DISPOSE](hit.key, hit.value)13826 self[LENGTH] -= hit.length13827 self[CACHE].delete(hit.key)13828 self[LRU_LIST].removeNode(node)13829 }13830}13831class Entry {13832 constructor (key, value, length, now, maxAge) {13833 this.key = key13834 this.value = value13835 this.length = length13836 this.now = now13837 this.maxAge = maxAge || 013838 }13839}13840const forEachStep = (self, fn, node, thisp) => {13841 let hit = node.value13842 if (isStale(self, hit)) {13843 del(self, node)13844 if (!self[ALLOW_STALE])13845 hit = undefined13846 }13847 if (hit)13848 fn.call(thisp, hit.value, hit.key, self)13849}13850module.exports = LRUCache13851/***/ }),13852/***/ 900:13853/***/ ((module) => {13854/**13855 * Helpers.13856 */13857var s = 1000;13858var m = s * 60;13859var h = m * 60;13860var d = h * 24;13861var w = d * 7;13862var y = d * 365.25;13863/**13864 * Parse or format the given `val`.13865 *13866 * Options:13867 *13868 * - `long` verbose formatting [false]13869 *13870 * @param {String|Number} val13871 * @param {Object} [options]13872 * @throws {Error} throw an error if val is not a non-empty string or a number13873 * @return {String|Number}13874 * @api public13875 */13876module.exports = function(val, options) {13877 options = options || {};13878 var type = typeof val;13879 if (type === 'string' && val.length > 0) {13880 return parse(val);13881 } else if (type === 'number' && isFinite(val)) {13882 return options.long ? fmtLong(val) : fmtShort(val);13883 }13884 throw new Error(13885 'val is not a non-empty string or a valid number. val=' +13886 JSON.stringify(val)13887 );13888};13889/**13890 * Parse the given `str` and return milliseconds.13891 *13892 * @param {String} str13893 * @return {Number}13894 * @api private13895 */13896function parse(str) {13897 str = String(str);13898 if (str.length > 100) {13899 return;13900 }13901 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(13902 str13903 );13904 if (!match) {13905 return;13906 }13907 var n = parseFloat(match[1]);13908 var type = (match[2] || 'ms').toLowerCase();13909 switch (type) {13910 case 'years':13911 case 'year':13912 case 'yrs':13913 case 'yr':13914 case 'y':13915 return n * y;13916 case 'weeks':13917 case 'week':13918 case 'w':13919 return n * w;13920 case 'days':13921 case 'day':13922 case 'd':13923 return n * d;13924 case 'hours':13925 case 'hour':13926 case 'hrs':13927 case 'hr':13928 case 'h':13929 return n * h;13930 case 'minutes':13931 case 'minute':13932 case 'mins':13933 case 'min':13934 case 'm':13935 return n * m;13936 case 'seconds':13937 case 'second':13938 case 'secs':13939 case 'sec':13940 case 's':13941 return n * s;13942 case 'milliseconds':13943 case 'millisecond':13944 case 'msecs':13945 case 'msec':13946 case 'ms':13947 return n;13948 default:13949 return undefined;13950 }13951}13952/**13953 * Short format for `ms`.13954 *13955 * @param {Number} ms13956 * @return {String}13957 * @api private13958 */13959function fmtShort(ms) {13960 var msAbs = Math.abs(ms);13961 if (msAbs >= d) {13962 return Math.round(ms / d) + 'd';13963 }13964 if (msAbs >= h) {13965 return Math.round(ms / h) + 'h';13966 }13967 if (msAbs >= m) {13968 return Math.round(ms / m) + 'm';13969 }13970 if (msAbs >= s) {13971 return Math.round(ms / s) + 's';13972 }13973 return ms + 'ms';13974}13975/**13976 * Long format for `ms`.13977 *13978 * @param {Number} ms13979 * @return {String}13980 * @api private13981 */13982function fmtLong(ms) {13983 var msAbs = Math.abs(ms);13984 if (msAbs >= d) {13985 return plural(ms, msAbs, d, 'day');13986 }13987 if (msAbs >= h) {13988 return plural(ms, msAbs, h, 'hour');13989 }13990 if (msAbs >= m) {13991 return plural(ms, msAbs, m, 'minute');13992 }13993 if (msAbs >= s) {13994 return plural(ms, msAbs, s, 'second');13995 }13996 return ms + ' ms';13997}13998/**13999 * Pluralization helper.14000 */14001function plural(ms, msAbs, n, name) {14002 var isPlural = msAbs >= n * 1.5;14003 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');14004}14005/***/ }),14006/***/ 467:14007/***/ ((module, exports, __nccwpck_require__) => {14008"use strict";14009Object.defineProperty(exports, "__esModule", ({ value: true }));14010function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }14011var Stream = _interopDefault(__nccwpck_require__(2781));14012var http = _interopDefault(__nccwpck_require__(3685));14013var Url = _interopDefault(__nccwpck_require__(7310));14014var whatwgUrl = _interopDefault(__nccwpck_require__(8665));14015var https = _interopDefault(__nccwpck_require__(5687));14016var zlib = _interopDefault(__nccwpck_require__(9796));14017// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js14018// fix for "Readable" isn't a named export issue14019const Readable = Stream.Readable;14020const BUFFER = Symbol('buffer');14021const TYPE = Symbol('type');14022class Blob {14023 constructor() {14024 this[TYPE] = '';14025 const blobParts = arguments[0];14026 const options = arguments[1];14027 const buffers = [];14028 let size = 0;14029 if (blobParts) {14030 const a = blobParts;14031 const length = Number(a.length);14032 for (let i = 0; i < length; i++) {14033 const element = a[i];14034 let buffer;14035 if (element instanceof Buffer) {14036 buffer = element;14037 } else if (ArrayBuffer.isView(element)) {14038 buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);14039 } else if (element instanceof ArrayBuffer) {14040 buffer = Buffer.from(element);14041 } else if (element instanceof Blob) {14042 buffer = element[BUFFER];14043 } else {14044 buffer = Buffer.from(typeof element === 'string' ? element : String(element));14045 }14046 size += buffer.length;14047 buffers.push(buffer);14048 }14049 }14050 this[BUFFER] = Buffer.concat(buffers);14051 let type = options && options.type !== undefined && String(options.type).toLowerCase();14052 if (type && !/[^\u0020-\u007E]/.test(type)) {14053 this[TYPE] = type;14054 }14055 }14056 get size() {14057 return this[BUFFER].length;14058 }14059 get type() {14060 return this[TYPE];14061 }14062 text() {14063 return Promise.resolve(this[BUFFER].toString());14064 }14065 arrayBuffer() {14066 const buf = this[BUFFER];14067 const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);14068 return Promise.resolve(ab);14069 }14070 stream() {14071 const readable = new Readable();14072 readable._read = function () {};14073 readable.push(this[BUFFER]);14074 readable.push(null);14075 return readable;14076 }14077 toString() {14078 return '[object Blob]';14079 }14080 slice() {14081 const size = this.size;14082 const start = arguments[0];14083 const end = arguments[1];14084 let relativeStart, relativeEnd;14085 if (start === undefined) {14086 relativeStart = 0;14087 } else if (start < 0) {14088 relativeStart = Math.max(size + start, 0);14089 } else {14090 relativeStart = Math.min(start, size);14091 }14092 if (end === undefined) {14093 relativeEnd = size;14094 } else if (end < 0) {14095 relativeEnd = Math.max(size + end, 0);14096 } else {14097 relativeEnd = Math.min(end, size);14098 }14099 const span = Math.max(relativeEnd - relativeStart, 0);14100 const buffer = this[BUFFER];14101 const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);14102 const blob = new Blob([], { type: arguments[2] });14103 blob[BUFFER] = slicedBuffer;14104 return blob;14105 }14106}14107Object.defineProperties(Blob.prototype, {14108 size: { enumerable: true },14109 type: { enumerable: true },14110 slice: { enumerable: true }14111});14112Object.defineProperty(Blob.prototype, Symbol.toStringTag, {14113 value: 'Blob',14114 writable: false,14115 enumerable: false,14116 configurable: true14117});14118/**14119 * fetch-error.js14120 *14121 * FetchError interface for operational errors14122 */14123/**14124 * Create FetchError instance14125 *14126 * @param String message Error message for human14127 * @param String type Error type for machine14128 * @param String systemError For Node.js system error14129 * @return FetchError14130 */14131function FetchError(message, type, systemError) {14132 Error.call(this, message);14133 this.message = message;14134 this.type = type;14135 // when err.type is `system`, err.code contains system error code14136 if (systemError) {14137 this.code = this.errno = systemError.code;14138 }14139 // hide custom error implementation details from end-users14140 Error.captureStackTrace(this, this.constructor);14141}14142FetchError.prototype = Object.create(Error.prototype);14143FetchError.prototype.constructor = FetchError;14144FetchError.prototype.name = 'FetchError';14145let convert;14146try {14147 convert = (__nccwpck_require__(2877).convert);14148} catch (e) {}14149const INTERNALS = Symbol('Body internals');14150// fix an issue where "PassThrough" isn't a named export for node <1014151const PassThrough = Stream.PassThrough;14152/**14153 * Body mixin14154 *14155 * Ref: https://fetch.spec.whatwg.org/#body14156 *14157 * @param Stream body Readable stream14158 * @param Object opts Response options14159 * @return Void14160 */14161function Body(body) {14162 var _this = this;14163 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},14164 _ref$size = _ref.size;14165 let size = _ref$size === undefined ? 0 : _ref$size;14166 var _ref$timeout = _ref.timeout;14167 let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;14168 if (body == null) {14169 // body is undefined or null14170 body = null;14171 } else if (isURLSearchParams(body)) {14172 // body is a URLSearchParams14173 body = Buffer.from(body.toString());14174 } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {14175 // body is ArrayBuffer14176 body = Buffer.from(body);14177 } else if (ArrayBuffer.isView(body)) {14178 // body is ArrayBufferView14179 body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);14180 } else if (body instanceof Stream) ; else {14181 // none of the above14182 // coerce to string then buffer14183 body = Buffer.from(String(body));14184 }14185 this[INTERNALS] = {14186 body,14187 disturbed: false,14188 error: null14189 };14190 this.size = size;14191 this.timeout = timeout;14192 if (body instanceof Stream) {14193 body.on('error', function (err) {14194 const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);14195 _this[INTERNALS].error = error;14196 });14197 }14198}14199Body.prototype = {14200 get body() {14201 return this[INTERNALS].body;14202 },14203 get bodyUsed() {14204 return this[INTERNALS].disturbed;14205 },14206 /**14207 * Decode response as ArrayBuffer14208 *14209 * @return Promise14210 */14211 arrayBuffer() {14212 return consumeBody.call(this).then(function (buf) {14213 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);14214 });14215 },14216 /**14217 * Return raw response as Blob14218 *14219 * @return Promise14220 */14221 blob() {14222 let ct = this.headers && this.headers.get('content-type') || '';14223 return consumeBody.call(this).then(function (buf) {14224 return Object.assign(14225 // Prevent copying14226 new Blob([], {14227 type: ct.toLowerCase()14228 }), {14229 [BUFFER]: buf14230 });14231 });14232 },14233 /**14234 * Decode response as json14235 *14236 * @return Promise14237 */14238 json() {14239 var _this2 = this;14240 return consumeBody.call(this).then(function (buffer) {14241 try {14242 return JSON.parse(buffer.toString());14243 } catch (err) {14244 return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));14245 }14246 });14247 },14248 /**14249 * Decode response as text14250 *14251 * @return Promise14252 */14253 text() {14254 return consumeBody.call(this).then(function (buffer) {14255 return buffer.toString();14256 });14257 },14258 /**14259 * Decode response as buffer (non-spec api)14260 *14261 * @return Promise14262 */14263 buffer() {14264 return consumeBody.call(this);14265 },14266 /**14267 * Decode response as text, while automatically detecting the encoding and14268 * trying to decode to UTF-8 (non-spec api)14269 *14270 * @return Promise14271 */14272 textConverted() {14273 var _this3 = this;14274 return consumeBody.call(this).then(function (buffer) {14275 return convertBody(buffer, _this3.headers);14276 });14277 }14278};14279// In browsers, all properties are enumerable.14280Object.defineProperties(Body.prototype, {14281 body: { enumerable: true },14282 bodyUsed: { enumerable: true },14283 arrayBuffer: { enumerable: true },14284 blob: { enumerable: true },14285 json: { enumerable: true },14286 text: { enumerable: true }14287});14288Body.mixIn = function (proto) {14289 for (const name of Object.getOwnPropertyNames(Body.prototype)) {14290 // istanbul ignore else: future proof14291 if (!(name in proto)) {14292 const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);14293 Object.defineProperty(proto, name, desc);14294 }14295 }14296};14297/**14298 * Consume and convert an entire Body to a Buffer.14299 *14300 * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body14301 *14302 * @return Promise14303 */14304function consumeBody() {14305 var _this4 = this;14306 if (this[INTERNALS].disturbed) {14307 return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));14308 }14309 this[INTERNALS].disturbed = true;14310 if (this[INTERNALS].error) {14311 return Body.Promise.reject(this[INTERNALS].error);14312 }14313 let body = this.body;14314 // body is null14315 if (body === null) {14316 return Body.Promise.resolve(Buffer.alloc(0));14317 }14318 // body is blob14319 if (isBlob(body)) {14320 body = body.stream();14321 }14322 // body is buffer14323 if (Buffer.isBuffer(body)) {14324 return Body.Promise.resolve(body);14325 }14326 // istanbul ignore if: should never happen14327 if (!(body instanceof Stream)) {14328 return Body.Promise.resolve(Buffer.alloc(0));14329 }14330 // body is stream14331 // get ready to actually consume the body14332 let accum = [];14333 let accumBytes = 0;14334 let abort = false;14335 return new Body.Promise(function (resolve, reject) {14336 let resTimeout;14337 // allow timeout on slow response body14338 if (_this4.timeout) {14339 resTimeout = setTimeout(function () {14340 abort = true;14341 reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));14342 }, _this4.timeout);14343 }14344 // handle stream errors14345 body.on('error', function (err) {14346 if (err.name === 'AbortError') {14347 // if the request was aborted, reject with this Error14348 abort = true;14349 reject(err);14350 } else {14351 // other errors, such as incorrect content-encoding14352 reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));14353 }14354 });14355 body.on('data', function (chunk) {14356 if (abort || chunk === null) {14357 return;14358 }14359 if (_this4.size && accumBytes + chunk.length > _this4.size) {14360 abort = true;14361 reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));14362 return;14363 }14364 accumBytes += chunk.length;14365 accum.push(chunk);14366 });14367 body.on('end', function () {14368 if (abort) {14369 return;14370 }14371 clearTimeout(resTimeout);14372 try {14373 resolve(Buffer.concat(accum, accumBytes));14374 } catch (err) {14375 // handle streams that have accumulated too much data (issue #414)14376 reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));14377 }14378 });14379 });14380}14381/**14382 * Detect buffer encoding and convert to target encoding14383 * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding14384 *14385 * @param Buffer buffer Incoming buffer14386 * @param String encoding Target encoding14387 * @return String14388 */14389function convertBody(buffer, headers) {14390 if (typeof convert !== 'function') {14391 throw new Error('The package `encoding` must be installed to use the textConverted() function');14392 }14393 const ct = headers.get('content-type');14394 let charset = 'utf-8';14395 let res, str;14396 // header14397 if (ct) {14398 res = /charset=([^;]*)/i.exec(ct);14399 }14400 // no charset in content type, peek at response body for at most 1024 bytes14401 str = buffer.slice(0, 1024).toString();14402 // html514403 if (!res && str) {14404 res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);14405 }14406 // html414407 if (!res && str) {14408 res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);14409 if (!res) {14410 res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);14411 if (res) {14412 res.pop(); // drop last quote14413 }14414 }14415 if (res) {14416 res = /charset=(.*)/i.exec(res.pop());14417 }14418 }14419 // xml14420 if (!res && str) {14421 res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);14422 }14423 // found charset14424 if (res) {14425 charset = res.pop();14426 // prevent decode issues when sites use incorrect encoding14427 // ref: https://hsivonen.fi/encoding-menu/14428 if (charset === 'gb2312' || charset === 'gbk') {14429 charset = 'gb18030';14430 }14431 }14432 // turn raw buffers into a single utf-8 buffer14433 return convert(buffer, 'UTF-8', charset).toString();14434}14435/**14436 * Detect a URLSearchParams object14437 * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-30759814314438 *14439 * @param Object obj Object to detect by type or brand14440 * @return String14441 */14442function isURLSearchParams(obj) {14443 // Duck-typing as a necessary condition.14444 if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {14445 return false;14446 }14447 // Brand-checking and more duck-typing as optional condition.14448 return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';14449}14450/**14451 * Check if `obj` is a W3C `Blob` object (which `File` inherits from)14452 * @param {*} obj14453 * @return {boolean}14454 */14455function isBlob(obj) {14456 return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);14457}14458/**14459 * Clone body given Res/Req instance14460 *14461 * @param Mixed instance Response or Request instance14462 * @return Mixed14463 */14464function clone(instance) {14465 let p1, p2;14466 let body = instance.body;14467 // don't allow cloning a used body14468 if (instance.bodyUsed) {14469 throw new Error('cannot clone body after it is used');14470 }14471 // check that body is a stream and not form-data object14472 // note: we can't clone the form-data object without having it as a dependency14473 if (body instanceof Stream && typeof body.getBoundary !== 'function') {14474 // tee instance body14475 p1 = new PassThrough();14476 p2 = new PassThrough();14477 body.pipe(p1);14478 body.pipe(p2);14479 // set instance body to teed body and return the other teed body14480 instance[INTERNALS].body = p1;14481 body = p2;14482 }14483 return body;14484}14485/**14486 * Performs the operation "extract a `Content-Type` value from |object|" as14487 * specified in the specification:14488 * https://fetch.spec.whatwg.org/#concept-bodyinit-extract14489 *14490 * This function assumes that instance.body is present.14491 *14492 * @param Mixed instance Any options.body input14493 */14494function extractContentType(body) {14495 if (body === null) {14496 // body is null14497 return null;14498 } else if (typeof body === 'string') {14499 // body is string14500 return 'text/plain;charset=UTF-8';14501 } else if (isURLSearchParams(body)) {14502 // body is a URLSearchParams14503 return 'application/x-www-form-urlencoded;charset=UTF-8';14504 } else if (isBlob(body)) {14505 // body is blob14506 return body.type || null;14507 } else if (Buffer.isBuffer(body)) {14508 // body is buffer14509 return null;14510 } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {14511 // body is ArrayBuffer14512 return null;14513 } else if (ArrayBuffer.isView(body)) {14514 // body is ArrayBufferView14515 return null;14516 } else if (typeof body.getBoundary === 'function') {14517 // detect form data input from form-data module14518 return `multipart/form-data;boundary=${body.getBoundary()}`;14519 } else if (body instanceof Stream) {14520 // body is stream14521 // can't really do much about this14522 return null;14523 } else {14524 // Body constructor defaults other things to string14525 return 'text/plain;charset=UTF-8';14526 }14527}14528/**14529 * The Fetch Standard treats this as if "total bytes" is a property on the body.14530 * For us, we have to explicitly get it with a function.14531 *14532 * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes14533 *14534 * @param Body instance Instance of Body14535 * @return Number? Number of bytes, or null if not possible14536 */14537function getTotalBytes(instance) {14538 const body = instance.body;14539 if (body === null) {14540 // body is null14541 return 0;14542 } else if (isBlob(body)) {14543 return body.size;14544 } else if (Buffer.isBuffer(body)) {14545 // body is buffer14546 return body.length;14547 } else if (body && typeof body.getLengthSync === 'function') {14548 // detect form data input from form-data module14549 if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x14550 body.hasKnownLength && body.hasKnownLength()) {14551 // 2.x14552 return body.getLengthSync();14553 }14554 return null;14555 } else {14556 // body is stream14557 return null;14558 }14559}14560/**14561 * Write a Body to a Node.js WritableStream (e.g. http.Request) object.14562 *14563 * @param Body instance Instance of Body14564 * @return Void14565 */14566function writeToStream(dest, instance) {14567 const body = instance.body;14568 if (body === null) {14569 // body is null14570 dest.end();14571 } else if (isBlob(body)) {14572 body.stream().pipe(dest);14573 } else if (Buffer.isBuffer(body)) {14574 // body is buffer14575 dest.write(body);14576 dest.end();14577 } else {14578 // body is stream14579 body.pipe(dest);14580 }14581}14582// expose Promise14583Body.Promise = global.Promise;14584/**14585 * headers.js14586 *14587 * Headers class offers convenient helpers14588 */14589const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;14590const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;14591function validateName(name) {14592 name = `${name}`;14593 if (invalidTokenRegex.test(name) || name === '') {14594 throw new TypeError(`${name} is not a legal HTTP header name`);14595 }14596}14597function validateValue(value) {14598 value = `${value}`;14599 if (invalidHeaderCharRegex.test(value)) {14600 throw new TypeError(`${value} is not a legal HTTP header value`);14601 }14602}14603/**14604 * Find the key in the map object given a header name.14605 *14606 * Returns undefined if not found.14607 *14608 * @param String name Header name14609 * @return String|Undefined14610 */14611function find(map, name) {14612 name = name.toLowerCase();14613 for (const key in map) {14614 if (key.toLowerCase() === name) {14615 return key;14616 }14617 }14618 return undefined;14619}14620const MAP = Symbol('map');14621class Headers {14622 /**14623 * Headers class14624 *14625 * @param Object headers Response headers14626 * @return Void14627 */14628 constructor() {14629 let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;14630 this[MAP] = Object.create(null);14631 if (init instanceof Headers) {14632 const rawHeaders = init.raw();14633 const headerNames = Object.keys(rawHeaders);14634 for (const headerName of headerNames) {14635 for (const value of rawHeaders[headerName]) {14636 this.append(headerName, value);14637 }14638 }14639 return;14640 }14641 // We don't worry about converting prop to ByteString here as append()14642 // will handle it.14643 if (init == null) ; else if (typeof init === 'object') {14644 const method = init[Symbol.iterator];14645 if (method != null) {14646 if (typeof method !== 'function') {14647 throw new TypeError('Header pairs must be iterable');14648 }14649 // sequence<sequence<ByteString>>14650 // Note: per spec we have to first exhaust the lists then process them14651 const pairs = [];14652 for (const pair of init) {14653 if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {14654 throw new TypeError('Each header pair must be iterable');14655 }14656 pairs.push(Array.from(pair));14657 }14658 for (const pair of pairs) {14659 if (pair.length !== 2) {14660 throw new TypeError('Each header pair must be a name/value tuple');14661 }14662 this.append(pair[0], pair[1]);14663 }14664 } else {14665 // record<ByteString, ByteString>14666 for (const key of Object.keys(init)) {14667 const value = init[key];14668 this.append(key, value);14669 }14670 }14671 } else {14672 throw new TypeError('Provided initializer must be an object');14673 }14674 }14675 /**14676 * Return combined header value given name14677 *14678 * @param String name Header name14679 * @return Mixed14680 */14681 get(name) {14682 name = `${name}`;14683 validateName(name);14684 const key = find(this[MAP], name);14685 if (key === undefined) {14686 return null;14687 }14688 return this[MAP][key].join(', ');14689 }14690 /**14691 * Iterate over all headers14692 *14693 * @param Function callback Executed for each item with parameters (value, name, thisArg)14694 * @param Boolean thisArg `this` context for callback function14695 * @return Void14696 */14697 forEach(callback) {14698 let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;14699 let pairs = getHeaders(this);14700 let i = 0;14701 while (i < pairs.length) {14702 var _pairs$i = pairs[i];14703 const name = _pairs$i[0],14704 value = _pairs$i[1];14705 callback.call(thisArg, value, name, this);14706 pairs = getHeaders(this);14707 i++;14708 }14709 }14710 /**14711 * Overwrite header values given name14712 *14713 * @param String name Header name14714 * @param String value Header value14715 * @return Void14716 */14717 set(name, value) {14718 name = `${name}`;14719 value = `${value}`;14720 validateName(name);14721 validateValue(value);14722 const key = find(this[MAP], name);14723 this[MAP][key !== undefined ? key : name] = [value];14724 }14725 /**14726 * Append a value onto existing header14727 *14728 * @param String name Header name14729 * @param String value Header value14730 * @return Void14731 */14732 append(name, value) {14733 name = `${name}`;14734 value = `${value}`;14735 validateName(name);14736 validateValue(value);14737 const key = find(this[MAP], name);14738 if (key !== undefined) {14739 this[MAP][key].push(value);14740 } else {14741 this[MAP][name] = [value];14742 }14743 }14744 /**14745 * Check for header name existence14746 *14747 * @param String name Header name14748 * @return Boolean14749 */14750 has(name) {14751 name = `${name}`;14752 validateName(name);14753 return find(this[MAP], name) !== undefined;14754 }14755 /**14756 * Delete all header values given name14757 *14758 * @param String name Header name14759 * @return Void14760 */14761 delete(name) {14762 name = `${name}`;14763 validateName(name);14764 const key = find(this[MAP], name);14765 if (key !== undefined) {14766 delete this[MAP][key];14767 }14768 }14769 /**14770 * Return raw headers (non-spec api)14771 *14772 * @return Object14773 */14774 raw() {14775 return this[MAP];14776 }14777 /**14778 * Get an iterator on keys.14779 *14780 * @return Iterator14781 */14782 keys() {14783 return createHeadersIterator(this, 'key');14784 }14785 /**14786 * Get an iterator on values.14787 *14788 * @return Iterator14789 */14790 values() {14791 return createHeadersIterator(this, 'value');14792 }14793 /**14794 * Get an iterator on entries.14795 *14796 * This is the default iterator of the Headers object.14797 *14798 * @return Iterator14799 */14800 [Symbol.iterator]() {14801 return createHeadersIterator(this, 'key+value');14802 }14803}14804Headers.prototype.entries = Headers.prototype[Symbol.iterator];14805Object.defineProperty(Headers.prototype, Symbol.toStringTag, {14806 value: 'Headers',14807 writable: false,14808 enumerable: false,14809 configurable: true14810});14811Object.defineProperties(Headers.prototype, {14812 get: { enumerable: true },14813 forEach: { enumerable: true },14814 set: { enumerable: true },14815 append: { enumerable: true },14816 has: { enumerable: true },14817 delete: { enumerable: true },14818 keys: { enumerable: true },14819 values: { enumerable: true },14820 entries: { enumerable: true }14821});14822function getHeaders(headers) {14823 let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';14824 const keys = Object.keys(headers[MAP]).sort();14825 return keys.map(kind === 'key' ? function (k) {14826 return k.toLowerCase();14827 } : kind === 'value' ? function (k) {14828 return headers[MAP][k].join(', ');14829 } : function (k) {14830 return [k.toLowerCase(), headers[MAP][k].join(', ')];14831 });14832}14833const INTERNAL = Symbol('internal');14834function createHeadersIterator(target, kind) {14835 const iterator = Object.create(HeadersIteratorPrototype);14836 iterator[INTERNAL] = {14837 target,14838 kind,14839 index: 014840 };14841 return iterator;14842}14843const HeadersIteratorPrototype = Object.setPrototypeOf({14844 next() {14845 // istanbul ignore if14846 if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {14847 throw new TypeError('Value of `this` is not a HeadersIterator');14848 }14849 var _INTERNAL = this[INTERNAL];14850 const target = _INTERNAL.target,14851 kind = _INTERNAL.kind,14852 index = _INTERNAL.index;14853 const values = getHeaders(target, kind);14854 const len = values.length;14855 if (index >= len) {14856 return {14857 value: undefined,14858 done: true14859 };14860 }14861 this[INTERNAL].index = index + 1;14862 return {14863 value: values[index],14864 done: false14865 };14866 }14867}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));14868Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {14869 value: 'HeadersIterator',14870 writable: false,14871 enumerable: false,14872 configurable: true14873});14874/**14875 * Export the Headers object in a form that Node.js can consume.14876 *14877 * @param Headers headers14878 * @return Object14879 */14880function exportNodeCompatibleHeaders(headers) {14881 const obj = Object.assign({ __proto__: null }, headers[MAP]);14882 // http.request() only supports string as Host header. This hack makes14883 // specifying custom Host header possible.14884 const hostHeaderKey = find(headers[MAP], 'Host');14885 if (hostHeaderKey !== undefined) {14886 obj[hostHeaderKey] = obj[hostHeaderKey][0];14887 }14888 return obj;14889}14890/**14891 * Create a Headers object from an object of headers, ignoring those that do14892 * not conform to HTTP grammar productions.14893 *14894 * @param Object obj Object of headers14895 * @return Headers14896 */14897function createHeadersLenient(obj) {14898 const headers = new Headers();14899 for (const name of Object.keys(obj)) {14900 if (invalidTokenRegex.test(name)) {14901 continue;14902 }14903 if (Array.isArray(obj[name])) {14904 for (const val of obj[name]) {14905 if (invalidHeaderCharRegex.test(val)) {14906 continue;14907 }14908 if (headers[MAP][name] === undefined) {14909 headers[MAP][name] = [val];14910 } else {14911 headers[MAP][name].push(val);14912 }14913 }14914 } else if (!invalidHeaderCharRegex.test(obj[name])) {14915 headers[MAP][name] = [obj[name]];14916 }14917 }14918 return headers;14919}14920const INTERNALS$1 = Symbol('Response internals');14921// fix an issue where "STATUS_CODES" aren't a named export for node <1014922const STATUS_CODES = http.STATUS_CODES;14923/**14924 * Response class14925 *14926 * @param Stream body Readable stream14927 * @param Object opts Response options14928 * @return Void14929 */14930class Response {14931 constructor() {14932 let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;14933 let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};14934 Body.call(this, body, opts);14935 const status = opts.status || 200;14936 const headers = new Headers(opts.headers);14937 if (body != null && !headers.has('Content-Type')) {14938 const contentType = extractContentType(body);14939 if (contentType) {14940 headers.append('Content-Type', contentType);14941 }14942 }14943 this[INTERNALS$1] = {14944 url: opts.url,14945 status,14946 statusText: opts.statusText || STATUS_CODES[status],14947 headers,14948 counter: opts.counter14949 };14950 }14951 get url() {14952 return this[INTERNALS$1].url || '';14953 }14954 get status() {14955 return this[INTERNALS$1].status;14956 }14957 /**14958 * Convenience property representing if the request ended normally14959 */14960 get ok() {14961 return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;14962 }14963 get redirected() {14964 return this[INTERNALS$1].counter > 0;14965 }14966 get statusText() {14967 return this[INTERNALS$1].statusText;14968 }14969 get headers() {14970 return this[INTERNALS$1].headers;14971 }14972 /**14973 * Clone this response14974 *14975 * @return Response14976 */14977 clone() {14978 return new Response(clone(this), {14979 url: this.url,14980 status: this.status,14981 statusText: this.statusText,14982 headers: this.headers,14983 ok: this.ok,14984 redirected: this.redirected14985 });14986 }14987}14988Body.mixIn(Response.prototype);14989Object.defineProperties(Response.prototype, {14990 url: { enumerable: true },14991 status: { enumerable: true },14992 ok: { enumerable: true },14993 redirected: { enumerable: true },14994 statusText: { enumerable: true },14995 headers: { enumerable: true },14996 clone: { enumerable: true }14997});14998Object.defineProperty(Response.prototype, Symbol.toStringTag, {14999 value: 'Response',15000 writable: false,15001 enumerable: false,15002 configurable: true15003});15004const INTERNALS$2 = Symbol('Request internals');15005const URL = Url.URL || whatwgUrl.URL;15006// fix an issue where "format", "parse" aren't a named export for node <1015007const parse_url = Url.parse;15008const format_url = Url.format;15009/**15010 * Wrapper around `new URL` to handle arbitrary URLs15011 *15012 * @param {string} urlStr15013 * @return {void}15014 */15015function parseURL(urlStr) {15016 /*15017 Check whether the URL is absolute or not15018 Scheme: https://tools.ietf.org/html/rfc3986#section-3.115019 Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.315020 */15021 if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {15022 urlStr = new URL(urlStr).toString();15023 }15024 // Fallback to old implementation for arbitrary URLs15025 return parse_url(urlStr);15026}15027const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;15028/**15029 * Check if a value is an instance of Request.15030 *15031 * @param Mixed input15032 * @return Boolean15033 */15034function isRequest(input) {15035 return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';15036}15037function isAbortSignal(signal) {15038 const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);15039 return !!(proto && proto.constructor.name === 'AbortSignal');15040}15041/**15042 * Request class15043 *15044 * @param Mixed input Url or Request instance15045 * @param Object init Custom options15046 * @return Void15047 */15048class Request {15049 constructor(input) {15050 let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};15051 let parsedURL;15052 // normalize input15053 if (!isRequest(input)) {15054 if (input && input.href) {15055 // in order to support Node.js' Url objects; though WHATWG's URL objects15056 // will fall into this branch also (since their `toString()` will return15057 // `href` property anyway)15058 parsedURL = parseURL(input.href);15059 } else {15060 // coerce input to a string before attempting to parse15061 parsedURL = parseURL(`${input}`);15062 }15063 input = {};15064 } else {15065 parsedURL = parseURL(input.url);15066 }15067 let method = init.method || input.method || 'GET';15068 method = method.toUpperCase();15069 if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {15070 throw new TypeError('Request with GET/HEAD method cannot have body');15071 }15072 let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;15073 Body.call(this, inputBody, {15074 timeout: init.timeout || input.timeout || 0,15075 size: init.size || input.size || 015076 });15077 const headers = new Headers(init.headers || input.headers || {});15078 if (inputBody != null && !headers.has('Content-Type')) {15079 const contentType = extractContentType(inputBody);15080 if (contentType) {15081 headers.append('Content-Type', contentType);15082 }15083 }15084 let signal = isRequest(input) ? input.signal : null;15085 if ('signal' in init) signal = init.signal;15086 if (signal != null && !isAbortSignal(signal)) {15087 throw new TypeError('Expected signal to be an instanceof AbortSignal');15088 }15089 this[INTERNALS$2] = {15090 method,15091 redirect: init.redirect || input.redirect || 'follow',15092 headers,15093 parsedURL,15094 signal15095 };15096 // node-fetch-only options15097 this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;15098 this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;15099 this.counter = init.counter || input.counter || 0;15100 this.agent = init.agent || input.agent;15101 }15102 get method() {15103 return this[INTERNALS$2].method;15104 }15105 get url() {15106 return format_url(this[INTERNALS$2].parsedURL);15107 }15108 get headers() {15109 return this[INTERNALS$2].headers;15110 }15111 get redirect() {15112 return this[INTERNALS$2].redirect;15113 }15114 get signal() {15115 return this[INTERNALS$2].signal;15116 }15117 /**15118 * Clone this request15119 *15120 * @return Request15121 */15122 clone() {15123 return new Request(this);15124 }15125}15126Body.mixIn(Request.prototype);15127Object.defineProperty(Request.prototype, Symbol.toStringTag, {15128 value: 'Request',15129 writable: false,15130 enumerable: false,15131 configurable: true15132});15133Object.defineProperties(Request.prototype, {15134 method: { enumerable: true },15135 url: { enumerable: true },15136 headers: { enumerable: true },15137 redirect: { enumerable: true },15138 clone: { enumerable: true },15139 signal: { enumerable: true }15140});15141/**15142 * Convert a Request to Node.js http request options.15143 *15144 * @param Request A Request instance15145 * @return Object The options object to be passed to http.request15146 */15147function getNodeRequestOptions(request) {15148 const parsedURL = request[INTERNALS$2].parsedURL;15149 const headers = new Headers(request[INTERNALS$2].headers);15150 // fetch step 1.315151 if (!headers.has('Accept')) {15152 headers.set('Accept', '*/*');15153 }15154 // Basic fetch15155 if (!parsedURL.protocol || !parsedURL.hostname) {15156 throw new TypeError('Only absolute URLs are supported');15157 }15158 if (!/^https?:$/.test(parsedURL.protocol)) {15159 throw new TypeError('Only HTTP(S) protocols are supported');15160 }15161 if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {15162 throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');15163 }15164 // HTTP-network-or-cache fetch steps 2.4-2.715165 let contentLengthValue = null;15166 if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {15167 contentLengthValue = '0';15168 }15169 if (request.body != null) {15170 const totalBytes = getTotalBytes(request);15171 if (typeof totalBytes === 'number') {15172 contentLengthValue = String(totalBytes);15173 }15174 }15175 if (contentLengthValue) {15176 headers.set('Content-Length', contentLengthValue);15177 }15178 // HTTP-network-or-cache fetch step 2.1115179 if (!headers.has('User-Agent')) {15180 headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');15181 }15182 // HTTP-network-or-cache fetch step 2.1515183 if (request.compress && !headers.has('Accept-Encoding')) {15184 headers.set('Accept-Encoding', 'gzip,deflate');15185 }15186 let agent = request.agent;15187 if (typeof agent === 'function') {15188 agent = agent(parsedURL);15189 }15190 if (!headers.has('Connection') && !agent) {15191 headers.set('Connection', 'close');15192 }15193 // HTTP-network fetch step 4.215194 // chunked encoding is handled by Node.js15195 return Object.assign({}, parsedURL, {15196 method: request.method,15197 headers: exportNodeCompatibleHeaders(headers),15198 agent15199 });15200}15201/**15202 * abort-error.js15203 *15204 * AbortError interface for cancelled requests15205 */15206/**15207 * Create AbortError instance15208 *15209 * @param String message Error message for human15210 * @return AbortError15211 */15212function AbortError(message) {15213 Error.call(this, message);15214 this.type = 'aborted';15215 this.message = message;15216 // hide custom error implementation details from end-users15217 Error.captureStackTrace(this, this.constructor);15218}15219AbortError.prototype = Object.create(Error.prototype);15220AbortError.prototype.constructor = AbortError;15221AbortError.prototype.name = 'AbortError';15222const URL$1 = Url.URL || whatwgUrl.URL;15223// fix an issue where "PassThrough", "resolve" aren't a named export for node <1015224const PassThrough$1 = Stream.PassThrough;15225const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {15226 const orig = new URL$1(original).hostname;15227 const dest = new URL$1(destination).hostname;15228 return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);15229};15230/**15231 * Fetch function15232 *15233 * @param Mixed url Absolute url or Request instance15234 * @param Object opts Fetch options15235 * @return Promise15236 */15237function fetch(url, opts) {15238 // allow custom promise15239 if (!fetch.Promise) {15240 throw new Error('native promise missing, set fetch.Promise to your favorite alternative');15241 }15242 Body.Promise = fetch.Promise;15243 // wrap http.request into fetch15244 return new fetch.Promise(function (resolve, reject) {15245 // build request object15246 const request = new Request(url, opts);15247 const options = getNodeRequestOptions(request);15248 const send = (options.protocol === 'https:' ? https : http).request;15249 const signal = request.signal;15250 let response = null;15251 const abort = function abort() {15252 let error = new AbortError('The user aborted a request.');15253 reject(error);15254 if (request.body && request.body instanceof Stream.Readable) {15255 request.body.destroy(error);15256 }15257 if (!response || !response.body) return;15258 response.body.emit('error', error);15259 };15260 if (signal && signal.aborted) {15261 abort();15262 return;15263 }15264 const abortAndFinalize = function abortAndFinalize() {15265 abort();15266 finalize();15267 };15268 // send request15269 const req = send(options);15270 let reqTimeout;15271 if (signal) {15272 signal.addEventListener('abort', abortAndFinalize);15273 }15274 function finalize() {15275 req.abort();15276 if (signal) signal.removeEventListener('abort', abortAndFinalize);15277 clearTimeout(reqTimeout);15278 }15279 if (request.timeout) {15280 req.once('socket', function (socket) {15281 reqTimeout = setTimeout(function () {15282 reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));15283 finalize();15284 }, request.timeout);15285 });15286 }15287 req.on('error', function (err) {15288 reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));15289 finalize();15290 });15291 req.on('response', function (res) {15292 clearTimeout(reqTimeout);15293 const headers = createHeadersLenient(res.headers);15294 // HTTP fetch step 515295 if (fetch.isRedirect(res.statusCode)) {15296 // HTTP fetch step 5.215297 const location = headers.get('Location');15298 // HTTP fetch step 5.315299 let locationURL = null;15300 try {15301 locationURL = location === null ? null : new URL$1(location, request.url).toString();15302 } catch (err) {15303 // error here can only be invalid URL in Location: header15304 // do not throw when options.redirect == manual15305 // let the user extract the errorneous redirect URL15306 if (request.redirect !== 'manual') {15307 reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));15308 finalize();15309 return;15310 }15311 }15312 // HTTP fetch step 5.515313 switch (request.redirect) {15314 case 'error':15315 reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));15316 finalize();15317 return;15318 case 'manual':15319 // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.15320 if (locationURL !== null) {15321 // handle corrupted header15322 try {15323 headers.set('Location', locationURL);15324 } catch (err) {15325 // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request15326 reject(err);15327 }15328 }15329 break;15330 case 'follow':15331 // HTTP-redirect fetch step 215332 if (locationURL === null) {15333 break;15334 }15335 // HTTP-redirect fetch step 515336 if (request.counter >= request.follow) {15337 reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));15338 finalize();15339 return;15340 }15341 // HTTP-redirect fetch step 6 (counter increment)15342 // Create a new Request object.15343 const requestOpts = {15344 headers: new Headers(request.headers),15345 follow: request.follow,15346 counter: request.counter + 1,15347 agent: request.agent,15348 compress: request.compress,15349 method: request.method,15350 body: request.body,15351 signal: request.signal,15352 timeout: request.timeout,15353 size: request.size15354 };15355 if (!isDomainOrSubdomain(request.url, locationURL)) {15356 for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {15357 requestOpts.headers.delete(name);15358 }15359 }15360 // HTTP-redirect fetch step 915361 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {15362 reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));15363 finalize();15364 return;15365 }15366 // HTTP-redirect fetch step 1115367 if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {15368 requestOpts.method = 'GET';15369 requestOpts.body = undefined;15370 requestOpts.headers.delete('content-length');15371 }15372 // HTTP-redirect fetch step 1515373 resolve(fetch(new Request(locationURL, requestOpts)));15374 finalize();15375 return;15376 }15377 }15378 // prepare response15379 res.once('end', function () {15380 if (signal) signal.removeEventListener('abort', abortAndFinalize);15381 });15382 let body = res.pipe(new PassThrough$1());15383 const response_options = {15384 url: request.url,15385 status: res.statusCode,15386 statusText: res.statusMessage,15387 headers: headers,15388 size: request.size,15389 timeout: request.timeout,15390 counter: request.counter15391 };15392 // HTTP-network fetch step 12.1.1.315393 const codings = headers.get('Content-Encoding');15394 // HTTP-network fetch step 12.1.1.4: handle content codings15395 // in following scenarios we ignore compression support15396 // 1. compression support is disabled15397 // 2. HEAD request15398 // 3. no Content-Encoding header15399 // 4. no content response (204)15400 // 5. content not modified response (304)15401 if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {15402 response = new Response(body, response_options);15403 resolve(response);15404 return;15405 }15406 // For Node v6+15407 // Be less strict when decoding compressed responses, since sometimes15408 // servers send slightly invalid responses that are still accepted15409 // by common browsers.15410 // Always using Z_SYNC_FLUSH is what cURL does.15411 const zlibOptions = {15412 flush: zlib.Z_SYNC_FLUSH,15413 finishFlush: zlib.Z_SYNC_FLUSH15414 };15415 // for gzip15416 if (codings == 'gzip' || codings == 'x-gzip') {15417 body = body.pipe(zlib.createGunzip(zlibOptions));15418 response = new Response(body, response_options);15419 resolve(response);15420 return;15421 }15422 // for deflate15423 if (codings == 'deflate' || codings == 'x-deflate') {15424 // handle the infamous raw deflate response from old servers15425 // a hack for old IIS and Apache servers15426 const raw = res.pipe(new PassThrough$1());15427 raw.once('data', function (chunk) {15428 // see http://stackoverflow.com/questions/3751982815429 if ((chunk[0] & 0x0F) === 0x08) {15430 body = body.pipe(zlib.createInflate());15431 } else {15432 body = body.pipe(zlib.createInflateRaw());15433 }15434 response = new Response(body, response_options);15435 resolve(response);15436 });15437 return;15438 }15439 // for br15440 if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {15441 body = body.pipe(zlib.createBrotliDecompress());15442 response = new Response(body, response_options);15443 resolve(response);15444 return;15445 }15446 // otherwise, use response as-is15447 response = new Response(body, response_options);15448 resolve(response);15449 });15450 writeToStream(req, request);15451 });15452}15453/**15454 * Redirect code matching15455 *15456 * @param Number code Status code15457 * @return Boolean15458 */15459fetch.isRedirect = function (code) {15460 return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;15461};15462// expose Promise15463fetch.Promise = global.Promise;15464module.exports = exports = fetch;15465Object.defineProperty(exports, "__esModule", ({ value: true }));15466exports["default"] = exports;15467exports.Headers = Headers;15468exports.Request = Request;15469exports.Response = Response;15470exports.FetchError = FetchError;15471/***/ }),15472/***/ 7994:15473/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {15474/**15475 * Advanced Encryption Standard (AES) implementation.15476 *15477 * This implementation is based on the public domain library 'jscrypto' which15478 * was written by:15479 *15480 * Emily Stark (estark@stanford.edu)15481 * Mike Hamburg (mhamburg@stanford.edu)15482 * Dan Boneh (dabo@cs.stanford.edu)15483 *15484 * Parts of this code are based on the OpenSSL implementation of AES:15485 * http://www.openssl.org15486 *15487 * @author Dave Longley15488 *15489 * Copyright (c) 2010-2014 Digital Bazaar, Inc.15490 */15491var forge = __nccwpck_require__(9177);15492__nccwpck_require__(7088);15493__nccwpck_require__(873);15494__nccwpck_require__(8339);15495/* AES API */15496module.exports = forge.aes = forge.aes || {};15497/**15498 * Deprecated. Instead, use:15499 *15500 * var cipher = forge.cipher.createCipher('AES-<mode>', key);15501 * cipher.start({iv: iv});15502 *15503 * Creates an AES cipher object to encrypt data using the given symmetric key.15504 * The output will be stored in the 'output' member of the returned cipher.15505 *15506 * The key and iv may be given as a string of bytes, an array of bytes,15507 * a byte buffer, or an array of 32-bit words.15508 *15509 * @param key the symmetric key to use.15510 * @param iv the initialization vector to use.15511 * @param output the buffer to write to, null to create one.15512 * @param mode the cipher mode to use (default: 'CBC').15513 *15514 * @return the cipher.15515 */15516forge.aes.startEncrypting = function(key, iv, output, mode) {15517 var cipher = _createCipher({15518 key: key,15519 output: output,15520 decrypt: false,15521 mode: mode15522 });15523 cipher.start(iv);15524 return cipher;15525};15526/**15527 * Deprecated. Instead, use:15528 *15529 * var cipher = forge.cipher.createCipher('AES-<mode>', key);15530 *15531 * Creates an AES cipher object to encrypt data using the given symmetric key.15532 *15533 * The key may be given as a string of bytes, an array of bytes, a15534 * byte buffer, or an array of 32-bit words.15535 *15536 * @param key the symmetric key to use.15537 * @param mode the cipher mode to use (default: 'CBC').15538 *15539 * @return the cipher.15540 */15541forge.aes.createEncryptionCipher = function(key, mode) {15542 return _createCipher({15543 key: key,15544 output: null,15545 decrypt: false,15546 mode: mode15547 });15548};15549/**15550 * Deprecated. Instead, use:15551 *15552 * var decipher = forge.cipher.createDecipher('AES-<mode>', key);15553 * decipher.start({iv: iv});15554 *15555 * Creates an AES cipher object to decrypt data using the given symmetric key.15556 * The output will be stored in the 'output' member of the returned cipher.15557 *15558 * The key and iv may be given as a string of bytes, an array of bytes,15559 * a byte buffer, or an array of 32-bit words.15560 *15561 * @param key the symmetric key to use.15562 * @param iv the initialization vector to use.15563 * @param output the buffer to write to, null to create one.15564 * @param mode the cipher mode to use (default: 'CBC').15565 *15566 * @return the cipher.15567 */15568forge.aes.startDecrypting = function(key, iv, output, mode) {15569 var cipher = _createCipher({15570 key: key,15571 output: output,15572 decrypt: true,15573 mode: mode15574 });15575 cipher.start(iv);15576 return cipher;15577};15578/**15579 * Deprecated. Instead, use:15580 *15581 * var decipher = forge.cipher.createDecipher('AES-<mode>', key);15582 *15583 * Creates an AES cipher object to decrypt data using the given symmetric key.15584 *15585 * The key may be given as a string of bytes, an array of bytes, a15586 * byte buffer, or an array of 32-bit words.15587 *15588 * @param key the symmetric key to use.15589 * @param mode the cipher mode to use (default: 'CBC').15590 *15591 * @return the cipher.15592 */15593forge.aes.createDecryptionCipher = function(key, mode) {15594 return _createCipher({15595 key: key,15596 output: null,15597 decrypt: true,15598 mode: mode15599 });15600};15601/**15602 * Creates a new AES cipher algorithm object.15603 *15604 * @param name the name of the algorithm.15605 * @param mode the mode factory function.15606 *15607 * @return the AES algorithm object.15608 */15609forge.aes.Algorithm = function(name, mode) {15610 if(!init) {15611 initialize();15612 }15613 var self = this;15614 self.name = name;15615 self.mode = new mode({15616 blockSize: 16,15617 cipher: {15618 encrypt: function(inBlock, outBlock) {15619 return _updateBlock(self._w, inBlock, outBlock, false);15620 },15621 decrypt: function(inBlock, outBlock) {15622 return _updateBlock(self._w, inBlock, outBlock, true);15623 }15624 }15625 });15626 self._init = false;15627};15628/**15629 * Initializes this AES algorithm by expanding its key.15630 *15631 * @param options the options to use.15632 * key the key to use with this algorithm.15633 * decrypt true if the algorithm should be initialized for decryption,15634 * false for encryption.15635 */15636forge.aes.Algorithm.prototype.initialize = function(options) {15637 if(this._init) {15638 return;15639 }15640 var key = options.key;15641 var tmp;15642 /* Note: The key may be a string of bytes, an array of bytes, a byte15643 buffer, or an array of 32-bit integers. If the key is in bytes, then15644 it must be 16, 24, or 32 bytes in length. If it is in 32-bit15645 integers, it must be 4, 6, or 8 integers long. */15646 if(typeof key === 'string' &&15647 (key.length === 16 || key.length === 24 || key.length === 32)) {15648 // convert key string into byte buffer15649 key = forge.util.createBuffer(key);15650 } else if(forge.util.isArray(key) &&15651 (key.length === 16 || key.length === 24 || key.length === 32)) {15652 // convert key integer array into byte buffer15653 tmp = key;15654 key = forge.util.createBuffer();15655 for(var i = 0; i < tmp.length; ++i) {15656 key.putByte(tmp[i]);15657 }15658 }15659 // convert key byte buffer into 32-bit integer array15660 if(!forge.util.isArray(key)) {15661 tmp = key;15662 key = [];15663 // key lengths of 16, 24, 32 bytes allowed15664 var len = tmp.length();15665 if(len === 16 || len === 24 || len === 32) {15666 len = len >>> 2;15667 for(var i = 0; i < len; ++i) {15668 key.push(tmp.getInt32());15669 }15670 }15671 }15672 // key must be an array of 32-bit integers by now15673 if(!forge.util.isArray(key) ||15674 !(key.length === 4 || key.length === 6 || key.length === 8)) {15675 throw new Error('Invalid key parameter.');15676 }15677 // encryption operation is always used for these modes15678 var mode = this.mode.name;15679 var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);15680 // do key expansion15681 this._w = _expandKey(key, options.decrypt && !encryptOp);15682 this._init = true;15683};15684/**15685 * Expands a key. Typically only used for testing.15686 *15687 * @param key the symmetric key to expand, as an array of 32-bit words.15688 * @param decrypt true to expand for decryption, false for encryption.15689 *15690 * @return the expanded key.15691 */15692forge.aes._expandKey = function(key, decrypt) {15693 if(!init) {15694 initialize();15695 }15696 return _expandKey(key, decrypt);15697};15698/**15699 * Updates a single block. Typically only used for testing.15700 *15701 * @param w the expanded key to use.15702 * @param input an array of block-size 32-bit words.15703 * @param output an array of block-size 32-bit words.15704 * @param decrypt true to decrypt, false to encrypt.15705 */15706forge.aes._updateBlock = _updateBlock;15707/** Register AES algorithms **/15708registerAlgorithm('AES-ECB', forge.cipher.modes.ecb);15709registerAlgorithm('AES-CBC', forge.cipher.modes.cbc);15710registerAlgorithm('AES-CFB', forge.cipher.modes.cfb);15711registerAlgorithm('AES-OFB', forge.cipher.modes.ofb);15712registerAlgorithm('AES-CTR', forge.cipher.modes.ctr);15713registerAlgorithm('AES-GCM', forge.cipher.modes.gcm);15714function registerAlgorithm(name, mode) {15715 var factory = function() {15716 return new forge.aes.Algorithm(name, mode);15717 };15718 forge.cipher.registerAlgorithm(name, factory);15719}15720/** AES implementation **/15721var init = false; // not yet initialized15722var Nb = 4; // number of words comprising the state (AES = 4)15723var sbox; // non-linear substitution table used in key expansion15724var isbox; // inversion of sbox15725var rcon; // round constant word array15726var mix; // mix-columns table15727var imix; // inverse mix-columns table15728/**15729 * Performs initialization, ie: precomputes tables to optimize for speed.15730 *15731 * One way to understand how AES works is to imagine that 'addition' and15732 * 'multiplication' are interfaces that require certain mathematical15733 * properties to hold true (ie: they are associative) but they might have15734 * different implementations and produce different kinds of results ...15735 * provided that their mathematical properties remain true. AES defines15736 * its own methods of addition and multiplication but keeps some important15737 * properties the same, ie: associativity and distributivity. The15738 * explanation below tries to shed some light on how AES defines addition15739 * and multiplication of bytes and 32-bit words in order to perform its15740 * encryption and decryption algorithms.15741 *15742 * The basics:15743 *15744 * The AES algorithm views bytes as binary representations of polynomials15745 * that have either 1 or 0 as the coefficients. It defines the addition15746 * or subtraction of two bytes as the XOR operation. It also defines the15747 * multiplication of two bytes as a finite field referred to as GF(2^8)15748 * (Note: 'GF' means "Galois Field" which is a field that contains a finite15749 * number of elements so GF(2^8) has 256 elements).15750 *15751 * This means that any two bytes can be represented as binary polynomials;15752 * when they multiplied together and modularly reduced by an irreducible15753 * polynomial of the 8th degree, the results are the field GF(2^8). The15754 * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.15755 * This multiplication is associative with 0x01 as the identity:15756 *15757 * (b * 0x01 = GF(b, 0x01) = b).15758 *15759 * The operation GF(b, 0x02) can be performed at the byte level by left15760 * shifting b once and then XOR'ing it (to perform the modular reduction)15761 * with 0x11b if b is >= 128. Repeated application of the multiplication15762 * of 0x02 can be used to implement the multiplication of any two bytes.15763 *15764 * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can15765 * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these15766 * factors can each be multiplied by 0x57 and then added together. To do15767 * the multiplication, values for 0x57 multiplied by each of these 3 factors15768 * can be precomputed and stored in a table. To add them, the values from15769 * the table are XOR'd together.15770 *15771 * AES also defines addition and multiplication of words, that is 4-byte15772 * numbers represented as polynomials of 3 degrees where the coefficients15773 * are the values of the bytes.15774 *15775 * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.15776 *15777 * Addition is performed by XOR'ing like powers of x. Multiplication15778 * is performed in two steps, the first is an algebriac expansion as15779 * you would do normally (where addition is XOR). But the result is15780 * a polynomial larger than 3 degrees and thus it cannot fit in a word. So15781 * next the result is modularly reduced by an AES-specific polynomial of15782 * degree 4 which will always produce a polynomial of less than 4 degrees15783 * such that it will fit in a word. In AES, this polynomial is x^4 + 1.15784 *15785 * The modular product of two polynomials 'a' and 'b' is thus:15786 *15787 * d(x) = d3x^3 + d2x^2 + d1x + d015788 * with15789 * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)15790 * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)15791 * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)15792 * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)15793 *15794 * As a matrix:15795 *15796 * [d0] = [a0 a3 a2 a1][b0]15797 * [d1] [a1 a0 a3 a2][b1]15798 * [d2] [a2 a1 a0 a3][b2]15799 * [d3] [a3 a2 a1 a0][b3]15800 *15801 * Special polynomials defined by AES (0x02 == {02}):15802 * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}15803 * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.15804 *15805 * These polynomials are used in the MixColumns() and InverseMixColumns()15806 * operations, respectively, to cause each element in the state to affect15807 * the output (referred to as diffusing).15808 *15809 * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the15810 * polynomial x3.15811 *15812 * The ShiftRows() method modifies the last 3 rows in the state (where15813 * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.15814 * The 1st byte in the second row is moved to the end of the row. The 1st15815 * and 2nd bytes in the third row are moved to the end of the row. The 1st,15816 * 2nd, and 3rd bytes are moved in the fourth row.15817 *15818 * More details on how AES arithmetic works:15819 *15820 * In the polynomial representation of binary numbers, XOR performs addition15821 * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)15822 * corresponds with the multiplication of polynomials modulo an irreducible15823 * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply15824 * polynomial 'a' with polynomial 'b' and then do a modular reduction by15825 * an AES-specific irreducible polynomial of degree 8.15826 *15827 * A polynomial is irreducible if its only divisors are one and itself. For15828 * the AES algorithm, this irreducible polynomial is:15829 *15830 * m(x) = x^8 + x^4 + x^3 + x + 1,15831 *15832 * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:15833 * 100011011 = 283 = 0x11b.15834 *15835 * For example, GF(0x57, 0x83) = 0xc1 because15836 *15837 * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 115838 * 0x85 = 131 = 10000101 = x^7 + x + 115839 *15840 * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)15841 * = x^13 + x^11 + x^9 + x^8 + x^7 +15842 * x^7 + x^5 + x^3 + x^2 + x +15843 * x^6 + x^4 + x^2 + x + 115844 * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y15845 * y modulo (x^8 + x^4 + x^3 + x + 1)15846 * = x^7 + x^6 + 1.15847 *15848 * The modular reduction by m(x) guarantees the result will be a binary15849 * polynomial of less than degree 8, so that it can fit in a byte.15850 *15851 * The operation to multiply a binary polynomial b with x (the polynomial15852 * x in binary representation is 00000010) is:15853 *15854 * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^115855 *15856 * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the15857 * most significant bit is 0 in b) then the result is already reduced. If15858 * it is 1, then we can reduce it by subtracting m(x) via an XOR.15859 *15860 * It follows that multiplication by x (00000010 or 0x02) can be implemented15861 * by performing a left shift followed by a conditional bitwise XOR with15862 * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by15863 * higher powers of x can be implemented by repeated application of xtime().15864 *15865 * By adding intermediate results, multiplication by any constant can be15866 * implemented. For instance:15867 *15868 * GF(0x57, 0x13) = 0xfe because:15869 *15870 * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)15871 *15872 * Note: We XOR with 0x11b instead of 0x1b because in javascript our15873 * datatype for b can be larger than 1 byte, so a left shift will not15874 * automatically eliminate bits that overflow a byte ... by XOR'ing the15875 * overflow bit with 1 (the extra one from 0x11b) we zero it out.15876 *15877 * GF(0x57, 0x02) = xtime(0x57) = 0xae15878 * GF(0x57, 0x04) = xtime(0xae) = 0x4715879 * GF(0x57, 0x08) = xtime(0x47) = 0x8e15880 * GF(0x57, 0x10) = xtime(0x8e) = 0x0715881 *15882 * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))15883 *15884 * And by the distributive property (since XOR is addition and GF() is15885 * multiplication):15886 *15887 * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)15888 * = 0x57 ^ 0xae ^ 0x0715889 * = 0xfe.15890 */15891function initialize() {15892 init = true;15893 /* Populate the Rcon table. These are the values given by15894 [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)15895 in the field of GF(2^8), where i starts at 1.15896 rcon[0] = [0x00, 0x00, 0x00, 0x00]15897 rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 115898 rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 215899 ...15900 rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B15901 rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x3615902 We only store the first byte because it is the only one used.15903 */15904 rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];15905 // compute xtime table which maps i onto GF(i, 0x02)15906 var xtime = new Array(256);15907 for(var i = 0; i < 128; ++i) {15908 xtime[i] = i << 1;15909 xtime[i + 128] = (i + 128) << 1 ^ 0x11B;15910 }15911 // compute all other tables15912 sbox = new Array(256);15913 isbox = new Array(256);15914 mix = new Array(4);15915 imix = new Array(4);15916 for(var i = 0; i < 4; ++i) {15917 mix[i] = new Array(256);15918 imix[i] = new Array(256);15919 }15920 var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;15921 for(var i = 0; i < 256; ++i) {15922 /* We need to generate the SubBytes() sbox and isbox tables so that15923 we can perform byte substitutions. This requires us to traverse15924 all of the elements in GF, find their multiplicative inverses,15925 and apply to each the following affine transformation:15926 bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^15927 b(i + 7) mod 8 ^ ci15928 for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the15929 ith bit of a byte c with the value {63} or {01100011}.15930 It is possible to traverse every possible value in a Galois field15931 using what is referred to as a 'generator'. There are many15932 generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully15933 traverse GF we iterate 255 times, multiplying by our generator15934 each time.15935 On each iteration we can determine the multiplicative inverse for15936 the current element.15937 Suppose there is an element in GF 'e'. For a given generator 'g',15938 e = g^x. The multiplicative inverse of e is g^(255 - x). It turns15939 out that if use the inverse of a generator as another generator15940 it will produce all of the corresponding multiplicative inverses15941 at the same time. For this reason, we choose 5 as our inverse15942 generator because it only requires 2 multiplies and 1 add and its15943 inverse, 82, requires relatively few operations as well.15944 In order to apply the affine transformation, the multiplicative15945 inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a15946 bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and15947 'x'. Then 's' is left shifted and the high bit of 's' is made the15948 low bit. The resulting value is stored in 's'. Then 'x' is XOR'd15949 with 's' and stored in 'x'. On each subsequent iteration the same15950 operation is performed. When 4 iterations are complete, 'x' is15951 XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.15952 For example:15953 s = 0100000115954 x = 0100000115955 iteration 1: s = 10000010, x ^= s15956 iteration 2: s = 00000101, x ^= s15957 iteration 3: s = 00001010, x ^= s15958 iteration 4: s = 00010100, x ^= s15959 x ^= 0x6315960 This can be done with a loop where s = (s << 1) | (s >> 7). However,15961 it can also be done by using a single 16-bit (in this case 32-bit)15962 number 'sx'. Since XOR is an associative operation, we can set 'sx'15963 to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.15964 The most significant bits will flow into the high 8 bit positions15965 and be correctly XOR'd with one another. All that remains will be15966 to cycle the high 8 bits by XOR'ing them all with the lower 8 bits15967 afterwards.15968 At the same time we're populating sbox and isbox we can precompute15969 the multiplication we'll need to do to do MixColumns() later.15970 */15971 // apply affine transformation15972 sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);15973 sx = (sx >> 8) ^ (sx & 255) ^ 0x63;15974 // update tables15975 sbox[e] = sx;15976 isbox[sx] = e;15977 /* Mixing columns is done using matrix multiplication. The columns15978 that are to be mixed are each a single word in the current state.15979 The state has Nb columns (4 columns). Therefore each column is a15980 4 byte word. So to mix the columns in a single column 'c' where15981 its rows are r0, r1, r2, and r3, we use the following matrix15982 multiplication:15983 [2 3 1 1]*[r0,c]=[r'0,c]15984 [1 2 3 1] [r1,c] [r'1,c]15985 [1 1 2 3] [r2,c] [r'2,c]15986 [3 1 1 2] [r3,c] [r'3,c]15987 r0, r1, r2, and r3 are each 1 byte of one of the words in the15988 state (a column). To do matrix multiplication for each mixed15989 column c' we multiply the corresponding row from the left matrix15990 with the corresponding column from the right matrix. In total, we15991 get 4 equations:15992 r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c15993 r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c15994 r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c15995 r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c15996 As usual, the multiplication is as previously defined and the15997 addition is XOR. In order to optimize mixing columns we can store15998 the multiplication results in tables. If you think of the whole15999 column as a word (it might help to visualize by mentally rotating16000 the equations above by counterclockwise 90 degrees) then you can16001 see that it would be useful to map the multiplications performed on16002 each byte (r0, r1, r2, r3) onto a word as well. For instance, we16003 could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the16004 highest 8 bits and 3*r0 in the lowest 8 bits (with the other two16005 respectively in the middle). This means that a table can be16006 constructed that uses r0 as an index to the word. We can do the16007 same with r1, r2, and r3, creating a total of 4 tables.16008 To construct a full c', we can just look up each byte of c in16009 their respective tables and XOR the results together.16010 Also, to build each table we only have to calculate the word16011 for 2,1,1,3 for every byte ... which we can do on each iteration16012 of this loop since we will iterate over every byte. After we have16013 calculated 2,1,1,3 we can get the results for the other tables16014 by cycling the byte at the end to the beginning. For instance16015 we can take the result of table 2,1,1,3 and produce table 3,2,1,116016 by moving the right most byte to the left most position just like16017 how you can imagine the 3 moved out of 2,1,1,3 and to the front16018 to produce 3,2,1,1.16019 There is another optimization in that the same multiples of16020 the current element we need in order to advance our generator16021 to the next iteration can be reused in performing the 2,1,1,316022 calculation. We also calculate the inverse mix column tables,16023 with e,9,d,b being the inverse of 2,1,1,3.16024 When we're done, and we need to actually mix columns, the first16025 byte of each state word should be put through mix[0] (2,1,1,3),16026 the second through mix[1] (3,2,1,1) and so forth. Then they should16027 be XOR'd together to produce the fully mixed column.16028 */16029 // calculate mix and imix table values16030 sx2 = xtime[sx];16031 e2 = xtime[e];16032 e4 = xtime[e2];16033 e8 = xtime[e4];16034 me =16035 (sx2 << 24) ^ // 216036 (sx << 16) ^ // 116037 (sx << 8) ^ // 116038 (sx ^ sx2); // 316039 ime =16040 (e2 ^ e4 ^ e8) << 24 ^ // E (14)16041 (e ^ e8) << 16 ^ // 916042 (e ^ e4 ^ e8) << 8 ^ // D (13)16043 (e ^ e2 ^ e8); // B (11)16044 // produce each of the mix tables by rotating the 2,1,1,3 value16045 for(var n = 0; n < 4; ++n) {16046 mix[n][e] = me;16047 imix[n][sx] = ime;16048 // cycle the right most byte to the left most position16049 // ie: 2,1,1,3 becomes 3,2,1,116050 me = me << 24 | me >>> 8;16051 ime = ime << 24 | ime >>> 8;16052 }16053 // get next element and inverse16054 if(e === 0) {16055 // 1 is the inverse of 116056 e = ei = 1;16057 } else {16058 // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)16059 // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)16060 e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];16061 ei ^= xtime[xtime[ei]];16062 }16063 }16064}16065/**16066 * Generates a key schedule using the AES key expansion algorithm.16067 *16068 * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion16069 * routine to generate a key schedule. The Key Expansion generates a total16070 * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,16071 * and each of the Nr rounds requires Nb words of key data. The resulting16072 * key schedule consists of a linear array of 4-byte words, denoted [wi ],16073 * with i in the range 0 <= i < Nb(Nr + 1).16074 *16075 * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)16076 * AES-128 (Nb=4, Nk=4, Nr=10)16077 * AES-192 (Nb=4, Nk=6, Nr=12)16078 * AES-256 (Nb=4, Nk=8, Nr=14)16079 * Note: Nr=Nk+6.16080 *16081 * Nb is the number of columns (32-bit words) comprising the State (or16082 * number of bytes in a block). For AES, Nb=4.16083 *16084 * @param key the key to schedule (as an array of 32-bit words).16085 * @param decrypt true to modify the key schedule to decrypt, false not to.16086 *16087 * @return the generated key schedule.16088 */16089function _expandKey(key, decrypt) {16090 // copy the key's words to initialize the key schedule16091 var w = key.slice(0);16092 /* RotWord() will rotate a word, moving the first byte to the last16093 byte's position (shifting the other bytes left).16094 We will be getting the value of Rcon at i / Nk. 'i' will iterate16095 from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in16096 a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from16097 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will16098 increase by 1. We use a counter iNk to keep track of this.16099 */16100 // go through the rounds expanding the key16101 var temp, iNk = 1;16102 var Nk = w.length;16103 var Nr1 = Nk + 6 + 1;16104 var end = Nb * Nr1;16105 for(var i = Nk; i < end; ++i) {16106 temp = w[i - 1];16107 if(i % Nk === 0) {16108 // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]16109 temp =16110 sbox[temp >>> 16 & 255] << 24 ^16111 sbox[temp >>> 8 & 255] << 16 ^16112 sbox[temp & 255] << 8 ^16113 sbox[temp >>> 24] ^ (rcon[iNk] << 24);16114 iNk++;16115 } else if(Nk > 6 && (i % Nk === 4)) {16116 // temp = SubWord(temp)16117 temp =16118 sbox[temp >>> 24] << 24 ^16119 sbox[temp >>> 16 & 255] << 16 ^16120 sbox[temp >>> 8 & 255] << 8 ^16121 sbox[temp & 255];16122 }16123 w[i] = w[i - Nk] ^ temp;16124 }16125 /* When we are updating a cipher block we always use the code path for16126 encryption whether we are decrypting or not (to shorten code and16127 simplify the generation of look up tables). However, because there16128 are differences in the decryption algorithm, other than just swapping16129 in different look up tables, we must transform our key schedule to16130 account for these changes:16131 1. The decryption algorithm gets its key rounds in reverse order.16132 2. The decryption algorithm adds the round key before mixing columns16133 instead of afterwards.16134 We don't need to modify our key schedule to handle the first case,16135 we can just traverse the key schedule in reverse order when decrypting.16136 The second case requires a little work.16137 The tables we built for performing rounds will take an input and then16138 perform SubBytes() and MixColumns() or, for the decrypt version,16139 InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires16140 us to AddRoundKey() before InvMixColumns(). This means we'll need to16141 apply some transformations to the round key to inverse-mix its columns16142 so they'll be correct for moving AddRoundKey() to after the state has16143 had its columns inverse-mixed.16144 To inverse-mix the columns of the state when we're decrypting we use a16145 lookup table that will apply InvSubBytes() and InvMixColumns() at the16146 same time. However, the round key's bytes are not inverse-substituted16147 in the decryption algorithm. To get around this problem, we can first16148 substitute the bytes in the round key so that when we apply the16149 transformation via the InvSubBytes()+InvMixColumns() table, it will16150 undo our substitution leaving us with the original value that we16151 want -- and then inverse-mix that value.16152 This change will correctly alter our key schedule so that we can XOR16153 each round key with our already transformed decryption state. This16154 allows us to use the same code path as the encryption algorithm.16155 We make one more change to the decryption key. Since the decryption16156 algorithm runs in reverse from the encryption algorithm, we reverse16157 the order of the round keys to avoid having to iterate over the key16158 schedule backwards when running the encryption algorithm later in16159 decryption mode. In addition to reversing the order of the round keys,16160 we also swap each round key's 2nd and 4th rows. See the comments16161 section where rounds are performed for more details about why this is16162 done. These changes are done inline with the other substitution16163 described above.16164 */16165 if(decrypt) {16166 var tmp;16167 var m0 = imix[0];16168 var m1 = imix[1];16169 var m2 = imix[2];16170 var m3 = imix[3];16171 var wnew = w.slice(0);16172 end = w.length;16173 for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {16174 // do not sub the first or last round key (round keys are Nb16175 // words) as no column mixing is performed before they are added,16176 // but do change the key order16177 if(i === 0 || i === (end - Nb)) {16178 wnew[i] = w[wi];16179 wnew[i + 1] = w[wi + 3];16180 wnew[i + 2] = w[wi + 2];16181 wnew[i + 3] = w[wi + 1];16182 } else {16183 // substitute each round key byte because the inverse-mix16184 // table will inverse-substitute it (effectively cancel the16185 // substitution because round key bytes aren't sub'd in16186 // decryption mode) and swap indexes 3 and 116187 for(var n = 0; n < Nb; ++n) {16188 tmp = w[wi + n];16189 wnew[i + (3&-n)] =16190 m0[sbox[tmp >>> 24]] ^16191 m1[sbox[tmp >>> 16 & 255]] ^16192 m2[sbox[tmp >>> 8 & 255]] ^16193 m3[sbox[tmp & 255]];16194 }16195 }16196 }16197 w = wnew;16198 }16199 return w;16200}16201/**16202 * Updates a single block (16 bytes) using AES. The update will either16203 * encrypt or decrypt the block.16204 *16205 * @param w the key schedule.16206 * @param input the input block (an array of 32-bit words).16207 * @param output the updated output block.16208 * @param decrypt true to decrypt the block, false to encrypt it.16209 */16210function _updateBlock(w, input, output, decrypt) {16211 /*16212 Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])16213 begin16214 byte state[4,Nb]16215 state = in16216 AddRoundKey(state, w[0, Nb-1])16217 for round = 1 step 1 to Nr-116218 SubBytes(state)16219 ShiftRows(state)16220 MixColumns(state)16221 AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])16222 end for16223 SubBytes(state)16224 ShiftRows(state)16225 AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])16226 out = state16227 end16228 InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])16229 begin16230 byte state[4,Nb]16231 state = in16232 AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])16233 for round = Nr-1 step -1 downto 116234 InvShiftRows(state)16235 InvSubBytes(state)16236 AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])16237 InvMixColumns(state)16238 end for16239 InvShiftRows(state)16240 InvSubBytes(state)16241 AddRoundKey(state, w[0, Nb-1])16242 out = state16243 end16244 */16245 // Encrypt: AddRoundKey(state, w[0, Nb-1])16246 // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])16247 var Nr = w.length / 4 - 1;16248 var m0, m1, m2, m3, sub;16249 if(decrypt) {16250 m0 = imix[0];16251 m1 = imix[1];16252 m2 = imix[2];16253 m3 = imix[3];16254 sub = isbox;16255 } else {16256 m0 = mix[0];16257 m1 = mix[1];16258 m2 = mix[2];16259 m3 = mix[3];16260 sub = sbox;16261 }16262 var a, b, c, d, a2, b2, c2;16263 a = input[0] ^ w[0];16264 b = input[decrypt ? 3 : 1] ^ w[1];16265 c = input[2] ^ w[2];16266 d = input[decrypt ? 1 : 3] ^ w[3];16267 var i = 3;16268 /* In order to share code we follow the encryption algorithm when both16269 encrypting and decrypting. To account for the changes required in the16270 decryption algorithm, we use different lookup tables when decrypting16271 and use a modified key schedule to account for the difference in the16272 order of transformations applied when performing rounds. We also get16273 key rounds in reverse order (relative to encryption). */16274 for(var round = 1; round < Nr; ++round) {16275 /* As described above, we'll be using table lookups to perform the16276 column mixing. Each column is stored as a word in the state (the16277 array 'input' has one column as a word at each index). In order to16278 mix a column, we perform these transformations on each row in c,16279 which is 1 byte in each word. The new column for c0 is c'0:16280 m0 m1 m2 m316281 r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c016282 r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c016283 r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c016284 r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c016285 So using mix tables where c0 is a word with r0 being its upper16286 8 bits and r3 being its lower 8 bits:16287 m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]16288 ...16289 m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]16290 Therefore to mix the columns in each word in the state we16291 do the following (& 255 omitted for brevity):16292 c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]16293 c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]16294 c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]16295 c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]16296 However, before mixing, the algorithm requires us to perform16297 ShiftRows(). The ShiftRows() transformation cyclically shifts the16298 last 3 rows of the state over different offsets. The first row16299 (r = 0) is not shifted.16300 s'_r,c = s_r,(c + shift(r, Nb) mod Nb16301 for 0 < r < 4 and 0 <= c < Nb and16302 shift(1, 4) = 116303 shift(2, 4) = 216304 shift(3, 4) = 3.16305 This causes the first byte in r = 1 to be moved to the end of16306 the row, the first 2 bytes in r = 2 to be moved to the end of16307 the row, the first 3 bytes in r = 3 to be moved to the end of16308 the row:16309 r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]16310 r2: [c0 c1 c2 c3] [c2 c3 c0 c1]16311 r3: [c0 c1 c2 c3] [c3 c0 c1 c2]16312 We can make these substitutions inline with our column mixing to16313 generate an updated set of equations to produce each word in the16314 state (note the columns have changed positions):16315 c0 c1 c2 c3 => c0 c1 c2 c316316 c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)16317 c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)16318 c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)16319 Therefore:16320 c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c316321 c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c316322 c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c316323 c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c316324 c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c016325 c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c016326 c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c016327 c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c016328 ... and so forth for c'2 and c'3. The important distinction is16329 that the columns are cycling, with c0 being used with the m016330 map when calculating c0, but c1 being used with the m0 map when16331 calculating c1 ... and so forth.16332 When performing the inverse we transform the mirror image and16333 skip the bottom row, instead of the top one, and move upwards:16334 c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption16335 c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)16336 c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption16337 c3 c2 c1 c0 c3 c2 c1 c016338 If you compare the resulting matrices for ShiftRows()+MixColumns()16339 and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are16340 different (in encrypt mode vs. decrypt mode). So in order to use16341 the same code to handle both encryption and decryption, we will16342 need to do some mapping.16343 If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r<N> be16344 a row number in the state, then the resulting matrix in encryption16345 mode for applying the above transformations would be:16346 r1: a b c d16347 r2: b c d a16348 r3: c d a b16349 r4: d a b c16350 If we did the same in decryption mode we would get:16351 r1: a d c b16352 r2: b a d c16353 r3: c b a d16354 r4: d c b a16355 If instead we swap d and b (set b=c3 and d=c1), then we get:16356 r1: a b c d16357 r2: d a b c16358 r3: c d a b16359 r4: b c d a16360 Now the 1st and 3rd rows are the same as the encryption matrix. All16361 we need to do then to make the mapping exactly the same is to swap16362 the 2nd and 4th rows when in decryption mode. To do this without16363 having to do it on each iteration, we swapped the 2nd and 4th rows16364 in the decryption key schedule. We also have to do the swap above16365 when we first pull in the input and when we set the final output. */16366 a2 =16367 m0[a >>> 24] ^16368 m1[b >>> 16 & 255] ^16369 m2[c >>> 8 & 255] ^16370 m3[d & 255] ^ w[++i];16371 b2 =16372 m0[b >>> 24] ^16373 m1[c >>> 16 & 255] ^16374 m2[d >>> 8 & 255] ^16375 m3[a & 255] ^ w[++i];16376 c2 =16377 m0[c >>> 24] ^16378 m1[d >>> 16 & 255] ^16379 m2[a >>> 8 & 255] ^16380 m3[b & 255] ^ w[++i];16381 d =16382 m0[d >>> 24] ^16383 m1[a >>> 16 & 255] ^16384 m2[b >>> 8 & 255] ^16385 m3[c & 255] ^ w[++i];16386 a = a2;16387 b = b2;16388 c = c2;16389 }16390 /*16391 Encrypt:16392 SubBytes(state)16393 ShiftRows(state)16394 AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])16395 Decrypt:16396 InvShiftRows(state)16397 InvSubBytes(state)16398 AddRoundKey(state, w[0, Nb-1])16399 */16400 // Note: rows are shifted inline16401 output[0] =16402 (sub[a >>> 24] << 24) ^16403 (sub[b >>> 16 & 255] << 16) ^16404 (sub[c >>> 8 & 255] << 8) ^16405 (sub[d & 255]) ^ w[++i];16406 output[decrypt ? 3 : 1] =16407 (sub[b >>> 24] << 24) ^16408 (sub[c >>> 16 & 255] << 16) ^16409 (sub[d >>> 8 & 255] << 8) ^16410 (sub[a & 255]) ^ w[++i];16411 output[2] =16412 (sub[c >>> 24] << 24) ^16413 (sub[d >>> 16 & 255] << 16) ^16414 (sub[a >>> 8 & 255] << 8) ^16415 (sub[b & 255]) ^ w[++i];16416 output[decrypt ? 1 : 3] =16417 (sub[d >>> 24] << 24) ^16418 (sub[a >>> 16 & 255] << 16) ^16419 (sub[b >>> 8 & 255] << 8) ^16420 (sub[c & 255]) ^ w[++i];16421}16422/**16423 * Deprecated. Instead, use:16424 *16425 * forge.cipher.createCipher('AES-<mode>', key);16426 * forge.cipher.createDecipher('AES-<mode>', key);16427 *16428 * Creates a deprecated AES cipher object. This object's mode will default to16429 * CBC (cipher-block-chaining).16430 *16431 * The key and iv may be given as a string of bytes, an array of bytes, a16432 * byte buffer, or an array of 32-bit words.16433 *16434 * @param options the options to use.16435 * key the symmetric key to use.16436 * output the buffer to write to.16437 * decrypt true for decryption, false for encryption.16438 * mode the cipher mode to use (default: 'CBC').16439 *16440 * @return the cipher.16441 */16442function _createCipher(options) {16443 options = options || {};16444 var mode = (options.mode || 'CBC').toUpperCase();16445 var algorithm = 'AES-' + mode;16446 var cipher;16447 if(options.decrypt) {16448 cipher = forge.cipher.createDecipher(algorithm, options.key);16449 } else {16450 cipher = forge.cipher.createCipher(algorithm, options.key);16451 }16452 // backwards compatible start API16453 var start = cipher.start;16454 cipher.start = function(iv, options) {16455 // backwards compatibility: support second arg as output buffer16456 var output = null;16457 if(options instanceof forge.util.ByteBuffer) {16458 output = options;16459 options = {};16460 }16461 options = options || {};16462 options.output = output;16463 options.iv = iv;16464 start.call(cipher, options);16465 };16466 return cipher;16467}16468/***/ }),16469/***/ 1449:16470/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {16471/**16472 * A Javascript implementation of AES Cipher Suites for TLS.16473 *16474 * @author Dave Longley16475 *16476 * Copyright (c) 2009-2015 Digital Bazaar, Inc.16477 *16478 */16479var forge = __nccwpck_require__(9177);16480__nccwpck_require__(7994);16481__nccwpck_require__(9167);16482var tls = module.exports = forge.tls;16483/**16484 * Supported cipher suites.16485 */16486tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = {16487 id: [0x00, 0x2f],16488 name: 'TLS_RSA_WITH_AES_128_CBC_SHA',16489 initSecurityParameters: function(sp) {16490 sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;16491 sp.cipher_type = tls.CipherType.block;16492 sp.enc_key_length = 16;16493 sp.block_length = 16;16494 sp.fixed_iv_length = 16;16495 sp.record_iv_length = 16;16496 sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;16497 sp.mac_length = 20;16498 sp.mac_key_length = 20;16499 },16500 initConnectionState: initConnectionState16501};16502tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = {16503 id: [0x00, 0x35],16504 name: 'TLS_RSA_WITH_AES_256_CBC_SHA',16505 initSecurityParameters: function(sp) {16506 sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;16507 sp.cipher_type = tls.CipherType.block;16508 sp.enc_key_length = 32;16509 sp.block_length = 16;16510 sp.fixed_iv_length = 16;16511 sp.record_iv_length = 16;16512 sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;16513 sp.mac_length = 20;16514 sp.mac_key_length = 20;16515 },16516 initConnectionState: initConnectionState16517};16518function initConnectionState(state, c, sp) {16519 var client = (c.entity === forge.tls.ConnectionEnd.client);16520 // cipher setup16521 state.read.cipherState = {16522 init: false,16523 cipher: forge.cipher.createDecipher('AES-CBC', client ?16524 sp.keys.server_write_key : sp.keys.client_write_key),16525 iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV16526 };16527 state.write.cipherState = {16528 init: false,16529 cipher: forge.cipher.createCipher('AES-CBC', client ?16530 sp.keys.client_write_key : sp.keys.server_write_key),16531 iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV16532 };16533 state.read.cipherFunction = decrypt_aes_cbc_sha1;16534 state.write.cipherFunction = encrypt_aes_cbc_sha1;16535 // MAC setup16536 state.read.macLength = state.write.macLength = sp.mac_length;16537 state.read.macFunction = state.write.macFunction = tls.hmac_sha1;16538}16539/**16540 * Encrypts the TLSCompressed record into a TLSCipherText record using AES16541 * in CBC mode.16542 *16543 * @param record the TLSCompressed record to encrypt.16544 * @param s the ConnectionState to use.16545 *16546 * @return true on success, false on failure.16547 */16548function encrypt_aes_cbc_sha1(record, s) {16549 var rval = false;16550 // append MAC to fragment, update sequence number16551 var mac = s.macFunction(s.macKey, s.sequenceNumber, record);16552 record.fragment.putBytes(mac);16553 s.updateSequenceNumber();16554 // TLS 1.1+ use an explicit IV every time to protect against CBC attacks16555 var iv;16556 if(record.version.minor === tls.Versions.TLS_1_0.minor) {16557 // use the pre-generated IV when initializing for TLS 1.0, otherwise use16558 // the residue from the previous encryption16559 iv = s.cipherState.init ? null : s.cipherState.iv;16560 } else {16561 iv = forge.random.getBytesSync(16);16562 }16563 s.cipherState.init = true;16564 // start cipher16565 var cipher = s.cipherState.cipher;16566 cipher.start({iv: iv});16567 // TLS 1.1+ write IV into output16568 if(record.version.minor >= tls.Versions.TLS_1_1.minor) {16569 cipher.output.putBytes(iv);16570 }16571 // do encryption (default padding is appropriate)16572 cipher.update(record.fragment);16573 if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {16574 // set record fragment to encrypted output16575 record.fragment = cipher.output;16576 record.length = record.fragment.length();16577 rval = true;16578 }16579 return rval;16580}16581/**16582 * Handles padding for aes_cbc_sha1 in encrypt mode.16583 *16584 * @param blockSize the block size.16585 * @param input the input buffer.16586 * @param decrypt true in decrypt mode, false in encrypt mode.16587 *16588 * @return true on success, false on failure.16589 */16590function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) {16591 /* The encrypted data length (TLSCiphertext.length) is one more than the sum16592 of SecurityParameters.block_length, TLSCompressed.length,16593 SecurityParameters.mac_length, and padding_length.16594 The padding may be any length up to 255 bytes long, as long as it results in16595 the TLSCiphertext.length being an integral multiple of the block length.16596 Lengths longer than necessary might be desirable to frustrate attacks on a16597 protocol based on analysis of the lengths of exchanged messages. Each uint816598 in the padding data vector must be filled with the padding length value.16599 The padding length should be such that the total size of the16600 GenericBlockCipher structure is a multiple of the cipher's block length.16601 Legal values range from zero to 255, inclusive. This length specifies the16602 length of the padding field exclusive of the padding_length field itself.16603 This is slightly different from PKCS#7 because the padding value is 116604 less than the actual number of padding bytes if you include the16605 padding_length uint8 itself as a padding byte. */16606 if(!decrypt) {16607 // get the number of padding bytes required to reach the blockSize and16608 // subtract 1 for the padding value (to make room for the padding_length16609 // uint8)16610 var padding = blockSize - (input.length() % blockSize);16611 input.fillWithByte(padding - 1, padding);16612 }16613 return true;16614}16615/**16616 * Handles padding for aes_cbc_sha1 in decrypt mode.16617 *16618 * @param blockSize the block size.16619 * @param output the output buffer.16620 * @param decrypt true in decrypt mode, false in encrypt mode.16621 *16622 * @return true on success, false on failure.16623 */16624function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {16625 var rval = true;16626 if(decrypt) {16627 /* The last byte in the output specifies the number of padding bytes not16628 including itself. Each of the padding bytes has the same value as that16629 last byte (known as the padding_length). Here we check all padding16630 bytes to ensure they have the value of padding_length even if one of16631 them is bad in order to ward-off timing attacks. */16632 var len = output.length();16633 var paddingLength = output.last();16634 for(var i = len - 1 - paddingLength; i < len - 1; ++i) {16635 rval = rval && (output.at(i) == paddingLength);16636 }16637 if(rval) {16638 // trim off padding bytes and last padding length byte16639 output.truncate(paddingLength + 1);16640 }16641 }16642 return rval;16643}16644/**16645 * Decrypts a TLSCipherText record into a TLSCompressed record using16646 * AES in CBC mode.16647 *16648 * @param record the TLSCipherText record to decrypt.16649 * @param s the ConnectionState to use.16650 *16651 * @return true on success, false on failure.16652 */16653function decrypt_aes_cbc_sha1(record, s) {16654 var rval = false;16655 var iv;16656 if(record.version.minor === tls.Versions.TLS_1_0.minor) {16657 // use pre-generated IV when initializing for TLS 1.0, otherwise use the16658 // residue from the previous decryption16659 iv = s.cipherState.init ? null : s.cipherState.iv;16660 } else {16661 // TLS 1.1+ use an explicit IV every time to protect against CBC attacks16662 // that is appended to the record fragment16663 iv = record.fragment.getBytes(16);16664 }16665 s.cipherState.init = true;16666 // start cipher16667 var cipher = s.cipherState.cipher;16668 cipher.start({iv: iv});16669 // do decryption16670 cipher.update(record.fragment);16671 rval = cipher.finish(decrypt_aes_cbc_sha1_padding);16672 // even if decryption fails, keep going to minimize timing attacks16673 // decrypted data:16674 // first (len - 20) bytes = application data16675 // last 20 bytes = MAC16676 var macLen = s.macLength;16677 // create a random MAC to check against should the mac length check fail16678 // Note: do this regardless of the failure to keep timing consistent16679 var mac = forge.random.getBytesSync(macLen);16680 // get fragment and mac16681 var len = cipher.output.length();16682 if(len >= macLen) {16683 record.fragment = cipher.output.getBytes(len - macLen);16684 mac = cipher.output.getBytes(macLen);16685 } else {16686 // bad data, but get bytes anyway to try to keep timing consistent16687 record.fragment = cipher.output.getBytes();16688 }16689 record.fragment = forge.util.createBuffer(record.fragment);16690 record.length = record.fragment.length();16691 // see if data integrity checks out, update sequence number16692 var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record);16693 s.updateSequenceNumber();16694 rval = compareMacs(s.macKey, mac, mac2) && rval;16695 return rval;16696}16697/**16698 * Safely compare two MACs. This function will compare two MACs in a way16699 * that protects against timing attacks.16700 *16701 * TODO: Expose elsewhere as a utility API.16702 *16703 * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/16704 *16705 * @param key the MAC key to use.16706 * @param mac1 as a binary-encoded string of bytes.16707 * @param mac2 as a binary-encoded string of bytes.16708 *16709 * @return true if the MACs are the same, false if not.16710 */16711function compareMacs(key, mac1, mac2) {16712 var hmac = forge.hmac.create();16713 hmac.start('SHA1', key);16714 hmac.update(mac1);16715 mac1 = hmac.digest().getBytes();16716 hmac.start(null, null);16717 hmac.update(mac2);16718 mac2 = hmac.digest().getBytes();16719 return mac1 === mac2;16720}16721/***/ }),16722/***/ 9414:16723/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {16724/**16725 * Copyright (c) 2019 Digital Bazaar, Inc.16726 */16727var forge = __nccwpck_require__(9177);16728__nccwpck_require__(9549);16729var asn1 = forge.asn1;16730exports.privateKeyValidator = {16731 // PrivateKeyInfo16732 name: 'PrivateKeyInfo',16733 tagClass: asn1.Class.UNIVERSAL,16734 type: asn1.Type.SEQUENCE,16735 constructed: true,16736 value: [{16737 // Version (INTEGER)16738 name: 'PrivateKeyInfo.version',16739 tagClass: asn1.Class.UNIVERSAL,16740 type: asn1.Type.INTEGER,16741 constructed: false,16742 capture: 'privateKeyVersion'16743 }, {16744 // privateKeyAlgorithm16745 name: 'PrivateKeyInfo.privateKeyAlgorithm',16746 tagClass: asn1.Class.UNIVERSAL,16747 type: asn1.Type.SEQUENCE,16748 constructed: true,16749 value: [{16750 name: 'AlgorithmIdentifier.algorithm',16751 tagClass: asn1.Class.UNIVERSAL,16752 type: asn1.Type.OID,16753 constructed: false,16754 capture: 'privateKeyOid'16755 }]16756 }, {16757 // PrivateKey16758 name: 'PrivateKeyInfo',16759 tagClass: asn1.Class.UNIVERSAL,16760 type: asn1.Type.OCTETSTRING,16761 constructed: false,16762 capture: 'privateKey'16763 }]16764};16765exports.publicKeyValidator = {16766 name: 'SubjectPublicKeyInfo',16767 tagClass: asn1.Class.UNIVERSAL,16768 type: asn1.Type.SEQUENCE,16769 constructed: true,16770 captureAsn1: 'subjectPublicKeyInfo',16771 value: [{16772 name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',16773 tagClass: asn1.Class.UNIVERSAL,16774 type: asn1.Type.SEQUENCE,16775 constructed: true,16776 value: [{16777 name: 'AlgorithmIdentifier.algorithm',16778 tagClass: asn1.Class.UNIVERSAL,16779 type: asn1.Type.OID,16780 constructed: false,16781 capture: 'publicKeyOid'16782 }]16783 },16784 // capture group for ed25519PublicKey16785 {16786 tagClass: asn1.Class.UNIVERSAL,16787 type: asn1.Type.BITSTRING,16788 constructed: false,16789 composed: true,16790 captureBitStringValue: 'ed25519PublicKey'16791 }16792 // FIXME: this is capture group for rsaPublicKey, use it in this API or16793 // discard?16794 /* {16795 // subjectPublicKey16796 name: 'SubjectPublicKeyInfo.subjectPublicKey',16797 tagClass: asn1.Class.UNIVERSAL,16798 type: asn1.Type.BITSTRING,16799 constructed: false,16800 value: [{16801 // RSAPublicKey16802 name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',16803 tagClass: asn1.Class.UNIVERSAL,16804 type: asn1.Type.SEQUENCE,16805 constructed: true,16806 optional: true,16807 captureAsn1: 'rsaPublicKey'16808 }]16809 } */16810 ]16811};16812/***/ }),16813/***/ 9549:16814/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {16815/**16816 * Javascript implementation of Abstract Syntax Notation Number One.16817 *16818 * @author Dave Longley16819 *16820 * Copyright (c) 2010-2015 Digital Bazaar, Inc.16821 *16822 * An API for storing data using the Abstract Syntax Notation Number One16823 * format using DER (Distinguished Encoding Rules) encoding. This encoding is16824 * commonly used to store data for PKI, i.e. X.509 Certificates, and this16825 * implementation exists for that purpose.16826 *16827 * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract16828 * syntax of information without restricting the way the information is encoded16829 * for transmission. It provides a standard that allows for open systems16830 * communication. ASN.1 defines the syntax of information data and a number of16831 * simple data types as well as a notation for describing them and specifying16832 * values for them.16833 *16834 * The RSA algorithm creates public and private keys that are often stored in16835 * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This16836 * class provides the most basic functionality required to store and load DSA16837 * keys that are encoded according to ASN.1.16838 *16839 * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)16840 * and DER (Distinguished Encoding Rules). DER is just a subset of BER that16841 * has stricter requirements for how data must be encoded.16842 *16843 * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)16844 * and a byte array for the value of this ASN1 structure which may be data or a16845 * list of ASN.1 structures.16846 *16847 * Each ASN.1 structure using BER is (Tag-Length-Value):16848 *16849 * | byte 0 | bytes X | bytes Y |16850 * |--------|---------|----------16851 * | tag | length | value |16852 *16853 * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to16854 * be two or more octets, but that is not supported by this class. A tag is16855 * only 1 byte. Bits 1-5 give the tag number (ie the data type within a16856 * particular 'class'), 6 indicates whether or not the ASN.1 value is16857 * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If16858 * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,16859 * then the class is APPLICATION. If only bit 8 is set, then the class is16860 * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.16861 * The tag numbers for the data types for the class UNIVERSAL are listed below:16862 *16863 * UNIVERSAL 0 Reserved for use by the encoding rules16864 * UNIVERSAL 1 Boolean type16865 * UNIVERSAL 2 Integer type16866 * UNIVERSAL 3 Bitstring type16867 * UNIVERSAL 4 Octetstring type16868 * UNIVERSAL 5 Null type16869 * UNIVERSAL 6 Object identifier type16870 * UNIVERSAL 7 Object descriptor type16871 * UNIVERSAL 8 External type and Instance-of type16872 * UNIVERSAL 9 Real type16873 * UNIVERSAL 10 Enumerated type16874 * UNIVERSAL 11 Embedded-pdv type16875 * UNIVERSAL 12 UTF8String type16876 * UNIVERSAL 13 Relative object identifier type16877 * UNIVERSAL 14-15 Reserved for future editions16878 * UNIVERSAL 16 Sequence and Sequence-of types16879 * UNIVERSAL 17 Set and Set-of types16880 * UNIVERSAL 18-22, 25-30 Character string types16881 * UNIVERSAL 23-24 Time types16882 *16883 * The length of an ASN.1 structure is specified after the tag identifier.16884 * There is a definite form and an indefinite form. The indefinite form may16885 * be used if the encoding is constructed and not all immediately available.16886 * The indefinite form is encoded using a length byte with only the 8th bit16887 * set. The end of the constructed object is marked using end-of-contents16888 * octets (two zero bytes).16889 *16890 * The definite form looks like this:16891 *16892 * The length may take up 1 or more bytes, it depends on the length of the16893 * value of the ASN.1 structure. DER encoding requires that if the ASN.116894 * structure has a value that has a length greater than 127, more than 1 byte16895 * will be used to store its length, otherwise just one byte will be used.16896 * This is strict.16897 *16898 * In the case that the length of the ASN.1 value is less than 127, 1 octet16899 * (byte) is used to store the "short form" length. The 8th bit has a value of16900 * 0 indicating the length is "short form" and not "long form" and bits 7-116901 * give the length of the data. (The 8th bit is the left-most, most significant16902 * bit: also known as big endian or network format).16903 *16904 * In the case that the length of the ASN.1 value is greater than 127, 2 to16905 * 127 octets (bytes) are used to store the "long form" length. The first16906 * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-116907 * give the number of additional octets. All following octets are in base 25616908 * with the most significant digit first (typical big-endian binary unsigned16909 * integer storage). So, for instance, if the length of a value was 257, the16910 * first byte would be set to:16911 *16912 * 10000010 = 130 = 0x82.16913 *16914 * This indicates there are 2 octets (base 256) for the length. The second and16915 * third bytes (the octets just mentioned) would store the length in base 256:16916 *16917 * octet 2: 00000001 = 1 * 256^1 = 25616918 * octet 3: 00000001 = 1 * 256^0 = 116919 * total = 25716920 *16921 * The algorithm for converting a js integer value of 257 to base-256 is:16922 *16923 * var value = 257;16924 * var bytes = [];16925 * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first16926 * bytes[1] = value & 0xFF; // least significant byte last16927 *16928 * On the ASN.1 UNIVERSAL Object Identifier (OID) type:16929 *16930 * An OID can be written like: "value1.value2.value3...valueN"16931 *16932 * The DER encoding rules:16933 *16934 * The first byte has the value 40 * value1 + value2.16935 * The following bytes, if any, encode the remaining values. Each value is16936 * encoded in base 128, most significant digit first (big endian), with as16937 * few digits as possible, and the most significant bit of each byte set16938 * to 1 except the last in each value's encoding. For example: Given the16939 * OID "1.2.840.113549", its DER encoding is (remember each byte except the16940 * last one in each encoding is OR'd with 0x80):16941 *16942 * byte 1: 40 * 1 + 2 = 42 = 0x2A.16943 * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x864816944 * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D16945 *16946 * The final value is: 0x2A864886F70D.16947 * The full OID (including ASN.1 tag and length of 6 bytes) is:16948 * 0x06062A864886F70D16949 */16950var forge = __nccwpck_require__(9177);16951__nccwpck_require__(8339);16952__nccwpck_require__(1925);16953/* ASN.1 API */16954var asn1 = module.exports = forge.asn1 = forge.asn1 || {};16955/**16956 * ASN.1 classes.16957 */16958asn1.Class = {16959 UNIVERSAL: 0x00,16960 APPLICATION: 0x40,16961 CONTEXT_SPECIFIC: 0x80,16962 PRIVATE: 0xC016963};16964/**16965 * ASN.1 types. Not all types are supported by this implementation, only16966 * those necessary to implement a simple PKI are implemented.16967 */16968asn1.Type = {16969 NONE: 0,16970 BOOLEAN: 1,16971 INTEGER: 2,16972 BITSTRING: 3,16973 OCTETSTRING: 4,16974 NULL: 5,16975 OID: 6,16976 ODESC: 7,16977 EXTERNAL: 8,16978 REAL: 9,16979 ENUMERATED: 10,16980 EMBEDDED: 11,16981 UTF8: 12,16982 ROID: 13,16983 SEQUENCE: 16,16984 SET: 17,16985 PRINTABLESTRING: 19,16986 IA5STRING: 22,16987 UTCTIME: 23,16988 GENERALIZEDTIME: 24,16989 BMPSTRING: 3016990};16991/**16992 * Creates a new asn1 object.16993 *16994 * @param tagClass the tag class for the object.16995 * @param type the data type (tag number) for the object.16996 * @param constructed true if the asn1 object is in constructed form.16997 * @param value the value for the object, if it is not constructed.16998 * @param [options] the options to use:16999 * [bitStringContents] the plain BIT STRING content including padding17000 * byte.17001 *17002 * @return the asn1 object.17003 */17004asn1.create = function(tagClass, type, constructed, value, options) {17005 /* An asn1 object has a tagClass, a type, a constructed flag, and a17006 value. The value's type depends on the constructed flag. If17007 constructed, it will contain a list of other asn1 objects. If not,17008 it will contain the ASN.1 value as an array of bytes formatted17009 according to the ASN.1 data type. */17010 // remove undefined values17011 if(forge.util.isArray(value)) {17012 var tmp = [];17013 for(var i = 0; i < value.length; ++i) {17014 if(value[i] !== undefined) {17015 tmp.push(value[i]);17016 }17017 }17018 value = tmp;17019 }17020 var obj = {17021 tagClass: tagClass,17022 type: type,17023 constructed: constructed,17024 composed: constructed || forge.util.isArray(value),17025 value: value17026 };17027 if(options && 'bitStringContents' in options) {17028 // TODO: copy byte buffer if it's a buffer not a string17029 obj.bitStringContents = options.bitStringContents;17030 // TODO: add readonly flag to avoid this overhead17031 // save copy to detect changes17032 obj.original = asn1.copy(obj);17033 }17034 return obj;17035};17036/**17037 * Copies an asn1 object.17038 *17039 * @param obj the asn1 object.17040 * @param [options] copy options:17041 * [excludeBitStringContents] true to not copy bitStringContents17042 *17043 * @return the a copy of the asn1 object.17044 */17045asn1.copy = function(obj, options) {17046 var copy;17047 if(forge.util.isArray(obj)) {17048 copy = [];17049 for(var i = 0; i < obj.length; ++i) {17050 copy.push(asn1.copy(obj[i], options));17051 }17052 return copy;17053 }17054 if(typeof obj === 'string') {17055 // TODO: copy byte buffer if it's a buffer not a string17056 return obj;17057 }17058 copy = {17059 tagClass: obj.tagClass,17060 type: obj.type,17061 constructed: obj.constructed,17062 composed: obj.composed,17063 value: asn1.copy(obj.value, options)17064 };17065 if(options && !options.excludeBitStringContents) {17066 // TODO: copy byte buffer if it's a buffer not a string17067 copy.bitStringContents = obj.bitStringContents;17068 }17069 return copy;17070};17071/**17072 * Compares asn1 objects for equality.17073 *17074 * Note this function does not run in constant time.17075 *17076 * @param obj1 the first asn1 object.17077 * @param obj2 the second asn1 object.17078 * @param [options] compare options:17079 * [includeBitStringContents] true to compare bitStringContents17080 *17081 * @return true if the asn1 objects are equal.17082 */17083asn1.equals = function(obj1, obj2, options) {17084 if(forge.util.isArray(obj1)) {17085 if(!forge.util.isArray(obj2)) {17086 return false;17087 }17088 if(obj1.length !== obj2.length) {17089 return false;17090 }17091 for(var i = 0; i < obj1.length; ++i) {17092 if(!asn1.equals(obj1[i], obj2[i])) {17093 return false;17094 }17095 }17096 return true;17097 }17098 if(typeof obj1 !== typeof obj2) {17099 return false;17100 }17101 if(typeof obj1 === 'string') {17102 return obj1 === obj2;17103 }17104 var equal = obj1.tagClass === obj2.tagClass &&17105 obj1.type === obj2.type &&17106 obj1.constructed === obj2.constructed &&17107 obj1.composed === obj2.composed &&17108 asn1.equals(obj1.value, obj2.value);17109 if(options && options.includeBitStringContents) {17110 equal = equal && (obj1.bitStringContents === obj2.bitStringContents);17111 }17112 return equal;17113};17114/**17115 * Gets the length of a BER-encoded ASN.1 value.17116 *17117 * In case the length is not specified, undefined is returned.17118 *17119 * @param b the BER-encoded ASN.1 byte buffer, starting with the first17120 * length byte.17121 *17122 * @return the length of the BER-encoded ASN.1 value or undefined.17123 */17124asn1.getBerValueLength = function(b) {17125 // TODO: move this function and related DER/BER functions to a der.js17126 // file; better abstract ASN.1 away from der/ber.17127 var b2 = b.getByte();17128 if(b2 === 0x80) {17129 return undefined;17130 }17131 // see if the length is "short form" or "long form" (bit 8 set)17132 var length;17133 var longForm = b2 & 0x80;17134 if(!longForm) {17135 // length is just the first byte17136 length = b2;17137 } else {17138 // the number of bytes the length is specified in bits 7 through 117139 // and each length byte is in big-endian base-25617140 length = b.getInt((b2 & 0x7F) << 3);17141 }17142 return length;17143};17144/**17145 * Check if the byte buffer has enough bytes. Throws an Error if not.17146 *17147 * @param bytes the byte buffer to parse from.17148 * @param remaining the bytes remaining in the current parsing state.17149 * @param n the number of bytes the buffer must have.17150 */17151function _checkBufferLength(bytes, remaining, n) {17152 if(n > remaining) {17153 var error = new Error('Too few bytes to parse DER.');17154 error.available = bytes.length();17155 error.remaining = remaining;17156 error.requested = n;17157 throw error;17158 }17159}17160/**17161 * Gets the length of a BER-encoded ASN.1 value.17162 *17163 * In case the length is not specified, undefined is returned.17164 *17165 * @param bytes the byte buffer to parse from.17166 * @param remaining the bytes remaining in the current parsing state.17167 *17168 * @return the length of the BER-encoded ASN.1 value or undefined.17169 */17170var _getValueLength = function(bytes, remaining) {17171 // TODO: move this function and related DER/BER functions to a der.js17172 // file; better abstract ASN.1 away from der/ber.17173 // fromDer already checked that this byte exists17174 var b2 = bytes.getByte();17175 remaining--;17176 if(b2 === 0x80) {17177 return undefined;17178 }17179 // see if the length is "short form" or "long form" (bit 8 set)17180 var length;17181 var longForm = b2 & 0x80;17182 if(!longForm) {17183 // length is just the first byte17184 length = b2;17185 } else {17186 // the number of bytes the length is specified in bits 7 through 117187 // and each length byte is in big-endian base-25617188 var longFormBytes = b2 & 0x7F;17189 _checkBufferLength(bytes, remaining, longFormBytes);17190 length = bytes.getInt(longFormBytes << 3);17191 }17192 // FIXME: this will only happen for 32 bit getInt with high bit set17193 if(length < 0) {17194 throw new Error('Negative length: ' + length);17195 }17196 return length;17197};17198/**17199 * Parses an asn1 object from a byte buffer in DER format.17200 *17201 * @param bytes the byte buffer to parse from.17202 * @param [strict] true to be strict when checking value lengths, false to17203 * allow truncated values (default: true).17204 * @param [options] object with options or boolean strict flag17205 * [strict] true to be strict when checking value lengths, false to17206 * allow truncated values (default: true).17207 * [parseAllBytes] true to ensure all bytes are parsed17208 * (default: true)17209 * [decodeBitStrings] true to attempt to decode the content of17210 * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that17211 * without schema support to understand the data context this can17212 * erroneously decode values that happen to be valid ASN.1. This17213 * flag will be deprecated or removed as soon as schema support is17214 * available. (default: true)17215 *17216 * @throws Will throw an error for various malformed input conditions.17217 *17218 * @return the parsed asn1 object.17219 */17220asn1.fromDer = function(bytes, options) {17221 if(options === undefined) {17222 options = {17223 strict: true,17224 parseAllBytes: true,17225 decodeBitStrings: true17226 };17227 }17228 if(typeof options === 'boolean') {17229 options = {17230 strict: options,17231 parseAllBytes: true,17232 decodeBitStrings: true17233 };17234 }17235 if(!('strict' in options)) {17236 options.strict = true;17237 }17238 if(!('parseAllBytes' in options)) {17239 options.parseAllBytes = true;17240 }17241 if(!('decodeBitStrings' in options)) {17242 options.decodeBitStrings = true;17243 }17244 // wrap in buffer if needed17245 if(typeof bytes === 'string') {17246 bytes = forge.util.createBuffer(bytes);17247 }17248 var byteCount = bytes.length();17249 var value = _fromDer(bytes, bytes.length(), 0, options);17250 if(options.parseAllBytes && bytes.length() !== 0) {17251 var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');17252 error.byteCount = byteCount;17253 error.remaining = bytes.length();17254 throw error;17255 }17256 return value;17257};17258/**17259 * Internal function to parse an asn1 object from a byte buffer in DER format.17260 *17261 * @param bytes the byte buffer to parse from.17262 * @param remaining the number of bytes remaining for this chunk.17263 * @param depth the current parsing depth.17264 * @param options object with same options as fromDer().17265 *17266 * @return the parsed asn1 object.17267 */17268function _fromDer(bytes, remaining, depth, options) {17269 // temporary storage for consumption calculations17270 var start;17271 // minimum length for ASN.1 DER structure is 217272 _checkBufferLength(bytes, remaining, 2);17273 // get the first byte17274 var b1 = bytes.getByte();17275 // consumed one byte17276 remaining--;17277 // get the tag class17278 var tagClass = (b1 & 0xC0);17279 // get the type (bits 1-5)17280 var type = b1 & 0x1F;17281 // get the variable value length and adjust remaining bytes17282 start = bytes.length();17283 var length = _getValueLength(bytes, remaining);17284 remaining -= start - bytes.length();17285 // ensure there are enough bytes to get the value17286 if(length !== undefined && length > remaining) {17287 if(options.strict) {17288 var error = new Error('Too few bytes to read ASN.1 value.');17289 error.available = bytes.length();17290 error.remaining = remaining;17291 error.requested = length;17292 throw error;17293 }17294 // Note: be lenient with truncated values and use remaining state bytes17295 length = remaining;17296 }17297 // value storage17298 var value;17299 // possible BIT STRING contents storage17300 var bitStringContents;17301 // constructed flag is bit 6 (32 = 0x20) of the first byte17302 var constructed = ((b1 & 0x20) === 0x20);17303 if(constructed) {17304 // parse child asn1 objects from the value17305 value = [];17306 if(length === undefined) {17307 // asn1 object of indefinite length, read until end tag17308 for(;;) {17309 _checkBufferLength(bytes, remaining, 2);17310 if(bytes.bytes(2) === String.fromCharCode(0, 0)) {17311 bytes.getBytes(2);17312 remaining -= 2;17313 break;17314 }17315 start = bytes.length();17316 value.push(_fromDer(bytes, remaining, depth + 1, options));17317 remaining -= start - bytes.length();17318 }17319 } else {17320 // parsing asn1 object of definite length17321 while(length > 0) {17322 start = bytes.length();17323 value.push(_fromDer(bytes, length, depth + 1, options));17324 remaining -= start - bytes.length();17325 length -= start - bytes.length();17326 }17327 }17328 }17329 // if a BIT STRING, save the contents including padding17330 if(value === undefined && tagClass === asn1.Class.UNIVERSAL &&17331 type === asn1.Type.BITSTRING) {17332 bitStringContents = bytes.bytes(length);17333 }17334 // determine if a non-constructed value should be decoded as a composed17335 // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)17336 // can be used this way.17337 if(value === undefined && options.decodeBitStrings &&17338 tagClass === asn1.Class.UNIVERSAL &&17339 // FIXME: OCTET STRINGs not yet supported here17340 // .. other parts of forge expect to decode OCTET STRINGs manually17341 (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&17342 length > 1) {17343 // save read position17344 var savedRead = bytes.read;17345 var savedRemaining = remaining;17346 var unused = 0;17347 if(type === asn1.Type.BITSTRING) {17348 /* The first octet gives the number of bits by which the length of the17349 bit string is less than the next multiple of eight (this is called17350 the "number of unused bits").17351 The second and following octets give the value of the bit string17352 converted to an octet string. */17353 _checkBufferLength(bytes, remaining, 1);17354 unused = bytes.getByte();17355 remaining--;17356 }17357 // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs17358 if(unused === 0) {17359 try {17360 // attempt to parse child asn1 object from the value17361 // (stored in array to signal composed value)17362 start = bytes.length();17363 var subOptions = {17364 // enforce strict mode to avoid parsing ASN.1 from plain data17365 strict: true,17366 decodeBitStrings: true17367 };17368 var composed = _fromDer(bytes, remaining, depth + 1, subOptions);17369 var used = start - bytes.length();17370 remaining -= used;17371 if(type == asn1.Type.BITSTRING) {17372 used++;17373 }17374 // if the data all decoded and the class indicates UNIVERSAL or17375 // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object17376 var tc = composed.tagClass;17377 if(used === length &&17378 (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) {17379 value = [composed];17380 }17381 } catch(ex) {17382 }17383 }17384 if(value === undefined) {17385 // restore read position17386 bytes.read = savedRead;17387 remaining = savedRemaining;17388 }17389 }17390 if(value === undefined) {17391 // asn1 not constructed or composed, get raw value17392 // TODO: do DER to OID conversion and vice-versa in .toDer?17393 if(length === undefined) {17394 if(options.strict) {17395 throw new Error('Non-constructed ASN.1 object of indefinite length.');17396 }17397 // be lenient and use remaining state bytes17398 length = remaining;17399 }17400 if(type === asn1.Type.BMPSTRING) {17401 value = '';17402 for(; length > 0; length -= 2) {17403 _checkBufferLength(bytes, remaining, 2);17404 value += String.fromCharCode(bytes.getInt16());17405 remaining -= 2;17406 }17407 } else {17408 value = bytes.getBytes(length);17409 remaining -= length;17410 }17411 }17412 // add BIT STRING contents if available17413 var asn1Options = bitStringContents === undefined ? null : {17414 bitStringContents: bitStringContents17415 };17416 // create and return asn1 object17417 return asn1.create(tagClass, type, constructed, value, asn1Options);17418}17419/**17420 * Converts the given asn1 object to a buffer of bytes in DER format.17421 *17422 * @param asn1 the asn1 object to convert to bytes.17423 *17424 * @return the buffer of bytes.17425 */17426asn1.toDer = function(obj) {17427 var bytes = forge.util.createBuffer();17428 // build the first byte17429 var b1 = obj.tagClass | obj.type;17430 // for storing the ASN.1 value17431 var value = forge.util.createBuffer();17432 // use BIT STRING contents if available and data not changed17433 var useBitStringContents = false;17434 if('bitStringContents' in obj) {17435 useBitStringContents = true;17436 if(obj.original) {17437 useBitStringContents = asn1.equals(obj, obj.original);17438 }17439 }17440 if(useBitStringContents) {17441 value.putBytes(obj.bitStringContents);17442 } else if(obj.composed) {17443 // if composed, use each child asn1 object's DER bytes as value17444 // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed17445 // from other asn1 objects17446 if(obj.constructed) {17447 b1 |= 0x20;17448 } else {17449 // type is a bit string, add unused bits of 0x0017450 value.putByte(0x00);17451 }17452 // add all of the child DER bytes together17453 for(var i = 0; i < obj.value.length; ++i) {17454 if(obj.value[i] !== undefined) {17455 value.putBuffer(asn1.toDer(obj.value[i]));17456 }17457 }17458 } else {17459 // use asn1.value directly17460 if(obj.type === asn1.Type.BMPSTRING) {17461 for(var i = 0; i < obj.value.length; ++i) {17462 value.putInt16(obj.value.charCodeAt(i));17463 }17464 } else {17465 // ensure integer is minimally-encoded17466 // TODO: should all leading bytes be stripped vs just one?17467 // .. ex '00 00 01' => '01'?17468 if(obj.type === asn1.Type.INTEGER &&17469 obj.value.length > 1 &&17470 // leading 0x00 for positive integer17471 ((obj.value.charCodeAt(0) === 0 &&17472 (obj.value.charCodeAt(1) & 0x80) === 0) ||17473 // leading 0xFF for negative integer17474 (obj.value.charCodeAt(0) === 0xFF &&17475 (obj.value.charCodeAt(1) & 0x80) === 0x80))) {17476 value.putBytes(obj.value.substr(1));17477 } else {17478 value.putBytes(obj.value);17479 }17480 }17481 }17482 // add tag byte17483 bytes.putByte(b1);17484 // use "short form" encoding17485 if(value.length() <= 127) {17486 // one byte describes the length17487 // bit 8 = 0 and bits 7-1 = length17488 bytes.putByte(value.length() & 0x7F);17489 } else {17490 // use "long form" encoding17491 // 2 to 127 bytes describe the length17492 // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes17493 // other bytes: length in base 256, big-endian17494 var len = value.length();17495 var lenBytes = '';17496 do {17497 lenBytes += String.fromCharCode(len & 0xFF);17498 len = len >>> 8;17499 } while(len > 0);17500 // set first byte to # bytes used to store the length and turn on17501 // bit 8 to indicate long-form length is used17502 bytes.putByte(lenBytes.length | 0x80);17503 // concatenate length bytes in reverse since they were generated17504 // little endian and we need big endian17505 for(var i = lenBytes.length - 1; i >= 0; --i) {17506 bytes.putByte(lenBytes.charCodeAt(i));17507 }17508 }17509 // concatenate value bytes17510 bytes.putBuffer(value);17511 return bytes;17512};17513/**17514 * Converts an OID dot-separated string to a byte buffer. The byte buffer17515 * contains only the DER-encoded value, not any tag or length bytes.17516 *17517 * @param oid the OID dot-separated string.17518 *17519 * @return the byte buffer.17520 */17521asn1.oidToDer = function(oid) {17522 // split OID into individual values17523 var values = oid.split('.');17524 var bytes = forge.util.createBuffer();17525 // first byte is 40 * value1 + value217526 bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));17527 // other bytes are each value in base 128 with 8th bit set except for17528 // the last byte for each value17529 var last, valueBytes, value, b;17530 for(var i = 2; i < values.length; ++i) {17531 // produce value bytes in reverse because we don't know how many17532 // bytes it will take to store the value17533 last = true;17534 valueBytes = [];17535 value = parseInt(values[i], 10);17536 do {17537 b = value & 0x7F;17538 value = value >>> 7;17539 // if value is not last, then turn on 8th bit17540 if(!last) {17541 b |= 0x80;17542 }17543 valueBytes.push(b);17544 last = false;17545 } while(value > 0);17546 // add value bytes in reverse (needs to be in big endian)17547 for(var n = valueBytes.length - 1; n >= 0; --n) {17548 bytes.putByte(valueBytes[n]);17549 }17550 }17551 return bytes;17552};17553/**17554 * Converts a DER-encoded byte buffer to an OID dot-separated string. The17555 * byte buffer should contain only the DER-encoded value, not any tag or17556 * length bytes.17557 *17558 * @param bytes the byte buffer.17559 *17560 * @return the OID dot-separated string.17561 */17562asn1.derToOid = function(bytes) {17563 var oid;17564 // wrap in buffer if needed17565 if(typeof bytes === 'string') {17566 bytes = forge.util.createBuffer(bytes);17567 }17568 // first byte is 40 * value1 + value217569 var b = bytes.getByte();17570 oid = Math.floor(b / 40) + '.' + (b % 40);17571 // other bytes are each value in base 128 with 8th bit set except for17572 // the last byte for each value17573 var value = 0;17574 while(bytes.length() > 0) {17575 b = bytes.getByte();17576 value = value << 7;17577 // not the last byte for the value17578 if(b & 0x80) {17579 value += b & 0x7F;17580 } else {17581 // last byte17582 oid += '.' + (value + b);17583 value = 0;17584 }17585 }17586 return oid;17587};17588/**17589 * Converts a UTCTime value to a date.17590 *17591 * Note: GeneralizedTime has 4 digits for the year and is used for X.50917592 * dates past 2049. Parsing that structure hasn't been implemented yet.17593 *17594 * @param utc the UTCTime value to convert.17595 *17596 * @return the date.17597 */17598asn1.utcTimeToDate = function(utc) {17599 /* The following formats can be used:17600 YYMMDDhhmmZ17601 YYMMDDhhmm+hh'mm'17602 YYMMDDhhmm-hh'mm'17603 YYMMDDhhmmssZ17604 YYMMDDhhmmss+hh'mm'17605 YYMMDDhhmmss-hh'mm'17606 Where:17607 YY is the least significant two digits of the year17608 MM is the month (01 to 12)17609 DD is the day (01 to 31)17610 hh is the hour (00 to 23)17611 mm are the minutes (00 to 59)17612 ss are the seconds (00 to 59)17613 Z indicates that local time is GMT, + indicates that local time is17614 later than GMT, and - indicates that local time is earlier than GMT17615 hh' is the absolute value of the offset from GMT in hours17616 mm' is the absolute value of the offset from GMT in minutes */17617 var date = new Date();17618 // if YY >= 50 use 19xx, if YY < 50 use 20xx17619 var year = parseInt(utc.substr(0, 2), 10);17620 year = (year >= 50) ? 1900 + year : 2000 + year;17621 var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month17622 var DD = parseInt(utc.substr(4, 2), 10);17623 var hh = parseInt(utc.substr(6, 2), 10);17624 var mm = parseInt(utc.substr(8, 2), 10);17625 var ss = 0;17626 // not just YYMMDDhhmmZ17627 if(utc.length > 11) {17628 // get character after minutes17629 var c = utc.charAt(10);17630 var end = 10;17631 // see if seconds are present17632 if(c !== '+' && c !== '-') {17633 // get seconds17634 ss = parseInt(utc.substr(10, 2), 10);17635 end += 2;17636 }17637 }17638 // update date17639 date.setUTCFullYear(year, MM, DD);17640 date.setUTCHours(hh, mm, ss, 0);17641 if(end) {17642 // get +/- after end of time17643 c = utc.charAt(end);17644 if(c === '+' || c === '-') {17645 // get hours+minutes offset17646 var hhoffset = parseInt(utc.substr(end + 1, 2), 10);17647 var mmoffset = parseInt(utc.substr(end + 4, 2), 10);17648 // calculate offset in milliseconds17649 var offset = hhoffset * 60 + mmoffset;17650 offset *= 60000;17651 // apply offset17652 if(c === '+') {17653 date.setTime(+date - offset);17654 } else {17655 date.setTime(+date + offset);17656 }17657 }17658 }17659 return date;17660};17661/**17662 * Converts a GeneralizedTime value to a date.17663 *17664 * @param gentime the GeneralizedTime value to convert.17665 *17666 * @return the date.17667 */17668asn1.generalizedTimeToDate = function(gentime) {17669 /* The following formats can be used:17670 YYYYMMDDHHMMSS17671 YYYYMMDDHHMMSS.fff17672 YYYYMMDDHHMMSSZ17673 YYYYMMDDHHMMSS.fffZ17674 YYYYMMDDHHMMSS+hh'mm'17675 YYYYMMDDHHMMSS.fff+hh'mm'17676 YYYYMMDDHHMMSS-hh'mm'17677 YYYYMMDDHHMMSS.fff-hh'mm'17678 Where:17679 YYYY is the year17680 MM is the month (01 to 12)17681 DD is the day (01 to 31)17682 hh is the hour (00 to 23)17683 mm are the minutes (00 to 59)17684 ss are the seconds (00 to 59)17685 .fff is the second fraction, accurate to three decimal places17686 Z indicates that local time is GMT, + indicates that local time is17687 later than GMT, and - indicates that local time is earlier than GMT17688 hh' is the absolute value of the offset from GMT in hours17689 mm' is the absolute value of the offset from GMT in minutes */17690 var date = new Date();17691 var YYYY = parseInt(gentime.substr(0, 4), 10);17692 var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month17693 var DD = parseInt(gentime.substr(6, 2), 10);17694 var hh = parseInt(gentime.substr(8, 2), 10);17695 var mm = parseInt(gentime.substr(10, 2), 10);17696 var ss = parseInt(gentime.substr(12, 2), 10);17697 var fff = 0;17698 var offset = 0;17699 var isUTC = false;17700 if(gentime.charAt(gentime.length - 1) === 'Z') {17701 isUTC = true;17702 }17703 var end = gentime.length - 5, c = gentime.charAt(end);17704 if(c === '+' || c === '-') {17705 // get hours+minutes offset17706 var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);17707 var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);17708 // calculate offset in milliseconds17709 offset = hhoffset * 60 + mmoffset;17710 offset *= 60000;17711 // apply offset17712 if(c === '+') {17713 offset *= -1;17714 }17715 isUTC = true;17716 }17717 // check for second fraction17718 if(gentime.charAt(14) === '.') {17719 fff = parseFloat(gentime.substr(14), 10) * 1000;17720 }17721 if(isUTC) {17722 date.setUTCFullYear(YYYY, MM, DD);17723 date.setUTCHours(hh, mm, ss, fff);17724 // apply offset17725 date.setTime(+date + offset);17726 } else {17727 date.setFullYear(YYYY, MM, DD);17728 date.setHours(hh, mm, ss, fff);17729 }17730 return date;17731};17732/**17733 * Converts a date to a UTCTime value.17734 *17735 * Note: GeneralizedTime has 4 digits for the year and is used for X.50917736 * dates past 2049. Converting to a GeneralizedTime hasn't been17737 * implemented yet.17738 *17739 * @param date the date to convert.17740 *17741 * @return the UTCTime value.17742 */17743asn1.dateToUtcTime = function(date) {17744 // TODO: validate; currently assumes proper format17745 if(typeof date === 'string') {17746 return date;17747 }17748 var rval = '';17749 // create format YYMMDDhhmmssZ17750 var format = [];17751 format.push(('' + date.getUTCFullYear()).substr(2));17752 format.push('' + (date.getUTCMonth() + 1));17753 format.push('' + date.getUTCDate());17754 format.push('' + date.getUTCHours());17755 format.push('' + date.getUTCMinutes());17756 format.push('' + date.getUTCSeconds());17757 // ensure 2 digits are used for each format entry17758 for(var i = 0; i < format.length; ++i) {17759 if(format[i].length < 2) {17760 rval += '0';17761 }17762 rval += format[i];17763 }17764 rval += 'Z';17765 return rval;17766};17767/**17768 * Converts a date to a GeneralizedTime value.17769 *17770 * @param date the date to convert.17771 *17772 * @return the GeneralizedTime value as a string.17773 */17774asn1.dateToGeneralizedTime = function(date) {17775 // TODO: validate; currently assumes proper format17776 if(typeof date === 'string') {17777 return date;17778 }17779 var rval = '';17780 // create format YYYYMMDDHHMMSSZ17781 var format = [];17782 format.push('' + date.getUTCFullYear());17783 format.push('' + (date.getUTCMonth() + 1));17784 format.push('' + date.getUTCDate());17785 format.push('' + date.getUTCHours());17786 format.push('' + date.getUTCMinutes());17787 format.push('' + date.getUTCSeconds());17788 // ensure 2 digits are used for each format entry17789 for(var i = 0; i < format.length; ++i) {17790 if(format[i].length < 2) {17791 rval += '0';17792 }17793 rval += format[i];17794 }17795 rval += 'Z';17796 return rval;17797};17798/**17799 * Converts a javascript integer to a DER-encoded byte buffer to be used17800 * as the value for an INTEGER type.17801 *17802 * @param x the integer.17803 *17804 * @return the byte buffer.17805 */17806asn1.integerToDer = function(x) {17807 var rval = forge.util.createBuffer();17808 if(x >= -0x80 && x < 0x80) {17809 return rval.putSignedInt(x, 8);17810 }17811 if(x >= -0x8000 && x < 0x8000) {17812 return rval.putSignedInt(x, 16);17813 }17814 if(x >= -0x800000 && x < 0x800000) {17815 return rval.putSignedInt(x, 24);17816 }17817 if(x >= -0x80000000 && x < 0x80000000) {17818 return rval.putSignedInt(x, 32);17819 }17820 var error = new Error('Integer too large; max is 32-bits.');17821 error.integer = x;17822 throw error;17823};17824/**17825 * Converts a DER-encoded byte buffer to a javascript integer. This is17826 * typically used to decode the value of an INTEGER type.17827 *17828 * @param bytes the byte buffer.17829 *17830 * @return the integer.17831 */17832asn1.derToInteger = function(bytes) {17833 // wrap in buffer if needed17834 if(typeof bytes === 'string') {17835 bytes = forge.util.createBuffer(bytes);17836 }17837 var n = bytes.length() * 8;17838 if(n > 32) {17839 throw new Error('Integer too large; max is 32-bits.');17840 }17841 return bytes.getSignedInt(n);17842};17843/**17844 * Validates that the given ASN.1 object is at least a super set of the17845 * given ASN.1 structure. Only tag classes and types are checked. An17846 * optional map may also be provided to capture ASN.1 values while the17847 * structure is checked.17848 *17849 * To capture an ASN.1 value, set an object in the validator's 'capture'17850 * parameter to the key to use in the capture map. To capture the full17851 * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including17852 * the leading unused bits counter byte, specify 'captureBitStringContents'.17853 * To capture BIT STRING bytes, without the leading unused bits counter byte,17854 * specify 'captureBitStringValue'.17855 *17856 * Objects in the validator may set a field 'optional' to true to indicate17857 * that it isn't necessary to pass validation.17858 *17859 * @param obj the ASN.1 object to validate.17860 * @param v the ASN.1 structure validator.17861 * @param capture an optional map to capture values in.17862 * @param errors an optional array for storing validation errors.17863 *17864 * @return true on success, false on failure.17865 */17866asn1.validate = function(obj, v, capture, errors) {17867 var rval = false;17868 // ensure tag class and type are the same if specified17869 if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&17870 (obj.type === v.type || typeof(v.type) === 'undefined')) {17871 // ensure constructed flag is the same if specified17872 if(obj.constructed === v.constructed ||17873 typeof(v.constructed) === 'undefined') {17874 rval = true;17875 // handle sub values17876 if(v.value && forge.util.isArray(v.value)) {17877 var j = 0;17878 for(var i = 0; rval && i < v.value.length; ++i) {17879 rval = v.value[i].optional || false;17880 if(obj.value[j]) {17881 rval = asn1.validate(obj.value[j], v.value[i], capture, errors);17882 if(rval) {17883 ++j;17884 } else if(v.value[i].optional) {17885 rval = true;17886 }17887 }17888 if(!rval && errors) {17889 errors.push(17890 '[' + v.name + '] ' +17891 'Tag class "' + v.tagClass + '", type "' +17892 v.type + '" expected value length "' +17893 v.value.length + '", got "' +17894 obj.value.length + '"');17895 }17896 }17897 }17898 if(rval && capture) {17899 if(v.capture) {17900 capture[v.capture] = obj.value;17901 }17902 if(v.captureAsn1) {17903 capture[v.captureAsn1] = obj;17904 }17905 if(v.captureBitStringContents && 'bitStringContents' in obj) {17906 capture[v.captureBitStringContents] = obj.bitStringContents;17907 }17908 if(v.captureBitStringValue && 'bitStringContents' in obj) {17909 var value;17910 if(obj.bitStringContents.length < 2) {17911 capture[v.captureBitStringValue] = '';17912 } else {17913 // FIXME: support unused bits with data shifting17914 var unused = obj.bitStringContents.charCodeAt(0);17915 if(unused !== 0) {17916 throw new Error(17917 'captureBitStringValue only supported for zero unused bits');17918 }17919 capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);17920 }17921 }17922 }17923 } else if(errors) {17924 errors.push(17925 '[' + v.name + '] ' +17926 'Expected constructed "' + v.constructed + '", got "' +17927 obj.constructed + '"');17928 }17929 } else if(errors) {17930 if(obj.tagClass !== v.tagClass) {17931 errors.push(17932 '[' + v.name + '] ' +17933 'Expected tag class "' + v.tagClass + '", got "' +17934 obj.tagClass + '"');17935 }17936 if(obj.type !== v.type) {17937 errors.push(17938 '[' + v.name + '] ' +17939 'Expected type "' + v.type + '", got "' + obj.type + '"');17940 }17941 }17942 return rval;17943};17944// regex for testing for non-latin characters17945var _nonLatinRegex = /[^\\u0000-\\u00ff]/;17946/**17947 * Pretty prints an ASN.1 object to a string.17948 *17949 * @param obj the object to write out.17950 * @param level the level in the tree.17951 * @param indentation the indentation to use.17952 *17953 * @return the string.17954 */17955asn1.prettyPrint = function(obj, level, indentation) {17956 var rval = '';17957 // set default level and indentation17958 level = level || 0;17959 indentation = indentation || 2;17960 // start new line for deep levels17961 if(level > 0) {17962 rval += '\n';17963 }17964 // create indent17965 var indent = '';17966 for(var i = 0; i < level * indentation; ++i) {17967 indent += ' ';17968 }17969 // print class:type17970 rval += indent + 'Tag: ';17971 switch(obj.tagClass) {17972 case asn1.Class.UNIVERSAL:17973 rval += 'Universal:';17974 break;17975 case asn1.Class.APPLICATION:17976 rval += 'Application:';17977 break;17978 case asn1.Class.CONTEXT_SPECIFIC:17979 rval += 'Context-Specific:';17980 break;17981 case asn1.Class.PRIVATE:17982 rval += 'Private:';17983 break;17984 }17985 if(obj.tagClass === asn1.Class.UNIVERSAL) {17986 rval += obj.type;17987 // known types17988 switch(obj.type) {17989 case asn1.Type.NONE:17990 rval += ' (None)';17991 break;17992 case asn1.Type.BOOLEAN:17993 rval += ' (Boolean)';17994 break;17995 case asn1.Type.INTEGER:17996 rval += ' (Integer)';17997 break;17998 case asn1.Type.BITSTRING:17999 rval += ' (Bit string)';18000 break;18001 case asn1.Type.OCTETSTRING:18002 rval += ' (Octet string)';18003 break;18004 case asn1.Type.NULL:18005 rval += ' (Null)';18006 break;18007 case asn1.Type.OID:18008 rval += ' (Object Identifier)';18009 break;18010 case asn1.Type.ODESC:18011 rval += ' (Object Descriptor)';18012 break;18013 case asn1.Type.EXTERNAL:18014 rval += ' (External or Instance of)';18015 break;18016 case asn1.Type.REAL:18017 rval += ' (Real)';18018 break;18019 case asn1.Type.ENUMERATED:18020 rval += ' (Enumerated)';18021 break;18022 case asn1.Type.EMBEDDED:18023 rval += ' (Embedded PDV)';18024 break;18025 case asn1.Type.UTF8:18026 rval += ' (UTF8)';18027 break;18028 case asn1.Type.ROID:18029 rval += ' (Relative Object Identifier)';18030 break;18031 case asn1.Type.SEQUENCE:18032 rval += ' (Sequence)';18033 break;18034 case asn1.Type.SET:18035 rval += ' (Set)';18036 break;18037 case asn1.Type.PRINTABLESTRING:18038 rval += ' (Printable String)';18039 break;18040 case asn1.Type.IA5String:18041 rval += ' (IA5String (ASCII))';18042 break;18043 case asn1.Type.UTCTIME:18044 rval += ' (UTC time)';18045 break;18046 case asn1.Type.GENERALIZEDTIME:18047 rval += ' (Generalized time)';18048 break;18049 case asn1.Type.BMPSTRING:18050 rval += ' (BMP String)';18051 break;18052 }18053 } else {18054 rval += obj.type;18055 }18056 rval += '\n';18057 rval += indent + 'Constructed: ' + obj.constructed + '\n';18058 if(obj.composed) {18059 var subvalues = 0;18060 var sub = '';18061 for(var i = 0; i < obj.value.length; ++i) {18062 if(obj.value[i] !== undefined) {18063 subvalues += 1;18064 sub += asn1.prettyPrint(obj.value[i], level + 1, indentation);18065 if((i + 1) < obj.value.length) {18066 sub += ',';18067 }18068 }18069 }18070 rval += indent + 'Sub values: ' + subvalues + sub;18071 } else {18072 rval += indent + 'Value: ';18073 if(obj.type === asn1.Type.OID) {18074 var oid = asn1.derToOid(obj.value);18075 rval += oid;18076 if(forge.pki && forge.pki.oids) {18077 if(oid in forge.pki.oids) {18078 rval += ' (' + forge.pki.oids[oid] + ') ';18079 }18080 }18081 }18082 if(obj.type === asn1.Type.INTEGER) {18083 try {18084 rval += asn1.derToInteger(obj.value);18085 } catch(ex) {18086 rval += '0x' + forge.util.bytesToHex(obj.value);18087 }18088 } else if(obj.type === asn1.Type.BITSTRING) {18089 // TODO: shift bits as needed to display without padding18090 if(obj.value.length > 1) {18091 // remove unused bits field18092 rval += '0x' + forge.util.bytesToHex(obj.value.slice(1));18093 } else {18094 rval += '(none)';18095 }18096 // show unused bit count18097 if(obj.value.length > 0) {18098 var unused = obj.value.charCodeAt(0);18099 if(unused == 1) {18100 rval += ' (1 unused bit shown)';18101 } else if(unused > 1) {18102 rval += ' (' + unused + ' unused bits shown)';18103 }18104 }18105 } else if(obj.type === asn1.Type.OCTETSTRING) {18106 if(!_nonLatinRegex.test(obj.value)) {18107 rval += '(' + obj.value + ') ';18108 }18109 rval += '0x' + forge.util.bytesToHex(obj.value);18110 } else if(obj.type === asn1.Type.UTF8) {18111 try {18112 rval += forge.util.decodeUtf8(obj.value);18113 } catch(e) {18114 if(e.message === 'URI malformed') {18115 rval +=18116 '0x' + forge.util.bytesToHex(obj.value) + ' (malformed UTF8)';18117 } else {18118 throw e;18119 }18120 }18121 } else if(obj.type === asn1.Type.PRINTABLESTRING ||18122 obj.type === asn1.Type.IA5String) {18123 rval += obj.value;18124 } else if(_nonLatinRegex.test(obj.value)) {18125 rval += '0x' + forge.util.bytesToHex(obj.value);18126 } else if(obj.value.length === 0) {18127 rval += '[null]';18128 } else {18129 rval += obj.value;18130 }18131 }18132 return rval;18133};18134/***/ }),18135/***/ 2300:18136/***/ ((module) => {18137/**18138 * Base-N/Base-X encoding/decoding functions.18139 *18140 * Original implementation from base-x:18141 * https://github.com/cryptocoinjs/base-x18142 *18143 * Which is MIT licensed:18144 *18145 * The MIT License (MIT)18146 *18147 * Copyright base-x contributors (c) 201618148 *18149 * Permission is hereby granted, free of charge, to any person obtaining a copy18150 * of this software and associated documentation files (the "Software"), to deal18151 * in the Software without restriction, including without limitation the rights18152 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell18153 * copies of the Software, and to permit persons to whom the Software is18154 * furnished to do so, subject to the following conditions:18155 *18156 * The above copyright notice and this permission notice shall be included in18157 * all copies or substantial portions of the Software.18158 *18159 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR18160 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18161 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18162 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18163 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING18164 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER18165 * DEALINGS IN THE SOFTWARE.18166 */18167var api = {};18168module.exports = api;18169// baseN alphabet indexes18170var _reverseAlphabets = {};18171/**18172 * BaseN-encodes a Uint8Array using the given alphabet.18173 *18174 * @param input the Uint8Array to encode.18175 * @param maxline the maximum number of encoded characters per line to use,18176 * defaults to none.18177 *18178 * @return the baseN-encoded output string.18179 */18180api.encode = function(input, alphabet, maxline) {18181 if(typeof alphabet !== 'string') {18182 throw new TypeError('"alphabet" must be a string.');18183 }18184 if(maxline !== undefined && typeof maxline !== 'number') {18185 throw new TypeError('"maxline" must be a number.');18186 }18187 var output = '';18188 if(!(input instanceof Uint8Array)) {18189 // assume forge byte buffer18190 output = _encodeWithByteBuffer(input, alphabet);18191 } else {18192 var i = 0;18193 var base = alphabet.length;18194 var first = alphabet.charAt(0);18195 var digits = [0];18196 for(i = 0; i < input.length; ++i) {18197 for(var j = 0, carry = input[i]; j < digits.length; ++j) {18198 carry += digits[j] << 8;18199 digits[j] = carry % base;18200 carry = (carry / base) | 0;18201 }18202 while(carry > 0) {18203 digits.push(carry % base);18204 carry = (carry / base) | 0;18205 }18206 }18207 // deal with leading zeros18208 for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {18209 output += first;18210 }18211 // convert digits to a string18212 for(i = digits.length - 1; i >= 0; --i) {18213 output += alphabet[digits[i]];18214 }18215 }18216 if(maxline) {18217 var regex = new RegExp('.{1,' + maxline + '}', 'g');18218 output = output.match(regex).join('\r\n');18219 }18220 return output;18221};18222/**18223 * Decodes a baseN-encoded (using the given alphabet) string to a18224 * Uint8Array.18225 *18226 * @param input the baseN-encoded input string.18227 *18228 * @return the Uint8Array.18229 */18230api.decode = function(input, alphabet) {18231 if(typeof input !== 'string') {18232 throw new TypeError('"input" must be a string.');18233 }18234 if(typeof alphabet !== 'string') {18235 throw new TypeError('"alphabet" must be a string.');18236 }18237 var table = _reverseAlphabets[alphabet];18238 if(!table) {18239 // compute reverse alphabet18240 table = _reverseAlphabets[alphabet] = [];18241 for(var i = 0; i < alphabet.length; ++i) {18242 table[alphabet.charCodeAt(i)] = i;18243 }18244 }18245 // remove whitespace characters18246 input = input.replace(/\s/g, '');18247 var base = alphabet.length;18248 var first = alphabet.charAt(0);18249 var bytes = [0];18250 for(var i = 0; i < input.length; i++) {18251 var value = table[input.charCodeAt(i)];18252 if(value === undefined) {18253 return;18254 }18255 for(var j = 0, carry = value; j < bytes.length; ++j) {18256 carry += bytes[j] * base;18257 bytes[j] = carry & 0xff;18258 carry >>= 8;18259 }18260 while(carry > 0) {18261 bytes.push(carry & 0xff);18262 carry >>= 8;18263 }18264 }18265 // deal with leading zeros18266 for(var k = 0; input[k] === first && k < input.length - 1; ++k) {18267 bytes.push(0);18268 }18269 if(typeof Buffer !== 'undefined') {18270 return Buffer.from(bytes.reverse());18271 }18272 return new Uint8Array(bytes.reverse());18273};18274function _encodeWithByteBuffer(input, alphabet) {18275 var i = 0;18276 var base = alphabet.length;18277 var first = alphabet.charAt(0);18278 var digits = [0];18279 for(i = 0; i < input.length(); ++i) {18280 for(var j = 0, carry = input.at(i); j < digits.length; ++j) {18281 carry += digits[j] << 8;18282 digits[j] = carry % base;18283 carry = (carry / base) | 0;18284 }18285 while(carry > 0) {18286 digits.push(carry % base);18287 carry = (carry / base) | 0;18288 }18289 }18290 var output = '';18291 // deal with leading zeros18292 for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {18293 output += first;18294 }18295 // convert digits to a string18296 for(i = digits.length - 1; i >= 0; --i) {18297 output += alphabet[digits[i]];18298 }18299 return output;18300}18301/***/ }),18302/***/ 7088:18303/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {18304/**18305 * Cipher base API.18306 *18307 * @author Dave Longley18308 *18309 * Copyright (c) 2010-2014 Digital Bazaar, Inc.18310 */18311var forge = __nccwpck_require__(9177);18312__nccwpck_require__(8339);18313module.exports = forge.cipher = forge.cipher || {};18314// registered algorithms18315forge.cipher.algorithms = forge.cipher.algorithms || {};18316/**18317 * Creates a cipher object that can be used to encrypt data using the given18318 * algorithm and key. The algorithm may be provided as a string value for a18319 * previously registered algorithm or it may be given as a cipher algorithm18320 * API object.18321 *18322 * @param algorithm the algorithm to use, either a string or an algorithm API18323 * object.18324 * @param key the key to use, as a binary-encoded string of bytes or a18325 * byte buffer.18326 *18327 * @return the cipher.18328 */18329forge.cipher.createCipher = function(algorithm, key) {18330 var api = algorithm;18331 if(typeof api === 'string') {18332 api = forge.cipher.getAlgorithm(api);18333 if(api) {18334 api = api();18335 }18336 }18337 if(!api) {18338 throw new Error('Unsupported algorithm: ' + algorithm);18339 }18340 // assume block cipher18341 return new forge.cipher.BlockCipher({18342 algorithm: api,18343 key: key,18344 decrypt: false18345 });18346};18347/**18348 * Creates a decipher object that can be used to decrypt data using the given18349 * algorithm and key. The algorithm may be provided as a string value for a18350 * previously registered algorithm or it may be given as a cipher algorithm18351 * API object.18352 *18353 * @param algorithm the algorithm to use, either a string or an algorithm API18354 * object.18355 * @param key the key to use, as a binary-encoded string of bytes or a18356 * byte buffer.18357 *18358 * @return the cipher.18359 */18360forge.cipher.createDecipher = function(algorithm, key) {18361 var api = algorithm;18362 if(typeof api === 'string') {18363 api = forge.cipher.getAlgorithm(api);18364 if(api) {18365 api = api();18366 }18367 }18368 if(!api) {18369 throw new Error('Unsupported algorithm: ' + algorithm);18370 }18371 // assume block cipher18372 return new forge.cipher.BlockCipher({18373 algorithm: api,18374 key: key,18375 decrypt: true18376 });18377};18378/**18379 * Registers an algorithm by name. If the name was already registered, the18380 * algorithm API object will be overwritten.18381 *18382 * @param name the name of the algorithm.18383 * @param algorithm the algorithm API object.18384 */18385forge.cipher.registerAlgorithm = function(name, algorithm) {18386 name = name.toUpperCase();18387 forge.cipher.algorithms[name] = algorithm;18388};18389/**18390 * Gets a registered algorithm by name.18391 *18392 * @param name the name of the algorithm.18393 *18394 * @return the algorithm, if found, null if not.18395 */18396forge.cipher.getAlgorithm = function(name) {18397 name = name.toUpperCase();18398 if(name in forge.cipher.algorithms) {18399 return forge.cipher.algorithms[name];18400 }18401 return null;18402};18403var BlockCipher = forge.cipher.BlockCipher = function(options) {18404 this.algorithm = options.algorithm;18405 this.mode = this.algorithm.mode;18406 this.blockSize = this.mode.blockSize;18407 this._finish = false;18408 this._input = null;18409 this.output = null;18410 this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;18411 this._decrypt = options.decrypt;18412 this.algorithm.initialize(options);18413};18414/**18415 * Starts or restarts the encryption or decryption process, whichever18416 * was previously configured.18417 *18418 * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array18419 * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in18420 * bytes, then it must be Nb (16) bytes in length. If the IV is given in as18421 * 32-bit integers, then it must be 4 integers long.18422 *18423 * Note: an IV is not required or used in ECB mode.18424 *18425 * For GCM-mode, the IV must be given as a binary-encoded string of bytes or18426 * a byte buffer. The number of bytes should be 12 (96 bits) as recommended18427 * by NIST SP-800-38D but another length may be given.18428 *18429 * @param options the options to use:18430 * iv the initialization vector to use as a binary-encoded string of18431 * bytes, null to reuse the last ciphered block from a previous18432 * update() (this "residue" method is for legacy support only).18433 * additionalData additional authentication data as a binary-encoded18434 * string of bytes, for 'GCM' mode, (default: none).18435 * tagLength desired length of authentication tag, in bits, for18436 * 'GCM' mode (0-128, default: 128).18437 * tag the authentication tag to check if decrypting, as a18438 * binary-encoded string of bytes.18439 * output the output the buffer to write to, null to create one.18440 */18441BlockCipher.prototype.start = function(options) {18442 options = options || {};18443 var opts = {};18444 for(var key in options) {18445 opts[key] = options[key];18446 }18447 opts.decrypt = this._decrypt;18448 this._finish = false;18449 this._input = forge.util.createBuffer();18450 this.output = options.output || forge.util.createBuffer();18451 this.mode.start(opts);18452};18453/**18454 * Updates the next block according to the cipher mode.18455 *18456 * @param input the buffer to read from.18457 */18458BlockCipher.prototype.update = function(input) {18459 if(input) {18460 // input given, so empty it into the input buffer18461 this._input.putBuffer(input);18462 }18463 // do cipher operation until it needs more input and not finished18464 while(!this._op.call(this.mode, this._input, this.output, this._finish) &&18465 !this._finish) {}18466 // free consumed memory from input buffer18467 this._input.compact();18468};18469/**18470 * Finishes encrypting or decrypting.18471 *18472 * @param pad a padding function to use in CBC mode, null for default,18473 * signature(blockSize, buffer, decrypt).18474 *18475 * @return true if successful, false on error.18476 */18477BlockCipher.prototype.finish = function(pad) {18478 // backwards-compatibility w/deprecated padding API18479 // Note: will overwrite padding functions even after another start() call18480 if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {18481 this.mode.pad = function(input) {18482 return pad(this.blockSize, input, false);18483 };18484 this.mode.unpad = function(output) {18485 return pad(this.blockSize, output, true);18486 };18487 }18488 // build options for padding and afterFinish functions18489 var options = {};18490 options.decrypt = this._decrypt;18491 // get # of bytes that won't fill a block18492 options.overflow = this._input.length() % this.blockSize;18493 if(!this._decrypt && this.mode.pad) {18494 if(!this.mode.pad(this._input, options)) {18495 return false;18496 }18497 }18498 // do final update18499 this._finish = true;18500 this.update();18501 if(this._decrypt && this.mode.unpad) {18502 if(!this.mode.unpad(this.output, options)) {18503 return false;18504 }18505 }18506 if(this.mode.afterFinish) {18507 if(!this.mode.afterFinish(this.output, options)) {18508 return false;18509 }18510 }18511 return true;18512};18513/***/ }),18514/***/ 873:18515/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {18516/**18517 * Supported cipher modes.18518 *18519 * @author Dave Longley18520 *18521 * Copyright (c) 2010-2014 Digital Bazaar, Inc.18522 */18523var forge = __nccwpck_require__(9177);18524__nccwpck_require__(8339);18525forge.cipher = forge.cipher || {};18526// supported cipher modes18527var modes = module.exports = forge.cipher.modes = forge.cipher.modes || {};18528/** Electronic codebook (ECB) (Don't use this; it's not secure) **/18529modes.ecb = function(options) {18530 options = options || {};18531 this.name = 'ECB';18532 this.cipher = options.cipher;18533 this.blockSize = options.blockSize || 16;18534 this._ints = this.blockSize / 4;18535 this._inBlock = new Array(this._ints);18536 this._outBlock = new Array(this._ints);18537};18538modes.ecb.prototype.start = function(options) {};18539modes.ecb.prototype.encrypt = function(input, output, finish) {18540 // not enough input to encrypt18541 if(input.length() < this.blockSize && !(finish && input.length() > 0)) {18542 return true;18543 }18544 // get next block18545 for(var i = 0; i < this._ints; ++i) {18546 this._inBlock[i] = input.getInt32();18547 }18548 // encrypt block18549 this.cipher.encrypt(this._inBlock, this._outBlock);18550 // write output18551 for(var i = 0; i < this._ints; ++i) {18552 output.putInt32(this._outBlock[i]);18553 }18554};18555modes.ecb.prototype.decrypt = function(input, output, finish) {18556 // not enough input to decrypt18557 if(input.length() < this.blockSize && !(finish && input.length() > 0)) {18558 return true;18559 }18560 // get next block18561 for(var i = 0; i < this._ints; ++i) {18562 this._inBlock[i] = input.getInt32();18563 }18564 // decrypt block18565 this.cipher.decrypt(this._inBlock, this._outBlock);18566 // write output18567 for(var i = 0; i < this._ints; ++i) {18568 output.putInt32(this._outBlock[i]);18569 }18570};18571modes.ecb.prototype.pad = function(input, options) {18572 // add PKCS#7 padding to block (each pad byte is the18573 // value of the number of pad bytes)18574 var padding = (input.length() === this.blockSize ?18575 this.blockSize : (this.blockSize - input.length()));18576 input.fillWithByte(padding, padding);18577 return true;18578};18579modes.ecb.prototype.unpad = function(output, options) {18580 // check for error: input data not a multiple of blockSize18581 if(options.overflow > 0) {18582 return false;18583 }18584 // ensure padding byte count is valid18585 var len = output.length();18586 var count = output.at(len - 1);18587 if(count > (this.blockSize << 2)) {18588 return false;18589 }18590 // trim off padding bytes18591 output.truncate(count);18592 return true;18593};18594/** Cipher-block Chaining (CBC) **/18595modes.cbc = function(options) {18596 options = options || {};18597 this.name = 'CBC';18598 this.cipher = options.cipher;18599 this.blockSize = options.blockSize || 16;18600 this._ints = this.blockSize / 4;18601 this._inBlock = new Array(this._ints);18602 this._outBlock = new Array(this._ints);18603};18604modes.cbc.prototype.start = function(options) {18605 // Note: legacy support for using IV residue (has security flaws)18606 // if IV is null, reuse block from previous processing18607 if(options.iv === null) {18608 // must have a previous block18609 if(!this._prev) {18610 throw new Error('Invalid IV parameter.');18611 }18612 this._iv = this._prev.slice(0);18613 } else if(!('iv' in options)) {18614 throw new Error('Invalid IV parameter.');18615 } else {18616 // save IV as "previous" block18617 this._iv = transformIV(options.iv, this.blockSize);18618 this._prev = this._iv.slice(0);18619 }18620};18621modes.cbc.prototype.encrypt = function(input, output, finish) {18622 // not enough input to encrypt18623 if(input.length() < this.blockSize && !(finish && input.length() > 0)) {18624 return true;18625 }18626 // get next block18627 // CBC XOR's IV (or previous block) with plaintext18628 for(var i = 0; i < this._ints; ++i) {18629 this._inBlock[i] = this._prev[i] ^ input.getInt32();18630 }18631 // encrypt block18632 this.cipher.encrypt(this._inBlock, this._outBlock);18633 // write output, save previous block18634 for(var i = 0; i < this._ints; ++i) {18635 output.putInt32(this._outBlock[i]);18636 }18637 this._prev = this._outBlock;18638};18639modes.cbc.prototype.decrypt = function(input, output, finish) {18640 // not enough input to decrypt18641 if(input.length() < this.blockSize && !(finish && input.length() > 0)) {18642 return true;18643 }18644 // get next block18645 for(var i = 0; i < this._ints; ++i) {18646 this._inBlock[i] = input.getInt32();18647 }18648 // decrypt block18649 this.cipher.decrypt(this._inBlock, this._outBlock);18650 // write output, save previous ciphered block18651 // CBC XOR's IV (or previous block) with ciphertext18652 for(var i = 0; i < this._ints; ++i) {18653 output.putInt32(this._prev[i] ^ this._outBlock[i]);18654 }18655 this._prev = this._inBlock.slice(0);18656};18657modes.cbc.prototype.pad = function(input, options) {18658 // add PKCS#7 padding to block (each pad byte is the18659 // value of the number of pad bytes)18660 var padding = (input.length() === this.blockSize ?18661 this.blockSize : (this.blockSize - input.length()));18662 input.fillWithByte(padding, padding);18663 return true;18664};18665modes.cbc.prototype.unpad = function(output, options) {18666 // check for error: input data not a multiple of blockSize18667 if(options.overflow > 0) {18668 return false;18669 }18670 // ensure padding byte count is valid18671 var len = output.length();18672 var count = output.at(len - 1);18673 if(count > (this.blockSize << 2)) {18674 return false;18675 }18676 // trim off padding bytes18677 output.truncate(count);18678 return true;18679};18680/** Cipher feedback (CFB) **/18681modes.cfb = function(options) {18682 options = options || {};18683 this.name = 'CFB';18684 this.cipher = options.cipher;18685 this.blockSize = options.blockSize || 16;18686 this._ints = this.blockSize / 4;18687 this._inBlock = null;18688 this._outBlock = new Array(this._ints);18689 this._partialBlock = new Array(this._ints);18690 this._partialOutput = forge.util.createBuffer();18691 this._partialBytes = 0;18692};18693modes.cfb.prototype.start = function(options) {18694 if(!('iv' in options)) {18695 throw new Error('Invalid IV parameter.');18696 }18697 // use IV as first input18698 this._iv = transformIV(options.iv, this.blockSize);18699 this._inBlock = this._iv.slice(0);18700 this._partialBytes = 0;18701};18702modes.cfb.prototype.encrypt = function(input, output, finish) {18703 // not enough input to encrypt18704 var inputLength = input.length();18705 if(inputLength === 0) {18706 return true;18707 }18708 // encrypt block18709 this.cipher.encrypt(this._inBlock, this._outBlock);18710 // handle full block18711 if(this._partialBytes === 0 && inputLength >= this.blockSize) {18712 // XOR input with output, write input as output18713 for(var i = 0; i < this._ints; ++i) {18714 this._inBlock[i] = input.getInt32() ^ this._outBlock[i];18715 output.putInt32(this._inBlock[i]);18716 }18717 return;18718 }18719 // handle partial block18720 var partialBytes = (this.blockSize - inputLength) % this.blockSize;18721 if(partialBytes > 0) {18722 partialBytes = this.blockSize - partialBytes;18723 }18724 // XOR input with output, write input as partial output18725 this._partialOutput.clear();18726 for(var i = 0; i < this._ints; ++i) {18727 this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];18728 this._partialOutput.putInt32(this._partialBlock[i]);18729 }18730 if(partialBytes > 0) {18731 // block still incomplete, restore input buffer18732 input.read -= this.blockSize;18733 } else {18734 // block complete, update input block18735 for(var i = 0; i < this._ints; ++i) {18736 this._inBlock[i] = this._partialBlock[i];18737 }18738 }18739 // skip any previous partial bytes18740 if(this._partialBytes > 0) {18741 this._partialOutput.getBytes(this._partialBytes);18742 }18743 if(partialBytes > 0 && !finish) {18744 output.putBytes(this._partialOutput.getBytes(18745 partialBytes - this._partialBytes));18746 this._partialBytes = partialBytes;18747 return true;18748 }18749 output.putBytes(this._partialOutput.getBytes(18750 inputLength - this._partialBytes));18751 this._partialBytes = 0;18752};18753modes.cfb.prototype.decrypt = function(input, output, finish) {18754 // not enough input to decrypt18755 var inputLength = input.length();18756 if(inputLength === 0) {18757 return true;18758 }18759 // encrypt block (CFB always uses encryption mode)18760 this.cipher.encrypt(this._inBlock, this._outBlock);18761 // handle full block18762 if(this._partialBytes === 0 && inputLength >= this.blockSize) {18763 // XOR input with output, write input as output18764 for(var i = 0; i < this._ints; ++i) {18765 this._inBlock[i] = input.getInt32();18766 output.putInt32(this._inBlock[i] ^ this._outBlock[i]);18767 }18768 return;18769 }18770 // handle partial block18771 var partialBytes = (this.blockSize - inputLength) % this.blockSize;18772 if(partialBytes > 0) {18773 partialBytes = this.blockSize - partialBytes;18774 }18775 // XOR input with output, write input as partial output18776 this._partialOutput.clear();18777 for(var i = 0; i < this._ints; ++i) {18778 this._partialBlock[i] = input.getInt32();18779 this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);18780 }18781 if(partialBytes > 0) {18782 // block still incomplete, restore input buffer18783 input.read -= this.blockSize;18784 } else {18785 // block complete, update input block18786 for(var i = 0; i < this._ints; ++i) {18787 this._inBlock[i] = this._partialBlock[i];18788 }18789 }18790 // skip any previous partial bytes18791 if(this._partialBytes > 0) {18792 this._partialOutput.getBytes(this._partialBytes);18793 }18794 if(partialBytes > 0 && !finish) {18795 output.putBytes(this._partialOutput.getBytes(18796 partialBytes - this._partialBytes));18797 this._partialBytes = partialBytes;18798 return true;18799 }18800 output.putBytes(this._partialOutput.getBytes(18801 inputLength - this._partialBytes));18802 this._partialBytes = 0;18803};18804/** Output feedback (OFB) **/18805modes.ofb = function(options) {18806 options = options || {};18807 this.name = 'OFB';18808 this.cipher = options.cipher;18809 this.blockSize = options.blockSize || 16;18810 this._ints = this.blockSize / 4;18811 this._inBlock = null;18812 this._outBlock = new Array(this._ints);18813 this._partialOutput = forge.util.createBuffer();18814 this._partialBytes = 0;18815};18816modes.ofb.prototype.start = function(options) {18817 if(!('iv' in options)) {18818 throw new Error('Invalid IV parameter.');18819 }18820 // use IV as first input18821 this._iv = transformIV(options.iv, this.blockSize);18822 this._inBlock = this._iv.slice(0);18823 this._partialBytes = 0;18824};18825modes.ofb.prototype.encrypt = function(input, output, finish) {18826 // not enough input to encrypt18827 var inputLength = input.length();18828 if(input.length() === 0) {18829 return true;18830 }18831 // encrypt block (OFB always uses encryption mode)18832 this.cipher.encrypt(this._inBlock, this._outBlock);18833 // handle full block18834 if(this._partialBytes === 0 && inputLength >= this.blockSize) {18835 // XOR input with output and update next input18836 for(var i = 0; i < this._ints; ++i) {18837 output.putInt32(input.getInt32() ^ this._outBlock[i]);18838 this._inBlock[i] = this._outBlock[i];18839 }18840 return;18841 }18842 // handle partial block18843 var partialBytes = (this.blockSize - inputLength) % this.blockSize;18844 if(partialBytes > 0) {18845 partialBytes = this.blockSize - partialBytes;18846 }18847 // XOR input with output18848 this._partialOutput.clear();18849 for(var i = 0; i < this._ints; ++i) {18850 this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);18851 }18852 if(partialBytes > 0) {18853 // block still incomplete, restore input buffer18854 input.read -= this.blockSize;18855 } else {18856 // block complete, update input block18857 for(var i = 0; i < this._ints; ++i) {18858 this._inBlock[i] = this._outBlock[i];18859 }18860 }18861 // skip any previous partial bytes18862 if(this._partialBytes > 0) {18863 this._partialOutput.getBytes(this._partialBytes);18864 }18865 if(partialBytes > 0 && !finish) {18866 output.putBytes(this._partialOutput.getBytes(18867 partialBytes - this._partialBytes));18868 this._partialBytes = partialBytes;18869 return true;18870 }18871 output.putBytes(this._partialOutput.getBytes(18872 inputLength - this._partialBytes));18873 this._partialBytes = 0;18874};18875modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;18876/** Counter (CTR) **/18877modes.ctr = function(options) {18878 options = options || {};18879 this.name = 'CTR';18880 this.cipher = options.cipher;18881 this.blockSize = options.blockSize || 16;18882 this._ints = this.blockSize / 4;18883 this._inBlock = null;18884 this._outBlock = new Array(this._ints);18885 this._partialOutput = forge.util.createBuffer();18886 this._partialBytes = 0;18887};18888modes.ctr.prototype.start = function(options) {18889 if(!('iv' in options)) {18890 throw new Error('Invalid IV parameter.');18891 }18892 // use IV as first input18893 this._iv = transformIV(options.iv, this.blockSize);18894 this._inBlock = this._iv.slice(0);18895 this._partialBytes = 0;18896};18897modes.ctr.prototype.encrypt = function(input, output, finish) {18898 // not enough input to encrypt18899 var inputLength = input.length();18900 if(inputLength === 0) {18901 return true;18902 }18903 // encrypt block (CTR always uses encryption mode)18904 this.cipher.encrypt(this._inBlock, this._outBlock);18905 // handle full block18906 if(this._partialBytes === 0 && inputLength >= this.blockSize) {18907 // XOR input with output18908 for(var i = 0; i < this._ints; ++i) {18909 output.putInt32(input.getInt32() ^ this._outBlock[i]);18910 }18911 } else {18912 // handle partial block18913 var partialBytes = (this.blockSize - inputLength) % this.blockSize;18914 if(partialBytes > 0) {18915 partialBytes = this.blockSize - partialBytes;18916 }18917 // XOR input with output18918 this._partialOutput.clear();18919 for(var i = 0; i < this._ints; ++i) {18920 this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);18921 }18922 if(partialBytes > 0) {18923 // block still incomplete, restore input buffer18924 input.read -= this.blockSize;18925 }18926 // skip any previous partial bytes18927 if(this._partialBytes > 0) {18928 this._partialOutput.getBytes(this._partialBytes);18929 }18930 if(partialBytes > 0 && !finish) {18931 output.putBytes(this._partialOutput.getBytes(18932 partialBytes - this._partialBytes));18933 this._partialBytes = partialBytes;18934 return true;18935 }18936 output.putBytes(this._partialOutput.getBytes(18937 inputLength - this._partialBytes));18938 this._partialBytes = 0;18939 }18940 // block complete, increment counter (input block)18941 inc32(this._inBlock);18942};18943modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;18944/** Galois/Counter Mode (GCM) **/18945modes.gcm = function(options) {18946 options = options || {};18947 this.name = 'GCM';18948 this.cipher = options.cipher;18949 this.blockSize = options.blockSize || 16;18950 this._ints = this.blockSize / 4;18951 this._inBlock = new Array(this._ints);18952 this._outBlock = new Array(this._ints);18953 this._partialOutput = forge.util.createBuffer();18954 this._partialBytes = 0;18955 // R is actually this value concatenated with 120 more zero bits, but18956 // we only XOR against R so the other zeros have no effect -- we just18957 // apply this value to the first integer in a block18958 this._R = 0xE1000000;18959};18960modes.gcm.prototype.start = function(options) {18961 if(!('iv' in options)) {18962 throw new Error('Invalid IV parameter.');18963 }18964 // ensure IV is a byte buffer18965 var iv = forge.util.createBuffer(options.iv);18966 // no ciphered data processed yet18967 this._cipherLength = 0;18968 // default additional data is none18969 var additionalData;18970 if('additionalData' in options) {18971 additionalData = forge.util.createBuffer(options.additionalData);18972 } else {18973 additionalData = forge.util.createBuffer();18974 }18975 // default tag length is 128 bits18976 if('tagLength' in options) {18977 this._tagLength = options.tagLength;18978 } else {18979 this._tagLength = 128;18980 }18981 // if tag is given, ensure tag matches tag length18982 this._tag = null;18983 if(options.decrypt) {18984 // save tag to check later18985 this._tag = forge.util.createBuffer(options.tag).getBytes();18986 if(this._tag.length !== (this._tagLength / 8)) {18987 throw new Error('Authentication tag does not match tag length.');18988 }18989 }18990 // create tmp storage for hash calculation18991 this._hashBlock = new Array(this._ints);18992 // no tag generated yet18993 this.tag = null;18994 // generate hash subkey18995 // (apply block cipher to "zero" block)18996 this._hashSubkey = new Array(this._ints);18997 this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);18998 // generate table M18999 // use 4-bit tables (32 component decomposition of a 16 byte value)19000 // 8-bit tables take more space and are known to have security19001 // vulnerabilities (in native implementations)19002 this.componentBits = 4;19003 this._m = this.generateHashTable(this._hashSubkey, this.componentBits);19004 // Note: support IV length different from 96 bits? (only supporting19005 // 96 bits is recommended by NIST SP-800-38D)19006 // generate J_019007 var ivLength = iv.length();19008 if(ivLength === 12) {19009 // 96-bit IV19010 this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];19011 } else {19012 // IV is NOT 96-bits19013 this._j0 = [0, 0, 0, 0];19014 while(iv.length() > 0) {19015 this._j0 = this.ghash(19016 this._hashSubkey, this._j0,19017 [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);19018 }19019 this._j0 = this.ghash(19020 this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));19021 }19022 // generate ICB (initial counter block)19023 this._inBlock = this._j0.slice(0);19024 inc32(this._inBlock);19025 this._partialBytes = 0;19026 // consume authentication data19027 additionalData = forge.util.createBuffer(additionalData);19028 // save additional data length as a BE 64-bit number19029 this._aDataLength = from64To32(additionalData.length() * 8);19030 // pad additional data to 128 bit (16 byte) block size19031 var overflow = additionalData.length() % this.blockSize;19032 if(overflow) {19033 additionalData.fillWithByte(0, this.blockSize - overflow);19034 }19035 this._s = [0, 0, 0, 0];19036 while(additionalData.length() > 0) {19037 this._s = this.ghash(this._hashSubkey, this._s, [19038 additionalData.getInt32(),19039 additionalData.getInt32(),19040 additionalData.getInt32(),19041 additionalData.getInt32()19042 ]);19043 }19044};19045modes.gcm.prototype.encrypt = function(input, output, finish) {19046 // not enough input to encrypt19047 var inputLength = input.length();19048 if(inputLength === 0) {19049 return true;19050 }19051 // encrypt block19052 this.cipher.encrypt(this._inBlock, this._outBlock);19053 // handle full block19054 if(this._partialBytes === 0 && inputLength >= this.blockSize) {19055 // XOR input with output19056 for(var i = 0; i < this._ints; ++i) {19057 output.putInt32(this._outBlock[i] ^= input.getInt32());19058 }19059 this._cipherLength += this.blockSize;19060 } else {19061 // handle partial block19062 var partialBytes = (this.blockSize - inputLength) % this.blockSize;19063 if(partialBytes > 0) {19064 partialBytes = this.blockSize - partialBytes;19065 }19066 // XOR input with output19067 this._partialOutput.clear();19068 for(var i = 0; i < this._ints; ++i) {19069 this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);19070 }19071 if(partialBytes <= 0 || finish) {19072 // handle overflow prior to hashing19073 if(finish) {19074 // get block overflow19075 var overflow = inputLength % this.blockSize;19076 this._cipherLength += overflow;19077 // truncate for hash function19078 this._partialOutput.truncate(this.blockSize - overflow);19079 } else {19080 this._cipherLength += this.blockSize;19081 }19082 // get output block for hashing19083 for(var i = 0; i < this._ints; ++i) {19084 this._outBlock[i] = this._partialOutput.getInt32();19085 }19086 this._partialOutput.read -= this.blockSize;19087 }19088 // skip any previous partial bytes19089 if(this._partialBytes > 0) {19090 this._partialOutput.getBytes(this._partialBytes);19091 }19092 if(partialBytes > 0 && !finish) {19093 // block still incomplete, restore input buffer, get partial output,19094 // and return early19095 input.read -= this.blockSize;19096 output.putBytes(this._partialOutput.getBytes(19097 partialBytes - this._partialBytes));19098 this._partialBytes = partialBytes;19099 return true;19100 }19101 output.putBytes(this._partialOutput.getBytes(19102 inputLength - this._partialBytes));19103 this._partialBytes = 0;19104 }19105 // update hash block S19106 this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);19107 // increment counter (input block)19108 inc32(this._inBlock);19109};19110modes.gcm.prototype.decrypt = function(input, output, finish) {19111 // not enough input to decrypt19112 var inputLength = input.length();19113 if(inputLength < this.blockSize && !(finish && inputLength > 0)) {19114 return true;19115 }19116 // encrypt block (GCM always uses encryption mode)19117 this.cipher.encrypt(this._inBlock, this._outBlock);19118 // increment counter (input block)19119 inc32(this._inBlock);19120 // update hash block S19121 this._hashBlock[0] = input.getInt32();19122 this._hashBlock[1] = input.getInt32();19123 this._hashBlock[2] = input.getInt32();19124 this._hashBlock[3] = input.getInt32();19125 this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);19126 // XOR hash input with output19127 for(var i = 0; i < this._ints; ++i) {19128 output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);19129 }19130 // increment cipher data length19131 if(inputLength < this.blockSize) {19132 this._cipherLength += inputLength % this.blockSize;19133 } else {19134 this._cipherLength += this.blockSize;19135 }19136};19137modes.gcm.prototype.afterFinish = function(output, options) {19138 var rval = true;19139 // handle overflow19140 if(options.decrypt && options.overflow) {19141 output.truncate(this.blockSize - options.overflow);19142 }19143 // handle authentication tag19144 this.tag = forge.util.createBuffer();19145 // concatenate additional data length with cipher length19146 var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));19147 // include lengths in hash19148 this._s = this.ghash(this._hashSubkey, this._s, lengths);19149 // do GCTR(J_0, S)19150 var tag = [];19151 this.cipher.encrypt(this._j0, tag);19152 for(var i = 0; i < this._ints; ++i) {19153 this.tag.putInt32(this._s[i] ^ tag[i]);19154 }19155 // trim tag to length19156 this.tag.truncate(this.tag.length() % (this._tagLength / 8));19157 // check authentication tag19158 if(options.decrypt && this.tag.bytes() !== this._tag) {19159 rval = false;19160 }19161 return rval;19162};19163/**19164 * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois19165 * field multiplication. The field, GF(2^128), is defined by the polynomial:19166 *19167 * x^128 + x^7 + x^2 + x + 119168 *19169 * Which is represented in little-endian binary form as: 11100001 (0xe1). When19170 * the value of a coefficient is 1, a bit is set. The value R, is the19171 * concatenation of this value and 120 zero bits, yielding a 128-bit value19172 * which matches the block size.19173 *19174 * This function will multiply two elements (vectors of bytes), X and Y, in19175 * the field GF(2^128). The result is initialized to zero. For each bit of19176 * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)19177 * by the current value of Y. For each bit, the value of Y will be raised by19178 * a power of x (multiplied by the polynomial x). This can be achieved by19179 * shifting Y once to the right. If the current value of Y, prior to being19180 * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.19181 * Otherwise, we must divide by R after shifting to find the remainder.19182 *19183 * @param x the first block to multiply by the second.19184 * @param y the second block to multiply by the first.19185 *19186 * @return the block result of the multiplication.19187 */19188modes.gcm.prototype.multiply = function(x, y) {19189 var z_i = [0, 0, 0, 0];19190 var v_i = y.slice(0);19191 // calculate Z_128 (block has 128 bits)19192 for(var i = 0; i < 128; ++i) {19193 // if x_i is 0, Z_{i+1} = Z_i (unchanged)19194 // else Z_{i+1} = Z_i ^ V_i19195 // get x_i by finding 32-bit int position, then left shift 1 by remainder19196 var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));19197 if(x_i) {19198 z_i[0] ^= v_i[0];19199 z_i[1] ^= v_i[1];19200 z_i[2] ^= v_i[2];19201 z_i[3] ^= v_i[3];19202 }19203 // if LSB(V_i) is 1, V_i = V_i >> 119204 // else V_i = (V_i >> 1) ^ R19205 this.pow(v_i, v_i);19206 }19207 return z_i;19208};19209modes.gcm.prototype.pow = function(x, out) {19210 // if LSB(x) is 1, x = x >>> 119211 // else x = (x >>> 1) ^ R19212 var lsb = x[3] & 1;19213 // always do x >>> 1:19214 // starting with the rightmost integer, shift each integer to the right19215 // one bit, pulling in the bit from the integer to the left as its top19216 // most bit (do this for the last 3 integers)19217 for(var i = 3; i > 0; --i) {19218 out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);19219 }19220 // shift the first integer normally19221 out[0] = x[0] >>> 1;19222 // if lsb was not set, then polynomial had a degree of 127 and doesn't19223 // need to divided; otherwise, XOR with R to find the remainder; we only19224 // need to XOR the first integer since R technically ends w/120 zero bits19225 if(lsb) {19226 out[0] ^= this._R;19227 }19228};19229modes.gcm.prototype.tableMultiply = function(x) {19230 // assumes 4-bit tables are used19231 var z = [0, 0, 0, 0];19232 for(var i = 0; i < 32; ++i) {19233 var idx = (i / 8) | 0;19234 var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;19235 var ah = this._m[i][x_i];19236 z[0] ^= ah[0];19237 z[1] ^= ah[1];19238 z[2] ^= ah[2];19239 z[3] ^= ah[3];19240 }19241 return z;19242};19243/**19244 * A continuing version of the GHASH algorithm that operates on a single19245 * block. The hash block, last hash value (Ym) and the new block to hash19246 * are given.19247 *19248 * @param h the hash block.19249 * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.19250 * @param x the block to hash.19251 *19252 * @return the hashed value (Ym).19253 */19254modes.gcm.prototype.ghash = function(h, y, x) {19255 y[0] ^= x[0];19256 y[1] ^= x[1];19257 y[2] ^= x[2];19258 y[3] ^= x[3];19259 return this.tableMultiply(y);19260 //return this.multiply(y, h);19261};19262/**19263 * Precomputes a table for multiplying against the hash subkey. This19264 * mechanism provides a substantial speed increase over multiplication19265 * performed without a table. The table-based multiplication this table is19266 * for solves X * H by multiplying each component of X by H and then19267 * composing the results together using XOR.19268 *19269 * This function can be used to generate tables with different bit sizes19270 * for the components, however, this implementation assumes there are19271 * 32 components of X (which is a 16 byte vector), therefore each component19272 * takes 4-bits (so the table is constructed with bits=4).19273 *19274 * @param h the hash subkey.19275 * @param bits the bit size for a component.19276 */19277modes.gcm.prototype.generateHashTable = function(h, bits) {19278 // TODO: There are further optimizations that would use only the19279 // first table M_0 (or some variant) along with a remainder table;19280 // this can be explored in the future19281 var multiplier = 8 / bits;19282 var perInt = 4 * multiplier;19283 var size = 16 * multiplier;19284 var m = new Array(size);19285 for(var i = 0; i < size; ++i) {19286 var tmp = [0, 0, 0, 0];19287 var idx = (i / perInt) | 0;19288 var shft = ((perInt - 1 - (i % perInt)) * bits);19289 tmp[idx] = (1 << (bits - 1)) << shft;19290 m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);19291 }19292 return m;19293};19294/**19295 * Generates a table for multiplying against the hash subkey for one19296 * particular component (out of all possible component values).19297 *19298 * @param mid the pre-multiplied value for the middle key of the table.19299 * @param bits the bit size for a component.19300 */19301modes.gcm.prototype.generateSubHashTable = function(mid, bits) {19302 // compute the table quickly by minimizing the number of19303 // POW operations -- they only need to be performed for powers of 2,19304 // all other entries can be composed from those powers using XOR19305 var size = 1 << bits;19306 var half = size >>> 1;19307 var m = new Array(size);19308 m[half] = mid.slice(0);19309 var i = half >>> 1;19310 while(i > 0) {19311 // raise m0[2 * i] and store in m0[i]19312 this.pow(m[2 * i], m[i] = []);19313 i >>= 1;19314 }19315 i = 2;19316 while(i < half) {19317 for(var j = 1; j < i; ++j) {19318 var m_i = m[i];19319 var m_j = m[j];19320 m[i + j] = [19321 m_i[0] ^ m_j[0],19322 m_i[1] ^ m_j[1],19323 m_i[2] ^ m_j[2],19324 m_i[3] ^ m_j[3]19325 ];19326 }19327 i *= 2;19328 }19329 m[0] = [0, 0, 0, 0];19330 /* Note: We could avoid storing these by doing composition during multiply19331 calculate top half using composition by speed is preferred. */19332 for(i = half + 1; i < size; ++i) {19333 var c = m[i ^ half];19334 m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];19335 }19336 return m;19337};19338/** Utility functions */19339function transformIV(iv, blockSize) {19340 if(typeof iv === 'string') {19341 // convert iv string into byte buffer19342 iv = forge.util.createBuffer(iv);19343 }19344 if(forge.util.isArray(iv) && iv.length > 4) {19345 // convert iv byte array into byte buffer19346 var tmp = iv;19347 iv = forge.util.createBuffer();19348 for(var i = 0; i < tmp.length; ++i) {19349 iv.putByte(tmp[i]);19350 }19351 }19352 if(iv.length() < blockSize) {19353 throw new Error(19354 'Invalid IV length; got ' + iv.length() +19355 ' bytes and expected ' + blockSize + ' bytes.');19356 }19357 if(!forge.util.isArray(iv)) {19358 // convert iv byte buffer into 32-bit integer array19359 var ints = [];19360 var blocks = blockSize / 4;19361 for(var i = 0; i < blocks; ++i) {19362 ints.push(iv.getInt32());19363 }19364 iv = ints;19365 }19366 return iv;19367}19368function inc32(block) {19369 // increment last 32 bits of block only19370 block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;19371}19372function from64To32(num) {19373 // convert 64-bit number to two BE Int32s19374 return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];19375}19376/***/ }),19377/***/ 7157:19378/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {19379/**19380 * DES (Data Encryption Standard) implementation.19381 *19382 * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.19383 * It is based on the BSD-licensed implementation by Paul Tero:19384 *19385 * Paul Tero, July 200119386 * http://www.tero.co.uk/des/19387 *19388 * Optimised for performance with large blocks by19389 * Michael Hayworth, November 200119390 * http://www.netdealing.com19391 *19392 * THIS SOFTWARE IS PROVIDED "AS IS" AND19393 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE19394 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE19395 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE19396 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL19397 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS19398 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)19399 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT19400 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY19401 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF19402 * SUCH DAMAGE.19403 *19404 * @author Stefan Siegl19405 * @author Dave Longley19406 *19407 * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>19408 * Copyright (c) 2012-2014 Digital Bazaar, Inc.19409 */19410var forge = __nccwpck_require__(9177);19411__nccwpck_require__(7088);19412__nccwpck_require__(873);19413__nccwpck_require__(8339);19414/* DES API */19415module.exports = forge.des = forge.des || {};19416/**19417 * Deprecated. Instead, use:19418 *19419 * var cipher = forge.cipher.createCipher('DES-<mode>', key);19420 * cipher.start({iv: iv});19421 *19422 * Creates an DES cipher object to encrypt data using the given symmetric key.19423 * The output will be stored in the 'output' member of the returned cipher.19424 *19425 * The key and iv may be given as binary-encoded strings of bytes or19426 * byte buffers.19427 *19428 * @param key the symmetric key to use (64 or 192 bits).19429 * @param iv the initialization vector to use.19430 * @param output the buffer to write to, null to create one.19431 * @param mode the cipher mode to use (default: 'CBC' if IV is19432 * given, 'ECB' if null).19433 *19434 * @return the cipher.19435 */19436forge.des.startEncrypting = function(key, iv, output, mode) {19437 var cipher = _createCipher({19438 key: key,19439 output: output,19440 decrypt: false,19441 mode: mode || (iv === null ? 'ECB' : 'CBC')19442 });19443 cipher.start(iv);19444 return cipher;19445};19446/**19447 * Deprecated. Instead, use:19448 *19449 * var cipher = forge.cipher.createCipher('DES-<mode>', key);19450 *19451 * Creates an DES cipher object to encrypt data using the given symmetric key.19452 *19453 * The key may be given as a binary-encoded string of bytes or a byte buffer.19454 *19455 * @param key the symmetric key to use (64 or 192 bits).19456 * @param mode the cipher mode to use (default: 'CBC').19457 *19458 * @return the cipher.19459 */19460forge.des.createEncryptionCipher = function(key, mode) {19461 return _createCipher({19462 key: key,19463 output: null,19464 decrypt: false,19465 mode: mode19466 });19467};19468/**19469 * Deprecated. Instead, use:19470 *19471 * var decipher = forge.cipher.createDecipher('DES-<mode>', key);19472 * decipher.start({iv: iv});19473 *19474 * Creates an DES cipher object to decrypt data using the given symmetric key.19475 * The output will be stored in the 'output' member of the returned cipher.19476 *19477 * The key and iv may be given as binary-encoded strings of bytes or19478 * byte buffers.19479 *19480 * @param key the symmetric key to use (64 or 192 bits).19481 * @param iv the initialization vector to use.19482 * @param output the buffer to write to, null to create one.19483 * @param mode the cipher mode to use (default: 'CBC' if IV is19484 * given, 'ECB' if null).19485 *19486 * @return the cipher.19487 */19488forge.des.startDecrypting = function(key, iv, output, mode) {19489 var cipher = _createCipher({19490 key: key,19491 output: output,19492 decrypt: true,19493 mode: mode || (iv === null ? 'ECB' : 'CBC')19494 });19495 cipher.start(iv);19496 return cipher;19497};19498/**19499 * Deprecated. Instead, use:19500 *19501 * var decipher = forge.cipher.createDecipher('DES-<mode>', key);19502 *19503 * Creates an DES cipher object to decrypt data using the given symmetric key.19504 *19505 * The key may be given as a binary-encoded string of bytes or a byte buffer.19506 *19507 * @param key the symmetric key to use (64 or 192 bits).19508 * @param mode the cipher mode to use (default: 'CBC').19509 *19510 * @return the cipher.19511 */19512forge.des.createDecryptionCipher = function(key, mode) {19513 return _createCipher({19514 key: key,19515 output: null,19516 decrypt: true,19517 mode: mode19518 });19519};19520/**19521 * Creates a new DES cipher algorithm object.19522 *19523 * @param name the name of the algorithm.19524 * @param mode the mode factory function.19525 *19526 * @return the DES algorithm object.19527 */19528forge.des.Algorithm = function(name, mode) {19529 var self = this;19530 self.name = name;19531 self.mode = new mode({19532 blockSize: 8,19533 cipher: {19534 encrypt: function(inBlock, outBlock) {19535 return _updateBlock(self._keys, inBlock, outBlock, false);19536 },19537 decrypt: function(inBlock, outBlock) {19538 return _updateBlock(self._keys, inBlock, outBlock, true);19539 }19540 }19541 });19542 self._init = false;19543};19544/**19545 * Initializes this DES algorithm by expanding its key.19546 *19547 * @param options the options to use.19548 * key the key to use with this algorithm.19549 * decrypt true if the algorithm should be initialized for decryption,19550 * false for encryption.19551 */19552forge.des.Algorithm.prototype.initialize = function(options) {19553 if(this._init) {19554 return;19555 }19556 var key = forge.util.createBuffer(options.key);19557 if(this.name.indexOf('3DES') === 0) {19558 if(key.length() !== 24) {19559 throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);19560 }19561 }19562 // do key expansion to 16 or 48 subkeys (single or triple DES)19563 this._keys = _createKeys(key);19564 this._init = true;19565};19566/** Register DES algorithms **/19567registerAlgorithm('DES-ECB', forge.cipher.modes.ecb);19568registerAlgorithm('DES-CBC', forge.cipher.modes.cbc);19569registerAlgorithm('DES-CFB', forge.cipher.modes.cfb);19570registerAlgorithm('DES-OFB', forge.cipher.modes.ofb);19571registerAlgorithm('DES-CTR', forge.cipher.modes.ctr);19572registerAlgorithm('3DES-ECB', forge.cipher.modes.ecb);19573registerAlgorithm('3DES-CBC', forge.cipher.modes.cbc);19574registerAlgorithm('3DES-CFB', forge.cipher.modes.cfb);19575registerAlgorithm('3DES-OFB', forge.cipher.modes.ofb);19576registerAlgorithm('3DES-CTR', forge.cipher.modes.ctr);19577function registerAlgorithm(name, mode) {19578 var factory = function() {19579 return new forge.des.Algorithm(name, mode);19580 };19581 forge.cipher.registerAlgorithm(name, factory);19582}19583/** DES implementation **/19584var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004];19585var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000];19586var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200];19587var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080];19588var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100];19589var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010];19590var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002];19591var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000];19592/**19593 * Create necessary sub keys.19594 *19595 * @param key the 64-bit or 192-bit key.19596 *19597 * @return the expanded keys.19598 */19599function _createKeys(key) {19600 var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],19601 pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],19602 pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],19603 pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],19604 pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],19605 pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],19606 pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],19607 pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],19608 pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],19609 pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],19610 pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],19611 pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],19612 pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],19613 pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];19614 // how many iterations (1 for des, 3 for triple des)19615 // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys19616 var iterations = key.length() > 8 ? 3 : 1;19617 // stores the return keys19618 var keys = [];19619 // now define the left shifts which need to be done19620 var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];19621 var n = 0, tmp;19622 for(var j = 0; j < iterations; j++) {19623 var left = key.getInt32();19624 var right = key.getInt32();19625 tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;19626 right ^= tmp;19627 left ^= (tmp << 4);19628 tmp = ((right >>> -16) ^ left) & 0x0000ffff;19629 left ^= tmp;19630 right ^= (tmp << -16);19631 tmp = ((left >>> 2) ^ right) & 0x33333333;19632 right ^= tmp;19633 left ^= (tmp << 2);19634 tmp = ((right >>> -16) ^ left) & 0x0000ffff;19635 left ^= tmp;19636 right ^= (tmp << -16);19637 tmp = ((left >>> 1) ^ right) & 0x55555555;19638 right ^= tmp;19639 left ^= (tmp << 1);19640 tmp = ((right >>> 8) ^ left) & 0x00ff00ff;19641 left ^= tmp;19642 right ^= (tmp << 8);19643 tmp = ((left >>> 1) ^ right) & 0x55555555;19644 right ^= tmp;19645 left ^= (tmp << 1);19646 // right needs to be shifted and OR'd with last four bits of left19647 tmp = (left << 8) | ((right >>> 20) & 0x000000f0);19648 // left needs to be put upside down19649 left = ((right << 24) | ((right << 8) & 0xff0000) |19650 ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));19651 right = tmp;19652 // now go through and perform these shifts on the left and right keys19653 for(var i = 0; i < shifts.length; ++i) {19654 //shift the keys either one or two bits to the left19655 if(shifts[i]) {19656 left = (left << 2) | (left >>> 26);19657 right = (right << 2) | (right >>> 26);19658 } else {19659 left = (left << 1) | (left >>> 27);19660 right = (right << 1) | (right >>> 27);19661 }19662 left &= -0xf;19663 right &= -0xf;19664 // now apply PC-2, in such a way that E is easier when encrypting or19665 // decrypting this conversion will look like PC-2 except only the last 619666 // bits of each byte are used rather than 48 consecutive bits and the19667 // order of lines will be according to how the S selection functions will19668 // be applied: S2, S4, S6, S8, S1, S3, S5, S719669 var lefttmp = (19670 pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |19671 pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |19672 pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |19673 pc2bytes6[(left >>> 4) & 0xf]);19674 var righttmp = (19675 pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |19676 pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |19677 pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |19678 pc2bytes13[(right >>> 4) & 0xf]);19679 tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;19680 keys[n++] = lefttmp ^ tmp;19681 keys[n++] = righttmp ^ (tmp << 16);19682 }19683 }19684 return keys;19685}19686/**19687 * Updates a single block (1 byte) using DES. The update will either19688 * encrypt or decrypt the block.19689 *19690 * @param keys the expanded keys.19691 * @param input the input block (an array of 32-bit words).19692 * @param output the updated output block.19693 * @param decrypt true to decrypt the block, false to encrypt it.19694 */19695function _updateBlock(keys, input, output, decrypt) {19696 // set up loops for single or triple DES19697 var iterations = keys.length === 32 ? 3 : 9;19698 var looping;19699 if(iterations === 3) {19700 looping = decrypt ? [30, -2, -2] : [0, 32, 2];19701 } else {19702 looping = (decrypt ?19703 [94, 62, -2, 32, 64, 2, 30, -2, -2] :19704 [0, 32, 2, 62, 30, -2, 64, 96, 2]);19705 }19706 var tmp;19707 var left = input[0];19708 var right = input[1];19709 // first each 64 bit chunk of the message must be permuted according to IP19710 tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;19711 right ^= tmp;19712 left ^= (tmp << 4);19713 tmp = ((left >>> 16) ^ right) & 0x0000ffff;19714 right ^= tmp;19715 left ^= (tmp << 16);19716 tmp = ((right >>> 2) ^ left) & 0x33333333;19717 left ^= tmp;19718 right ^= (tmp << 2);19719 tmp = ((right >>> 8) ^ left) & 0x00ff00ff;19720 left ^= tmp;19721 right ^= (tmp << 8);19722 tmp = ((left >>> 1) ^ right) & 0x55555555;19723 right ^= tmp;19724 left ^= (tmp << 1);19725 // rotate left 1 bit19726 left = ((left << 1) | (left >>> 31));19727 right = ((right << 1) | (right >>> 31));19728 for(var j = 0; j < iterations; j += 3) {19729 var endloop = looping[j + 1];19730 var loopinc = looping[j + 2];19731 // now go through and perform the encryption or decryption19732 for(var i = looping[j]; i != endloop; i += loopinc) {19733 var right1 = right ^ keys[i];19734 var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];19735 // passing these bytes through the S selection functions19736 tmp = left;19737 left = right;19738 right = tmp ^ (19739 spfunction2[(right1 >>> 24) & 0x3f] |19740 spfunction4[(right1 >>> 16) & 0x3f] |19741 spfunction6[(right1 >>> 8) & 0x3f] |19742 spfunction8[right1 & 0x3f] |19743 spfunction1[(right2 >>> 24) & 0x3f] |19744 spfunction3[(right2 >>> 16) & 0x3f] |19745 spfunction5[(right2 >>> 8) & 0x3f] |19746 spfunction7[right2 & 0x3f]);19747 }19748 // unreverse left and right19749 tmp = left;19750 left = right;19751 right = tmp;19752 }19753 // rotate right 1 bit19754 left = ((left >>> 1) | (left << 31));19755 right = ((right >>> 1) | (right << 31));19756 // now perform IP-1, which is IP in the opposite direction19757 tmp = ((left >>> 1) ^ right) & 0x55555555;19758 right ^= tmp;19759 left ^= (tmp << 1);19760 tmp = ((right >>> 8) ^ left) & 0x00ff00ff;19761 left ^= tmp;19762 right ^= (tmp << 8);19763 tmp = ((right >>> 2) ^ left) & 0x33333333;19764 left ^= tmp;19765 right ^= (tmp << 2);19766 tmp = ((left >>> 16) ^ right) & 0x0000ffff;19767 right ^= tmp;19768 left ^= (tmp << 16);19769 tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;19770 right ^= tmp;19771 left ^= (tmp << 4);19772 output[0] = left;19773 output[1] = right;19774}19775/**19776 * Deprecated. Instead, use:19777 *19778 * forge.cipher.createCipher('DES-<mode>', key);19779 * forge.cipher.createDecipher('DES-<mode>', key);19780 *19781 * Creates a deprecated DES cipher object. This object's mode will default to19782 * CBC (cipher-block-chaining).19783 *19784 * The key may be given as a binary-encoded string of bytes or a byte buffer.19785 *19786 * @param options the options to use.19787 * key the symmetric key to use (64 or 192 bits).19788 * output the buffer to write to.19789 * decrypt true for decryption, false for encryption.19790 * mode the cipher mode to use (default: 'CBC').19791 *19792 * @return the cipher.19793 */19794function _createCipher(options) {19795 options = options || {};19796 var mode = (options.mode || 'CBC').toUpperCase();19797 var algorithm = 'DES-' + mode;19798 var cipher;19799 if(options.decrypt) {19800 cipher = forge.cipher.createDecipher(algorithm, options.key);19801 } else {19802 cipher = forge.cipher.createCipher(algorithm, options.key);19803 }19804 // backwards compatible start API19805 var start = cipher.start;19806 cipher.start = function(iv, options) {19807 // backwards compatibility: support second arg as output buffer19808 var output = null;19809 if(options instanceof forge.util.ByteBuffer) {19810 output = options;19811 options = {};19812 }19813 options = options || {};19814 options.output = output;19815 options.iv = iv;19816 start.call(cipher, options);19817 };19818 return cipher;19819}19820/***/ }),19821/***/ 0:19822/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {19823/**19824 * JavaScript implementation of Ed25519.19825 *19826 * Copyright (c) 2017-2019 Digital Bazaar, Inc.19827 *19828 * This implementation is based on the most excellent TweetNaCl which is19829 * in the public domain. Many thanks to its contributors:19830 *19831 * https://github.com/dchest/tweetnacl-js19832 */19833var forge = __nccwpck_require__(9177);19834__nccwpck_require__(7052);19835__nccwpck_require__(7821);19836__nccwpck_require__(9542);19837__nccwpck_require__(8339);19838var asn1Validator = __nccwpck_require__(9414);19839var publicKeyValidator = asn1Validator.publicKeyValidator;19840var privateKeyValidator = asn1Validator.privateKeyValidator;19841if(typeof BigInteger === 'undefined') {19842 var BigInteger = forge.jsbn.BigInteger;19843}19844var ByteBuffer = forge.util.ByteBuffer;19845var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer;19846/*19847 * Ed25519 algorithms, see RFC 8032:19848 * https://tools.ietf.org/html/rfc803219849 */19850forge.pki = forge.pki || {};19851module.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {};19852var ed25519 = forge.ed25519;19853ed25519.constants = {};19854ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;19855ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;19856ed25519.constants.SEED_BYTE_LENGTH = 32;19857ed25519.constants.SIGN_BYTE_LENGTH = 64;19858ed25519.constants.HASH_BYTE_LENGTH = 64;19859ed25519.generateKeyPair = function(options) {19860 options = options || {};19861 var seed = options.seed;19862 if(seed === undefined) {19863 // generate seed19864 seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);19865 } else if(typeof seed === 'string') {19866 if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {19867 throw new TypeError(19868 '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH +19869 ' bytes in length.');19870 }19871 } else if(!(seed instanceof Uint8Array)) {19872 throw new TypeError(19873 '"seed" must be a node.js Buffer, Uint8Array, or a binary string.');19874 }19875 seed = messageToNativeBuffer({message: seed, encoding: 'binary'});19876 var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);19877 var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);19878 for(var i = 0; i < 32; ++i) {19879 sk[i] = seed[i];19880 }19881 crypto_sign_keypair(pk, sk);19882 return {publicKey: pk, privateKey: sk};19883};19884/**19885 * Converts a private key from a RFC8410 ASN.1 encoding.19886 *19887 * @param obj - The asn1 representation of a private key.19888 *19889 * @returns {Object} keyInfo - The key information.19890 * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes.19891 */19892ed25519.privateKeyFromAsn1 = function(obj) {19893 var capture = {};19894 var errors = [];19895 var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors);19896 if(!valid) {19897 var error = new Error('Invalid Key.');19898 error.errors = errors;19899 throw error;19900 }19901 var oid = forge.asn1.derToOid(capture.privateKeyOid);19902 var ed25519Oid = forge.oids.EdDSA25519;19903 if(oid !== ed25519Oid) {19904 throw new Error('Invalid OID "' + oid + '"; OID must be "' +19905 ed25519Oid + '".');19906 }19907 var privateKey = capture.privateKey;19908 // manually extract the private key bytes from nested octet string, see FIXME:19909 // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L54219910 var privateKeyBytes = messageToNativeBuffer({19911 message: forge.asn1.fromDer(privateKey).value,19912 encoding: 'binary'19913 });19914 // TODO: RFC8410 specifies a format for encoding the public key bytes along19915 // with the private key bytes. `publicKeyBytes` can be returned in the19916 // future. https://tools.ietf.org/html/rfc8410#section-10.319917 return {privateKeyBytes: privateKeyBytes};19918};19919/**19920 * Converts a public key from a RFC8410 ASN.1 encoding.19921 *19922 * @param obj - The asn1 representation of a public key.19923 *19924 * @return {Buffer|Uint8Array} - 32 public key bytes.19925 */19926ed25519.publicKeyFromAsn1 = function(obj) {19927 // get SubjectPublicKeyInfo19928 var capture = {};19929 var errors = [];19930 var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors);19931 if(!valid) {19932 var error = new Error('Invalid Key.');19933 error.errors = errors;19934 throw error;19935 }19936 var oid = forge.asn1.derToOid(capture.publicKeyOid);19937 var ed25519Oid = forge.oids.EdDSA25519;19938 if(oid !== ed25519Oid) {19939 throw new Error('Invalid OID "' + oid + '"; OID must be "' +19940 ed25519Oid + '".');19941 }19942 var publicKeyBytes = capture.ed25519PublicKey;19943 if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {19944 throw new Error('Key length is invalid.');19945 }19946 return messageToNativeBuffer({19947 message: publicKeyBytes,19948 encoding: 'binary'19949 });19950};19951ed25519.publicKeyFromPrivateKey = function(options) {19952 options = options || {};19953 var privateKey = messageToNativeBuffer({19954 message: options.privateKey, encoding: 'binary'19955 });19956 if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {19957 throw new TypeError(19958 '"options.privateKey" must have a byte length of ' +19959 ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);19960 }19961 var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);19962 for(var i = 0; i < pk.length; ++i) {19963 pk[i] = privateKey[32 + i];19964 }19965 return pk;19966};19967ed25519.sign = function(options) {19968 options = options || {};19969 var msg = messageToNativeBuffer(options);19970 var privateKey = messageToNativeBuffer({19971 message: options.privateKey,19972 encoding: 'binary'19973 });19974 if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {19975 var keyPair = ed25519.generateKeyPair({seed: privateKey});19976 privateKey = keyPair.privateKey;19977 } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {19978 throw new TypeError(19979 '"options.privateKey" must have a byte length of ' +19980 ed25519.constants.SEED_BYTE_LENGTH + ' or ' +19981 ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);19982 }19983 var signedMsg = new NativeBuffer(19984 ed25519.constants.SIGN_BYTE_LENGTH + msg.length);19985 crypto_sign(signedMsg, msg, msg.length, privateKey);19986 var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);19987 for(var i = 0; i < sig.length; ++i) {19988 sig[i] = signedMsg[i];19989 }19990 return sig;19991};19992ed25519.verify = function(options) {19993 options = options || {};19994 var msg = messageToNativeBuffer(options);19995 if(options.signature === undefined) {19996 throw new TypeError(19997 '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' +19998 'ByteBuffer, or a binary string.');19999 }20000 var sig = messageToNativeBuffer({20001 message: options.signature,20002 encoding: 'binary'20003 });20004 if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {20005 throw new TypeError(20006 '"options.signature" must have a byte length of ' +20007 ed25519.constants.SIGN_BYTE_LENGTH);20008 }20009 var publicKey = messageToNativeBuffer({20010 message: options.publicKey,20011 encoding: 'binary'20012 });20013 if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {20014 throw new TypeError(20015 '"options.publicKey" must have a byte length of ' +20016 ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);20017 }20018 var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);20019 var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);20020 var i;20021 for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) {20022 sm[i] = sig[i];20023 }20024 for(i = 0; i < msg.length; ++i) {20025 sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i];20026 }20027 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);20028};20029function messageToNativeBuffer(options) {20030 var message = options.message;20031 if(message instanceof Uint8Array || message instanceof NativeBuffer) {20032 return message;20033 }20034 var encoding = options.encoding;20035 if(message === undefined) {20036 if(options.md) {20037 // TODO: more rigorous validation that `md` is a MessageDigest20038 message = options.md.digest().getBytes();20039 encoding = 'binary';20040 } else {20041 throw new TypeError('"options.message" or "options.md" not specified.');20042 }20043 }20044 if(typeof message === 'string' && !encoding) {20045 throw new TypeError('"options.encoding" must be "binary" or "utf8".');20046 }20047 if(typeof message === 'string') {20048 if(typeof Buffer !== 'undefined') {20049 return Buffer.from(message, encoding);20050 }20051 message = new ByteBuffer(message, encoding);20052 } else if(!(message instanceof ByteBuffer)) {20053 throw new TypeError(20054 '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' +20055 'ByteBuffer, or a string with "options.encoding" specifying its ' +20056 'encoding.');20057 }20058 // convert to native buffer20059 var buffer = new NativeBuffer(message.length());20060 for(var i = 0; i < buffer.length; ++i) {20061 buffer[i] = message.at(i);20062 }20063 return buffer;20064}20065var gf0 = gf();20066var gf1 = gf([1]);20067var D = gf([20068 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,20069 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]);20070var D2 = gf([20071 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,20072 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]);20073var X = gf([20074 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,20075 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]);20076var Y = gf([20077 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,20078 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]);20079var L = new Float64Array([20080 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,20081 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,20082 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);20083var I = gf([20084 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,20085 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);20086// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`,20087// whichever is available, to improve performance20088function sha512(msg, msgLen) {20089 // Note: `out` and `msg` are NativeBuffer20090 var md = forge.md.sha512.create();20091 var buffer = new ByteBuffer(msg);20092 md.update(buffer.getBytes(msgLen), 'binary');20093 var hash = md.digest().getBytes();20094 if(typeof Buffer !== 'undefined') {20095 return Buffer.from(hash, 'binary');20096 }20097 var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);20098 for(var i = 0; i < 64; ++i) {20099 out[i] = hash.charCodeAt(i);20100 }20101 return out;20102}20103function crypto_sign_keypair(pk, sk) {20104 var p = [gf(), gf(), gf(), gf()];20105 var i;20106 var d = sha512(sk, 32);20107 d[0] &= 248;20108 d[31] &= 127;20109 d[31] |= 64;20110 scalarbase(p, d);20111 pack(pk, p);20112 for(i = 0; i < 32; ++i) {20113 sk[i + 32] = pk[i];20114 }20115 return 0;20116}20117// Note: difference from C - smlen returned, not passed as argument.20118function crypto_sign(sm, m, n, sk) {20119 var i, j, x = new Float64Array(64);20120 var p = [gf(), gf(), gf(), gf()];20121 var d = sha512(sk, 32);20122 d[0] &= 248;20123 d[31] &= 127;20124 d[31] |= 64;20125 var smlen = n + 64;20126 for(i = 0; i < n; ++i) {20127 sm[64 + i] = m[i];20128 }20129 for(i = 0; i < 32; ++i) {20130 sm[32 + i] = d[32 + i];20131 }20132 var r = sha512(sm.subarray(32), n + 32);20133 reduce(r);20134 scalarbase(p, r);20135 pack(sm, p);20136 for(i = 32; i < 64; ++i) {20137 sm[i] = sk[i];20138 }20139 var h = sha512(sm, n + 64);20140 reduce(h);20141 for(i = 32; i < 64; ++i) {20142 x[i] = 0;20143 }20144 for(i = 0; i < 32; ++i) {20145 x[i] = r[i];20146 }20147 for(i = 0; i < 32; ++i) {20148 for(j = 0; j < 32; j++) {20149 x[i + j] += h[i] * d[j];20150 }20151 }20152 modL(sm.subarray(32), x);20153 return smlen;20154}20155function crypto_sign_open(m, sm, n, pk) {20156 var i, mlen;20157 var t = new NativeBuffer(32);20158 var p = [gf(), gf(), gf(), gf()],20159 q = [gf(), gf(), gf(), gf()];20160 mlen = -1;20161 if(n < 64) {20162 return -1;20163 }20164 if(unpackneg(q, pk)) {20165 return -1;20166 }20167 for(i = 0; i < n; ++i) {20168 m[i] = sm[i];20169 }20170 for(i = 0; i < 32; ++i) {20171 m[i + 32] = pk[i];20172 }20173 var h = sha512(m, n);20174 reduce(h);20175 scalarmult(p, q, h);20176 scalarbase(q, sm.subarray(32));20177 add(p, q);20178 pack(t, p);20179 n -= 64;20180 if(crypto_verify_32(sm, 0, t, 0)) {20181 for(i = 0; i < n; ++i) {20182 m[i] = 0;20183 }20184 return -1;20185 }20186 for(i = 0; i < n; ++i) {20187 m[i] = sm[i + 64];20188 }20189 mlen = n;20190 return mlen;20191}20192function modL(r, x) {20193 var carry, i, j, k;20194 for(i = 63; i >= 32; --i) {20195 carry = 0;20196 for(j = i - 32, k = i - 12; j < k; ++j) {20197 x[j] += carry - 16 * x[i] * L[j - (i - 32)];20198 carry = (x[j] + 128) >> 8;20199 x[j] -= carry * 256;20200 }20201 x[j] += carry;20202 x[i] = 0;20203 }20204 carry = 0;20205 for(j = 0; j < 32; ++j) {20206 x[j] += carry - (x[31] >> 4) * L[j];20207 carry = x[j] >> 8;20208 x[j] &= 255;20209 }20210 for(j = 0; j < 32; ++j) {20211 x[j] -= carry * L[j];20212 }20213 for(i = 0; i < 32; ++i) {20214 x[i + 1] += x[i] >> 8;20215 r[i] = x[i] & 255;20216 }20217}20218function reduce(r) {20219 var x = new Float64Array(64);20220 for(var i = 0; i < 64; ++i) {20221 x[i] = r[i];20222 r[i] = 0;20223 }20224 modL(r, x);20225}20226function add(p, q) {20227 var a = gf(), b = gf(), c = gf(),20228 d = gf(), e = gf(), f = gf(),20229 g = gf(), h = gf(), t = gf();20230 Z(a, p[1], p[0]);20231 Z(t, q[1], q[0]);20232 M(a, a, t);20233 A(b, p[0], p[1]);20234 A(t, q[0], q[1]);20235 M(b, b, t);20236 M(c, p[3], q[3]);20237 M(c, c, D2);20238 M(d, p[2], q[2]);20239 A(d, d, d);20240 Z(e, b, a);20241 Z(f, d, c);20242 A(g, d, c);20243 A(h, b, a);20244 M(p[0], e, f);20245 M(p[1], h, g);20246 M(p[2], g, f);20247 M(p[3], e, h);20248}20249function cswap(p, q, b) {20250 for(var i = 0; i < 4; ++i) {20251 sel25519(p[i], q[i], b);20252 }20253}20254function pack(r, p) {20255 var tx = gf(), ty = gf(), zi = gf();20256 inv25519(zi, p[2]);20257 M(tx, p[0], zi);20258 M(ty, p[1], zi);20259 pack25519(r, ty);20260 r[31] ^= par25519(tx) << 7;20261}20262function pack25519(o, n) {20263 var i, j, b;20264 var m = gf(), t = gf();20265 for(i = 0; i < 16; ++i) {20266 t[i] = n[i];20267 }20268 car25519(t);20269 car25519(t);20270 car25519(t);20271 for(j = 0; j < 2; ++j) {20272 m[0] = t[0] - 0xffed;20273 for(i = 1; i < 15; ++i) {20274 m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);20275 m[i-1] &= 0xffff;20276 }20277 m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);20278 b = (m[15] >> 16) & 1;20279 m[14] &= 0xffff;20280 sel25519(t, m, 1 - b);20281 }20282 for (i = 0; i < 16; i++) {20283 o[2 * i] = t[i] & 0xff;20284 o[2 * i + 1] = t[i] >> 8;20285 }20286}20287function unpackneg(r, p) {20288 var t = gf(), chk = gf(), num = gf(),20289 den = gf(), den2 = gf(), den4 = gf(),20290 den6 = gf();20291 set25519(r[2], gf1);20292 unpack25519(r[1], p);20293 S(num, r[1]);20294 M(den, num, D);20295 Z(num, num, r[2]);20296 A(den, r[2], den);20297 S(den2, den);20298 S(den4, den2);20299 M(den6, den4, den2);20300 M(t, den6, num);20301 M(t, t, den);20302 pow2523(t, t);20303 M(t, t, num);20304 M(t, t, den);20305 M(t, t, den);20306 M(r[0], t, den);20307 S(chk, r[0]);20308 M(chk, chk, den);20309 if(neq25519(chk, num)) {20310 M(r[0], r[0], I);20311 }20312 S(chk, r[0]);20313 M(chk, chk, den);20314 if(neq25519(chk, num)) {20315 return -1;20316 }20317 if(par25519(r[0]) === (p[31] >> 7)) {20318 Z(r[0], gf0, r[0]);20319 }20320 M(r[3], r[0], r[1]);20321 return 0;20322}20323function unpack25519(o, n) {20324 var i;20325 for(i = 0; i < 16; ++i) {20326 o[i] = n[2 * i] + (n[2 * i + 1] << 8);20327 }20328 o[15] &= 0x7fff;20329}20330function pow2523(o, i) {20331 var c = gf();20332 var a;20333 for(a = 0; a < 16; ++a) {20334 c[a] = i[a];20335 }20336 for(a = 250; a >= 0; --a) {20337 S(c, c);20338 if(a !== 1) {20339 M(c, c, i);20340 }20341 }20342 for(a = 0; a < 16; ++a) {20343 o[a] = c[a];20344 }20345}20346function neq25519(a, b) {20347 var c = new NativeBuffer(32);20348 var d = new NativeBuffer(32);20349 pack25519(c, a);20350 pack25519(d, b);20351 return crypto_verify_32(c, 0, d, 0);20352}20353function crypto_verify_32(x, xi, y, yi) {20354 return vn(x, xi, y, yi, 32);20355}20356function vn(x, xi, y, yi, n) {20357 var i, d = 0;20358 for(i = 0; i < n; ++i) {20359 d |= x[xi + i] ^ y[yi + i];20360 }20361 return (1 & ((d - 1) >>> 8)) - 1;20362}20363function par25519(a) {20364 var d = new NativeBuffer(32);20365 pack25519(d, a);20366 return d[0] & 1;20367}20368function scalarmult(p, q, s) {20369 var b, i;20370 set25519(p[0], gf0);20371 set25519(p[1], gf1);20372 set25519(p[2], gf1);20373 set25519(p[3], gf0);20374 for(i = 255; i >= 0; --i) {20375 b = (s[(i / 8)|0] >> (i & 7)) & 1;20376 cswap(p, q, b);20377 add(q, p);20378 add(p, p);20379 cswap(p, q, b);20380 }20381}20382function scalarbase(p, s) {20383 var q = [gf(), gf(), gf(), gf()];20384 set25519(q[0], X);20385 set25519(q[1], Y);20386 set25519(q[2], gf1);20387 M(q[3], X, Y);20388 scalarmult(p, q, s);20389}20390function set25519(r, a) {20391 var i;20392 for(i = 0; i < 16; i++) {20393 r[i] = a[i] | 0;20394 }20395}20396function inv25519(o, i) {20397 var c = gf();20398 var a;20399 for(a = 0; a < 16; ++a) {20400 c[a] = i[a];20401 }20402 for(a = 253; a >= 0; --a) {20403 S(c, c);20404 if(a !== 2 && a !== 4) {20405 M(c, c, i);20406 }20407 }20408 for(a = 0; a < 16; ++a) {20409 o[a] = c[a];20410 }20411}20412function car25519(o) {20413 var i, v, c = 1;20414 for(i = 0; i < 16; ++i) {20415 v = o[i] + c + 65535;20416 c = Math.floor(v / 65536);20417 o[i] = v - c * 65536;20418 }20419 o[0] += c - 1 + 37 * (c - 1);20420}20421function sel25519(p, q, b) {20422 var t, c = ~(b - 1);20423 for(var i = 0; i < 16; ++i) {20424 t = c & (p[i] ^ q[i]);20425 p[i] ^= t;20426 q[i] ^= t;20427 }20428}20429function gf(init) {20430 var i, r = new Float64Array(16);20431 if(init) {20432 for(i = 0; i < init.length; ++i) {20433 r[i] = init[i];20434 }20435 }20436 return r;20437}20438function A(o, a, b) {20439 for(var i = 0; i < 16; ++i) {20440 o[i] = a[i] + b[i];20441 }20442}20443function Z(o, a, b) {20444 for(var i = 0; i < 16; ++i) {20445 o[i] = a[i] - b[i];20446 }20447}20448function S(o, a) {20449 M(o, a, a);20450}20451function M(o, a, b) {20452 var v, c,20453 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,20454 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,20455 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,20456 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,20457 b0 = b[0],20458 b1 = b[1],20459 b2 = b[2],20460 b3 = b[3],20461 b4 = b[4],20462 b5 = b[5],20463 b6 = b[6],20464 b7 = b[7],20465 b8 = b[8],20466 b9 = b[9],20467 b10 = b[10],20468 b11 = b[11],20469 b12 = b[12],20470 b13 = b[13],20471 b14 = b[14],20472 b15 = b[15];20473 v = a[0];20474 t0 += v * b0;20475 t1 += v * b1;20476 t2 += v * b2;20477 t3 += v * b3;20478 t4 += v * b4;20479 t5 += v * b5;20480 t6 += v * b6;20481 t7 += v * b7;20482 t8 += v * b8;20483 t9 += v * b9;20484 t10 += v * b10;20485 t11 += v * b11;20486 t12 += v * b12;20487 t13 += v * b13;20488 t14 += v * b14;20489 t15 += v * b15;20490 v = a[1];20491 t1 += v * b0;20492 t2 += v * b1;20493 t3 += v * b2;20494 t4 += v * b3;20495 t5 += v * b4;20496 t6 += v * b5;20497 t7 += v * b6;20498 t8 += v * b7;20499 t9 += v * b8;20500 t10 += v * b9;20501 t11 += v * b10;20502 t12 += v * b11;20503 t13 += v * b12;20504 t14 += v * b13;20505 t15 += v * b14;20506 t16 += v * b15;20507 v = a[2];20508 t2 += v * b0;20509 t3 += v * b1;20510 t4 += v * b2;20511 t5 += v * b3;20512 t6 += v * b4;20513 t7 += v * b5;20514 t8 += v * b6;20515 t9 += v * b7;20516 t10 += v * b8;20517 t11 += v * b9;20518 t12 += v * b10;20519 t13 += v * b11;20520 t14 += v * b12;20521 t15 += v * b13;20522 t16 += v * b14;20523 t17 += v * b15;20524 v = a[3];20525 t3 += v * b0;20526 t4 += v * b1;20527 t5 += v * b2;20528 t6 += v * b3;20529 t7 += v * b4;20530 t8 += v * b5;20531 t9 += v * b6;20532 t10 += v * b7;20533 t11 += v * b8;20534 t12 += v * b9;20535 t13 += v * b10;20536 t14 += v * b11;20537 t15 += v * b12;20538 t16 += v * b13;20539 t17 += v * b14;20540 t18 += v * b15;20541 v = a[4];20542 t4 += v * b0;20543 t5 += v * b1;20544 t6 += v * b2;20545 t7 += v * b3;20546 t8 += v * b4;20547 t9 += v * b5;20548 t10 += v * b6;20549 t11 += v * b7;20550 t12 += v * b8;20551 t13 += v * b9;20552 t14 += v * b10;20553 t15 += v * b11;20554 t16 += v * b12;20555 t17 += v * b13;20556 t18 += v * b14;20557 t19 += v * b15;20558 v = a[5];20559 t5 += v * b0;20560 t6 += v * b1;20561 t7 += v * b2;20562 t8 += v * b3;20563 t9 += v * b4;20564 t10 += v * b5;20565 t11 += v * b6;20566 t12 += v * b7;20567 t13 += v * b8;20568 t14 += v * b9;20569 t15 += v * b10;20570 t16 += v * b11;20571 t17 += v * b12;20572 t18 += v * b13;20573 t19 += v * b14;20574 t20 += v * b15;20575 v = a[6];20576 t6 += v * b0;20577 t7 += v * b1;20578 t8 += v * b2;20579 t9 += v * b3;20580 t10 += v * b4;20581 t11 += v * b5;20582 t12 += v * b6;20583 t13 += v * b7;20584 t14 += v * b8;20585 t15 += v * b9;20586 t16 += v * b10;20587 t17 += v * b11;20588 t18 += v * b12;20589 t19 += v * b13;20590 t20 += v * b14;20591 t21 += v * b15;20592 v = a[7];20593 t7 += v * b0;20594 t8 += v * b1;20595 t9 += v * b2;20596 t10 += v * b3;20597 t11 += v * b4;20598 t12 += v * b5;20599 t13 += v * b6;20600 t14 += v * b7;20601 t15 += v * b8;20602 t16 += v * b9;20603 t17 += v * b10;20604 t18 += v * b11;20605 t19 += v * b12;20606 t20 += v * b13;20607 t21 += v * b14;20608 t22 += v * b15;20609 v = a[8];20610 t8 += v * b0;20611 t9 += v * b1;20612 t10 += v * b2;20613 t11 += v * b3;20614 t12 += v * b4;20615 t13 += v * b5;20616 t14 += v * b6;20617 t15 += v * b7;20618 t16 += v * b8;20619 t17 += v * b9;20620 t18 += v * b10;20621 t19 += v * b11;20622 t20 += v * b12;20623 t21 += v * b13;20624 t22 += v * b14;20625 t23 += v * b15;20626 v = a[9];20627 t9 += v * b0;20628 t10 += v * b1;20629 t11 += v * b2;20630 t12 += v * b3;20631 t13 += v * b4;20632 t14 += v * b5;20633 t15 += v * b6;20634 t16 += v * b7;20635 t17 += v * b8;20636 t18 += v * b9;20637 t19 += v * b10;20638 t20 += v * b11;20639 t21 += v * b12;20640 t22 += v * b13;20641 t23 += v * b14;20642 t24 += v * b15;20643 v = a[10];20644 t10 += v * b0;20645 t11 += v * b1;20646 t12 += v * b2;20647 t13 += v * b3;20648 t14 += v * b4;20649 t15 += v * b5;20650 t16 += v * b6;20651 t17 += v * b7;20652 t18 += v * b8;20653 t19 += v * b9;20654 t20 += v * b10;20655 t21 += v * b11;20656 t22 += v * b12;20657 t23 += v * b13;20658 t24 += v * b14;20659 t25 += v * b15;20660 v = a[11];20661 t11 += v * b0;20662 t12 += v * b1;20663 t13 += v * b2;20664 t14 += v * b3;20665 t15 += v * b4;20666 t16 += v * b5;20667 t17 += v * b6;20668 t18 += v * b7;20669 t19 += v * b8;20670 t20 += v * b9;20671 t21 += v * b10;20672 t22 += v * b11;20673 t23 += v * b12;20674 t24 += v * b13;20675 t25 += v * b14;20676 t26 += v * b15;20677 v = a[12];20678 t12 += v * b0;20679 t13 += v * b1;20680 t14 += v * b2;20681 t15 += v * b3;20682 t16 += v * b4;20683 t17 += v * b5;20684 t18 += v * b6;20685 t19 += v * b7;20686 t20 += v * b8;20687 t21 += v * b9;20688 t22 += v * b10;20689 t23 += v * b11;20690 t24 += v * b12;20691 t25 += v * b13;20692 t26 += v * b14;20693 t27 += v * b15;20694 v = a[13];20695 t13 += v * b0;20696 t14 += v * b1;20697 t15 += v * b2;20698 t16 += v * b3;20699 t17 += v * b4;20700 t18 += v * b5;20701 t19 += v * b6;20702 t20 += v * b7;20703 t21 += v * b8;20704 t22 += v * b9;20705 t23 += v * b10;20706 t24 += v * b11;20707 t25 += v * b12;20708 t26 += v * b13;20709 t27 += v * b14;20710 t28 += v * b15;20711 v = a[14];20712 t14 += v * b0;20713 t15 += v * b1;20714 t16 += v * b2;20715 t17 += v * b3;20716 t18 += v * b4;20717 t19 += v * b5;20718 t20 += v * b6;20719 t21 += v * b7;20720 t22 += v * b8;20721 t23 += v * b9;20722 t24 += v * b10;20723 t25 += v * b11;20724 t26 += v * b12;20725 t27 += v * b13;20726 t28 += v * b14;20727 t29 += v * b15;20728 v = a[15];20729 t15 += v * b0;20730 t16 += v * b1;20731 t17 += v * b2;20732 t18 += v * b3;20733 t19 += v * b4;20734 t20 += v * b5;20735 t21 += v * b6;20736 t22 += v * b7;20737 t23 += v * b8;20738 t24 += v * b9;20739 t25 += v * b10;20740 t26 += v * b11;20741 t27 += v * b12;20742 t28 += v * b13;20743 t29 += v * b14;20744 t30 += v * b15;20745 t0 += 38 * t16;20746 t1 += 38 * t17;20747 t2 += 38 * t18;20748 t3 += 38 * t19;20749 t4 += 38 * t20;20750 t5 += 38 * t21;20751 t6 += 38 * t22;20752 t7 += 38 * t23;20753 t8 += 38 * t24;20754 t9 += 38 * t25;20755 t10 += 38 * t26;20756 t11 += 38 * t27;20757 t12 += 38 * t28;20758 t13 += 38 * t29;20759 t14 += 38 * t30;20760 // t15 left as is20761 // first car20762 c = 1;20763 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;20764 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;20765 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;20766 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;20767 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;20768 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;20769 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;20770 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;20771 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;20772 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;20773 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;20774 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;20775 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;20776 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;20777 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;20778 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;20779 t0 += c-1 + 37 * (c-1);20780 // second car20781 c = 1;20782 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;20783 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;20784 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;20785 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;20786 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;20787 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;20788 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;20789 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;20790 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;20791 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;20792 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;20793 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;20794 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;20795 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;20796 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;20797 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;20798 t0 += c-1 + 37 * (c-1);20799 o[ 0] = t0;20800 o[ 1] = t1;20801 o[ 2] = t2;20802 o[ 3] = t3;20803 o[ 4] = t4;20804 o[ 5] = t5;20805 o[ 6] = t6;20806 o[ 7] = t7;20807 o[ 8] = t8;20808 o[ 9] = t9;20809 o[10] = t10;20810 o[11] = t11;20811 o[12] = t12;20812 o[13] = t13;20813 o[14] = t14;20814 o[15] = t15;20815}20816/***/ }),20817/***/ 9177:20818/***/ ((module) => {20819/**20820 * Node.js module for Forge.20821 *20822 * @author Dave Longley20823 *20824 * Copyright 2011-2016 Digital Bazaar, Inc.20825 */20826module.exports = {20827 // default options20828 options: {20829 usePureJavaScript: false20830 }20831};20832/***/ }),20833/***/ 5104:20834/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {20835/**20836 * Hash-based Message Authentication Code implementation. Requires a message20837 * digest object that can be obtained, for example, from forge.md.sha1 or20838 * forge.md.md5.20839 *20840 * @author Dave Longley20841 *20842 * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.20843 */20844var forge = __nccwpck_require__(9177);20845__nccwpck_require__(6231);20846__nccwpck_require__(8339);20847/* HMAC API */20848var hmac = module.exports = forge.hmac = forge.hmac || {};20849/**20850 * Creates an HMAC object that uses the given message digest object.20851 *20852 * @return an HMAC object.20853 */20854hmac.create = function() {20855 // the hmac key to use20856 var _key = null;20857 // the message digest to use20858 var _md = null;20859 // the inner padding20860 var _ipadding = null;20861 // the outer padding20862 var _opadding = null;20863 // hmac context20864 var ctx = {};20865 /**20866 * Starts or restarts the HMAC with the given key and message digest.20867 *20868 * @param md the message digest to use, null to reuse the previous one,20869 * a string to use builtin 'sha1', 'md5', 'sha256'.20870 * @param key the key to use as a string, array of bytes, byte buffer,20871 * or null to reuse the previous key.20872 */20873 ctx.start = function(md, key) {20874 if(md !== null) {20875 if(typeof md === 'string') {20876 // create builtin message digest20877 md = md.toLowerCase();20878 if(md in forge.md.algorithms) {20879 _md = forge.md.algorithms[md].create();20880 } else {20881 throw new Error('Unknown hash algorithm "' + md + '"');20882 }20883 } else {20884 // store message digest20885 _md = md;20886 }20887 }20888 if(key === null) {20889 // reuse previous key20890 key = _key;20891 } else {20892 if(typeof key === 'string') {20893 // convert string into byte buffer20894 key = forge.util.createBuffer(key);20895 } else if(forge.util.isArray(key)) {20896 // convert byte array into byte buffer20897 var tmp = key;20898 key = forge.util.createBuffer();20899 for(var i = 0; i < tmp.length; ++i) {20900 key.putByte(tmp[i]);20901 }20902 }20903 // if key is longer than blocksize, hash it20904 var keylen = key.length();20905 if(keylen > _md.blockLength) {20906 _md.start();20907 _md.update(key.bytes());20908 key = _md.digest();20909 }20910 // mix key into inner and outer padding20911 // ipadding = [0x36 * blocksize] ^ key20912 // opadding = [0x5C * blocksize] ^ key20913 _ipadding = forge.util.createBuffer();20914 _opadding = forge.util.createBuffer();20915 keylen = key.length();20916 for(var i = 0; i < keylen; ++i) {20917 var tmp = key.at(i);20918 _ipadding.putByte(0x36 ^ tmp);20919 _opadding.putByte(0x5C ^ tmp);20920 }20921 // if key is shorter than blocksize, add additional padding20922 if(keylen < _md.blockLength) {20923 var tmp = _md.blockLength - keylen;20924 for(var i = 0; i < tmp; ++i) {20925 _ipadding.putByte(0x36);20926 _opadding.putByte(0x5C);20927 }20928 }20929 _key = key;20930 _ipadding = _ipadding.bytes();20931 _opadding = _opadding.bytes();20932 }20933 // digest is done like so: hash(opadding | hash(ipadding | message))20934 // prepare to do inner hash20935 // hash(ipadding | message)20936 _md.start();20937 _md.update(_ipadding);20938 };20939 /**20940 * Updates the HMAC with the given message bytes.20941 *20942 * @param bytes the bytes to update with.20943 */20944 ctx.update = function(bytes) {20945 _md.update(bytes);20946 };20947 /**20948 * Produces the Message Authentication Code (MAC).20949 *20950 * @return a byte buffer containing the digest value.20951 */20952 ctx.getMac = function() {20953 // digest is done like so: hash(opadding | hash(ipadding | message))20954 // here we do the outer hashing20955 var inner = _md.digest().bytes();20956 _md.start();20957 _md.update(_opadding);20958 _md.update(inner);20959 return _md.digest();20960 };20961 // alias for getMac20962 ctx.digest = ctx.getMac;20963 return ctx;20964};20965/***/ }),20966/***/ 7655:20967/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {20968/**20969 * Node.js module for Forge.20970 *20971 * @author Dave Longley20972 *20973 * Copyright 2011-2016 Digital Bazaar, Inc.20974 */20975module.exports = __nccwpck_require__(9177);20976__nccwpck_require__(7994);20977__nccwpck_require__(1449);20978__nccwpck_require__(9549);20979__nccwpck_require__(7088);20980__nccwpck_require__(7157);20981__nccwpck_require__(0);20982__nccwpck_require__(5104);20983__nccwpck_require__(5173);20984__nccwpck_require__(9994);20985__nccwpck_require__(1145);20986__nccwpck_require__(3339);20987__nccwpck_require__(1611);20988__nccwpck_require__(154);20989__nccwpck_require__(7014);20990__nccwpck_require__(466);20991__nccwpck_require__(4829);20992__nccwpck_require__(6924);20993__nccwpck_require__(6861);20994__nccwpck_require__(4467);20995__nccwpck_require__(4376);20996__nccwpck_require__(7821);20997__nccwpck_require__(9965);20998__nccwpck_require__(4280);20999__nccwpck_require__(9167);21000__nccwpck_require__(8339);21001/***/ }),21002/***/ 7052:21003/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {21004// Copyright (c) 2005 Tom Wu21005// All Rights Reserved.21006// See "LICENSE" for details.21007// Basic JavaScript BN library - subset useful for RSA encryption.21008/*21009Licensing (LICENSE)21010-------------------21011This software is covered under the following copyright:21012*/21013/*21014 * Copyright (c) 2003-2005 Tom Wu21015 * All Rights Reserved.21016 *21017 * Permission is hereby granted, free of charge, to any person obtaining21018 * a copy of this software and associated documentation files (the21019 * "Software"), to deal in the Software without restriction, including21020 * without limitation the rights to use, copy, modify, merge, publish,21021 * distribute, sublicense, and/or sell copies of the Software, and to21022 * permit persons to whom the Software is furnished to do so, subject to21023 * the following conditions:21024 *21025 * The above copyright notice and this permission notice shall be21026 * included in all copies or substantial portions of the Software.21027 *21028 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,21029 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY21030 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.21031 *21032 * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,21033 * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER21034 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF21035 * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT21036 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.21037 *21038 * In addition, the following condition applies:21039 *21040 * All redistributions must retain an intact copy of this copyright notice21041 * and disclaimer.21042 */21043/*21044Address all questions regarding this license to:21045 Tom Wu21046 tjw@cs.Stanford.EDU21047*/21048var forge = __nccwpck_require__(9177);21049module.exports = forge.jsbn = forge.jsbn || {};21050// Bits per digit21051var dbits;21052// JavaScript engine analysis21053var canary = 0xdeadbeefcafe;21054var j_lm = ((canary&0xffffff)==0xefcafe);21055// (public) Constructor21056function BigInteger(a,b,c) {21057 this.data = [];21058 if(a != null)21059 if("number" == typeof a) this.fromNumber(a,b,c);21060 else if(b == null && "string" != typeof a) this.fromString(a,256);21061 else this.fromString(a,b);21062}21063forge.jsbn.BigInteger = BigInteger;21064// return new, unset BigInteger21065function nbi() { return new BigInteger(null); }21066// am: Compute w_j += (x*this_i), propagate carries,21067// c is initial carry, returns final carry.21068// c < 3*dvalue, x < 2*dvalue, this_i < dvalue21069// We need to select the fastest one that works in this environment.21070// am1: use a single mult and divide to get the high bits,21071// max digit bits should be 26 because21072// max internal value = 2*dvalue^2-2*dvalue (< 2^53)21073function am1(i,x,w,j,c,n) {21074 while(--n >= 0) {21075 var v = x*this.data[i++]+w.data[j]+c;21076 c = Math.floor(v/0x4000000);21077 w.data[j++] = v&0x3ffffff;21078 }21079 return c;21080}21081// am2 avoids a big mult-and-extract completely.21082// Max digit bits should be <= 30 because we do bitwise ops21083// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)21084function am2(i,x,w,j,c,n) {21085 var xl = x&0x7fff, xh = x>>15;21086 while(--n >= 0) {21087 var l = this.data[i]&0x7fff;21088 var h = this.data[i++]>>15;21089 var m = xh*l+h*xl;21090 l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);21091 c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);21092 w.data[j++] = l&0x3fffffff;21093 }21094 return c;21095}21096// Alternately, set max digit bits to 28 since some21097// browsers slow down when dealing with 32-bit numbers.21098function am3(i,x,w,j,c,n) {21099 var xl = x&0x3fff, xh = x>>14;21100 while(--n >= 0) {21101 var l = this.data[i]&0x3fff;21102 var h = this.data[i++]>>14;21103 var m = xh*l+h*xl;21104 l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;21105 c = (l>>28)+(m>>14)+xh*h;21106 w.data[j++] = l&0xfffffff;21107 }21108 return c;21109}21110// node.js (no browser)21111if(typeof(navigator) === 'undefined')21112{21113 BigInteger.prototype.am = am3;21114 dbits = 28;21115} else if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) {21116 BigInteger.prototype.am = am2;21117 dbits = 30;21118} else if(j_lm && (navigator.appName != "Netscape")) {21119 BigInteger.prototype.am = am1;21120 dbits = 26;21121} else { // Mozilla/Netscape seems to prefer am321122 BigInteger.prototype.am = am3;21123 dbits = 28;21124}21125BigInteger.prototype.DB = dbits;21126BigInteger.prototype.DM = ((1<<dbits)-1);21127BigInteger.prototype.DV = (1<<dbits);21128var BI_FP = 52;21129BigInteger.prototype.FV = Math.pow(2,BI_FP);21130BigInteger.prototype.F1 = BI_FP-dbits;21131BigInteger.prototype.F2 = 2*dbits-BI_FP;21132// Digit conversions21133var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";21134var BI_RC = new Array();21135var rr,vv;21136rr = "0".charCodeAt(0);21137for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;21138rr = "a".charCodeAt(0);21139for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;21140rr = "A".charCodeAt(0);21141for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;21142function int2char(n) { return BI_RM.charAt(n); }21143function intAt(s,i) {21144 var c = BI_RC[s.charCodeAt(i)];21145 return (c==null)?-1:c;21146}21147// (protected) copy this to r21148function bnpCopyTo(r) {21149 for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];21150 r.t = this.t;21151 r.s = this.s;21152}21153// (protected) set from integer value x, -DV <= x < DV21154function bnpFromInt(x) {21155 this.t = 1;21156 this.s = (x<0)?-1:0;21157 if(x > 0) this.data[0] = x;21158 else if(x < -1) this.data[0] = x+this.DV;21159 else this.t = 0;21160}21161// return bigint initialized to value21162function nbv(i) { var r = nbi(); r.fromInt(i); return r; }21163// (protected) set from string and radix21164function bnpFromString(s,b) {21165 var k;21166 if(b == 16) k = 4;21167 else if(b == 8) k = 3;21168 else if(b == 256) k = 8; // byte array21169 else if(b == 2) k = 1;21170 else if(b == 32) k = 5;21171 else if(b == 4) k = 2;21172 else { this.fromRadix(s,b); return; }21173 this.t = 0;21174 this.s = 0;21175 var i = s.length, mi = false, sh = 0;21176 while(--i >= 0) {21177 var x = (k==8)?s[i]&0xff:intAt(s,i);21178 if(x < 0) {21179 if(s.charAt(i) == "-") mi = true;21180 continue;21181 }21182 mi = false;21183 if(sh == 0)21184 this.data[this.t++] = x;21185 else if(sh+k > this.DB) {21186 this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;21187 this.data[this.t++] = (x>>(this.DB-sh));21188 } else21189 this.data[this.t-1] |= x<<sh;21190 sh += k;21191 if(sh >= this.DB) sh -= this.DB;21192 }21193 if(k == 8 && (s[0]&0x80) != 0) {21194 this.s = -1;21195 if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;21196 }21197 this.clamp();21198 if(mi) BigInteger.ZERO.subTo(this,this);21199}21200// (protected) clamp off excess high words21201function bnpClamp() {21202 var c = this.s&this.DM;21203 while(this.t > 0 && this.data[this.t-1] == c) --this.t;21204}21205// (public) return string representation in given radix21206function bnToString(b) {21207 if(this.s < 0) return "-"+this.negate().toString(b);21208 var k;21209 if(b == 16) k = 4;21210 else if(b == 8) k = 3;21211 else if(b == 2) k = 1;21212 else if(b == 32) k = 5;21213 else if(b == 4) k = 2;21214 else return this.toRadix(b);21215 var km = (1<<k)-1, d, m = false, r = "", i = this.t;21216 var p = this.DB-(i*this.DB)%k;21217 if(i-- > 0) {21218 if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }21219 while(i >= 0) {21220 if(p < k) {21221 d = (this.data[i]&((1<<p)-1))<<(k-p);21222 d |= this.data[--i]>>(p+=this.DB-k);21223 } else {21224 d = (this.data[i]>>(p-=k))&km;21225 if(p <= 0) { p += this.DB; --i; }21226 }21227 if(d > 0) m = true;21228 if(m) r += int2char(d);21229 }21230 }21231 return m?r:"0";21232}21233// (public) -this21234function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }21235// (public) |this|21236function bnAbs() { return (this.s<0)?this.negate():this; }21237// (public) return + if this > a, - if this < a, 0 if equal21238function bnCompareTo(a) {21239 var r = this.s-a.s;21240 if(r != 0) return r;21241 var i = this.t;21242 r = i-a.t;21243 if(r != 0) return (this.s<0)?-r:r;21244 while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;21245 return 0;21246}21247// returns bit length of the integer x21248function nbits(x) {21249 var r = 1, t;21250 if((t=x>>>16) != 0) { x = t; r += 16; }21251 if((t=x>>8) != 0) { x = t; r += 8; }21252 if((t=x>>4) != 0) { x = t; r += 4; }21253 if((t=x>>2) != 0) { x = t; r += 2; }21254 if((t=x>>1) != 0) { x = t; r += 1; }21255 return r;21256}21257// (public) return the number of bits in "this"21258function bnBitLength() {21259 if(this.t <= 0) return 0;21260 return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));21261}21262// (protected) r = this << n*DB21263function bnpDLShiftTo(n,r) {21264 var i;21265 for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];21266 for(i = n-1; i >= 0; --i) r.data[i] = 0;21267 r.t = this.t+n;21268 r.s = this.s;21269}21270// (protected) r = this >> n*DB21271function bnpDRShiftTo(n,r) {21272 for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];21273 r.t = Math.max(this.t-n,0);21274 r.s = this.s;21275}21276// (protected) r = this << n21277function bnpLShiftTo(n,r) {21278 var bs = n%this.DB;21279 var cbs = this.DB-bs;21280 var bm = (1<<cbs)-1;21281 var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;21282 for(i = this.t-1; i >= 0; --i) {21283 r.data[i+ds+1] = (this.data[i]>>cbs)|c;21284 c = (this.data[i]&bm)<<bs;21285 }21286 for(i = ds-1; i >= 0; --i) r.data[i] = 0;21287 r.data[ds] = c;21288 r.t = this.t+ds+1;21289 r.s = this.s;21290 r.clamp();21291}21292// (protected) r = this >> n21293function bnpRShiftTo(n,r) {21294 r.s = this.s;21295 var ds = Math.floor(n/this.DB);21296 if(ds >= this.t) { r.t = 0; return; }21297 var bs = n%this.DB;21298 var cbs = this.DB-bs;21299 var bm = (1<<bs)-1;21300 r.data[0] = this.data[ds]>>bs;21301 for(var i = ds+1; i < this.t; ++i) {21302 r.data[i-ds-1] |= (this.data[i]&bm)<<cbs;21303 r.data[i-ds] = this.data[i]>>bs;21304 }21305 if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<<cbs;21306 r.t = this.t-ds;21307 r.clamp();21308}21309// (protected) r = this - a21310function bnpSubTo(a,r) {21311 var i = 0, c = 0, m = Math.min(a.t,this.t);21312 while(i < m) {21313 c += this.data[i]-a.data[i];21314 r.data[i++] = c&this.DM;21315 c >>= this.DB;21316 }21317 if(a.t < this.t) {21318 c -= a.s;21319 while(i < this.t) {21320 c += this.data[i];21321 r.data[i++] = c&this.DM;21322 c >>= this.DB;21323 }21324 c += this.s;21325 } else {21326 c += this.s;21327 while(i < a.t) {21328 c -= a.data[i];21329 r.data[i++] = c&this.DM;21330 c >>= this.DB;21331 }21332 c -= a.s;21333 }21334 r.s = (c<0)?-1:0;21335 if(c < -1) r.data[i++] = this.DV+c;21336 else if(c > 0) r.data[i++] = c;21337 r.t = i;21338 r.clamp();21339}21340// (protected) r = this * a, r != this,a (HAC 14.12)21341// "this" should be the larger one if appropriate.21342function bnpMultiplyTo(a,r) {21343 var x = this.abs(), y = a.abs();21344 var i = x.t;21345 r.t = i+y.t;21346 while(--i >= 0) r.data[i] = 0;21347 for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);21348 r.s = 0;21349 r.clamp();21350 if(this.s != a.s) BigInteger.ZERO.subTo(r,r);21351}21352// (protected) r = this^2, r != this (HAC 14.16)21353function bnpSquareTo(r) {21354 var x = this.abs();21355 var i = r.t = 2*x.t;21356 while(--i >= 0) r.data[i] = 0;21357 for(i = 0; i < x.t-1; ++i) {21358 var c = x.am(i,x.data[i],r,2*i,0,1);21359 if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {21360 r.data[i+x.t] -= x.DV;21361 r.data[i+x.t+1] = 1;21362 }21363 }21364 if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);21365 r.s = 0;21366 r.clamp();21367}21368// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)21369// r != q, this != m. q or r may be null.21370function bnpDivRemTo(m,q,r) {21371 var pm = m.abs();21372 if(pm.t <= 0) return;21373 var pt = this.abs();21374 if(pt.t < pm.t) {21375 if(q != null) q.fromInt(0);21376 if(r != null) this.copyTo(r);21377 return;21378 }21379 if(r == null) r = nbi();21380 var y = nbi(), ts = this.s, ms = m.s;21381 var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus21382 if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }21383 var ys = y.t;21384 var y0 = y.data[ys-1];21385 if(y0 == 0) return;21386 var yt = y0*(1<<this.F1)+((ys>1)?y.data[ys-2]>>this.F2:0);21387 var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;21388 var i = r.t, j = i-ys, t = (q==null)?nbi():q;21389 y.dlShiftTo(j,t);21390 if(r.compareTo(t) >= 0) {21391 r.data[r.t++] = 1;21392 r.subTo(t,r);21393 }21394 BigInteger.ONE.dlShiftTo(ys,t);21395 t.subTo(y,y); // "negative" y so we can replace sub with am later21396 while(y.t < ys) y.data[y.t++] = 0;21397 while(--j >= 0) {21398 // Estimate quotient digit21399 var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);21400 if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out21401 y.dlShiftTo(j,t);21402 r.subTo(t,r);21403 while(r.data[i] < --qd) r.subTo(t,r);21404 }21405 }21406 if(q != null) {21407 r.drShiftTo(ys,q);21408 if(ts != ms) BigInteger.ZERO.subTo(q,q);21409 }21410 r.t = ys;21411 r.clamp();21412 if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder21413 if(ts < 0) BigInteger.ZERO.subTo(r,r);21414}21415// (public) this mod a21416function bnMod(a) {21417 var r = nbi();21418 this.abs().divRemTo(a,null,r);21419 if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);21420 return r;21421}21422// Modular reduction using "classic" algorithm21423function Classic(m) { this.m = m; }21424function cConvert(x) {21425 if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);21426 else return x;21427}21428function cRevert(x) { return x; }21429function cReduce(x) { x.divRemTo(this.m,null,x); }21430function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }21431function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }21432Classic.prototype.convert = cConvert;21433Classic.prototype.revert = cRevert;21434Classic.prototype.reduce = cReduce;21435Classic.prototype.mulTo = cMulTo;21436Classic.prototype.sqrTo = cSqrTo;21437// (protected) return "-1/this % 2^DB"; useful for Mont. reduction21438// justification:21439// xy == 1 (mod m)21440// xy = 1+km21441// xy(2-xy) = (1+km)(1-km)21442// x[y(2-xy)] = 1-k^2m^221443// x[y(2-xy)] == 1 (mod m^2)21444// if y is 1/x mod m, then y(2-xy) is 1/x mod m^221445// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.21446// JS multiply "overflows" differently from C/C++, so care is needed here.21447function bnpInvDigit() {21448 if(this.t < 1) return 0;21449 var x = this.data[0];21450 if((x&1) == 0) return 0;21451 var y = x&3; // y == 1/x mod 2^221452 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^421453 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^821454 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^1621455 // last step - calculate inverse mod DV directly;21456 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints21457 y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits21458 // we really want the negative inverse, and -DV < y < DV21459 return (y>0)?this.DV-y:-y;21460}21461// Montgomery reduction21462function Montgomery(m) {21463 this.m = m;21464 this.mp = m.invDigit();21465 this.mpl = this.mp&0x7fff;21466 this.mph = this.mp>>15;21467 this.um = (1<<(m.DB-15))-1;21468 this.mt2 = 2*m.t;21469}21470// xR mod m21471function montConvert(x) {21472 var r = nbi();21473 x.abs().dlShiftTo(this.m.t,r);21474 r.divRemTo(this.m,null,r);21475 if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);21476 return r;21477}21478// x/R mod m21479function montRevert(x) {21480 var r = nbi();21481 x.copyTo(r);21482 this.reduce(r);21483 return r;21484}21485// x = x/R mod m (HAC 14.32)21486function montReduce(x) {21487 while(x.t <= this.mt2) // pad x so am has enough room later21488 x.data[x.t++] = 0;21489 for(var i = 0; i < this.m.t; ++i) {21490 // faster way of calculating u0 = x.data[i]*mp mod DV21491 var j = x.data[i]&0x7fff;21492 var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;21493 // use am to combine the multiply-shift-add into one call21494 j = i+this.m.t;21495 x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);21496 // propagate carry21497 while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }21498 }21499 x.clamp();21500 x.drShiftTo(this.m.t,x);21501 if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);21502}21503// r = "x^2/R mod m"; x != r21504function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }21505// r = "xy/R mod m"; x,y != r21506function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }21507Montgomery.prototype.convert = montConvert;21508Montgomery.prototype.revert = montRevert;21509Montgomery.prototype.reduce = montReduce;21510Montgomery.prototype.mulTo = montMulTo;21511Montgomery.prototype.sqrTo = montSqrTo;21512// (protected) true iff this is even21513function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }21514// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)21515function bnpExp(e,z) {21516 if(e > 0xffffffff || e < 1) return BigInteger.ONE;21517 var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;21518 g.copyTo(r);21519 while(--i >= 0) {21520 z.sqrTo(r,r2);21521 if((e&(1<<i)) > 0) z.mulTo(r2,g,r);21522 else { var t = r; r = r2; r2 = t; }21523 }21524 return z.revert(r);21525}21526// (public) this^e % m, 0 <= e < 2^3221527function bnModPowInt(e,m) {21528 var z;21529 if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);21530 return this.exp(e,z);21531}21532// protected21533BigInteger.prototype.copyTo = bnpCopyTo;21534BigInteger.prototype.fromInt = bnpFromInt;21535BigInteger.prototype.fromString = bnpFromString;21536BigInteger.prototype.clamp = bnpClamp;21537BigInteger.prototype.dlShiftTo = bnpDLShiftTo;21538BigInteger.prototype.drShiftTo = bnpDRShiftTo;21539BigInteger.prototype.lShiftTo = bnpLShiftTo;21540BigInteger.prototype.rShiftTo = bnpRShiftTo;21541BigInteger.prototype.subTo = bnpSubTo;21542BigInteger.prototype.multiplyTo = bnpMultiplyTo;21543BigInteger.prototype.squareTo = bnpSquareTo;21544BigInteger.prototype.divRemTo = bnpDivRemTo;21545BigInteger.prototype.invDigit = bnpInvDigit;21546BigInteger.prototype.isEven = bnpIsEven;21547BigInteger.prototype.exp = bnpExp;21548// public21549BigInteger.prototype.toString = bnToString;21550BigInteger.prototype.negate = bnNegate;21551BigInteger.prototype.abs = bnAbs;21552BigInteger.prototype.compareTo = bnCompareTo;21553BigInteger.prototype.bitLength = bnBitLength;21554BigInteger.prototype.mod = bnMod;21555BigInteger.prototype.modPowInt = bnModPowInt;21556// "constants"21557BigInteger.ZERO = nbv(0);21558BigInteger.ONE = nbv(1);21559// jsbn2 lib21560//Copyright (c) 2005-2009 Tom Wu21561//All Rights Reserved.21562//See "LICENSE" for details (See jsbn.js for LICENSE).21563//Extended JavaScript BN functions, required for RSA private ops.21564//Version 1.1: new BigInteger("0", 10) returns "proper" zero21565//(public)21566function bnClone() { var r = nbi(); this.copyTo(r); return r; }21567//(public) return value as integer21568function bnIntValue() {21569if(this.s < 0) {21570 if(this.t == 1) return this.data[0]-this.DV;21571 else if(this.t == 0) return -1;21572} else if(this.t == 1) return this.data[0];21573else if(this.t == 0) return 0;21574// assumes 16 < DB < 3221575return ((this.data[1]&((1<<(32-this.DB))-1))<<this.DB)|this.data[0];21576}21577//(public) return value as byte21578function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }21579//(public) return value as short (assumes DB>=16)21580function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }21581//(protected) return x s.t. r^x < DV21582function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }21583//(public) 0 if this == 0, 1 if this > 021584function bnSigNum() {21585if(this.s < 0) return -1;21586else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;21587else return 1;21588}21589//(protected) convert to radix string21590function bnpToRadix(b) {21591if(b == null) b = 10;21592if(this.signum() == 0 || b < 2 || b > 36) return "0";21593var cs = this.chunkSize(b);21594var a = Math.pow(b,cs);21595var d = nbv(a), y = nbi(), z = nbi(), r = "";21596this.divRemTo(d,y,z);21597while(y.signum() > 0) {21598 r = (a+z.intValue()).toString(b).substr(1) + r;21599 y.divRemTo(d,y,z);21600}21601return z.intValue().toString(b) + r;21602}21603//(protected) convert from radix string21604function bnpFromRadix(s,b) {21605this.fromInt(0);21606if(b == null) b = 10;21607var cs = this.chunkSize(b);21608var d = Math.pow(b,cs), mi = false, j = 0, w = 0;21609for(var i = 0; i < s.length; ++i) {21610 var x = intAt(s,i);21611 if(x < 0) {21612 if(s.charAt(i) == "-" && this.signum() == 0) mi = true;21613 continue;21614 }21615 w = b*w+x;21616 if(++j >= cs) {21617 this.dMultiply(d);21618 this.dAddOffset(w,0);21619 j = 0;21620 w = 0;21621 }21622}21623if(j > 0) {21624 this.dMultiply(Math.pow(b,j));21625 this.dAddOffset(w,0);21626}21627if(mi) BigInteger.ZERO.subTo(this,this);21628}21629//(protected) alternate constructor21630function bnpFromNumber(a,b,c) {21631if("number" == typeof b) {21632 // new BigInteger(int,int,RNG)21633 if(a < 2) this.fromInt(1);21634 else {21635 this.fromNumber(a,c);21636 if(!this.testBit(a-1)) // force MSB set21637 this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);21638 if(this.isEven()) this.dAddOffset(1,0); // force odd21639 while(!this.isProbablePrime(b)) {21640 this.dAddOffset(2,0);21641 if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);21642 }21643 }21644} else {21645 // new BigInteger(int,RNG)21646 var x = new Array(), t = a&7;21647 x.length = (a>>3)+1;21648 b.nextBytes(x);21649 if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;21650 this.fromString(x,256);21651}21652}21653//(public) convert to bigendian byte array21654function bnToByteArray() {21655var i = this.t, r = new Array();21656r[0] = this.s;21657var p = this.DB-(i*this.DB)%8, d, k = 0;21658if(i-- > 0) {21659 if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)21660 r[k++] = d|(this.s<<(this.DB-p));21661 while(i >= 0) {21662 if(p < 8) {21663 d = (this.data[i]&((1<<p)-1))<<(8-p);21664 d |= this.data[--i]>>(p+=this.DB-8);21665 } else {21666 d = (this.data[i]>>(p-=8))&0xff;21667 if(p <= 0) { p += this.DB; --i; }21668 }21669 if((d&0x80) != 0) d |= -256;21670 if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;21671 if(k > 0 || d != this.s) r[k++] = d;21672 }21673}21674return r;21675}21676function bnEquals(a) { return(this.compareTo(a)==0); }21677function bnMin(a) { return(this.compareTo(a)<0)?this:a; }21678function bnMax(a) { return(this.compareTo(a)>0)?this:a; }21679//(protected) r = this op a (bitwise)21680function bnpBitwiseTo(a,op,r) {21681var i, f, m = Math.min(a.t,this.t);21682for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);21683if(a.t < this.t) {21684 f = a.s&this.DM;21685 for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);21686 r.t = this.t;21687} else {21688 f = this.s&this.DM;21689 for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);21690 r.t = a.t;21691}21692r.s = op(this.s,a.s);21693r.clamp();21694}21695//(public) this & a21696function op_and(x,y) { return x&y; }21697function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }21698//(public) this | a21699function op_or(x,y) { return x|y; }21700function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }21701//(public) this ^ a21702function op_xor(x,y) { return x^y; }21703function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }21704//(public) this & ~a21705function op_andnot(x,y) { return x&~y; }21706function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }21707//(public) ~this21708function bnNot() {21709var r = nbi();21710for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];21711r.t = this.t;21712r.s = ~this.s;21713return r;21714}21715//(public) this << n21716function bnShiftLeft(n) {21717var r = nbi();21718if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);21719return r;21720}21721//(public) this >> n21722function bnShiftRight(n) {21723var r = nbi();21724if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);21725return r;21726}21727//return index of lowest 1-bit in x, x < 2^3121728function lbit(x) {21729if(x == 0) return -1;21730var r = 0;21731if((x&0xffff) == 0) { x >>= 16; r += 16; }21732if((x&0xff) == 0) { x >>= 8; r += 8; }21733if((x&0xf) == 0) { x >>= 4; r += 4; }21734if((x&3) == 0) { x >>= 2; r += 2; }21735if((x&1) == 0) ++r;21736return r;21737}21738//(public) returns index of lowest 1-bit (or -1 if none)21739function bnGetLowestSetBit() {21740for(var i = 0; i < this.t; ++i)21741 if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);21742if(this.s < 0) return this.t*this.DB;21743return -1;21744}21745//return number of 1 bits in x21746function cbit(x) {21747var r = 0;21748while(x != 0) { x &= x-1; ++r; }21749return r;21750}21751//(public) return number of set bits21752function bnBitCount() {21753var r = 0, x = this.s&this.DM;21754for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);21755return r;21756}21757//(public) true iff nth bit is set21758function bnTestBit(n) {21759var j = Math.floor(n/this.DB);21760if(j >= this.t) return(this.s!=0);21761return((this.data[j]&(1<<(n%this.DB)))!=0);21762}21763//(protected) this op (1<<n)21764function bnpChangeBit(n,op) {21765var r = BigInteger.ONE.shiftLeft(n);21766this.bitwiseTo(r,op,r);21767return r;21768}21769//(public) this | (1<<n)21770function bnSetBit(n) { return this.changeBit(n,op_or); }21771//(public) this & ~(1<<n)21772function bnClearBit(n) { return this.changeBit(n,op_andnot); }21773//(public) this ^ (1<<n)21774function bnFlipBit(n) { return this.changeBit(n,op_xor); }21775//(protected) r = this + a21776function bnpAddTo(a,r) {21777var i = 0, c = 0, m = Math.min(a.t,this.t);21778while(i < m) {21779 c += this.data[i]+a.data[i];21780 r.data[i++] = c&this.DM;21781 c >>= this.DB;21782}21783if(a.t < this.t) {21784 c += a.s;21785 while(i < this.t) {21786 c += this.data[i];21787 r.data[i++] = c&this.DM;21788 c >>= this.DB;21789 }21790 c += this.s;21791} else {21792 c += this.s;21793 while(i < a.t) {21794 c += a.data[i];21795 r.data[i++] = c&this.DM;21796 c >>= this.DB;21797 }21798 c += a.s;21799}21800r.s = (c<0)?-1:0;21801if(c > 0) r.data[i++] = c;21802else if(c < -1) r.data[i++] = this.DV+c;21803r.t = i;21804r.clamp();21805}21806//(public) this + a21807function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }21808//(public) this - a21809function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }21810//(public) this * a21811function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }21812//(public) this / a21813function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }21814//(public) this % a21815function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }21816//(public) [this/a,this%a]21817function bnDivideAndRemainder(a) {21818var q = nbi(), r = nbi();21819this.divRemTo(a,q,r);21820return new Array(q,r);21821}21822//(protected) this *= n, this >= 0, 1 < n < DV21823function bnpDMultiply(n) {21824this.data[this.t] = this.am(0,n-1,this,0,0,this.t);21825++this.t;21826this.clamp();21827}21828//(protected) this += n << w words, this >= 021829function bnpDAddOffset(n,w) {21830if(n == 0) return;21831while(this.t <= w) this.data[this.t++] = 0;21832this.data[w] += n;21833while(this.data[w] >= this.DV) {21834 this.data[w] -= this.DV;21835 if(++w >= this.t) this.data[this.t++] = 0;21836 ++this.data[w];21837}21838}21839//A "null" reducer21840function NullExp() {}21841function nNop(x) { return x; }21842function nMulTo(x,y,r) { x.multiplyTo(y,r); }21843function nSqrTo(x,r) { x.squareTo(r); }21844NullExp.prototype.convert = nNop;21845NullExp.prototype.revert = nNop;21846NullExp.prototype.mulTo = nMulTo;21847NullExp.prototype.sqrTo = nSqrTo;21848//(public) this^e21849function bnPow(e) { return this.exp(e,new NullExp()); }21850//(protected) r = lower n words of "this * a", a.t <= n21851//"this" should be the larger one if appropriate.21852function bnpMultiplyLowerTo(a,n,r) {21853var i = Math.min(this.t+a.t,n);21854r.s = 0; // assumes a,this >= 021855r.t = i;21856while(i > 0) r.data[--i] = 0;21857var j;21858for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);21859for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);21860r.clamp();21861}21862//(protected) r = "this * a" without lower n words, n > 021863//"this" should be the larger one if appropriate.21864function bnpMultiplyUpperTo(a,n,r) {21865--n;21866var i = r.t = this.t+a.t-n;21867r.s = 0; // assumes a,this >= 021868while(--i >= 0) r.data[i] = 0;21869for(i = Math.max(n-this.t,0); i < a.t; ++i)21870 r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);21871r.clamp();21872r.drShiftTo(1,r);21873}21874//Barrett modular reduction21875function Barrett(m) {21876// setup Barrett21877this.r2 = nbi();21878this.q3 = nbi();21879BigInteger.ONE.dlShiftTo(2*m.t,this.r2);21880this.mu = this.r2.divide(m);21881this.m = m;21882}21883function barrettConvert(x) {21884if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);21885else if(x.compareTo(this.m) < 0) return x;21886else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }21887}21888function barrettRevert(x) { return x; }21889//x = x mod m (HAC 14.42)21890function barrettReduce(x) {21891x.drShiftTo(this.m.t-1,this.r2);21892if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }21893this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);21894this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);21895while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);21896x.subTo(this.r2,x);21897while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);21898}21899//r = x^2 mod m; x != r21900function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }21901//r = x*y mod m; x,y != r21902function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }21903Barrett.prototype.convert = barrettConvert;21904Barrett.prototype.revert = barrettRevert;21905Barrett.prototype.reduce = barrettReduce;21906Barrett.prototype.mulTo = barrettMulTo;21907Barrett.prototype.sqrTo = barrettSqrTo;21908//(public) this^e % m (HAC 14.85)21909function bnModPow(e,m) {21910var i = e.bitLength(), k, r = nbv(1), z;21911if(i <= 0) return r;21912else if(i < 18) k = 1;21913else if(i < 48) k = 3;21914else if(i < 144) k = 4;21915else if(i < 768) k = 5;21916else k = 6;21917if(i < 8)21918 z = new Classic(m);21919else if(m.isEven())21920 z = new Barrett(m);21921else21922 z = new Montgomery(m);21923// precomputation21924var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;21925g[1] = z.convert(this);21926if(k > 1) {21927 var g2 = nbi();21928 z.sqrTo(g[1],g2);21929 while(n <= km) {21930 g[n] = nbi();21931 z.mulTo(g2,g[n-2],g[n]);21932 n += 2;21933 }21934}21935var j = e.t-1, w, is1 = true, r2 = nbi(), t;21936i = nbits(e.data[j])-1;21937while(j >= 0) {21938 if(i >= k1) w = (e.data[j]>>(i-k1))&km;21939 else {21940 w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);21941 if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);21942 }21943 n = k;21944 while((w&1) == 0) { w >>= 1; --n; }21945 if((i -= n) < 0) { i += this.DB; --j; }21946 if(is1) { // ret == 1, don't bother squaring or multiplying it21947 g[w].copyTo(r);21948 is1 = false;21949 } else {21950 while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }21951 if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }21952 z.mulTo(r2,g[w],r);21953 }21954 while(j >= 0 && (e.data[j]&(1<<i)) == 0) {21955 z.sqrTo(r,r2); t = r; r = r2; r2 = t;21956 if(--i < 0) { i = this.DB-1; --j; }21957 }21958}21959return z.revert(r);21960}21961//(public) gcd(this,a) (HAC 14.54)21962function bnGCD(a) {21963var x = (this.s<0)?this.negate():this.clone();21964var y = (a.s<0)?a.negate():a.clone();21965if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }21966var i = x.getLowestSetBit(), g = y.getLowestSetBit();21967if(g < 0) return x;21968if(i < g) g = i;21969if(g > 0) {21970 x.rShiftTo(g,x);21971 y.rShiftTo(g,y);21972}21973while(x.signum() > 0) {21974 if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);21975 if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);21976 if(x.compareTo(y) >= 0) {21977 x.subTo(y,x);21978 x.rShiftTo(1,x);21979 } else {21980 y.subTo(x,y);21981 y.rShiftTo(1,y);21982 }21983}21984if(g > 0) y.lShiftTo(g,y);21985return y;21986}21987//(protected) this % n, n < 2^2621988function bnpModInt(n) {21989if(n <= 0) return 0;21990var d = this.DV%n, r = (this.s<0)?n-1:0;21991if(this.t > 0)21992 if(d == 0) r = this.data[0]%n;21993 else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;21994return r;21995}21996//(public) 1/this % m (HAC 14.61)21997function bnModInverse(m) {21998var ac = m.isEven();21999if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;22000var u = m.clone(), v = this.clone();22001var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);22002while(u.signum() != 0) {22003 while(u.isEven()) {22004 u.rShiftTo(1,u);22005 if(ac) {22006 if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }22007 a.rShiftTo(1,a);22008 } else if(!b.isEven()) b.subTo(m,b);22009 b.rShiftTo(1,b);22010 }22011 while(v.isEven()) {22012 v.rShiftTo(1,v);22013 if(ac) {22014 if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }22015 c.rShiftTo(1,c);22016 } else if(!d.isEven()) d.subTo(m,d);22017 d.rShiftTo(1,d);22018 }22019 if(u.compareTo(v) >= 0) {22020 u.subTo(v,u);22021 if(ac) a.subTo(c,a);22022 b.subTo(d,b);22023 } else {22024 v.subTo(u,v);22025 if(ac) c.subTo(a,c);22026 d.subTo(b,d);22027 }22028}22029if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;22030if(d.compareTo(m) >= 0) return d.subtract(m);22031if(d.signum() < 0) d.addTo(m,d); else return d;22032if(d.signum() < 0) return d.add(m); else return d;22033}22034var 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];22035var lplim = (1<<26)/lowprimes[lowprimes.length-1];22036//(public) test primality with certainty >= 1-.5^t22037function bnIsProbablePrime(t) {22038var i, x = this.abs();22039if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {22040 for(i = 0; i < lowprimes.length; ++i)22041 if(x.data[0] == lowprimes[i]) return true;22042 return false;22043}22044if(x.isEven()) return false;22045i = 1;22046while(i < lowprimes.length) {22047 var m = lowprimes[i], j = i+1;22048 while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];22049 m = x.modInt(m);22050 while(i < j) if(m%lowprimes[i++] == 0) return false;22051}22052return x.millerRabin(t);22053}22054//(protected) true if probably prime (HAC 4.24, Miller-Rabin)22055function bnpMillerRabin(t) {22056var n1 = this.subtract(BigInteger.ONE);22057var k = n1.getLowestSetBit();22058if(k <= 0) return false;22059var r = n1.shiftRight(k);22060var prng = bnGetPrng();22061var a;22062for(var i = 0; i < t; ++i) {22063 // select witness 'a' at random from between 1 and n122064 do {22065 a = new BigInteger(this.bitLength(), prng);22066 }22067 while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0);22068 var y = a.modPow(r,this);22069 if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {22070 var j = 1;22071 while(j++ < k && y.compareTo(n1) != 0) {22072 y = y.modPowInt(2,this);22073 if(y.compareTo(BigInteger.ONE) == 0) return false;22074 }22075 if(y.compareTo(n1) != 0) return false;22076 }22077}22078return true;22079}22080// get pseudo random number generator22081function bnGetPrng() {22082 // create prng with api that matches BigInteger secure random22083 return {22084 // x is an array to fill with bytes22085 nextBytes: function(x) {22086 for(var i = 0; i < x.length; ++i) {22087 x[i] = Math.floor(Math.random() * 0x0100);22088 }22089 }22090 };22091}22092//protected22093BigInteger.prototype.chunkSize = bnpChunkSize;22094BigInteger.prototype.toRadix = bnpToRadix;22095BigInteger.prototype.fromRadix = bnpFromRadix;22096BigInteger.prototype.fromNumber = bnpFromNumber;22097BigInteger.prototype.bitwiseTo = bnpBitwiseTo;22098BigInteger.prototype.changeBit = bnpChangeBit;22099BigInteger.prototype.addTo = bnpAddTo;22100BigInteger.prototype.dMultiply = bnpDMultiply;22101BigInteger.prototype.dAddOffset = bnpDAddOffset;22102BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;22103BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;22104BigInteger.prototype.modInt = bnpModInt;22105BigInteger.prototype.millerRabin = bnpMillerRabin;22106//public22107BigInteger.prototype.clone = bnClone;22108BigInteger.prototype.intValue = bnIntValue;22109BigInteger.prototype.byteValue = bnByteValue;22110BigInteger.prototype.shortValue = bnShortValue;22111BigInteger.prototype.signum = bnSigNum;22112BigInteger.prototype.toByteArray = bnToByteArray;22113BigInteger.prototype.equals = bnEquals;22114BigInteger.prototype.min = bnMin;22115BigInteger.prototype.max = bnMax;22116BigInteger.prototype.and = bnAnd;22117BigInteger.prototype.or = bnOr;22118BigInteger.prototype.xor = bnXor;22119BigInteger.prototype.andNot = bnAndNot;22120BigInteger.prototype.not = bnNot;22121BigInteger.prototype.shiftLeft = bnShiftLeft;22122BigInteger.prototype.shiftRight = bnShiftRight;22123BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;22124BigInteger.prototype.bitCount = bnBitCount;22125BigInteger.prototype.testBit = bnTestBit;22126BigInteger.prototype.setBit = bnSetBit;22127BigInteger.prototype.clearBit = bnClearBit;22128BigInteger.prototype.flipBit = bnFlipBit;22129BigInteger.prototype.add = bnAdd;22130BigInteger.prototype.subtract = bnSubtract;22131BigInteger.prototype.multiply = bnMultiply;22132BigInteger.prototype.divide = bnDivide;22133BigInteger.prototype.remainder = bnRemainder;22134BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;22135BigInteger.prototype.modPow = bnModPow;22136BigInteger.prototype.modInverse = bnModInverse;22137BigInteger.prototype.pow = bnPow;22138BigInteger.prototype.gcd = bnGCD;22139BigInteger.prototype.isProbablePrime = bnIsProbablePrime;22140//BigInteger interfaces not implemented in jsbn:22141//BigInteger(int signum, byte[] magnitude)22142//double doubleValue()22143//float floatValue()22144//int hashCode()22145//long longValue()22146//static BigInteger valueOf(long val)22147/***/ }),22148/***/ 5173:22149/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {22150/**22151 * Javascript implementation of RSA-KEM.22152 *22153 * @author Lautaro Cozzani Rodriguez22154 * @author Dave Longley22155 *22156 * Copyright (c) 2014 Lautaro Cozzani <lautaro.cozzani@scytl.com>22157 * Copyright (c) 2014 Digital Bazaar, Inc.22158 */22159var forge = __nccwpck_require__(9177);22160__nccwpck_require__(8339);22161__nccwpck_require__(7821);22162__nccwpck_require__(7052);22163module.exports = forge.kem = forge.kem || {};22164var BigInteger = forge.jsbn.BigInteger;22165/**22166 * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2.22167 */22168forge.kem.rsa = {};22169/**22170 * Creates an RSA KEM API object for generating a secret asymmetric key.22171 *22172 * The symmetric key may be generated via a call to 'encrypt', which will22173 * produce a ciphertext to be transmitted to the recipient and a key to be22174 * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which22175 * will produce the same secret key for the recipient to use to decrypt a22176 * message that was encrypted with the secret key.22177 *22178 * @param kdf the KDF API to use (eg: new forge.kem.kdf1()).22179 * @param options the options to use.22180 * [prng] a custom crypto-secure pseudo-random number generator to use,22181 * that must define "getBytesSync".22182 */22183forge.kem.rsa.create = function(kdf, options) {22184 options = options || {};22185 var prng = options.prng || forge.random;22186 var kem = {};22187 /**22188 * Generates a secret key and its encapsulation.22189 *22190 * @param publicKey the RSA public key to encrypt with.22191 * @param keyLength the length, in bytes, of the secret key to generate.22192 *22193 * @return an object with:22194 * encapsulation: the ciphertext for generating the secret key, as a22195 * binary-encoded string of bytes.22196 * key: the secret key to use for encrypting a message.22197 */22198 kem.encrypt = function(publicKey, keyLength) {22199 // generate a random r where 1 < r < n22200 var byteLength = Math.ceil(publicKey.n.bitLength() / 8);22201 var r;22202 do {22203 r = new BigInteger(22204 forge.util.bytesToHex(prng.getBytesSync(byteLength)),22205 16).mod(publicKey.n);22206 } while(r.compareTo(BigInteger.ONE) <= 0);22207 // prepend r with zeros22208 r = forge.util.hexToBytes(r.toString(16));22209 var zeros = byteLength - r.length;22210 if(zeros > 0) {22211 r = forge.util.fillString(String.fromCharCode(0), zeros) + r;22212 }22213 // encrypt the random22214 var encapsulation = publicKey.encrypt(r, 'NONE');22215 // generate the secret key22216 var key = kdf.generate(r, keyLength);22217 return {encapsulation: encapsulation, key: key};22218 };22219 /**22220 * Decrypts an encapsulated secret key.22221 *22222 * @param privateKey the RSA private key to decrypt with.22223 * @param encapsulation the ciphertext for generating the secret key, as22224 * a binary-encoded string of bytes.22225 * @param keyLength the length, in bytes, of the secret key to generate.22226 *22227 * @return the secret key as a binary-encoded string of bytes.22228 */22229 kem.decrypt = function(privateKey, encapsulation, keyLength) {22230 // decrypt the encapsulation and generate the secret key22231 var r = privateKey.decrypt(encapsulation, 'NONE');22232 return kdf.generate(r, keyLength);22233 };22234 return kem;22235};22236// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API?22237/**22238 * Creates a key derivation API object that implements KDF1 per ISO 18033-2.22239 *22240 * @param md the hash API to use.22241 * @param [digestLength] an optional digest length that must be positive and22242 * less than or equal to md.digestLength.22243 *22244 * @return a KDF1 API object.22245 */22246forge.kem.kdf1 = function(md, digestLength) {22247 _createKDF(this, md, 0, digestLength || md.digestLength);22248};22249/**22250 * Creates a key derivation API object that implements KDF2 per ISO 18033-2.22251 *22252 * @param md the hash API to use.22253 * @param [digestLength] an optional digest length that must be positive and22254 * less than or equal to md.digestLength.22255 *22256 * @return a KDF2 API object.22257 */22258forge.kem.kdf2 = function(md, digestLength) {22259 _createKDF(this, md, 1, digestLength || md.digestLength);22260};22261/**22262 * Creates a KDF1 or KDF2 API object.22263 *22264 * @param md the hash API to use.22265 * @param counterStart the starting index for the counter.22266 * @param digestLength the digest length to use.22267 *22268 * @return the KDF API object.22269 */22270function _createKDF(kdf, md, counterStart, digestLength) {22271 /**22272 * Generate a key of the specified length.22273 *22274 * @param x the binary-encoded byte string to generate a key from.22275 * @param length the number of bytes to generate (the size of the key).22276 *22277 * @return the key as a binary-encoded string.22278 */22279 kdf.generate = function(x, length) {22280 var key = new forge.util.ByteBuffer();22281 // run counter from counterStart to ceil(length / Hash.len)22282 var k = Math.ceil(length / digestLength) + counterStart;22283 var c = new forge.util.ByteBuffer();22284 for(var i = counterStart; i < k; ++i) {22285 // I2OSP(i, 4): convert counter to an octet string of 4 octets22286 c.putInt32(i);22287 // digest 'x' and the counter and add the result to the key22288 md.start();22289 md.update(x + c.getBytes());22290 var hash = md.digest();22291 key.putBytes(hash.getBytes(digestLength));22292 }22293 // truncate to the correct key length22294 key.truncate(key.length() - length);22295 return key.getBytes();22296 };22297}22298/***/ }),22299/***/ 9994:22300/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {22301/**22302 * Cross-browser support for logging in a web application.22303 *22304 * @author David I. Lehn <dlehn@digitalbazaar.com>22305 *22306 * Copyright (c) 2008-2013 Digital Bazaar, Inc.22307 */22308var forge = __nccwpck_require__(9177);22309__nccwpck_require__(8339);22310/* LOG API */22311module.exports = forge.log = forge.log || {};22312/**22313 * Application logging system.22314 *22315 * Each logger level available as it's own function of the form:22316 * forge.log.level(category, args...)22317 * The category is an arbitrary string, and the args are the same as22318 * Firebug's console.log API. By default the call will be output as:22319 * 'LEVEL [category] <args[0]>, args[1], ...'22320 * This enables proper % formatting via the first argument.22321 * Each category is enabled by default but can be enabled or disabled with22322 * the setCategoryEnabled() function.22323 */22324// list of known levels22325forge.log.levels = [22326 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max'];22327// info on the levels indexed by name:22328// index: level index22329// name: uppercased display name22330var sLevelInfo = {};22331// list of loggers22332var sLoggers = [];22333/**22334 * Standard console logger. If no console support is enabled this will22335 * remain null. Check before using.22336 */22337var sConsoleLogger = null;22338// logger flags22339/**22340 * Lock the level at the current value. Used in cases where user config may22341 * set the level such that only critical messages are seen but more verbose22342 * messages are needed for debugging or other purposes.22343 */22344forge.log.LEVEL_LOCKED = (1 << 1);22345/**22346 * Always call log function. By default, the logging system will check the22347 * message level against logger.level before calling the log function. This22348 * flag allows the function to do its own check.22349 */22350forge.log.NO_LEVEL_CHECK = (1 << 2);22351/**22352 * Perform message interpolation with the passed arguments. "%" style22353 * fields in log messages will be replaced by arguments as needed. Some22354 * loggers, such as Firebug, may do this automatically. The original log22355 * message will be available as 'message' and the interpolated version will22356 * be available as 'fullMessage'.22357 */22358forge.log.INTERPOLATE = (1 << 3);22359// setup each log level22360for(var i = 0; i < forge.log.levels.length; ++i) {22361 var level = forge.log.levels[i];22362 sLevelInfo[level] = {22363 index: i,22364 name: level.toUpperCase()22365 };22366}22367/**22368 * Message logger. Will dispatch a message to registered loggers as needed.22369 *22370 * @param message message object22371 */22372forge.log.logMessage = function(message) {22373 var messageLevelIndex = sLevelInfo[message.level].index;22374 for(var i = 0; i < sLoggers.length; ++i) {22375 var logger = sLoggers[i];22376 if(logger.flags & forge.log.NO_LEVEL_CHECK) {22377 logger.f(message);22378 } else {22379 // get logger level22380 var loggerLevelIndex = sLevelInfo[logger.level].index;22381 // check level22382 if(messageLevelIndex <= loggerLevelIndex) {22383 // message critical enough, call logger22384 logger.f(logger, message);22385 }22386 }22387 }22388};22389/**22390 * Sets the 'standard' key on a message object to:22391 * "LEVEL [category] " + message22392 *22393 * @param message a message log object22394 */22395forge.log.prepareStandard = function(message) {22396 if(!('standard' in message)) {22397 message.standard =22398 sLevelInfo[message.level].name +22399 //' ' + +message.timestamp +22400 ' [' + message.category + '] ' +22401 message.message;22402 }22403};22404/**22405 * Sets the 'full' key on a message object to the original message22406 * interpolated via % formatting with the message arguments.22407 *22408 * @param message a message log object.22409 */22410forge.log.prepareFull = function(message) {22411 if(!('full' in message)) {22412 // copy args and insert message at the front22413 var args = [message.message];22414 args = args.concat([] || 0);22415 // format the message22416 message.full = forge.util.format.apply(this, args);22417 }22418};22419/**22420 * Applies both preparseStandard() and prepareFull() to a message object and22421 * store result in 'standardFull'.22422 *22423 * @param message a message log object.22424 */22425forge.log.prepareStandardFull = function(message) {22426 if(!('standardFull' in message)) {22427 // FIXME implement 'standardFull' logging22428 forge.log.prepareStandard(message);22429 message.standardFull = message.standard;22430 }22431};22432// create log level functions22433if(true) {22434 // levels for which we want functions22435 var levels = ['error', 'warning', 'info', 'debug', 'verbose'];22436 for(var i = 0; i < levels.length; ++i) {22437 // wrap in a function to ensure proper level var is passed22438 (function(level) {22439 // create function for this level22440 forge.log[level] = function(category, message/*, args...*/) {22441 // convert arguments to real array, remove category and message22442 var args = Array.prototype.slice.call(arguments).slice(2);22443 // create message object22444 // Note: interpolation and standard formatting is done lazily22445 var msg = {22446 timestamp: new Date(),22447 level: level,22448 category: category,22449 message: message,22450 'arguments': args22451 /*standard*/22452 /*full*/22453 /*fullMessage*/22454 };22455 // process this message22456 forge.log.logMessage(msg);22457 };22458 })(levels[i]);22459 }22460}22461/**22462 * Creates a new logger with specified custom logging function.22463 *22464 * The logging function has a signature of:22465 * function(logger, message)22466 * logger: current logger22467 * message: object:22468 * level: level id22469 * category: category22470 * message: string message22471 * arguments: Array of extra arguments22472 * fullMessage: interpolated message and arguments if INTERPOLATE flag set22473 *22474 * @param logFunction a logging function which takes a log message object22475 * as a parameter.22476 *22477 * @return a logger object.22478 */22479forge.log.makeLogger = function(logFunction) {22480 var logger = {22481 flags: 0,22482 f: logFunction22483 };22484 forge.log.setLevel(logger, 'none');22485 return logger;22486};22487/**22488 * Sets the current log level on a logger.22489 *22490 * @param logger the target logger.22491 * @param level the new maximum log level as a string.22492 *22493 * @return true if set, false if not.22494 */22495forge.log.setLevel = function(logger, level) {22496 var rval = false;22497 if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) {22498 for(var i = 0; i < forge.log.levels.length; ++i) {22499 var aValidLevel = forge.log.levels[i];22500 if(level == aValidLevel) {22501 // set level22502 logger.level = level;22503 rval = true;22504 break;22505 }22506 }22507 }22508 return rval;22509};22510/**22511 * Locks the log level at its current value.22512 *22513 * @param logger the target logger.22514 * @param lock boolean lock value, default to true.22515 */22516forge.log.lock = function(logger, lock) {22517 if(typeof lock === 'undefined' || lock) {22518 logger.flags |= forge.log.LEVEL_LOCKED;22519 } else {22520 logger.flags &= ~forge.log.LEVEL_LOCKED;22521 }22522};22523/**22524 * Adds a logger.22525 *22526 * @param logger the logger object.22527 */22528forge.log.addLogger = function(logger) {22529 sLoggers.push(logger);22530};22531// setup the console logger if possible, else create fake console.log22532if(typeof(console) !== 'undefined' && 'log' in console) {22533 var logger;22534 if(console.error && console.warn && console.info && console.debug) {22535 // looks like Firebug-style logging is available22536 // level handlers map22537 var levelHandlers = {22538 error: console.error,22539 warning: console.warn,22540 info: console.info,22541 debug: console.debug,22542 verbose: console.debug22543 };22544 var f = function(logger, message) {22545 forge.log.prepareStandard(message);22546 var handler = levelHandlers[message.level];22547 // prepend standard message and concat args22548 var args = [message.standard];22549 args = args.concat(message['arguments'].slice());22550 // apply to low-level console function22551 handler.apply(console, args);22552 };22553 logger = forge.log.makeLogger(f);22554 } else {22555 // only appear to have basic console.log22556 var f = function(logger, message) {22557 forge.log.prepareStandardFull(message);22558 console.log(message.standardFull);22559 };22560 logger = forge.log.makeLogger(f);22561 }22562 forge.log.setLevel(logger, 'debug');22563 forge.log.addLogger(logger);22564 sConsoleLogger = logger;22565} else {22566 // define fake console.log to avoid potential script errors on22567 // browsers that do not have console logging22568 console = {22569 log: function() {}22570 };22571}22572/*22573 * Check for logging control query vars in current URL.22574 *22575 * console.level=<level-name>22576 * Set's the console log level by name. Useful to override defaults and22577 * allow more verbose logging before a user config is loaded.22578 *22579 * console.lock=<true|false>22580 * Lock the console log level at whatever level it is set at. This is run22581 * after console.level is processed. Useful to force a level of verbosity22582 * that could otherwise be limited by a user config.22583 */22584if(sConsoleLogger !== null &&22585 typeof window !== 'undefined' && window.location22586) {22587 var query = new URL(window.location.href).searchParams;22588 if(query.has('console.level')) {22589 // set with last value22590 forge.log.setLevel(22591 sConsoleLogger, query.get('console.level').slice(-1)[0]);22592 }22593 if(query.has('console.lock')) {22594 // set with last value22595 var lock = query.get('console.lock').slice(-1)[0];22596 if(lock == 'true') {22597 forge.log.lock(sConsoleLogger);22598 }22599 }22600}22601// provide public access to console logger22602forge.log.consoleLogger = sConsoleLogger;22603/***/ }),22604/***/ 1145:22605/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {22606/**22607 * Node.js module for all known Forge message digests.22608 *22609 * @author Dave Longley22610 *22611 * Copyright 2011-2017 Digital Bazaar, Inc.22612 */22613module.exports = __nccwpck_require__(6231);22614__nccwpck_require__(6594);22615__nccwpck_require__(279);22616__nccwpck_require__(4086);22617__nccwpck_require__(9542);22618/***/ }),22619/***/ 6231:22620/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {22621/**22622 * Node.js module for Forge message digests.22623 *22624 * @author Dave Longley22625 *22626 * Copyright 2011-2017 Digital Bazaar, Inc.22627 */22628var forge = __nccwpck_require__(9177);22629module.exports = forge.md = forge.md || {};22630forge.md.algorithms = forge.md.algorithms || {};22631/***/ }),22632/***/ 6594:22633/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {22634/**22635 * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation.22636 *22637 * @author Dave Longley22638 *22639 * Copyright (c) 2010-2014 Digital Bazaar, Inc.22640 */22641var forge = __nccwpck_require__(9177);22642__nccwpck_require__(6231);22643__nccwpck_require__(8339);22644var md5 = module.exports = forge.md5 = forge.md5 || {};22645forge.md.md5 = forge.md.algorithms.md5 = md5;22646/**22647 * Creates an MD5 message digest object.22648 *22649 * @return a message digest object.22650 */22651md5.create = function() {22652 // do initialization as necessary22653 if(!_initialized) {22654 _init();22655 }22656 // MD5 state contains four 32-bit integers22657 var _state = null;22658 // input buffer22659 var _input = forge.util.createBuffer();22660 // used for word storage22661 var _w = new Array(16);22662 // message digest object22663 var md = {22664 algorithm: 'md5',22665 blockLength: 64,22666 digestLength: 16,22667 // 56-bit length of message so far (does not including padding)22668 messageLength: 0,22669 // true message length22670 fullMessageLength: null,22671 // size of message length in bytes22672 messageLengthSize: 822673 };22674 /**22675 * Starts the digest.22676 *22677 * @return this digest object.22678 */22679 md.start = function() {22680 // up to 56-bit message length for convenience22681 md.messageLength = 0;22682 // full message length (set md.messageLength64 for backwards-compatibility)22683 md.fullMessageLength = md.messageLength64 = [];22684 var int32s = md.messageLengthSize / 4;22685 for(var i = 0; i < int32s; ++i) {22686 md.fullMessageLength.push(0);22687 }22688 _input = forge.util.createBuffer();22689 _state = {22690 h0: 0x67452301,22691 h1: 0xEFCDAB89,22692 h2: 0x98BADCFE,22693 h3: 0x1032547622694 };22695 return md;22696 };22697 // start digest automatically for first time22698 md.start();22699 /**22700 * Updates the digest with the given message input. The given input can22701 * treated as raw input (no encoding will be applied) or an encoding of22702 * 'utf8' maybe given to encode the input using UTF-8.22703 *22704 * @param msg the message input to update with.22705 * @param encoding the encoding to use (default: 'raw', other: 'utf8').22706 *22707 * @return this digest object.22708 */22709 md.update = function(msg, encoding) {22710 if(encoding === 'utf8') {22711 msg = forge.util.encodeUtf8(msg);22712 }22713 // update message length22714 var len = msg.length;22715 md.messageLength += len;22716 len = [(len / 0x100000000) >>> 0, len >>> 0];22717 for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {22718 md.fullMessageLength[i] += len[1];22719 len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);22720 md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;22721 len[0] = (len[1] / 0x100000000) >>> 0;22722 }22723 // add bytes to input buffer22724 _input.putBytes(msg);22725 // process bytes22726 _update(_state, _w, _input);22727 // compact input buffer every 2K or if empty22728 if(_input.read > 2048 || _input.length() === 0) {22729 _input.compact();22730 }22731 return md;22732 };22733 /**22734 * Produces the digest.22735 *22736 * @return a byte buffer containing the digest value.22737 */22738 md.digest = function() {22739 /* Note: Here we copy the remaining bytes in the input buffer and22740 add the appropriate MD5 padding. Then we do the final update22741 on a copy of the state so that if the user wants to get22742 intermediate digests they can do so. */22743 /* Determine the number of bytes that must be added to the message22744 to ensure its length is congruent to 448 mod 512. In other words,22745 the data to be digested must be a multiple of 512 bits (or 128 bytes).22746 This data includes the message, some padding, and the length of the22747 message. Since the length of the message will be encoded as 8 bytes (6422748 bits), that means that the last segment of the data must have 56 bytes22749 (448 bits) of message and padding. Therefore, the length of the message22750 plus the padding must be congruent to 448 mod 512 because22751 512 - 128 = 448.22752 In order to fill up the message length it must be filled with22753 padding that begins with 1 bit followed by all 0 bits. Padding22754 must *always* be present, so if the message length is already22755 congruent to 448 mod 512, then 512 padding bits must be added. */22756 var finalBlock = forge.util.createBuffer();22757 finalBlock.putBytes(_input.bytes());22758 // compute remaining size to be digested (include message length size)22759 var remaining = (22760 md.fullMessageLength[md.fullMessageLength.length - 1] +22761 md.messageLengthSize);22762 // add padding for overflow blockSize - overflow22763 // _padding starts with 1 byte with first bit is set (byte value 128), then22764 // there may be up to (blockSize - 1) other pad bytes22765 var overflow = remaining & (md.blockLength - 1);22766 finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));22767 // serialize message length in bits in little-endian order; since length22768 // is stored in bytes we multiply by 8 and add carry22769 var bits, carry = 0;22770 for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {22771 bits = md.fullMessageLength[i] * 8 + carry;22772 carry = (bits / 0x100000000) >>> 0;22773 finalBlock.putInt32Le(bits >>> 0);22774 }22775 var s2 = {22776 h0: _state.h0,22777 h1: _state.h1,22778 h2: _state.h2,22779 h3: _state.h322780 };22781 _update(s2, _w, finalBlock);22782 var rval = forge.util.createBuffer();22783 rval.putInt32Le(s2.h0);22784 rval.putInt32Le(s2.h1);22785 rval.putInt32Le(s2.h2);22786 rval.putInt32Le(s2.h3);22787 return rval;22788 };22789 return md;22790};22791// padding, constant tables for calculating md522792var _padding = null;22793var _g = null;22794var _r = null;22795var _k = null;22796var _initialized = false;22797/**22798 * Initializes the constant tables.22799 */22800function _init() {22801 // create padding22802 _padding = String.fromCharCode(128);22803 _padding += forge.util.fillString(String.fromCharCode(0x00), 64);22804 // g values22805 _g = [22806 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,22807 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12,22808 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2,22809 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9];22810 // rounds table22811 _r = [22812 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,22813 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,22814 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,22815 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];22816 // get the result of abs(sin(i + 1)) as a 32-bit integer22817 _k = new Array(64);22818 for(var i = 0; i < 64; ++i) {22819 _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000);22820 }22821 // now initialized22822 _initialized = true;22823}22824/**22825 * Updates an MD5 state with the given byte buffer.22826 *22827 * @param s the MD5 state to update.22828 * @param w the array to use to store words.22829 * @param bytes the byte buffer to update with.22830 */22831function _update(s, w, bytes) {22832 // consume 512 bit (64 byte) chunks22833 var t, a, b, c, d, f, r, i;22834 var len = bytes.length();22835 while(len >= 64) {22836 // initialize hash value for this chunk22837 a = s.h0;22838 b = s.h1;22839 c = s.h2;22840 d = s.h3;22841 // round 122842 for(i = 0; i < 16; ++i) {22843 w[i] = bytes.getInt32Le();22844 f = d ^ (b & (c ^ d));22845 t = (a + f + _k[i] + w[i]);22846 r = _r[i];22847 a = d;22848 d = c;22849 c = b;22850 b += (t << r) | (t >>> (32 - r));22851 }22852 // round 222853 for(; i < 32; ++i) {22854 f = c ^ (d & (b ^ c));22855 t = (a + f + _k[i] + w[_g[i]]);22856 r = _r[i];22857 a = d;22858 d = c;22859 c = b;22860 b += (t << r) | (t >>> (32 - r));22861 }22862 // round 322863 for(; i < 48; ++i) {22864 f = b ^ c ^ d;22865 t = (a + f + _k[i] + w[_g[i]]);22866 r = _r[i];22867 a = d;22868 d = c;22869 c = b;22870 b += (t << r) | (t >>> (32 - r));22871 }22872 // round 422873 for(; i < 64; ++i) {22874 f = c ^ (b | ~d);22875 t = (a + f + _k[i] + w[_g[i]]);22876 r = _r[i];22877 a = d;22878 d = c;22879 c = b;22880 b += (t << r) | (t >>> (32 - r));22881 }22882 // update hash state22883 s.h0 = (s.h0 + a) | 0;22884 s.h1 = (s.h1 + b) | 0;22885 s.h2 = (s.h2 + c) | 0;22886 s.h3 = (s.h3 + d) | 0;22887 len -= 64;22888 }22889}22890/***/ }),22891/***/ 7973:22892/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {22893/**22894 * Node.js module for Forge mask generation functions.22895 *22896 * @author Stefan Siegl22897 *22898 * Copyright 2012 Stefan Siegl <stesie@brokenpipe.de>22899 */22900var forge = __nccwpck_require__(9177);22901__nccwpck_require__(3339);22902module.exports = forge.mgf = forge.mgf || {};22903forge.mgf.mgf1 = forge.mgf1;22904/***/ }),22905/***/ 3339:22906/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {22907/**22908 * Javascript implementation of mask generation function MGF1.22909 *22910 * @author Stefan Siegl22911 * @author Dave Longley22912 *22913 * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>22914 * Copyright (c) 2014 Digital Bazaar, Inc.22915 */22916var forge = __nccwpck_require__(9177);22917__nccwpck_require__(8339);22918forge.mgf = forge.mgf || {};22919var mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};22920/**22921 * Creates a MGF1 mask generation function object.22922 *22923 * @param md the message digest API to use (eg: forge.md.sha1.create()).22924 *22925 * @return a mask generation function object.22926 */22927mgf1.create = function(md) {22928 var mgf = {22929 /**22930 * Generate mask of specified length.22931 *22932 * @param {String} seed The seed for mask generation.22933 * @param maskLen Number of bytes to generate.22934 * @return {String} The generated mask.22935 */22936 generate: function(seed, maskLen) {22937 /* 2. Let T be the empty octet string. */22938 var t = new forge.util.ByteBuffer();22939 /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */22940 var len = Math.ceil(maskLen / md.digestLength);22941 for(var i = 0; i < len; i++) {22942 /* a. Convert counter to an octet string C of length 4 octets */22943 var c = new forge.util.ByteBuffer();22944 c.putInt32(i);22945 /* b. Concatenate the hash of the seed mgfSeed and C to the octet22946 * string T: */22947 md.start();22948 md.update(seed + c.getBytes());22949 t.putBuffer(md.digest());22950 }22951 /* Output the leading maskLen octets of T as the octet string mask. */22952 t.truncate(t.length() - maskLen);22953 return t.getBytes();22954 }22955 };22956 return mgf;22957};22958/***/ }),22959/***/ 1925:22960/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {22961/**22962 * Object IDs for ASN.1.22963 *22964 * @author Dave Longley22965 *22966 * Copyright (c) 2010-2013 Digital Bazaar, Inc.22967 */22968var forge = __nccwpck_require__(9177);22969forge.pki = forge.pki || {};22970var oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {};22971// set id to name mapping and name to id mapping22972function _IN(id, name) {22973 oids[id] = name;22974 oids[name] = id;22975}22976// set id to name mapping only22977function _I_(id, name) {22978 oids[id] = name;22979}22980// algorithm OIDs22981_IN('1.2.840.113549.1.1.1', 'rsaEncryption');22982// Note: md2 & md4 not implemented22983//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');22984//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');22985_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');22986_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');22987_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');22988_IN('1.2.840.113549.1.1.8', 'mgf1');22989_IN('1.2.840.113549.1.1.9', 'pSpecified');22990_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');22991_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');22992_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');22993_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');22994// Edwards-curve Digital Signature Algorithm (EdDSA) Ed2551922995_IN('1.3.101.112', 'EdDSA25519');22996_IN('1.2.840.10040.4.3', 'dsa-with-sha1');22997_IN('1.3.14.3.2.7', 'desCBC');22998_IN('1.3.14.3.2.26', 'sha1');22999// Deprecated equivalent of sha1WithRSAEncryption23000_IN('1.3.14.3.2.29', 'sha1WithRSASignature');23001_IN('2.16.840.1.101.3.4.2.1', 'sha256');23002_IN('2.16.840.1.101.3.4.2.2', 'sha384');23003_IN('2.16.840.1.101.3.4.2.3', 'sha512');23004_IN('2.16.840.1.101.3.4.2.4', 'sha224');23005_IN('2.16.840.1.101.3.4.2.5', 'sha512-224');23006_IN('2.16.840.1.101.3.4.2.6', 'sha512-256');23007_IN('1.2.840.113549.2.2', 'md2');23008_IN('1.2.840.113549.2.5', 'md5');23009// pkcs#7 content types23010_IN('1.2.840.113549.1.7.1', 'data');23011_IN('1.2.840.113549.1.7.2', 'signedData');23012_IN('1.2.840.113549.1.7.3', 'envelopedData');23013_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');23014_IN('1.2.840.113549.1.7.5', 'digestedData');23015_IN('1.2.840.113549.1.7.6', 'encryptedData');23016// pkcs#9 oids23017_IN('1.2.840.113549.1.9.1', 'emailAddress');23018_IN('1.2.840.113549.1.9.2', 'unstructuredName');23019_IN('1.2.840.113549.1.9.3', 'contentType');23020_IN('1.2.840.113549.1.9.4', 'messageDigest');23021_IN('1.2.840.113549.1.9.5', 'signingTime');23022_IN('1.2.840.113549.1.9.6', 'counterSignature');23023_IN('1.2.840.113549.1.9.7', 'challengePassword');23024_IN('1.2.840.113549.1.9.8', 'unstructuredAddress');23025_IN('1.2.840.113549.1.9.14', 'extensionRequest');23026_IN('1.2.840.113549.1.9.20', 'friendlyName');23027_IN('1.2.840.113549.1.9.21', 'localKeyId');23028_IN('1.2.840.113549.1.9.22.1', 'x509Certificate');23029// pkcs#12 safe bags23030_IN('1.2.840.113549.1.12.10.1.1', 'keyBag');23031_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');23032_IN('1.2.840.113549.1.12.10.1.3', 'certBag');23033_IN('1.2.840.113549.1.12.10.1.4', 'crlBag');23034_IN('1.2.840.113549.1.12.10.1.5', 'secretBag');23035_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');23036// password-based-encryption for pkcs#1223037_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');23038_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');23039_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');23040_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');23041_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');23042_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');23043_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');23044_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');23045// hmac OIDs23046_IN('1.2.840.113549.2.7', 'hmacWithSHA1');23047_IN('1.2.840.113549.2.8', 'hmacWithSHA224');23048_IN('1.2.840.113549.2.9', 'hmacWithSHA256');23049_IN('1.2.840.113549.2.10', 'hmacWithSHA384');23050_IN('1.2.840.113549.2.11', 'hmacWithSHA512');23051// symmetric key algorithm oids23052_IN('1.2.840.113549.3.7', 'des-EDE3-CBC');23053_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');23054_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');23055_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');23056// certificate issuer/subject OIDs23057_IN('2.5.4.3', 'commonName');23058_IN('2.5.4.4', 'surname');23059_IN('2.5.4.5', 'serialNumber');23060_IN('2.5.4.6', 'countryName');23061_IN('2.5.4.7', 'localityName');23062_IN('2.5.4.8', 'stateOrProvinceName');23063_IN('2.5.4.9', 'streetAddress');23064_IN('2.5.4.10', 'organizationName');23065_IN('2.5.4.11', 'organizationalUnitName');23066_IN('2.5.4.12', 'title');23067_IN('2.5.4.13', 'description');23068_IN('2.5.4.15', 'businessCategory');23069_IN('2.5.4.17', 'postalCode');23070_IN('2.5.4.42', 'givenName');23071_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');23072_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');23073// X.509 extension OIDs23074_IN('2.16.840.1.113730.1.1', 'nsCertType');23075_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used23076_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .3523077_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .1523078_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .3223079_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .1523080_I_('2.5.29.5', 'policyMapping'); // deprecated use .3323081_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .3023082_I_('2.5.29.7', 'subjectAltName'); // deprecated use .1723083_I_('2.5.29.8', 'issuerAltName'); // deprecated use .1823084_I_('2.5.29.9', 'subjectDirectoryAttributes');23085_I_('2.5.29.10', 'basicConstraints'); // deprecated use .1923086_I_('2.5.29.11', 'nameConstraints'); // deprecated use .3023087_I_('2.5.29.12', 'policyConstraints'); // deprecated use .3623088_I_('2.5.29.13', 'basicConstraints'); // deprecated use .1923089_IN('2.5.29.14', 'subjectKeyIdentifier');23090_IN('2.5.29.15', 'keyUsage');23091_I_('2.5.29.16', 'privateKeyUsagePeriod');23092_IN('2.5.29.17', 'subjectAltName');23093_IN('2.5.29.18', 'issuerAltName');23094_IN('2.5.29.19', 'basicConstraints');23095_I_('2.5.29.20', 'cRLNumber');23096_I_('2.5.29.21', 'cRLReason');23097_I_('2.5.29.22', 'expirationDate');23098_I_('2.5.29.23', 'instructionCode');23099_I_('2.5.29.24', 'invalidityDate');23100_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .3123101_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .2823102_I_('2.5.29.27', 'deltaCRLIndicator');23103_I_('2.5.29.28', 'issuingDistributionPoint');23104_I_('2.5.29.29', 'certificateIssuer');23105_I_('2.5.29.30', 'nameConstraints');23106_IN('2.5.29.31', 'cRLDistributionPoints');23107_IN('2.5.29.32', 'certificatePolicies');23108_I_('2.5.29.33', 'policyMappings');23109_I_('2.5.29.34', 'policyConstraints'); // deprecated use .3623110_IN('2.5.29.35', 'authorityKeyIdentifier');23111_I_('2.5.29.36', 'policyConstraints');23112_IN('2.5.29.37', 'extKeyUsage');23113_I_('2.5.29.46', 'freshestCRL');23114_I_('2.5.29.54', 'inhibitAnyPolicy');23115// extKeyUsage purposes23116_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');23117_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');23118_IN('1.3.6.1.5.5.7.3.1', 'serverAuth');23119_IN('1.3.6.1.5.5.7.3.2', 'clientAuth');23120_IN('1.3.6.1.5.5.7.3.3', 'codeSigning');23121_IN('1.3.6.1.5.5.7.3.4', 'emailProtection');23122_IN('1.3.6.1.5.5.7.3.8', 'timeStamping');23123/***/ }),23124/***/ 1281:23125/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {23126/**23127 * Password-based encryption functions.23128 *23129 * @author Dave Longley23130 * @author Stefan Siegl <stesie@brokenpipe.de>23131 *23132 * Copyright (c) 2010-2013 Digital Bazaar, Inc.23133 * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>23134 *23135 * An EncryptedPrivateKeyInfo:23136 *23137 * EncryptedPrivateKeyInfo ::= SEQUENCE {23138 * encryptionAlgorithm EncryptionAlgorithmIdentifier,23139 * encryptedData EncryptedData }23140 *23141 * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier23142 *23143 * EncryptedData ::= OCTET STRING23144 */23145var forge = __nccwpck_require__(9177);23146__nccwpck_require__(7994);23147__nccwpck_require__(9549);23148__nccwpck_require__(7157);23149__nccwpck_require__(6231);23150__nccwpck_require__(1925);23151__nccwpck_require__(1611);23152__nccwpck_require__(154);23153__nccwpck_require__(7821);23154__nccwpck_require__(9965);23155__nccwpck_require__(3921);23156__nccwpck_require__(8339);23157if(typeof BigInteger === 'undefined') {23158 var BigInteger = forge.jsbn.BigInteger;23159}23160// shortcut for asn.1 API23161var asn1 = forge.asn1;23162/* Password-based encryption implementation. */23163var pki = forge.pki = forge.pki || {};23164module.exports = pki.pbe = forge.pbe = forge.pbe || {};23165var oids = pki.oids;23166// validator for an EncryptedPrivateKeyInfo structure23167// Note: Currently only works w/algorithm params23168var encryptedPrivateKeyValidator = {23169 name: 'EncryptedPrivateKeyInfo',23170 tagClass: asn1.Class.UNIVERSAL,23171 type: asn1.Type.SEQUENCE,23172 constructed: true,23173 value: [{23174 name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',23175 tagClass: asn1.Class.UNIVERSAL,23176 type: asn1.Type.SEQUENCE,23177 constructed: true,23178 value: [{23179 name: 'AlgorithmIdentifier.algorithm',23180 tagClass: asn1.Class.UNIVERSAL,23181 type: asn1.Type.OID,23182 constructed: false,23183 capture: 'encryptionOid'23184 }, {23185 name: 'AlgorithmIdentifier.parameters',23186 tagClass: asn1.Class.UNIVERSAL,23187 type: asn1.Type.SEQUENCE,23188 constructed: true,23189 captureAsn1: 'encryptionParams'23190 }]23191 }, {23192 // encryptedData23193 name: 'EncryptedPrivateKeyInfo.encryptedData',23194 tagClass: asn1.Class.UNIVERSAL,23195 type: asn1.Type.OCTETSTRING,23196 constructed: false,23197 capture: 'encryptedData'23198 }]23199};23200// validator for a PBES2Algorithms structure23201// Note: Currently only works w/PBKDF2 + AES encryption schemes23202var PBES2AlgorithmsValidator = {23203 name: 'PBES2Algorithms',23204 tagClass: asn1.Class.UNIVERSAL,23205 type: asn1.Type.SEQUENCE,23206 constructed: true,23207 value: [{23208 name: 'PBES2Algorithms.keyDerivationFunc',23209 tagClass: asn1.Class.UNIVERSAL,23210 type: asn1.Type.SEQUENCE,23211 constructed: true,23212 value: [{23213 name: 'PBES2Algorithms.keyDerivationFunc.oid',23214 tagClass: asn1.Class.UNIVERSAL,23215 type: asn1.Type.OID,23216 constructed: false,23217 capture: 'kdfOid'23218 }, {23219 name: 'PBES2Algorithms.params',23220 tagClass: asn1.Class.UNIVERSAL,23221 type: asn1.Type.SEQUENCE,23222 constructed: true,23223 value: [{23224 name: 'PBES2Algorithms.params.salt',23225 tagClass: asn1.Class.UNIVERSAL,23226 type: asn1.Type.OCTETSTRING,23227 constructed: false,23228 capture: 'kdfSalt'23229 }, {23230 name: 'PBES2Algorithms.params.iterationCount',23231 tagClass: asn1.Class.UNIVERSAL,23232 type: asn1.Type.INTEGER,23233 constructed: false,23234 capture: 'kdfIterationCount'23235 }, {23236 name: 'PBES2Algorithms.params.keyLength',23237 tagClass: asn1.Class.UNIVERSAL,23238 type: asn1.Type.INTEGER,23239 constructed: false,23240 optional: true,23241 capture: 'keyLength'23242 }, {23243 // prf23244 name: 'PBES2Algorithms.params.prf',23245 tagClass: asn1.Class.UNIVERSAL,23246 type: asn1.Type.SEQUENCE,23247 constructed: true,23248 optional: true,23249 value: [{23250 name: 'PBES2Algorithms.params.prf.algorithm',23251 tagClass: asn1.Class.UNIVERSAL,23252 type: asn1.Type.OID,23253 constructed: false,23254 capture: 'prfOid'23255 }]23256 }]23257 }]23258 }, {23259 name: 'PBES2Algorithms.encryptionScheme',23260 tagClass: asn1.Class.UNIVERSAL,23261 type: asn1.Type.SEQUENCE,23262 constructed: true,23263 value: [{23264 name: 'PBES2Algorithms.encryptionScheme.oid',23265 tagClass: asn1.Class.UNIVERSAL,23266 type: asn1.Type.OID,23267 constructed: false,23268 capture: 'encOid'23269 }, {23270 name: 'PBES2Algorithms.encryptionScheme.iv',23271 tagClass: asn1.Class.UNIVERSAL,23272 type: asn1.Type.OCTETSTRING,23273 constructed: false,23274 capture: 'encIv'23275 }]23276 }]23277};23278var pkcs12PbeParamsValidator = {23279 name: 'pkcs-12PbeParams',23280 tagClass: asn1.Class.UNIVERSAL,23281 type: asn1.Type.SEQUENCE,23282 constructed: true,23283 value: [{23284 name: 'pkcs-12PbeParams.salt',23285 tagClass: asn1.Class.UNIVERSAL,23286 type: asn1.Type.OCTETSTRING,23287 constructed: false,23288 capture: 'salt'23289 }, {23290 name: 'pkcs-12PbeParams.iterations',23291 tagClass: asn1.Class.UNIVERSAL,23292 type: asn1.Type.INTEGER,23293 constructed: false,23294 capture: 'iterations'23295 }]23296};23297/**23298 * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.23299 *23300 * PBES2Algorithms ALGORITHM-IDENTIFIER ::=23301 * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}23302 *23303 * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}23304 *23305 * PBES2-params ::= SEQUENCE {23306 * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},23307 * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}23308 * }23309 *23310 * PBES2-KDFs ALGORITHM-IDENTIFIER ::=23311 * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }23312 *23313 * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }23314 *23315 * PBKDF2-params ::= SEQUENCE {23316 * salt CHOICE {23317 * specified OCTET STRING,23318 * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}23319 * },23320 * iterationCount INTEGER (1..MAX),23321 * keyLength INTEGER (1..MAX) OPTIONAL,23322 * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA123323 * }23324 *23325 * @param obj the ASN.1 PrivateKeyInfo object.23326 * @param password the password to encrypt with.23327 * @param options:23328 * algorithm the encryption algorithm to use23329 * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.23330 * count the iteration count to use.23331 * saltSize the salt size to use.23332 * prfAlgorithm the PRF message digest algorithm to use23333 * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')23334 *23335 * @return the ASN.1 EncryptedPrivateKeyInfo.23336 */23337pki.encryptPrivateKeyInfo = function(obj, password, options) {23338 // set default options23339 options = options || {};23340 options.saltSize = options.saltSize || 8;23341 options.count = options.count || 2048;23342 options.algorithm = options.algorithm || 'aes128';23343 options.prfAlgorithm = options.prfAlgorithm || 'sha1';23344 // generate PBE params23345 var salt = forge.random.getBytesSync(options.saltSize);23346 var count = options.count;23347 var countBytes = asn1.integerToDer(count);23348 var dkLen;23349 var encryptionAlgorithm;23350 var encryptedData;23351 if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {23352 // do PBES223353 var ivLen, encOid, cipherFn;23354 switch(options.algorithm) {23355 case 'aes128':23356 dkLen = 16;23357 ivLen = 16;23358 encOid = oids['aes128-CBC'];23359 cipherFn = forge.aes.createEncryptionCipher;23360 break;23361 case 'aes192':23362 dkLen = 24;23363 ivLen = 16;23364 encOid = oids['aes192-CBC'];23365 cipherFn = forge.aes.createEncryptionCipher;23366 break;23367 case 'aes256':23368 dkLen = 32;23369 ivLen = 16;23370 encOid = oids['aes256-CBC'];23371 cipherFn = forge.aes.createEncryptionCipher;23372 break;23373 case 'des':23374 dkLen = 8;23375 ivLen = 8;23376 encOid = oids['desCBC'];23377 cipherFn = forge.des.createEncryptionCipher;23378 break;23379 default:23380 var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');23381 error.algorithm = options.algorithm;23382 throw error;23383 }23384 // get PRF message digest23385 var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();23386 var md = prfAlgorithmToMessageDigest(prfAlgorithm);23387 // encrypt private key using pbe SHA-1 and AES/DES23388 var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);23389 var iv = forge.random.getBytesSync(ivLen);23390 var cipher = cipherFn(dk);23391 cipher.start(iv);23392 cipher.update(asn1.toDer(obj));23393 cipher.finish();23394 encryptedData = cipher.output.getBytes();23395 // get PBKDF2-params23396 var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);23397 encryptionAlgorithm = asn1.create(23398 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [23399 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,23400 asn1.oidToDer(oids['pkcs5PBES2']).getBytes()),23401 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [23402 // keyDerivationFunc23403 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [23404 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,23405 asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()),23406 // PBKDF2-params23407 params23408 ]),23409 // encryptionScheme23410 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [23411 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,23412 asn1.oidToDer(encOid).getBytes()),23413 // iv23414 asn1.create(23415 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv)23416 ])23417 ])23418 ]);23419 } else if(options.algorithm === '3des') {23420 // Do PKCS12 PBE23421 dkLen = 24;23422 var saltBytes = new forge.util.ByteBuffer(salt);23423 var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);23424 var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);23425 var cipher = forge.des.createEncryptionCipher(dk);23426 cipher.start(iv);23427 cipher.update(asn1.toDer(obj));23428 cipher.finish();23429 encryptedData = cipher.output.getBytes();23430 encryptionAlgorithm = asn1.create(23431 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [23432 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,23433 asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),23434 // pkcs-12PbeParams23435 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [23436 // salt23437 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),23438 // iteration count23439 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,23440 countBytes.getBytes())23441 ])23442 ]);23443 } else {23444 var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');23445 error.algorithm = options.algorithm;23446 throw error;23447 }23448 // EncryptedPrivateKeyInfo23449 var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [23450 // encryptionAlgorithm23451 encryptionAlgorithm,23452 // encryptedData23453 asn1.create(23454 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData)23455 ]);23456 return rval;23457};23458/**23459 * Decrypts a ASN.1 PrivateKeyInfo object.23460 *23461 * @param obj the ASN.1 EncryptedPrivateKeyInfo object.23462 * @param password the password to decrypt with.23463 *23464 * @return the ASN.1 PrivateKeyInfo on success, null on failure.23465 */23466pki.decryptPrivateKeyInfo = function(obj, password) {23467 var rval = null;23468 // get PBE params23469 var capture = {};23470 var errors = [];23471 if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {23472 var error = new Error('Cannot read encrypted private key. ' +23473 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');23474 error.errors = errors;23475 throw error;23476 }23477 // get cipher23478 var oid = asn1.derToOid(capture.encryptionOid);23479 var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);23480 // get encrypted data23481 var encrypted = forge.util.createBuffer(capture.encryptedData);23482 cipher.update(encrypted);23483 if(cipher.finish()) {23484 rval = asn1.fromDer(cipher.output);23485 }23486 return rval;23487};23488/**23489 * Converts a EncryptedPrivateKeyInfo to PEM format.23490 *23491 * @param epki the EncryptedPrivateKeyInfo.23492 * @param maxline the maximum characters per line, defaults to 64.23493 *23494 * @return the PEM-formatted encrypted private key.23495 */23496pki.encryptedPrivateKeyToPem = function(epki, maxline) {23497 // convert to DER, then PEM-encode23498 var msg = {23499 type: 'ENCRYPTED PRIVATE KEY',23500 body: asn1.toDer(epki).getBytes()23501 };23502 return forge.pem.encode(msg, {maxline: maxline});23503};23504/**23505 * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption23506 * is not performed.23507 *23508 * @param pem the EncryptedPrivateKeyInfo in PEM-format.23509 *23510 * @return the ASN.1 EncryptedPrivateKeyInfo.23511 */23512pki.encryptedPrivateKeyFromPem = function(pem) {23513 var msg = forge.pem.decode(pem)[0];23514 if(msg.type !== 'ENCRYPTED PRIVATE KEY') {23515 var error = new Error('Could not convert encrypted private key from PEM; ' +23516 'PEM header type is "ENCRYPTED PRIVATE KEY".');23517 error.headerType = msg.type;23518 throw error;23519 }23520 if(msg.procType && msg.procType.type === 'ENCRYPTED') {23521 throw new Error('Could not convert encrypted private key from PEM; ' +23522 'PEM is encrypted.');23523 }23524 // convert DER to ASN.1 object23525 return asn1.fromDer(msg.body);23526};23527/**23528 * Encrypts an RSA private key. By default, the key will be wrapped in23529 * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.23530 * This is the standard, preferred way to encrypt a private key.23531 *23532 * To produce a non-standard PEM-encrypted private key that uses encapsulated23533 * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL23534 * private key encryption), set the 'legacy' option to true. Note: Using this23535 * option will cause the iteration count to be forced to 1.23536 *23537 * Note: The 'des' algorithm is supported, but it is not considered to be23538 * secure because it only uses a single 56-bit key. If possible, it is highly23539 * recommended that a different algorithm be used.23540 *23541 * @param rsaKey the RSA key to encrypt.23542 * @param password the password to use.23543 * @param options:23544 * algorithm: the encryption algorithm to use23545 * ('aes128', 'aes192', 'aes256', '3des', 'des').23546 * count: the iteration count to use.23547 * saltSize: the salt size to use.23548 * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated23549 * headers (DEK-Info) private key.23550 *23551 * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.23552 */23553pki.encryptRsaPrivateKey = function(rsaKey, password, options) {23554 // standard PKCS#823555 options = options || {};23556 if(!options.legacy) {23557 // encrypt PrivateKeyInfo23558 var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));23559 rval = pki.encryptPrivateKeyInfo(rval, password, options);23560 return pki.encryptedPrivateKeyToPem(rval);23561 }23562 // legacy non-PKCS#823563 var algorithm;23564 var iv;23565 var dkLen;23566 var cipherFn;23567 switch(options.algorithm) {23568 case 'aes128':23569 algorithm = 'AES-128-CBC';23570 dkLen = 16;23571 iv = forge.random.getBytesSync(16);23572 cipherFn = forge.aes.createEncryptionCipher;23573 break;23574 case 'aes192':23575 algorithm = 'AES-192-CBC';23576 dkLen = 24;23577 iv = forge.random.getBytesSync(16);23578 cipherFn = forge.aes.createEncryptionCipher;23579 break;23580 case 'aes256':23581 algorithm = 'AES-256-CBC';23582 dkLen = 32;23583 iv = forge.random.getBytesSync(16);23584 cipherFn = forge.aes.createEncryptionCipher;23585 break;23586 case '3des':23587 algorithm = 'DES-EDE3-CBC';23588 dkLen = 24;23589 iv = forge.random.getBytesSync(8);23590 cipherFn = forge.des.createEncryptionCipher;23591 break;23592 case 'des':23593 algorithm = 'DES-CBC';23594 dkLen = 8;23595 iv = forge.random.getBytesSync(8);23596 cipherFn = forge.des.createEncryptionCipher;23597 break;23598 default:23599 var error = new Error('Could not encrypt RSA private key; unsupported ' +23600 'encryption algorithm "' + options.algorithm + '".');23601 error.algorithm = options.algorithm;23602 throw error;23603 }23604 // encrypt private key using OpenSSL legacy key derivation23605 var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);23606 var cipher = cipherFn(dk);23607 cipher.start(iv);23608 cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey)));23609 cipher.finish();23610 var msg = {23611 type: 'RSA PRIVATE KEY',23612 procType: {23613 version: '4',23614 type: 'ENCRYPTED'23615 },23616 dekInfo: {23617 algorithm: algorithm,23618 parameters: forge.util.bytesToHex(iv).toUpperCase()23619 },23620 body: cipher.output.getBytes()23621 };23622 return forge.pem.encode(msg);23623};23624/**23625 * Decrypts an RSA private key.23626 *23627 * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.23628 * @param password the password to use.23629 *23630 * @return the RSA key on success, null on failure.23631 */23632pki.decryptRsaPrivateKey = function(pem, password) {23633 var rval = null;23634 var msg = forge.pem.decode(pem)[0];23635 if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&23636 msg.type !== 'PRIVATE KEY' &&23637 msg.type !== 'RSA PRIVATE KEY') {23638 var error = new Error('Could not convert private key from PEM; PEM header type ' +23639 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');23640 error.headerType = error;23641 throw error;23642 }23643 if(msg.procType && msg.procType.type === 'ENCRYPTED') {23644 var dkLen;23645 var cipherFn;23646 switch(msg.dekInfo.algorithm) {23647 case 'DES-CBC':23648 dkLen = 8;23649 cipherFn = forge.des.createDecryptionCipher;23650 break;23651 case 'DES-EDE3-CBC':23652 dkLen = 24;23653 cipherFn = forge.des.createDecryptionCipher;23654 break;23655 case 'AES-128-CBC':23656 dkLen = 16;23657 cipherFn = forge.aes.createDecryptionCipher;23658 break;23659 case 'AES-192-CBC':23660 dkLen = 24;23661 cipherFn = forge.aes.createDecryptionCipher;23662 break;23663 case 'AES-256-CBC':23664 dkLen = 32;23665 cipherFn = forge.aes.createDecryptionCipher;23666 break;23667 case 'RC2-40-CBC':23668 dkLen = 5;23669 cipherFn = function(key) {23670 return forge.rc2.createDecryptionCipher(key, 40);23671 };23672 break;23673 case 'RC2-64-CBC':23674 dkLen = 8;23675 cipherFn = function(key) {23676 return forge.rc2.createDecryptionCipher(key, 64);23677 };23678 break;23679 case 'RC2-128-CBC':23680 dkLen = 16;23681 cipherFn = function(key) {23682 return forge.rc2.createDecryptionCipher(key, 128);23683 };23684 break;23685 default:23686 var error = new Error('Could not decrypt private key; unsupported ' +23687 'encryption algorithm "' + msg.dekInfo.algorithm + '".');23688 error.algorithm = msg.dekInfo.algorithm;23689 throw error;23690 }23691 // use OpenSSL legacy key derivation23692 var iv = forge.util.hexToBytes(msg.dekInfo.parameters);23693 var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);23694 var cipher = cipherFn(dk);23695 cipher.start(iv);23696 cipher.update(forge.util.createBuffer(msg.body));23697 if(cipher.finish()) {23698 rval = cipher.output.getBytes();23699 } else {23700 return rval;23701 }23702 } else {23703 rval = msg.body;23704 }23705 if(msg.type === 'ENCRYPTED PRIVATE KEY') {23706 rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password);23707 } else {23708 // decryption already performed above23709 rval = asn1.fromDer(rval);23710 }23711 if(rval !== null) {23712 rval = pki.privateKeyFromAsn1(rval);23713 }23714 return rval;23715};23716/**23717 * Derives a PKCS#12 key.23718 *23719 * @param password the password to derive the key material from, null or23720 * undefined for none.23721 * @param salt the salt, as a ByteBuffer, to use.23722 * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).23723 * @param iter the iteration count.23724 * @param n the number of bytes to derive from the password.23725 * @param md the message digest to use, defaults to SHA-1.23726 *23727 * @return a ByteBuffer with the bytes derived from the password.23728 */23729pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {23730 var j, l;23731 if(typeof md === 'undefined' || md === null) {23732 if(!('sha1' in forge.md)) {23733 throw new Error('"sha1" hash algorithm unavailable.');23734 }23735 md = forge.md.sha1.create();23736 }23737 var u = md.digestLength;23738 var v = md.blockLength;23739 var result = new forge.util.ByteBuffer();23740 /* Convert password to Unicode byte buffer + trailing 0-byte. */23741 var passBuf = new forge.util.ByteBuffer();23742 if(password !== null && password !== undefined) {23743 for(l = 0; l < password.length; l++) {23744 passBuf.putInt16(password.charCodeAt(l));23745 }23746 passBuf.putInt16(0);23747 }23748 /* Length of salt and password in BYTES. */23749 var p = passBuf.length();23750 var s = salt.length();23751 /* 1. Construct a string, D (the "diversifier"), by concatenating23752 v copies of ID. */23753 var D = new forge.util.ByteBuffer();23754 D.fillWithByte(id, v);23755 /* 2. Concatenate copies of the salt together to create a string S of length23756 v * ceil(s / v) bytes (the final copy of the salt may be trunacted23757 to create S).23758 Note that if the salt is the empty string, then so is S. */23759 var Slen = v * Math.ceil(s / v);23760 var S = new forge.util.ByteBuffer();23761 for(l = 0; l < Slen; l++) {23762 S.putByte(salt.at(l % s));23763 }23764 /* 3. Concatenate copies of the password together to create a string P of23765 length v * ceil(p / v) bytes (the final copy of the password may be23766 truncated to create P).23767 Note that if the password is the empty string, then so is P. */23768 var Plen = v * Math.ceil(p / v);23769 var P = new forge.util.ByteBuffer();23770 for(l = 0; l < Plen; l++) {23771 P.putByte(passBuf.at(l % p));23772 }23773 /* 4. Set I=S||P to be the concatenation of S and P. */23774 var I = S;23775 I.putBuffer(P);23776 /* 5. Set c=ceil(n / u). */23777 var c = Math.ceil(n / u);23778 /* 6. For i=1, 2, ..., c, do the following: */23779 for(var i = 1; i <= c; i++) {23780 /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */23781 var buf = new forge.util.ByteBuffer();23782 buf.putBytes(D.bytes());23783 buf.putBytes(I.bytes());23784 for(var round = 0; round < iter; round++) {23785 md.start();23786 md.update(buf.getBytes());23787 buf = md.digest();23788 }23789 /* b) Concatenate copies of Ai to create a string B of length v bytes (the23790 final copy of Ai may be truncated to create B). */23791 var B = new forge.util.ByteBuffer();23792 for(l = 0; l < v; l++) {23793 B.putByte(buf.at(l % u));23794 }23795 /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,23796 where k=ceil(s / v) + ceil(p / v), modify I by setting23797 Ij=(Ij+B+1) mod 2v for each j. */23798 var k = Math.ceil(s / v) + Math.ceil(p / v);23799 var Inew = new forge.util.ByteBuffer();23800 for(j = 0; j < k; j++) {23801 var chunk = new forge.util.ByteBuffer(I.getBytes(v));23802 var x = 0x1ff;23803 for(l = B.length() - 1; l >= 0; l--) {23804 x = x >> 8;23805 x += B.at(l) + chunk.at(l);23806 chunk.setAt(l, x & 0xff);23807 }23808 Inew.putBuffer(chunk);23809 }23810 I = Inew;23811 /* Add Ai to A. */23812 result.putBuffer(buf);23813 }23814 result.truncate(result.length() - n);23815 return result;23816};23817/**23818 * Get new Forge cipher object instance.23819 *23820 * @param oid the OID (in string notation).23821 * @param params the ASN.1 params object.23822 * @param password the password to decrypt with.23823 *23824 * @return new cipher object instance.23825 */23826pki.pbe.getCipher = function(oid, params, password) {23827 switch(oid) {23828 case pki.oids['pkcs5PBES2']:23829 return pki.pbe.getCipherForPBES2(oid, params, password);23830 case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:23831 case pki.oids['pbewithSHAAnd40BitRC2-CBC']:23832 return pki.pbe.getCipherForPKCS12PBE(oid, params, password);23833 default:23834 var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');23835 error.oid = oid;23836 error.supportedOids = [23837 'pkcs5PBES2',23838 'pbeWithSHAAnd3-KeyTripleDES-CBC',23839 'pbewithSHAAnd40BitRC2-CBC'23840 ];23841 throw error;23842 }23843};23844/**23845 * Get new Forge cipher object instance according to PBES2 params block.23846 *23847 * The returned cipher instance is already started using the IV23848 * from PBES2 parameter block.23849 *23850 * @param oid the PKCS#5 PBKDF2 OID (in string notation).23851 * @param params the ASN.1 PBES2-params object.23852 * @param password the password to decrypt with.23853 *23854 * @return new cipher object instance.23855 */23856pki.pbe.getCipherForPBES2 = function(oid, params, password) {23857 // get PBE params23858 var capture = {};23859 var errors = [];23860 if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {23861 var error = new Error('Cannot read password-based-encryption algorithm ' +23862 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');23863 error.errors = errors;23864 throw error;23865 }23866 // check oids23867 oid = asn1.derToOid(capture.kdfOid);23868 if(oid !== pki.oids['pkcs5PBKDF2']) {23869 var error = new Error('Cannot read encrypted private key. ' +23870 'Unsupported key derivation function OID.');23871 error.oid = oid;23872 error.supportedOids = ['pkcs5PBKDF2'];23873 throw error;23874 }23875 oid = asn1.derToOid(capture.encOid);23876 if(oid !== pki.oids['aes128-CBC'] &&23877 oid !== pki.oids['aes192-CBC'] &&23878 oid !== pki.oids['aes256-CBC'] &&23879 oid !== pki.oids['des-EDE3-CBC'] &&23880 oid !== pki.oids['desCBC']) {23881 var error = new Error('Cannot read encrypted private key. ' +23882 'Unsupported encryption scheme OID.');23883 error.oid = oid;23884 error.supportedOids = [23885 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];23886 throw error;23887 }23888 // set PBE params23889 var salt = capture.kdfSalt;23890 var count = forge.util.createBuffer(capture.kdfIterationCount);23891 count = count.getInt(count.length() << 3);23892 var dkLen;23893 var cipherFn;23894 switch(pki.oids[oid]) {23895 case 'aes128-CBC':23896 dkLen = 16;23897 cipherFn = forge.aes.createDecryptionCipher;23898 break;23899 case 'aes192-CBC':23900 dkLen = 24;23901 cipherFn = forge.aes.createDecryptionCipher;23902 break;23903 case 'aes256-CBC':23904 dkLen = 32;23905 cipherFn = forge.aes.createDecryptionCipher;23906 break;23907 case 'des-EDE3-CBC':23908 dkLen = 24;23909 cipherFn = forge.des.createDecryptionCipher;23910 break;23911 case 'desCBC':23912 dkLen = 8;23913 cipherFn = forge.des.createDecryptionCipher;23914 break;23915 }23916 // get PRF message digest23917 var md = prfOidToMessageDigest(capture.prfOid);23918 // decrypt private key using pbe with chosen PRF and AES/DES23919 var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md);23920 var iv = capture.encIv;23921 var cipher = cipherFn(dk);23922 cipher.start(iv);23923 return cipher;23924};23925/**23926 * Get new Forge cipher object instance for PKCS#12 PBE.23927 *23928 * The returned cipher instance is already started using the key & IV23929 * derived from the provided password and PKCS#12 PBE salt.23930 *23931 * @param oid The PKCS#12 PBE OID (in string notation).23932 * @param params The ASN.1 PKCS#12 PBE-params object.23933 * @param password The password to decrypt with.23934 *23935 * @return the new cipher object instance.23936 */23937pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {23938 // get PBE params23939 var capture = {};23940 var errors = [];23941 if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {23942 var error = new Error('Cannot read password-based-encryption algorithm ' +23943 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');23944 error.errors = errors;23945 throw error;23946 }23947 var salt = forge.util.createBuffer(capture.salt);23948 var count = forge.util.createBuffer(capture.iterations);23949 count = count.getInt(count.length() << 3);23950 var dkLen, dIvLen, cipherFn;23951 switch(oid) {23952 case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:23953 dkLen = 24;23954 dIvLen = 8;23955 cipherFn = forge.des.startDecrypting;23956 break;23957 case pki.oids['pbewithSHAAnd40BitRC2-CBC']:23958 dkLen = 5;23959 dIvLen = 8;23960 cipherFn = function(key, iv) {23961 var cipher = forge.rc2.createDecryptionCipher(key, 40);23962 cipher.start(iv, null);23963 return cipher;23964 };23965 break;23966 default:23967 var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');23968 error.oid = oid;23969 throw error;23970 }23971 // get PRF message digest23972 var md = prfOidToMessageDigest(capture.prfOid);23973 var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);23974 md.start();23975 var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);23976 return cipherFn(key, iv);23977};23978/**23979 * OpenSSL's legacy key derivation function.23980 *23981 * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html23982 *23983 * @param password the password to derive the key from.23984 * @param salt the salt to use, null for none.23985 * @param dkLen the number of bytes needed for the derived key.23986 * @param [options] the options to use:23987 * [md] an optional message digest object to use.23988 */23989pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {23990 if(typeof md === 'undefined' || md === null) {23991 if(!('md5' in forge.md)) {23992 throw new Error('"md5" hash algorithm unavailable.');23993 }23994 md = forge.md.md5.create();23995 }23996 if(salt === null) {23997 salt = '';23998 }23999 var digests = [hash(md, password + salt)];24000 for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {24001 digests.push(hash(md, digests[i - 1] + password + salt));24002 }24003 return digests.join('').substr(0, dkLen);24004};24005function hash(md, bytes) {24006 return md.start().update(bytes).digest().getBytes();24007}24008function prfOidToMessageDigest(prfOid) {24009 // get PRF algorithm, default to SHA-124010 var prfAlgorithm;24011 if(!prfOid) {24012 prfAlgorithm = 'hmacWithSHA1';24013 } else {24014 prfAlgorithm = pki.oids[asn1.derToOid(prfOid)];24015 if(!prfAlgorithm) {24016 var error = new Error('Unsupported PRF OID.');24017 error.oid = prfOid;24018 error.supported = [24019 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',24020 'hmacWithSHA512'];24021 throw error;24022 }24023 }24024 return prfAlgorithmToMessageDigest(prfAlgorithm);24025}24026function prfAlgorithmToMessageDigest(prfAlgorithm) {24027 var factory = forge.md;24028 switch(prfAlgorithm) {24029 case 'hmacWithSHA224':24030 factory = forge.md.sha512;24031 case 'hmacWithSHA1':24032 case 'hmacWithSHA256':24033 case 'hmacWithSHA384':24034 case 'hmacWithSHA512':24035 prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();24036 break;24037 default:24038 var error = new Error('Unsupported PRF algorithm.');24039 error.algorithm = prfAlgorithm;24040 error.supported = [24041 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',24042 'hmacWithSHA512'];24043 throw error;24044 }24045 if(!factory || !(prfAlgorithm in factory)) {24046 throw new Error('Unknown hash algorithm: ' + prfAlgorithm);24047 }24048 return factory[prfAlgorithm].create();24049}24050function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {24051 var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [24052 // salt24053 asn1.create(24054 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt),24055 // iteration count24056 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,24057 countBytes.getBytes())24058 ]);24059 // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm24060 if(prfAlgorithm !== 'hmacWithSHA1') {24061 params.value.push(24062 // key length24063 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,24064 forge.util.hexToBytes(dkLen.toString(16))),24065 // AlgorithmIdentifier24066 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [24067 // algorithm24068 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,24069 asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),24070 // parameters (null)24071 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')24072 ]));24073 }24074 return params;24075}24076/***/ }),24077/***/ 1611:24078/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {24079/**24080 * Password-Based Key-Derivation Function #2 implementation.24081 *24082 * See RFC 2898 for details.24083 *24084 * @author Dave Longley24085 *24086 * Copyright (c) 2010-2013 Digital Bazaar, Inc.24087 */24088var forge = __nccwpck_require__(9177);24089__nccwpck_require__(5104);24090__nccwpck_require__(6231);24091__nccwpck_require__(8339);24092var pkcs5 = forge.pkcs5 = forge.pkcs5 || {};24093var crypto;24094if(forge.util.isNodejs && !forge.options.usePureJavaScript) {24095 crypto = __nccwpck_require__(6113);24096}24097/**24098 * Derives a key from a password.24099 *24100 * @param p the password as a binary-encoded string of bytes.24101 * @param s the salt as a binary-encoded string of bytes.24102 * @param c the iteration count, a positive integer.24103 * @param dkLen the intended length, in bytes, of the derived key,24104 * (max: 2^32 - 1) * hash length of the PRF.24105 * @param [md] the message digest (or algorithm identifier as a string) to use24106 * in the PRF, defaults to SHA-1.24107 * @param [callback(err, key)] presence triggers asynchronous version, called24108 * once the operation completes.24109 *24110 * @return the derived key, as a binary-encoded string of bytes, for the24111 * synchronous version (if no callback is specified).24112 */24113module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(24114 p, s, c, dkLen, md, callback) {24115 if(typeof md === 'function') {24116 callback = md;24117 md = null;24118 }24119 // use native implementation if possible and not disabled, note that24120 // some node versions only support SHA-1, others allow digest to be changed24121 if(forge.util.isNodejs && !forge.options.usePureJavaScript &&24122 crypto.pbkdf2 && (md === null || typeof md !== 'object') &&24123 (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {24124 if(typeof md !== 'string') {24125 // default prf to SHA-124126 md = 'sha1';24127 }24128 p = Buffer.from(p, 'binary');24129 s = Buffer.from(s, 'binary');24130 if(!callback) {24131 if(crypto.pbkdf2Sync.length === 4) {24132 return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');24133 }24134 return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');24135 }24136 if(crypto.pbkdf2Sync.length === 4) {24137 return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {24138 if(err) {24139 return callback(err);24140 }24141 callback(null, key.toString('binary'));24142 });24143 }24144 return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {24145 if(err) {24146 return callback(err);24147 }24148 callback(null, key.toString('binary'));24149 });24150 }24151 if(typeof md === 'undefined' || md === null) {24152 // default prf to SHA-124153 md = 'sha1';24154 }24155 if(typeof md === 'string') {24156 if(!(md in forge.md.algorithms)) {24157 throw new Error('Unknown hash algorithm: ' + md);24158 }24159 md = forge.md[md].create();24160 }24161 var hLen = md.digestLength;24162 /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and24163 stop. */24164 if(dkLen > (0xFFFFFFFF * hLen)) {24165 var err = new Error('Derived key is too long.');24166 if(callback) {24167 return callback(err);24168 }24169 throw err;24170 }24171 /* 2. Let len be the number of hLen-octet blocks in the derived key,24172 rounding up, and let r be the number of octets in the last24173 block:24174 len = CEIL(dkLen / hLen),24175 r = dkLen - (len - 1) * hLen. */24176 var len = Math.ceil(dkLen / hLen);24177 var r = dkLen - (len - 1) * hLen;24178 /* 3. For each block of the derived key apply the function F defined24179 below to the password P, the salt S, the iteration count c, and24180 the block index to compute the block:24181 T_1 = F(P, S, c, 1),24182 T_2 = F(P, S, c, 2),24183 ...24184 T_len = F(P, S, c, len),24185 where the function F is defined as the exclusive-or sum of the24186 first c iterates of the underlying pseudorandom function PRF24187 applied to the password P and the concatenation of the salt S24188 and the block index i:24189 F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c24190 where24191 u_1 = PRF(P, S || INT(i)),24192 u_2 = PRF(P, u_1),24193 ...24194 u_c = PRF(P, u_{c-1}).24195 Here, INT(i) is a four-octet encoding of the integer i, most24196 significant octet first. */24197 var prf = forge.hmac.create();24198 prf.start(md, p);24199 var dk = '';24200 var xor, u_c, u_c1;24201 // sync version24202 if(!callback) {24203 for(var i = 1; i <= len; ++i) {24204 // PRF(P, S || INT(i)) (first iteration)24205 prf.start(null, null);24206 prf.update(s);24207 prf.update(forge.util.int32ToBytes(i));24208 xor = u_c1 = prf.digest().getBytes();24209 // PRF(P, u_{c-1}) (other iterations)24210 for(var j = 2; j <= c; ++j) {24211 prf.start(null, null);24212 prf.update(u_c1);24213 u_c = prf.digest().getBytes();24214 // F(p, s, c, i)24215 xor = forge.util.xorBytes(xor, u_c, hLen);24216 u_c1 = u_c;24217 }24218 /* 4. Concatenate the blocks and extract the first dkLen octets to24219 produce a derived key DK:24220 DK = T_1 || T_2 || ... || T_len<0..r-1> */24221 dk += (i < len) ? xor : xor.substr(0, r);24222 }24223 /* 5. Output the derived key DK. */24224 return dk;24225 }24226 // async version24227 var i = 1, j;24228 function outer() {24229 if(i > len) {24230 // done24231 return callback(null, dk);24232 }24233 // PRF(P, S || INT(i)) (first iteration)24234 prf.start(null, null);24235 prf.update(s);24236 prf.update(forge.util.int32ToBytes(i));24237 xor = u_c1 = prf.digest().getBytes();24238 // PRF(P, u_{c-1}) (other iterations)24239 j = 2;24240 inner();24241 }24242 function inner() {24243 if(j <= c) {24244 prf.start(null, null);24245 prf.update(u_c1);24246 u_c = prf.digest().getBytes();24247 // F(p, s, c, i)24248 xor = forge.util.xorBytes(xor, u_c, hLen);24249 u_c1 = u_c;24250 ++j;24251 return forge.util.setImmediate(inner);24252 }24253 /* 4. Concatenate the blocks and extract the first dkLen octets to24254 produce a derived key DK:24255 DK = T_1 || T_2 || ... || T_len<0..r-1> */24256 dk += (i < len) ? xor : xor.substr(0, r);24257 ++i;24258 outer();24259 }24260 outer();24261};24262/***/ }),24263/***/ 154:24264/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {24265/**24266 * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.24267 *24268 * See: RFC 1421.24269 *24270 * @author Dave Longley24271 *24272 * Copyright (c) 2013-2014 Digital Bazaar, Inc.24273 *24274 * A Forge PEM object has the following fields:24275 *24276 * type: identifies the type of message (eg: "RSA PRIVATE KEY").24277 *24278 * procType: identifies the type of processing performed on the message,24279 * it has two subfields: version and type, eg: 4,ENCRYPTED.24280 *24281 * contentDomain: identifies the type of content in the message, typically24282 * only uses the value: "RFC822".24283 *24284 * dekInfo: identifies the message encryption algorithm and mode and includes24285 * any parameters for the algorithm, it has two subfields: algorithm and24286 * parameters, eg: DES-CBC,F8143EDE5960C597.24287 *24288 * headers: contains all other PEM encapsulated headers -- where order is24289 * significant (for pairing data like recipient ID + key info).24290 *24291 * body: the binary-encoded body.24292 */24293var forge = __nccwpck_require__(9177);24294__nccwpck_require__(8339);24295// shortcut for pem API24296var pem = module.exports = forge.pem = forge.pem || {};24297/**24298 * Encodes (serializes) the given PEM object.24299 *24300 * @param msg the PEM message object to encode.24301 * @param options the options to use:24302 * maxline the maximum characters per line for the body, (default: 64).24303 *24304 * @return the PEM-formatted string.24305 */24306pem.encode = function(msg, options) {24307 options = options || {};24308 var rval = '-----BEGIN ' + msg.type + '-----\r\n';24309 // encode special headers24310 var header;24311 if(msg.procType) {24312 header = {24313 name: 'Proc-Type',24314 values: [String(msg.procType.version), msg.procType.type]24315 };24316 rval += foldHeader(header);24317 }24318 if(msg.contentDomain) {24319 header = {name: 'Content-Domain', values: [msg.contentDomain]};24320 rval += foldHeader(header);24321 }24322 if(msg.dekInfo) {24323 header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};24324 if(msg.dekInfo.parameters) {24325 header.values.push(msg.dekInfo.parameters);24326 }24327 rval += foldHeader(header);24328 }24329 if(msg.headers) {24330 // encode all other headers24331 for(var i = 0; i < msg.headers.length; ++i) {24332 rval += foldHeader(msg.headers[i]);24333 }24334 }24335 // terminate header24336 if(msg.procType) {24337 rval += '\r\n';24338 }24339 // add body24340 rval += forge.util.encode64(msg.body, options.maxline || 64) + '\r\n';24341 rval += '-----END ' + msg.type + '-----\r\n';24342 return rval;24343};24344/**24345 * Decodes (deserializes) all PEM messages found in the given string.24346 *24347 * @param str the PEM-formatted string to decode.24348 *24349 * @return the PEM message objects in an array.24350 */24351pem.decode = function(str) {24352 var rval = [];24353 // split string into PEM messages (be lenient w/EOF on BEGIN line)24354 var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g;24355 var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/;24356 var rCRLF = /\r?\n/;24357 var match;24358 while(true) {24359 match = rMessage.exec(str);24360 if(!match) {24361 break;24362 }24363 // accept "NEW CERTIFICATE REQUEST" as "CERTIFICATE REQUEST"24364 // https://datatracker.ietf.org/doc/html/rfc7468#section-724365 var type = match[1];24366 if(type === 'NEW CERTIFICATE REQUEST') {24367 type = 'CERTIFICATE REQUEST';24368 }24369 var msg = {24370 type: type,24371 procType: null,24372 contentDomain: null,24373 dekInfo: null,24374 headers: [],24375 body: forge.util.decode64(match[3])24376 };24377 rval.push(msg);24378 // no headers24379 if(!match[2]) {24380 continue;24381 }24382 // parse headers24383 var lines = match[2].split(rCRLF);24384 var li = 0;24385 while(match && li < lines.length) {24386 // get line, trim any rhs whitespace24387 var line = lines[li].replace(/\s+$/, '');24388 // RFC2822 unfold any following folded lines24389 for(var nl = li + 1; nl < lines.length; ++nl) {24390 var next = lines[nl];24391 if(!/\s/.test(next[0])) {24392 break;24393 }24394 line += next;24395 li = nl;24396 }24397 // parse header24398 match = line.match(rHeader);24399 if(match) {24400 var header = {name: match[1], values: []};24401 var values = match[2].split(',');24402 for(var vi = 0; vi < values.length; ++vi) {24403 header.values.push(ltrim(values[vi]));24404 }24405 // Proc-Type must be the first header24406 if(!msg.procType) {24407 if(header.name !== 'Proc-Type') {24408 throw new Error('Invalid PEM formatted message. The first ' +24409 'encapsulated header must be "Proc-Type".');24410 } else if(header.values.length !== 2) {24411 throw new Error('Invalid PEM formatted message. The "Proc-Type" ' +24412 'header must have two subfields.');24413 }24414 msg.procType = {version: values[0], type: values[1]};24415 } else if(!msg.contentDomain && header.name === 'Content-Domain') {24416 // special-case Content-Domain24417 msg.contentDomain = values[0] || '';24418 } else if(!msg.dekInfo && header.name === 'DEK-Info') {24419 // special-case DEK-Info24420 if(header.values.length === 0) {24421 throw new Error('Invalid PEM formatted message. The "DEK-Info" ' +24422 'header must have at least one subfield.');24423 }24424 msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};24425 } else {24426 msg.headers.push(header);24427 }24428 }24429 ++li;24430 }24431 if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {24432 throw new Error('Invalid PEM formatted message. The "DEK-Info" ' +24433 'header must be present if "Proc-Type" is "ENCRYPTED".');24434 }24435 }24436 if(rval.length === 0) {24437 throw new Error('Invalid PEM formatted message.');24438 }24439 return rval;24440};24441function foldHeader(header) {24442 var rval = header.name + ': ';24443 // ensure values with CRLF are folded24444 var values = [];24445 var insertSpace = function(match, $1) {24446 return ' ' + $1;24447 };24448 for(var i = 0; i < header.values.length; ++i) {24449 values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace));24450 }24451 rval += values.join(',') + '\r\n';24452 // do folding24453 var length = 0;24454 var candidate = -1;24455 for(var i = 0; i < rval.length; ++i, ++length) {24456 if(length > 65 && candidate !== -1) {24457 var insert = rval[candidate];24458 if(insert === ',') {24459 ++candidate;24460 rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate);24461 } else {24462 rval = rval.substr(0, candidate) +24463 '\r\n' + insert + rval.substr(candidate + 1);24464 }24465 length = (i - candidate - 1);24466 candidate = -1;24467 ++i;24468 } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') {24469 candidate = i;24470 }24471 }24472 return rval;24473}24474function ltrim(str) {24475 return str.replace(/^\s+/, '');24476}24477/***/ }),24478/***/ 7014:24479/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {24480/**24481 * Partial implementation of PKCS#1 v2.2: RSA-OEAP24482 *24483 * Modified but based on the following MIT and BSD licensed code:24484 *24485 * https://github.com/kjur/jsjws/blob/master/rsa.js:24486 *24487 * The 'jsjws'(JSON Web Signature JavaScript Library) License24488 *24489 * Copyright (c) 2012 Kenji Urushima24490 *24491 * Permission is hereby granted, free of charge, to any person obtaining a copy24492 * of this software and associated documentation files (the "Software"), to deal24493 * in the Software without restriction, including without limitation the rights24494 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell24495 * copies of the Software, and to permit persons to whom the Software is24496 * furnished to do so, subject to the following conditions:24497 *24498 * The above copyright notice and this permission notice shall be included in24499 * all copies or substantial portions of the Software.24500 *24501 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR24502 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,24503 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE24504 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER24505 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,24506 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN24507 * THE SOFTWARE.24508 *24509 * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:24510 *24511 * RSAES-OAEP.js24512 * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $24513 * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)24514 * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.24515 * Contact: ellis@nukinetics.com24516 * Distributed under the BSD License.24517 *24518 * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=212524519 *24520 * @author Evan Jones (http://evanjones.ca/)24521 * @author Dave Longley24522 *24523 * Copyright (c) 2013-2014 Digital Bazaar, Inc.24524 */24525var forge = __nccwpck_require__(9177);24526__nccwpck_require__(8339);24527__nccwpck_require__(7821);24528__nccwpck_require__(279);24529// shortcut for PKCS#1 API24530var pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {};24531/**24532 * Encode the given RSAES-OAEP message (M) using key, with optional label (L)24533 * and seed.24534 *24535 * This method does not perform RSA encryption, it only encodes the message24536 * using RSAES-OAEP.24537 *24538 * @param key the RSA key to use.24539 * @param message the message to encode.24540 * @param options the options to use:24541 * label an optional label to use.24542 * seed the seed to use.24543 * md the message digest object to use, undefined for SHA-1.24544 * mgf1 optional mgf1 parameters:24545 * md the message digest object to use for MGF1.24546 *24547 * @return the encoded message bytes.24548 */24549pkcs1.encode_rsa_oaep = function(key, message, options) {24550 // parse arguments24551 var label;24552 var seed;24553 var md;24554 var mgf1Md;24555 // legacy args (label, seed, md)24556 if(typeof options === 'string') {24557 label = options;24558 seed = arguments[3] || undefined;24559 md = arguments[4] || undefined;24560 } else if(options) {24561 label = options.label || undefined;24562 seed = options.seed || undefined;24563 md = options.md || undefined;24564 if(options.mgf1 && options.mgf1.md) {24565 mgf1Md = options.mgf1.md;24566 }24567 }24568 // default OAEP to SHA-1 message digest24569 if(!md) {24570 md = forge.md.sha1.create();24571 } else {24572 md.start();24573 }24574 // default MGF-1 to same as OAEP24575 if(!mgf1Md) {24576 mgf1Md = md;24577 }24578 // compute length in bytes and check output24579 var keyLength = Math.ceil(key.n.bitLength() / 8);24580 var maxLength = keyLength - 2 * md.digestLength - 2;24581 if(message.length > maxLength) {24582 var error = new Error('RSAES-OAEP input message length is too long.');24583 error.length = message.length;24584 error.maxLength = maxLength;24585 throw error;24586 }24587 if(!label) {24588 label = '';24589 }24590 md.update(label, 'raw');24591 var lHash = md.digest();24592 var PS = '';24593 var PS_length = maxLength - message.length;24594 for(var i = 0; i < PS_length; i++) {24595 PS += '\x00';24596 }24597 var DB = lHash.getBytes() + PS + '\x01' + message;24598 if(!seed) {24599 seed = forge.random.getBytes(md.digestLength);24600 } else if(seed.length !== md.digestLength) {24601 var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +24602 'match the digest length.');24603 error.seedLength = seed.length;24604 error.digestLength = md.digestLength;24605 throw error;24606 }24607 var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);24608 var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length);24609 var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);24610 var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length);24611 // return encoded message24612 return '\x00' + maskedSeed + maskedDB;24613};24614/**24615 * Decode the given RSAES-OAEP encoded message (EM) using key, with optional24616 * label (L).24617 *24618 * This method does not perform RSA decryption, it only decodes the message24619 * using RSAES-OAEP.24620 *24621 * @param key the RSA key to use.24622 * @param em the encoded message to decode.24623 * @param options the options to use:24624 * label an optional label to use.24625 * md the message digest object to use for OAEP, undefined for SHA-1.24626 * mgf1 optional mgf1 parameters:24627 * md the message digest object to use for MGF1.24628 *24629 * @return the decoded message bytes.24630 */24631pkcs1.decode_rsa_oaep = function(key, em, options) {24632 // parse args24633 var label;24634 var md;24635 var mgf1Md;24636 // legacy args24637 if(typeof options === 'string') {24638 label = options;24639 md = arguments[3] || undefined;24640 } else if(options) {24641 label = options.label || undefined;24642 md = options.md || undefined;24643 if(options.mgf1 && options.mgf1.md) {24644 mgf1Md = options.mgf1.md;24645 }24646 }24647 // compute length in bytes24648 var keyLength = Math.ceil(key.n.bitLength() / 8);24649 if(em.length !== keyLength) {24650 var error = new Error('RSAES-OAEP encoded message length is invalid.');24651 error.length = em.length;24652 error.expectedLength = keyLength;24653 throw error;24654 }24655 // default OAEP to SHA-1 message digest24656 if(md === undefined) {24657 md = forge.md.sha1.create();24658 } else {24659 md.start();24660 }24661 // default MGF-1 to same as OAEP24662 if(!mgf1Md) {24663 mgf1Md = md;24664 }24665 if(keyLength < 2 * md.digestLength + 2) {24666 throw new Error('RSAES-OAEP key is too short for the hash function.');24667 }24668 if(!label) {24669 label = '';24670 }24671 md.update(label, 'raw');24672 var lHash = md.digest().getBytes();24673 // split the message into its parts24674 var y = em.charAt(0);24675 var maskedSeed = em.substring(1, md.digestLength + 1);24676 var maskedDB = em.substring(1 + md.digestLength);24677 var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);24678 var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);24679 var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);24680 var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);24681 var lHashPrime = db.substring(0, md.digestLength);24682 // constant time check that all values match what is expected24683 var error = (y !== '\x00');24684 // constant time check lHash vs lHashPrime24685 for(var i = 0; i < md.digestLength; ++i) {24686 error |= (lHash.charAt(i) !== lHashPrime.charAt(i));24687 }24688 // "constant time" find the 0x1 byte separating the padding (zeros) from the24689 // message24690 // TODO: It must be possible to do this in a better/smarter way?24691 var in_ps = 1;24692 var index = md.digestLength;24693 for(var j = md.digestLength; j < db.length; j++) {24694 var code = db.charCodeAt(j);24695 var is_0 = (code & 0x1) ^ 0x1;24696 // non-zero if not 0 or 1 in the ps section24697 var error_mask = in_ps ? 0xfffe : 0x0000;24698 error |= (code & error_mask);24699 // latch in_ps to zero after we find 0x124700 in_ps = in_ps & is_0;24701 index += in_ps;24702 }24703 if(error || db.charCodeAt(index) !== 0x1) {24704 throw new Error('Invalid RSAES-OAEP padding.');24705 }24706 return db.substring(index + 1);24707};24708function rsa_mgf1(seed, maskLength, hash) {24709 // default to SHA-1 message digest24710 if(!hash) {24711 hash = forge.md.sha1.create();24712 }24713 var t = '';24714 var count = Math.ceil(maskLength / hash.digestLength);24715 for(var i = 0; i < count; ++i) {24716 var c = String.fromCharCode(24717 (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);24718 hash.start();24719 hash.update(seed + c);24720 t += hash.digest().getBytes();24721 }24722 return t.substring(0, maskLength);24723}24724/***/ }),24725/***/ 466:24726/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {24727/**24728 * Javascript implementation of PKCS#12.24729 *24730 * @author Dave Longley24731 * @author Stefan Siegl <stesie@brokenpipe.de>24732 *24733 * Copyright (c) 2010-2014 Digital Bazaar, Inc.24734 * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>24735 *24736 * The ASN.1 representation of PKCS#12 is as follows24737 * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details)24738 *24739 * PFX ::= SEQUENCE {24740 * version INTEGER {v3(3)}(v3,...),24741 * authSafe ContentInfo,24742 * macData MacData OPTIONAL24743 * }24744 *24745 * MacData ::= SEQUENCE {24746 * mac DigestInfo,24747 * macSalt OCTET STRING,24748 * iterations INTEGER DEFAULT 124749 * }24750 * Note: The iterations default is for historical reasons and its use is24751 * deprecated. A higher value, like 1024, is recommended.24752 *24753 * DigestInfo is defined in PKCS#7 as follows:24754 *24755 * DigestInfo ::= SEQUENCE {24756 * digestAlgorithm DigestAlgorithmIdentifier,24757 * digest Digest24758 * }24759 *24760 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier24761 *24762 * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters24763 * for the algorithm, if any. In the case of SHA1 there is none.24764 *24765 * AlgorithmIdentifer ::= SEQUENCE {24766 * algorithm OBJECT IDENTIFIER,24767 * parameters ANY DEFINED BY algorithm OPTIONAL24768 * }24769 *24770 * Digest ::= OCTET STRING24771 *24772 *24773 * ContentInfo ::= SEQUENCE {24774 * contentType ContentType,24775 * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL24776 * }24777 *24778 * ContentType ::= OBJECT IDENTIFIER24779 *24780 * AuthenticatedSafe ::= SEQUENCE OF ContentInfo24781 * -- Data if unencrypted24782 * -- EncryptedData if password-encrypted24783 * -- EnvelopedData if public key-encrypted24784 *24785 *24786 * SafeContents ::= SEQUENCE OF SafeBag24787 *24788 * SafeBag ::= SEQUENCE {24789 * bagId BAG-TYPE.&id ({PKCS12BagSet})24790 * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),24791 * bagAttributes SET OF PKCS12Attribute OPTIONAL24792 * }24793 *24794 * PKCS12Attribute ::= SEQUENCE {24795 * attrId ATTRIBUTE.&id ({PKCS12AttrSet}),24796 * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})24797 * } -- This type is compatible with the X.500 type 'Attribute'24798 *24799 * PKCS12AttrSet ATTRIBUTE ::= {24800 * friendlyName | -- from PKCS #924801 * localKeyId, -- from PKCS #924802 * ... -- Other attributes are allowed24803 * }24804 *24805 * CertBag ::= SEQUENCE {24806 * certId BAG-TYPE.&id ({CertTypes}),24807 * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})24808 * }24809 *24810 * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}}24811 * -- DER-encoded X.509 certificate stored in OCTET STRING24812 *24813 * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}}24814 * -- Base64-encoded SDSI certificate stored in IA5String24815 *24816 * CertTypes BAG-TYPE ::= {24817 * x509Certificate |24818 * sdsiCertificate,24819 * ... -- For future extensions24820 * }24821 */24822var forge = __nccwpck_require__(9177);24823__nccwpck_require__(9549);24824__nccwpck_require__(5104);24825__nccwpck_require__(1925);24826__nccwpck_require__(266);24827__nccwpck_require__(1281);24828__nccwpck_require__(7821);24829__nccwpck_require__(3921);24830__nccwpck_require__(279);24831__nccwpck_require__(8339);24832__nccwpck_require__(8180);24833// shortcut for asn.1 & PKI API24834var asn1 = forge.asn1;24835var pki = forge.pki;24836// shortcut for PKCS#12 API24837var p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {};24838var contentInfoValidator = {24839 name: 'ContentInfo',24840 tagClass: asn1.Class.UNIVERSAL,24841 type: asn1.Type.SEQUENCE, // a ContentInfo24842 constructed: true,24843 value: [{24844 name: 'ContentInfo.contentType',24845 tagClass: asn1.Class.UNIVERSAL,24846 type: asn1.Type.OID,24847 constructed: false,24848 capture: 'contentType'24849 }, {24850 name: 'ContentInfo.content',24851 tagClass: asn1.Class.CONTEXT_SPECIFIC,24852 constructed: true,24853 captureAsn1: 'content'24854 }]24855};24856var pfxValidator = {24857 name: 'PFX',24858 tagClass: asn1.Class.UNIVERSAL,24859 type: asn1.Type.SEQUENCE,24860 constructed: true,24861 value: [{24862 name: 'PFX.version',24863 tagClass: asn1.Class.UNIVERSAL,24864 type: asn1.Type.INTEGER,24865 constructed: false,24866 capture: 'version'24867 },24868 contentInfoValidator, {24869 name: 'PFX.macData',24870 tagClass: asn1.Class.UNIVERSAL,24871 type: asn1.Type.SEQUENCE,24872 constructed: true,24873 optional: true,24874 captureAsn1: 'mac',24875 value: [{24876 name: 'PFX.macData.mac',24877 tagClass: asn1.Class.UNIVERSAL,24878 type: asn1.Type.SEQUENCE, // DigestInfo24879 constructed: true,24880 value: [{24881 name: 'PFX.macData.mac.digestAlgorithm',24882 tagClass: asn1.Class.UNIVERSAL,24883 type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier24884 constructed: true,24885 value: [{24886 name: 'PFX.macData.mac.digestAlgorithm.algorithm',24887 tagClass: asn1.Class.UNIVERSAL,24888 type: asn1.Type.OID,24889 constructed: false,24890 capture: 'macAlgorithm'24891 }, {24892 name: 'PFX.macData.mac.digestAlgorithm.parameters',24893 tagClass: asn1.Class.UNIVERSAL,24894 captureAsn1: 'macAlgorithmParameters'24895 }]24896 }, {24897 name: 'PFX.macData.mac.digest',24898 tagClass: asn1.Class.UNIVERSAL,24899 type: asn1.Type.OCTETSTRING,24900 constructed: false,24901 capture: 'macDigest'24902 }]24903 }, {24904 name: 'PFX.macData.macSalt',24905 tagClass: asn1.Class.UNIVERSAL,24906 type: asn1.Type.OCTETSTRING,24907 constructed: false,24908 capture: 'macSalt'24909 }, {24910 name: 'PFX.macData.iterations',24911 tagClass: asn1.Class.UNIVERSAL,24912 type: asn1.Type.INTEGER,24913 constructed: false,24914 optional: true,24915 capture: 'macIterations'24916 }]24917 }]24918};24919var safeBagValidator = {24920 name: 'SafeBag',24921 tagClass: asn1.Class.UNIVERSAL,24922 type: asn1.Type.SEQUENCE,24923 constructed: true,24924 value: [{24925 name: 'SafeBag.bagId',24926 tagClass: asn1.Class.UNIVERSAL,24927 type: asn1.Type.OID,24928 constructed: false,24929 capture: 'bagId'24930 }, {24931 name: 'SafeBag.bagValue',24932 tagClass: asn1.Class.CONTEXT_SPECIFIC,24933 constructed: true,24934 captureAsn1: 'bagValue'24935 }, {24936 name: 'SafeBag.bagAttributes',24937 tagClass: asn1.Class.UNIVERSAL,24938 type: asn1.Type.SET,24939 constructed: true,24940 optional: true,24941 capture: 'bagAttributes'24942 }]24943};24944var attributeValidator = {24945 name: 'Attribute',24946 tagClass: asn1.Class.UNIVERSAL,24947 type: asn1.Type.SEQUENCE,24948 constructed: true,24949 value: [{24950 name: 'Attribute.attrId',24951 tagClass: asn1.Class.UNIVERSAL,24952 type: asn1.Type.OID,24953 constructed: false,24954 capture: 'oid'24955 }, {24956 name: 'Attribute.attrValues',24957 tagClass: asn1.Class.UNIVERSAL,24958 type: asn1.Type.SET,24959 constructed: true,24960 capture: 'values'24961 }]24962};24963var certBagValidator = {24964 name: 'CertBag',24965 tagClass: asn1.Class.UNIVERSAL,24966 type: asn1.Type.SEQUENCE,24967 constructed: true,24968 value: [{24969 name: 'CertBag.certId',24970 tagClass: asn1.Class.UNIVERSAL,24971 type: asn1.Type.OID,24972 constructed: false,24973 capture: 'certId'24974 }, {24975 name: 'CertBag.certValue',24976 tagClass: asn1.Class.CONTEXT_SPECIFIC,24977 constructed: true,24978 /* So far we only support X.509 certificates (which are wrapped in24979 an OCTET STRING, hence hard code that here). */24980 value: [{24981 name: 'CertBag.certValue[0]',24982 tagClass: asn1.Class.UNIVERSAL,24983 type: asn1.Class.OCTETSTRING,24984 constructed: false,24985 capture: 'cert'24986 }]24987 }]24988};24989/**24990 * Search SafeContents structure for bags with matching attributes.24991 *24992 * The search can optionally be narrowed by a certain bag type.24993 *24994 * @param safeContents the SafeContents structure to search in.24995 * @param attrName the name of the attribute to compare against.24996 * @param attrValue the attribute value to search for.24997 * @param [bagType] bag type to narrow search by.24998 *24999 * @return an array of matching bags.25000 */25001function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {25002 var result = [];25003 for(var i = 0; i < safeContents.length; i++) {25004 for(var j = 0; j < safeContents[i].safeBags.length; j++) {25005 var bag = safeContents[i].safeBags[j];25006 if(bagType !== undefined && bag.type !== bagType) {25007 continue;25008 }25009 // only filter by bag type, no attribute specified25010 if(attrName === null) {25011 result.push(bag);25012 continue;25013 }25014 if(bag.attributes[attrName] !== undefined &&25015 bag.attributes[attrName].indexOf(attrValue) >= 0) {25016 result.push(bag);25017 }25018 }25019 }25020 return result;25021}25022/**25023 * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object.25024 *25025 * @param obj The PKCS#12 PFX in ASN.1 notation.25026 * @param strict true to use strict DER decoding, false not to (default: true).25027 * @param {String} password Password to decrypt with (optional).25028 *25029 * @return PKCS#12 PFX object.25030 */25031p12.pkcs12FromAsn1 = function(obj, strict, password) {25032 // handle args25033 if(typeof strict === 'string') {25034 password = strict;25035 strict = true;25036 } else if(strict === undefined) {25037 strict = true;25038 }25039 // validate PFX and capture data25040 var capture = {};25041 var errors = [];25042 if(!asn1.validate(obj, pfxValidator, capture, errors)) {25043 var error = new Error('Cannot read PKCS#12 PFX. ' +25044 'ASN.1 object is not an PKCS#12 PFX.');25045 error.errors = error;25046 throw error;25047 }25048 var pfx = {25049 version: capture.version.charCodeAt(0),25050 safeContents: [],25051 /**25052 * Gets bags with matching attributes.25053 *25054 * @param filter the attributes to filter by:25055 * [localKeyId] the localKeyId to search for.25056 * [localKeyIdHex] the localKeyId in hex to search for.25057 * [friendlyName] the friendly name to search for.25058 * [bagType] bag type to narrow each attribute search by.25059 *25060 * @return a map of attribute type to an array of matching bags or, if no25061 * attribute was given but a bag type, the map key will be the25062 * bag type.25063 */25064 getBags: function(filter) {25065 var rval = {};25066 var localKeyId;25067 if('localKeyId' in filter) {25068 localKeyId = filter.localKeyId;25069 } else if('localKeyIdHex' in filter) {25070 localKeyId = forge.util.hexToBytes(filter.localKeyIdHex);25071 }25072 // filter on bagType only25073 if(localKeyId === undefined && !('friendlyName' in filter) &&25074 'bagType' in filter) {25075 rval[filter.bagType] = _getBagsByAttribute(25076 pfx.safeContents, null, null, filter.bagType);25077 }25078 if(localKeyId !== undefined) {25079 rval.localKeyId = _getBagsByAttribute(25080 pfx.safeContents, 'localKeyId',25081 localKeyId, filter.bagType);25082 }25083 if('friendlyName' in filter) {25084 rval.friendlyName = _getBagsByAttribute(25085 pfx.safeContents, 'friendlyName',25086 filter.friendlyName, filter.bagType);25087 }25088 return rval;25089 },25090 /**25091 * DEPRECATED: use getBags() instead.25092 *25093 * Get bags with matching friendlyName attribute.25094 *25095 * @param friendlyName the friendly name to search for.25096 * @param [bagType] bag type to narrow search by.25097 *25098 * @return an array of bags with matching friendlyName attribute.25099 */25100 getBagsByFriendlyName: function(friendlyName, bagType) {25101 return _getBagsByAttribute(25102 pfx.safeContents, 'friendlyName', friendlyName, bagType);25103 },25104 /**25105 * DEPRECATED: use getBags() instead.25106 *25107 * Get bags with matching localKeyId attribute.25108 *25109 * @param localKeyId the localKeyId to search for.25110 * @param [bagType] bag type to narrow search by.25111 *25112 * @return an array of bags with matching localKeyId attribute.25113 */25114 getBagsByLocalKeyId: function(localKeyId, bagType) {25115 return _getBagsByAttribute(25116 pfx.safeContents, 'localKeyId', localKeyId, bagType);25117 }25118 };25119 if(capture.version.charCodeAt(0) !== 3) {25120 var error = new Error('PKCS#12 PFX of version other than 3 not supported.');25121 error.version = capture.version.charCodeAt(0);25122 throw error;25123 }25124 if(asn1.derToOid(capture.contentType) !== pki.oids.data) {25125 var error = new Error('Only PKCS#12 PFX in password integrity mode supported.');25126 error.oid = asn1.derToOid(capture.contentType);25127 throw error;25128 }25129 var data = capture.content.value[0];25130 if(data.tagClass !== asn1.Class.UNIVERSAL ||25131 data.type !== asn1.Type.OCTETSTRING) {25132 throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.');25133 }25134 data = _decodePkcs7Data(data);25135 // check for MAC25136 if(capture.mac) {25137 var md = null;25138 var macKeyBytes = 0;25139 var macAlgorithm = asn1.derToOid(capture.macAlgorithm);25140 switch(macAlgorithm) {25141 case pki.oids.sha1:25142 md = forge.md.sha1.create();25143 macKeyBytes = 20;25144 break;25145 case pki.oids.sha256:25146 md = forge.md.sha256.create();25147 macKeyBytes = 32;25148 break;25149 case pki.oids.sha384:25150 md = forge.md.sha384.create();25151 macKeyBytes = 48;25152 break;25153 case pki.oids.sha512:25154 md = forge.md.sha512.create();25155 macKeyBytes = 64;25156 break;25157 case pki.oids.md5:25158 md = forge.md.md5.create();25159 macKeyBytes = 16;25160 break;25161 }25162 if(md === null) {25163 throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm);25164 }25165 // verify MAC (iterations default to 1)25166 var macSalt = new forge.util.ByteBuffer(capture.macSalt);25167 var macIterations = (('macIterations' in capture) ?25168 parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1);25169 var macKey = p12.generateKey(25170 password, macSalt, 3, macIterations, macKeyBytes, md);25171 var mac = forge.hmac.create();25172 mac.start(md, macKey);25173 mac.update(data.value);25174 var macValue = mac.getMac();25175 if(macValue.getBytes() !== capture.macDigest) {25176 throw new Error('PKCS#12 MAC could not be verified. Invalid password?');25177 }25178 }25179 _decodeAuthenticatedSafe(pfx, data.value, strict, password);25180 return pfx;25181};25182/**25183 * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING,25184 * but it is sometimes an OCTET STRING that is composed/constructed of chunks,25185 * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This25186 * function transforms this corner-case into the usual simple,25187 * non-composed/constructed OCTET STRING.25188 *25189 * This function may be moved to ASN.1 at some point to better deal with25190 * more BER-encoding issues, should they arise.25191 *25192 * @param data the ASN.1 Data object to transform.25193 */25194function _decodePkcs7Data(data) {25195 // handle special case of "chunked" data content: an octet string composed25196 // of other octet strings25197 if(data.composed || data.constructed) {25198 var value = forge.util.createBuffer();25199 for(var i = 0; i < data.value.length; ++i) {25200 value.putBytes(data.value[i].value);25201 }25202 data.composed = data.constructed = false;25203 data.value = value.getBytes();25204 }25205 return data;25206}25207/**25208 * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object.25209 *25210 * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo.25211 *25212 * @param pfx The PKCS#12 PFX object to fill.25213 * @param {String} authSafe BER-encoded AuthenticatedSafe.25214 * @param strict true to use strict DER decoding, false not to.25215 * @param {String} password Password to decrypt with (optional).25216 */25217function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {25218 authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */25219 if(authSafe.tagClass !== asn1.Class.UNIVERSAL ||25220 authSafe.type !== asn1.Type.SEQUENCE ||25221 authSafe.constructed !== true) {25222 throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' +25223 'SEQUENCE OF ContentInfo');25224 }25225 for(var i = 0; i < authSafe.value.length; i++) {25226 var contentInfo = authSafe.value[i];25227 // validate contentInfo and capture data25228 var capture = {};25229 var errors = [];25230 if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) {25231 var error = new Error('Cannot read ContentInfo.');25232 error.errors = errors;25233 throw error;25234 }25235 var obj = {25236 encrypted: false25237 };25238 var safeContents = null;25239 var data = capture.content.value[0];25240 switch(asn1.derToOid(capture.contentType)) {25241 case pki.oids.data:25242 if(data.tagClass !== asn1.Class.UNIVERSAL ||25243 data.type !== asn1.Type.OCTETSTRING) {25244 throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.');25245 }25246 safeContents = _decodePkcs7Data(data).value;25247 break;25248 case pki.oids.encryptedData:25249 safeContents = _decryptSafeContents(data, password);25250 obj.encrypted = true;25251 break;25252 default:25253 var error = new Error('Unsupported PKCS#12 contentType.');25254 error.contentType = asn1.derToOid(capture.contentType);25255 throw error;25256 }25257 obj.safeBags = _decodeSafeContents(safeContents, strict, password);25258 pfx.safeContents.push(obj);25259 }25260}25261/**25262 * Decrypt PKCS#7 EncryptedData structure.25263 *25264 * @param data ASN.1 encoded EncryptedContentInfo object.25265 * @param password The user-provided password.25266 *25267 * @return The decrypted SafeContents (ASN.1 object).25268 */25269function _decryptSafeContents(data, password) {25270 var capture = {};25271 var errors = [];25272 if(!asn1.validate(25273 data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) {25274 var error = new Error('Cannot read EncryptedContentInfo.');25275 error.errors = errors;25276 throw error;25277 }25278 var oid = asn1.derToOid(capture.contentType);25279 if(oid !== pki.oids.data) {25280 var error = new Error(25281 'PKCS#12 EncryptedContentInfo ContentType is not Data.');25282 error.oid = oid;25283 throw error;25284 }25285 // get cipher25286 oid = asn1.derToOid(capture.encAlgorithm);25287 var cipher = pki.pbe.getCipher(oid, capture.encParameter, password);25288 // get encrypted data25289 var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);25290 var encrypted = forge.util.createBuffer(encryptedContentAsn1.value);25291 cipher.update(encrypted);25292 if(!cipher.finish()) {25293 throw new Error('Failed to decrypt PKCS#12 SafeContents.');25294 }25295 return cipher.output.getBytes();25296}25297/**25298 * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects.25299 *25300 * The safeContents is a BER-encoded SEQUENCE OF SafeBag.25301 *25302 * @param {String} safeContents BER-encoded safeContents.25303 * @param strict true to use strict DER decoding, false not to.25304 * @param {String} password Password to decrypt with (optional).25305 *25306 * @return {Array} Array of Bag objects.25307 */25308function _decodeSafeContents(safeContents, strict, password) {25309 // if strict and no safe contents, return empty safes25310 if(!strict && safeContents.length === 0) {25311 return [];25312 }25313 // actually it's BER-encoded25314 safeContents = asn1.fromDer(safeContents, strict);25315 if(safeContents.tagClass !== asn1.Class.UNIVERSAL ||25316 safeContents.type !== asn1.Type.SEQUENCE ||25317 safeContents.constructed !== true) {25318 throw new Error(25319 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.');25320 }25321 var res = [];25322 for(var i = 0; i < safeContents.value.length; i++) {25323 var safeBag = safeContents.value[i];25324 // validate SafeBag and capture data25325 var capture = {};25326 var errors = [];25327 if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) {25328 var error = new Error('Cannot read SafeBag.');25329 error.errors = errors;25330 throw error;25331 }25332 /* Create bag object and push to result array. */25333 var bag = {25334 type: asn1.derToOid(capture.bagId),25335 attributes: _decodeBagAttributes(capture.bagAttributes)25336 };25337 res.push(bag);25338 var validator, decoder;25339 var bagAsn1 = capture.bagValue.value[0];25340 switch(bag.type) {25341 case pki.oids.pkcs8ShroudedKeyBag:25342 /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt.25343 Afterwards we can handle it like a keyBag,25344 which is a PrivateKeyInfo. */25345 bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password);25346 if(bagAsn1 === null) {25347 throw new Error(25348 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?');25349 }25350 /* fall through */25351 case pki.oids.keyBag:25352 /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our25353 PKI module, hence we don't have to do validation/capturing here,25354 just pass what we already got. */25355 try {25356 bag.key = pki.privateKeyFromAsn1(bagAsn1);25357 } catch(e) {25358 // ignore unknown key type, pass asn1 value25359 bag.key = null;25360 bag.asn1 = bagAsn1;25361 }25362 continue; /* Nothing more to do. */25363 case pki.oids.certBag:25364 /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates.25365 Therefore put the SafeBag content through another validator to25366 capture the fields. Afterwards check & store the results. */25367 validator = certBagValidator;25368 decoder = function() {25369 if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) {25370 var error = new Error(25371 'Unsupported certificate type, only X.509 supported.');25372 error.oid = asn1.derToOid(capture.certId);25373 throw error;25374 }25375 // true=produce cert hash25376 var certAsn1 = asn1.fromDer(capture.cert, strict);25377 try {25378 bag.cert = pki.certificateFromAsn1(certAsn1, true);25379 } catch(e) {25380 // ignore unknown cert type, pass asn1 value25381 bag.cert = null;25382 bag.asn1 = certAsn1;25383 }25384 };25385 break;25386 default:25387 var error = new Error('Unsupported PKCS#12 SafeBag type.');25388 error.oid = bag.type;25389 throw error;25390 }25391 /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */25392 if(validator !== undefined &&25393 !asn1.validate(bagAsn1, validator, capture, errors)) {25394 var error = new Error('Cannot read PKCS#12 ' + validator.name);25395 error.errors = errors;25396 throw error;25397 }25398 /* Call decoder function from above to store the results. */25399 decoder();25400 }25401 return res;25402}25403/**25404 * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object.25405 *25406 * @param attributes SET OF PKCS12Attribute (ASN.1 object).25407 *25408 * @return the decoded attributes.25409 */25410function _decodeBagAttributes(attributes) {25411 var decodedAttrs = {};25412 if(attributes !== undefined) {25413 for(var i = 0; i < attributes.length; ++i) {25414 var capture = {};25415 var errors = [];25416 if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) {25417 var error = new Error('Cannot read PKCS#12 BagAttribute.');25418 error.errors = errors;25419 throw error;25420 }25421 var oid = asn1.derToOid(capture.oid);25422 if(pki.oids[oid] === undefined) {25423 // unsupported attribute type, ignore.25424 continue;25425 }25426 decodedAttrs[pki.oids[oid]] = [];25427 for(var j = 0; j < capture.values.length; ++j) {25428 decodedAttrs[pki.oids[oid]].push(capture.values[j].value);25429 }25430 }25431 }25432 return decodedAttrs;25433}25434/**25435 * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a25436 * password is provided then the private key will be encrypted.25437 *25438 * An entire certificate chain may also be included. To do this, pass25439 * an array for the "cert" parameter where the first certificate is25440 * the one that is paired with the private key and each subsequent one25441 * verifies the previous one. The certificates may be in PEM format or25442 * have been already parsed by Forge.25443 *25444 * @todo implement password-based-encryption for the whole package25445 *25446 * @param key the private key.25447 * @param cert the certificate (may be an array of certificates in order25448 * to specify a certificate chain).25449 * @param password the password to use, null for none.25450 * @param options:25451 * algorithm the encryption algorithm to use25452 * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.25453 * count the iteration count to use.25454 * saltSize the salt size to use.25455 * useMac true to include a MAC, false not to, defaults to true.25456 * localKeyId the local key ID to use, in hex.25457 * friendlyName the friendly name to use.25458 * generateLocalKeyId true to generate a random local key ID,25459 * false not to, defaults to true.25460 *25461 * @return the PKCS#12 PFX ASN.1 object.25462 */25463p12.toPkcs12Asn1 = function(key, cert, password, options) {25464 // set default options25465 options = options || {};25466 options.saltSize = options.saltSize || 8;25467 options.count = options.count || 2048;25468 options.algorithm = options.algorithm || options.encAlgorithm || 'aes128';25469 if(!('useMac' in options)) {25470 options.useMac = true;25471 }25472 if(!('localKeyId' in options)) {25473 options.localKeyId = null;25474 }25475 if(!('generateLocalKeyId' in options)) {25476 options.generateLocalKeyId = true;25477 }25478 var localKeyId = options.localKeyId;25479 var bagAttrs;25480 if(localKeyId !== null) {25481 localKeyId = forge.util.hexToBytes(localKeyId);25482 } else if(options.generateLocalKeyId) {25483 // use SHA-1 of paired cert, if available25484 if(cert) {25485 var pairedCert = forge.util.isArray(cert) ? cert[0] : cert;25486 if(typeof pairedCert === 'string') {25487 pairedCert = pki.certificateFromPem(pairedCert);25488 }25489 var sha1 = forge.md.sha1.create();25490 sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());25491 localKeyId = sha1.digest().getBytes();25492 } else {25493 // FIXME: consider using SHA-1 of public key (which can be generated25494 // from private key components), see: cert.generateSubjectKeyIdentifier25495 // generate random bytes25496 localKeyId = forge.random.getBytes(20);25497 }25498 }25499 var attrs = [];25500 if(localKeyId !== null) {25501 attrs.push(25502 // localKeyID25503 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25504 // attrId25505 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25506 asn1.oidToDer(pki.oids.localKeyId).getBytes()),25507 // attrValues25508 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [25509 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,25510 localKeyId)25511 ])25512 ]));25513 }25514 if('friendlyName' in options) {25515 attrs.push(25516 // friendlyName25517 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25518 // attrId25519 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25520 asn1.oidToDer(pki.oids.friendlyName).getBytes()),25521 // attrValues25522 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [25523 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false,25524 options.friendlyName)25525 ])25526 ]));25527 }25528 if(attrs.length > 0) {25529 bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs);25530 }25531 // collect contents for AuthenticatedSafe25532 var contents = [];25533 // create safe bag(s) for certificate chain25534 var chain = [];25535 if(cert !== null) {25536 if(forge.util.isArray(cert)) {25537 chain = cert;25538 } else {25539 chain = [cert];25540 }25541 }25542 var certSafeBags = [];25543 for(var i = 0; i < chain.length; ++i) {25544 // convert cert from PEM as necessary25545 cert = chain[i];25546 if(typeof cert === 'string') {25547 cert = pki.certificateFromPem(cert);25548 }25549 // SafeBag25550 var certBagAttrs = (i === 0) ? bagAttrs : undefined;25551 var certAsn1 = pki.certificateToAsn1(cert);25552 var certSafeBag =25553 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25554 // bagId25555 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25556 asn1.oidToDer(pki.oids.certBag).getBytes()),25557 // bagValue25558 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [25559 // CertBag25560 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25561 // certId25562 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25563 asn1.oidToDer(pki.oids.x509Certificate).getBytes()),25564 // certValue (x509Certificate)25565 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [25566 asn1.create(25567 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,25568 asn1.toDer(certAsn1).getBytes())25569 ])])]),25570 // bagAttributes (OPTIONAL)25571 certBagAttrs25572 ]);25573 certSafeBags.push(certSafeBag);25574 }25575 if(certSafeBags.length > 0) {25576 // SafeContents25577 var certSafeContents = asn1.create(25578 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags);25579 // ContentInfo25580 var certCI =25581 // PKCS#7 ContentInfo25582 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25583 // contentType25584 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25585 // OID for the content type is 'data'25586 asn1.oidToDer(pki.oids.data).getBytes()),25587 // content25588 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [25589 asn1.create(25590 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,25591 asn1.toDer(certSafeContents).getBytes())25592 ])25593 ]);25594 contents.push(certCI);25595 }25596 // create safe contents for private key25597 var keyBag = null;25598 if(key !== null) {25599 // SafeBag25600 var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));25601 if(password === null) {25602 // no encryption25603 keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25604 // bagId25605 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25606 asn1.oidToDer(pki.oids.keyBag).getBytes()),25607 // bagValue25608 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [25609 // PrivateKeyInfo25610 pkAsn125611 ]),25612 // bagAttributes (OPTIONAL)25613 bagAttrs25614 ]);25615 } else {25616 // encrypted PrivateKeyInfo25617 keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25618 // bagId25619 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25620 asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),25621 // bagValue25622 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [25623 // EncryptedPrivateKeyInfo25624 pki.encryptPrivateKeyInfo(pkAsn1, password, options)25625 ]),25626 // bagAttributes (OPTIONAL)25627 bagAttrs25628 ]);25629 }25630 // SafeContents25631 var keySafeContents =25632 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]);25633 // ContentInfo25634 var keyCI =25635 // PKCS#7 ContentInfo25636 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25637 // contentType25638 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25639 // OID for the content type is 'data'25640 asn1.oidToDer(pki.oids.data).getBytes()),25641 // content25642 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [25643 asn1.create(25644 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,25645 asn1.toDer(keySafeContents).getBytes())25646 ])25647 ]);25648 contents.push(keyCI);25649 }25650 // create AuthenticatedSafe by stringing together the contents25651 var safe = asn1.create(25652 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents);25653 var macData;25654 if(options.useMac) {25655 // MacData25656 var sha1 = forge.md.sha1.create();25657 var macSalt = new forge.util.ByteBuffer(25658 forge.random.getBytes(options.saltSize));25659 var count = options.count;25660 // 160-bit key25661 var key = p12.generateKey(password, macSalt, 3, count, 20);25662 var mac = forge.hmac.create();25663 mac.start(sha1, key);25664 mac.update(asn1.toDer(safe).getBytes());25665 var macValue = mac.getMac();25666 macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25667 // mac DigestInfo25668 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25669 // digestAlgorithm25670 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25671 // algorithm = SHA-125672 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25673 asn1.oidToDer(pki.oids.sha1).getBytes()),25674 // parameters = Null25675 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')25676 ]),25677 // digest25678 asn1.create(25679 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,25680 false, macValue.getBytes())25681 ]),25682 // macSalt OCTET STRING25683 asn1.create(25684 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()),25685 // iterations INTEGER (XXX: Only support count < 65536)25686 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,25687 asn1.integerToDer(count).getBytes()25688 )25689 ]);25690 }25691 // PFX25692 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25693 // version (3)25694 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,25695 asn1.integerToDer(3).getBytes()),25696 // PKCS#7 ContentInfo25697 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25698 // contentType25699 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25700 // OID for the content type is 'data'25701 asn1.oidToDer(pki.oids.data).getBytes()),25702 // content25703 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [25704 asn1.create(25705 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,25706 asn1.toDer(safe).getBytes())25707 ])25708 ]),25709 macData25710 ]);25711};25712/**25713 * Derives a PKCS#12 key.25714 *25715 * @param password the password to derive the key material from, null or25716 * undefined for none.25717 * @param salt the salt, as a ByteBuffer, to use.25718 * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).25719 * @param iter the iteration count.25720 * @param n the number of bytes to derive from the password.25721 * @param md the message digest to use, defaults to SHA-1.25722 *25723 * @return a ByteBuffer with the bytes derived from the password.25724 */25725p12.generateKey = forge.pbe.generatePkcs12Key;25726/***/ }),25727/***/ 4829:25728/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {25729/**25730 * Javascript implementation of PKCS#7 v1.5.25731 *25732 * @author Stefan Siegl25733 * @author Dave Longley25734 *25735 * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>25736 * Copyright (c) 2012-2015 Digital Bazaar, Inc.25737 *25738 * Currently this implementation only supports ContentType of EnvelopedData,25739 * EncryptedData, or SignedData at the root level. The top level elements may25740 * contain only a ContentInfo of ContentType Data, i.e. plain data. Further25741 * nesting is not (yet) supported.25742 *25743 * The Forge validators for PKCS #7's ASN.1 structures are available from25744 * a separate file pkcs7asn1.js, since those are referenced from other25745 * PKCS standards like PKCS #12.25746 */25747var forge = __nccwpck_require__(9177);25748__nccwpck_require__(7994);25749__nccwpck_require__(9549);25750__nccwpck_require__(7157);25751__nccwpck_require__(1925);25752__nccwpck_require__(154);25753__nccwpck_require__(266);25754__nccwpck_require__(7821);25755__nccwpck_require__(8339);25756__nccwpck_require__(8180);25757// shortcut for ASN.1 API25758var asn1 = forge.asn1;25759// shortcut for PKCS#7 API25760var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};25761/**25762 * Converts a PKCS#7 message from PEM format.25763 *25764 * @param pem the PEM-formatted PKCS#7 message.25765 *25766 * @return the PKCS#7 message.25767 */25768p7.messageFromPem = function(pem) {25769 var msg = forge.pem.decode(pem)[0];25770 if(msg.type !== 'PKCS7') {25771 var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +25772 'header type is not "PKCS#7".');25773 error.headerType = msg.type;25774 throw error;25775 }25776 if(msg.procType && msg.procType.type === 'ENCRYPTED') {25777 throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');25778 }25779 // convert DER to ASN.1 object25780 var obj = asn1.fromDer(msg.body);25781 return p7.messageFromAsn1(obj);25782};25783/**25784 * Converts a PKCS#7 message to PEM format.25785 *25786 * @param msg The PKCS#7 message object25787 * @param maxline The maximum characters per line, defaults to 64.25788 *25789 * @return The PEM-formatted PKCS#7 message.25790 */25791p7.messageToPem = function(msg, maxline) {25792 // convert to ASN.1, then DER, then PEM-encode25793 var pemObj = {25794 type: 'PKCS7',25795 body: asn1.toDer(msg.toAsn1()).getBytes()25796 };25797 return forge.pem.encode(pemObj, {maxline: maxline});25798};25799/**25800 * Converts a PKCS#7 message from an ASN.1 object.25801 *25802 * @param obj the ASN.1 representation of a ContentInfo.25803 *25804 * @return the PKCS#7 message.25805 */25806p7.messageFromAsn1 = function(obj) {25807 // validate root level ContentInfo and capture data25808 var capture = {};25809 var errors = [];25810 if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {25811 var error = new Error('Cannot read PKCS#7 message. ' +25812 'ASN.1 object is not an PKCS#7 ContentInfo.');25813 error.errors = errors;25814 throw error;25815 }25816 var contentType = asn1.derToOid(capture.contentType);25817 var msg;25818 switch(contentType) {25819 case forge.pki.oids.envelopedData:25820 msg = p7.createEnvelopedData();25821 break;25822 case forge.pki.oids.encryptedData:25823 msg = p7.createEncryptedData();25824 break;25825 case forge.pki.oids.signedData:25826 msg = p7.createSignedData();25827 break;25828 default:25829 throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +25830 contentType + ' is not (yet) supported.');25831 }25832 msg.fromAsn1(capture.content.value[0]);25833 return msg;25834};25835p7.createSignedData = function() {25836 var msg = null;25837 msg = {25838 type: forge.pki.oids.signedData,25839 version: 1,25840 certificates: [],25841 crls: [],25842 // TODO: add json-formatted signer stuff here?25843 signers: [],25844 // populated during sign()25845 digestAlgorithmIdentifiers: [],25846 contentInfo: null,25847 signerInfos: [],25848 fromAsn1: function(obj) {25849 // validate SignedData content block and capture data.25850 _fromAsn1(msg, obj, p7.asn1.signedDataValidator);25851 msg.certificates = [];25852 msg.crls = [];25853 msg.digestAlgorithmIdentifiers = [];25854 msg.contentInfo = null;25855 msg.signerInfos = [];25856 if(msg.rawCapture.certificates) {25857 var certs = msg.rawCapture.certificates.value;25858 for(var i = 0; i < certs.length; ++i) {25859 msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));25860 }25861 }25862 // TODO: parse crls25863 },25864 toAsn1: function() {25865 // degenerate case with no content25866 if(!msg.contentInfo) {25867 msg.sign();25868 }25869 var certs = [];25870 for(var i = 0; i < msg.certificates.length; ++i) {25871 certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));25872 }25873 var crls = [];25874 // TODO: implement CRLs25875 // [0] SignedData25876 var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [25877 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25878 // Version25879 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,25880 asn1.integerToDer(msg.version).getBytes()),25881 // DigestAlgorithmIdentifiers25882 asn1.create(25883 asn1.Class.UNIVERSAL, asn1.Type.SET, true,25884 msg.digestAlgorithmIdentifiers),25885 // ContentInfo25886 msg.contentInfo25887 ])25888 ]);25889 if(certs.length > 0) {25890 // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL25891 signedData.value[0].value.push(25892 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));25893 }25894 if(crls.length > 0) {25895 // [1] IMPLICIT CertificateRevocationLists OPTIONAL25896 signedData.value[0].value.push(25897 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));25898 }25899 // SignerInfos25900 signedData.value[0].value.push(25901 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,25902 msg.signerInfos));25903 // ContentInfo25904 return asn1.create(25905 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [25906 // ContentType25907 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,25908 asn1.oidToDer(msg.type).getBytes()),25909 // [0] SignedData25910 signedData25911 ]);25912 },25913 /**25914 * Add (another) entity to list of signers.25915 *25916 * Note: If authenticatedAttributes are provided, then, per RFC 2315,25917 * they must include at least two attributes: content type and25918 * message digest. The message digest attribute value will be25919 * auto-calculated during signing and will be ignored if provided.25920 *25921 * Here's an example of providing these two attributes:25922 *25923 * forge.pkcs7.createSignedData();25924 * p7.addSigner({25925 * issuer: cert.issuer.attributes,25926 * serialNumber: cert.serialNumber,25927 * key: privateKey,25928 * digestAlgorithm: forge.pki.oids.sha1,25929 * authenticatedAttributes: [{25930 * type: forge.pki.oids.contentType,25931 * value: forge.pki.oids.data25932 * }, {25933 * type: forge.pki.oids.messageDigest25934 * }]25935 * });25936 *25937 * TODO: Support [subjectKeyIdentifier] as signer's ID.25938 *25939 * @param signer the signer information:25940 * key the signer's private key.25941 * [certificate] a certificate containing the public key25942 * associated with the signer's private key; use this option as25943 * an alternative to specifying signer.issuer and25944 * signer.serialNumber.25945 * [issuer] the issuer attributes (eg: cert.issuer.attributes).25946 * [serialNumber] the signer's certificate's serial number in25947 * hexadecimal (eg: cert.serialNumber).25948 * [digestAlgorithm] the message digest OID, as a string, to use25949 * (eg: forge.pki.oids.sha1).25950 * [authenticatedAttributes] an optional array of attributes25951 * to also sign along with the content.25952 */25953 addSigner: function(signer) {25954 var issuer = signer.issuer;25955 var serialNumber = signer.serialNumber;25956 if(signer.certificate) {25957 var cert = signer.certificate;25958 if(typeof cert === 'string') {25959 cert = forge.pki.certificateFromPem(cert);25960 }25961 issuer = cert.issuer.attributes;25962 serialNumber = cert.serialNumber;25963 }25964 var key = signer.key;25965 if(!key) {25966 throw new Error(25967 'Could not add PKCS#7 signer; no private key specified.');25968 }25969 if(typeof key === 'string') {25970 key = forge.pki.privateKeyFromPem(key);25971 }25972 // ensure OID known for digest algorithm25973 var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;25974 switch(digestAlgorithm) {25975 case forge.pki.oids.sha1:25976 case forge.pki.oids.sha256:25977 case forge.pki.oids.sha384:25978 case forge.pki.oids.sha512:25979 case forge.pki.oids.md5:25980 break;25981 default:25982 throw new Error(25983 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +25984 digestAlgorithm);25985 }25986 // if authenticatedAttributes is present, then the attributes25987 // must contain at least PKCS #9 content-type and message-digest25988 var authenticatedAttributes = signer.authenticatedAttributes || [];25989 if(authenticatedAttributes.length > 0) {25990 var contentType = false;25991 var messageDigest = false;25992 for(var i = 0; i < authenticatedAttributes.length; ++i) {25993 var attr = authenticatedAttributes[i];25994 if(!contentType && attr.type === forge.pki.oids.contentType) {25995 contentType = true;25996 if(messageDigest) {25997 break;25998 }25999 continue;26000 }26001 if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {26002 messageDigest = true;26003 if(contentType) {26004 break;26005 }26006 continue;26007 }26008 }26009 if(!contentType || !messageDigest) {26010 throw new Error('Invalid signer.authenticatedAttributes. If ' +26011 'signer.authenticatedAttributes is specified, then it must ' +26012 'contain at least two attributes, PKCS #9 content-type and ' +26013 'PKCS #9 message-digest.');26014 }26015 }26016 msg.signers.push({26017 key: key,26018 version: 1,26019 issuer: issuer,26020 serialNumber: serialNumber,26021 digestAlgorithm: digestAlgorithm,26022 signatureAlgorithm: forge.pki.oids.rsaEncryption,26023 signature: null,26024 authenticatedAttributes: authenticatedAttributes,26025 unauthenticatedAttributes: []26026 });26027 },26028 /**26029 * Signs the content.26030 * @param options Options to apply when signing:26031 * [detached] boolean. If signing should be done in detached mode. Defaults to false.26032 */26033 sign: function(options) {26034 options = options || {};26035 // auto-generate content info26036 if(typeof msg.content !== 'object' || msg.contentInfo === null) {26037 // use Data ContentInfo26038 msg.contentInfo = asn1.create(26039 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26040 // ContentType26041 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26042 asn1.oidToDer(forge.pki.oids.data).getBytes())26043 ]);26044 // add actual content, if present26045 if('content' in msg) {26046 var content;26047 if(msg.content instanceof forge.util.ByteBuffer) {26048 content = msg.content.bytes();26049 } else if(typeof msg.content === 'string') {26050 content = forge.util.encodeUtf8(msg.content);26051 }26052 if (options.detached) {26053 msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);26054 } else {26055 msg.contentInfo.value.push(26056 // [0] EXPLICIT content26057 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [26058 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,26059 content)26060 ]));26061 }26062 }26063 }26064 // no signers, return early (degenerate case for certificate container)26065 if(msg.signers.length === 0) {26066 return;26067 }26068 // generate digest algorithm identifiers26069 var mds = addDigestAlgorithmIds();26070 // generate signerInfos26071 addSignerInfos(mds);26072 },26073 verify: function() {26074 throw new Error('PKCS#7 signature verification not yet implemented.');26075 },26076 /**26077 * Add a certificate.26078 *26079 * @param cert the certificate to add.26080 */26081 addCertificate: function(cert) {26082 // convert from PEM26083 if(typeof cert === 'string') {26084 cert = forge.pki.certificateFromPem(cert);26085 }26086 msg.certificates.push(cert);26087 },26088 /**26089 * Add a certificate revokation list.26090 *26091 * @param crl the certificate revokation list to add.26092 */26093 addCertificateRevokationList: function(crl) {26094 throw new Error('PKCS#7 CRL support not yet implemented.');26095 }26096 };26097 return msg;26098 function addDigestAlgorithmIds() {26099 var mds = {};26100 for(var i = 0; i < msg.signers.length; ++i) {26101 var signer = msg.signers[i];26102 var oid = signer.digestAlgorithm;26103 if(!(oid in mds)) {26104 // content digest26105 mds[oid] = forge.md[forge.pki.oids[oid]].create();26106 }26107 if(signer.authenticatedAttributes.length === 0) {26108 // no custom attributes to digest; use content message digest26109 signer.md = mds[oid];26110 } else {26111 // custom attributes to be digested; use own message digest26112 // TODO: optimize to just copy message digest state if that26113 // feature is ever supported with message digests26114 signer.md = forge.md[forge.pki.oids[oid]].create();26115 }26116 }26117 // add unique digest algorithm identifiers26118 msg.digestAlgorithmIdentifiers = [];26119 for(var oid in mds) {26120 msg.digestAlgorithmIdentifiers.push(26121 // AlgorithmIdentifier26122 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26123 // algorithm26124 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26125 asn1.oidToDer(oid).getBytes()),26126 // parameters (null)26127 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')26128 ]));26129 }26130 return mds;26131 }26132 function addSignerInfos(mds) {26133 var content;26134 if (msg.detachedContent) {26135 // Signature has been made in detached mode.26136 content = msg.detachedContent;26137 } else {26138 // Note: ContentInfo is a SEQUENCE with 2 values, second value is26139 // the content field and is optional for a ContentInfo but required here26140 // since signers are present26141 // get ContentInfo content26142 content = msg.contentInfo.value[1];26143 // skip [0] EXPLICIT content wrapper26144 content = content.value[0];26145 }26146 if(!content) {26147 throw new Error(26148 'Could not sign PKCS#7 message; there is no content to sign.');26149 }26150 // get ContentInfo content type26151 var contentType = asn1.derToOid(msg.contentInfo.value[0].value);26152 // serialize content26153 var bytes = asn1.toDer(content);26154 // skip identifier and length per RFC 2315 9.326155 // skip identifier (1 byte)26156 bytes.getByte();26157 // read and discard length bytes26158 asn1.getBerValueLength(bytes);26159 bytes = bytes.getBytes();26160 // digest content DER value bytes26161 for(var oid in mds) {26162 mds[oid].start().update(bytes);26163 }26164 // sign content26165 var signingTime = new Date();26166 for(var i = 0; i < msg.signers.length; ++i) {26167 var signer = msg.signers[i];26168 if(signer.authenticatedAttributes.length === 0) {26169 // if ContentInfo content type is not "Data", then26170 // authenticatedAttributes must be present per RFC 231526171 if(contentType !== forge.pki.oids.data) {26172 throw new Error(26173 'Invalid signer; authenticatedAttributes must be present ' +26174 'when the ContentInfo content type is not PKCS#7 Data.');26175 }26176 } else {26177 // process authenticated attributes26178 // [0] IMPLICIT26179 signer.authenticatedAttributesAsn1 = asn1.create(26180 asn1.Class.CONTEXT_SPECIFIC, 0, true, []);26181 // per RFC 2315, attributes are to be digested using a SET container26182 // not the above [0] IMPLICIT container26183 var attrsAsn1 = asn1.create(26184 asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);26185 for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {26186 var attr = signer.authenticatedAttributes[ai];26187 if(attr.type === forge.pki.oids.messageDigest) {26188 // use content message digest as value26189 attr.value = mds[signer.digestAlgorithm].digest();26190 } else if(attr.type === forge.pki.oids.signingTime) {26191 // auto-populate signing time if not already set26192 if(!attr.value) {26193 attr.value = signingTime;26194 }26195 }26196 // convert to ASN.1 and push onto Attributes SET (for signing) and26197 // onto authenticatedAttributesAsn1 to complete SignedData ASN.126198 // TODO: optimize away duplication26199 attrsAsn1.value.push(_attributeToAsn1(attr));26200 signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));26201 }26202 // DER-serialize and digest SET OF attributes only26203 bytes = asn1.toDer(attrsAsn1).getBytes();26204 signer.md.start().update(bytes);26205 }26206 // sign digest26207 signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');26208 }26209 // add signer info26210 msg.signerInfos = _signersToAsn1(msg.signers);26211 }26212};26213/**26214 * Creates an empty PKCS#7 message of type EncryptedData.26215 *26216 * @return the message.26217 */26218p7.createEncryptedData = function() {26219 var msg = null;26220 msg = {26221 type: forge.pki.oids.encryptedData,26222 version: 0,26223 encryptedContent: {26224 algorithm: forge.pki.oids['aes256-CBC']26225 },26226 /**26227 * Reads an EncryptedData content block (in ASN.1 format)26228 *26229 * @param obj The ASN.1 representation of the EncryptedData content block26230 */26231 fromAsn1: function(obj) {26232 // Validate EncryptedData content block and capture data.26233 _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);26234 },26235 /**26236 * Decrypt encrypted content26237 *26238 * @param key The (symmetric) key as a byte buffer26239 */26240 decrypt: function(key) {26241 if(key !== undefined) {26242 msg.encryptedContent.key = key;26243 }26244 _decryptContent(msg);26245 }26246 };26247 return msg;26248};26249/**26250 * Creates an empty PKCS#7 message of type EnvelopedData.26251 *26252 * @return the message.26253 */26254p7.createEnvelopedData = function() {26255 var msg = null;26256 msg = {26257 type: forge.pki.oids.envelopedData,26258 version: 0,26259 recipients: [],26260 encryptedContent: {26261 algorithm: forge.pki.oids['aes256-CBC']26262 },26263 /**26264 * Reads an EnvelopedData content block (in ASN.1 format)26265 *26266 * @param obj the ASN.1 representation of the EnvelopedData content block.26267 */26268 fromAsn1: function(obj) {26269 // validate EnvelopedData content block and capture data26270 var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);26271 msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);26272 },26273 toAsn1: function() {26274 // ContentInfo26275 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26276 // ContentType26277 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26278 asn1.oidToDer(msg.type).getBytes()),26279 // [0] EnvelopedData26280 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [26281 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26282 // Version26283 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,26284 asn1.integerToDer(msg.version).getBytes()),26285 // RecipientInfos26286 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,26287 _recipientsToAsn1(msg.recipients)),26288 // EncryptedContentInfo26289 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,26290 _encryptedContentToAsn1(msg.encryptedContent))26291 ])26292 ])26293 ]);26294 },26295 /**26296 * Find recipient by X.509 certificate's issuer.26297 *26298 * @param cert the certificate with the issuer to look for.26299 *26300 * @return the recipient object.26301 */26302 findRecipient: function(cert) {26303 var sAttr = cert.issuer.attributes;26304 for(var i = 0; i < msg.recipients.length; ++i) {26305 var r = msg.recipients[i];26306 var rAttr = r.issuer;26307 if(r.serialNumber !== cert.serialNumber) {26308 continue;26309 }26310 if(rAttr.length !== sAttr.length) {26311 continue;26312 }26313 var match = true;26314 for(var j = 0; j < sAttr.length; ++j) {26315 if(rAttr[j].type !== sAttr[j].type ||26316 rAttr[j].value !== sAttr[j].value) {26317 match = false;26318 break;26319 }26320 }26321 if(match) {26322 return r;26323 }26324 }26325 return null;26326 },26327 /**26328 * Decrypt enveloped content26329 *26330 * @param recipient The recipient object related to the private key26331 * @param privKey The (RSA) private key object26332 */26333 decrypt: function(recipient, privKey) {26334 if(msg.encryptedContent.key === undefined && recipient !== undefined &&26335 privKey !== undefined) {26336 switch(recipient.encryptedContent.algorithm) {26337 case forge.pki.oids.rsaEncryption:26338 case forge.pki.oids.desCBC:26339 var key = privKey.decrypt(recipient.encryptedContent.content);26340 msg.encryptedContent.key = forge.util.createBuffer(key);26341 break;26342 default:26343 throw new Error('Unsupported asymmetric cipher, ' +26344 'OID ' + recipient.encryptedContent.algorithm);26345 }26346 }26347 _decryptContent(msg);26348 },26349 /**26350 * Add (another) entity to list of recipients.26351 *26352 * @param cert The certificate of the entity to add.26353 */26354 addRecipient: function(cert) {26355 msg.recipients.push({26356 version: 0,26357 issuer: cert.issuer.attributes,26358 serialNumber: cert.serialNumber,26359 encryptedContent: {26360 // We simply assume rsaEncryption here, since forge.pki only26361 // supports RSA so far. If the PKI module supports other26362 // ciphers one day, we need to modify this one as well.26363 algorithm: forge.pki.oids.rsaEncryption,26364 key: cert.publicKey26365 }26366 });26367 },26368 /**26369 * Encrypt enveloped content.26370 *26371 * This function supports two optional arguments, cipher and key, which26372 * can be used to influence symmetric encryption. Unless cipher is26373 * provided, the cipher specified in encryptedContent.algorithm is used26374 * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key26375 * is (re-)used. If that one's not set, a random key will be generated26376 * automatically.26377 *26378 * @param [key] The key to be used for symmetric encryption.26379 * @param [cipher] The OID of the symmetric cipher to use.26380 */26381 encrypt: function(key, cipher) {26382 // Part 1: Symmetric encryption26383 if(msg.encryptedContent.content === undefined) {26384 cipher = cipher || msg.encryptedContent.algorithm;26385 key = key || msg.encryptedContent.key;26386 var keyLen, ivLen, ciphFn;26387 switch(cipher) {26388 case forge.pki.oids['aes128-CBC']:26389 keyLen = 16;26390 ivLen = 16;26391 ciphFn = forge.aes.createEncryptionCipher;26392 break;26393 case forge.pki.oids['aes192-CBC']:26394 keyLen = 24;26395 ivLen = 16;26396 ciphFn = forge.aes.createEncryptionCipher;26397 break;26398 case forge.pki.oids['aes256-CBC']:26399 keyLen = 32;26400 ivLen = 16;26401 ciphFn = forge.aes.createEncryptionCipher;26402 break;26403 case forge.pki.oids['des-EDE3-CBC']:26404 keyLen = 24;26405 ivLen = 8;26406 ciphFn = forge.des.createEncryptionCipher;26407 break;26408 default:26409 throw new Error('Unsupported symmetric cipher, OID ' + cipher);26410 }26411 if(key === undefined) {26412 key = forge.util.createBuffer(forge.random.getBytes(keyLen));26413 } else if(key.length() != keyLen) {26414 throw new Error('Symmetric key has wrong length; ' +26415 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');26416 }26417 // Keep a copy of the key & IV in the object, so the caller can26418 // use it for whatever reason.26419 msg.encryptedContent.algorithm = cipher;26420 msg.encryptedContent.key = key;26421 msg.encryptedContent.parameter = forge.util.createBuffer(26422 forge.random.getBytes(ivLen));26423 var ciph = ciphFn(key);26424 ciph.start(msg.encryptedContent.parameter.copy());26425 ciph.update(msg.content);26426 // The finish function does PKCS#7 padding by default, therefore26427 // no action required by us.26428 if(!ciph.finish()) {26429 throw new Error('Symmetric encryption failed.');26430 }26431 msg.encryptedContent.content = ciph.output;26432 }26433 // Part 2: asymmetric encryption for each recipient26434 for(var i = 0; i < msg.recipients.length; ++i) {26435 var recipient = msg.recipients[i];26436 // Nothing to do, encryption already done.26437 if(recipient.encryptedContent.content !== undefined) {26438 continue;26439 }26440 switch(recipient.encryptedContent.algorithm) {26441 case forge.pki.oids.rsaEncryption:26442 recipient.encryptedContent.content =26443 recipient.encryptedContent.key.encrypt(26444 msg.encryptedContent.key.data);26445 break;26446 default:26447 throw new Error('Unsupported asymmetric cipher, OID ' +26448 recipient.encryptedContent.algorithm);26449 }26450 }26451 }26452 };26453 return msg;26454};26455/**26456 * Converts a single recipient from an ASN.1 object.26457 *26458 * @param obj the ASN.1 RecipientInfo.26459 *26460 * @return the recipient object.26461 */26462function _recipientFromAsn1(obj) {26463 // validate EnvelopedData content block and capture data26464 var capture = {};26465 var errors = [];26466 if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {26467 var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +26468 'ASN.1 object is not an PKCS#7 RecipientInfo.');26469 error.errors = errors;26470 throw error;26471 }26472 return {26473 version: capture.version.charCodeAt(0),26474 issuer: forge.pki.RDNAttributesAsArray(capture.issuer),26475 serialNumber: forge.util.createBuffer(capture.serial).toHex(),26476 encryptedContent: {26477 algorithm: asn1.derToOid(capture.encAlgorithm),26478 parameter: capture.encParameter ? capture.encParameter.value : undefined,26479 content: capture.encKey26480 }26481 };26482}26483/**26484 * Converts a single recipient object to an ASN.1 object.26485 *26486 * @param obj the recipient object.26487 *26488 * @return the ASN.1 RecipientInfo.26489 */26490function _recipientToAsn1(obj) {26491 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26492 // Version26493 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,26494 asn1.integerToDer(obj.version).getBytes()),26495 // IssuerAndSerialNumber26496 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26497 // Name26498 forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),26499 // Serial26500 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,26501 forge.util.hexToBytes(obj.serialNumber))26502 ]),26503 // KeyEncryptionAlgorithmIdentifier26504 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26505 // Algorithm26506 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26507 asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),26508 // Parameter, force NULL, only RSA supported for now.26509 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')26510 ]),26511 // EncryptedKey26512 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,26513 obj.encryptedContent.content)26514 ]);26515}26516/**26517 * Map a set of RecipientInfo ASN.1 objects to recipient objects.26518 *26519 * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).26520 *26521 * @return an array of recipient objects.26522 */26523function _recipientsFromAsn1(infos) {26524 var ret = [];26525 for(var i = 0; i < infos.length; ++i) {26526 ret.push(_recipientFromAsn1(infos[i]));26527 }26528 return ret;26529}26530/**26531 * Map an array of recipient objects to ASN.1 RecipientInfo objects.26532 *26533 * @param recipients an array of recipientInfo objects.26534 *26535 * @return an array of ASN.1 RecipientInfos.26536 */26537function _recipientsToAsn1(recipients) {26538 var ret = [];26539 for(var i = 0; i < recipients.length; ++i) {26540 ret.push(_recipientToAsn1(recipients[i]));26541 }26542 return ret;26543}26544/**26545 * Converts a single signer from an ASN.1 object.26546 *26547 * @param obj the ASN.1 representation of a SignerInfo.26548 *26549 * @return the signer object.26550 */26551function _signerFromAsn1(obj) {26552 // validate EnvelopedData content block and capture data26553 var capture = {};26554 var errors = [];26555 if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {26556 var error = new Error('Cannot read PKCS#7 SignerInfo. ' +26557 'ASN.1 object is not an PKCS#7 SignerInfo.');26558 error.errors = errors;26559 throw error;26560 }26561 var rval = {26562 version: capture.version.charCodeAt(0),26563 issuer: forge.pki.RDNAttributesAsArray(capture.issuer),26564 serialNumber: forge.util.createBuffer(capture.serial).toHex(),26565 digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),26566 signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),26567 signature: capture.signature,26568 authenticatedAttributes: [],26569 unauthenticatedAttributes: []26570 };26571 // TODO: convert attributes26572 var authenticatedAttributes = capture.authenticatedAttributes || [];26573 var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];26574 return rval;26575}26576/**26577 * Converts a single signerInfo object to an ASN.1 object.26578 *26579 * @param obj the signerInfo object.26580 *26581 * @return the ASN.1 representation of a SignerInfo.26582 */26583function _signerToAsn1(obj) {26584 // SignerInfo26585 var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26586 // version26587 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,26588 asn1.integerToDer(obj.version).getBytes()),26589 // issuerAndSerialNumber26590 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26591 // name26592 forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),26593 // serial26594 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,26595 forge.util.hexToBytes(obj.serialNumber))26596 ]),26597 // digestAlgorithm26598 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26599 // algorithm26600 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26601 asn1.oidToDer(obj.digestAlgorithm).getBytes()),26602 // parameters (null)26603 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')26604 ])26605 ]);26606 // authenticatedAttributes (OPTIONAL)26607 if(obj.authenticatedAttributesAsn1) {26608 // add ASN.1 previously generated during signing26609 rval.value.push(obj.authenticatedAttributesAsn1);26610 }26611 // digestEncryptionAlgorithm26612 rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26613 // algorithm26614 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26615 asn1.oidToDer(obj.signatureAlgorithm).getBytes()),26616 // parameters (null)26617 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')26618 ]));26619 // encryptedDigest26620 rval.value.push(asn1.create(26621 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));26622 // unauthenticatedAttributes (OPTIONAL)26623 if(obj.unauthenticatedAttributes.length > 0) {26624 // [1] IMPLICIT26625 var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);26626 for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {26627 var attr = obj.unauthenticatedAttributes[i];26628 attrsAsn1.values.push(_attributeToAsn1(attr));26629 }26630 rval.value.push(attrsAsn1);26631 }26632 return rval;26633}26634/**26635 * Map a set of SignerInfo ASN.1 objects to an array of signer objects.26636 *26637 * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).26638 *26639 * @return an array of signers objects.26640 */26641function _signersFromAsn1(signerInfoAsn1s) {26642 var ret = [];26643 for(var i = 0; i < signerInfoAsn1s.length; ++i) {26644 ret.push(_signerFromAsn1(signerInfoAsn1s[i]));26645 }26646 return ret;26647}26648/**26649 * Map an array of signer objects to ASN.1 objects.26650 *26651 * @param signers an array of signer objects.26652 *26653 * @return an array of ASN.1 SignerInfos.26654 */26655function _signersToAsn1(signers) {26656 var ret = [];26657 for(var i = 0; i < signers.length; ++i) {26658 ret.push(_signerToAsn1(signers[i]));26659 }26660 return ret;26661}26662/**26663 * Convert an attribute object to an ASN.1 Attribute.26664 *26665 * @param attr the attribute object.26666 *26667 * @return the ASN.1 Attribute.26668 */26669function _attributeToAsn1(attr) {26670 var value;26671 // TODO: generalize to support more attributes26672 if(attr.type === forge.pki.oids.contentType) {26673 value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26674 asn1.oidToDer(attr.value).getBytes());26675 } else if(attr.type === forge.pki.oids.messageDigest) {26676 value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,26677 attr.value.bytes());26678 } else if(attr.type === forge.pki.oids.signingTime) {26679 /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 204926680 (inclusive) MUST be encoded as UTCTime. Any dates with year values26681 before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]26682 UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST26683 include seconds (i.e., times are YYMMDDHHMMSSZ), even where the26684 number of seconds is zero. Midnight (GMT) must be represented as26685 "YYMMDD000000Z". */26686 // TODO: make these module-level constants26687 var jan_1_1950 = new Date('1950-01-01T00:00:00Z');26688 var jan_1_2050 = new Date('2050-01-01T00:00:00Z');26689 var date = attr.value;26690 if(typeof date === 'string') {26691 // try to parse date26692 var timestamp = Date.parse(date);26693 if(!isNaN(timestamp)) {26694 date = new Date(timestamp);26695 } else if(date.length === 13) {26696 // YYMMDDHHMMSSZ (13 chars for UTCTime)26697 date = asn1.utcTimeToDate(date);26698 } else {26699 // assume generalized time26700 date = asn1.generalizedTimeToDate(date);26701 }26702 }26703 if(date >= jan_1_1950 && date < jan_1_2050) {26704 value = asn1.create(26705 asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,26706 asn1.dateToUtcTime(date));26707 } else {26708 value = asn1.create(26709 asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,26710 asn1.dateToGeneralizedTime(date));26711 }26712 }26713 // TODO: expose as common API call26714 // create a RelativeDistinguishedName set26715 // each value in the set is an AttributeTypeAndValue first26716 // containing the type (an OID) and second the value26717 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26718 // AttributeType26719 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26720 asn1.oidToDer(attr.type).getBytes()),26721 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [26722 // AttributeValue26723 value26724 ])26725 ]);26726}26727/**26728 * Map messages encrypted content to ASN.1 objects.26729 *26730 * @param ec The encryptedContent object of the message.26731 *26732 * @return ASN.1 representation of the encryptedContent object (SEQUENCE).26733 */26734function _encryptedContentToAsn1(ec) {26735 return [26736 // ContentType, always Data for the moment26737 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26738 asn1.oidToDer(forge.pki.oids.data).getBytes()),26739 // ContentEncryptionAlgorithmIdentifier26740 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [26741 // Algorithm26742 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,26743 asn1.oidToDer(ec.algorithm).getBytes()),26744 // Parameters (IV)26745 !ec.parameter ?26746 undefined :26747 asn1.create(26748 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,26749 ec.parameter.getBytes())26750 ]),26751 // [0] EncryptedContent26752 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [26753 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,26754 ec.content.getBytes())26755 ])26756 ];26757}26758/**26759 * Reads the "common part" of an PKCS#7 content block (in ASN.1 format)26760 *26761 * This function reads the "common part" of the PKCS#7 content blocks26762 * EncryptedData and EnvelopedData, i.e. version number and symmetrically26763 * encrypted content block.26764 *26765 * The result of the ASN.1 validate and capture process is returned26766 * to allow the caller to extract further data, e.g. the list of recipients26767 * in case of a EnvelopedData object.26768 *26769 * @param msg the PKCS#7 object to read the data to.26770 * @param obj the ASN.1 representation of the content block.26771 * @param validator the ASN.1 structure validator object to use.26772 *26773 * @return the value map captured by validator object.26774 */26775function _fromAsn1(msg, obj, validator) {26776 var capture = {};26777 var errors = [];26778 if(!asn1.validate(obj, validator, capture, errors)) {26779 var error = new Error('Cannot read PKCS#7 message. ' +26780 'ASN.1 object is not a supported PKCS#7 message.');26781 error.errors = error;26782 throw error;26783 }26784 // Check contentType, so far we only support (raw) Data.26785 var contentType = asn1.derToOid(capture.contentType);26786 if(contentType !== forge.pki.oids.data) {26787 throw new Error('Unsupported PKCS#7 message. ' +26788 'Only wrapped ContentType Data supported.');26789 }26790 if(capture.encryptedContent) {26791 var content = '';26792 if(forge.util.isArray(capture.encryptedContent)) {26793 for(var i = 0; i < capture.encryptedContent.length; ++i) {26794 if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {26795 throw new Error('Malformed PKCS#7 message, expecting encrypted ' +26796 'content constructed of only OCTET STRING objects.');26797 }26798 content += capture.encryptedContent[i].value;26799 }26800 } else {26801 content = capture.encryptedContent;26802 }26803 msg.encryptedContent = {26804 algorithm: asn1.derToOid(capture.encAlgorithm),26805 parameter: forge.util.createBuffer(capture.encParameter.value),26806 content: forge.util.createBuffer(content)26807 };26808 }26809 if(capture.content) {26810 var content = '';26811 if(forge.util.isArray(capture.content)) {26812 for(var i = 0; i < capture.content.length; ++i) {26813 if(capture.content[i].type !== asn1.Type.OCTETSTRING) {26814 throw new Error('Malformed PKCS#7 message, expecting ' +26815 'content constructed of only OCTET STRING objects.');26816 }26817 content += capture.content[i].value;26818 }26819 } else {26820 content = capture.content;26821 }26822 msg.content = forge.util.createBuffer(content);26823 }26824 msg.version = capture.version.charCodeAt(0);26825 msg.rawCapture = capture;26826 return capture;26827}26828/**26829 * Decrypt the symmetrically encrypted content block of the PKCS#7 message.26830 *26831 * Decryption is skipped in case the PKCS#7 message object already has a26832 * (decrypted) content attribute. The algorithm, key and cipher parameters26833 * (probably the iv) are taken from the encryptedContent attribute of the26834 * message object.26835 *26836 * @param The PKCS#7 message object.26837 */26838function _decryptContent(msg) {26839 if(msg.encryptedContent.key === undefined) {26840 throw new Error('Symmetric key not available.');26841 }26842 if(msg.content === undefined) {26843 var ciph;26844 switch(msg.encryptedContent.algorithm) {26845 case forge.pki.oids['aes128-CBC']:26846 case forge.pki.oids['aes192-CBC']:26847 case forge.pki.oids['aes256-CBC']:26848 ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);26849 break;26850 case forge.pki.oids['desCBC']:26851 case forge.pki.oids['des-EDE3-CBC']:26852 ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);26853 break;26854 default:26855 throw new Error('Unsupported symmetric cipher, OID ' +26856 msg.encryptedContent.algorithm);26857 }26858 ciph.start(msg.encryptedContent.parameter);26859 ciph.update(msg.encryptedContent.content);26860 if(!ciph.finish()) {26861 throw new Error('Symmetric decryption failed.');26862 }26863 msg.content = ciph.output;26864 }26865}26866/***/ }),26867/***/ 266:26868/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {26869/**26870 * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.26871 *26872 * @author Dave Longley26873 * @author Stefan Siegl26874 *26875 * Copyright (c) 2012-2015 Digital Bazaar, Inc.26876 * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>26877 *26878 * The ASN.1 representation of PKCS#7 is as follows26879 * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):26880 *26881 * A PKCS#7 message consists of a ContentInfo on root level, which may26882 * contain any number of further ContentInfo nested into it.26883 *26884 * ContentInfo ::= SEQUENCE {26885 * contentType ContentType,26886 * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL26887 * }26888 *26889 * ContentType ::= OBJECT IDENTIFIER26890 *26891 * EnvelopedData ::= SEQUENCE {26892 * version Version,26893 * recipientInfos RecipientInfos,26894 * encryptedContentInfo EncryptedContentInfo26895 * }26896 *26897 * EncryptedData ::= SEQUENCE {26898 * version Version,26899 * encryptedContentInfo EncryptedContentInfo26900 * }26901 *26902 * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)26903 * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }26904 *26905 * SignedData ::= SEQUENCE {26906 * version INTEGER,26907 * digestAlgorithms DigestAlgorithmIdentifiers,26908 * contentInfo ContentInfo,26909 * certificates [0] IMPLICIT Certificates OPTIONAL,26910 * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,26911 * signerInfos SignerInfos26912 * }26913 *26914 * SignerInfos ::= SET OF SignerInfo26915 *26916 * SignerInfo ::= SEQUENCE {26917 * version Version,26918 * issuerAndSerialNumber IssuerAndSerialNumber,26919 * digestAlgorithm DigestAlgorithmIdentifier,26920 * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,26921 * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,26922 * encryptedDigest EncryptedDigest,26923 * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL26924 * }26925 *26926 * EncryptedDigest ::= OCTET STRING26927 *26928 * Attributes ::= SET OF Attribute26929 *26930 * Attribute ::= SEQUENCE {26931 * attrType OBJECT IDENTIFIER,26932 * attrValues SET OF AttributeValue26933 * }26934 *26935 * AttributeValue ::= ANY26936 *26937 * Version ::= INTEGER26938 *26939 * RecipientInfos ::= SET OF RecipientInfo26940 *26941 * EncryptedContentInfo ::= SEQUENCE {26942 * contentType ContentType,26943 * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,26944 * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL26945 * }26946 *26947 * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier26948 *26949 * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters26950 * for the algorithm, if any. In the case of AES and DES3, there is only one,26951 * the IV.26952 *26953 * AlgorithmIdentifer ::= SEQUENCE {26954 * algorithm OBJECT IDENTIFIER,26955 * parameters ANY DEFINED BY algorithm OPTIONAL26956 * }26957 *26958 * EncryptedContent ::= OCTET STRING26959 *26960 * RecipientInfo ::= SEQUENCE {26961 * version Version,26962 * issuerAndSerialNumber IssuerAndSerialNumber,26963 * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,26964 * encryptedKey EncryptedKey26965 * }26966 *26967 * IssuerAndSerialNumber ::= SEQUENCE {26968 * issuer Name,26969 * serialNumber CertificateSerialNumber26970 * }26971 *26972 * CertificateSerialNumber ::= INTEGER26973 *26974 * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier26975 *26976 * EncryptedKey ::= OCTET STRING26977 */26978var forge = __nccwpck_require__(9177);26979__nccwpck_require__(9549);26980__nccwpck_require__(8339);26981// shortcut for ASN.1 API26982var asn1 = forge.asn1;26983// shortcut for PKCS#7 API26984var p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {};26985forge.pkcs7 = forge.pkcs7 || {};26986forge.pkcs7.asn1 = p7v;26987var contentInfoValidator = {26988 name: 'ContentInfo',26989 tagClass: asn1.Class.UNIVERSAL,26990 type: asn1.Type.SEQUENCE,26991 constructed: true,26992 value: [{26993 name: 'ContentInfo.ContentType',26994 tagClass: asn1.Class.UNIVERSAL,26995 type: asn1.Type.OID,26996 constructed: false,26997 capture: 'contentType'26998 }, {26999 name: 'ContentInfo.content',27000 tagClass: asn1.Class.CONTEXT_SPECIFIC,27001 type: 0,27002 constructed: true,27003 optional: true,27004 captureAsn1: 'content'27005 }]27006};27007p7v.contentInfoValidator = contentInfoValidator;27008var encryptedContentInfoValidator = {27009 name: 'EncryptedContentInfo',27010 tagClass: asn1.Class.UNIVERSAL,27011 type: asn1.Type.SEQUENCE,27012 constructed: true,27013 value: [{27014 name: 'EncryptedContentInfo.contentType',27015 tagClass: asn1.Class.UNIVERSAL,27016 type: asn1.Type.OID,27017 constructed: false,27018 capture: 'contentType'27019 }, {27020 name: 'EncryptedContentInfo.contentEncryptionAlgorithm',27021 tagClass: asn1.Class.UNIVERSAL,27022 type: asn1.Type.SEQUENCE,27023 constructed: true,27024 value: [{27025 name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',27026 tagClass: asn1.Class.UNIVERSAL,27027 type: asn1.Type.OID,27028 constructed: false,27029 capture: 'encAlgorithm'27030 }, {27031 name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',27032 tagClass: asn1.Class.UNIVERSAL,27033 captureAsn1: 'encParameter'27034 }]27035 }, {27036 name: 'EncryptedContentInfo.encryptedContent',27037 tagClass: asn1.Class.CONTEXT_SPECIFIC,27038 type: 0,27039 /* The PKCS#7 structure output by OpenSSL somewhat differs from what27040 * other implementations do generate.27041 *27042 * OpenSSL generates a structure like this:27043 * SEQUENCE {27044 * ...27045 * [0]27046 * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 3827047 * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 4527048 * ...27049 * }27050 *27051 * Whereas other implementations (and this PKCS#7 module) generate:27052 * SEQUENCE {27053 * ...27054 * [0] {27055 * OCTET STRING27056 * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 3827057 * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 4527058 * ...27059 * }27060 * }27061 *27062 * In order to support both, we just capture the context specific27063 * field here. The OCTET STRING bit is removed below.27064 */27065 capture: 'encryptedContent',27066 captureAsn1: 'encryptedContentAsn1'27067 }]27068};27069p7v.envelopedDataValidator = {27070 name: 'EnvelopedData',27071 tagClass: asn1.Class.UNIVERSAL,27072 type: asn1.Type.SEQUENCE,27073 constructed: true,27074 value: [{27075 name: 'EnvelopedData.Version',27076 tagClass: asn1.Class.UNIVERSAL,27077 type: asn1.Type.INTEGER,27078 constructed: false,27079 capture: 'version'27080 }, {27081 name: 'EnvelopedData.RecipientInfos',27082 tagClass: asn1.Class.UNIVERSAL,27083 type: asn1.Type.SET,27084 constructed: true,27085 captureAsn1: 'recipientInfos'27086 }].concat(encryptedContentInfoValidator)27087};27088p7v.encryptedDataValidator = {27089 name: 'EncryptedData',27090 tagClass: asn1.Class.UNIVERSAL,27091 type: asn1.Type.SEQUENCE,27092 constructed: true,27093 value: [{27094 name: 'EncryptedData.Version',27095 tagClass: asn1.Class.UNIVERSAL,27096 type: asn1.Type.INTEGER,27097 constructed: false,27098 capture: 'version'27099 }].concat(encryptedContentInfoValidator)27100};27101var signerValidator = {27102 name: 'SignerInfo',27103 tagClass: asn1.Class.UNIVERSAL,27104 type: asn1.Type.SEQUENCE,27105 constructed: true,27106 value: [{27107 name: 'SignerInfo.version',27108 tagClass: asn1.Class.UNIVERSAL,27109 type: asn1.Type.INTEGER,27110 constructed: false27111 }, {27112 name: 'SignerInfo.issuerAndSerialNumber',27113 tagClass: asn1.Class.UNIVERSAL,27114 type: asn1.Type.SEQUENCE,27115 constructed: true,27116 value: [{27117 name: 'SignerInfo.issuerAndSerialNumber.issuer',27118 tagClass: asn1.Class.UNIVERSAL,27119 type: asn1.Type.SEQUENCE,27120 constructed: true,27121 captureAsn1: 'issuer'27122 }, {27123 name: 'SignerInfo.issuerAndSerialNumber.serialNumber',27124 tagClass: asn1.Class.UNIVERSAL,27125 type: asn1.Type.INTEGER,27126 constructed: false,27127 capture: 'serial'27128 }]27129 }, {27130 name: 'SignerInfo.digestAlgorithm',27131 tagClass: asn1.Class.UNIVERSAL,27132 type: asn1.Type.SEQUENCE,27133 constructed: true,27134 value: [{27135 name: 'SignerInfo.digestAlgorithm.algorithm',27136 tagClass: asn1.Class.UNIVERSAL,27137 type: asn1.Type.OID,27138 constructed: false,27139 capture: 'digestAlgorithm'27140 }, {27141 name: 'SignerInfo.digestAlgorithm.parameter',27142 tagClass: asn1.Class.UNIVERSAL,27143 constructed: false,27144 captureAsn1: 'digestParameter',27145 optional: true27146 }]27147 }, {27148 name: 'SignerInfo.authenticatedAttributes',27149 tagClass: asn1.Class.CONTEXT_SPECIFIC,27150 type: 0,27151 constructed: true,27152 optional: true,27153 capture: 'authenticatedAttributes'27154 }, {27155 name: 'SignerInfo.digestEncryptionAlgorithm',27156 tagClass: asn1.Class.UNIVERSAL,27157 type: asn1.Type.SEQUENCE,27158 constructed: true,27159 capture: 'signatureAlgorithm'27160 }, {27161 name: 'SignerInfo.encryptedDigest',27162 tagClass: asn1.Class.UNIVERSAL,27163 type: asn1.Type.OCTETSTRING,27164 constructed: false,27165 capture: 'signature'27166 }, {27167 name: 'SignerInfo.unauthenticatedAttributes',27168 tagClass: asn1.Class.CONTEXT_SPECIFIC,27169 type: 1,27170 constructed: true,27171 optional: true,27172 capture: 'unauthenticatedAttributes'27173 }]27174};27175p7v.signedDataValidator = {27176 name: 'SignedData',27177 tagClass: asn1.Class.UNIVERSAL,27178 type: asn1.Type.SEQUENCE,27179 constructed: true,27180 value: [{27181 name: 'SignedData.Version',27182 tagClass: asn1.Class.UNIVERSAL,27183 type: asn1.Type.INTEGER,27184 constructed: false,27185 capture: 'version'27186 }, {27187 name: 'SignedData.DigestAlgorithms',27188 tagClass: asn1.Class.UNIVERSAL,27189 type: asn1.Type.SET,27190 constructed: true,27191 captureAsn1: 'digestAlgorithms'27192 },27193 contentInfoValidator,27194 {27195 name: 'SignedData.Certificates',27196 tagClass: asn1.Class.CONTEXT_SPECIFIC,27197 type: 0,27198 optional: true,27199 captureAsn1: 'certificates'27200 }, {27201 name: 'SignedData.CertificateRevocationLists',27202 tagClass: asn1.Class.CONTEXT_SPECIFIC,27203 type: 1,27204 optional: true,27205 captureAsn1: 'crls'27206 }, {27207 name: 'SignedData.SignerInfos',27208 tagClass: asn1.Class.UNIVERSAL,27209 type: asn1.Type.SET,27210 capture: 'signerInfos',27211 optional: true,27212 value: [signerValidator]27213 }]27214};27215p7v.recipientInfoValidator = {27216 name: 'RecipientInfo',27217 tagClass: asn1.Class.UNIVERSAL,27218 type: asn1.Type.SEQUENCE,27219 constructed: true,27220 value: [{27221 name: 'RecipientInfo.version',27222 tagClass: asn1.Class.UNIVERSAL,27223 type: asn1.Type.INTEGER,27224 constructed: false,27225 capture: 'version'27226 }, {27227 name: 'RecipientInfo.issuerAndSerial',27228 tagClass: asn1.Class.UNIVERSAL,27229 type: asn1.Type.SEQUENCE,27230 constructed: true,27231 value: [{27232 name: 'RecipientInfo.issuerAndSerial.issuer',27233 tagClass: asn1.Class.UNIVERSAL,27234 type: asn1.Type.SEQUENCE,27235 constructed: true,27236 captureAsn1: 'issuer'27237 }, {27238 name: 'RecipientInfo.issuerAndSerial.serialNumber',27239 tagClass: asn1.Class.UNIVERSAL,27240 type: asn1.Type.INTEGER,27241 constructed: false,27242 capture: 'serial'27243 }]27244 }, {27245 name: 'RecipientInfo.keyEncryptionAlgorithm',27246 tagClass: asn1.Class.UNIVERSAL,27247 type: asn1.Type.SEQUENCE,27248 constructed: true,27249 value: [{27250 name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',27251 tagClass: asn1.Class.UNIVERSAL,27252 type: asn1.Type.OID,27253 constructed: false,27254 capture: 'encAlgorithm'27255 }, {27256 name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',27257 tagClass: asn1.Class.UNIVERSAL,27258 constructed: false,27259 captureAsn1: 'encParameter',27260 optional: true27261 }]27262 }, {27263 name: 'RecipientInfo.encryptedKey',27264 tagClass: asn1.Class.UNIVERSAL,27265 type: asn1.Type.OCTETSTRING,27266 constructed: false,27267 capture: 'encKey'27268 }]27269};27270/***/ }),27271/***/ 6924:27272/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {27273/**27274 * Javascript implementation of a basic Public Key Infrastructure, including27275 * support for RSA public and private keys.27276 *27277 * @author Dave Longley27278 *27279 * Copyright (c) 2010-2013 Digital Bazaar, Inc.27280 */27281var forge = __nccwpck_require__(9177);27282__nccwpck_require__(9549);27283__nccwpck_require__(1925);27284__nccwpck_require__(1281);27285__nccwpck_require__(154);27286__nccwpck_require__(1611);27287__nccwpck_require__(466);27288__nccwpck_require__(4376);27289__nccwpck_require__(3921);27290__nccwpck_require__(8339);27291__nccwpck_require__(8180);27292// shortcut for asn.1 API27293var asn1 = forge.asn1;27294/* Public Key Infrastructure (PKI) implementation. */27295var pki = module.exports = forge.pki = forge.pki || {};27296/**27297 * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead.27298 *27299 * Converts PEM-formatted data to DER.27300 *27301 * @param pem the PEM-formatted data.27302 *27303 * @return the DER-formatted data.27304 */27305pki.pemToDer = function(pem) {27306 var msg = forge.pem.decode(pem)[0];27307 if(msg.procType && msg.procType.type === 'ENCRYPTED') {27308 throw new Error('Could not convert PEM to DER; PEM is encrypted.');27309 }27310 return forge.util.createBuffer(msg.body);27311};27312/**27313 * Converts an RSA private key from PEM format.27314 *27315 * @param pem the PEM-formatted private key.27316 *27317 * @return the private key.27318 */27319pki.privateKeyFromPem = function(pem) {27320 var msg = forge.pem.decode(pem)[0];27321 if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') {27322 var error = new Error('Could not convert private key from PEM; PEM ' +27323 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');27324 error.headerType = msg.type;27325 throw error;27326 }27327 if(msg.procType && msg.procType.type === 'ENCRYPTED') {27328 throw new Error('Could not convert private key from PEM; PEM is encrypted.');27329 }27330 // convert DER to ASN.1 object27331 var obj = asn1.fromDer(msg.body);27332 return pki.privateKeyFromAsn1(obj);27333};27334/**27335 * Converts an RSA private key to PEM format.27336 *27337 * @param key the private key.27338 * @param maxline the maximum characters per line, defaults to 64.27339 *27340 * @return the PEM-formatted private key.27341 */27342pki.privateKeyToPem = function(key, maxline) {27343 // convert to ASN.1, then DER, then PEM-encode27344 var msg = {27345 type: 'RSA PRIVATE KEY',27346 body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()27347 };27348 return forge.pem.encode(msg, {maxline: maxline});27349};27350/**27351 * Converts a PrivateKeyInfo to PEM format.27352 *27353 * @param pki the PrivateKeyInfo.27354 * @param maxline the maximum characters per line, defaults to 64.27355 *27356 * @return the PEM-formatted private key.27357 */27358pki.privateKeyInfoToPem = function(pki, maxline) {27359 // convert to DER, then PEM-encode27360 var msg = {27361 type: 'PRIVATE KEY',27362 body: asn1.toDer(pki).getBytes()27363 };27364 return forge.pem.encode(msg, {maxline: maxline});27365};27366/***/ }),27367/***/ 6861:27368/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {27369/**27370 * Prime number generation API.27371 *27372 * @author Dave Longley27373 *27374 * Copyright (c) 2014 Digital Bazaar, Inc.27375 */27376var forge = __nccwpck_require__(9177);27377__nccwpck_require__(8339);27378__nccwpck_require__(7052);27379__nccwpck_require__(7821);27380(function() {27381// forge.prime already defined27382if(forge.prime) {27383 module.exports = forge.prime;27384 return;27385}27386/* PRIME API */27387var prime = module.exports = forge.prime = forge.prime || {};27388var BigInteger = forge.jsbn.BigInteger;27389// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 2927390var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];27391var THIRTY = new BigInteger(null);27392THIRTY.fromInt(30);27393var op_or = function(x, y) {return x|y;};27394/**27395 * Generates a random probable prime with the given number of bits.27396 *27397 * Alternative algorithms can be specified by name as a string or as an27398 * object with custom options like so:27399 *27400 * {27401 * name: 'PRIMEINC',27402 * options: {27403 * maxBlockTime: <the maximum amount of time to block the main27404 * thread before allowing I/O other JS to run>,27405 * millerRabinTests: <the number of miller-rabin tests to run>,27406 * workerScript: <the worker script URL>,27407 * workers: <the number of web workers (if supported) to use,27408 * -1 to use estimated cores minus one>.27409 * workLoad: the size of the work load, ie: number of possible prime27410 * numbers for each web worker to check per work assignment,27411 * (default: 100).27412 * }27413 * }27414 *27415 * @param bits the number of bits for the prime number.27416 * @param options the options to use.27417 * [algorithm] the algorithm to use (default: 'PRIMEINC').27418 * [prng] a custom crypto-secure pseudo-random number generator to use,27419 * that must define "getBytesSync".27420 *27421 * @return callback(err, num) called once the operation completes.27422 */27423prime.generateProbablePrime = function(bits, options, callback) {27424 if(typeof options === 'function') {27425 callback = options;27426 options = {};27427 }27428 options = options || {};27429 // default to PRIMEINC algorithm27430 var algorithm = options.algorithm || 'PRIMEINC';27431 if(typeof algorithm === 'string') {27432 algorithm = {name: algorithm};27433 }27434 algorithm.options = algorithm.options || {};27435 // create prng with api that matches BigInteger secure random27436 var prng = options.prng || forge.random;27437 var rng = {27438 // x is an array to fill with bytes27439 nextBytes: function(x) {27440 var b = prng.getBytesSync(x.length);27441 for(var i = 0; i < x.length; ++i) {27442 x[i] = b.charCodeAt(i);27443 }27444 }27445 };27446 if(algorithm.name === 'PRIMEINC') {27447 return primeincFindPrime(bits, rng, algorithm.options, callback);27448 }27449 throw new Error('Invalid prime generation algorithm: ' + algorithm.name);27450};27451function primeincFindPrime(bits, rng, options, callback) {27452 if('workers' in options) {27453 return primeincFindPrimeWithWorkers(bits, rng, options, callback);27454 }27455 return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);27456}27457function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {27458 // initialize random number27459 var num = generateRandom(bits, rng);27460 /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The27461 number we are given is always aligned at 30k + 1. Each time the number is27462 determined not to be prime we add to get to the next 'i', eg: if the number27463 was at 30k + 1 we add 6. */27464 var deltaIdx = 0;27465 // get required number of MR tests27466 var mrTests = getMillerRabinTests(num.bitLength());27467 if('millerRabinTests' in options) {27468 mrTests = options.millerRabinTests;27469 }27470 // find prime nearest to 'num' for maxBlockTime ms27471 // 10 ms gives 5ms of leeway for other calculations before dropping27472 // below 60fps (1000/60 == 16.67), but in reality, the number will27473 // likely be higher due to an 'atomic' big int modPow27474 var maxBlockTime = 10;27475 if('maxBlockTime' in options) {27476 maxBlockTime = options.maxBlockTime;27477 }27478 _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);27479}27480function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {27481 var start = +new Date();27482 do {27483 // overflow, regenerate random number27484 if(num.bitLength() > bits) {27485 num = generateRandom(bits, rng);27486 }27487 // do primality test27488 if(num.isProbablePrime(mrTests)) {27489 return callback(null, num);27490 }27491 // get next potential prime27492 num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);27493 } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));27494 // keep trying later27495 forge.util.setImmediate(function() {27496 _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);27497 });27498}27499// NOTE: This algorithm is indeterminate in nature because workers27500// run in parallel looking at different segments of numbers. Even if this27501// algorithm is run twice with the same input from a predictable RNG, it27502// may produce different outputs.27503function primeincFindPrimeWithWorkers(bits, rng, options, callback) {27504 // web workers unavailable27505 if(typeof Worker === 'undefined') {27506 return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);27507 }27508 // initialize random number27509 var num = generateRandom(bits, rng);27510 // use web workers to generate keys27511 var numWorkers = options.workers;27512 var workLoad = options.workLoad || 100;27513 var range = workLoad * 30 / 8;27514 var workerScript = options.workerScript || 'forge/prime.worker.js';27515 if(numWorkers === -1) {27516 return forge.util.estimateCores(function(err, cores) {27517 if(err) {27518 // default to 227519 cores = 2;27520 }27521 numWorkers = cores - 1;27522 generate();27523 });27524 }27525 generate();27526 function generate() {27527 // require at least 1 worker27528 numWorkers = Math.max(1, numWorkers);27529 // TODO: consider optimizing by starting workers outside getPrime() ...27530 // note that in order to clean up they will have to be made internally27531 // asynchronous which may actually be slower27532 // start workers immediately27533 var workers = [];27534 for(var i = 0; i < numWorkers; ++i) {27535 // FIXME: fix path or use blob URLs27536 workers[i] = new Worker(workerScript);27537 }27538 var running = numWorkers;27539 // listen for requests from workers and assign ranges to find prime27540 for(var i = 0; i < numWorkers; ++i) {27541 workers[i].addEventListener('message', workerMessage);27542 }27543 /* Note: The distribution of random numbers is unknown. Therefore, each27544 web worker is continuously allocated a range of numbers to check for a27545 random number until one is found.27546 Every 30 numbers will be checked just 8 times, because prime numbers27547 have the form:27548 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)27549 Therefore, if we want a web worker to run N checks before asking for27550 a new range of numbers, each range must contain N*30/8 numbers.27551 For 100 checks (workLoad), this is a range of 375. */27552 var found = false;27553 function workerMessage(e) {27554 // ignore message, prime already found27555 if(found) {27556 return;27557 }27558 --running;27559 var data = e.data;27560 if(data.found) {27561 // terminate all workers27562 for(var i = 0; i < workers.length; ++i) {27563 workers[i].terminate();27564 }27565 found = true;27566 return callback(null, new BigInteger(data.prime, 16));27567 }27568 // overflow, regenerate random number27569 if(num.bitLength() > bits) {27570 num = generateRandom(bits, rng);27571 }27572 // assign new range to check27573 var hex = num.toString(16);27574 // start prime search27575 e.target.postMessage({27576 hex: hex,27577 workLoad: workLoad27578 });27579 num.dAddOffset(range, 0);27580 }27581 }27582}27583/**27584 * Generates a random number using the given number of bits and RNG.27585 *27586 * @param bits the number of bits for the number.27587 * @param rng the random number generator to use.27588 *27589 * @return the random number.27590 */27591function generateRandom(bits, rng) {27592 var num = new BigInteger(bits, rng);27593 // force MSB set27594 var bits1 = bits - 1;27595 if(!num.testBit(bits1)) {27596 num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);27597 }27598 // align number on 30k+1 boundary27599 num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);27600 return num;27601}27602/**27603 * Returns the required number of Miller-Rabin tests to generate a27604 * prime with an error probability of (1/2)^80.27605 *27606 * See Handbook of Applied Cryptography Chapter 4, Table 4.4.27607 *27608 * @param bits the bit size.27609 *27610 * @return the required number of iterations.27611 */27612function getMillerRabinTests(bits) {27613 if(bits <= 100) return 27;27614 if(bits <= 150) return 18;27615 if(bits <= 200) return 15;27616 if(bits <= 250) return 12;27617 if(bits <= 300) return 9;27618 if(bits <= 350) return 8;27619 if(bits <= 400) return 7;27620 if(bits <= 500) return 6;27621 if(bits <= 600) return 5;27622 if(bits <= 800) return 4;27623 if(bits <= 1250) return 3;27624 return 2;27625}27626})();27627/***/ }),27628/***/ 4467:27629/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {27630/**27631 * A javascript implementation of a cryptographically-secure27632 * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed27633 * here though the use of SHA-256 is not enforced; when generating an27634 * a PRNG context, the hashing algorithm and block cipher used for27635 * the generator are specified via a plugin.27636 *27637 * @author Dave Longley27638 *27639 * Copyright (c) 2010-2014 Digital Bazaar, Inc.27640 */27641var forge = __nccwpck_require__(9177);27642__nccwpck_require__(8339);27643var _crypto = null;27644if(forge.util.isNodejs && !forge.options.usePureJavaScript &&27645 !process.versions['node-webkit']) {27646 _crypto = __nccwpck_require__(6113);27647}27648/* PRNG API */27649var prng = module.exports = forge.prng = forge.prng || {};27650/**27651 * Creates a new PRNG context.27652 *27653 * A PRNG plugin must be passed in that will provide:27654 *27655 * 1. A function that initializes the key and seed of a PRNG context. It27656 * will be given a 16 byte key and a 16 byte seed. Any key expansion27657 * or transformation of the seed from a byte string into an array of27658 * integers (or similar) should be performed.27659 * 2. The cryptographic function used by the generator. It takes a key and27660 * a seed.27661 * 3. A seed increment function. It takes the seed and returns seed + 1.27662 * 4. An api to create a message digest.27663 *27664 * For an example, see random.js.27665 *27666 * @param plugin the PRNG plugin to use.27667 */27668prng.create = function(plugin) {27669 var ctx = {27670 plugin: plugin,27671 key: null,27672 seed: null,27673 time: null,27674 // number of reseeds so far27675 reseeds: 0,27676 // amount of data generated so far27677 generated: 0,27678 // no initial key bytes27679 keyBytes: ''27680 };27681 // create 32 entropy pools (each is a message digest)27682 var md = plugin.md;27683 var pools = new Array(32);27684 for(var i = 0; i < 32; ++i) {27685 pools[i] = md.create();27686 }27687 ctx.pools = pools;27688 // entropy pools are written to cyclically, starting at index 027689 ctx.pool = 0;27690 /**27691 * Generates random bytes. The bytes may be generated synchronously or27692 * asynchronously. Web workers must use the asynchronous interface or27693 * else the behavior is undefined.27694 *27695 * @param count the number of random bytes to generate.27696 * @param [callback(err, bytes)] called once the operation completes.27697 *27698 * @return count random bytes as a string.27699 */27700 ctx.generate = function(count, callback) {27701 // do synchronously27702 if(!callback) {27703 return ctx.generateSync(count);27704 }27705 // simple generator using counter-based CBC27706 var cipher = ctx.plugin.cipher;27707 var increment = ctx.plugin.increment;27708 var formatKey = ctx.plugin.formatKey;27709 var formatSeed = ctx.plugin.formatSeed;27710 var b = forge.util.createBuffer();27711 // paranoid deviation from Fortuna:27712 // reset key for every request to protect previously27713 // generated random bytes should the key be discovered;27714 // there is no 100ms based reseeding because of this27715 // forced reseed for every `generate` call27716 ctx.key = null;27717 generate();27718 function generate(err) {27719 if(err) {27720 return callback(err);27721 }27722 // sufficient bytes generated27723 if(b.length() >= count) {27724 return callback(null, b.getBytes(count));27725 }27726 // if amount of data generated is greater than 1 MiB, trigger reseed27727 if(ctx.generated > 0xfffff) {27728 ctx.key = null;27729 }27730 if(ctx.key === null) {27731 // prevent stack overflow27732 return forge.util.nextTick(function() {27733 _reseed(generate);27734 });27735 }27736 // generate the random bytes27737 var bytes = cipher(ctx.key, ctx.seed);27738 ctx.generated += bytes.length;27739 b.putBytes(bytes);27740 // generate bytes for a new key and seed27741 ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));27742 ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));27743 forge.util.setImmediate(generate);27744 }27745 };27746 /**27747 * Generates random bytes synchronously.27748 *27749 * @param count the number of random bytes to generate.27750 *27751 * @return count random bytes as a string.27752 */27753 ctx.generateSync = function(count) {27754 // simple generator using counter-based CBC27755 var cipher = ctx.plugin.cipher;27756 var increment = ctx.plugin.increment;27757 var formatKey = ctx.plugin.formatKey;27758 var formatSeed = ctx.plugin.formatSeed;27759 // paranoid deviation from Fortuna:27760 // reset key for every request to protect previously27761 // generated random bytes should the key be discovered;27762 // there is no 100ms based reseeding because of this27763 // forced reseed for every `generateSync` call27764 ctx.key = null;27765 var b = forge.util.createBuffer();27766 while(b.length() < count) {27767 // if amount of data generated is greater than 1 MiB, trigger reseed27768 if(ctx.generated > 0xfffff) {27769 ctx.key = null;27770 }27771 if(ctx.key === null) {27772 _reseedSync();27773 }27774 // generate the random bytes27775 var bytes = cipher(ctx.key, ctx.seed);27776 ctx.generated += bytes.length;27777 b.putBytes(bytes);27778 // generate bytes for a new key and seed27779 ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));27780 ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));27781 }27782 return b.getBytes(count);27783 };27784 /**27785 * Private function that asynchronously reseeds a generator.27786 *27787 * @param callback(err) called once the operation completes.27788 */27789 function _reseed(callback) {27790 if(ctx.pools[0].messageLength >= 32) {27791 _seed();27792 return callback();27793 }27794 // not enough seed data...27795 var needed = (32 - ctx.pools[0].messageLength) << 5;27796 ctx.seedFile(needed, function(err, bytes) {27797 if(err) {27798 return callback(err);27799 }27800 ctx.collect(bytes);27801 _seed();27802 callback();27803 });27804 }27805 /**27806 * Private function that synchronously reseeds a generator.27807 */27808 function _reseedSync() {27809 if(ctx.pools[0].messageLength >= 32) {27810 return _seed();27811 }27812 // not enough seed data...27813 var needed = (32 - ctx.pools[0].messageLength) << 5;27814 ctx.collect(ctx.seedFileSync(needed));27815 _seed();27816 }27817 /**27818 * Private function that seeds a generator once enough bytes are available.27819 */27820 function _seed() {27821 // update reseed count27822 ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;27823 // goal is to update `key` via:27824 // key = hash(key + s)27825 // where 's' is all collected entropy from selected pools, then...27826 // create a plugin-based message digest27827 var md = ctx.plugin.md.create();27828 // consume current key bytes27829 md.update(ctx.keyBytes);27830 // digest the entropy of pools whose index k meet the27831 // condition 'n mod 2^k == 0' where n is the number of reseeds27832 var _2powK = 1;27833 for(var k = 0; k < 32; ++k) {27834 if(ctx.reseeds % _2powK === 0) {27835 md.update(ctx.pools[k].digest().getBytes());27836 ctx.pools[k].start();27837 }27838 _2powK = _2powK << 1;27839 }27840 // get digest for key bytes27841 ctx.keyBytes = md.digest().getBytes();27842 // paranoid deviation from Fortuna:27843 // update `seed` via `seed = hash(key)`27844 // instead of initializing to zero once and only27845 // ever incrementing it27846 md.start();27847 md.update(ctx.keyBytes);27848 var seedBytes = md.digest().getBytes();27849 // update state27850 ctx.key = ctx.plugin.formatKey(ctx.keyBytes);27851 ctx.seed = ctx.plugin.formatSeed(seedBytes);27852 ctx.generated = 0;27853 }27854 /**27855 * The built-in default seedFile. This seedFile is used when entropy27856 * is needed immediately.27857 *27858 * @param needed the number of bytes that are needed.27859 *27860 * @return the random bytes.27861 */27862 function defaultSeedFile(needed) {27863 // use window.crypto.getRandomValues strong source of entropy if available27864 var getRandomValues = null;27865 var globalScope = forge.util.globalScope;27866 var _crypto = globalScope.crypto || globalScope.msCrypto;27867 if(_crypto && _crypto.getRandomValues) {27868 getRandomValues = function(arr) {27869 return _crypto.getRandomValues(arr);27870 };27871 }27872 var b = forge.util.createBuffer();27873 if(getRandomValues) {27874 while(b.length() < needed) {27875 // max byte length is 65536 before QuotaExceededError is thrown27876 // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues27877 var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);27878 var entropy = new Uint32Array(Math.floor(count));27879 try {27880 getRandomValues(entropy);27881 for(var i = 0; i < entropy.length; ++i) {27882 b.putInt32(entropy[i]);27883 }27884 } catch(e) {27885 /* only ignore QuotaExceededError */27886 if(!(typeof QuotaExceededError !== 'undefined' &&27887 e instanceof QuotaExceededError)) {27888 throw e;27889 }27890 }27891 }27892 }27893 // be sad and add some weak random data27894 if(b.length() < needed) {27895 /* Draws from Park-Miller "minimal standard" 31 bit PRNG,27896 implemented with David G. Carta's optimization: with 32 bit math27897 and without division (Public Domain). */27898 var hi, lo, next;27899 var seed = Math.floor(Math.random() * 0x010000);27900 while(b.length() < needed) {27901 lo = 16807 * (seed & 0xFFFF);27902 hi = 16807 * (seed >> 16);27903 lo += (hi & 0x7FFF) << 16;27904 lo += hi >> 15;27905 lo = (lo & 0x7FFFFFFF) + (lo >> 31);27906 seed = lo & 0xFFFFFFFF;27907 // consume lower 3 bytes of seed27908 for(var i = 0; i < 3; ++i) {27909 // throw in more pseudo random27910 next = seed >>> (i << 3);27911 next ^= Math.floor(Math.random() * 0x0100);27912 b.putByte(next & 0xFF);27913 }27914 }27915 }27916 return b.getBytes(needed);27917 }27918 // initialize seed file APIs27919 if(_crypto) {27920 // use nodejs async API27921 ctx.seedFile = function(needed, callback) {27922 _crypto.randomBytes(needed, function(err, bytes) {27923 if(err) {27924 return callback(err);27925 }27926 callback(null, bytes.toString());27927 });27928 };27929 // use nodejs sync API27930 ctx.seedFileSync = function(needed) {27931 return _crypto.randomBytes(needed).toString();27932 };27933 } else {27934 ctx.seedFile = function(needed, callback) {27935 try {27936 callback(null, defaultSeedFile(needed));27937 } catch(e) {27938 callback(e);27939 }27940 };27941 ctx.seedFileSync = defaultSeedFile;27942 }27943 /**27944 * Adds entropy to a prng ctx's accumulator.27945 *27946 * @param bytes the bytes of entropy as a string.27947 */27948 ctx.collect = function(bytes) {27949 // iterate over pools distributing entropy cyclically27950 var count = bytes.length;27951 for(var i = 0; i < count; ++i) {27952 ctx.pools[ctx.pool].update(bytes.substr(i, 1));27953 ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;27954 }27955 };27956 /**27957 * Collects an integer of n bits.27958 *27959 * @param i the integer entropy.27960 * @param n the number of bits in the integer.27961 */27962 ctx.collectInt = function(i, n) {27963 var bytes = '';27964 for(var x = 0; x < n; x += 8) {27965 bytes += String.fromCharCode((i >> x) & 0xFF);27966 }27967 ctx.collect(bytes);27968 };27969 /**27970 * Registers a Web Worker to receive immediate entropy from the main thread.27971 * This method is required until Web Workers can access the native crypto27972 * API. This method should be called twice for each created worker, once in27973 * the main thread, and once in the worker itself.27974 *27975 * @param worker the worker to register.27976 */27977 ctx.registerWorker = function(worker) {27978 // worker receives random bytes27979 if(worker === self) {27980 ctx.seedFile = function(needed, callback) {27981 function listener(e) {27982 var data = e.data;27983 if(data.forge && data.forge.prng) {27984 self.removeEventListener('message', listener);27985 callback(data.forge.prng.err, data.forge.prng.bytes);27986 }27987 }27988 self.addEventListener('message', listener);27989 self.postMessage({forge: {prng: {needed: needed}}});27990 };27991 } else {27992 // main thread sends random bytes upon request27993 var listener = function(e) {27994 var data = e.data;27995 if(data.forge && data.forge.prng) {27996 ctx.seedFile(data.forge.prng.needed, function(err, bytes) {27997 worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});27998 });27999 }28000 };28001 // TODO: do we need to remove the event listener when the worker dies?28002 worker.addEventListener('message', listener);28003 }28004 };28005 return ctx;28006};28007/***/ }),28008/***/ 4376:28009/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {28010/**28011 * Javascript implementation of PKCS#1 PSS signature padding.28012 *28013 * @author Stefan Siegl28014 *28015 * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>28016 */28017var forge = __nccwpck_require__(9177);28018__nccwpck_require__(7821);28019__nccwpck_require__(8339);28020// shortcut for PSS API28021var pss = module.exports = forge.pss = forge.pss || {};28022/**28023 * Creates a PSS signature scheme object.28024 *28025 * There are several ways to provide a salt for encoding:28026 *28027 * 1. Specify the saltLength only and the built-in PRNG will generate it.28028 * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that28029 * will be used.28030 * 3. Specify the salt itself as a forge.util.ByteBuffer.28031 *28032 * @param options the options to use:28033 * md the message digest object to use, a forge md instance.28034 * mgf the mask generation function to use, a forge mgf instance.28035 * [saltLength] the length of the salt in octets.28036 * [prng] the pseudo-random number generator to use to produce a salt.28037 * [salt] the salt to use when encoding.28038 *28039 * @return a signature scheme object.28040 */28041pss.create = function(options) {28042 // backwards compatibility w/legacy args: hash, mgf, sLen28043 if(arguments.length === 3) {28044 options = {28045 md: arguments[0],28046 mgf: arguments[1],28047 saltLength: arguments[2]28048 };28049 }28050 var hash = options.md;28051 var mgf = options.mgf;28052 var hLen = hash.digestLength;28053 var salt_ = options.salt || null;28054 if(typeof salt_ === 'string') {28055 // assume binary-encoded string28056 salt_ = forge.util.createBuffer(salt_);28057 }28058 var sLen;28059 if('saltLength' in options) {28060 sLen = options.saltLength;28061 } else if(salt_ !== null) {28062 sLen = salt_.length();28063 } else {28064 throw new Error('Salt length not specified or specific salt not given.');28065 }28066 if(salt_ !== null && salt_.length() !== sLen) {28067 throw new Error('Given salt length does not match length of given salt.');28068 }28069 var prng = options.prng || forge.random;28070 var pssobj = {};28071 /**28072 * Encodes a PSS signature.28073 *28074 * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.28075 *28076 * @param md the message digest object with the hash to sign.28077 * @param modsBits the length of the RSA modulus in bits.28078 *28079 * @return the encoded message as a binary-encoded string of length28080 * ceil((modBits - 1) / 8).28081 */28082 pssobj.encode = function(md, modBits) {28083 var i;28084 var emBits = modBits - 1;28085 var emLen = Math.ceil(emBits / 8);28086 /* 2. Let mHash = Hash(M), an octet string of length hLen. */28087 var mHash = md.digest().getBytes();28088 /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */28089 if(emLen < hLen + sLen + 2) {28090 throw new Error('Message is too long to encrypt.');28091 }28092 /* 4. Generate a random octet string salt of length sLen; if sLen = 0,28093 * then salt is the empty string. */28094 var salt;28095 if(salt_ === null) {28096 salt = prng.getBytesSync(sLen);28097 } else {28098 salt = salt_.bytes();28099 }28100 /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */28101 var m_ = new forge.util.ByteBuffer();28102 m_.fillWithByte(0, 8);28103 m_.putBytes(mHash);28104 m_.putBytes(salt);28105 /* 6. Let H = Hash(M'), an octet string of length hLen. */28106 hash.start();28107 hash.update(m_.getBytes());28108 var h = hash.digest().getBytes();28109 /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 228110 * zero octets. The length of PS may be 0. */28111 var ps = new forge.util.ByteBuffer();28112 ps.fillWithByte(0, emLen - sLen - hLen - 2);28113 /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length28114 * emLen - hLen - 1. */28115 ps.putByte(0x01);28116 ps.putBytes(salt);28117 var db = ps.getBytes();28118 /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */28119 var maskLen = emLen - hLen - 1;28120 var dbMask = mgf.generate(h, maskLen);28121 /* 10. Let maskedDB = DB \xor dbMask. */28122 var maskedDB = '';28123 for(i = 0; i < maskLen; i++) {28124 maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));28125 }28126 /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in28127 * maskedDB to zero. */28128 var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;28129 maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +28130 maskedDB.substr(1);28131 /* 12. Let EM = maskedDB || H || 0xbc.28132 * 13. Output EM. */28133 return maskedDB + h + String.fromCharCode(0xbc);28134 };28135 /**28136 * Verifies a PSS signature.28137 *28138 * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.28139 *28140 * @param mHash the message digest hash, as a binary-encoded string, to28141 * compare against the signature.28142 * @param em the encoded message, as a binary-encoded string28143 * (RSA decryption result).28144 * @param modsBits the length of the RSA modulus in bits.28145 *28146 * @return true if the signature was verified, false if not.28147 */28148 pssobj.verify = function(mHash, em, modBits) {28149 var i;28150 var emBits = modBits - 1;28151 var emLen = Math.ceil(emBits / 8);28152 /* c. Convert the message representative m to an encoded message EM28153 * of length emLen = ceil((modBits - 1) / 8) octets, where modBits28154 * is the length in bits of the RSA modulus n */28155 em = em.substr(-emLen);28156 /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */28157 if(emLen < hLen + sLen + 2) {28158 throw new Error('Inconsistent parameters to PSS signature verification.');28159 }28160 /* 4. If the rightmost octet of EM does not have hexadecimal value28161 * 0xbc, output "inconsistent" and stop. */28162 if(em.charCodeAt(emLen - 1) !== 0xbc) {28163 throw new Error('Encoded message does not end in 0xBC.');28164 }28165 /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and28166 * let H be the next hLen octets. */28167 var maskLen = emLen - hLen - 1;28168 var maskedDB = em.substr(0, maskLen);28169 var h = em.substr(maskLen, hLen);28170 /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in28171 * maskedDB are not all equal to zero, output "inconsistent" and stop. */28172 var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;28173 if((maskedDB.charCodeAt(0) & mask) !== 0) {28174 throw new Error('Bits beyond keysize not zero as expected.');28175 }28176 /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */28177 var dbMask = mgf.generate(h, maskLen);28178 /* 8. Let DB = maskedDB \xor dbMask. */28179 var db = '';28180 for(i = 0; i < maskLen; i++) {28181 db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));28182 }28183 /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet28184 * in DB to zero. */28185 db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);28186 /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero28187 * or if the octet at position emLen - hLen - sLen - 1 (the leftmost28188 * position is "position 1") does not have hexadecimal value 0x01,28189 * output "inconsistent" and stop. */28190 var checkLen = emLen - hLen - sLen - 2;28191 for(i = 0; i < checkLen; i++) {28192 if(db.charCodeAt(i) !== 0x00) {28193 throw new Error('Leftmost octets not zero as expected');28194 }28195 }28196 if(db.charCodeAt(checkLen) !== 0x01) {28197 throw new Error('Inconsistent PSS signature, 0x01 marker not found');28198 }28199 /* 11. Let salt be the last sLen octets of DB. */28200 var salt = db.substr(-sLen);28201 /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */28202 var m_ = new forge.util.ByteBuffer();28203 m_.fillWithByte(0, 8);28204 m_.putBytes(mHash);28205 m_.putBytes(salt);28206 /* 13. Let H' = Hash(M'), an octet string of length hLen. */28207 hash.start();28208 hash.update(m_.getBytes());28209 var h_ = hash.digest().getBytes();28210 /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */28211 return h === h_;28212 };28213 return pssobj;28214};28215/***/ }),28216/***/ 7821:28217/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {28218/**28219 * An API for getting cryptographically-secure random bytes. The bytes are28220 * generated using the Fortuna algorithm devised by Bruce Schneier and28221 * Niels Ferguson.28222 *28223 * Getting strong random bytes is not yet easy to do in javascript. The only28224 * truish random entropy that can be collected is from the mouse, keyboard, or28225 * from timing with respect to page loads, etc. This generator makes a poor28226 * attempt at providing random bytes when those sources haven't yet provided28227 * enough entropy to initially seed or to reseed the PRNG.28228 *28229 * @author Dave Longley28230 *28231 * Copyright (c) 2009-2014 Digital Bazaar, Inc.28232 */28233var forge = __nccwpck_require__(9177);28234__nccwpck_require__(7994);28235__nccwpck_require__(4086);28236__nccwpck_require__(4467);28237__nccwpck_require__(8339);28238(function() {28239// forge.random already defined28240if(forge.random && forge.random.getBytes) {28241 module.exports = forge.random;28242 return;28243}28244(function(jQuery) {28245// the default prng plugin, uses AES-12828246var prng_aes = {};28247var _prng_aes_output = new Array(4);28248var _prng_aes_buffer = forge.util.createBuffer();28249prng_aes.formatKey = function(key) {28250 // convert the key into 32-bit integers28251 var tmp = forge.util.createBuffer(key);28252 key = new Array(4);28253 key[0] = tmp.getInt32();28254 key[1] = tmp.getInt32();28255 key[2] = tmp.getInt32();28256 key[3] = tmp.getInt32();28257 // return the expanded key28258 return forge.aes._expandKey(key, false);28259};28260prng_aes.formatSeed = function(seed) {28261 // convert seed into 32-bit integers28262 var tmp = forge.util.createBuffer(seed);28263 seed = new Array(4);28264 seed[0] = tmp.getInt32();28265 seed[1] = tmp.getInt32();28266 seed[2] = tmp.getInt32();28267 seed[3] = tmp.getInt32();28268 return seed;28269};28270prng_aes.cipher = function(key, seed) {28271 forge.aes._updateBlock(key, seed, _prng_aes_output, false);28272 _prng_aes_buffer.putInt32(_prng_aes_output[0]);28273 _prng_aes_buffer.putInt32(_prng_aes_output[1]);28274 _prng_aes_buffer.putInt32(_prng_aes_output[2]);28275 _prng_aes_buffer.putInt32(_prng_aes_output[3]);28276 return _prng_aes_buffer.getBytes();28277};28278prng_aes.increment = function(seed) {28279 // FIXME: do we care about carry or signed issues?28280 ++seed[3];28281 return seed;28282};28283prng_aes.md = forge.md.sha256;28284/**28285 * Creates a new PRNG.28286 */28287function spawnPrng() {28288 var ctx = forge.prng.create(prng_aes);28289 /**28290 * Gets random bytes. If a native secure crypto API is unavailable, this28291 * method tries to make the bytes more unpredictable by drawing from data that28292 * can be collected from the user of the browser, eg: mouse movement.28293 *28294 * If a callback is given, this method will be called asynchronously.28295 *28296 * @param count the number of random bytes to get.28297 * @param [callback(err, bytes)] called once the operation completes.28298 *28299 * @return the random bytes in a string.28300 */28301 ctx.getBytes = function(count, callback) {28302 return ctx.generate(count, callback);28303 };28304 /**28305 * Gets random bytes asynchronously. If a native secure crypto API is28306 * unavailable, this method tries to make the bytes more unpredictable by28307 * drawing from data that can be collected from the user of the browser,28308 * eg: mouse movement.28309 *28310 * @param count the number of random bytes to get.28311 *28312 * @return the random bytes in a string.28313 */28314 ctx.getBytesSync = function(count) {28315 return ctx.generate(count);28316 };28317 return ctx;28318}28319// create default prng context28320var _ctx = spawnPrng();28321// add other sources of entropy only if window.crypto.getRandomValues is not28322// available -- otherwise this source will be automatically used by the prng28323var getRandomValues = null;28324var globalScope = forge.util.globalScope;28325var _crypto = globalScope.crypto || globalScope.msCrypto;28326if(_crypto && _crypto.getRandomValues) {28327 getRandomValues = function(arr) {28328 return _crypto.getRandomValues(arr);28329 };28330}28331if(forge.options.usePureJavaScript ||28332 (!forge.util.isNodejs && !getRandomValues)) {28333 // if this is a web worker, do not use weak entropy, instead register to28334 // receive strong entropy asynchronously from the main thread28335 if(typeof window === 'undefined' || window.document === undefined) {28336 // FIXME:28337 }28338 // get load time entropy28339 _ctx.collectInt(+new Date(), 32);28340 // add some entropy from navigator object28341 if(typeof(navigator) !== 'undefined') {28342 var _navBytes = '';28343 for(var key in navigator) {28344 try {28345 if(typeof(navigator[key]) == 'string') {28346 _navBytes += navigator[key];28347 }28348 } catch(e) {28349 /* Some navigator keys might not be accessible, e.g. the geolocation28350 attribute throws an exception if touched in Mozilla chrome://28351 context.28352 Silently ignore this and just don't use this as a source of28353 entropy. */28354 }28355 }28356 _ctx.collect(_navBytes);28357 _navBytes = null;28358 }28359 // add mouse and keyboard collectors if jquery is available28360 if(jQuery) {28361 // set up mouse entropy capture28362 jQuery().mousemove(function(e) {28363 // add mouse coords28364 _ctx.collectInt(e.clientX, 16);28365 _ctx.collectInt(e.clientY, 16);28366 });28367 // set up keyboard entropy capture28368 jQuery().keypress(function(e) {28369 _ctx.collectInt(e.charCode, 8);28370 });28371 }28372}28373/* Random API */28374if(!forge.random) {28375 forge.random = _ctx;28376} else {28377 // extend forge.random with _ctx28378 for(var key in _ctx) {28379 forge.random[key] = _ctx[key];28380 }28381}28382// expose spawn PRNG28383forge.random.createInstance = spawnPrng;28384module.exports = forge.random;28385})(typeof(jQuery) !== 'undefined' ? jQuery : null);28386})();28387/***/ }),28388/***/ 9965:28389/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {28390/**28391 * RC2 implementation.28392 *28393 * @author Stefan Siegl28394 *28395 * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>28396 *28397 * Information on the RC2 cipher is available from RFC #2268,28398 * http://www.ietf.org/rfc/rfc2268.txt28399 */28400var forge = __nccwpck_require__(9177);28401__nccwpck_require__(8339);28402var piTable = [28403 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,28404 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,28405 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,28406 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,28407 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,28408 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,28409 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,28410 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,28411 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,28412 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,28413 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,28414 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,28415 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,28416 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,28417 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,28418 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad28419];28420var s = [1, 2, 3, 5];28421/**28422 * Rotate a word left by given number of bits.28423 *28424 * Bits that are shifted out on the left are put back in on the right28425 * hand side.28426 *28427 * @param word The word to shift left.28428 * @param bits The number of bits to shift by.28429 * @return The rotated word.28430 */28431var rol = function(word, bits) {28432 return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));28433};28434/**28435 * Rotate a word right by given number of bits.28436 *28437 * Bits that are shifted out on the right are put back in on the left28438 * hand side.28439 *28440 * @param word The word to shift right.28441 * @param bits The number of bits to shift by.28442 * @return The rotated word.28443 */28444var ror = function(word, bits) {28445 return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);28446};28447/* RC2 API */28448module.exports = forge.rc2 = forge.rc2 || {};28449/**28450 * Perform RC2 key expansion as per RFC #2268, section 2.28451 *28452 * @param key variable-length user key (between 1 and 128 bytes)28453 * @param effKeyBits number of effective key bits (default: 128)28454 * @return the expanded RC2 key (ByteBuffer of 128 bytes)28455 */28456forge.rc2.expandKey = function(key, effKeyBits) {28457 if(typeof key === 'string') {28458 key = forge.util.createBuffer(key);28459 }28460 effKeyBits = effKeyBits || 128;28461 /* introduce variables that match the names used in RFC #2268 */28462 var L = key;28463 var T = key.length();28464 var T1 = effKeyBits;28465 var T8 = Math.ceil(T1 / 8);28466 var TM = 0xff >> (T1 & 0x07);28467 var i;28468 for(i = T; i < 128; i++) {28469 L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);28470 }28471 L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);28472 for(i = 127 - T8; i >= 0; i--) {28473 L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);28474 }28475 return L;28476};28477/**28478 * Creates a RC2 cipher object.28479 *28480 * @param key the symmetric key to use (as base for key generation).28481 * @param bits the number of effective key bits.28482 * @param encrypt false for decryption, true for encryption.28483 *28484 * @return the cipher.28485 */28486var createCipher = function(key, bits, encrypt) {28487 var _finish = false, _input = null, _output = null, _iv = null;28488 var mixRound, mashRound;28489 var i, j, K = [];28490 /* Expand key and fill into K[] Array */28491 key = forge.rc2.expandKey(key, bits);28492 for(i = 0; i < 64; i++) {28493 K.push(key.getInt16Le());28494 }28495 if(encrypt) {28496 /**28497 * Perform one mixing round "in place".28498 *28499 * @param R Array of four words to perform mixing on.28500 */28501 mixRound = function(R) {28502 for(i = 0; i < 4; i++) {28503 R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +28504 ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);28505 R[i] = rol(R[i], s[i]);28506 j++;28507 }28508 };28509 /**28510 * Perform one mashing round "in place".28511 *28512 * @param R Array of four words to perform mashing on.28513 */28514 mashRound = function(R) {28515 for(i = 0; i < 4; i++) {28516 R[i] += K[R[(i + 3) % 4] & 63];28517 }28518 };28519 } else {28520 /**28521 * Perform one r-mixing round "in place".28522 *28523 * @param R Array of four words to perform mixing on.28524 */28525 mixRound = function(R) {28526 for(i = 3; i >= 0; i--) {28527 R[i] = ror(R[i], s[i]);28528 R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +28529 ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);28530 j--;28531 }28532 };28533 /**28534 * Perform one r-mashing round "in place".28535 *28536 * @param R Array of four words to perform mashing on.28537 */28538 mashRound = function(R) {28539 for(i = 3; i >= 0; i--) {28540 R[i] -= K[R[(i + 3) % 4] & 63];28541 }28542 };28543 }28544 /**28545 * Run the specified cipher execution plan.28546 *28547 * This function takes four words from the input buffer, applies the IV on28548 * it (if requested) and runs the provided execution plan.28549 *28550 * The plan must be put together in form of a array of arrays. Where the28551 * outer one is simply a list of steps to perform and the inner one needs28552 * to have two elements: the first one telling how many rounds to perform,28553 * the second one telling what to do (i.e. the function to call).28554 *28555 * @param {Array} plan The plan to execute.28556 */28557 var runPlan = function(plan) {28558 var R = [];28559 /* Get data from input buffer and fill the four words into R */28560 for(i = 0; i < 4; i++) {28561 var val = _input.getInt16Le();28562 if(_iv !== null) {28563 if(encrypt) {28564 /* We're encrypting, apply the IV first. */28565 val ^= _iv.getInt16Le();28566 } else {28567 /* We're decryption, keep cipher text for next block. */28568 _iv.putInt16Le(val);28569 }28570 }28571 R.push(val & 0xffff);28572 }28573 /* Reset global "j" variable as per spec. */28574 j = encrypt ? 0 : 63;28575 /* Run execution plan. */28576 for(var ptr = 0; ptr < plan.length; ptr++) {28577 for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {28578 plan[ptr][1](R);28579 }28580 }28581 /* Write back result to output buffer. */28582 for(i = 0; i < 4; i++) {28583 if(_iv !== null) {28584 if(encrypt) {28585 /* We're encrypting in CBC-mode, feed back encrypted bytes into28586 IV buffer to carry it forward to next block. */28587 _iv.putInt16Le(R[i]);28588 } else {28589 R[i] ^= _iv.getInt16Le();28590 }28591 }28592 _output.putInt16Le(R[i]);28593 }28594 };28595 /* Create cipher object */28596 var cipher = null;28597 cipher = {28598 /**28599 * Starts or restarts the encryption or decryption process, whichever28600 * was previously configured.28601 *28602 * To use the cipher in CBC mode, iv may be given either as a string28603 * of bytes, or as a byte buffer. For ECB mode, give null as iv.28604 *28605 * @param iv the initialization vector to use, null for ECB mode.28606 * @param output the output the buffer to write to, null to create one.28607 */28608 start: function(iv, output) {28609 if(iv) {28610 /* CBC mode */28611 if(typeof iv === 'string') {28612 iv = forge.util.createBuffer(iv);28613 }28614 }28615 _finish = false;28616 _input = forge.util.createBuffer();28617 _output = output || new forge.util.createBuffer();28618 _iv = iv;28619 cipher.output = _output;28620 },28621 /**28622 * Updates the next block.28623 *28624 * @param input the buffer to read from.28625 */28626 update: function(input) {28627 if(!_finish) {28628 // not finishing, so fill the input buffer with more input28629 _input.putBuffer(input);28630 }28631 while(_input.length() >= 8) {28632 runPlan([28633 [ 5, mixRound ],28634 [ 1, mashRound ],28635 [ 6, mixRound ],28636 [ 1, mashRound ],28637 [ 5, mixRound ]28638 ]);28639 }28640 },28641 /**28642 * Finishes encrypting or decrypting.28643 *28644 * @param pad a padding function to use, null for PKCS#7 padding,28645 * signature(blockSize, buffer, decrypt).28646 *28647 * @return true if successful, false on error.28648 */28649 finish: function(pad) {28650 var rval = true;28651 if(encrypt) {28652 if(pad) {28653 rval = pad(8, _input, !encrypt);28654 } else {28655 // add PKCS#7 padding to block (each pad byte is the28656 // value of the number of pad bytes)28657 var padding = (_input.length() === 8) ? 8 : (8 - _input.length());28658 _input.fillWithByte(padding, padding);28659 }28660 }28661 if(rval) {28662 // do final update28663 _finish = true;28664 cipher.update();28665 }28666 if(!encrypt) {28667 // check for error: input data not a multiple of block size28668 rval = (_input.length() === 0);28669 if(rval) {28670 if(pad) {28671 rval = pad(8, _output, !encrypt);28672 } else {28673 // ensure padding byte count is valid28674 var len = _output.length();28675 var count = _output.at(len - 1);28676 if(count > len) {28677 rval = false;28678 } else {28679 // trim off padding bytes28680 _output.truncate(count);28681 }28682 }28683 }28684 }28685 return rval;28686 }28687 };28688 return cipher;28689};28690/**28691 * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the28692 * given symmetric key. The output will be stored in the 'output' member28693 * of the returned cipher.28694 *28695 * The key and iv may be given as a string of bytes or a byte buffer.28696 * The cipher is initialized to use 128 effective key bits.28697 *28698 * @param key the symmetric key to use.28699 * @param iv the initialization vector to use.28700 * @param output the buffer to write to, null to create one.28701 *28702 * @return the cipher.28703 */28704forge.rc2.startEncrypting = function(key, iv, output) {28705 var cipher = forge.rc2.createEncryptionCipher(key, 128);28706 cipher.start(iv, output);28707 return cipher;28708};28709/**28710 * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the28711 * given symmetric key.28712 *28713 * The key may be given as a string of bytes or a byte buffer.28714 *28715 * To start encrypting call start() on the cipher with an iv and optional28716 * output buffer.28717 *28718 * @param key the symmetric key to use.28719 *28720 * @return the cipher.28721 */28722forge.rc2.createEncryptionCipher = function(key, bits) {28723 return createCipher(key, bits, true);28724};28725/**28726 * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the28727 * given symmetric key. The output will be stored in the 'output' member28728 * of the returned cipher.28729 *28730 * The key and iv may be given as a string of bytes or a byte buffer.28731 * The cipher is initialized to use 128 effective key bits.28732 *28733 * @param key the symmetric key to use.28734 * @param iv the initialization vector to use.28735 * @param output the buffer to write to, null to create one.28736 *28737 * @return the cipher.28738 */28739forge.rc2.startDecrypting = function(key, iv, output) {28740 var cipher = forge.rc2.createDecryptionCipher(key, 128);28741 cipher.start(iv, output);28742 return cipher;28743};28744/**28745 * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the28746 * given symmetric key.28747 *28748 * The key may be given as a string of bytes or a byte buffer.28749 *28750 * To start decrypting call start() on the cipher with an iv and optional28751 * output buffer.28752 *28753 * @param key the symmetric key to use.28754 *28755 * @return the cipher.28756 */28757forge.rc2.createDecryptionCipher = function(key, bits) {28758 return createCipher(key, bits, false);28759};28760/***/ }),28761/***/ 3921:28762/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {28763/**28764 * Javascript implementation of basic RSA algorithms.28765 *28766 * @author Dave Longley28767 *28768 * Copyright (c) 2010-2014 Digital Bazaar, Inc.28769 *28770 * The only algorithm currently supported for PKI is RSA.28771 *28772 * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo28773 * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier28774 * and a subjectPublicKey of type bit string.28775 *28776 * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters28777 * for the algorithm, if any. In the case of RSA, there aren't any.28778 *28779 * SubjectPublicKeyInfo ::= SEQUENCE {28780 * algorithm AlgorithmIdentifier,28781 * subjectPublicKey BIT STRING28782 * }28783 *28784 * AlgorithmIdentifer ::= SEQUENCE {28785 * algorithm OBJECT IDENTIFIER,28786 * parameters ANY DEFINED BY algorithm OPTIONAL28787 * }28788 *28789 * For an RSA public key, the subjectPublicKey is:28790 *28791 * RSAPublicKey ::= SEQUENCE {28792 * modulus INTEGER, -- n28793 * publicExponent INTEGER -- e28794 * }28795 *28796 * PrivateKeyInfo ::= SEQUENCE {28797 * version Version,28798 * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,28799 * privateKey PrivateKey,28800 * attributes [0] IMPLICIT Attributes OPTIONAL28801 * }28802 *28803 * Version ::= INTEGER28804 * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier28805 * PrivateKey ::= OCTET STRING28806 * Attributes ::= SET OF Attribute28807 *28808 * An RSA private key as the following structure:28809 *28810 * RSAPrivateKey ::= SEQUENCE {28811 * version Version,28812 * modulus INTEGER, -- n28813 * publicExponent INTEGER, -- e28814 * privateExponent INTEGER, -- d28815 * prime1 INTEGER, -- p28816 * prime2 INTEGER, -- q28817 * exponent1 INTEGER, -- d mod (p-1)28818 * exponent2 INTEGER, -- d mod (q-1)28819 * coefficient INTEGER -- (inverse of q) mod p28820 * }28821 *28822 * Version ::= INTEGER28823 *28824 * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.128825 */28826var forge = __nccwpck_require__(9177);28827__nccwpck_require__(9549);28828__nccwpck_require__(7052);28829__nccwpck_require__(1925);28830__nccwpck_require__(7014);28831__nccwpck_require__(6861);28832__nccwpck_require__(7821);28833__nccwpck_require__(8339);28834if(typeof BigInteger === 'undefined') {28835 var BigInteger = forge.jsbn.BigInteger;28836}28837var _crypto = forge.util.isNodejs ? __nccwpck_require__(6113) : null;28838// shortcut for asn.1 API28839var asn1 = forge.asn1;28840// shortcut for util API28841var util = forge.util;28842/*28843 * RSA encryption and decryption, see RFC 2313.28844 */28845forge.pki = forge.pki || {};28846module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {};28847var pki = forge.pki;28848// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 2928849var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];28850// validator for a PrivateKeyInfo structure28851var privateKeyValidator = {28852 // PrivateKeyInfo28853 name: 'PrivateKeyInfo',28854 tagClass: asn1.Class.UNIVERSAL,28855 type: asn1.Type.SEQUENCE,28856 constructed: true,28857 value: [{28858 // Version (INTEGER)28859 name: 'PrivateKeyInfo.version',28860 tagClass: asn1.Class.UNIVERSAL,28861 type: asn1.Type.INTEGER,28862 constructed: false,28863 capture: 'privateKeyVersion'28864 }, {28865 // privateKeyAlgorithm28866 name: 'PrivateKeyInfo.privateKeyAlgorithm',28867 tagClass: asn1.Class.UNIVERSAL,28868 type: asn1.Type.SEQUENCE,28869 constructed: true,28870 value: [{28871 name: 'AlgorithmIdentifier.algorithm',28872 tagClass: asn1.Class.UNIVERSAL,28873 type: asn1.Type.OID,28874 constructed: false,28875 capture: 'privateKeyOid'28876 }]28877 }, {28878 // PrivateKey28879 name: 'PrivateKeyInfo',28880 tagClass: asn1.Class.UNIVERSAL,28881 type: asn1.Type.OCTETSTRING,28882 constructed: false,28883 capture: 'privateKey'28884 }]28885};28886// validator for an RSA private key28887var rsaPrivateKeyValidator = {28888 // RSAPrivateKey28889 name: 'RSAPrivateKey',28890 tagClass: asn1.Class.UNIVERSAL,28891 type: asn1.Type.SEQUENCE,28892 constructed: true,28893 value: [{28894 // Version (INTEGER)28895 name: 'RSAPrivateKey.version',28896 tagClass: asn1.Class.UNIVERSAL,28897 type: asn1.Type.INTEGER,28898 constructed: false,28899 capture: 'privateKeyVersion'28900 }, {28901 // modulus (n)28902 name: 'RSAPrivateKey.modulus',28903 tagClass: asn1.Class.UNIVERSAL,28904 type: asn1.Type.INTEGER,28905 constructed: false,28906 capture: 'privateKeyModulus'28907 }, {28908 // publicExponent (e)28909 name: 'RSAPrivateKey.publicExponent',28910 tagClass: asn1.Class.UNIVERSAL,28911 type: asn1.Type.INTEGER,28912 constructed: false,28913 capture: 'privateKeyPublicExponent'28914 }, {28915 // privateExponent (d)28916 name: 'RSAPrivateKey.privateExponent',28917 tagClass: asn1.Class.UNIVERSAL,28918 type: asn1.Type.INTEGER,28919 constructed: false,28920 capture: 'privateKeyPrivateExponent'28921 }, {28922 // prime1 (p)28923 name: 'RSAPrivateKey.prime1',28924 tagClass: asn1.Class.UNIVERSAL,28925 type: asn1.Type.INTEGER,28926 constructed: false,28927 capture: 'privateKeyPrime1'28928 }, {28929 // prime2 (q)28930 name: 'RSAPrivateKey.prime2',28931 tagClass: asn1.Class.UNIVERSAL,28932 type: asn1.Type.INTEGER,28933 constructed: false,28934 capture: 'privateKeyPrime2'28935 }, {28936 // exponent1 (d mod (p-1))28937 name: 'RSAPrivateKey.exponent1',28938 tagClass: asn1.Class.UNIVERSAL,28939 type: asn1.Type.INTEGER,28940 constructed: false,28941 capture: 'privateKeyExponent1'28942 }, {28943 // exponent2 (d mod (q-1))28944 name: 'RSAPrivateKey.exponent2',28945 tagClass: asn1.Class.UNIVERSAL,28946 type: asn1.Type.INTEGER,28947 constructed: false,28948 capture: 'privateKeyExponent2'28949 }, {28950 // coefficient ((inverse of q) mod p)28951 name: 'RSAPrivateKey.coefficient',28952 tagClass: asn1.Class.UNIVERSAL,28953 type: asn1.Type.INTEGER,28954 constructed: false,28955 capture: 'privateKeyCoefficient'28956 }]28957};28958// validator for an RSA public key28959var rsaPublicKeyValidator = {28960 // RSAPublicKey28961 name: 'RSAPublicKey',28962 tagClass: asn1.Class.UNIVERSAL,28963 type: asn1.Type.SEQUENCE,28964 constructed: true,28965 value: [{28966 // modulus (n)28967 name: 'RSAPublicKey.modulus',28968 tagClass: asn1.Class.UNIVERSAL,28969 type: asn1.Type.INTEGER,28970 constructed: false,28971 capture: 'publicKeyModulus'28972 }, {28973 // publicExponent (e)28974 name: 'RSAPublicKey.exponent',28975 tagClass: asn1.Class.UNIVERSAL,28976 type: asn1.Type.INTEGER,28977 constructed: false,28978 capture: 'publicKeyExponent'28979 }]28980};28981// validator for an SubjectPublicKeyInfo structure28982// Note: Currently only works with an RSA public key28983var publicKeyValidator = forge.pki.rsa.publicKeyValidator = {28984 name: 'SubjectPublicKeyInfo',28985 tagClass: asn1.Class.UNIVERSAL,28986 type: asn1.Type.SEQUENCE,28987 constructed: true,28988 captureAsn1: 'subjectPublicKeyInfo',28989 value: [{28990 name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',28991 tagClass: asn1.Class.UNIVERSAL,28992 type: asn1.Type.SEQUENCE,28993 constructed: true,28994 value: [{28995 name: 'AlgorithmIdentifier.algorithm',28996 tagClass: asn1.Class.UNIVERSAL,28997 type: asn1.Type.OID,28998 constructed: false,28999 capture: 'publicKeyOid'29000 }]29001 }, {29002 // subjectPublicKey29003 name: 'SubjectPublicKeyInfo.subjectPublicKey',29004 tagClass: asn1.Class.UNIVERSAL,29005 type: asn1.Type.BITSTRING,29006 constructed: false,29007 value: [{29008 // RSAPublicKey29009 name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',29010 tagClass: asn1.Class.UNIVERSAL,29011 type: asn1.Type.SEQUENCE,29012 constructed: true,29013 optional: true,29014 captureAsn1: 'rsaPublicKey'29015 }]29016 }]29017};29018// validator for a DigestInfo structure29019var digestInfoValidator = {29020 name: 'DigestInfo',29021 tagClass: asn1.Class.UNIVERSAL,29022 type: asn1.Type.SEQUENCE,29023 constructed: true,29024 value: [{29025 name: 'DigestInfo.DigestAlgorithm',29026 tagClass: asn1.Class.UNIVERSAL,29027 type: asn1.Type.SEQUENCE,29028 constructed: true,29029 value: [{29030 name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',29031 tagClass: asn1.Class.UNIVERSAL,29032 type: asn1.Type.OID,29033 constructed: false,29034 capture: 'algorithmIdentifier'29035 }, {29036 // NULL paramters29037 name: 'DigestInfo.DigestAlgorithm.parameters',29038 tagClass: asn1.Class.UNIVERSAL,29039 type: asn1.Type.NULL,29040 // captured only to check existence for md2 and md529041 capture: 'parameters',29042 optional: true,29043 constructed: false29044 }]29045 }, {29046 // digest29047 name: 'DigestInfo.digest',29048 tagClass: asn1.Class.UNIVERSAL,29049 type: asn1.Type.OCTETSTRING,29050 constructed: false,29051 capture: 'digest'29052 }]29053};29054/**29055 * Wrap digest in DigestInfo object.29056 *29057 * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.29058 *29059 * DigestInfo ::= SEQUENCE {29060 * digestAlgorithm DigestAlgorithmIdentifier,29061 * digest Digest29062 * }29063 *29064 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier29065 * Digest ::= OCTET STRING29066 *29067 * @param md the message digest object with the hash to sign.29068 *29069 * @return the encoded message (ready for RSA encrytion)29070 */29071var emsaPkcs1v15encode = function(md) {29072 // get the oid for the algorithm29073 var oid;29074 if(md.algorithm in pki.oids) {29075 oid = pki.oids[md.algorithm];29076 } else {29077 var error = new Error('Unknown message digest algorithm.');29078 error.algorithm = md.algorithm;29079 throw error;29080 }29081 var oidBytes = asn1.oidToDer(oid).getBytes();29082 // create the digest info29083 var digestInfo = asn1.create(29084 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);29085 var digestAlgorithm = asn1.create(29086 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);29087 digestAlgorithm.value.push(asn1.create(29088 asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes));29089 digestAlgorithm.value.push(asn1.create(29090 asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''));29091 var digest = asn1.create(29092 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING,29093 false, md.digest().getBytes());29094 digestInfo.value.push(digestAlgorithm);29095 digestInfo.value.push(digest);29096 // encode digest info29097 return asn1.toDer(digestInfo).getBytes();29098};29099/**29100 * Performs x^c mod n (RSA encryption or decryption operation).29101 *29102 * @param x the number to raise and mod.29103 * @param key the key to use.29104 * @param pub true if the key is public, false if private.29105 *29106 * @return the result of x^c mod n.29107 */29108var _modPow = function(x, key, pub) {29109 if(pub) {29110 return x.modPow(key.e, key.n);29111 }29112 if(!key.p || !key.q) {29113 // allow calculation without CRT params (slow)29114 return x.modPow(key.d, key.n);29115 }29116 // pre-compute dP, dQ, and qInv if necessary29117 if(!key.dP) {29118 key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));29119 }29120 if(!key.dQ) {29121 key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));29122 }29123 if(!key.qInv) {29124 key.qInv = key.q.modInverse(key.p);29125 }29126 /* Chinese remainder theorem (CRT) states:29127 Suppose n1, n2, ..., nk are positive integers which are pairwise29128 coprime (n1 and n2 have no common factors other than 1). For any29129 integers x1, x2, ..., xk there exists an integer x solving the29130 system of simultaneous congruences (where ~= means modularly29131 congruent so a ~= b mod n means a mod n = b mod n):29132 x ~= x1 mod n129133 x ~= x2 mod n229134 ...29135 x ~= xk mod nk29136 This system of congruences has a single simultaneous solution x29137 between 0 and n - 1. Furthermore, each xk solution and x itself29138 is congruent modulo the product n = n1*n2*...*nk.29139 So x1 mod n = x2 mod n = xk mod n = x mod n.29140 The single simultaneous solution x can be solved with the following29141 equation:29142 x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.29143 Where x is less than n, xi = x mod ni.29144 For RSA we are only concerned with k = 2. The modulus n = pq, where29145 p and q are coprime. The RSA decryption algorithm is:29146 y = x^d mod n29147 Given the above:29148 x1 = x^d mod p29149 r1 = n/p = q29150 s1 = q^-1 mod p29151 x2 = x^d mod q29152 r2 = n/q = p29153 s2 = p^-1 mod q29154 So y = (x1r1s1 + x2r2s2) mod n29155 = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n29156 According to Fermat's Little Theorem, if the modulus P is prime,29157 for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.29158 Since A is not divisible by P it follows that if:29159 N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:29160 A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort29161 to calculate). In order to calculate x^d mod p more quickly the29162 exponent d mod (p - 1) is stored in the RSA private key (the same29163 is done for x^d mod q). These values are referred to as dP and dQ29164 respectively. Therefore we now have:29165 y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n29166 Since we'll be reducing x^dP by modulo p (same for q) we can also29167 reduce x by p (and q respectively) before hand. Therefore, let29168 xp = ((x mod p)^dP mod p), and29169 xq = ((x mod q)^dQ mod q), yielding:29170 y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n29171 This can be further reduced to a simple algorithm that only29172 requires 1 inverse (the q inverse is used) to be used and stored.29173 The algorithm is called Garner's algorithm. If qInv is the29174 inverse of q, we simply calculate:29175 y = (qInv*(xp - xq) mod p) * q + xq29176 However, there are two further complications. First, we need to29177 ensure that xp > xq to prevent signed BigIntegers from being used29178 so we add p until this is true (since we will be mod'ing with29179 p anyway). Then, there is a known timing attack on algorithms29180 using the CRT. To mitigate this risk, "cryptographic blinding"29181 should be used. This requires simply generating a random number r29182 between 0 and n-1 and its inverse and multiplying x by r^e before29183 calculating y and then multiplying y by r^-1 afterwards. Note that29184 r must be coprime with n (gcd(r, n) === 1) in order to have an29185 inverse.29186 */29187 // cryptographic blinding29188 var r;29189 do {29190 r = new BigInteger(29191 forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)),29192 16);29193 } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));29194 x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);29195 // calculate xp and xq29196 var xp = x.mod(key.p).modPow(key.dP, key.p);29197 var xq = x.mod(key.q).modPow(key.dQ, key.q);29198 // xp must be larger than xq to avoid signed bit usage29199 while(xp.compareTo(xq) < 0) {29200 xp = xp.add(key.p);29201 }29202 // do last step29203 var y = xp.subtract(xq)29204 .multiply(key.qInv).mod(key.p)29205 .multiply(key.q).add(xq);29206 // remove effect of random for cryptographic blinding29207 y = y.multiply(r.modInverse(key.n)).mod(key.n);29208 return y;29209};29210/**29211 * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or29212 * 'encrypt' on a public key object instead.29213 *29214 * Performs RSA encryption.29215 *29216 * The parameter bt controls whether to put padding bytes before the29217 * message passed in. Set bt to either true or false to disable padding29218 * completely (in order to handle e.g. EMSA-PSS encoding seperately before),29219 * signaling whether the encryption operation is a public key operation29220 * (i.e. encrypting data) or not, i.e. private key operation (data signing).29221 *29222 * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x0129223 * (for signing) or 0x02 (for encryption). The key operation mode (private29224 * or public) is derived from this flag in that case).29225 *29226 * @param m the message to encrypt as a byte string.29227 * @param key the RSA key to use.29228 * @param bt for PKCS#1 v1.5 padding, the block type to use29229 * (0x01 for private key, 0x02 for public),29230 * to disable padding: true = public key, false = private key.29231 *29232 * @return the encrypted bytes as a string.29233 */29234pki.rsa.encrypt = function(m, key, bt) {29235 var pub = bt;29236 var eb;29237 // get the length of the modulus in bytes29238 var k = Math.ceil(key.n.bitLength() / 8);29239 if(bt !== false && bt !== true) {29240 // legacy, default to PKCS#1 v1.5 padding29241 pub = (bt === 0x02);29242 eb = _encodePkcs1_v1_5(m, key, bt);29243 } else {29244 eb = forge.util.createBuffer();29245 eb.putBytes(m);29246 }29247 // load encryption block as big integer 'x'29248 // FIXME: hex conversion inefficient, get BigInteger w/byte strings29249 var x = new BigInteger(eb.toHex(), 16);29250 // do RSA encryption29251 var y = _modPow(x, key, pub);29252 // convert y into the encrypted data byte string, if y is shorter in29253 // bytes than k, then prepend zero bytes to fill up ed29254 // FIXME: hex conversion inefficient, get BigInteger w/byte strings29255 var yhex = y.toString(16);29256 var ed = forge.util.createBuffer();29257 var zeros = k - Math.ceil(yhex.length / 2);29258 while(zeros > 0) {29259 ed.putByte(0x00);29260 --zeros;29261 }29262 ed.putBytes(forge.util.hexToBytes(yhex));29263 return ed.getBytes();29264};29265/**29266 * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or29267 * 'verify' on a public key object instead.29268 *29269 * Performs RSA decryption.29270 *29271 * The parameter ml controls whether to apply PKCS#1 v1.5 padding29272 * or not. Set ml = false to disable padding removal completely29273 * (in order to handle e.g. EMSA-PSS later on) and simply pass back29274 * the RSA encryption block.29275 *29276 * @param ed the encrypted data to decrypt in as a byte string.29277 * @param key the RSA key to use.29278 * @param pub true for a public key operation, false for private.29279 * @param ml the message length, if known, false to disable padding.29280 *29281 * @return the decrypted message as a byte string.29282 */29283pki.rsa.decrypt = function(ed, key, pub, ml) {29284 // get the length of the modulus in bytes29285 var k = Math.ceil(key.n.bitLength() / 8);29286 // error if the length of the encrypted data ED is not k29287 if(ed.length !== k) {29288 var error = new Error('Encrypted message length is invalid.');29289 error.length = ed.length;29290 error.expected = k;29291 throw error;29292 }29293 // convert encrypted data into a big integer29294 // FIXME: hex conversion inefficient, get BigInteger w/byte strings29295 var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16);29296 // y must be less than the modulus or it wasn't the result of29297 // a previous mod operation (encryption) using that modulus29298 if(y.compareTo(key.n) >= 0) {29299 throw new Error('Encrypted message is invalid.');29300 }29301 // do RSA decryption29302 var x = _modPow(y, key, pub);29303 // create the encryption block, if x is shorter in bytes than k, then29304 // prepend zero bytes to fill up eb29305 // FIXME: hex conversion inefficient, get BigInteger w/byte strings29306 var xhex = x.toString(16);29307 var eb = forge.util.createBuffer();29308 var zeros = k - Math.ceil(xhex.length / 2);29309 while(zeros > 0) {29310 eb.putByte(0x00);29311 --zeros;29312 }29313 eb.putBytes(forge.util.hexToBytes(xhex));29314 if(ml !== false) {29315 // legacy, default to PKCS#1 v1.5 padding29316 return _decodePkcs1_v1_5(eb.getBytes(), key, pub);29317 }29318 // return message29319 return eb.getBytes();29320};29321/**29322 * Creates an RSA key-pair generation state object. It is used to allow29323 * key-generation to be performed in steps. It also allows for a UI to29324 * display progress updates.29325 *29326 * @param bits the size for the private key in bits, defaults to 2048.29327 * @param e the public exponent to use, defaults to 65537 (0x10001).29328 * @param [options] the options to use.29329 * prng a custom crypto-secure pseudo-random number generator to use,29330 * that must define "getBytesSync".29331 * algorithm the algorithm to use (default: 'PRIMEINC').29332 *29333 * @return the state object to use to generate the key-pair.29334 */29335pki.rsa.createKeyPairGenerationState = function(bits, e, options) {29336 // TODO: migrate step-based prime generation code to forge.prime29337 // set default bits29338 if(typeof(bits) === 'string') {29339 bits = parseInt(bits, 10);29340 }29341 bits = bits || 2048;29342 // create prng with api that matches BigInteger secure random29343 options = options || {};29344 var prng = options.prng || forge.random;29345 var rng = {29346 // x is an array to fill with bytes29347 nextBytes: function(x) {29348 var b = prng.getBytesSync(x.length);29349 for(var i = 0; i < x.length; ++i) {29350 x[i] = b.charCodeAt(i);29351 }29352 }29353 };29354 var algorithm = options.algorithm || 'PRIMEINC';29355 // create PRIMEINC algorithm state29356 var rval;29357 if(algorithm === 'PRIMEINC') {29358 rval = {29359 algorithm: algorithm,29360 state: 0,29361 bits: bits,29362 rng: rng,29363 eInt: e || 65537,29364 e: new BigInteger(null),29365 p: null,29366 q: null,29367 qBits: bits >> 1,29368 pBits: bits - (bits >> 1),29369 pqState: 0,29370 num: null,29371 keys: null29372 };29373 rval.e.fromInt(rval.eInt);29374 } else {29375 throw new Error('Invalid key generation algorithm: ' + algorithm);29376 }29377 return rval;29378};29379/**29380 * Attempts to runs the key-generation algorithm for at most n seconds29381 * (approximately) using the given state. When key-generation has completed,29382 * the keys will be stored in state.keys.29383 *29384 * To use this function to update a UI while generating a key or to prevent29385 * causing browser lockups/warnings, set "n" to a value other than 0. A29386 * simple pattern for generating a key and showing a progress indicator is:29387 *29388 * var state = pki.rsa.createKeyPairGenerationState(2048);29389 * var step = function() {29390 * // step key-generation, run algorithm for 100 ms, repeat29391 * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {29392 * setTimeout(step, 1);29393 * } else {29394 * // key-generation complete29395 * // TODO: turn off progress indicator here29396 * // TODO: use the generated key-pair in "state.keys"29397 * }29398 * };29399 * // TODO: turn on progress indicator here29400 * setTimeout(step, 0);29401 *29402 * @param state the state to use.29403 * @param n the maximum number of milliseconds to run the algorithm for, 029404 * to run the algorithm to completion.29405 *29406 * @return true if the key-generation completed, false if not.29407 */29408pki.rsa.stepKeyPairGenerationState = function(state, n) {29409 // set default algorithm if not set29410 if(!('algorithm' in state)) {29411 state.algorithm = 'PRIMEINC';29412 }29413 // TODO: migrate step-based prime generation code to forge.prime29414 // TODO: abstract as PRIMEINC algorithm29415 // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)29416 // with some minor optimizations and designed to run in steps29417 // local state vars29418 var THIRTY = new BigInteger(null);29419 THIRTY.fromInt(30);29420 var deltaIdx = 0;29421 var op_or = function(x, y) {return x | y;};29422 // keep stepping until time limit is reached or done29423 var t1 = +new Date();29424 var t2;29425 var total = 0;29426 while(state.keys === null && (n <= 0 || total < n)) {29427 // generate p or q29428 if(state.state === 0) {29429 /* Note: All primes are of the form:29430 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i29431 When we generate a random number, we always align it at 30k + 1. Each29432 time the number is determined not to be prime we add to get to the29433 next 'i', eg: if the number was at 30k + 1 we add 6. */29434 var bits = (state.p === null) ? state.pBits : state.qBits;29435 var bits1 = bits - 1;29436 // get a random number29437 if(state.pqState === 0) {29438 state.num = new BigInteger(bits, state.rng);29439 // force MSB set29440 if(!state.num.testBit(bits1)) {29441 state.num.bitwiseTo(29442 BigInteger.ONE.shiftLeft(bits1), op_or, state.num);29443 }29444 // align number on 30k+1 boundary29445 state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);29446 deltaIdx = 0;29447 ++state.pqState;29448 } else if(state.pqState === 1) {29449 // try to make the number a prime29450 if(state.num.bitLength() > bits) {29451 // overflow, try again29452 state.pqState = 0;29453 // do primality test29454 } else if(state.num.isProbablePrime(29455 _getMillerRabinTests(state.num.bitLength()))) {29456 ++state.pqState;29457 } else {29458 // get next potential prime29459 state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);29460 }29461 } else if(state.pqState === 2) {29462 // ensure number is coprime with e29463 state.pqState =29464 (state.num.subtract(BigInteger.ONE).gcd(state.e)29465 .compareTo(BigInteger.ONE) === 0) ? 3 : 0;29466 } else if(state.pqState === 3) {29467 // store p or q29468 state.pqState = 0;29469 if(state.p === null) {29470 state.p = state.num;29471 } else {29472 state.q = state.num;29473 }29474 // advance state if both p and q are ready29475 if(state.p !== null && state.q !== null) {29476 ++state.state;29477 }29478 state.num = null;29479 }29480 } else if(state.state === 1) {29481 // ensure p is larger than q (swap them if not)29482 if(state.p.compareTo(state.q) < 0) {29483 state.num = state.p;29484 state.p = state.q;29485 state.q = state.num;29486 }29487 ++state.state;29488 } else if(state.state === 2) {29489 // compute phi: (p - 1)(q - 1) (Euler's totient function)29490 state.p1 = state.p.subtract(BigInteger.ONE);29491 state.q1 = state.q.subtract(BigInteger.ONE);29492 state.phi = state.p1.multiply(state.q1);29493 ++state.state;29494 } else if(state.state === 3) {29495 // ensure e and phi are coprime29496 if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {29497 // phi and e are coprime, advance29498 ++state.state;29499 } else {29500 // phi and e aren't coprime, so generate a new p and q29501 state.p = null;29502 state.q = null;29503 state.state = 0;29504 }29505 } else if(state.state === 4) {29506 // create n, ensure n is has the right number of bits29507 state.n = state.p.multiply(state.q);29508 // ensure n is right number of bits29509 if(state.n.bitLength() === state.bits) {29510 // success, advance29511 ++state.state;29512 } else {29513 // failed, get new q29514 state.q = null;29515 state.state = 0;29516 }29517 } else if(state.state === 5) {29518 // set keys29519 var d = state.e.modInverse(state.phi);29520 state.keys = {29521 privateKey: pki.rsa.setPrivateKey(29522 state.n, state.e, d, state.p, state.q,29523 d.mod(state.p1), d.mod(state.q1),29524 state.q.modInverse(state.p)),29525 publicKey: pki.rsa.setPublicKey(state.n, state.e)29526 };29527 }29528 // update timing29529 t2 = +new Date();29530 total += t2 - t1;29531 t1 = t2;29532 }29533 return state.keys !== null;29534};29535/**29536 * Generates an RSA public-private key pair in a single call.29537 *29538 * To generate a key-pair in steps (to allow for progress updates and to29539 * prevent blocking or warnings in slow browsers) then use the key-pair29540 * generation state functions.29541 *29542 * To generate a key-pair asynchronously (either through web-workers, if29543 * available, or by breaking up the work on the main thread), pass a29544 * callback function.29545 *29546 * @param [bits] the size for the private key in bits, defaults to 2048.29547 * @param [e] the public exponent to use, defaults to 65537.29548 * @param [options] options for key-pair generation, if given then 'bits'29549 * and 'e' must *not* be given:29550 * bits the size for the private key in bits, (default: 2048).29551 * e the public exponent to use, (default: 65537 (0x10001)).29552 * workerScript the worker script URL.29553 * workers the number of web workers (if supported) to use,29554 * (default: 2).29555 * workLoad the size of the work load, ie: number of possible prime29556 * numbers for each web worker to check per work assignment,29557 * (default: 100).29558 * prng a custom crypto-secure pseudo-random number generator to use,29559 * that must define "getBytesSync". Disables use of native APIs.29560 * algorithm the algorithm to use (default: 'PRIMEINC').29561 * @param [callback(err, keypair)] called once the operation completes.29562 *29563 * @return an object with privateKey and publicKey properties.29564 */29565pki.rsa.generateKeyPair = function(bits, e, options, callback) {29566 // (bits), (options), (callback)29567 if(arguments.length === 1) {29568 if(typeof bits === 'object') {29569 options = bits;29570 bits = undefined;29571 } else if(typeof bits === 'function') {29572 callback = bits;29573 bits = undefined;29574 }29575 } else if(arguments.length === 2) {29576 // (bits, e), (bits, options), (bits, callback), (options, callback)29577 if(typeof bits === 'number') {29578 if(typeof e === 'function') {29579 callback = e;29580 e = undefined;29581 } else if(typeof e !== 'number') {29582 options = e;29583 e = undefined;29584 }29585 } else {29586 options = bits;29587 callback = e;29588 bits = undefined;29589 e = undefined;29590 }29591 } else if(arguments.length === 3) {29592 // (bits, e, options), (bits, e, callback), (bits, options, callback)29593 if(typeof e === 'number') {29594 if(typeof options === 'function') {29595 callback = options;29596 options = undefined;29597 }29598 } else {29599 callback = options;29600 options = e;29601 e = undefined;29602 }29603 }29604 options = options || {};29605 if(bits === undefined) {29606 bits = options.bits || 2048;29607 }29608 if(e === undefined) {29609 e = options.e || 0x10001;29610 }29611 // use native code if permitted, available, and parameters are acceptable29612 if(!forge.options.usePureJavaScript && !options.prng &&29613 bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {29614 if(callback) {29615 // try native async29616 if(_detectNodeCrypto('generateKeyPair')) {29617 return _crypto.generateKeyPair('rsa', {29618 modulusLength: bits,29619 publicExponent: e,29620 publicKeyEncoding: {29621 type: 'spki',29622 format: 'pem'29623 },29624 privateKeyEncoding: {29625 type: 'pkcs8',29626 format: 'pem'29627 }29628 }, function(err, pub, priv) {29629 if(err) {29630 return callback(err);29631 }29632 callback(null, {29633 privateKey: pki.privateKeyFromPem(priv),29634 publicKey: pki.publicKeyFromPem(pub)29635 });29636 });29637 }29638 if(_detectSubtleCrypto('generateKey') &&29639 _detectSubtleCrypto('exportKey')) {29640 // use standard native generateKey29641 return util.globalScope.crypto.subtle.generateKey({29642 name: 'RSASSA-PKCS1-v1_5',29643 modulusLength: bits,29644 publicExponent: _intToUint8Array(e),29645 hash: {name: 'SHA-256'}29646 }, true /* key can be exported*/, ['sign', 'verify'])29647 .then(function(pair) {29648 return util.globalScope.crypto.subtle.exportKey(29649 'pkcs8', pair.privateKey);29650 // avoiding catch(function(err) {...}) to support IE <= 829651 }).then(undefined, function(err) {29652 callback(err);29653 }).then(function(pkcs8) {29654 if(pkcs8) {29655 var privateKey = pki.privateKeyFromAsn1(29656 asn1.fromDer(forge.util.createBuffer(pkcs8)));29657 callback(null, {29658 privateKey: privateKey,29659 publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)29660 });29661 }29662 });29663 }29664 if(_detectSubtleMsCrypto('generateKey') &&29665 _detectSubtleMsCrypto('exportKey')) {29666 var genOp = util.globalScope.msCrypto.subtle.generateKey({29667 name: 'RSASSA-PKCS1-v1_5',29668 modulusLength: bits,29669 publicExponent: _intToUint8Array(e),29670 hash: {name: 'SHA-256'}29671 }, true /* key can be exported*/, ['sign', 'verify']);29672 genOp.oncomplete = function(e) {29673 var pair = e.target.result;29674 var exportOp = util.globalScope.msCrypto.subtle.exportKey(29675 'pkcs8', pair.privateKey);29676 exportOp.oncomplete = function(e) {29677 var pkcs8 = e.target.result;29678 var privateKey = pki.privateKeyFromAsn1(29679 asn1.fromDer(forge.util.createBuffer(pkcs8)));29680 callback(null, {29681 privateKey: privateKey,29682 publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e)29683 });29684 };29685 exportOp.onerror = function(err) {29686 callback(err);29687 };29688 };29689 genOp.onerror = function(err) {29690 callback(err);29691 };29692 return;29693 }29694 } else {29695 // try native sync29696 if(_detectNodeCrypto('generateKeyPairSync')) {29697 var keypair = _crypto.generateKeyPairSync('rsa', {29698 modulusLength: bits,29699 publicExponent: e,29700 publicKeyEncoding: {29701 type: 'spki',29702 format: 'pem'29703 },29704 privateKeyEncoding: {29705 type: 'pkcs8',29706 format: 'pem'29707 }29708 });29709 return {29710 privateKey: pki.privateKeyFromPem(keypair.privateKey),29711 publicKey: pki.publicKeyFromPem(keypair.publicKey)29712 };29713 }29714 }29715 }29716 // use JavaScript implementation29717 var state = pki.rsa.createKeyPairGenerationState(bits, e, options);29718 if(!callback) {29719 pki.rsa.stepKeyPairGenerationState(state, 0);29720 return state.keys;29721 }29722 _generateKeyPair(state, options, callback);29723};29724/**29725 * Sets an RSA public key from BigIntegers modulus and exponent.29726 *29727 * @param n the modulus.29728 * @param e the exponent.29729 *29730 * @return the public key.29731 */29732pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {29733 var key = {29734 n: n,29735 e: e29736 };29737 /**29738 * Encrypts the given data with this public key. Newer applications29739 * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for29740 * legacy applications.29741 *29742 * @param data the byte string to encrypt.29743 * @param scheme the encryption scheme to use:29744 * 'RSAES-PKCS1-V1_5' (default),29745 * 'RSA-OAEP',29746 * 'RAW', 'NONE', or null to perform raw RSA encryption,29747 * an object with an 'encode' property set to a function29748 * with the signature 'function(data, key)' that returns29749 * a binary-encoded string representing the encoded data.29750 * @param schemeOptions any scheme-specific options.29751 *29752 * @return the encrypted byte string.29753 */29754 key.encrypt = function(data, scheme, schemeOptions) {29755 if(typeof scheme === 'string') {29756 scheme = scheme.toUpperCase();29757 } else if(scheme === undefined) {29758 scheme = 'RSAES-PKCS1-V1_5';29759 }29760 if(scheme === 'RSAES-PKCS1-V1_5') {29761 scheme = {29762 encode: function(m, key, pub) {29763 return _encodePkcs1_v1_5(m, key, 0x02).getBytes();29764 }29765 };29766 } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {29767 scheme = {29768 encode: function(m, key) {29769 return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions);29770 }29771 };29772 } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {29773 scheme = {encode: function(e) {return e;}};29774 } else if(typeof scheme === 'string') {29775 throw new Error('Unsupported encryption scheme: "' + scheme + '".');29776 }29777 // do scheme-based encoding then rsa encryption29778 var e = scheme.encode(data, key, true);29779 return pki.rsa.encrypt(e, key, true);29780 };29781 /**29782 * Verifies the given signature against the given digest.29783 *29784 * PKCS#1 supports multiple (currently two) signature schemes:29785 * RSASSA-PKCS1-V1_5 and RSASSA-PSS.29786 *29787 * By default this implementation uses the "old scheme", i.e.29788 * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the29789 * signature is an OCTET STRING that holds a DigestInfo.29790 *29791 * DigestInfo ::= SEQUENCE {29792 * digestAlgorithm DigestAlgorithmIdentifier,29793 * digest Digest29794 * }29795 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier29796 * Digest ::= OCTET STRING29797 *29798 * To perform PSS signature verification, provide an instance29799 * of Forge PSS object as the scheme parameter.29800 *29801 * @param digest the message digest hash to compare against the signature,29802 * as a binary-encoded string.29803 * @param signature the signature to verify, as a binary-encoded string.29804 * @param scheme signature verification scheme to use:29805 * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,29806 * a Forge PSS object for RSASSA-PSS,29807 * 'NONE' or null for none, DigestInfo will not be expected, but29808 * PKCS#1 v1.5 padding will still be used.29809 * @param options optional verify options29810 * _parseAllDigestBytes testing flag to control parsing of all29811 * digest bytes. Unsupported and not for general usage.29812 * (default: true)29813 *29814 * @return true if the signature was verified, false if not.29815 */29816 key.verify = function(digest, signature, scheme, options) {29817 if(typeof scheme === 'string') {29818 scheme = scheme.toUpperCase();29819 } else if(scheme === undefined) {29820 scheme = 'RSASSA-PKCS1-V1_5';29821 }29822 if(options === undefined) {29823 options = {29824 _parseAllDigestBytes: true29825 };29826 }29827 if(!('_parseAllDigestBytes' in options)) {29828 options._parseAllDigestBytes = true;29829 }29830 if(scheme === 'RSASSA-PKCS1-V1_5') {29831 scheme = {29832 verify: function(digest, d) {29833 // remove padding29834 d = _decodePkcs1_v1_5(d, key, true);29835 // d is ASN.1 BER-encoded DigestInfo29836 var obj = asn1.fromDer(d, {29837 parseAllBytes: options._parseAllDigestBytes29838 });29839 // validate DigestInfo29840 var capture = {};29841 var errors = [];29842 if(!asn1.validate(obj, digestInfoValidator, capture, errors)) {29843 var error = new Error(29844 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +29845 'DigestInfo value.');29846 error.errors = errors;29847 throw error;29848 }29849 // check hash algorithm identifier29850 // see PKCS1-v1-5DigestAlgorithms in RFC 801729851 // FIXME: add support to vaidator for strict value choices29852 var oid = asn1.derToOid(capture.algorithmIdentifier);29853 if(!(oid === forge.oids.md2 ||29854 oid === forge.oids.md5 ||29855 oid === forge.oids.sha1 ||29856 oid === forge.oids.sha224 ||29857 oid === forge.oids.sha256 ||29858 oid === forge.oids.sha384 ||29859 oid === forge.oids.sha512 ||29860 oid === forge.oids['sha512-224'] ||29861 oid === forge.oids['sha512-256'])) {29862 var error = new Error(29863 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');29864 error.oid = oid;29865 throw error;29866 }29867 // special check for md2 and md5 that NULL parameters exist29868 if(oid === forge.oids.md2 || oid === forge.oids.md5) {29869 if(!('parameters' in capture)) {29870 throw new Error(29871 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +29872 'DigestInfo value. ' +29873 'Missing algorithm identifer NULL parameters.');29874 }29875 }29876 // compare the given digest to the decrypted one29877 return digest === capture.digest;29878 }29879 };29880 } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {29881 scheme = {29882 verify: function(digest, d) {29883 // remove padding29884 d = _decodePkcs1_v1_5(d, key, true);29885 return digest === d;29886 }29887 };29888 }29889 // do rsa decryption w/o any decoding, then verify -- which does decoding29890 var d = pki.rsa.decrypt(signature, key, true, false);29891 return scheme.verify(digest, d, key.n.bitLength());29892 };29893 return key;29894};29895/**29896 * Sets an RSA private key from BigIntegers modulus, exponent, primes,29897 * prime exponents, and modular multiplicative inverse.29898 *29899 * @param n the modulus.29900 * @param e the public exponent.29901 * @param d the private exponent ((inverse of e) mod n).29902 * @param p the first prime.29903 * @param q the second prime.29904 * @param dP exponent1 (d mod (p-1)).29905 * @param dQ exponent2 (d mod (q-1)).29906 * @param qInv ((inverse of q) mod p)29907 *29908 * @return the private key.29909 */29910pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(29911 n, e, d, p, q, dP, dQ, qInv) {29912 var key = {29913 n: n,29914 e: e,29915 d: d,29916 p: p,29917 q: q,29918 dP: dP,29919 dQ: dQ,29920 qInv: qInv29921 };29922 /**29923 * Decrypts the given data with this private key. The decryption scheme29924 * must match the one used to encrypt the data.29925 *29926 * @param data the byte string to decrypt.29927 * @param scheme the decryption scheme to use:29928 * 'RSAES-PKCS1-V1_5' (default),29929 * 'RSA-OAEP',29930 * 'RAW', 'NONE', or null to perform raw RSA decryption.29931 * @param schemeOptions any scheme-specific options.29932 *29933 * @return the decrypted byte string.29934 */29935 key.decrypt = function(data, scheme, schemeOptions) {29936 if(typeof scheme === 'string') {29937 scheme = scheme.toUpperCase();29938 } else if(scheme === undefined) {29939 scheme = 'RSAES-PKCS1-V1_5';29940 }29941 // do rsa decryption w/o any decoding29942 var d = pki.rsa.decrypt(data, key, false, false);29943 if(scheme === 'RSAES-PKCS1-V1_5') {29944 scheme = {decode: _decodePkcs1_v1_5};29945 } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {29946 scheme = {29947 decode: function(d, key) {29948 return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions);29949 }29950 };29951 } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {29952 scheme = {decode: function(d) {return d;}};29953 } else {29954 throw new Error('Unsupported encryption scheme: "' + scheme + '".');29955 }29956 // decode according to scheme29957 return scheme.decode(d, key, false);29958 };29959 /**29960 * Signs the given digest, producing a signature.29961 *29962 * PKCS#1 supports multiple (currently two) signature schemes:29963 * RSASSA-PKCS1-V1_5 and RSASSA-PSS.29964 *29965 * By default this implementation uses the "old scheme", i.e.29966 * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide29967 * an instance of Forge PSS object as the scheme parameter.29968 *29969 * @param md the message digest object with the hash to sign.29970 * @param scheme the signature scheme to use:29971 * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,29972 * a Forge PSS object for RSASSA-PSS,29973 * 'NONE' or null for none, DigestInfo will not be used but29974 * PKCS#1 v1.5 padding will still be used.29975 *29976 * @return the signature as a byte string.29977 */29978 key.sign = function(md, scheme) {29979 /* Note: The internal implementation of RSA operations is being29980 transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy29981 code like the use of an encoding block identifier 'bt' will eventually29982 be removed. */29983 // private key operation29984 var bt = false;29985 if(typeof scheme === 'string') {29986 scheme = scheme.toUpperCase();29987 }29988 if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {29989 scheme = {encode: emsaPkcs1v15encode};29990 bt = 0x01;29991 } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {29992 scheme = {encode: function() {return md;}};29993 bt = 0x01;29994 }29995 // encode and then encrypt29996 var d = scheme.encode(md, key.n.bitLength());29997 return pki.rsa.encrypt(d, key, bt);29998 };29999 return key;30000};30001/**30002 * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.30003 *30004 * @param rsaKey the ASN.1 RSAPrivateKey.30005 *30006 * @return the ASN.1 PrivateKeyInfo.30007 */30008pki.wrapRsaPrivateKey = function(rsaKey) {30009 // PrivateKeyInfo30010 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [30011 // version (0)30012 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30013 asn1.integerToDer(0).getBytes()),30014 // privateKeyAlgorithm30015 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [30016 asn1.create(30017 asn1.Class.UNIVERSAL, asn1.Type.OID, false,30018 asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),30019 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')30020 ]),30021 // PrivateKey30022 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,30023 asn1.toDer(rsaKey).getBytes())30024 ]);30025};30026/**30027 * Converts a private key from an ASN.1 object.30028 *30029 * @param obj the ASN.1 representation of a PrivateKeyInfo containing an30030 * RSAPrivateKey or an RSAPrivateKey.30031 *30032 * @return the private key.30033 */30034pki.privateKeyFromAsn1 = function(obj) {30035 // get PrivateKeyInfo30036 var capture = {};30037 var errors = [];30038 if(asn1.validate(obj, privateKeyValidator, capture, errors)) {30039 obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey));30040 }30041 // get RSAPrivateKey30042 capture = {};30043 errors = [];30044 if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {30045 var error = new Error('Cannot read private key. ' +30046 'ASN.1 object does not contain an RSAPrivateKey.');30047 error.errors = errors;30048 throw error;30049 }30050 // Note: Version is currently ignored.30051 // capture.privateKeyVersion30052 // FIXME: inefficient, get a BigInteger that uses byte strings30053 var n, e, d, p, q, dP, dQ, qInv;30054 n = forge.util.createBuffer(capture.privateKeyModulus).toHex();30055 e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex();30056 d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex();30057 p = forge.util.createBuffer(capture.privateKeyPrime1).toHex();30058 q = forge.util.createBuffer(capture.privateKeyPrime2).toHex();30059 dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex();30060 dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex();30061 qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex();30062 // set private key30063 return pki.setRsaPrivateKey(30064 new BigInteger(n, 16),30065 new BigInteger(e, 16),30066 new BigInteger(d, 16),30067 new BigInteger(p, 16),30068 new BigInteger(q, 16),30069 new BigInteger(dP, 16),30070 new BigInteger(dQ, 16),30071 new BigInteger(qInv, 16));30072};30073/**30074 * Converts a private key to an ASN.1 RSAPrivateKey.30075 *30076 * @param key the private key.30077 *30078 * @return the ASN.1 representation of an RSAPrivateKey.30079 */30080pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) {30081 // RSAPrivateKey30082 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [30083 // version (0 = only 2 primes, 1 multiple primes)30084 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30085 asn1.integerToDer(0).getBytes()),30086 // modulus (n)30087 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30088 _bnToBytes(key.n)),30089 // publicExponent (e)30090 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30091 _bnToBytes(key.e)),30092 // privateExponent (d)30093 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30094 _bnToBytes(key.d)),30095 // privateKeyPrime1 (p)30096 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30097 _bnToBytes(key.p)),30098 // privateKeyPrime2 (q)30099 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30100 _bnToBytes(key.q)),30101 // privateKeyExponent1 (dP)30102 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30103 _bnToBytes(key.dP)),30104 // privateKeyExponent2 (dQ)30105 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30106 _bnToBytes(key.dQ)),30107 // coefficient (qInv)30108 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30109 _bnToBytes(key.qInv))30110 ]);30111};30112/**30113 * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.30114 *30115 * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.30116 *30117 * @return the public key.30118 */30119pki.publicKeyFromAsn1 = function(obj) {30120 // get SubjectPublicKeyInfo30121 var capture = {};30122 var errors = [];30123 if(asn1.validate(obj, publicKeyValidator, capture, errors)) {30124 // get oid30125 var oid = asn1.derToOid(capture.publicKeyOid);30126 if(oid !== pki.oids.rsaEncryption) {30127 var error = new Error('Cannot read public key. Unknown OID.');30128 error.oid = oid;30129 throw error;30130 }30131 obj = capture.rsaPublicKey;30132 }30133 // get RSA params30134 errors = [];30135 if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {30136 var error = new Error('Cannot read public key. ' +30137 'ASN.1 object does not contain an RSAPublicKey.');30138 error.errors = errors;30139 throw error;30140 }30141 // FIXME: inefficient, get a BigInteger that uses byte strings30142 var n = forge.util.createBuffer(capture.publicKeyModulus).toHex();30143 var e = forge.util.createBuffer(capture.publicKeyExponent).toHex();30144 // set public key30145 return pki.setRsaPublicKey(30146 new BigInteger(n, 16),30147 new BigInteger(e, 16));30148};30149/**30150 * Converts a public key to an ASN.1 SubjectPublicKeyInfo.30151 *30152 * @param key the public key.30153 *30154 * @return the asn1 representation of a SubjectPublicKeyInfo.30155 */30156pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) {30157 // SubjectPublicKeyInfo30158 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [30159 // AlgorithmIdentifier30160 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [30161 // algorithm30162 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,30163 asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),30164 // parameters (null)30165 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')30166 ]),30167 // subjectPublicKey30168 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [30169 pki.publicKeyToRSAPublicKey(key)30170 ])30171 ]);30172};30173/**30174 * Converts a public key to an ASN.1 RSAPublicKey.30175 *30176 * @param key the public key.30177 *30178 * @return the asn1 representation of a RSAPublicKey.30179 */30180pki.publicKeyToRSAPublicKey = function(key) {30181 // RSAPublicKey30182 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [30183 // modulus (n)30184 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30185 _bnToBytes(key.n)),30186 // publicExponent (e)30187 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,30188 _bnToBytes(key.e))30189 ]);30190};30191/**30192 * Encodes a message using PKCS#1 v1.5 padding.30193 *30194 * @param m the message to encode.30195 * @param key the RSA key to use.30196 * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x0230197 * (for encryption).30198 *30199 * @return the padded byte buffer.30200 */30201function _encodePkcs1_v1_5(m, key, bt) {30202 var eb = forge.util.createBuffer();30203 // get the length of the modulus in bytes30204 var k = Math.ceil(key.n.bitLength() / 8);30205 /* use PKCS#1 v1.5 padding */30206 if(m.length > (k - 11)) {30207 var error = new Error('Message is too long for PKCS#1 v1.5 padding.');30208 error.length = m.length;30209 error.max = k - 11;30210 throw error;30211 }30212 /* A block type BT, a padding string PS, and the data D shall be30213 formatted into an octet string EB, the encryption block:30214 EB = 00 || BT || PS || 00 || D30215 The block type BT shall be a single octet indicating the structure of30216 the encryption block. For this version of the document it shall have30217 value 00, 01, or 02. For a private-key operation, the block type30218 shall be 00 or 01. For a public-key operation, it shall be 02.30219 The padding string PS shall consist of k-3-||D|| octets. For block30220 type 00, the octets shall have value 00; for block type 01, they30221 shall have value FF; and for block type 02, they shall be30222 pseudorandomly generated and nonzero. This makes the length of the30223 encryption block EB equal to k. */30224 // build the encryption block30225 eb.putByte(0x00);30226 eb.putByte(bt);30227 // create the padding30228 var padNum = k - 3 - m.length;30229 var padByte;30230 // private key op30231 if(bt === 0x00 || bt === 0x01) {30232 padByte = (bt === 0x00) ? 0x00 : 0xFF;30233 for(var i = 0; i < padNum; ++i) {30234 eb.putByte(padByte);30235 }30236 } else {30237 // public key op30238 // pad with random non-zero values30239 while(padNum > 0) {30240 var numZeros = 0;30241 var padBytes = forge.random.getBytes(padNum);30242 for(var i = 0; i < padNum; ++i) {30243 padByte = padBytes.charCodeAt(i);30244 if(padByte === 0) {30245 ++numZeros;30246 } else {30247 eb.putByte(padByte);30248 }30249 }30250 padNum = numZeros;30251 }30252 }30253 // zero followed by message30254 eb.putByte(0x00);30255 eb.putBytes(m);30256 return eb;30257}30258/**30259 * Decodes a message using PKCS#1 v1.5 padding.30260 *30261 * @param em the message to decode.30262 * @param key the RSA key to use.30263 * @param pub true if the key is a public key, false if it is private.30264 * @param ml the message length, if specified.30265 *30266 * @return the decoded bytes.30267 */30268function _decodePkcs1_v1_5(em, key, pub, ml) {30269 // get the length of the modulus in bytes30270 var k = Math.ceil(key.n.bitLength() / 8);30271 /* It is an error if any of the following conditions occurs:30272 1. The encryption block EB cannot be parsed unambiguously.30273 2. The padding string PS consists of fewer than eight octets30274 or is inconsisent with the block type BT.30275 3. The decryption process is a public-key operation and the block30276 type BT is not 00 or 01, or the decryption process is a30277 private-key operation and the block type is not 02.30278 */30279 // parse the encryption block30280 var eb = forge.util.createBuffer(em);30281 var first = eb.getByte();30282 var bt = eb.getByte();30283 if(first !== 0x00 ||30284 (pub && bt !== 0x00 && bt !== 0x01) ||30285 (!pub && bt != 0x02) ||30286 (pub && bt === 0x00 && typeof(ml) === 'undefined')) {30287 throw new Error('Encryption block is invalid.');30288 }30289 var padNum = 0;30290 if(bt === 0x00) {30291 // check all padding bytes for 0x0030292 padNum = k - 3 - ml;30293 for(var i = 0; i < padNum; ++i) {30294 if(eb.getByte() !== 0x00) {30295 throw new Error('Encryption block is invalid.');30296 }30297 }30298 } else if(bt === 0x01) {30299 // find the first byte that isn't 0xFF, should be after all padding30300 padNum = 0;30301 while(eb.length() > 1) {30302 if(eb.getByte() !== 0xFF) {30303 --eb.read;30304 break;30305 }30306 ++padNum;30307 }30308 } else if(bt === 0x02) {30309 // look for 0x00 byte30310 padNum = 0;30311 while(eb.length() > 1) {30312 if(eb.getByte() === 0x00) {30313 --eb.read;30314 break;30315 }30316 ++padNum;30317 }30318 }30319 // zero must be 0x00 and padNum must be (k - 3 - message length)30320 var zero = eb.getByte();30321 if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {30322 throw new Error('Encryption block is invalid.');30323 }30324 return eb.getBytes();30325}30326/**30327 * Runs the key-generation algorithm asynchronously, either in the background30328 * via Web Workers, or using the main thread and setImmediate.30329 *30330 * @param state the key-pair generation state.30331 * @param [options] options for key-pair generation:30332 * workerScript the worker script URL.30333 * workers the number of web workers (if supported) to use,30334 * (default: 2, -1 to use estimated cores minus one).30335 * workLoad the size of the work load, ie: number of possible prime30336 * numbers for each web worker to check per work assignment,30337 * (default: 100).30338 * @param callback(err, keypair) called once the operation completes.30339 */30340function _generateKeyPair(state, options, callback) {30341 if(typeof options === 'function') {30342 callback = options;30343 options = {};30344 }30345 options = options || {};30346 var opts = {30347 algorithm: {30348 name: options.algorithm || 'PRIMEINC',30349 options: {30350 workers: options.workers || 2,30351 workLoad: options.workLoad || 100,30352 workerScript: options.workerScript30353 }30354 }30355 };30356 if('prng' in options) {30357 opts.prng = options.prng;30358 }30359 generate();30360 function generate() {30361 // find p and then q (done in series to simplify)30362 getPrime(state.pBits, function(err, num) {30363 if(err) {30364 return callback(err);30365 }30366 state.p = num;30367 if(state.q !== null) {30368 return finish(err, state.q);30369 }30370 getPrime(state.qBits, finish);30371 });30372 }30373 function getPrime(bits, callback) {30374 forge.prime.generateProbablePrime(bits, opts, callback);30375 }30376 function finish(err, num) {30377 if(err) {30378 return callback(err);30379 }30380 // set q30381 state.q = num;30382 // ensure p is larger than q (swap them if not)30383 if(state.p.compareTo(state.q) < 0) {30384 var tmp = state.p;30385 state.p = state.q;30386 state.q = tmp;30387 }30388 // ensure p is coprime with e30389 if(state.p.subtract(BigInteger.ONE).gcd(state.e)30390 .compareTo(BigInteger.ONE) !== 0) {30391 state.p = null;30392 generate();30393 return;30394 }30395 // ensure q is coprime with e30396 if(state.q.subtract(BigInteger.ONE).gcd(state.e)30397 .compareTo(BigInteger.ONE) !== 0) {30398 state.q = null;30399 getPrime(state.qBits, finish);30400 return;30401 }30402 // compute phi: (p - 1)(q - 1) (Euler's totient function)30403 state.p1 = state.p.subtract(BigInteger.ONE);30404 state.q1 = state.q.subtract(BigInteger.ONE);30405 state.phi = state.p1.multiply(state.q1);30406 // ensure e and phi are coprime30407 if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {30408 // phi and e aren't coprime, so generate a new p and q30409 state.p = state.q = null;30410 generate();30411 return;30412 }30413 // create n, ensure n is has the right number of bits30414 state.n = state.p.multiply(state.q);30415 if(state.n.bitLength() !== state.bits) {30416 // failed, get new q30417 state.q = null;30418 getPrime(state.qBits, finish);30419 return;30420 }30421 // set keys30422 var d = state.e.modInverse(state.phi);30423 state.keys = {30424 privateKey: pki.rsa.setPrivateKey(30425 state.n, state.e, d, state.p, state.q,30426 d.mod(state.p1), d.mod(state.q1),30427 state.q.modInverse(state.p)),30428 publicKey: pki.rsa.setPublicKey(state.n, state.e)30429 };30430 callback(null, state.keys);30431 }30432}30433/**30434 * Converts a positive BigInteger into 2's-complement big-endian bytes.30435 *30436 * @param b the big integer to convert.30437 *30438 * @return the bytes.30439 */30440function _bnToBytes(b) {30441 // prepend 0x00 if first byte >= 0x8030442 var hex = b.toString(16);30443 if(hex[0] >= '8') {30444 hex = '00' + hex;30445 }30446 var bytes = forge.util.hexToBytes(hex);30447 // ensure integer is minimally-encoded30448 if(bytes.length > 1 &&30449 // leading 0x00 for positive integer30450 ((bytes.charCodeAt(0) === 0 &&30451 (bytes.charCodeAt(1) & 0x80) === 0) ||30452 // leading 0xFF for negative integer30453 (bytes.charCodeAt(0) === 0xFF &&30454 (bytes.charCodeAt(1) & 0x80) === 0x80))) {30455 return bytes.substr(1);30456 }30457 return bytes;30458}30459/**30460 * Returns the required number of Miller-Rabin tests to generate a30461 * prime with an error probability of (1/2)^80.30462 *30463 * See Handbook of Applied Cryptography Chapter 4, Table 4.4.30464 *30465 * @param bits the bit size.30466 *30467 * @return the required number of iterations.30468 */30469function _getMillerRabinTests(bits) {30470 if(bits <= 100) return 27;30471 if(bits <= 150) return 18;30472 if(bits <= 200) return 15;30473 if(bits <= 250) return 12;30474 if(bits <= 300) return 9;30475 if(bits <= 350) return 8;30476 if(bits <= 400) return 7;30477 if(bits <= 500) return 6;30478 if(bits <= 600) return 5;30479 if(bits <= 800) return 4;30480 if(bits <= 1250) return 3;30481 return 2;30482}30483/**30484 * Performs feature detection on the Node crypto interface.30485 *30486 * @param fn the feature (function) to detect.30487 *30488 * @return true if detected, false if not.30489 */30490function _detectNodeCrypto(fn) {30491 return forge.util.isNodejs && typeof _crypto[fn] === 'function';30492}30493/**30494 * Performs feature detection on the SubtleCrypto interface.30495 *30496 * @param fn the feature (function) to detect.30497 *30498 * @return true if detected, false if not.30499 */30500function _detectSubtleCrypto(fn) {30501 return (typeof util.globalScope !== 'undefined' &&30502 typeof util.globalScope.crypto === 'object' &&30503 typeof util.globalScope.crypto.subtle === 'object' &&30504 typeof util.globalScope.crypto.subtle[fn] === 'function');30505}30506/**30507 * Performs feature detection on the deprecated Microsoft Internet Explorer30508 * outdated SubtleCrypto interface. This function should only be used after30509 * checking for the modern, standard SubtleCrypto interface.30510 *30511 * @param fn the feature (function) to detect.30512 *30513 * @return true if detected, false if not.30514 */30515function _detectSubtleMsCrypto(fn) {30516 return (typeof util.globalScope !== 'undefined' &&30517 typeof util.globalScope.msCrypto === 'object' &&30518 typeof util.globalScope.msCrypto.subtle === 'object' &&30519 typeof util.globalScope.msCrypto.subtle[fn] === 'function');30520}30521function _intToUint8Array(x) {30522 var bytes = forge.util.hexToBytes(x.toString(16));30523 var buffer = new Uint8Array(bytes.length);30524 for(var i = 0; i < bytes.length; ++i) {30525 buffer[i] = bytes.charCodeAt(i);30526 }30527 return buffer;30528}30529function _privateKeyFromJwk(jwk) {30530 if(jwk.kty !== 'RSA') {30531 throw new Error(30532 'Unsupported key algorithm "' + jwk.kty + '"; algorithm must be "RSA".');30533 }30534 return pki.setRsaPrivateKey(30535 _base64ToBigInt(jwk.n),30536 _base64ToBigInt(jwk.e),30537 _base64ToBigInt(jwk.d),30538 _base64ToBigInt(jwk.p),30539 _base64ToBigInt(jwk.q),30540 _base64ToBigInt(jwk.dp),30541 _base64ToBigInt(jwk.dq),30542 _base64ToBigInt(jwk.qi));30543}30544function _publicKeyFromJwk(jwk) {30545 if(jwk.kty !== 'RSA') {30546 throw new Error('Key algorithm must be "RSA".');30547 }30548 return pki.setRsaPublicKey(30549 _base64ToBigInt(jwk.n),30550 _base64ToBigInt(jwk.e));30551}30552function _base64ToBigInt(b64) {30553 return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16);30554}30555/***/ }),30556/***/ 279:30557/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {30558/**30559 * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.30560 *30561 * @author Dave Longley30562 *30563 * Copyright (c) 2010-2015 Digital Bazaar, Inc.30564 */30565var forge = __nccwpck_require__(9177);30566__nccwpck_require__(6231);30567__nccwpck_require__(8339);30568var sha1 = module.exports = forge.sha1 = forge.sha1 || {};30569forge.md.sha1 = forge.md.algorithms.sha1 = sha1;30570/**30571 * Creates a SHA-1 message digest object.30572 *30573 * @return a message digest object.30574 */30575sha1.create = function() {30576 // do initialization as necessary30577 if(!_initialized) {30578 _init();30579 }30580 // SHA-1 state contains five 32-bit integers30581 var _state = null;30582 // input buffer30583 var _input = forge.util.createBuffer();30584 // used for word storage30585 var _w = new Array(80);30586 // message digest object30587 var md = {30588 algorithm: 'sha1',30589 blockLength: 64,30590 digestLength: 20,30591 // 56-bit length of message so far (does not including padding)30592 messageLength: 0,30593 // true message length30594 fullMessageLength: null,30595 // size of message length in bytes30596 messageLengthSize: 830597 };30598 /**30599 * Starts the digest.30600 *30601 * @return this digest object.30602 */30603 md.start = function() {30604 // up to 56-bit message length for convenience30605 md.messageLength = 0;30606 // full message length (set md.messageLength64 for backwards-compatibility)30607 md.fullMessageLength = md.messageLength64 = [];30608 var int32s = md.messageLengthSize / 4;30609 for(var i = 0; i < int32s; ++i) {30610 md.fullMessageLength.push(0);30611 }30612 _input = forge.util.createBuffer();30613 _state = {30614 h0: 0x67452301,30615 h1: 0xEFCDAB89,30616 h2: 0x98BADCFE,30617 h3: 0x10325476,30618 h4: 0xC3D2E1F030619 };30620 return md;30621 };30622 // start digest automatically for first time30623 md.start();30624 /**30625 * Updates the digest with the given message input. The given input can30626 * treated as raw input (no encoding will be applied) or an encoding of30627 * 'utf8' maybe given to encode the input using UTF-8.30628 *30629 * @param msg the message input to update with.30630 * @param encoding the encoding to use (default: 'raw', other: 'utf8').30631 *30632 * @return this digest object.30633 */30634 md.update = function(msg, encoding) {30635 if(encoding === 'utf8') {30636 msg = forge.util.encodeUtf8(msg);30637 }30638 // update message length30639 var len = msg.length;30640 md.messageLength += len;30641 len = [(len / 0x100000000) >>> 0, len >>> 0];30642 for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {30643 md.fullMessageLength[i] += len[1];30644 len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);30645 md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;30646 len[0] = ((len[1] / 0x100000000) >>> 0);30647 }30648 // add bytes to input buffer30649 _input.putBytes(msg);30650 // process bytes30651 _update(_state, _w, _input);30652 // compact input buffer every 2K or if empty30653 if(_input.read > 2048 || _input.length() === 0) {30654 _input.compact();30655 }30656 return md;30657 };30658 /**30659 * Produces the digest.30660 *30661 * @return a byte buffer containing the digest value.30662 */30663 md.digest = function() {30664 /* Note: Here we copy the remaining bytes in the input buffer and30665 add the appropriate SHA-1 padding. Then we do the final update30666 on a copy of the state so that if the user wants to get30667 intermediate digests they can do so. */30668 /* Determine the number of bytes that must be added to the message30669 to ensure its length is congruent to 448 mod 512. In other words,30670 the data to be digested must be a multiple of 512 bits (or 128 bytes).30671 This data includes the message, some padding, and the length of the30672 message. Since the length of the message will be encoded as 8 bytes (6430673 bits), that means that the last segment of the data must have 56 bytes30674 (448 bits) of message and padding. Therefore, the length of the message30675 plus the padding must be congruent to 448 mod 512 because30676 512 - 128 = 448.30677 In order to fill up the message length it must be filled with30678 padding that begins with 1 bit followed by all 0 bits. Padding30679 must *always* be present, so if the message length is already30680 congruent to 448 mod 512, then 512 padding bits must be added. */30681 var finalBlock = forge.util.createBuffer();30682 finalBlock.putBytes(_input.bytes());30683 // compute remaining size to be digested (include message length size)30684 var remaining = (30685 md.fullMessageLength[md.fullMessageLength.length - 1] +30686 md.messageLengthSize);30687 // add padding for overflow blockSize - overflow30688 // _padding starts with 1 byte with first bit is set (byte value 128), then30689 // there may be up to (blockSize - 1) other pad bytes30690 var overflow = remaining & (md.blockLength - 1);30691 finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));30692 // serialize message length in bits in big-endian order; since length30693 // is stored in bytes we multiply by 8 and add carry from next int30694 var next, carry;30695 var bits = md.fullMessageLength[0] * 8;30696 for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {30697 next = md.fullMessageLength[i + 1] * 8;30698 carry = (next / 0x100000000) >>> 0;30699 bits += carry;30700 finalBlock.putInt32(bits >>> 0);30701 bits = next >>> 0;30702 }30703 finalBlock.putInt32(bits);30704 var s2 = {30705 h0: _state.h0,30706 h1: _state.h1,30707 h2: _state.h2,30708 h3: _state.h3,30709 h4: _state.h430710 };30711 _update(s2, _w, finalBlock);30712 var rval = forge.util.createBuffer();30713 rval.putInt32(s2.h0);30714 rval.putInt32(s2.h1);30715 rval.putInt32(s2.h2);30716 rval.putInt32(s2.h3);30717 rval.putInt32(s2.h4);30718 return rval;30719 };30720 return md;30721};30722// sha-1 padding bytes not initialized yet30723var _padding = null;30724var _initialized = false;30725/**30726 * Initializes the constant tables.30727 */30728function _init() {30729 // create padding30730 _padding = String.fromCharCode(128);30731 _padding += forge.util.fillString(String.fromCharCode(0x00), 64);30732 // now initialized30733 _initialized = true;30734}30735/**30736 * Updates a SHA-1 state with the given byte buffer.30737 *30738 * @param s the SHA-1 state to update.30739 * @param w the array to use to store words.30740 * @param bytes the byte buffer to update with.30741 */30742function _update(s, w, bytes) {30743 // consume 512 bit (64 byte) chunks30744 var t, a, b, c, d, e, f, i;30745 var len = bytes.length();30746 while(len >= 64) {30747 // the w array will be populated with sixteen 32-bit big-endian words30748 // and then extended into 80 32-bit words according to SHA-1 algorithm30749 // and for 32-79 using Max Locktyukhin's optimization30750 // initialize hash value for this chunk30751 a = s.h0;30752 b = s.h1;30753 c = s.h2;30754 d = s.h3;30755 e = s.h4;30756 // round 130757 for(i = 0; i < 16; ++i) {30758 t = bytes.getInt32();30759 w[i] = t;30760 f = d ^ (b & (c ^ d));30761 t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;30762 e = d;30763 d = c;30764 // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug30765 c = ((b << 30) | (b >>> 2)) >>> 0;30766 b = a;30767 a = t;30768 }30769 for(; i < 20; ++i) {30770 t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);30771 t = (t << 1) | (t >>> 31);30772 w[i] = t;30773 f = d ^ (b & (c ^ d));30774 t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;30775 e = d;30776 d = c;30777 // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug30778 c = ((b << 30) | (b >>> 2)) >>> 0;30779 b = a;30780 a = t;30781 }30782 // round 230783 for(; i < 32; ++i) {30784 t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);30785 t = (t << 1) | (t >>> 31);30786 w[i] = t;30787 f = b ^ c ^ d;30788 t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;30789 e = d;30790 d = c;30791 // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug30792 c = ((b << 30) | (b >>> 2)) >>> 0;30793 b = a;30794 a = t;30795 }30796 for(; i < 40; ++i) {30797 t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);30798 t = (t << 2) | (t >>> 30);30799 w[i] = t;30800 f = b ^ c ^ d;30801 t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;30802 e = d;30803 d = c;30804 // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug30805 c = ((b << 30) | (b >>> 2)) >>> 0;30806 b = a;30807 a = t;30808 }30809 // round 330810 for(; i < 60; ++i) {30811 t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);30812 t = (t << 2) | (t >>> 30);30813 w[i] = t;30814 f = (b & c) | (d & (b ^ c));30815 t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;30816 e = d;30817 d = c;30818 // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug30819 c = ((b << 30) | (b >>> 2)) >>> 0;30820 b = a;30821 a = t;30822 }30823 // round 430824 for(; i < 80; ++i) {30825 t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);30826 t = (t << 2) | (t >>> 30);30827 w[i] = t;30828 f = b ^ c ^ d;30829 t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;30830 e = d;30831 d = c;30832 // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug30833 c = ((b << 30) | (b >>> 2)) >>> 0;30834 b = a;30835 a = t;30836 }30837 // update hash state30838 s.h0 = (s.h0 + a) | 0;30839 s.h1 = (s.h1 + b) | 0;30840 s.h2 = (s.h2 + c) | 0;30841 s.h3 = (s.h3 + d) | 0;30842 s.h4 = (s.h4 + e) | 0;30843 len -= 64;30844 }30845}30846/***/ }),30847/***/ 4086:30848/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {30849/**30850 * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.30851 *30852 * See FIPS 180-2 for details.30853 *30854 * @author Dave Longley30855 *30856 * Copyright (c) 2010-2015 Digital Bazaar, Inc.30857 */30858var forge = __nccwpck_require__(9177);30859__nccwpck_require__(6231);30860__nccwpck_require__(8339);30861var sha256 = module.exports = forge.sha256 = forge.sha256 || {};30862forge.md.sha256 = forge.md.algorithms.sha256 = sha256;30863/**30864 * Creates a SHA-256 message digest object.30865 *30866 * @return a message digest object.30867 */30868sha256.create = function() {30869 // do initialization as necessary30870 if(!_initialized) {30871 _init();30872 }30873 // SHA-256 state contains eight 32-bit integers30874 var _state = null;30875 // input buffer30876 var _input = forge.util.createBuffer();30877 // used for word storage30878 var _w = new Array(64);30879 // message digest object30880 var md = {30881 algorithm: 'sha256',30882 blockLength: 64,30883 digestLength: 32,30884 // 56-bit length of message so far (does not including padding)30885 messageLength: 0,30886 // true message length30887 fullMessageLength: null,30888 // size of message length in bytes30889 messageLengthSize: 830890 };30891 /**30892 * Starts the digest.30893 *30894 * @return this digest object.30895 */30896 md.start = function() {30897 // up to 56-bit message length for convenience30898 md.messageLength = 0;30899 // full message length (set md.messageLength64 for backwards-compatibility)30900 md.fullMessageLength = md.messageLength64 = [];30901 var int32s = md.messageLengthSize / 4;30902 for(var i = 0; i < int32s; ++i) {30903 md.fullMessageLength.push(0);30904 }30905 _input = forge.util.createBuffer();30906 _state = {30907 h0: 0x6A09E667,30908 h1: 0xBB67AE85,30909 h2: 0x3C6EF372,30910 h3: 0xA54FF53A,30911 h4: 0x510E527F,30912 h5: 0x9B05688C,30913 h6: 0x1F83D9AB,30914 h7: 0x5BE0CD1930915 };30916 return md;30917 };30918 // start digest automatically for first time30919 md.start();30920 /**30921 * Updates the digest with the given message input. The given input can30922 * treated as raw input (no encoding will be applied) or an encoding of30923 * 'utf8' maybe given to encode the input using UTF-8.30924 *30925 * @param msg the message input to update with.30926 * @param encoding the encoding to use (default: 'raw', other: 'utf8').30927 *30928 * @return this digest object.30929 */30930 md.update = function(msg, encoding) {30931 if(encoding === 'utf8') {30932 msg = forge.util.encodeUtf8(msg);30933 }30934 // update message length30935 var len = msg.length;30936 md.messageLength += len;30937 len = [(len / 0x100000000) >>> 0, len >>> 0];30938 for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {30939 md.fullMessageLength[i] += len[1];30940 len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);30941 md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;30942 len[0] = ((len[1] / 0x100000000) >>> 0);30943 }30944 // add bytes to input buffer30945 _input.putBytes(msg);30946 // process bytes30947 _update(_state, _w, _input);30948 // compact input buffer every 2K or if empty30949 if(_input.read > 2048 || _input.length() === 0) {30950 _input.compact();30951 }30952 return md;30953 };30954 /**30955 * Produces the digest.30956 *30957 * @return a byte buffer containing the digest value.30958 */30959 md.digest = function() {30960 /* Note: Here we copy the remaining bytes in the input buffer and30961 add the appropriate SHA-256 padding. Then we do the final update30962 on a copy of the state so that if the user wants to get30963 intermediate digests they can do so. */30964 /* Determine the number of bytes that must be added to the message30965 to ensure its length is congruent to 448 mod 512. In other words,30966 the data to be digested must be a multiple of 512 bits (or 128 bytes).30967 This data includes the message, some padding, and the length of the30968 message. Since the length of the message will be encoded as 8 bytes (6430969 bits), that means that the last segment of the data must have 56 bytes30970 (448 bits) of message and padding. Therefore, the length of the message30971 plus the padding must be congruent to 448 mod 512 because30972 512 - 128 = 448.30973 In order to fill up the message length it must be filled with30974 padding that begins with 1 bit followed by all 0 bits. Padding30975 must *always* be present, so if the message length is already30976 congruent to 448 mod 512, then 512 padding bits must be added. */30977 var finalBlock = forge.util.createBuffer();30978 finalBlock.putBytes(_input.bytes());30979 // compute remaining size to be digested (include message length size)30980 var remaining = (30981 md.fullMessageLength[md.fullMessageLength.length - 1] +30982 md.messageLengthSize);30983 // add padding for overflow blockSize - overflow30984 // _padding starts with 1 byte with first bit is set (byte value 128), then30985 // there may be up to (blockSize - 1) other pad bytes30986 var overflow = remaining & (md.blockLength - 1);30987 finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));30988 // serialize message length in bits in big-endian order; since length30989 // is stored in bytes we multiply by 8 and add carry from next int30990 var next, carry;30991 var bits = md.fullMessageLength[0] * 8;30992 for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {30993 next = md.fullMessageLength[i + 1] * 8;30994 carry = (next / 0x100000000) >>> 0;30995 bits += carry;30996 finalBlock.putInt32(bits >>> 0);30997 bits = next >>> 0;30998 }30999 finalBlock.putInt32(bits);31000 var s2 = {31001 h0: _state.h0,31002 h1: _state.h1,31003 h2: _state.h2,31004 h3: _state.h3,31005 h4: _state.h4,31006 h5: _state.h5,31007 h6: _state.h6,31008 h7: _state.h731009 };31010 _update(s2, _w, finalBlock);31011 var rval = forge.util.createBuffer();31012 rval.putInt32(s2.h0);31013 rval.putInt32(s2.h1);31014 rval.putInt32(s2.h2);31015 rval.putInt32(s2.h3);31016 rval.putInt32(s2.h4);31017 rval.putInt32(s2.h5);31018 rval.putInt32(s2.h6);31019 rval.putInt32(s2.h7);31020 return rval;31021 };31022 return md;31023};31024// sha-256 padding bytes not initialized yet31025var _padding = null;31026var _initialized = false;31027// table of constants31028var _k = null;31029/**31030 * Initializes the constant tables.31031 */31032function _init() {31033 // create padding31034 _padding = String.fromCharCode(128);31035 _padding += forge.util.fillString(String.fromCharCode(0x00), 64);31036 // create K table for SHA-25631037 _k = [31038 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,31039 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,31040 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,31041 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,31042 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,31043 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,31044 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,31045 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,31046 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,31047 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,31048 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,31049 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,31050 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,31051 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,31052 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,31053 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];31054 // now initialized31055 _initialized = true;31056}31057/**31058 * Updates a SHA-256 state with the given byte buffer.31059 *31060 * @param s the SHA-256 state to update.31061 * @param w the array to use to store words.31062 * @param bytes the byte buffer to update with.31063 */31064function _update(s, w, bytes) {31065 // consume 512 bit (64 byte) chunks31066 var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;31067 var len = bytes.length();31068 while(len >= 64) {31069 // the w array will be populated with sixteen 32-bit big-endian words31070 // and then extended into 64 32-bit words according to SHA-25631071 for(i = 0; i < 16; ++i) {31072 w[i] = bytes.getInt32();31073 }31074 for(; i < 64; ++i) {31075 // XOR word 2 words ago rot right 17, rot right 19, shft right 1031076 t1 = w[i - 2];31077 t1 =31078 ((t1 >>> 17) | (t1 << 15)) ^31079 ((t1 >>> 19) | (t1 << 13)) ^31080 (t1 >>> 10);31081 // XOR word 15 words ago rot right 7, rot right 18, shft right 331082 t2 = w[i - 15];31083 t2 =31084 ((t2 >>> 7) | (t2 << 25)) ^31085 ((t2 >>> 18) | (t2 << 14)) ^31086 (t2 >>> 3);31087 // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^3231088 w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;31089 }31090 // initialize hash value for this chunk31091 a = s.h0;31092 b = s.h1;31093 c = s.h2;31094 d = s.h3;31095 e = s.h4;31096 f = s.h5;31097 g = s.h6;31098 h = s.h7;31099 // round function31100 for(i = 0; i < 64; ++i) {31101 // Sum1(e)31102 s1 =31103 ((e >>> 6) | (e << 26)) ^31104 ((e >>> 11) | (e << 21)) ^31105 ((e >>> 25) | (e << 7));31106 // Ch(e, f, g) (optimized the same way as SHA-1)31107 ch = g ^ (e & (f ^ g));31108 // Sum0(a)31109 s0 =31110 ((a >>> 2) | (a << 30)) ^31111 ((a >>> 13) | (a << 19)) ^31112 ((a >>> 22) | (a << 10));31113 // Maj(a, b, c) (optimized the same way as SHA-1)31114 maj = (a & b) | (c & (a ^ b));31115 // main algorithm31116 t1 = h + s1 + ch + _k[i] + w[i];31117 t2 = s0 + maj;31118 h = g;31119 g = f;31120 f = e;31121 // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug31122 // can't truncate with `| 0`31123 e = (d + t1) >>> 0;31124 d = c;31125 c = b;31126 b = a;31127 // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug31128 // can't truncate with `| 0`31129 a = (t1 + t2) >>> 0;31130 }31131 // update hash state31132 s.h0 = (s.h0 + a) | 0;31133 s.h1 = (s.h1 + b) | 0;31134 s.h2 = (s.h2 + c) | 0;31135 s.h3 = (s.h3 + d) | 0;31136 s.h4 = (s.h4 + e) | 0;31137 s.h5 = (s.h5 + f) | 0;31138 s.h6 = (s.h6 + g) | 0;31139 s.h7 = (s.h7 + h) | 0;31140 len -= 64;31141 }31142}31143/***/ }),31144/***/ 9542:31145/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {31146/**31147 * Secure Hash Algorithm with a 1024-bit block size implementation.31148 *31149 * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For31150 * SHA-256 (block size 512 bits), see sha256.js.31151 *31152 * See FIPS 180-4 for details.31153 *31154 * @author Dave Longley31155 *31156 * Copyright (c) 2014-2015 Digital Bazaar, Inc.31157 */31158var forge = __nccwpck_require__(9177);31159__nccwpck_require__(6231);31160__nccwpck_require__(8339);31161var sha512 = module.exports = forge.sha512 = forge.sha512 || {};31162// SHA-51231163forge.md.sha512 = forge.md.algorithms.sha512 = sha512;31164// SHA-38431165var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {};31166sha384.create = function() {31167 return sha512.create('SHA-384');31168};31169forge.md.sha384 = forge.md.algorithms.sha384 = sha384;31170// SHA-512/25631171forge.sha512.sha256 = forge.sha512.sha256 || {31172 create: function() {31173 return sha512.create('SHA-512/256');31174 }31175};31176forge.md['sha512/256'] = forge.md.algorithms['sha512/256'] =31177 forge.sha512.sha256;31178// SHA-512/22431179forge.sha512.sha224 = forge.sha512.sha224 || {31180 create: function() {31181 return sha512.create('SHA-512/224');31182 }31183};31184forge.md['sha512/224'] = forge.md.algorithms['sha512/224'] =31185 forge.sha512.sha224;31186/**31187 * Creates a SHA-2 message digest object.31188 *31189 * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,31190 * SHA-512/256).31191 *31192 * @return a message digest object.31193 */31194sha512.create = function(algorithm) {31195 // do initialization as necessary31196 if(!_initialized) {31197 _init();31198 }31199 if(typeof algorithm === 'undefined') {31200 algorithm = 'SHA-512';31201 }31202 if(!(algorithm in _states)) {31203 throw new Error('Invalid SHA-512 algorithm: ' + algorithm);31204 }31205 // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)31206 var _state = _states[algorithm];31207 var _h = null;31208 // input buffer31209 var _input = forge.util.createBuffer();31210 // used for 64-bit word storage31211 var _w = new Array(80);31212 for(var wi = 0; wi < 80; ++wi) {31213 _w[wi] = new Array(2);31214 }31215 // determine digest length by algorithm name (default)31216 var digestLength = 64;31217 switch(algorithm) {31218 case 'SHA-384':31219 digestLength = 48;31220 break;31221 case 'SHA-512/256':31222 digestLength = 32;31223 break;31224 case 'SHA-512/224':31225 digestLength = 28;31226 break;31227 }31228 // message digest object31229 var md = {31230 // SHA-512 => sha51231231 algorithm: algorithm.replace('-', '').toLowerCase(),31232 blockLength: 128,31233 digestLength: digestLength,31234 // 56-bit length of message so far (does not including padding)31235 messageLength: 0,31236 // true message length31237 fullMessageLength: null,31238 // size of message length in bytes31239 messageLengthSize: 1631240 };31241 /**31242 * Starts the digest.31243 *31244 * @return this digest object.31245 */31246 md.start = function() {31247 // up to 56-bit message length for convenience31248 md.messageLength = 0;31249 // full message length (set md.messageLength128 for backwards-compatibility)31250 md.fullMessageLength = md.messageLength128 = [];31251 var int32s = md.messageLengthSize / 4;31252 for(var i = 0; i < int32s; ++i) {31253 md.fullMessageLength.push(0);31254 }31255 _input = forge.util.createBuffer();31256 _h = new Array(_state.length);31257 for(var i = 0; i < _state.length; ++i) {31258 _h[i] = _state[i].slice(0);31259 }31260 return md;31261 };31262 // start digest automatically for first time31263 md.start();31264 /**31265 * Updates the digest with the given message input. The given input can31266 * treated as raw input (no encoding will be applied) or an encoding of31267 * 'utf8' maybe given to encode the input using UTF-8.31268 *31269 * @param msg the message input to update with.31270 * @param encoding the encoding to use (default: 'raw', other: 'utf8').31271 *31272 * @return this digest object.31273 */31274 md.update = function(msg, encoding) {31275 if(encoding === 'utf8') {31276 msg = forge.util.encodeUtf8(msg);31277 }31278 // update message length31279 var len = msg.length;31280 md.messageLength += len;31281 len = [(len / 0x100000000) >>> 0, len >>> 0];31282 for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {31283 md.fullMessageLength[i] += len[1];31284 len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);31285 md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;31286 len[0] = ((len[1] / 0x100000000) >>> 0);31287 }31288 // add bytes to input buffer31289 _input.putBytes(msg);31290 // process bytes31291 _update(_h, _w, _input);31292 // compact input buffer every 2K or if empty31293 if(_input.read > 2048 || _input.length() === 0) {31294 _input.compact();31295 }31296 return md;31297 };31298 /**31299 * Produces the digest.31300 *31301 * @return a byte buffer containing the digest value.31302 */31303 md.digest = function() {31304 /* Note: Here we copy the remaining bytes in the input buffer and31305 add the appropriate SHA-512 padding. Then we do the final update31306 on a copy of the state so that if the user wants to get31307 intermediate digests they can do so. */31308 /* Determine the number of bytes that must be added to the message31309 to ensure its length is congruent to 896 mod 1024. In other words,31310 the data to be digested must be a multiple of 1024 bits (or 128 bytes).31311 This data includes the message, some padding, and the length of the31312 message. Since the length of the message will be encoded as 16 bytes (12831313 bits), that means that the last segment of the data must have 112 bytes31314 (896 bits) of message and padding. Therefore, the length of the message31315 plus the padding must be congruent to 896 mod 1024 because31316 1024 - 128 = 896.31317 In order to fill up the message length it must be filled with31318 padding that begins with 1 bit followed by all 0 bits. Padding31319 must *always* be present, so if the message length is already31320 congruent to 896 mod 1024, then 1024 padding bits must be added. */31321 var finalBlock = forge.util.createBuffer();31322 finalBlock.putBytes(_input.bytes());31323 // compute remaining size to be digested (include message length size)31324 var remaining = (31325 md.fullMessageLength[md.fullMessageLength.length - 1] +31326 md.messageLengthSize);31327 // add padding for overflow blockSize - overflow31328 // _padding starts with 1 byte with first bit is set (byte value 128), then31329 // there may be up to (blockSize - 1) other pad bytes31330 var overflow = remaining & (md.blockLength - 1);31331 finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));31332 // serialize message length in bits in big-endian order; since length31333 // is stored in bytes we multiply by 8 and add carry from next int31334 var next, carry;31335 var bits = md.fullMessageLength[0] * 8;31336 for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {31337 next = md.fullMessageLength[i + 1] * 8;31338 carry = (next / 0x100000000) >>> 0;31339 bits += carry;31340 finalBlock.putInt32(bits >>> 0);31341 bits = next >>> 0;31342 }31343 finalBlock.putInt32(bits);31344 var h = new Array(_h.length);31345 for(var i = 0; i < _h.length; ++i) {31346 h[i] = _h[i].slice(0);31347 }31348 _update(h, _w, finalBlock);31349 var rval = forge.util.createBuffer();31350 var hlen;31351 if(algorithm === 'SHA-512') {31352 hlen = h.length;31353 } else if(algorithm === 'SHA-384') {31354 hlen = h.length - 2;31355 } else {31356 hlen = h.length - 4;31357 }31358 for(var i = 0; i < hlen; ++i) {31359 rval.putInt32(h[i][0]);31360 if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {31361 rval.putInt32(h[i][1]);31362 }31363 }31364 return rval;31365 };31366 return md;31367};31368// sha-512 padding bytes not initialized yet31369var _padding = null;31370var _initialized = false;31371// table of constants31372var _k = null;31373// initial hash states31374var _states = null;31375/**31376 * Initializes the constant tables.31377 */31378function _init() {31379 // create padding31380 _padding = String.fromCharCode(128);31381 _padding += forge.util.fillString(String.fromCharCode(0x00), 128);31382 // create K table for SHA-51231383 _k = [31384 [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd],31385 [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc],31386 [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019],31387 [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118],31388 [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe],31389 [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2],31390 [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1],31391 [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694],31392 [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3],31393 [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65],31394 [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483],31395 [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5],31396 [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210],31397 [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4],31398 [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725],31399 [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70],31400 [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926],31401 [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df],31402 [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8],31403 [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b],31404 [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001],31405 [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30],31406 [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910],31407 [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8],31408 [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53],31409 [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8],31410 [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb],31411 [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3],31412 [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60],31413 [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec],31414 [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9],31415 [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b],31416 [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207],31417 [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178],31418 [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6],31419 [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b],31420 [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493],31421 [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c],31422 [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a],31423 [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817]31424 ];31425 // initial hash states31426 _states = {};31427 _states['SHA-512'] = [31428 [0x6a09e667, 0xf3bcc908],31429 [0xbb67ae85, 0x84caa73b],31430 [0x3c6ef372, 0xfe94f82b],31431 [0xa54ff53a, 0x5f1d36f1],31432 [0x510e527f, 0xade682d1],31433 [0x9b05688c, 0x2b3e6c1f],31434 [0x1f83d9ab, 0xfb41bd6b],31435 [0x5be0cd19, 0x137e2179]31436 ];31437 _states['SHA-384'] = [31438 [0xcbbb9d5d, 0xc1059ed8],31439 [0x629a292a, 0x367cd507],31440 [0x9159015a, 0x3070dd17],31441 [0x152fecd8, 0xf70e5939],31442 [0x67332667, 0xffc00b31],31443 [0x8eb44a87, 0x68581511],31444 [0xdb0c2e0d, 0x64f98fa7],31445 [0x47b5481d, 0xbefa4fa4]31446 ];31447 _states['SHA-512/256'] = [31448 [0x22312194, 0xFC2BF72C],31449 [0x9F555FA3, 0xC84C64C2],31450 [0x2393B86B, 0x6F53B151],31451 [0x96387719, 0x5940EABD],31452 [0x96283EE2, 0xA88EFFE3],31453 [0xBE5E1E25, 0x53863992],31454 [0x2B0199FC, 0x2C85B8AA],31455 [0x0EB72DDC, 0x81C52CA2]31456 ];31457 _states['SHA-512/224'] = [31458 [0x8C3D37C8, 0x19544DA2],31459 [0x73E19966, 0x89DCD4D6],31460 [0x1DFAB7AE, 0x32FF9C82],31461 [0x679DD514, 0x582F9FCF],31462 [0x0F6D2B69, 0x7BD44DA8],31463 [0x77E36F73, 0x04C48942],31464 [0x3F9D85A8, 0x6A1D36C8],31465 [0x1112E6AD, 0x91D692A1]31466 ];31467 // now initialized31468 _initialized = true;31469}31470/**31471 * Updates a SHA-512 state with the given byte buffer.31472 *31473 * @param s the SHA-512 state to update.31474 * @param w the array to use to store words.31475 * @param bytes the byte buffer to update with.31476 */31477function _update(s, w, bytes) {31478 // consume 512 bit (128 byte) chunks31479 var t1_hi, t1_lo;31480 var t2_hi, t2_lo;31481 var s0_hi, s0_lo;31482 var s1_hi, s1_lo;31483 var ch_hi, ch_lo;31484 var maj_hi, maj_lo;31485 var a_hi, a_lo;31486 var b_hi, b_lo;31487 var c_hi, c_lo;31488 var d_hi, d_lo;31489 var e_hi, e_lo;31490 var f_hi, f_lo;31491 var g_hi, g_lo;31492 var h_hi, h_lo;31493 var i, hi, lo, w2, w7, w15, w16;31494 var len = bytes.length();31495 while(len >= 128) {31496 // the w array will be populated with sixteen 64-bit big-endian words31497 // and then extended into 64 64-bit words according to SHA-51231498 for(i = 0; i < 16; ++i) {31499 w[i][0] = bytes.getInt32() >>> 0;31500 w[i][1] = bytes.getInt32() >>> 0;31501 }31502 for(; i < 80; ++i) {31503 // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)31504 w2 = w[i - 2];31505 hi = w2[0];31506 lo = w2[1];31507 // high bits31508 t1_hi = (31509 ((hi >>> 19) | (lo << 13)) ^ // ROTR 1931510 ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)31511 (hi >>> 6)) >>> 0; // SHR 631512 // low bits31513 t1_lo = (31514 ((hi << 13) | (lo >>> 19)) ^ // ROTR 1931515 ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)31516 ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 631517 // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)31518 w15 = w[i - 15];31519 hi = w15[0];31520 lo = w15[1];31521 // high bits31522 t2_hi = (31523 ((hi >>> 1) | (lo << 31)) ^ // ROTR 131524 ((hi >>> 8) | (lo << 24)) ^ // ROTR 831525 (hi >>> 7)) >>> 0; // SHR 731526 // low bits31527 t2_lo = (31528 ((hi << 31) | (lo >>> 1)) ^ // ROTR 131529 ((hi << 24) | (lo >>> 8)) ^ // ROTR 831530 ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 731531 // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)31532 w7 = w[i - 7];31533 w16 = w[i - 16];31534 lo = (t1_lo + w7[1] + t2_lo + w16[1]);31535 w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +31536 ((lo / 0x100000000) >>> 0)) >>> 0;31537 w[i][1] = lo >>> 0;31538 }31539 // initialize hash value for this chunk31540 a_hi = s[0][0];31541 a_lo = s[0][1];31542 b_hi = s[1][0];31543 b_lo = s[1][1];31544 c_hi = s[2][0];31545 c_lo = s[2][1];31546 d_hi = s[3][0];31547 d_lo = s[3][1];31548 e_hi = s[4][0];31549 e_lo = s[4][1];31550 f_hi = s[5][0];31551 f_lo = s[5][1];31552 g_hi = s[6][0];31553 g_lo = s[6][1];31554 h_hi = s[7][0];31555 h_lo = s[7][1];31556 // round function31557 for(i = 0; i < 80; ++i) {31558 // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)31559 s1_hi = (31560 ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 1431561 ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 1831562 ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)31563 s1_lo = (31564 ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 1431565 ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 1831566 ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)31567 // Ch(e, f, g) (optimized the same way as SHA-1)31568 ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;31569 ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;31570 // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)31571 s0_hi = (31572 ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 2831573 ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)31574 ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)31575 s0_lo = (31576 ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 2831577 ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)31578 ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)31579 // Maj(a, b, c) (optimized the same way as SHA-1)31580 maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;31581 maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;31582 // main algorithm31583 // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)31584 lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);31585 t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +31586 ((lo / 0x100000000) >>> 0)) >>> 0;31587 t1_lo = lo >>> 0;31588 // t2 = s0 + maj modulo 2^64 (carry lo overflow)31589 lo = s0_lo + maj_lo;31590 t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31591 t2_lo = lo >>> 0;31592 h_hi = g_hi;31593 h_lo = g_lo;31594 g_hi = f_hi;31595 g_lo = f_lo;31596 f_hi = e_hi;31597 f_lo = e_lo;31598 // e = (d + t1) modulo 2^64 (carry lo overflow)31599 lo = d_lo + t1_lo;31600 e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31601 e_lo = lo >>> 0;31602 d_hi = c_hi;31603 d_lo = c_lo;31604 c_hi = b_hi;31605 c_lo = b_lo;31606 b_hi = a_hi;31607 b_lo = a_lo;31608 // a = (t1 + t2) modulo 2^64 (carry lo overflow)31609 lo = t1_lo + t2_lo;31610 a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31611 a_lo = lo >>> 0;31612 }31613 // update hash state (additional modulo 2^64)31614 lo = s[0][1] + a_lo;31615 s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31616 s[0][1] = lo >>> 0;31617 lo = s[1][1] + b_lo;31618 s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31619 s[1][1] = lo >>> 0;31620 lo = s[2][1] + c_lo;31621 s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31622 s[2][1] = lo >>> 0;31623 lo = s[3][1] + d_lo;31624 s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31625 s[3][1] = lo >>> 0;31626 lo = s[4][1] + e_lo;31627 s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31628 s[4][1] = lo >>> 0;31629 lo = s[5][1] + f_lo;31630 s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31631 s[5][1] = lo >>> 0;31632 lo = s[6][1] + g_lo;31633 s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31634 s[6][1] = lo >>> 0;31635 lo = s[7][1] + h_lo;31636 s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;31637 s[7][1] = lo >>> 0;31638 len -= 128;31639 }31640}31641/***/ }),31642/***/ 4280:31643/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {31644/**31645 * Functions to output keys in SSH-friendly formats.31646 *31647 * This is part of the Forge project which may be used under the terms of31648 * either the BSD License or the GNU General Public License (GPL) Version 2.31649 *31650 * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE31651 *31652 * @author https://github.com/shellac31653 */31654var forge = __nccwpck_require__(9177);31655__nccwpck_require__(7994);31656__nccwpck_require__(5104);31657__nccwpck_require__(6594);31658__nccwpck_require__(279);31659__nccwpck_require__(8339);31660var ssh = module.exports = forge.ssh = forge.ssh || {};31661/**31662 * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file.31663 *31664 * @param privateKey the key.31665 * @param passphrase a passphrase to protect the key (falsy for no encryption).31666 * @param comment a comment to include in the key file.31667 *31668 * @return the PPK file as a string.31669 */31670ssh.privateKeyToPutty = function(privateKey, passphrase, comment) {31671 comment = comment || '';31672 passphrase = passphrase || '';31673 var algorithm = 'ssh-rsa';31674 var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc';31675 var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n';31676 ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n';31677 ppk += 'Comment: ' + comment + '\r\n';31678 // public key into buffer for ppk31679 var pubbuffer = forge.util.createBuffer();31680 _addStringToBuffer(pubbuffer, algorithm);31681 _addBigIntegerToBuffer(pubbuffer, privateKey.e);31682 _addBigIntegerToBuffer(pubbuffer, privateKey.n);31683 // write public key31684 var pub = forge.util.encode64(pubbuffer.bytes(), 64);31685 var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \r\n31686 ppk += 'Public-Lines: ' + length + '\r\n';31687 ppk += pub;31688 // private key into a buffer31689 var privbuffer = forge.util.createBuffer();31690 _addBigIntegerToBuffer(privbuffer, privateKey.d);31691 _addBigIntegerToBuffer(privbuffer, privateKey.p);31692 _addBigIntegerToBuffer(privbuffer, privateKey.q);31693 _addBigIntegerToBuffer(privbuffer, privateKey.qInv);31694 // optionally encrypt the private key31695 var priv;31696 if(!passphrase) {31697 // use the unencrypted buffer31698 priv = forge.util.encode64(privbuffer.bytes(), 64);31699 } else {31700 // encrypt RSA key using passphrase31701 var encLen = privbuffer.length() + 16 - 1;31702 encLen -= encLen % 16;31703 // pad private key with sha1-d data -- needs to be a multiple of 1631704 var padding = _sha1(privbuffer.bytes());31705 padding.truncate(padding.length() - encLen + privbuffer.length());31706 privbuffer.putBuffer(padding);31707 var aeskey = forge.util.createBuffer();31708 aeskey.putBuffer(_sha1('\x00\x00\x00\x00', passphrase));31709 aeskey.putBuffer(_sha1('\x00\x00\x00\x01', passphrase));31710 // encrypt some bytes using CBC mode31711 // key is 40 bytes, so truncate *by* 8 bytes31712 var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC');31713 cipher.start(forge.util.createBuffer().fillWithByte(0, 16));31714 cipher.update(privbuffer.copy());31715 cipher.finish();31716 var encrypted = cipher.output;31717 // Note: this appears to differ from Putty -- is forge wrong, or putty?31718 // due to padding we finish as an exact multiple of 1631719 encrypted.truncate(16); // all padding31720 priv = forge.util.encode64(encrypted.bytes(), 64);31721 }31722 // output private key31723 length = Math.floor(priv.length / 66) + 1; // 64 + \r\n31724 ppk += '\r\nPrivate-Lines: ' + length + '\r\n';31725 ppk += priv;31726 // MAC31727 var mackey = _sha1('putty-private-key-file-mac-key', passphrase);31728 var macbuffer = forge.util.createBuffer();31729 _addStringToBuffer(macbuffer, algorithm);31730 _addStringToBuffer(macbuffer, encryptionAlgorithm);31731 _addStringToBuffer(macbuffer, comment);31732 macbuffer.putInt32(pubbuffer.length());31733 macbuffer.putBuffer(pubbuffer);31734 macbuffer.putInt32(privbuffer.length());31735 macbuffer.putBuffer(privbuffer);31736 var hmac = forge.hmac.create();31737 hmac.start('sha1', mackey);31738 hmac.update(macbuffer.bytes());31739 ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n';31740 return ppk;31741};31742/**31743 * Encodes a public RSA key as an OpenSSH file.31744 *31745 * @param key the key.31746 * @param comment a comment.31747 *31748 * @return the public key in OpenSSH format.31749 */31750ssh.publicKeyToOpenSSH = function(key, comment) {31751 var type = 'ssh-rsa';31752 comment = comment || '';31753 var buffer = forge.util.createBuffer();31754 _addStringToBuffer(buffer, type);31755 _addBigIntegerToBuffer(buffer, key.e);31756 _addBigIntegerToBuffer(buffer, key.n);31757 return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment;31758};31759/**31760 * Encodes a private RSA key as an OpenSSH file.31761 *31762 * @param key the key.31763 * @param passphrase a passphrase to protect the key (falsy for no encryption).31764 *31765 * @return the public key in OpenSSH format.31766 */31767ssh.privateKeyToOpenSSH = function(privateKey, passphrase) {31768 if(!passphrase) {31769 return forge.pki.privateKeyToPem(privateKey);31770 }31771 // OpenSSH private key is just a legacy format, it seems31772 return forge.pki.encryptRsaPrivateKey(privateKey, passphrase,31773 {legacy: true, algorithm: 'aes128'});31774};31775/**31776 * Gets the SSH fingerprint for the given public key.31777 *31778 * @param options the options to use.31779 * [md] the message digest object to use (defaults to forge.md.md5).31780 * [encoding] an alternative output encoding, such as 'hex'31781 * (defaults to none, outputs a byte buffer).31782 * [delimiter] the delimiter to use between bytes for 'hex' encoded31783 * output, eg: ':' (defaults to none).31784 *31785 * @return the fingerprint as a byte buffer or other encoding based on options.31786 */31787ssh.getPublicKeyFingerprint = function(key, options) {31788 options = options || {};31789 var md = options.md || forge.md.md5.create();31790 var type = 'ssh-rsa';31791 var buffer = forge.util.createBuffer();31792 _addStringToBuffer(buffer, type);31793 _addBigIntegerToBuffer(buffer, key.e);31794 _addBigIntegerToBuffer(buffer, key.n);31795 // hash public key bytes31796 md.start();31797 md.update(buffer.getBytes());31798 var digest = md.digest();31799 if(options.encoding === 'hex') {31800 var hex = digest.toHex();31801 if(options.delimiter) {31802 return hex.match(/.{2}/g).join(options.delimiter);31803 }31804 return hex;31805 } else if(options.encoding === 'binary') {31806 return digest.getBytes();31807 } else if(options.encoding) {31808 throw new Error('Unknown encoding "' + options.encoding + '".');31809 }31810 return digest;31811};31812/**31813 * Adds len(val) then val to a buffer.31814 *31815 * @param buffer the buffer to add to.31816 * @param val a big integer.31817 */31818function _addBigIntegerToBuffer(buffer, val) {31819 var hexVal = val.toString(16);31820 // ensure 2s complement +ve31821 if(hexVal[0] >= '8') {31822 hexVal = '00' + hexVal;31823 }31824 var bytes = forge.util.hexToBytes(hexVal);31825 buffer.putInt32(bytes.length);31826 buffer.putBytes(bytes);31827}31828/**31829 * Adds len(val) then val to a buffer.31830 *31831 * @param buffer the buffer to add to.31832 * @param val a string.31833 */31834function _addStringToBuffer(buffer, val) {31835 buffer.putInt32(val.length);31836 buffer.putString(val);31837}31838/**31839 * Hashes the arguments into one value using SHA-1.31840 *31841 * @return the sha1 hash of the provided arguments.31842 */31843function _sha1() {31844 var sha = forge.md.sha1.create();31845 var num = arguments.length;31846 for (var i = 0; i < num; ++i) {31847 sha.update(arguments[i]);31848 }31849 return sha.digest();31850}31851/***/ }),31852/***/ 9167:31853/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {31854/**31855 * A Javascript implementation of Transport Layer Security (TLS).31856 *31857 * @author Dave Longley31858 *31859 * Copyright (c) 2009-2014 Digital Bazaar, Inc.31860 *31861 * The TLS Handshake Protocol involves the following steps:31862 *31863 * - Exchange hello messages to agree on algorithms, exchange random values,31864 * and check for session resumption.31865 *31866 * - Exchange the necessary cryptographic parameters to allow the client and31867 * server to agree on a premaster secret.31868 *31869 * - Exchange certificates and cryptographic information to allow the client31870 * and server to authenticate themselves.31871 *31872 * - Generate a master secret from the premaster secret and exchanged random31873 * values.31874 *31875 * - Provide security parameters to the record layer.31876 *31877 * - Allow the client and server to verify that their peer has calculated the31878 * same security parameters and that the handshake occurred without tampering31879 * by an attacker.31880 *31881 * Up to 4 different messages may be sent during a key exchange. The server31882 * certificate, the server key exchange, the client certificate, and the31883 * client key exchange.31884 *31885 * A typical handshake (from the client's perspective).31886 *31887 * 1. Client sends ClientHello.31888 * 2. Client receives ServerHello.31889 * 3. Client receives optional Certificate.31890 * 4. Client receives optional ServerKeyExchange.31891 * 5. Client receives ServerHelloDone.31892 * 6. Client sends optional Certificate.31893 * 7. Client sends ClientKeyExchange.31894 * 8. Client sends optional CertificateVerify.31895 * 9. Client sends ChangeCipherSpec.31896 * 10. Client sends Finished.31897 * 11. Client receives ChangeCipherSpec.31898 * 12. Client receives Finished.31899 * 13. Client sends/receives application data.31900 *31901 * To reuse an existing session:31902 *31903 * 1. Client sends ClientHello with session ID for reuse.31904 * 2. Client receives ServerHello with same session ID if reusing.31905 * 3. Client receives ChangeCipherSpec message if reusing.31906 * 4. Client receives Finished.31907 * 5. Client sends ChangeCipherSpec.31908 * 6. Client sends Finished.31909 *31910 * Note: Client ignores HelloRequest if in the middle of a handshake.31911 *31912 * Record Layer:31913 *31914 * The record layer fragments information blocks into TLSPlaintext records31915 * carrying data in chunks of 2^14 bytes or less. Client message boundaries are31916 * not preserved in the record layer (i.e., multiple client messages of the31917 * same ContentType MAY be coalesced into a single TLSPlaintext record, or a31918 * single message MAY be fragmented across several records).31919 *31920 * struct {31921 * uint8 major;31922 * uint8 minor;31923 * } ProtocolVersion;31924 *31925 * struct {31926 * ContentType type;31927 * ProtocolVersion version;31928 * uint16 length;31929 * opaque fragment[TLSPlaintext.length];31930 * } TLSPlaintext;31931 *31932 * type:31933 * The higher-level protocol used to process the enclosed fragment.31934 *31935 * version:31936 * The version of the protocol being employed. TLS Version 1.2 uses version31937 * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that31938 * supports multiple versions of TLS may not know what version will be31939 * employed before it receives the ServerHello.31940 *31941 * length:31942 * The length (in bytes) of the following TLSPlaintext.fragment. The length31943 * MUST NOT exceed 2^14 = 16384 bytes.31944 *31945 * fragment:31946 * The application data. This data is transparent and treated as an31947 * independent block to be dealt with by the higher-level protocol specified31948 * by the type field.31949 *31950 * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or31951 * ChangeCipherSpec content types. Zero-length fragments of Application data31952 * MAY be sent as they are potentially useful as a traffic analysis31953 * countermeasure.31954 *31955 * Note: Data of different TLS record layer content types MAY be interleaved.31956 * Application data is generally of lower precedence for transmission than31957 * other content types. However, records MUST be delivered to the network in31958 * the same order as they are protected by the record layer. Recipients MUST31959 * receive and process interleaved application layer traffic during handshakes31960 * subsequent to the first one on a connection.31961 *31962 * struct {31963 * ContentType type; // same as TLSPlaintext.type31964 * ProtocolVersion version;// same as TLSPlaintext.version31965 * uint16 length;31966 * opaque fragment[TLSCompressed.length];31967 * } TLSCompressed;31968 *31969 * length:31970 * The length (in bytes) of the following TLSCompressed.fragment.31971 * The length MUST NOT exceed 2^14 + 1024.31972 *31973 * fragment:31974 * The compressed form of TLSPlaintext.fragment.31975 *31976 * Note: A CompressionMethod.null operation is an identity operation; no fields31977 * are altered. In this implementation, since no compression is supported,31978 * uncompressed records are always the same as compressed records.31979 *31980 * Encryption Information:31981 *31982 * The encryption and MAC functions translate a TLSCompressed structure into a31983 * TLSCiphertext. The decryption functions reverse the process. The MAC of the31984 * record also includes a sequence number so that missing, extra, or repeated31985 * messages are detectable.31986 *31987 * struct {31988 * ContentType type;31989 * ProtocolVersion version;31990 * uint16 length;31991 * select (SecurityParameters.cipher_type) {31992 * case stream: GenericStreamCipher;31993 * case block: GenericBlockCipher;31994 * case aead: GenericAEADCipher;31995 * } fragment;31996 * } TLSCiphertext;31997 *31998 * type:31999 * The type field is identical to TLSCompressed.type.32000 *32001 * version:32002 * The version field is identical to TLSCompressed.version.32003 *32004 * length:32005 * The length (in bytes) of the following TLSCiphertext.fragment.32006 * The length MUST NOT exceed 2^14 + 2048.32007 *32008 * fragment:32009 * The encrypted form of TLSCompressed.fragment, with the MAC.32010 *32011 * Note: Only CBC Block Ciphers are supported by this implementation.32012 *32013 * The TLSCompressed.fragment structures are converted to/from block32014 * TLSCiphertext.fragment structures.32015 *32016 * struct {32017 * opaque IV[SecurityParameters.record_iv_length];32018 * block-ciphered struct {32019 * opaque content[TLSCompressed.length];32020 * opaque MAC[SecurityParameters.mac_length];32021 * uint8 padding[GenericBlockCipher.padding_length];32022 * uint8 padding_length;32023 * };32024 * } GenericBlockCipher;32025 *32026 * The MAC is generated as described in Section 6.2.3.1.32027 *32028 * IV:32029 * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be32030 * unpredictable. Note that in versions of TLS prior to 1.1, there was no32031 * IV field, and the last ciphertext block of the previous record (the "CBC32032 * residue") was used as the IV. This was changed to prevent the attacks32033 * described in [CBCATT]. For block ciphers, the IV length is of length32034 * SecurityParameters.record_iv_length, which is equal to the32035 * SecurityParameters.block_size.32036 *32037 * padding:32038 * Padding that is added to force the length of the plaintext to be an32039 * integral multiple of the block cipher's block length. The padding MAY be32040 * any length up to 255 bytes, as long as it results in the32041 * TLSCiphertext.length being an integral multiple of the block length.32042 * Lengths longer than necessary might be desirable to frustrate attacks on32043 * a protocol that are based on analysis of the lengths of exchanged32044 * messages. Each uint8 in the padding data vector MUST be filled with the32045 * padding length value. The receiver MUST check this padding and MUST use32046 * the bad_record_mac alert to indicate padding errors.32047 *32048 * padding_length:32049 * The padding length MUST be such that the total size of the32050 * GenericBlockCipher structure is a multiple of the cipher's block length.32051 * Legal values range from zero to 255, inclusive. This length specifies the32052 * length of the padding field exclusive of the padding_length field itself.32053 *32054 * The encrypted data length (TLSCiphertext.length) is one more than the sum of32055 * SecurityParameters.block_length, TLSCompressed.length,32056 * SecurityParameters.mac_length, and padding_length.32057 *32058 * Example: If the block length is 8 bytes, the content length32059 * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the32060 * length before padding is 82 bytes (this does not include the IV. Thus, the32061 * padding length modulo 8 must be equal to 6 in order to make the total length32062 * an even multiple of 8 bytes (the block length). The padding length can be32063 * 6, 14, 22, and so on, through 254. If the padding length were the minimum32064 * necessary, 6, the padding would be 6 bytes, each containing the value 6.32065 * Thus, the last 8 octets of the GenericBlockCipher before block encryption32066 * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC.32067 *32068 * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical32069 * that the entire plaintext of the record be known before any ciphertext is32070 * transmitted. Otherwise, it is possible for the attacker to mount the attack32071 * described in [CBCATT].32072 *32073 * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing32074 * attack on CBC padding based on the time required to compute the MAC. In32075 * order to defend against this attack, implementations MUST ensure that32076 * record processing time is essentially the same whether or not the padding32077 * is correct. In general, the best way to do this is to compute the MAC even32078 * if the padding is incorrect, and only then reject the packet. For instance,32079 * if the pad appears to be incorrect, the implementation might assume a32080 * zero-length pad and then compute the MAC. This leaves a small timing32081 * channel, since MAC performance depends, to some extent, on the size of the32082 * data fragment, but it is not believed to be large enough to be exploitable,32083 * due to the large block size of existing MACs and the small size of the32084 * timing signal.32085 */32086var forge = __nccwpck_require__(9177);32087__nccwpck_require__(9549);32088__nccwpck_require__(5104);32089__nccwpck_require__(6594);32090__nccwpck_require__(154);32091__nccwpck_require__(6924);32092__nccwpck_require__(7821);32093__nccwpck_require__(279);32094__nccwpck_require__(8339);32095/**32096 * Generates pseudo random bytes by mixing the result of two hash functions,32097 * MD5 and SHA-1.32098 *32099 * prf_TLS1(secret, label, seed) =32100 * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);32101 *32102 * Each P_hash function functions as follows:32103 *32104 * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +32105 * HMAC_hash(secret, A(2) + seed) +32106 * HMAC_hash(secret, A(3) + seed) + ...32107 * A() is defined as:32108 * A(0) = seed32109 * A(i) = HMAC_hash(secret, A(i-1))32110 *32111 * The '+' operator denotes concatenation.32112 *32113 * As many iterations A(N) as are needed are performed to generate enough32114 * pseudo random byte output. If an iteration creates more data than is32115 * necessary, then it is truncated.32116 *32117 * Therefore:32118 * A(1) = HMAC_hash(secret, A(0))32119 * = HMAC_hash(secret, seed)32120 * A(2) = HMAC_hash(secret, A(1))32121 * = HMAC_hash(secret, HMAC_hash(secret, seed))32122 *32123 * Therefore:32124 * P_hash(secret, seed) =32125 * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) +32126 * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) +32127 * ...32128 *32129 * Therefore:32130 * P_hash(secret, seed) =32131 * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) +32132 * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) +32133 * ...32134 *32135 * @param secret the secret to use.32136 * @param label the label to use.32137 * @param seed the seed value to use.32138 * @param length the number of bytes to generate.32139 *32140 * @return the pseudo random bytes in a byte buffer.32141 */32142var prf_TLS1 = function(secret, label, seed, length) {32143 var rval = forge.util.createBuffer();32144 /* For TLS 1.0, the secret is split in half, into two secrets of equal32145 length. If the secret has an odd length then the last byte of the first32146 half will be the same as the first byte of the second. The length of the32147 two secrets is half of the secret rounded up. */32148 var idx = (secret.length >> 1);32149 var slen = idx + (secret.length & 1);32150 var s1 = secret.substr(0, slen);32151 var s2 = secret.substr(idx, slen);32152 var ai = forge.util.createBuffer();32153 var hmac = forge.hmac.create();32154 seed = label + seed;32155 // determine the number of iterations that must be performed to generate32156 // enough output bytes, md5 creates 16 byte hashes, sha1 creates 2032157 var md5itr = Math.ceil(length / 16);32158 var sha1itr = Math.ceil(length / 20);32159 // do md5 iterations32160 hmac.start('MD5', s1);32161 var md5bytes = forge.util.createBuffer();32162 ai.putBytes(seed);32163 for(var i = 0; i < md5itr; ++i) {32164 // HMAC_hash(secret, A(i-1))32165 hmac.start(null, null);32166 hmac.update(ai.getBytes());32167 ai.putBuffer(hmac.digest());32168 // HMAC_hash(secret, A(i) + seed)32169 hmac.start(null, null);32170 hmac.update(ai.bytes() + seed);32171 md5bytes.putBuffer(hmac.digest());32172 }32173 // do sha1 iterations32174 hmac.start('SHA1', s2);32175 var sha1bytes = forge.util.createBuffer();32176 ai.clear();32177 ai.putBytes(seed);32178 for(var i = 0; i < sha1itr; ++i) {32179 // HMAC_hash(secret, A(i-1))32180 hmac.start(null, null);32181 hmac.update(ai.getBytes());32182 ai.putBuffer(hmac.digest());32183 // HMAC_hash(secret, A(i) + seed)32184 hmac.start(null, null);32185 hmac.update(ai.bytes() + seed);32186 sha1bytes.putBuffer(hmac.digest());32187 }32188 // XOR the md5 bytes with the sha1 bytes32189 rval.putBytes(forge.util.xorBytes(32190 md5bytes.getBytes(), sha1bytes.getBytes(), length));32191 return rval;32192};32193/**32194 * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2.32195 *32196 * @param secret the secret to use.32197 * @param label the label to use.32198 * @param seed the seed value to use.32199 * @param length the number of bytes to generate.32200 *32201 * @return the pseudo random bytes in a byte buffer.32202 */32203var prf_sha256 = function(secret, label, seed, length) {32204 // FIXME: implement me for TLS 1.232205};32206/**32207 * Gets a MAC for a record using the SHA-1 hash algorithm.32208 *32209 * @param key the mac key.32210 * @param state the sequence number (array of two 32-bit integers).32211 * @param record the record.32212 *32213 * @return the sha-1 hash (20 bytes) for the given record.32214 */32215var hmac_sha1 = function(key, seqNum, record) {32216 /* MAC is computed like so:32217 HMAC_hash(32218 key, seqNum +32219 TLSCompressed.type +32220 TLSCompressed.version +32221 TLSCompressed.length +32222 TLSCompressed.fragment)32223 */32224 var hmac = forge.hmac.create();32225 hmac.start('SHA1', key);32226 var b = forge.util.createBuffer();32227 b.putInt32(seqNum[0]);32228 b.putInt32(seqNum[1]);32229 b.putByte(record.type);32230 b.putByte(record.version.major);32231 b.putByte(record.version.minor);32232 b.putInt16(record.length);32233 b.putBytes(record.fragment.bytes());32234 hmac.update(b.getBytes());32235 return hmac.digest().getBytes();32236};32237/**32238 * Compresses the TLSPlaintext record into a TLSCompressed record using the32239 * deflate algorithm.32240 *32241 * @param c the TLS connection.32242 * @param record the TLSPlaintext record to compress.32243 * @param s the ConnectionState to use.32244 *32245 * @return true on success, false on failure.32246 */32247var deflate = function(c, record, s) {32248 var rval = false;32249 try {32250 var bytes = c.deflate(record.fragment.getBytes());32251 record.fragment = forge.util.createBuffer(bytes);32252 record.length = bytes.length;32253 rval = true;32254 } catch(ex) {32255 // deflate error, fail out32256 }32257 return rval;32258};32259/**32260 * Decompresses the TLSCompressed record into a TLSPlaintext record using the32261 * deflate algorithm.32262 *32263 * @param c the TLS connection.32264 * @param record the TLSCompressed record to decompress.32265 * @param s the ConnectionState to use.32266 *32267 * @return true on success, false on failure.32268 */32269var inflate = function(c, record, s) {32270 var rval = false;32271 try {32272 var bytes = c.inflate(record.fragment.getBytes());32273 record.fragment = forge.util.createBuffer(bytes);32274 record.length = bytes.length;32275 rval = true;32276 } catch(ex) {32277 // inflate error, fail out32278 }32279 return rval;32280};32281/**32282 * Reads a TLS variable-length vector from a byte buffer.32283 *32284 * Variable-length vectors are defined by specifying a subrange of legal32285 * lengths, inclusively, using the notation <floor..ceiling>. When these are32286 * encoded, the actual length precedes the vector's contents in the byte32287 * stream. The length will be in the form of a number consuming as many bytes32288 * as required to hold the vector's specified maximum (ceiling) length. A32289 * variable-length vector with an actual length field of zero is referred to32290 * as an empty vector.32291 *32292 * @param b the byte buffer.32293 * @param lenBytes the number of bytes required to store the length.32294 *32295 * @return the resulting byte buffer.32296 */32297var readVector = function(b, lenBytes) {32298 var len = 0;32299 switch(lenBytes) {32300 case 1:32301 len = b.getByte();32302 break;32303 case 2:32304 len = b.getInt16();32305 break;32306 case 3:32307 len = b.getInt24();32308 break;32309 case 4:32310 len = b.getInt32();32311 break;32312 }32313 // read vector bytes into a new buffer32314 return forge.util.createBuffer(b.getBytes(len));32315};32316/**32317 * Writes a TLS variable-length vector to a byte buffer.32318 *32319 * @param b the byte buffer.32320 * @param lenBytes the number of bytes required to store the length.32321 * @param v the byte buffer vector.32322 */32323var writeVector = function(b, lenBytes, v) {32324 // encode length at the start of the vector, where the number of bytes for32325 // the length is the maximum number of bytes it would take to encode the32326 // vector's ceiling32327 b.putInt(v.length(), lenBytes << 3);32328 b.putBuffer(v);32329};32330/**32331 * The tls implementation.32332 */32333var tls = {};32334/**32335 * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and32336 * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time32337 * of this implementation so TLS 1.0 was implemented instead.32338 */32339tls.Versions = {32340 TLS_1_0: {major: 3, minor: 1},32341 TLS_1_1: {major: 3, minor: 2},32342 TLS_1_2: {major: 3, minor: 3}32343};32344tls.SupportedVersions = [32345 tls.Versions.TLS_1_1,32346 tls.Versions.TLS_1_032347];32348tls.Version = tls.SupportedVersions[0];32349/**32350 * Maximum fragment size. True maximum is 16384, but we fragment before that32351 * to allow for unusual small increases during compression.32352 */32353tls.MaxFragment = 16384 - 1024;32354/**32355 * Whether this entity is considered the "client" or "server".32356 * enum { server, client } ConnectionEnd;32357 */32358tls.ConnectionEnd = {32359 server: 0,32360 client: 132361};32362/**32363 * Pseudo-random function algorithm used to generate keys from the master32364 * secret.32365 * enum { tls_prf_sha256 } PRFAlgorithm;32366 */32367tls.PRFAlgorithm = {32368 tls_prf_sha256: 032369};32370/**32371 * Bulk encryption algorithms.32372 * enum { null, rc4, des3, aes } BulkCipherAlgorithm;32373 */32374tls.BulkCipherAlgorithm = {32375 none: null,32376 rc4: 0,32377 des3: 1,32378 aes: 232379};32380/**32381 * Cipher types.32382 * enum { stream, block, aead } CipherType;32383 */32384tls.CipherType = {32385 stream: 0,32386 block: 1,32387 aead: 232388};32389/**32390 * MAC (Message Authentication Code) algorithms.32391 * enum { null, hmac_md5, hmac_sha1, hmac_sha256,32392 * hmac_sha384, hmac_sha512} MACAlgorithm;32393 */32394tls.MACAlgorithm = {32395 none: null,32396 hmac_md5: 0,32397 hmac_sha1: 1,32398 hmac_sha256: 2,32399 hmac_sha384: 3,32400 hmac_sha512: 432401};32402/**32403 * Compression algorithms.32404 * enum { null(0), deflate(1), (255) } CompressionMethod;32405 */32406tls.CompressionMethod = {32407 none: 0,32408 deflate: 132409};32410/**32411 * TLS record content types.32412 * enum {32413 * change_cipher_spec(20), alert(21), handshake(22),32414 * application_data(23), (255)32415 * } ContentType;32416 */32417tls.ContentType = {32418 change_cipher_spec: 20,32419 alert: 21,32420 handshake: 22,32421 application_data: 23,32422 heartbeat: 2432423};32424/**32425 * TLS handshake types.32426 * enum {32427 * hello_request(0), client_hello(1), server_hello(2),32428 * certificate(11), server_key_exchange (12),32429 * certificate_request(13), server_hello_done(14),32430 * certificate_verify(15), client_key_exchange(16),32431 * finished(20), (255)32432 * } HandshakeType;32433 */32434tls.HandshakeType = {32435 hello_request: 0,32436 client_hello: 1,32437 server_hello: 2,32438 certificate: 11,32439 server_key_exchange: 12,32440 certificate_request: 13,32441 server_hello_done: 14,32442 certificate_verify: 15,32443 client_key_exchange: 16,32444 finished: 2032445};32446/**32447 * TLS Alert Protocol.32448 *32449 * enum { warning(1), fatal(2), (255) } AlertLevel;32450 *32451 * enum {32452 * close_notify(0),32453 * unexpected_message(10),32454 * bad_record_mac(20),32455 * decryption_failed(21),32456 * record_overflow(22),32457 * decompression_failure(30),32458 * handshake_failure(40),32459 * bad_certificate(42),32460 * unsupported_certificate(43),32461 * certificate_revoked(44),32462 * certificate_expired(45),32463 * certificate_unknown(46),32464 * illegal_parameter(47),32465 * unknown_ca(48),32466 * access_denied(49),32467 * decode_error(50),32468 * decrypt_error(51),32469 * export_restriction(60),32470 * protocol_version(70),32471 * insufficient_security(71),32472 * internal_error(80),32473 * user_canceled(90),32474 * no_renegotiation(100),32475 * (255)32476 * } AlertDescription;32477 *32478 * struct {32479 * AlertLevel level;32480 * AlertDescription description;32481 * } Alert;32482 */32483tls.Alert = {};32484tls.Alert.Level = {32485 warning: 1,32486 fatal: 232487};32488tls.Alert.Description = {32489 close_notify: 0,32490 unexpected_message: 10,32491 bad_record_mac: 20,32492 decryption_failed: 21,32493 record_overflow: 22,32494 decompression_failure: 30,32495 handshake_failure: 40,32496 bad_certificate: 42,32497 unsupported_certificate: 43,32498 certificate_revoked: 44,32499 certificate_expired: 45,32500 certificate_unknown: 46,32501 illegal_parameter: 47,32502 unknown_ca: 48,32503 access_denied: 49,32504 decode_error: 50,32505 decrypt_error: 51,32506 export_restriction: 60,32507 protocol_version: 70,32508 insufficient_security: 71,32509 internal_error: 80,32510 user_canceled: 90,32511 no_renegotiation: 10032512};32513/**32514 * TLS Heartbeat Message types.32515 * enum {32516 * heartbeat_request(1),32517 * heartbeat_response(2),32518 * (255)32519 * } HeartbeatMessageType;32520 */32521tls.HeartbeatMessageType = {32522 heartbeat_request: 1,32523 heartbeat_response: 232524};32525/**32526 * Supported cipher suites.32527 */32528tls.CipherSuites = {};32529/**32530 * Gets a supported cipher suite from its 2 byte ID.32531 *32532 * @param twoBytes two bytes in a string.32533 *32534 * @return the matching supported cipher suite or null.32535 */32536tls.getCipherSuite = function(twoBytes) {32537 var rval = null;32538 for(var key in tls.CipherSuites) {32539 var cs = tls.CipherSuites[key];32540 if(cs.id[0] === twoBytes.charCodeAt(0) &&32541 cs.id[1] === twoBytes.charCodeAt(1)) {32542 rval = cs;32543 break;32544 }32545 }32546 return rval;32547};32548/**32549 * Called when an unexpected record is encountered.32550 *32551 * @param c the connection.32552 * @param record the record.32553 */32554tls.handleUnexpected = function(c, record) {32555 // if connection is client and closed, ignore unexpected messages32556 var ignore = (!c.open && c.entity === tls.ConnectionEnd.client);32557 if(!ignore) {32558 c.error(c, {32559 message: 'Unexpected message. Received TLS record out of order.',32560 send: true,32561 alert: {32562 level: tls.Alert.Level.fatal,32563 description: tls.Alert.Description.unexpected_message32564 }32565 });32566 }32567};32568/**32569 * Called when a client receives a HelloRequest record.32570 *32571 * @param c the connection.32572 * @param record the record.32573 * @param length the length of the handshake message.32574 */32575tls.handleHelloRequest = function(c, record, length) {32576 // ignore renegotiation requests from the server during a handshake, but32577 // if handshaking, send a warning alert that renegotation is denied32578 if(!c.handshaking && c.handshakes > 0) {32579 // send alert warning32580 tls.queue(c, tls.createAlert(c, {32581 level: tls.Alert.Level.warning,32582 description: tls.Alert.Description.no_renegotiation32583 }));32584 tls.flush(c);32585 }32586 // continue32587 c.process();32588};32589/**32590 * Parses a hello message from a ClientHello or ServerHello record.32591 *32592 * @param record the record to parse.32593 *32594 * @return the parsed message.32595 */32596tls.parseHelloMessage = function(c, record, length) {32597 var msg = null;32598 var client = (c.entity === tls.ConnectionEnd.client);32599 // minimum of 38 bytes in message32600 if(length < 38) {32601 c.error(c, {32602 message: client ?32603 'Invalid ServerHello message. Message too short.' :32604 'Invalid ClientHello message. Message too short.',32605 send: true,32606 alert: {32607 level: tls.Alert.Level.fatal,32608 description: tls.Alert.Description.illegal_parameter32609 }32610 });32611 } else {32612 // use 'remaining' to calculate # of remaining bytes in the message32613 var b = record.fragment;32614 var remaining = b.length();32615 msg = {32616 version: {32617 major: b.getByte(),32618 minor: b.getByte()32619 },32620 random: forge.util.createBuffer(b.getBytes(32)),32621 session_id: readVector(b, 1),32622 extensions: []32623 };32624 if(client) {32625 msg.cipher_suite = b.getBytes(2);32626 msg.compression_method = b.getByte();32627 } else {32628 msg.cipher_suites = readVector(b, 2);32629 msg.compression_methods = readVector(b, 1);32630 }32631 // read extensions if there are any bytes left in the message32632 remaining = length - (remaining - b.length());32633 if(remaining > 0) {32634 // parse extensions32635 var exts = readVector(b, 2);32636 while(exts.length() > 0) {32637 msg.extensions.push({32638 type: [exts.getByte(), exts.getByte()],32639 data: readVector(exts, 2)32640 });32641 }32642 // TODO: make extension support modular32643 if(!client) {32644 for(var i = 0; i < msg.extensions.length; ++i) {32645 var ext = msg.extensions[i];32646 // support SNI extension32647 if(ext.type[0] === 0x00 && ext.type[1] === 0x00) {32648 // get server name list32649 var snl = readVector(ext.data, 2);32650 while(snl.length() > 0) {32651 // read server name type32652 var snType = snl.getByte();32653 // only HostName type (0x00) is known, break out if32654 // another type is detected32655 if(snType !== 0x00) {32656 break;32657 }32658 // add host name to server name list32659 c.session.extensions.server_name.serverNameList.push(32660 readVector(snl, 2).getBytes());32661 }32662 }32663 }32664 }32665 }32666 // version already set, do not allow version change32667 if(c.session.version) {32668 if(msg.version.major !== c.session.version.major ||32669 msg.version.minor !== c.session.version.minor) {32670 return c.error(c, {32671 message: 'TLS version change is disallowed during renegotiation.',32672 send: true,32673 alert: {32674 level: tls.Alert.Level.fatal,32675 description: tls.Alert.Description.protocol_version32676 }32677 });32678 }32679 }32680 // get the chosen (ServerHello) cipher suite32681 if(client) {32682 // FIXME: should be checking configured acceptable cipher suites32683 c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite);32684 } else {32685 // get a supported preferred (ClientHello) cipher suite32686 // choose the first supported cipher suite32687 var tmp = forge.util.createBuffer(msg.cipher_suites.bytes());32688 while(tmp.length() > 0) {32689 // FIXME: should be checking configured acceptable suites32690 // cipher suites take up 2 bytes32691 c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2));32692 if(c.session.cipherSuite !== null) {32693 break;32694 }32695 }32696 }32697 // cipher suite not supported32698 if(c.session.cipherSuite === null) {32699 return c.error(c, {32700 message: 'No cipher suites in common.',32701 send: true,32702 alert: {32703 level: tls.Alert.Level.fatal,32704 description: tls.Alert.Description.handshake_failure32705 },32706 cipherSuite: forge.util.bytesToHex(msg.cipher_suite)32707 });32708 }32709 // TODO: handle compression methods32710 if(client) {32711 c.session.compressionMethod = msg.compression_method;32712 } else {32713 // no compression32714 c.session.compressionMethod = tls.CompressionMethod.none;32715 }32716 }32717 return msg;32718};32719/**32720 * Creates security parameters for the given connection based on the given32721 * hello message.32722 *32723 * @param c the TLS connection.32724 * @param msg the hello message.32725 */32726tls.createSecurityParameters = function(c, msg) {32727 /* Note: security params are from TLS 1.2, some values like prf_algorithm32728 are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is32729 used. */32730 // TODO: handle other options from server when more supported32731 // get client and server randoms32732 var client = (c.entity === tls.ConnectionEnd.client);32733 var msgRandom = msg.random.bytes();32734 var cRandom = client ? c.session.sp.client_random : msgRandom;32735 var sRandom = client ? msgRandom : tls.createRandom().getBytes();32736 // create new security parameters32737 c.session.sp = {32738 entity: c.entity,32739 prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256,32740 bulk_cipher_algorithm: null,32741 cipher_type: null,32742 enc_key_length: null,32743 block_length: null,32744 fixed_iv_length: null,32745 record_iv_length: null,32746 mac_algorithm: null,32747 mac_length: null,32748 mac_key_length: null,32749 compression_algorithm: c.session.compressionMethod,32750 pre_master_secret: null,32751 master_secret: null,32752 client_random: cRandom,32753 server_random: sRandom32754 };32755};32756/**32757 * Called when a client receives a ServerHello record.32758 *32759 * When a ServerHello message will be sent:32760 * The server will send this message in response to a client hello message32761 * when it was able to find an acceptable set of algorithms. If it cannot32762 * find such a match, it will respond with a handshake failure alert.32763 *32764 * uint24 length;32765 * struct {32766 * ProtocolVersion server_version;32767 * Random random;32768 * SessionID session_id;32769 * CipherSuite cipher_suite;32770 * CompressionMethod compression_method;32771 * select(extensions_present) {32772 * case false:32773 * struct {};32774 * case true:32775 * Extension extensions<0..2^16-1>;32776 * };32777 * } ServerHello;32778 *32779 * @param c the connection.32780 * @param record the record.32781 * @param length the length of the handshake message.32782 */32783tls.handleServerHello = function(c, record, length) {32784 var msg = tls.parseHelloMessage(c, record, length);32785 if(c.fail) {32786 return;32787 }32788 // ensure server version is compatible32789 if(msg.version.minor <= c.version.minor) {32790 c.version.minor = msg.version.minor;32791 } else {32792 return c.error(c, {32793 message: 'Incompatible TLS version.',32794 send: true,32795 alert: {32796 level: tls.Alert.Level.fatal,32797 description: tls.Alert.Description.protocol_version32798 }32799 });32800 }32801 // indicate session version has been set32802 c.session.version = c.version;32803 // get the session ID from the message32804 var sessionId = msg.session_id.bytes();32805 // if the session ID is not blank and matches the cached one, resume32806 // the session32807 if(sessionId.length > 0 && sessionId === c.session.id) {32808 // resuming session, expect a ChangeCipherSpec next32809 c.expect = SCC;32810 c.session.resuming = true;32811 // get new server random32812 c.session.sp.server_random = msg.random.bytes();32813 } else {32814 // not resuming, expect a server Certificate message next32815 c.expect = SCE;32816 c.session.resuming = false;32817 // create new security parameters32818 tls.createSecurityParameters(c, msg);32819 }32820 // set new session ID32821 c.session.id = sessionId;32822 // continue32823 c.process();32824};32825/**32826 * Called when a server receives a ClientHello record.32827 *32828 * When a ClientHello message will be sent:32829 * When a client first connects to a server it is required to send the32830 * client hello as its first message. The client can also send a client32831 * hello in response to a hello request or on its own initiative in order32832 * to renegotiate the security parameters in an existing connection.32833 *32834 * @param c the connection.32835 * @param record the record.32836 * @param length the length of the handshake message.32837 */32838tls.handleClientHello = function(c, record, length) {32839 var msg = tls.parseHelloMessage(c, record, length);32840 if(c.fail) {32841 return;32842 }32843 // get the session ID from the message32844 var sessionId = msg.session_id.bytes();32845 // see if the given session ID is in the cache32846 var session = null;32847 if(c.sessionCache) {32848 session = c.sessionCache.getSession(sessionId);32849 if(session === null) {32850 // session ID not found32851 sessionId = '';32852 } else if(session.version.major !== msg.version.major ||32853 session.version.minor > msg.version.minor) {32854 // if session version is incompatible with client version, do not resume32855 session = null;32856 sessionId = '';32857 }32858 }32859 // no session found to resume, generate a new session ID32860 if(sessionId.length === 0) {32861 sessionId = forge.random.getBytes(32);32862 }32863 // update session32864 c.session.id = sessionId;32865 c.session.clientHelloVersion = msg.version;32866 c.session.sp = {};32867 if(session) {32868 // use version and security parameters from resumed session32869 c.version = c.session.version = session.version;32870 c.session.sp = session.sp;32871 } else {32872 // use highest compatible minor version32873 var version;32874 for(var i = 1; i < tls.SupportedVersions.length; ++i) {32875 version = tls.SupportedVersions[i];32876 if(version.minor <= msg.version.minor) {32877 break;32878 }32879 }32880 c.version = {major: version.major, minor: version.minor};32881 c.session.version = c.version;32882 }32883 // if a session is set, resume it32884 if(session !== null) {32885 // resuming session, expect a ChangeCipherSpec next32886 c.expect = CCC;32887 c.session.resuming = true;32888 // get new client random32889 c.session.sp.client_random = msg.random.bytes();32890 } else {32891 // not resuming, expect a Certificate or ClientKeyExchange32892 c.expect = (c.verifyClient !== false) ? CCE : CKE;32893 c.session.resuming = false;32894 // create new security parameters32895 tls.createSecurityParameters(c, msg);32896 }32897 // connection now open32898 c.open = true;32899 // queue server hello32900 tls.queue(c, tls.createRecord(c, {32901 type: tls.ContentType.handshake,32902 data: tls.createServerHello(c)32903 }));32904 if(c.session.resuming) {32905 // queue change cipher spec message32906 tls.queue(c, tls.createRecord(c, {32907 type: tls.ContentType.change_cipher_spec,32908 data: tls.createChangeCipherSpec()32909 }));32910 // create pending state32911 c.state.pending = tls.createConnectionState(c);32912 // change current write state to pending write state32913 c.state.current.write = c.state.pending.write;32914 // queue finished32915 tls.queue(c, tls.createRecord(c, {32916 type: tls.ContentType.handshake,32917 data: tls.createFinished(c)32918 }));32919 } else {32920 // queue server certificate32921 tls.queue(c, tls.createRecord(c, {32922 type: tls.ContentType.handshake,32923 data: tls.createCertificate(c)32924 }));32925 if(!c.fail) {32926 // queue server key exchange32927 tls.queue(c, tls.createRecord(c, {32928 type: tls.ContentType.handshake,32929 data: tls.createServerKeyExchange(c)32930 }));32931 // request client certificate if set32932 if(c.verifyClient !== false) {32933 // queue certificate request32934 tls.queue(c, tls.createRecord(c, {32935 type: tls.ContentType.handshake,32936 data: tls.createCertificateRequest(c)32937 }));32938 }32939 // queue server hello done32940 tls.queue(c, tls.createRecord(c, {32941 type: tls.ContentType.handshake,32942 data: tls.createServerHelloDone(c)32943 }));32944 }32945 }32946 // send records32947 tls.flush(c);32948 // continue32949 c.process();32950};32951/**32952 * Called when a client receives a Certificate record.32953 *32954 * When this message will be sent:32955 * The server must send a certificate whenever the agreed-upon key exchange32956 * method is not an anonymous one. This message will always immediately32957 * follow the server hello message.32958 *32959 * Meaning of this message:32960 * The certificate type must be appropriate for the selected cipher suite's32961 * key exchange algorithm, and is generally an X.509v3 certificate. It must32962 * contain a key which matches the key exchange method, as follows. Unless32963 * otherwise specified, the signing algorithm for the certificate must be32964 * the same as the algorithm for the certificate key. Unless otherwise32965 * specified, the public key may be of any length.32966 *32967 * opaque ASN.1Cert<1..2^24-1>;32968 * struct {32969 * ASN.1Cert certificate_list<1..2^24-1>;32970 * } Certificate;32971 *32972 * @param c the connection.32973 * @param record the record.32974 * @param length the length of the handshake message.32975 */32976tls.handleCertificate = function(c, record, length) {32977 // minimum of 3 bytes in message32978 if(length < 3) {32979 return c.error(c, {32980 message: 'Invalid Certificate message. Message too short.',32981 send: true,32982 alert: {32983 level: tls.Alert.Level.fatal,32984 description: tls.Alert.Description.illegal_parameter32985 }32986 });32987 }32988 var b = record.fragment;32989 var msg = {32990 certificate_list: readVector(b, 3)32991 };32992 /* The sender's certificate will be first in the list (chain), each32993 subsequent one that follows will certify the previous one, but root32994 certificates (self-signed) that specify the certificate authority may32995 be omitted under the assumption that clients must already possess it. */32996 var cert, asn1;32997 var certs = [];32998 try {32999 while(msg.certificate_list.length() > 0) {33000 // each entry in msg.certificate_list is a vector with 3 len bytes33001 cert = readVector(msg.certificate_list, 3);33002 asn1 = forge.asn1.fromDer(cert);33003 cert = forge.pki.certificateFromAsn1(asn1, true);33004 certs.push(cert);33005 }33006 } catch(ex) {33007 return c.error(c, {33008 message: 'Could not parse certificate list.',33009 cause: ex,33010 send: true,33011 alert: {33012 level: tls.Alert.Level.fatal,33013 description: tls.Alert.Description.bad_certificate33014 }33015 });33016 }33017 // ensure at least 1 certificate was provided if in client-mode33018 // or if verifyClient was set to true to require a certificate33019 // (as opposed to 'optional')33020 var client = (c.entity === tls.ConnectionEnd.client);33021 if((client || c.verifyClient === true) && certs.length === 0) {33022 // error, no certificate33023 c.error(c, {33024 message: client ?33025 'No server certificate provided.' :33026 'No client certificate provided.',33027 send: true,33028 alert: {33029 level: tls.Alert.Level.fatal,33030 description: tls.Alert.Description.illegal_parameter33031 }33032 });33033 } else if(certs.length === 0) {33034 // no certs to verify33035 // expect a ServerKeyExchange or ClientKeyExchange message next33036 c.expect = client ? SKE : CKE;33037 } else {33038 // save certificate in session33039 if(client) {33040 c.session.serverCertificate = certs[0];33041 } else {33042 c.session.clientCertificate = certs[0];33043 }33044 if(tls.verifyCertificateChain(c, certs)) {33045 // expect a ServerKeyExchange or ClientKeyExchange message next33046 c.expect = client ? SKE : CKE;33047 }33048 }33049 // continue33050 c.process();33051};33052/**33053 * Called when a client receives a ServerKeyExchange record.33054 *33055 * When this message will be sent:33056 * This message will be sent immediately after the server certificate33057 * message (or the server hello message, if this is an anonymous33058 * negotiation).33059 *33060 * The server key exchange message is sent by the server only when the33061 * server certificate message (if sent) does not contain enough data to33062 * allow the client to exchange a premaster secret.33063 *33064 * Meaning of this message:33065 * This message conveys cryptographic information to allow the client to33066 * communicate the premaster secret: either an RSA public key to encrypt33067 * the premaster secret with, or a Diffie-Hellman public key with which the33068 * client can complete a key exchange (with the result being the premaster33069 * secret.)33070 *33071 * enum {33072 * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa33073 * } KeyExchangeAlgorithm;33074 *33075 * struct {33076 * opaque dh_p<1..2^16-1>;33077 * opaque dh_g<1..2^16-1>;33078 * opaque dh_Ys<1..2^16-1>;33079 * } ServerDHParams;33080 *33081 * struct {33082 * select(KeyExchangeAlgorithm) {33083 * case dh_anon:33084 * ServerDHParams params;33085 * case dhe_dss:33086 * case dhe_rsa:33087 * ServerDHParams params;33088 * digitally-signed struct {33089 * opaque client_random[32];33090 * opaque server_random[32];33091 * ServerDHParams params;33092 * } signed_params;33093 * case rsa:33094 * case dh_dss:33095 * case dh_rsa:33096 * struct {};33097 * };33098 * } ServerKeyExchange;33099 *33100 * @param c the connection.33101 * @param record the record.33102 * @param length the length of the handshake message.33103 */33104tls.handleServerKeyExchange = function(c, record, length) {33105 // this implementation only supports RSA, no Diffie-Hellman support33106 // so any length > 0 is invalid33107 if(length > 0) {33108 return c.error(c, {33109 message: 'Invalid key parameters. Only RSA is supported.',33110 send: true,33111 alert: {33112 level: tls.Alert.Level.fatal,33113 description: tls.Alert.Description.unsupported_certificate33114 }33115 });33116 }33117 // expect an optional CertificateRequest message next33118 c.expect = SCR;33119 // continue33120 c.process();33121};33122/**33123 * Called when a client receives a ClientKeyExchange record.33124 *33125 * @param c the connection.33126 * @param record the record.33127 * @param length the length of the handshake message.33128 */33129tls.handleClientKeyExchange = function(c, record, length) {33130 // this implementation only supports RSA, no Diffie-Hellman support33131 // so any length < 48 is invalid33132 if(length < 48) {33133 return c.error(c, {33134 message: 'Invalid key parameters. Only RSA is supported.',33135 send: true,33136 alert: {33137 level: tls.Alert.Level.fatal,33138 description: tls.Alert.Description.unsupported_certificate33139 }33140 });33141 }33142 var b = record.fragment;33143 var msg = {33144 enc_pre_master_secret: readVector(b, 2).getBytes()33145 };33146 // do rsa decryption33147 var privateKey = null;33148 if(c.getPrivateKey) {33149 try {33150 privateKey = c.getPrivateKey(c, c.session.serverCertificate);33151 privateKey = forge.pki.privateKeyFromPem(privateKey);33152 } catch(ex) {33153 c.error(c, {33154 message: 'Could not get private key.',33155 cause: ex,33156 send: true,33157 alert: {33158 level: tls.Alert.Level.fatal,33159 description: tls.Alert.Description.internal_error33160 }33161 });33162 }33163 }33164 if(privateKey === null) {33165 return c.error(c, {33166 message: 'No private key set.',33167 send: true,33168 alert: {33169 level: tls.Alert.Level.fatal,33170 description: tls.Alert.Description.internal_error33171 }33172 });33173 }33174 try {33175 // decrypt 48-byte pre-master secret33176 var sp = c.session.sp;33177 sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);33178 // ensure client hello version matches first 2 bytes33179 var version = c.session.clientHelloVersion;33180 if(version.major !== sp.pre_master_secret.charCodeAt(0) ||33181 version.minor !== sp.pre_master_secret.charCodeAt(1)) {33182 // error, do not send alert (see BLEI attack below)33183 throw new Error('TLS version rollback attack detected.');33184 }33185 } catch(ex) {33186 /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a33187 TLS server which is using PKCS#1 encoded RSA, so instead of33188 failing here, we generate 48 random bytes and use that as33189 the pre-master secret. */33190 sp.pre_master_secret = forge.random.getBytes(48);33191 }33192 // expect a CertificateVerify message if a Certificate was received that33193 // does not have fixed Diffie-Hellman params, otherwise expect33194 // ChangeCipherSpec33195 c.expect = CCC;33196 if(c.session.clientCertificate !== null) {33197 // only RSA support, so expect CertificateVerify33198 // TODO: support Diffie-Hellman33199 c.expect = CCV;33200 }33201 // continue33202 c.process();33203};33204/**33205 * Called when a client receives a CertificateRequest record.33206 *33207 * When this message will be sent:33208 * A non-anonymous server can optionally request a certificate from the33209 * client, if appropriate for the selected cipher suite. This message, if33210 * sent, will immediately follow the Server Key Exchange message (if it is33211 * sent; otherwise, the Server Certificate message).33212 *33213 * enum {33214 * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),33215 * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6),33216 * fortezza_dms_RESERVED(20), (255)33217 * } ClientCertificateType;33218 *33219 * opaque DistinguishedName<1..2^16-1>;33220 *33221 * struct {33222 * ClientCertificateType certificate_types<1..2^8-1>;33223 * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>;33224 * DistinguishedName certificate_authorities<0..2^16-1>;33225 * } CertificateRequest;33226 *33227 * @param c the connection.33228 * @param record the record.33229 * @param length the length of the handshake message.33230 */33231tls.handleCertificateRequest = function(c, record, length) {33232 // minimum of 3 bytes in message33233 if(length < 3) {33234 return c.error(c, {33235 message: 'Invalid CertificateRequest. Message too short.',33236 send: true,33237 alert: {33238 level: tls.Alert.Level.fatal,33239 description: tls.Alert.Description.illegal_parameter33240 }33241 });33242 }33243 // TODO: TLS 1.2+ has different format including33244 // SignatureAndHashAlgorithm after cert types33245 var b = record.fragment;33246 var msg = {33247 certificate_types: readVector(b, 1),33248 certificate_authorities: readVector(b, 2)33249 };33250 // save certificate request in session33251 c.session.certificateRequest = msg;33252 // expect a ServerHelloDone message next33253 c.expect = SHD;33254 // continue33255 c.process();33256};33257/**33258 * Called when a server receives a CertificateVerify record.33259 *33260 * @param c the connection.33261 * @param record the record.33262 * @param length the length of the handshake message.33263 */33264tls.handleCertificateVerify = function(c, record, length) {33265 if(length < 2) {33266 return c.error(c, {33267 message: 'Invalid CertificateVerify. Message too short.',33268 send: true,33269 alert: {33270 level: tls.Alert.Level.fatal,33271 description: tls.Alert.Description.illegal_parameter33272 }33273 });33274 }33275 // rewind to get full bytes for message so it can be manually33276 // digested below (special case for CertificateVerify messages because33277 // they must be digested *after* handling as opposed to all others)33278 var b = record.fragment;33279 b.read -= 4;33280 var msgBytes = b.bytes();33281 b.read += 4;33282 var msg = {33283 signature: readVector(b, 2).getBytes()33284 };33285 // TODO: add support for DSA33286 // generate data to verify33287 var verify = forge.util.createBuffer();33288 verify.putBuffer(c.session.md5.digest());33289 verify.putBuffer(c.session.sha1.digest());33290 verify = verify.getBytes();33291 try {33292 var cert = c.session.clientCertificate;33293 /*b = forge.pki.rsa.decrypt(33294 msg.signature, cert.publicKey, true, verify.length);33295 if(b !== verify) {*/33296 if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) {33297 throw new Error('CertificateVerify signature does not match.');33298 }33299 // digest message now that it has been handled33300 c.session.md5.update(msgBytes);33301 c.session.sha1.update(msgBytes);33302 } catch(ex) {33303 return c.error(c, {33304 message: 'Bad signature in CertificateVerify.',33305 send: true,33306 alert: {33307 level: tls.Alert.Level.fatal,33308 description: tls.Alert.Description.handshake_failure33309 }33310 });33311 }33312 // expect ChangeCipherSpec33313 c.expect = CCC;33314 // continue33315 c.process();33316};33317/**33318 * Called when a client receives a ServerHelloDone record.33319 *33320 * When this message will be sent:33321 * The server hello done message is sent by the server to indicate the end33322 * of the server hello and associated messages. After sending this message33323 * the server will wait for a client response.33324 *33325 * Meaning of this message:33326 * This message means that the server is done sending messages to support33327 * the key exchange, and the client can proceed with its phase of the key33328 * exchange.33329 *33330 * Upon receipt of the server hello done message the client should verify33331 * that the server provided a valid certificate if required and check that33332 * the server hello parameters are acceptable.33333 *33334 * struct {} ServerHelloDone;33335 *33336 * @param c the connection.33337 * @param record the record.33338 * @param length the length of the handshake message.33339 */33340tls.handleServerHelloDone = function(c, record, length) {33341 // len must be 0 bytes33342 if(length > 0) {33343 return c.error(c, {33344 message: 'Invalid ServerHelloDone message. Invalid length.',33345 send: true,33346 alert: {33347 level: tls.Alert.Level.fatal,33348 description: tls.Alert.Description.record_overflow33349 }33350 });33351 }33352 if(c.serverCertificate === null) {33353 // no server certificate was provided33354 var error = {33355 message: 'No server certificate provided. Not enough security.',33356 send: true,33357 alert: {33358 level: tls.Alert.Level.fatal,33359 description: tls.Alert.Description.insufficient_security33360 }33361 };33362 // call application callback33363 var depth = 0;33364 var ret = c.verify(c, error.alert.description, depth, []);33365 if(ret !== true) {33366 // check for custom alert info33367 if(ret || ret === 0) {33368 // set custom message and alert description33369 if(typeof ret === 'object' && !forge.util.isArray(ret)) {33370 if(ret.message) {33371 error.message = ret.message;33372 }33373 if(ret.alert) {33374 error.alert.description = ret.alert;33375 }33376 } else if(typeof ret === 'number') {33377 // set custom alert description33378 error.alert.description = ret;33379 }33380 }33381 // send error33382 return c.error(c, error);33383 }33384 }33385 // create client certificate message if requested33386 if(c.session.certificateRequest !== null) {33387 record = tls.createRecord(c, {33388 type: tls.ContentType.handshake,33389 data: tls.createCertificate(c)33390 });33391 tls.queue(c, record);33392 }33393 // create client key exchange message33394 record = tls.createRecord(c, {33395 type: tls.ContentType.handshake,33396 data: tls.createClientKeyExchange(c)33397 });33398 tls.queue(c, record);33399 // expect no messages until the following callback has been called33400 c.expect = SER;33401 // create callback to handle client signature (for client-certs)33402 var callback = function(c, signature) {33403 if(c.session.certificateRequest !== null &&33404 c.session.clientCertificate !== null) {33405 // create certificate verify message33406 tls.queue(c, tls.createRecord(c, {33407 type: tls.ContentType.handshake,33408 data: tls.createCertificateVerify(c, signature)33409 }));33410 }33411 // create change cipher spec message33412 tls.queue(c, tls.createRecord(c, {33413 type: tls.ContentType.change_cipher_spec,33414 data: tls.createChangeCipherSpec()33415 }));33416 // create pending state33417 c.state.pending = tls.createConnectionState(c);33418 // change current write state to pending write state33419 c.state.current.write = c.state.pending.write;33420 // create finished message33421 tls.queue(c, tls.createRecord(c, {33422 type: tls.ContentType.handshake,33423 data: tls.createFinished(c)33424 }));33425 // expect a server ChangeCipherSpec message next33426 c.expect = SCC;33427 // send records33428 tls.flush(c);33429 // continue33430 c.process();33431 };33432 // if there is no certificate request or no client certificate, do33433 // callback immediately33434 if(c.session.certificateRequest === null ||33435 c.session.clientCertificate === null) {33436 return callback(c, null);33437 }33438 // otherwise get the client signature33439 tls.getClientSignature(c, callback);33440};33441/**33442 * Called when a ChangeCipherSpec record is received.33443 *33444 * @param c the connection.33445 * @param record the record.33446 */33447tls.handleChangeCipherSpec = function(c, record) {33448 if(record.fragment.getByte() !== 0x01) {33449 return c.error(c, {33450 message: 'Invalid ChangeCipherSpec message received.',33451 send: true,33452 alert: {33453 level: tls.Alert.Level.fatal,33454 description: tls.Alert.Description.illegal_parameter33455 }33456 });33457 }33458 // create pending state if:33459 // 1. Resuming session in client mode OR33460 // 2. NOT resuming session in server mode33461 var client = (c.entity === tls.ConnectionEnd.client);33462 if((c.session.resuming && client) || (!c.session.resuming && !client)) {33463 c.state.pending = tls.createConnectionState(c);33464 }33465 // change current read state to pending read state33466 c.state.current.read = c.state.pending.read;33467 // clear pending state if:33468 // 1. NOT resuming session in client mode OR33469 // 2. resuming a session in server mode33470 if((!c.session.resuming && client) || (c.session.resuming && !client)) {33471 c.state.pending = null;33472 }33473 // expect a Finished record next33474 c.expect = client ? SFI : CFI;33475 // continue33476 c.process();33477};33478/**33479 * Called when a Finished record is received.33480 *33481 * When this message will be sent:33482 * A finished message is always sent immediately after a change33483 * cipher spec message to verify that the key exchange and33484 * authentication processes were successful. It is essential that a33485 * change cipher spec message be received between the other33486 * handshake messages and the Finished message.33487 *33488 * Meaning of this message:33489 * The finished message is the first protected with the just-33490 * negotiated algorithms, keys, and secrets. Recipients of finished33491 * messages must verify that the contents are correct. Once a side33492 * has sent its Finished message and received and validated the33493 * Finished message from its peer, it may begin to send and receive33494 * application data over the connection.33495 *33496 * struct {33497 * opaque verify_data[verify_data_length];33498 * } Finished;33499 *33500 * verify_data33501 * PRF(master_secret, finished_label, Hash(handshake_messages))33502 * [0..verify_data_length-1];33503 *33504 * finished_label33505 * For Finished messages sent by the client, the string33506 * "client finished". For Finished messages sent by the server, the33507 * string "server finished".33508 *33509 * verify_data_length depends on the cipher suite. If it is not specified33510 * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used33511 * 12 bytes.33512 *33513 * @param c the connection.33514 * @param record the record.33515 * @param length the length of the handshake message.33516 */33517tls.handleFinished = function(c, record, length) {33518 // rewind to get full bytes for message so it can be manually33519 // digested below (special case for Finished messages because they33520 // must be digested *after* handling as opposed to all others)33521 var b = record.fragment;33522 b.read -= 4;33523 var msgBytes = b.bytes();33524 b.read += 4;33525 // message contains only verify_data33526 var vd = record.fragment.getBytes();33527 // ensure verify data is correct33528 b = forge.util.createBuffer();33529 b.putBuffer(c.session.md5.digest());33530 b.putBuffer(c.session.sha1.digest());33531 // set label based on entity type33532 var client = (c.entity === tls.ConnectionEnd.client);33533 var label = client ? 'server finished' : 'client finished';33534 // TODO: determine prf function and verify length for TLS 1.233535 var sp = c.session.sp;33536 var vdl = 12;33537 var prf = prf_TLS1;33538 b = prf(sp.master_secret, label, b.getBytes(), vdl);33539 if(b.getBytes() !== vd) {33540 return c.error(c, {33541 message: 'Invalid verify_data in Finished message.',33542 send: true,33543 alert: {33544 level: tls.Alert.Level.fatal,33545 description: tls.Alert.Description.decrypt_error33546 }33547 });33548 }33549 // digest finished message now that it has been handled33550 c.session.md5.update(msgBytes);33551 c.session.sha1.update(msgBytes);33552 // resuming session as client or NOT resuming session as server33553 if((c.session.resuming && client) || (!c.session.resuming && !client)) {33554 // create change cipher spec message33555 tls.queue(c, tls.createRecord(c, {33556 type: tls.ContentType.change_cipher_spec,33557 data: tls.createChangeCipherSpec()33558 }));33559 // change current write state to pending write state, clear pending33560 c.state.current.write = c.state.pending.write;33561 c.state.pending = null;33562 // create finished message33563 tls.queue(c, tls.createRecord(c, {33564 type: tls.ContentType.handshake,33565 data: tls.createFinished(c)33566 }));33567 }33568 // expect application data next33569 c.expect = client ? SAD : CAD;33570 // handshake complete33571 c.handshaking = false;33572 ++c.handshakes;33573 // save access to peer certificate33574 c.peerCertificate = client ?33575 c.session.serverCertificate : c.session.clientCertificate;33576 // send records33577 tls.flush(c);33578 // now connected33579 c.isConnected = true;33580 c.connected(c);33581 // continue33582 c.process();33583};33584/**33585 * Called when an Alert record is received.33586 *33587 * @param c the connection.33588 * @param record the record.33589 */33590tls.handleAlert = function(c, record) {33591 // read alert33592 var b = record.fragment;33593 var alert = {33594 level: b.getByte(),33595 description: b.getByte()33596 };33597 // TODO: consider using a table?33598 // get appropriate message33599 var msg;33600 switch(alert.description) {33601 case tls.Alert.Description.close_notify:33602 msg = 'Connection closed.';33603 break;33604 case tls.Alert.Description.unexpected_message:33605 msg = 'Unexpected message.';33606 break;33607 case tls.Alert.Description.bad_record_mac:33608 msg = 'Bad record MAC.';33609 break;33610 case tls.Alert.Description.decryption_failed:33611 msg = 'Decryption failed.';33612 break;33613 case tls.Alert.Description.record_overflow:33614 msg = 'Record overflow.';33615 break;33616 case tls.Alert.Description.decompression_failure:33617 msg = 'Decompression failed.';33618 break;33619 case tls.Alert.Description.handshake_failure:33620 msg = 'Handshake failure.';33621 break;33622 case tls.Alert.Description.bad_certificate:33623 msg = 'Bad certificate.';33624 break;33625 case tls.Alert.Description.unsupported_certificate:33626 msg = 'Unsupported certificate.';33627 break;33628 case tls.Alert.Description.certificate_revoked:33629 msg = 'Certificate revoked.';33630 break;33631 case tls.Alert.Description.certificate_expired:33632 msg = 'Certificate expired.';33633 break;33634 case tls.Alert.Description.certificate_unknown:33635 msg = 'Certificate unknown.';33636 break;33637 case tls.Alert.Description.illegal_parameter:33638 msg = 'Illegal parameter.';33639 break;33640 case tls.Alert.Description.unknown_ca:33641 msg = 'Unknown certificate authority.';33642 break;33643 case tls.Alert.Description.access_denied:33644 msg = 'Access denied.';33645 break;33646 case tls.Alert.Description.decode_error:33647 msg = 'Decode error.';33648 break;33649 case tls.Alert.Description.decrypt_error:33650 msg = 'Decrypt error.';33651 break;33652 case tls.Alert.Description.export_restriction:33653 msg = 'Export restriction.';33654 break;33655 case tls.Alert.Description.protocol_version:33656 msg = 'Unsupported protocol version.';33657 break;33658 case tls.Alert.Description.insufficient_security:33659 msg = 'Insufficient security.';33660 break;33661 case tls.Alert.Description.internal_error:33662 msg = 'Internal error.';33663 break;33664 case tls.Alert.Description.user_canceled:33665 msg = 'User canceled.';33666 break;33667 case tls.Alert.Description.no_renegotiation:33668 msg = 'Renegotiation not supported.';33669 break;33670 default:33671 msg = 'Unknown error.';33672 break;33673 }33674 // close connection on close_notify, not an error33675 if(alert.description === tls.Alert.Description.close_notify) {33676 return c.close();33677 }33678 // call error handler33679 c.error(c, {33680 message: msg,33681 send: false,33682 // origin is the opposite end33683 origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client',33684 alert: alert33685 });33686 // continue33687 c.process();33688};33689/**33690 * Called when a Handshake record is received.33691 *33692 * @param c the connection.33693 * @param record the record.33694 */33695tls.handleHandshake = function(c, record) {33696 // get the handshake type and message length33697 var b = record.fragment;33698 var type = b.getByte();33699 var length = b.getInt24();33700 // see if the record fragment doesn't yet contain the full message33701 if(length > b.length()) {33702 // cache the record, clear its fragment, and reset the buffer read33703 // pointer before the type and length were read33704 c.fragmented = record;33705 record.fragment = forge.util.createBuffer();33706 b.read -= 4;33707 // continue33708 return c.process();33709 }33710 // full message now available, clear cache, reset read pointer to33711 // before type and length33712 c.fragmented = null;33713 b.read -= 4;33714 // save the handshake bytes for digestion after handler is found33715 // (include type and length of handshake msg)33716 var bytes = b.bytes(length + 4);33717 // restore read pointer33718 b.read += 4;33719 // handle expected message33720 if(type in hsTable[c.entity][c.expect]) {33721 // initialize server session33722 if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) {33723 c.handshaking = true;33724 c.session = {33725 version: null,33726 extensions: {33727 server_name: {33728 serverNameList: []33729 }33730 },33731 cipherSuite: null,33732 compressionMethod: null,33733 serverCertificate: null,33734 clientCertificate: null,33735 md5: forge.md.md5.create(),33736 sha1: forge.md.sha1.create()33737 };33738 }33739 /* Update handshake messages digest. Finished and CertificateVerify33740 messages are not digested here. They can't be digested as part of33741 the verify_data that they contain. These messages are manually33742 digested in their handlers. HelloRequest messages are simply never33743 included in the handshake message digest according to spec. */33744 if(type !== tls.HandshakeType.hello_request &&33745 type !== tls.HandshakeType.certificate_verify &&33746 type !== tls.HandshakeType.finished) {33747 c.session.md5.update(bytes);33748 c.session.sha1.update(bytes);33749 }33750 // handle specific handshake type record33751 hsTable[c.entity][c.expect][type](c, record, length);33752 } else {33753 // unexpected record33754 tls.handleUnexpected(c, record);33755 }33756};33757/**33758 * Called when an ApplicationData record is received.33759 *33760 * @param c the connection.33761 * @param record the record.33762 */33763tls.handleApplicationData = function(c, record) {33764 // buffer data, notify that its ready33765 c.data.putBuffer(record.fragment);33766 c.dataReady(c);33767 // continue33768 c.process();33769};33770/**33771 * Called when a Heartbeat record is received.33772 *33773 * @param c the connection.33774 * @param record the record.33775 */33776tls.handleHeartbeat = function(c, record) {33777 // get the heartbeat type and payload33778 var b = record.fragment;33779 var type = b.getByte();33780 var length = b.getInt16();33781 var payload = b.getBytes(length);33782 if(type === tls.HeartbeatMessageType.heartbeat_request) {33783 // discard request during handshake or if length is too large33784 if(c.handshaking || length > payload.length) {33785 // continue33786 return c.process();33787 }33788 // retransmit payload33789 tls.queue(c, tls.createRecord(c, {33790 type: tls.ContentType.heartbeat,33791 data: tls.createHeartbeat(33792 tls.HeartbeatMessageType.heartbeat_response, payload)33793 }));33794 tls.flush(c);33795 } else if(type === tls.HeartbeatMessageType.heartbeat_response) {33796 // check payload against expected payload, discard heartbeat if no match33797 if(payload !== c.expectedHeartbeatPayload) {33798 // continue33799 return c.process();33800 }33801 // notify that a valid heartbeat was received33802 if(c.heartbeatReceived) {33803 c.heartbeatReceived(c, forge.util.createBuffer(payload));33804 }33805 }33806 // continue33807 c.process();33808};33809/**33810 * The transistional state tables for receiving TLS records. It maps the33811 * current TLS engine state and a received record to a function to handle the33812 * record and update the state.33813 *33814 * For instance, if the current state is SHE, then the TLS engine is expecting33815 * a ServerHello record. Once a record is received, the handler function is33816 * looked up using the state SHE and the record's content type.33817 *33818 * The resulting function will either be an error handler or a record handler.33819 * The function will take whatever action is appropriate and update the state33820 * for the next record.33821 *33822 * The states are all based on possible server record types. Note that the33823 * client will never specifically expect to receive a HelloRequest or an alert33824 * from the server so there is no state that reflects this. These messages may33825 * occur at any time.33826 *33827 * There are two tables for mapping states because there is a second tier of33828 * types for handshake messages. Once a record with a content type of handshake33829 * is received, the handshake record handler will look up the handshake type in33830 * the secondary map to get its appropriate handler.33831 *33832 * Valid message orders are as follows:33833 *33834 * =======================FULL HANDSHAKE======================33835 * Client Server33836 *33837 * ClientHello -------->33838 * ServerHello33839 * Certificate*33840 * ServerKeyExchange*33841 * CertificateRequest*33842 * <-------- ServerHelloDone33843 * Certificate*33844 * ClientKeyExchange33845 * CertificateVerify*33846 * [ChangeCipherSpec]33847 * Finished -------->33848 * [ChangeCipherSpec]33849 * <-------- Finished33850 * Application Data <-------> Application Data33851 *33852 * =====================SESSION RESUMPTION=====================33853 * Client Server33854 *33855 * ClientHello -------->33856 * ServerHello33857 * [ChangeCipherSpec]33858 * <-------- Finished33859 * [ChangeCipherSpec]33860 * Finished -------->33861 * Application Data <-------> Application Data33862 */33863// client expect states (indicate which records are expected to be received)33864var SHE = 0; // rcv server hello33865var SCE = 1; // rcv server certificate33866var SKE = 2; // rcv server key exchange33867var SCR = 3; // rcv certificate request33868var SHD = 4; // rcv server hello done33869var SCC = 5; // rcv change cipher spec33870var SFI = 6; // rcv finished33871var SAD = 7; // rcv application data33872var SER = 8; // not expecting any messages at this point33873// server expect states33874var CHE = 0; // rcv client hello33875var CCE = 1; // rcv client certificate33876var CKE = 2; // rcv client key exchange33877var CCV = 3; // rcv certificate verify33878var CCC = 4; // rcv change cipher spec33879var CFI = 5; // rcv finished33880var CAD = 6; // rcv application data33881var CER = 7; // not expecting any messages at this point33882// map client current expect state and content type to function33883var __ = tls.handleUnexpected;33884var R0 = tls.handleChangeCipherSpec;33885var R1 = tls.handleAlert;33886var R2 = tls.handleHandshake;33887var R3 = tls.handleApplicationData;33888var R4 = tls.handleHeartbeat;33889var ctTable = [];33890ctTable[tls.ConnectionEnd.client] = [33891// CC,AL,HS,AD,HB33892/*SHE*/[__,R1,R2,__,R4],33893/*SCE*/[__,R1,R2,__,R4],33894/*SKE*/[__,R1,R2,__,R4],33895/*SCR*/[__,R1,R2,__,R4],33896/*SHD*/[__,R1,R2,__,R4],33897/*SCC*/[R0,R1,__,__,R4],33898/*SFI*/[__,R1,R2,__,R4],33899/*SAD*/[__,R1,R2,R3,R4],33900/*SER*/[__,R1,R2,__,R4]33901];33902// map server current expect state and content type to function33903ctTable[tls.ConnectionEnd.server] = [33904// CC,AL,HS,AD33905/*CHE*/[__,R1,R2,__,R4],33906/*CCE*/[__,R1,R2,__,R4],33907/*CKE*/[__,R1,R2,__,R4],33908/*CCV*/[__,R1,R2,__,R4],33909/*CCC*/[R0,R1,__,__,R4],33910/*CFI*/[__,R1,R2,__,R4],33911/*CAD*/[__,R1,R2,R3,R4],33912/*CER*/[__,R1,R2,__,R4]33913];33914// map client current expect state and handshake type to function33915var H0 = tls.handleHelloRequest;33916var H1 = tls.handleServerHello;33917var H2 = tls.handleCertificate;33918var H3 = tls.handleServerKeyExchange;33919var H4 = tls.handleCertificateRequest;33920var H5 = tls.handleServerHelloDone;33921var H6 = tls.handleFinished;33922var hsTable = [];33923hsTable[tls.ConnectionEnd.client] = [33924// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI33925/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],33926/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],33927/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],33928/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],33929/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],33930/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],33931/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],33932/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],33933/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]33934];33935// map server current expect state and handshake type to function33936// Note: CAD[CH] does not map to FB because renegotation is prohibited33937var H7 = tls.handleClientHello;33938var H8 = tls.handleClientKeyExchange;33939var H9 = tls.handleCertificateVerify;33940hsTable[tls.ConnectionEnd.server] = [33941// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI33942/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],33943/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],33944/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],33945/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],33946/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],33947/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],33948/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],33949/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]33950];33951/**33952 * Generates the master_secret and keys using the given security parameters.33953 *33954 * The security parameters for a TLS connection state are defined as such:33955 *33956 * struct {33957 * ConnectionEnd entity;33958 * PRFAlgorithm prf_algorithm;33959 * BulkCipherAlgorithm bulk_cipher_algorithm;33960 * CipherType cipher_type;33961 * uint8 enc_key_length;33962 * uint8 block_length;33963 * uint8 fixed_iv_length;33964 * uint8 record_iv_length;33965 * MACAlgorithm mac_algorithm;33966 * uint8 mac_length;33967 * uint8 mac_key_length;33968 * CompressionMethod compression_algorithm;33969 * opaque master_secret[48];33970 * opaque client_random[32];33971 * opaque server_random[32];33972 * } SecurityParameters;33973 *33974 * Note that this definition is from TLS 1.2. In TLS 1.0 some of these33975 * parameters are ignored because, for instance, the PRFAlgorithm is a33976 * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0.33977 *33978 * The Record Protocol requires an algorithm to generate keys required by the33979 * current connection state.33980 *33981 * The master secret is expanded into a sequence of secure bytes, which is then33982 * split to a client write MAC key, a server write MAC key, a client write33983 * encryption key, and a server write encryption key. In TLS 1.0 a client write33984 * IV and server write IV are also generated. Each of these is generated from33985 * the byte sequence in that order. Unused values are empty. In TLS 1.2, some33986 * AEAD ciphers may additionally require a client write IV and a server write33987 * IV (see Section 6.2.3.3).33988 *33989 * When keys, MAC keys, and IVs are generated, the master secret is used as an33990 * entropy source.33991 *33992 * To generate the key material, compute:33993 *33994 * master_secret = PRF(pre_master_secret, "master secret",33995 * ClientHello.random + ServerHello.random)33996 *33997 * key_block = PRF(SecurityParameters.master_secret,33998 * "key expansion",33999 * SecurityParameters.server_random +34000 * SecurityParameters.client_random);34001 *34002 * until enough output has been generated. Then, the key_block is34003 * partitioned as follows:34004 *34005 * client_write_MAC_key[SecurityParameters.mac_key_length]34006 * server_write_MAC_key[SecurityParameters.mac_key_length]34007 * client_write_key[SecurityParameters.enc_key_length]34008 * server_write_key[SecurityParameters.enc_key_length]34009 * client_write_IV[SecurityParameters.fixed_iv_length]34010 * server_write_IV[SecurityParameters.fixed_iv_length]34011 *34012 * In TLS 1.2, the client_write_IV and server_write_IV are only generated for34013 * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This34014 * implementation uses TLS 1.0 so IVs are generated.34015 *34016 * Implementation note: The currently defined cipher suite which requires the34017 * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 3234018 * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also34019 * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material.34020 *34021 * @param c the connection.34022 * @param sp the security parameters to use.34023 *34024 * @return the security keys.34025 */34026tls.generateKeys = function(c, sp) {34027 // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) &34028 // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented34029 // at present34030 // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with34031 // TLS 1.0 but we don't care right now because AES is better and we have34032 // an implementation for it34033 // TODO: TLS 1.2 implementation34034 /*34035 // determine the PRF34036 var prf;34037 switch(sp.prf_algorithm) {34038 case tls.PRFAlgorithm.tls_prf_sha256:34039 prf = prf_sha256;34040 break;34041 default:34042 // should never happen34043 throw new Error('Invalid PRF');34044 }34045 */34046 // TLS 1.0/1.1 implementation34047 var prf = prf_TLS1;34048 // concatenate server and client random34049 var random = sp.client_random + sp.server_random;34050 // only create master secret if session is new34051 if(!c.session.resuming) {34052 // create master secret, clean up pre-master secret34053 sp.master_secret = prf(34054 sp.pre_master_secret, 'master secret', random, 48).bytes();34055 sp.pre_master_secret = null;34056 }34057 // generate the amount of key material needed34058 random = sp.server_random + sp.client_random;34059 var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;34060 // include IV for TLS/1.034061 var tls10 = (c.version.major === tls.Versions.TLS_1_0.major &&34062 c.version.minor === tls.Versions.TLS_1_0.minor);34063 if(tls10) {34064 length += 2 * sp.fixed_iv_length;34065 }34066 var km = prf(sp.master_secret, 'key expansion', random, length);34067 // split the key material into the MAC and encryption keys34068 var rval = {34069 client_write_MAC_key: km.getBytes(sp.mac_key_length),34070 server_write_MAC_key: km.getBytes(sp.mac_key_length),34071 client_write_key: km.getBytes(sp.enc_key_length),34072 server_write_key: km.getBytes(sp.enc_key_length)34073 };34074 // include TLS 1.0 IVs34075 if(tls10) {34076 rval.client_write_IV = km.getBytes(sp.fixed_iv_length);34077 rval.server_write_IV = km.getBytes(sp.fixed_iv_length);34078 }34079 return rval;34080};34081/**34082 * Creates a new initialized TLS connection state. A connection state has34083 * a read mode and a write mode.34084 *34085 * compression state:34086 * The current state of the compression algorithm.34087 *34088 * cipher state:34089 * The current state of the encryption algorithm. This will consist of the34090 * scheduled key for that connection. For stream ciphers, this will also34091 * contain whatever state information is necessary to allow the stream to34092 * continue to encrypt or decrypt data.34093 *34094 * MAC key:34095 * The MAC key for the connection.34096 *34097 * sequence number:34098 * Each connection state contains a sequence number, which is maintained34099 * separately for read and write states. The sequence number MUST be set to34100 * zero whenever a connection state is made the active state. Sequence34101 * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do34102 * not wrap. If a TLS implementation would need to wrap a sequence number,34103 * it must renegotiate instead. A sequence number is incremented after each34104 * record: specifically, the first record transmitted under a particular34105 * connection state MUST use sequence number 0.34106 *34107 * @param c the connection.34108 *34109 * @return the new initialized TLS connection state.34110 */34111tls.createConnectionState = function(c) {34112 var client = (c.entity === tls.ConnectionEnd.client);34113 var createMode = function() {34114 var mode = {34115 // two 32-bit numbers, first is most significant34116 sequenceNumber: [0, 0],34117 macKey: null,34118 macLength: 0,34119 macFunction: null,34120 cipherState: null,34121 cipherFunction: function(record) {return true;},34122 compressionState: null,34123 compressFunction: function(record) {return true;},34124 updateSequenceNumber: function() {34125 if(mode.sequenceNumber[1] === 0xFFFFFFFF) {34126 mode.sequenceNumber[1] = 0;34127 ++mode.sequenceNumber[0];34128 } else {34129 ++mode.sequenceNumber[1];34130 }34131 }34132 };34133 return mode;34134 };34135 var state = {34136 read: createMode(),34137 write: createMode()34138 };34139 // update function in read mode will decrypt then decompress a record34140 state.read.update = function(c, record) {34141 if(!state.read.cipherFunction(record, state.read)) {34142 c.error(c, {34143 message: 'Could not decrypt record or bad MAC.',34144 send: true,34145 alert: {34146 level: tls.Alert.Level.fatal,34147 // doesn't matter if decryption failed or MAC was34148 // invalid, return the same error so as not to reveal34149 // which one occurred34150 description: tls.Alert.Description.bad_record_mac34151 }34152 });34153 } else if(!state.read.compressFunction(c, record, state.read)) {34154 c.error(c, {34155 message: 'Could not decompress record.',34156 send: true,34157 alert: {34158 level: tls.Alert.Level.fatal,34159 description: tls.Alert.Description.decompression_failure34160 }34161 });34162 }34163 return !c.fail;34164 };34165 // update function in write mode will compress then encrypt a record34166 state.write.update = function(c, record) {34167 if(!state.write.compressFunction(c, record, state.write)) {34168 // error, but do not send alert since it would require34169 // compression as well34170 c.error(c, {34171 message: 'Could not compress record.',34172 send: false,34173 alert: {34174 level: tls.Alert.Level.fatal,34175 description: tls.Alert.Description.internal_error34176 }34177 });34178 } else if(!state.write.cipherFunction(record, state.write)) {34179 // error, but do not send alert since it would require34180 // encryption as well34181 c.error(c, {34182 message: 'Could not encrypt record.',34183 send: false,34184 alert: {34185 level: tls.Alert.Level.fatal,34186 description: tls.Alert.Description.internal_error34187 }34188 });34189 }34190 return !c.fail;34191 };34192 // handle security parameters34193 if(c.session) {34194 var sp = c.session.sp;34195 c.session.cipherSuite.initSecurityParameters(sp);34196 // generate keys34197 sp.keys = tls.generateKeys(c, sp);34198 state.read.macKey = client ?34199 sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;34200 state.write.macKey = client ?34201 sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;34202 // cipher suite setup34203 c.session.cipherSuite.initConnectionState(state, c, sp);34204 // compression setup34205 switch(sp.compression_algorithm) {34206 case tls.CompressionMethod.none:34207 break;34208 case tls.CompressionMethod.deflate:34209 state.read.compressFunction = inflate;34210 state.write.compressFunction = deflate;34211 break;34212 default:34213 throw new Error('Unsupported compression algorithm.');34214 }34215 }34216 return state;34217};34218/**34219 * Creates a Random structure.34220 *34221 * struct {34222 * uint32 gmt_unix_time;34223 * opaque random_bytes[28];34224 * } Random;34225 *34226 * gmt_unix_time:34227 * The current time and date in standard UNIX 32-bit format (seconds since34228 * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according34229 * to the sender's internal clock. Clocks are not required to be set34230 * correctly by the basic TLS protocol; higher-level or application34231 * protocols may define additional requirements. Note that, for historical34232 * reasons, the data element is named using GMT, the predecessor of the34233 * current worldwide time base, UTC.34234 * random_bytes:34235 * 28 bytes generated by a secure random number generator.34236 *34237 * @return the Random structure as a byte array.34238 */34239tls.createRandom = function() {34240 // get UTC milliseconds34241 var d = new Date();34242 var utc = +d + d.getTimezoneOffset() * 60000;34243 var rval = forge.util.createBuffer();34244 rval.putInt32(utc);34245 rval.putBytes(forge.random.getBytes(28));34246 return rval;34247};34248/**34249 * Creates a TLS record with the given type and data.34250 *34251 * @param c the connection.34252 * @param options:34253 * type: the record type.34254 * data: the plain text data in a byte buffer.34255 *34256 * @return the created record.34257 */34258tls.createRecord = function(c, options) {34259 if(!options.data) {34260 return null;34261 }34262 var record = {34263 type: options.type,34264 version: {34265 major: c.version.major,34266 minor: c.version.minor34267 },34268 length: options.data.length(),34269 fragment: options.data34270 };34271 return record;34272};34273/**34274 * Creates a TLS alert record.34275 *34276 * @param c the connection.34277 * @param alert:34278 * level: the TLS alert level.34279 * description: the TLS alert description.34280 *34281 * @return the created alert record.34282 */34283tls.createAlert = function(c, alert) {34284 var b = forge.util.createBuffer();34285 b.putByte(alert.level);34286 b.putByte(alert.description);34287 return tls.createRecord(c, {34288 type: tls.ContentType.alert,34289 data: b34290 });34291};34292/* The structure of a TLS handshake message.34293 *34294 * struct {34295 * HandshakeType msg_type; // handshake type34296 * uint24 length; // bytes in message34297 * select(HandshakeType) {34298 * case hello_request: HelloRequest;34299 * case client_hello: ClientHello;34300 * case server_hello: ServerHello;34301 * case certificate: Certificate;34302 * case server_key_exchange: ServerKeyExchange;34303 * case certificate_request: CertificateRequest;34304 * case server_hello_done: ServerHelloDone;34305 * case certificate_verify: CertificateVerify;34306 * case client_key_exchange: ClientKeyExchange;34307 * case finished: Finished;34308 * } body;34309 * } Handshake;34310 */34311/**34312 * Creates a ClientHello message.34313 *34314 * opaque SessionID<0..32>;34315 * enum { null(0), deflate(1), (255) } CompressionMethod;34316 * uint8 CipherSuite[2];34317 *34318 * struct {34319 * ProtocolVersion client_version;34320 * Random random;34321 * SessionID session_id;34322 * CipherSuite cipher_suites<2..2^16-2>;34323 * CompressionMethod compression_methods<1..2^8-1>;34324 * select(extensions_present) {34325 * case false:34326 * struct {};34327 * case true:34328 * Extension extensions<0..2^16-1>;34329 * };34330 * } ClientHello;34331 *34332 * The extension format for extended client hellos and server hellos is:34333 *34334 * struct {34335 * ExtensionType extension_type;34336 * opaque extension_data<0..2^16-1>;34337 * } Extension;34338 *34339 * Here:34340 *34341 * - "extension_type" identifies the particular extension type.34342 * - "extension_data" contains information specific to the particular34343 * extension type.34344 *34345 * The extension types defined in this document are:34346 *34347 * enum {34348 * server_name(0), max_fragment_length(1),34349 * client_certificate_url(2), trusted_ca_keys(3),34350 * truncated_hmac(4), status_request(5), (65535)34351 * } ExtensionType;34352 *34353 * @param c the connection.34354 *34355 * @return the ClientHello byte buffer.34356 */34357tls.createClientHello = function(c) {34358 // save hello version34359 c.session.clientHelloVersion = {34360 major: c.version.major,34361 minor: c.version.minor34362 };34363 // create supported cipher suites34364 var cipherSuites = forge.util.createBuffer();34365 for(var i = 0; i < c.cipherSuites.length; ++i) {34366 var cs = c.cipherSuites[i];34367 cipherSuites.putByte(cs.id[0]);34368 cipherSuites.putByte(cs.id[1]);34369 }34370 var cSuites = cipherSuites.length();34371 // create supported compression methods, null always supported, but34372 // also support deflate if connection has inflate and deflate methods34373 var compressionMethods = forge.util.createBuffer();34374 compressionMethods.putByte(tls.CompressionMethod.none);34375 // FIXME: deflate support disabled until issues with raw deflate data34376 // without zlib headers are resolved34377 /*34378 if(c.inflate !== null && c.deflate !== null) {34379 compressionMethods.putByte(tls.CompressionMethod.deflate);34380 }34381 */34382 var cMethods = compressionMethods.length();34383 // create TLS SNI (server name indication) extension if virtual host34384 // has been specified, see RFC 354634385 var extensions = forge.util.createBuffer();34386 if(c.virtualHost) {34387 // create extension struct34388 var ext = forge.util.createBuffer();34389 ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes)34390 ext.putByte(0x00);34391 /* In order to provide the server name, clients MAY include an34392 * extension of type "server_name" in the (extended) client hello.34393 * The "extension_data" field of this extension SHALL contain34394 * "ServerNameList" where:34395 *34396 * struct {34397 * NameType name_type;34398 * select(name_type) {34399 * case host_name: HostName;34400 * } name;34401 * } ServerName;34402 *34403 * enum {34404 * host_name(0), (255)34405 * } NameType;34406 *34407 * opaque HostName<1..2^16-1>;34408 *34409 * struct {34410 * ServerName server_name_list<1..2^16-1>34411 * } ServerNameList;34412 */34413 var serverName = forge.util.createBuffer();34414 serverName.putByte(0x00); // type host_name34415 writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost));34416 // ServerNameList is in extension_data34417 var snList = forge.util.createBuffer();34418 writeVector(snList, 2, serverName);34419 writeVector(ext, 2, snList);34420 extensions.putBuffer(ext);34421 }34422 var extLength = extensions.length();34423 if(extLength > 0) {34424 // add extension vector length34425 extLength += 2;34426 }34427 // determine length of the handshake message34428 // cipher suites and compression methods size will need to be34429 // updated if more get added to the list34430 var sessionId = c.session.id;34431 var length =34432 sessionId.length + 1 + // session ID vector34433 2 + // version (major + minor)34434 4 + 28 + // random time and random bytes34435 2 + cSuites + // cipher suites vector34436 1 + cMethods + // compression methods vector34437 extLength; // extensions vector34438 // build record fragment34439 var rval = forge.util.createBuffer();34440 rval.putByte(tls.HandshakeType.client_hello);34441 rval.putInt24(length); // handshake length34442 rval.putByte(c.version.major); // major version34443 rval.putByte(c.version.minor); // minor version34444 rval.putBytes(c.session.sp.client_random); // random time + bytes34445 writeVector(rval, 1, forge.util.createBuffer(sessionId));34446 writeVector(rval, 2, cipherSuites);34447 writeVector(rval, 1, compressionMethods);34448 if(extLength > 0) {34449 writeVector(rval, 2, extensions);34450 }34451 return rval;34452};34453/**34454 * Creates a ServerHello message.34455 *34456 * @param c the connection.34457 *34458 * @return the ServerHello byte buffer.34459 */34460tls.createServerHello = function(c) {34461 // determine length of the handshake message34462 var sessionId = c.session.id;34463 var length =34464 sessionId.length + 1 + // session ID vector34465 2 + // version (major + minor)34466 4 + 28 + // random time and random bytes34467 2 + // chosen cipher suite34468 1; // chosen compression method34469 // build record fragment34470 var rval = forge.util.createBuffer();34471 rval.putByte(tls.HandshakeType.server_hello);34472 rval.putInt24(length); // handshake length34473 rval.putByte(c.version.major); // major version34474 rval.putByte(c.version.minor); // minor version34475 rval.putBytes(c.session.sp.server_random); // random time + bytes34476 writeVector(rval, 1, forge.util.createBuffer(sessionId));34477 rval.putByte(c.session.cipherSuite.id[0]);34478 rval.putByte(c.session.cipherSuite.id[1]);34479 rval.putByte(c.session.compressionMethod);34480 return rval;34481};34482/**34483 * Creates a Certificate message.34484 *34485 * When this message will be sent:34486 * This is the first message the client can send after receiving a server34487 * hello done message and the first message the server can send after34488 * sending a ServerHello. This client message is only sent if the server34489 * requests a certificate. If no suitable certificate is available, the34490 * client should send a certificate message containing no certificates. If34491 * client authentication is required by the server for the handshake to34492 * continue, it may respond with a fatal handshake failure alert.34493 *34494 * opaque ASN.1Cert<1..2^24-1>;34495 *34496 * struct {34497 * ASN.1Cert certificate_list<0..2^24-1>;34498 * } Certificate;34499 *34500 * @param c the connection.34501 *34502 * @return the Certificate byte buffer.34503 */34504tls.createCertificate = function(c) {34505 // TODO: check certificate request to ensure types are supported34506 // get a certificate (a certificate as a PEM string)34507 var client = (c.entity === tls.ConnectionEnd.client);34508 var cert = null;34509 if(c.getCertificate) {34510 var hint;34511 if(client) {34512 hint = c.session.certificateRequest;34513 } else {34514 hint = c.session.extensions.server_name.serverNameList;34515 }34516 cert = c.getCertificate(c, hint);34517 }34518 // buffer to hold certificate list34519 var certList = forge.util.createBuffer();34520 if(cert !== null) {34521 try {34522 // normalize cert to a chain of certificates34523 if(!forge.util.isArray(cert)) {34524 cert = [cert];34525 }34526 var asn1 = null;34527 for(var i = 0; i < cert.length; ++i) {34528 var msg = forge.pem.decode(cert[i])[0];34529 if(msg.type !== 'CERTIFICATE' &&34530 msg.type !== 'X509 CERTIFICATE' &&34531 msg.type !== 'TRUSTED CERTIFICATE') {34532 var error = new Error('Could not convert certificate from PEM; PEM ' +34533 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' +34534 '"TRUSTED CERTIFICATE".');34535 error.headerType = msg.type;34536 throw error;34537 }34538 if(msg.procType && msg.procType.type === 'ENCRYPTED') {34539 throw new Error('Could not convert certificate from PEM; PEM is encrypted.');34540 }34541 var der = forge.util.createBuffer(msg.body);34542 if(asn1 === null) {34543 asn1 = forge.asn1.fromDer(der.bytes(), false);34544 }34545 // certificate entry is itself a vector with 3 length bytes34546 var certBuffer = forge.util.createBuffer();34547 writeVector(certBuffer, 3, der);34548 // add cert vector to cert list vector34549 certList.putBuffer(certBuffer);34550 }34551 // save certificate34552 cert = forge.pki.certificateFromAsn1(asn1);34553 if(client) {34554 c.session.clientCertificate = cert;34555 } else {34556 c.session.serverCertificate = cert;34557 }34558 } catch(ex) {34559 return c.error(c, {34560 message: 'Could not send certificate list.',34561 cause: ex,34562 send: true,34563 alert: {34564 level: tls.Alert.Level.fatal,34565 description: tls.Alert.Description.bad_certificate34566 }34567 });34568 }34569 }34570 // determine length of the handshake message34571 var length = 3 + certList.length(); // cert list vector34572 // build record fragment34573 var rval = forge.util.createBuffer();34574 rval.putByte(tls.HandshakeType.certificate);34575 rval.putInt24(length);34576 writeVector(rval, 3, certList);34577 return rval;34578};34579/**34580 * Creates a ClientKeyExchange message.34581 *34582 * When this message will be sent:34583 * This message is always sent by the client. It will immediately follow the34584 * client certificate message, if it is sent. Otherwise it will be the first34585 * message sent by the client after it receives the server hello done34586 * message.34587 *34588 * Meaning of this message:34589 * With this message, the premaster secret is set, either though direct34590 * transmission of the RSA-encrypted secret, or by the transmission of34591 * Diffie-Hellman parameters which will allow each side to agree upon the34592 * same premaster secret. When the key exchange method is DH_RSA or DH_DSS,34593 * client certification has been requested, and the client was able to34594 * respond with a certificate which contained a Diffie-Hellman public key34595 * whose parameters (group and generator) matched those specified by the34596 * server in its certificate, this message will not contain any data.34597 *34598 * Meaning of this message:34599 * If RSA is being used for key agreement and authentication, the client34600 * generates a 48-byte premaster secret, encrypts it using the public key34601 * from the server's certificate or the temporary RSA key provided in a34602 * server key exchange message, and sends the result in an encrypted34603 * premaster secret message. This structure is a variant of the client34604 * key exchange message, not a message in itself.34605 *34606 * struct {34607 * select(KeyExchangeAlgorithm) {34608 * case rsa: EncryptedPreMasterSecret;34609 * case diffie_hellman: ClientDiffieHellmanPublic;34610 * } exchange_keys;34611 * } ClientKeyExchange;34612 *34613 * struct {34614 * ProtocolVersion client_version;34615 * opaque random[46];34616 * } PreMasterSecret;34617 *34618 * struct {34619 * public-key-encrypted PreMasterSecret pre_master_secret;34620 * } EncryptedPreMasterSecret;34621 *34622 * A public-key-encrypted element is encoded as a vector <0..2^16-1>.34623 *34624 * @param c the connection.34625 *34626 * @return the ClientKeyExchange byte buffer.34627 */34628tls.createClientKeyExchange = function(c) {34629 // create buffer to encrypt34630 var b = forge.util.createBuffer();34631 // add highest client-supported protocol to help server avoid version34632 // rollback attacks34633 b.putByte(c.session.clientHelloVersion.major);34634 b.putByte(c.session.clientHelloVersion.minor);34635 // generate and add 46 random bytes34636 b.putBytes(forge.random.getBytes(46));34637 // save pre-master secret34638 var sp = c.session.sp;34639 sp.pre_master_secret = b.getBytes();34640 // RSA-encrypt the pre-master secret34641 var key = c.session.serverCertificate.publicKey;34642 b = key.encrypt(sp.pre_master_secret);34643 /* Note: The encrypted pre-master secret will be stored in a34644 public-key-encrypted opaque vector that has the length prefixed using34645 2 bytes, so include those 2 bytes in the handshake message length. This34646 is done as a minor optimization instead of calling writeVector(). */34647 // determine length of the handshake message34648 var length = b.length + 2;34649 // build record fragment34650 var rval = forge.util.createBuffer();34651 rval.putByte(tls.HandshakeType.client_key_exchange);34652 rval.putInt24(length);34653 // add vector length bytes34654 rval.putInt16(b.length);34655 rval.putBytes(b);34656 return rval;34657};34658/**34659 * Creates a ServerKeyExchange message.34660 *34661 * @param c the connection.34662 *34663 * @return the ServerKeyExchange byte buffer.34664 */34665tls.createServerKeyExchange = function(c) {34666 // this implementation only supports RSA, no Diffie-Hellman support,34667 // so this record is empty34668 // determine length of the handshake message34669 var length = 0;34670 // build record fragment34671 var rval = forge.util.createBuffer();34672 if(length > 0) {34673 rval.putByte(tls.HandshakeType.server_key_exchange);34674 rval.putInt24(length);34675 }34676 return rval;34677};34678/**34679 * Gets the signed data used to verify a client-side certificate. See34680 * tls.createCertificateVerify() for details.34681 *34682 * @param c the connection.34683 * @param callback the callback to call once the signed data is ready.34684 */34685tls.getClientSignature = function(c, callback) {34686 // generate data to RSA encrypt34687 var b = forge.util.createBuffer();34688 b.putBuffer(c.session.md5.digest());34689 b.putBuffer(c.session.sha1.digest());34690 b = b.getBytes();34691 // create default signing function as necessary34692 c.getSignature = c.getSignature || function(c, b, callback) {34693 // do rsa encryption, call callback34694 var privateKey = null;34695 if(c.getPrivateKey) {34696 try {34697 privateKey = c.getPrivateKey(c, c.session.clientCertificate);34698 privateKey = forge.pki.privateKeyFromPem(privateKey);34699 } catch(ex) {34700 c.error(c, {34701 message: 'Could not get private key.',34702 cause: ex,34703 send: true,34704 alert: {34705 level: tls.Alert.Level.fatal,34706 description: tls.Alert.Description.internal_error34707 }34708 });34709 }34710 }34711 if(privateKey === null) {34712 c.error(c, {34713 message: 'No private key set.',34714 send: true,34715 alert: {34716 level: tls.Alert.Level.fatal,34717 description: tls.Alert.Description.internal_error34718 }34719 });34720 } else {34721 b = privateKey.sign(b, null);34722 }34723 callback(c, b);34724 };34725 // get client signature34726 c.getSignature(c, b, callback);34727};34728/**34729 * Creates a CertificateVerify message.34730 *34731 * Meaning of this message:34732 * This structure conveys the client's Diffie-Hellman public value34733 * (Yc) if it was not already included in the client's certificate.34734 * The encoding used for Yc is determined by the enumerated34735 * PublicValueEncoding. This structure is a variant of the client34736 * key exchange message, not a message in itself.34737 *34738 * When this message will be sent:34739 * This message is used to provide explicit verification of a client34740 * certificate. This message is only sent following a client34741 * certificate that has signing capability (i.e. all certificates34742 * except those containing fixed Diffie-Hellman parameters). When34743 * sent, it will immediately follow the client key exchange message.34744 *34745 * struct {34746 * Signature signature;34747 * } CertificateVerify;34748 *34749 * CertificateVerify.signature.md5_hash34750 * MD5(handshake_messages);34751 *34752 * Certificate.signature.sha_hash34753 * SHA(handshake_messages);34754 *34755 * Here handshake_messages refers to all handshake messages sent or34756 * received starting at client hello up to but not including this34757 * message, including the type and length fields of the handshake34758 * messages.34759 *34760 * select(SignatureAlgorithm) {34761 * case anonymous: struct { };34762 * case rsa:34763 * digitally-signed struct {34764 * opaque md5_hash[16];34765 * opaque sha_hash[20];34766 * };34767 * case dsa:34768 * digitally-signed struct {34769 * opaque sha_hash[20];34770 * };34771 * } Signature;34772 *34773 * In digital signing, one-way hash functions are used as input for a34774 * signing algorithm. A digitally-signed element is encoded as an opaque34775 * vector <0..2^16-1>, where the length is specified by the signing34776 * algorithm and key.34777 *34778 * In RSA signing, a 36-byte structure of two hashes (one SHA and one34779 * MD5) is signed (encrypted with the private key). It is encoded with34780 * PKCS #1 block type 0 or type 1 as described in [PKCS1].34781 *34782 * In DSS, the 20 bytes of the SHA hash are run directly through the34783 * Digital Signing Algorithm with no additional hashing.34784 *34785 * @param c the connection.34786 * @param signature the signature to include in the message.34787 *34788 * @return the CertificateVerify byte buffer.34789 */34790tls.createCertificateVerify = function(c, signature) {34791 /* Note: The signature will be stored in a "digitally-signed" opaque34792 vector that has the length prefixed using 2 bytes, so include those34793 2 bytes in the handshake message length. This is done as a minor34794 optimization instead of calling writeVector(). */34795 // determine length of the handshake message34796 var length = signature.length + 2;34797 // build record fragment34798 var rval = forge.util.createBuffer();34799 rval.putByte(tls.HandshakeType.certificate_verify);34800 rval.putInt24(length);34801 // add vector length bytes34802 rval.putInt16(signature.length);34803 rval.putBytes(signature);34804 return rval;34805};34806/**34807 * Creates a CertificateRequest message.34808 *34809 * @param c the connection.34810 *34811 * @return the CertificateRequest byte buffer.34812 */34813tls.createCertificateRequest = function(c) {34814 // TODO: support other certificate types34815 var certTypes = forge.util.createBuffer();34816 // common RSA certificate type34817 certTypes.putByte(0x01);34818 // add distinguished names from CA store34819 var cAs = forge.util.createBuffer();34820 for(var key in c.caStore.certs) {34821 var cert = c.caStore.certs[key];34822 var dn = forge.pki.distinguishedNameToAsn1(cert.subject);34823 var byteBuffer = forge.asn1.toDer(dn);34824 cAs.putInt16(byteBuffer.length());34825 cAs.putBuffer(byteBuffer);34826 }34827 // TODO: TLS 1.2+ has a different format34828 // determine length of the handshake message34829 var length =34830 1 + certTypes.length() +34831 2 + cAs.length();34832 // build record fragment34833 var rval = forge.util.createBuffer();34834 rval.putByte(tls.HandshakeType.certificate_request);34835 rval.putInt24(length);34836 writeVector(rval, 1, certTypes);34837 writeVector(rval, 2, cAs);34838 return rval;34839};34840/**34841 * Creates a ServerHelloDone message.34842 *34843 * @param c the connection.34844 *34845 * @return the ServerHelloDone byte buffer.34846 */34847tls.createServerHelloDone = function(c) {34848 // build record fragment34849 var rval = forge.util.createBuffer();34850 rval.putByte(tls.HandshakeType.server_hello_done);34851 rval.putInt24(0);34852 return rval;34853};34854/**34855 * Creates a ChangeCipherSpec message.34856 *34857 * The change cipher spec protocol exists to signal transitions in34858 * ciphering strategies. The protocol consists of a single message,34859 * which is encrypted and compressed under the current (not the pending)34860 * connection state. The message consists of a single byte of value 1.34861 *34862 * struct {34863 * enum { change_cipher_spec(1), (255) } type;34864 * } ChangeCipherSpec;34865 *34866 * @return the ChangeCipherSpec byte buffer.34867 */34868tls.createChangeCipherSpec = function() {34869 var rval = forge.util.createBuffer();34870 rval.putByte(0x01);34871 return rval;34872};34873/**34874 * Creates a Finished message.34875 *34876 * struct {34877 * opaque verify_data[12];34878 * } Finished;34879 *34880 * verify_data34881 * PRF(master_secret, finished_label, MD5(handshake_messages) +34882 * SHA-1(handshake_messages)) [0..11];34883 *34884 * finished_label34885 * For Finished messages sent by the client, the string "client34886 * finished". For Finished messages sent by the server, the34887 * string "server finished".34888 *34889 * handshake_messages34890 * All of the data from all handshake messages up to but not34891 * including this message. This is only data visible at the34892 * handshake layer and does not include record layer headers.34893 * This is the concatenation of all the Handshake structures as34894 * defined in 7.4 exchanged thus far.34895 *34896 * @param c the connection.34897 *34898 * @return the Finished byte buffer.34899 */34900tls.createFinished = function(c) {34901 // generate verify_data34902 var b = forge.util.createBuffer();34903 b.putBuffer(c.session.md5.digest());34904 b.putBuffer(c.session.sha1.digest());34905 // TODO: determine prf function and verify length for TLS 1.234906 var client = (c.entity === tls.ConnectionEnd.client);34907 var sp = c.session.sp;34908 var vdl = 12;34909 var prf = prf_TLS1;34910 var label = client ? 'client finished' : 'server finished';34911 b = prf(sp.master_secret, label, b.getBytes(), vdl);34912 // build record fragment34913 var rval = forge.util.createBuffer();34914 rval.putByte(tls.HandshakeType.finished);34915 rval.putInt24(b.length());34916 rval.putBuffer(b);34917 return rval;34918};34919/**34920 * Creates a HeartbeatMessage (See RFC 6520).34921 *34922 * struct {34923 * HeartbeatMessageType type;34924 * uint16 payload_length;34925 * opaque payload[HeartbeatMessage.payload_length];34926 * opaque padding[padding_length];34927 * } HeartbeatMessage;34928 *34929 * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or34930 * max_fragment_length when negotiated as defined in [RFC6066].34931 *34932 * type: The message type, either heartbeat_request or heartbeat_response.34933 *34934 * payload_length: The length of the payload.34935 *34936 * payload: The payload consists of arbitrary content.34937 *34938 * padding: The padding is random content that MUST be ignored by the34939 * receiver. The length of a HeartbeatMessage is TLSPlaintext.length34940 * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the34941 * length of the type field is 1 byte, and the length of the34942 * payload_length is 2. Therefore, the padding_length is34943 * TLSPlaintext.length - payload_length - 3 for TLS and34944 * DTLSPlaintext.length - payload_length - 3 for DTLS. The34945 * padding_length MUST be at least 16.34946 *34947 * The sender of a HeartbeatMessage MUST use a random padding of at34948 * least 16 bytes. The padding of a received HeartbeatMessage message34949 * MUST be ignored.34950 *34951 * If the payload_length of a received HeartbeatMessage is too large,34952 * the received HeartbeatMessage MUST be discarded silently.34953 *34954 * @param c the connection.34955 * @param type the tls.HeartbeatMessageType.34956 * @param payload the heartbeat data to send as the payload.34957 * @param [payloadLength] the payload length to use, defaults to the34958 * actual payload length.34959 *34960 * @return the HeartbeatRequest byte buffer.34961 */34962tls.createHeartbeat = function(type, payload, payloadLength) {34963 if(typeof payloadLength === 'undefined') {34964 payloadLength = payload.length;34965 }34966 // build record fragment34967 var rval = forge.util.createBuffer();34968 rval.putByte(type); // heartbeat message type34969 rval.putInt16(payloadLength); // payload length34970 rval.putBytes(payload); // payload34971 // padding34972 var plaintextLength = rval.length();34973 var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);34974 rval.putBytes(forge.random.getBytes(paddingLength));34975 return rval;34976};34977/**34978 * Fragments, compresses, encrypts, and queues a record for delivery.34979 *34980 * @param c the connection.34981 * @param record the record to queue.34982 */34983tls.queue = function(c, record) {34984 // error during record creation34985 if(!record) {34986 return;34987 }34988 if(record.fragment.length() === 0) {34989 if(record.type === tls.ContentType.handshake ||34990 record.type === tls.ContentType.alert ||34991 record.type === tls.ContentType.change_cipher_spec) {34992 // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent.34993 return;34994 }34995 }34996 // if the record is a handshake record, update handshake hashes34997 if(record.type === tls.ContentType.handshake) {34998 var bytes = record.fragment.bytes();34999 c.session.md5.update(bytes);35000 c.session.sha1.update(bytes);35001 bytes = null;35002 }35003 // handle record fragmentation35004 var records;35005 if(record.fragment.length() <= tls.MaxFragment) {35006 records = [record];35007 } else {35008 // fragment data as long as it is too long35009 records = [];35010 var data = record.fragment.bytes();35011 while(data.length > tls.MaxFragment) {35012 records.push(tls.createRecord(c, {35013 type: record.type,35014 data: forge.util.createBuffer(data.slice(0, tls.MaxFragment))35015 }));35016 data = data.slice(tls.MaxFragment);35017 }35018 // add last record35019 if(data.length > 0) {35020 records.push(tls.createRecord(c, {35021 type: record.type,35022 data: forge.util.createBuffer(data)35023 }));35024 }35025 }35026 // compress and encrypt all fragmented records35027 for(var i = 0; i < records.length && !c.fail; ++i) {35028 // update the record using current write state35029 var rec = records[i];35030 var s = c.state.current.write;35031 if(s.update(c, rec)) {35032 // store record35033 c.records.push(rec);35034 }35035 }35036};35037/**35038 * Flushes all queued records to the output buffer and calls the35039 * tlsDataReady() handler on the given connection.35040 *35041 * @param c the connection.35042 *35043 * @return true on success, false on failure.35044 */35045tls.flush = function(c) {35046 for(var i = 0; i < c.records.length; ++i) {35047 var record = c.records[i];35048 // add record header and fragment35049 c.tlsData.putByte(record.type);35050 c.tlsData.putByte(record.version.major);35051 c.tlsData.putByte(record.version.minor);35052 c.tlsData.putInt16(record.fragment.length());35053 c.tlsData.putBuffer(c.records[i].fragment);35054 }35055 c.records = [];35056 return c.tlsDataReady(c);35057};35058/**35059 * Maps a pki.certificateError to a tls.Alert.Description.35060 *35061 * @param error the error to map.35062 *35063 * @return the alert description.35064 */35065var _certErrorToAlertDesc = function(error) {35066 switch(error) {35067 case true:35068 return true;35069 case forge.pki.certificateError.bad_certificate:35070 return tls.Alert.Description.bad_certificate;35071 case forge.pki.certificateError.unsupported_certificate:35072 return tls.Alert.Description.unsupported_certificate;35073 case forge.pki.certificateError.certificate_revoked:35074 return tls.Alert.Description.certificate_revoked;35075 case forge.pki.certificateError.certificate_expired:35076 return tls.Alert.Description.certificate_expired;35077 case forge.pki.certificateError.certificate_unknown:35078 return tls.Alert.Description.certificate_unknown;35079 case forge.pki.certificateError.unknown_ca:35080 return tls.Alert.Description.unknown_ca;35081 default:35082 return tls.Alert.Description.bad_certificate;35083 }35084};35085/**35086 * Maps a tls.Alert.Description to a pki.certificateError.35087 *35088 * @param desc the alert description.35089 *35090 * @return the certificate error.35091 */35092var _alertDescToCertError = function(desc) {35093 switch(desc) {35094 case true:35095 return true;35096 case tls.Alert.Description.bad_certificate:35097 return forge.pki.certificateError.bad_certificate;35098 case tls.Alert.Description.unsupported_certificate:35099 return forge.pki.certificateError.unsupported_certificate;35100 case tls.Alert.Description.certificate_revoked:35101 return forge.pki.certificateError.certificate_revoked;35102 case tls.Alert.Description.certificate_expired:35103 return forge.pki.certificateError.certificate_expired;35104 case tls.Alert.Description.certificate_unknown:35105 return forge.pki.certificateError.certificate_unknown;35106 case tls.Alert.Description.unknown_ca:35107 return forge.pki.certificateError.unknown_ca;35108 default:35109 return forge.pki.certificateError.bad_certificate;35110 }35111};35112/**35113 * Verifies a certificate chain against the given connection's35114 * Certificate Authority store.35115 *35116 * @param c the TLS connection.35117 * @param chain the certificate chain to verify, with the root or highest35118 * authority at the end.35119 *35120 * @return true if successful, false if not.35121 */35122tls.verifyCertificateChain = function(c, chain) {35123 try {35124 // Make a copy of c.verifyOptions so that we can modify options.verify35125 // without modifying c.verifyOptions.35126 var options = {};35127 for (var key in c.verifyOptions) {35128 options[key] = c.verifyOptions[key];35129 }35130 options.verify = function(vfd, depth, chain) {35131 // convert pki.certificateError to tls alert description35132 var desc = _certErrorToAlertDesc(vfd);35133 // call application callback35134 var ret = c.verify(c, vfd, depth, chain);35135 if(ret !== true) {35136 if(typeof ret === 'object' && !forge.util.isArray(ret)) {35137 // throw custom error35138 var error = new Error('The application rejected the certificate.');35139 error.send = true;35140 error.alert = {35141 level: tls.Alert.Level.fatal,35142 description: tls.Alert.Description.bad_certificate35143 };35144 if(ret.message) {35145 error.message = ret.message;35146 }35147 if(ret.alert) {35148 error.alert.description = ret.alert;35149 }35150 throw error;35151 }35152 // convert tls alert description to pki.certificateError35153 if(ret !== vfd) {35154 ret = _alertDescToCertError(ret);35155 }35156 }35157 return ret;35158 };35159 // verify chain35160 forge.pki.verifyCertificateChain(c.caStore, chain, options);35161 } catch(ex) {35162 // build tls error if not already customized35163 var err = ex;35164 if(typeof err !== 'object' || forge.util.isArray(err)) {35165 err = {35166 send: true,35167 alert: {35168 level: tls.Alert.Level.fatal,35169 description: _certErrorToAlertDesc(ex)35170 }35171 };35172 }35173 if(!('send' in err)) {35174 err.send = true;35175 }35176 if(!('alert' in err)) {35177 err.alert = {35178 level: tls.Alert.Level.fatal,35179 description: _certErrorToAlertDesc(err.error)35180 };35181 }35182 // send error35183 c.error(c, err);35184 }35185 return !c.fail;35186};35187/**35188 * Creates a new TLS session cache.35189 *35190 * @param cache optional map of session ID to cached session.35191 * @param capacity the maximum size for the cache (default: 100).35192 *35193 * @return the new TLS session cache.35194 */35195tls.createSessionCache = function(cache, capacity) {35196 var rval = null;35197 // assume input is already a session cache object35198 if(cache && cache.getSession && cache.setSession && cache.order) {35199 rval = cache;35200 } else {35201 // create cache35202 rval = {};35203 rval.cache = cache || {};35204 rval.capacity = Math.max(capacity || 100, 1);35205 rval.order = [];35206 // store order for sessions, delete session overflow35207 for(var key in cache) {35208 if(rval.order.length <= capacity) {35209 rval.order.push(key);35210 } else {35211 delete cache[key];35212 }35213 }35214 // get a session from a session ID (or get any session)35215 rval.getSession = function(sessionId) {35216 var session = null;35217 var key = null;35218 // if session ID provided, use it35219 if(sessionId) {35220 key = forge.util.bytesToHex(sessionId);35221 } else if(rval.order.length > 0) {35222 // get first session from cache35223 key = rval.order[0];35224 }35225 if(key !== null && key in rval.cache) {35226 // get cached session and remove from cache35227 session = rval.cache[key];35228 delete rval.cache[key];35229 for(var i in rval.order) {35230 if(rval.order[i] === key) {35231 rval.order.splice(i, 1);35232 break;35233 }35234 }35235 }35236 return session;35237 };35238 // set a session in the cache35239 rval.setSession = function(sessionId, session) {35240 // remove session from cache if at capacity35241 if(rval.order.length === rval.capacity) {35242 var key = rval.order.shift();35243 delete rval.cache[key];35244 }35245 // add session to cache35246 var key = forge.util.bytesToHex(sessionId);35247 rval.order.push(key);35248 rval.cache[key] = session;35249 };35250 }35251 return rval;35252};35253/**35254 * Creates a new TLS connection.35255 *35256 * See public createConnection() docs for more details.35257 *35258 * @param options the options for this connection.35259 *35260 * @return the new TLS connection.35261 */35262tls.createConnection = function(options) {35263 var caStore = null;35264 if(options.caStore) {35265 // if CA store is an array, convert it to a CA store object35266 if(forge.util.isArray(options.caStore)) {35267 caStore = forge.pki.createCaStore(options.caStore);35268 } else {35269 caStore = options.caStore;35270 }35271 } else {35272 // create empty CA store35273 caStore = forge.pki.createCaStore();35274 }35275 // setup default cipher suites35276 var cipherSuites = options.cipherSuites || null;35277 if(cipherSuites === null) {35278 cipherSuites = [];35279 for(var key in tls.CipherSuites) {35280 cipherSuites.push(tls.CipherSuites[key]);35281 }35282 }35283 // set default entity35284 var entity = (options.server || false) ?35285 tls.ConnectionEnd.server : tls.ConnectionEnd.client;35286 // create session cache if requested35287 var sessionCache = options.sessionCache ?35288 tls.createSessionCache(options.sessionCache) : null;35289 // create TLS connection35290 var c = {35291 version: {major: tls.Version.major, minor: tls.Version.minor},35292 entity: entity,35293 sessionId: options.sessionId,35294 caStore: caStore,35295 sessionCache: sessionCache,35296 cipherSuites: cipherSuites,35297 connected: options.connected,35298 virtualHost: options.virtualHost || null,35299 verifyClient: options.verifyClient || false,35300 verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;},35301 verifyOptions: options.verifyOptions || {},35302 getCertificate: options.getCertificate || null,35303 getPrivateKey: options.getPrivateKey || null,35304 getSignature: options.getSignature || null,35305 input: forge.util.createBuffer(),35306 tlsData: forge.util.createBuffer(),35307 data: forge.util.createBuffer(),35308 tlsDataReady: options.tlsDataReady,35309 dataReady: options.dataReady,35310 heartbeatReceived: options.heartbeatReceived,35311 closed: options.closed,35312 error: function(c, ex) {35313 // set origin if not set35314 ex.origin = ex.origin ||35315 ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server');35316 // send TLS alert35317 if(ex.send) {35318 tls.queue(c, tls.createAlert(c, ex.alert));35319 tls.flush(c);35320 }35321 // error is fatal by default35322 var fatal = (ex.fatal !== false);35323 if(fatal) {35324 // set fail flag35325 c.fail = true;35326 }35327 // call error handler first35328 options.error(c, ex);35329 if(fatal) {35330 // fatal error, close connection, do not clear fail35331 c.close(false);35332 }35333 },35334 deflate: options.deflate || null,35335 inflate: options.inflate || null35336 };35337 /**35338 * Resets a closed TLS connection for reuse. Called in c.close().35339 *35340 * @param clearFail true to clear the fail flag (default: true).35341 */35342 c.reset = function(clearFail) {35343 c.version = {major: tls.Version.major, minor: tls.Version.minor};35344 c.record = null;35345 c.session = null;35346 c.peerCertificate = null;35347 c.state = {35348 pending: null,35349 current: null35350 };35351 c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE;35352 c.fragmented = null;35353 c.records = [];35354 c.open = false;35355 c.handshakes = 0;35356 c.handshaking = false;35357 c.isConnected = false;35358 c.fail = !(clearFail || typeof(clearFail) === 'undefined');35359 c.input.clear();35360 c.tlsData.clear();35361 c.data.clear();35362 c.state.current = tls.createConnectionState(c);35363 };35364 // do initial reset of connection35365 c.reset();35366 /**35367 * Updates the current TLS engine state based on the given record.35368 *35369 * @param c the TLS connection.35370 * @param record the TLS record to act on.35371 */35372 var _update = function(c, record) {35373 // get record handler (align type in table by subtracting lowest)35374 var aligned = record.type - tls.ContentType.change_cipher_spec;35375 var handlers = ctTable[c.entity][c.expect];35376 if(aligned in handlers) {35377 handlers[aligned](c, record);35378 } else {35379 // unexpected record35380 tls.handleUnexpected(c, record);35381 }35382 };35383 /**35384 * Reads the record header and initializes the next record on the given35385 * connection.35386 *35387 * @param c the TLS connection with the next record.35388 *35389 * @return 0 if the input data could be processed, otherwise the35390 * number of bytes required for data to be processed.35391 */35392 var _readRecordHeader = function(c) {35393 var rval = 0;35394 // get input buffer and its length35395 var b = c.input;35396 var len = b.length();35397 // need at least 5 bytes to initialize a record35398 if(len < 5) {35399 rval = 5 - len;35400 } else {35401 // enough bytes for header35402 // initialize record35403 c.record = {35404 type: b.getByte(),35405 version: {35406 major: b.getByte(),35407 minor: b.getByte()35408 },35409 length: b.getInt16(),35410 fragment: forge.util.createBuffer(),35411 ready: false35412 };35413 // check record version35414 var compatibleVersion = (c.record.version.major === c.version.major);35415 if(compatibleVersion && c.session && c.session.version) {35416 // session version already set, require same minor version35417 compatibleVersion = (c.record.version.minor === c.version.minor);35418 }35419 if(!compatibleVersion) {35420 c.error(c, {35421 message: 'Incompatible TLS version.',35422 send: true,35423 alert: {35424 level: tls.Alert.Level.fatal,35425 description: tls.Alert.Description.protocol_version35426 }35427 });35428 }35429 }35430 return rval;35431 };35432 /**35433 * Reads the next record's contents and appends its message to any35434 * previously fragmented message.35435 *35436 * @param c the TLS connection with the next record.35437 *35438 * @return 0 if the input data could be processed, otherwise the35439 * number of bytes required for data to be processed.35440 */35441 var _readRecord = function(c) {35442 var rval = 0;35443 // ensure there is enough input data to get the entire record35444 var b = c.input;35445 var len = b.length();35446 if(len < c.record.length) {35447 // not enough data yet, return how much is required35448 rval = c.record.length - len;35449 } else {35450 // there is enough data to parse the pending record35451 // fill record fragment and compact input buffer35452 c.record.fragment.putBytes(b.getBytes(c.record.length));35453 b.compact();35454 // update record using current read state35455 var s = c.state.current.read;35456 if(s.update(c, c.record)) {35457 // see if there is a previously fragmented message that the35458 // new record's message fragment should be appended to35459 if(c.fragmented !== null) {35460 // if the record type matches a previously fragmented35461 // record, append the record fragment to it35462 if(c.fragmented.type === c.record.type) {35463 // concatenate record fragments35464 c.fragmented.fragment.putBuffer(c.record.fragment);35465 c.record = c.fragmented;35466 } else {35467 // error, invalid fragmented record35468 c.error(c, {35469 message: 'Invalid fragmented record.',35470 send: true,35471 alert: {35472 level: tls.Alert.Level.fatal,35473 description:35474 tls.Alert.Description.unexpected_message35475 }35476 });35477 }35478 }35479 // record is now ready35480 c.record.ready = true;35481 }35482 }35483 return rval;35484 };35485 /**35486 * Performs a handshake using the TLS Handshake Protocol, as a client.35487 *35488 * This method should only be called if the connection is in client mode.35489 *35490 * @param sessionId the session ID to use, null to start a new one.35491 */35492 c.handshake = function(sessionId) {35493 // error to call this in non-client mode35494 if(c.entity !== tls.ConnectionEnd.client) {35495 // not fatal error35496 c.error(c, {35497 message: 'Cannot initiate handshake as a server.',35498 fatal: false35499 });35500 } else if(c.handshaking) {35501 // handshake is already in progress, fail but not fatal error35502 c.error(c, {35503 message: 'Handshake already in progress.',35504 fatal: false35505 });35506 } else {35507 // clear fail flag on reuse35508 if(c.fail && !c.open && c.handshakes === 0) {35509 c.fail = false;35510 }35511 // now handshaking35512 c.handshaking = true;35513 // default to blank (new session)35514 sessionId = sessionId || '';35515 // if a session ID was specified, try to find it in the cache35516 var session = null;35517 if(sessionId.length > 0) {35518 if(c.sessionCache) {35519 session = c.sessionCache.getSession(sessionId);35520 }35521 // matching session not found in cache, clear session ID35522 if(session === null) {35523 sessionId = '';35524 }35525 }35526 // no session given, grab a session from the cache, if available35527 if(sessionId.length === 0 && c.sessionCache) {35528 session = c.sessionCache.getSession();35529 if(session !== null) {35530 sessionId = session.id;35531 }35532 }35533 // set up session35534 c.session = {35535 id: sessionId,35536 version: null,35537 cipherSuite: null,35538 compressionMethod: null,35539 serverCertificate: null,35540 certificateRequest: null,35541 clientCertificate: null,35542 sp: {},35543 md5: forge.md.md5.create(),35544 sha1: forge.md.sha1.create()35545 };35546 // use existing session information35547 if(session) {35548 // only update version on connection, session version not yet set35549 c.version = session.version;35550 c.session.sp = session.sp;35551 }35552 // generate new client random35553 c.session.sp.client_random = tls.createRandom().getBytes();35554 // connection now open35555 c.open = true;35556 // send hello35557 tls.queue(c, tls.createRecord(c, {35558 type: tls.ContentType.handshake,35559 data: tls.createClientHello(c)35560 }));35561 tls.flush(c);35562 }35563 };35564 /**35565 * Called when TLS protocol data has been received from somewhere and should35566 * be processed by the TLS engine.35567 *35568 * @param data the TLS protocol data, as a string, to process.35569 *35570 * @return 0 if the data could be processed, otherwise the number of bytes35571 * required for data to be processed.35572 */35573 c.process = function(data) {35574 var rval = 0;35575 // buffer input data35576 if(data) {35577 c.input.putBytes(data);35578 }35579 // process next record if no failure, process will be called after35580 // each record is handled (since handling can be asynchronous)35581 if(!c.fail) {35582 // reset record if ready and now empty35583 if(c.record !== null &&35584 c.record.ready && c.record.fragment.isEmpty()) {35585 c.record = null;35586 }35587 // if there is no pending record, try to read record header35588 if(c.record === null) {35589 rval = _readRecordHeader(c);35590 }35591 // read the next record (if record not yet ready)35592 if(!c.fail && c.record !== null && !c.record.ready) {35593 rval = _readRecord(c);35594 }35595 // record ready to be handled, update engine state35596 if(!c.fail && c.record !== null && c.record.ready) {35597 _update(c, c.record);35598 }35599 }35600 return rval;35601 };35602 /**35603 * Requests that application data be packaged into a TLS record. The35604 * tlsDataReady handler will be called when the TLS record(s) have been35605 * prepared.35606 *35607 * @param data the application data, as a raw 'binary' encoded string, to35608 * be sent; to send utf-16/utf-8 string data, use the return value35609 * of util.encodeUtf8(str).35610 *35611 * @return true on success, false on failure.35612 */35613 c.prepare = function(data) {35614 tls.queue(c, tls.createRecord(c, {35615 type: tls.ContentType.application_data,35616 data: forge.util.createBuffer(data)35617 }));35618 return tls.flush(c);35619 };35620 /**35621 * Requests that a heartbeat request be packaged into a TLS record for35622 * transmission. The tlsDataReady handler will be called when TLS record(s)35623 * have been prepared.35624 *35625 * When a heartbeat response has been received, the heartbeatReceived35626 * handler will be called with the matching payload. This handler can35627 * be used to clear a retransmission timer, etc.35628 *35629 * @param payload the heartbeat data to send as the payload in the message.35630 * @param [payloadLength] the payload length to use, defaults to the35631 * actual payload length.35632 *35633 * @return true on success, false on failure.35634 */35635 c.prepareHeartbeatRequest = function(payload, payloadLength) {35636 if(payload instanceof forge.util.ByteBuffer) {35637 payload = payload.bytes();35638 }35639 if(typeof payloadLength === 'undefined') {35640 payloadLength = payload.length;35641 }35642 c.expectedHeartbeatPayload = payload;35643 tls.queue(c, tls.createRecord(c, {35644 type: tls.ContentType.heartbeat,35645 data: tls.createHeartbeat(35646 tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength)35647 }));35648 return tls.flush(c);35649 };35650 /**35651 * Closes the connection (sends a close_notify alert).35652 *35653 * @param clearFail true to clear the fail flag (default: true).35654 */35655 c.close = function(clearFail) {35656 // save session if connection didn't fail35657 if(!c.fail && c.sessionCache && c.session) {35658 // only need to preserve session ID, version, and security params35659 var session = {35660 id: c.session.id,35661 version: c.session.version,35662 sp: c.session.sp35663 };35664 session.sp.keys = null;35665 c.sessionCache.setSession(session.id, session);35666 }35667 if(c.open) {35668 // connection no longer open, clear input35669 c.open = false;35670 c.input.clear();35671 // if connected or handshaking, send an alert35672 if(c.isConnected || c.handshaking) {35673 c.isConnected = c.handshaking = false;35674 // send close_notify alert35675 tls.queue(c, tls.createAlert(c, {35676 level: tls.Alert.Level.warning,35677 description: tls.Alert.Description.close_notify35678 }));35679 tls.flush(c);35680 }35681 // call handler35682 c.closed(c);35683 }35684 // reset TLS connection, do not clear fail flag35685 c.reset(clearFail);35686 };35687 return c;35688};35689/* TLS API */35690module.exports = forge.tls = forge.tls || {};35691// expose non-functions35692for(var key in tls) {35693 if(typeof tls[key] !== 'function') {35694 forge.tls[key] = tls[key];35695 }35696}35697// expose prf_tls1 for testing35698forge.tls.prf_tls1 = prf_TLS1;35699// expose sha1 hmac method35700forge.tls.hmac_sha1 = hmac_sha1;35701// expose session cache creation35702forge.tls.createSessionCache = tls.createSessionCache;35703/**35704 * Creates a new TLS connection. This does not make any assumptions about the35705 * transport layer that TLS is working on top of, ie: it does not assume there35706 * is a TCP/IP connection or establish one. A TLS connection is totally35707 * abstracted away from the layer is runs on top of, it merely establishes a35708 * secure channel between a client" and a "server".35709 *35710 * A TLS connection contains 4 connection states: pending read and write, and35711 * current read and write.35712 *35713 * At initialization, the current read and write states will be null. Only once35714 * the security parameters have been set and the keys have been generated can35715 * the pending states be converted into current states. Current states will be35716 * updated for each record processed.35717 *35718 * A custom certificate verify callback may be provided to check information35719 * like the common name on the server's certificate. It will be called for35720 * every certificate in the chain. It has the following signature:35721 *35722 * variable func(c, certs, index, preVerify)35723 * Where:35724 * c The TLS connection35725 * verified Set to true if certificate was verified, otherwise the alert35726 * tls.Alert.Description for why the certificate failed.35727 * depth The current index in the chain, where 0 is the server's cert.35728 * certs The certificate chain, *NOTE* if the server was anonymous then35729 * the chain will be empty.35730 *35731 * The function returns true on success and on failure either the appropriate35732 * tls.Alert.Description or an object with 'alert' set to the appropriate35733 * tls.Alert.Description and 'message' set to a custom error message. If true35734 * is not returned then the connection will abort using, in order of35735 * availability, first the returned alert description, second the preVerify35736 * alert description, and lastly the default 'bad_certificate'.35737 *35738 * There are three callbacks that can be used to make use of client-side35739 * certificates where each takes the TLS connection as the first parameter:35740 *35741 * getCertificate(conn, hint)35742 * The second parameter is a hint as to which certificate should be35743 * returned. If the connection entity is a client, then the hint will be35744 * the CertificateRequest message from the server that is part of the35745 * TLS protocol. If the connection entity is a server, then it will be35746 * the servername list provided via an SNI extension the ClientHello, if35747 * one was provided (empty array if not). The hint can be examined to35748 * determine which certificate to use (advanced). Most implementations35749 * will just return a certificate. The return value must be a35750 * PEM-formatted certificate or an array of PEM-formatted certificates35751 * that constitute a certificate chain, with the first in the array/chain35752 * being the client's certificate.35753 * getPrivateKey(conn, certificate)35754 * The second parameter is an forge.pki X.509 certificate object that35755 * is associated with the requested private key. The return value must35756 * be a PEM-formatted private key.35757 * getSignature(conn, bytes, callback)35758 * This callback can be used instead of getPrivateKey if the private key35759 * is not directly accessible in javascript or should not be. For35760 * instance, a secure external web service could provide the signature35761 * in exchange for appropriate credentials. The second parameter is a35762 * string of bytes to be signed that are part of the TLS protocol. These35763 * bytes are used to verify that the private key for the previously35764 * provided client-side certificate is accessible to the client. The35765 * callback is a function that takes 2 parameters, the TLS connection35766 * and the RSA encrypted (signed) bytes as a string. This callback must35767 * be called once the signature is ready.35768 *35769 * @param options the options for this connection:35770 * server: true if the connection is server-side, false for client.35771 * sessionId: a session ID to reuse, null for a new connection.35772 * caStore: an array of certificates to trust.35773 * sessionCache: a session cache to use.35774 * cipherSuites: an optional array of cipher suites to use,35775 * see tls.CipherSuites.35776 * connected: function(conn) called when the first handshake completes.35777 * virtualHost: the virtual server name to use in a TLS SNI extension.35778 * verifyClient: true to require a client certificate in server mode,35779 * 'optional' to request one, false not to (default: false).35780 * verify: a handler used to custom verify certificates in the chain.35781 * verifyOptions: an object with options for the certificate chain validation.35782 * See documentation of pki.verifyCertificateChain for possible options.35783 * verifyOptions.verify is ignored. If you wish to specify a verify handler35784 * use the verify key.35785 * getCertificate: an optional callback used to get a certificate or35786 * a chain of certificates (as an array).35787 * getPrivateKey: an optional callback used to get a private key.35788 * getSignature: an optional callback used to get a signature.35789 * tlsDataReady: function(conn) called when TLS protocol data has been35790 * prepared and is ready to be used (typically sent over a socket35791 * connection to its destination), read from conn.tlsData buffer.35792 * dataReady: function(conn) called when application data has35793 * been parsed from a TLS record and should be consumed by the35794 * application, read from conn.data buffer.35795 * closed: function(conn) called when the connection has been closed.35796 * error: function(conn, error) called when there was an error.35797 * deflate: function(inBytes) if provided, will deflate TLS records using35798 * the deflate algorithm if the server supports it.35799 * inflate: function(inBytes) if provided, will inflate TLS records using35800 * the deflate algorithm if the server supports it.35801 *35802 * @return the new TLS connection.35803 */35804forge.tls.createConnection = tls.createConnection;35805/***/ }),35806/***/ 8339:35807/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {35808/**35809 * Utility functions for web applications.35810 *35811 * @author Dave Longley35812 *35813 * Copyright (c) 2010-2018 Digital Bazaar, Inc.35814 */35815var forge = __nccwpck_require__(9177);35816var baseN = __nccwpck_require__(2300);35817/* Utilities API */35818var util = module.exports = forge.util = forge.util || {};35819// define setImmediate and nextTick35820(function() {35821 // use native nextTick (unless we're in webpack)35822 // webpack (or better node-libs-browser polyfill) sets process.browser.35823 // this way we can detect webpack properly35824 if(typeof process !== 'undefined' && process.nextTick && !process.browser) {35825 util.nextTick = process.nextTick;35826 if(typeof setImmediate === 'function') {35827 util.setImmediate = setImmediate;35828 } else {35829 // polyfill setImmediate with nextTick, older versions of node35830 // (those w/o setImmediate) won't totally starve IO35831 util.setImmediate = util.nextTick;35832 }35833 return;35834 }35835 // polyfill nextTick with native setImmediate35836 if(typeof setImmediate === 'function') {35837 util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };35838 util.nextTick = function(callback) {35839 return setImmediate(callback);35840 };35841 return;35842 }35843 /* Note: A polyfill upgrade pattern is used here to allow combining35844 polyfills. For example, MutationObserver is fast, but blocks UI updates,35845 so it needs to allow UI updates periodically, so it falls back on35846 postMessage or setTimeout. */35847 // polyfill with setTimeout35848 util.setImmediate = function(callback) {35849 setTimeout(callback, 0);35850 };35851 // upgrade polyfill to use postMessage35852 if(typeof window !== 'undefined' &&35853 typeof window.postMessage === 'function') {35854 var msg = 'forge.setImmediate';35855 var callbacks = [];35856 util.setImmediate = function(callback) {35857 callbacks.push(callback);35858 // only send message when one hasn't been sent in35859 // the current turn of the event loop35860 if(callbacks.length === 1) {35861 window.postMessage(msg, '*');35862 }35863 };35864 function handler(event) {35865 if(event.source === window && event.data === msg) {35866 event.stopPropagation();35867 var copy = callbacks.slice();35868 callbacks.length = 0;35869 copy.forEach(function(callback) {35870 callback();35871 });35872 }35873 }35874 window.addEventListener('message', handler, true);35875 }35876 // upgrade polyfill to use MutationObserver35877 if(typeof MutationObserver !== 'undefined') {35878 // polyfill with MutationObserver35879 var now = Date.now();35880 var attr = true;35881 var div = document.createElement('div');35882 var callbacks = [];35883 new MutationObserver(function() {35884 var copy = callbacks.slice();35885 callbacks.length = 0;35886 copy.forEach(function(callback) {35887 callback();35888 });35889 }).observe(div, {attributes: true});35890 var oldSetImmediate = util.setImmediate;35891 util.setImmediate = function(callback) {35892 if(Date.now() - now > 15) {35893 now = Date.now();35894 oldSetImmediate(callback);35895 } else {35896 callbacks.push(callback);35897 // only trigger observer when it hasn't been triggered in35898 // the current turn of the event loop35899 if(callbacks.length === 1) {35900 div.setAttribute('a', attr = !attr);35901 }35902 }35903 };35904 }35905 util.nextTick = util.setImmediate;35906})();35907// check if running under Node.js35908util.isNodejs =35909 typeof process !== 'undefined' && process.versions && process.versions.node;35910// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while35911// it will point to `window` in the main thread.35912// To remain compatible with older browsers, we fall back to 'window' if 'self'35913// is not available.35914util.globalScope = (function() {35915 if(util.isNodejs) {35916 return global;35917 }35918 return typeof self === 'undefined' ? window : self;35919})();35920// define isArray35921util.isArray = Array.isArray || function(x) {35922 return Object.prototype.toString.call(x) === '[object Array]';35923};35924// define isArrayBuffer35925util.isArrayBuffer = function(x) {35926 return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;35927};35928// define isArrayBufferView35929util.isArrayBufferView = function(x) {35930 return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;35931};35932/**35933 * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for35934 * algorithms where bit manipulation, JavaScript limitations, and/or algorithm35935 * design only allow for byte operations of a limited size.35936 *35937 * @param n number of bits.35938 *35939 * Throw Error if n invalid.35940 */35941function _checkBitsParam(n) {35942 if(!(n === 8 || n === 16 || n === 24 || n === 32)) {35943 throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);35944 }35945}35946// TODO: set ByteBuffer to best available backing35947util.ByteBuffer = ByteStringBuffer;35948/** Buffer w/BinaryString backing */35949/**35950 * Constructor for a binary string backed byte buffer.35951 *35952 * @param [b] the bytes to wrap (either encoded as string, one byte per35953 * character, or as an ArrayBuffer or Typed Array).35954 */35955function ByteStringBuffer(b) {35956 // TODO: update to match DataBuffer API35957 // the data in this buffer35958 this.data = '';35959 // the pointer for reading from this buffer35960 this.read = 0;35961 if(typeof b === 'string') {35962 this.data = b;35963 } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {35964 if(typeof Buffer !== 'undefined' && b instanceof Buffer) {35965 this.data = b.toString('binary');35966 } else {35967 // convert native buffer to forge buffer35968 // FIXME: support native buffers internally instead35969 var arr = new Uint8Array(b);35970 try {35971 this.data = String.fromCharCode.apply(null, arr);35972 } catch(e) {35973 for(var i = 0; i < arr.length; ++i) {35974 this.putByte(arr[i]);35975 }35976 }35977 }35978 } else if(b instanceof ByteStringBuffer ||35979 (typeof b === 'object' && typeof b.data === 'string' &&35980 typeof b.read === 'number')) {35981 // copy existing buffer35982 this.data = b.data;35983 this.read = b.read;35984 }35985 // used for v8 optimization35986 this._constructedStringLength = 0;35987}35988util.ByteStringBuffer = ByteStringBuffer;35989/* Note: This is an optimization for V8-based browsers. When V8 concatenates35990 a string, the strings are only joined logically using a "cons string" or35991 "constructed/concatenated string". These containers keep references to one35992 another and can result in very large memory usage. For example, if a 2MB35993 string is constructed by concatenating 4 bytes together at a time, the35994 memory usage will be ~44MB; so ~22x increase. The strings are only joined35995 together when an operation requiring their joining takes place, such as35996 substr(). This function is called when adding data to this buffer to ensure35997 these types of strings are periodically joined to reduce the memory35998 footprint. */35999var _MAX_CONSTRUCTED_STRING_LENGTH = 4096;36000util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {36001 this._constructedStringLength += x;36002 if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {36003 // this substr() should cause the constructed string to join36004 this.data.substr(0, 1);36005 this._constructedStringLength = 0;36006 }36007};36008/**36009 * Gets the number of bytes in this buffer.36010 *36011 * @return the number of bytes in this buffer.36012 */36013util.ByteStringBuffer.prototype.length = function() {36014 return this.data.length - this.read;36015};36016/**36017 * Gets whether or not this buffer is empty.36018 *36019 * @return true if this buffer is empty, false if not.36020 */36021util.ByteStringBuffer.prototype.isEmpty = function() {36022 return this.length() <= 0;36023};36024/**36025 * Puts a byte in this buffer.36026 *36027 * @param b the byte to put.36028 *36029 * @return this buffer.36030 */36031util.ByteStringBuffer.prototype.putByte = function(b) {36032 return this.putBytes(String.fromCharCode(b));36033};36034/**36035 * Puts a byte in this buffer N times.36036 *36037 * @param b the byte to put.36038 * @param n the number of bytes of value b to put.36039 *36040 * @return this buffer.36041 */36042util.ByteStringBuffer.prototype.fillWithByte = function(b, n) {36043 b = String.fromCharCode(b);36044 var d = this.data;36045 while(n > 0) {36046 if(n & 1) {36047 d += b;36048 }36049 n >>>= 1;36050 if(n > 0) {36051 b += b;36052 }36053 }36054 this.data = d;36055 this._optimizeConstructedString(n);36056 return this;36057};36058/**36059 * Puts bytes in this buffer.36060 *36061 * @param bytes the bytes (as a binary encoded string) to put.36062 *36063 * @return this buffer.36064 */36065util.ByteStringBuffer.prototype.putBytes = function(bytes) {36066 this.data += bytes;36067 this._optimizeConstructedString(bytes.length);36068 return this;36069};36070/**36071 * Puts a UTF-16 encoded string into this buffer.36072 *36073 * @param str the string to put.36074 *36075 * @return this buffer.36076 */36077util.ByteStringBuffer.prototype.putString = function(str) {36078 return this.putBytes(util.encodeUtf8(str));36079};36080/**36081 * Puts a 16-bit integer in this buffer in big-endian order.36082 *36083 * @param i the 16-bit integer.36084 *36085 * @return this buffer.36086 */36087util.ByteStringBuffer.prototype.putInt16 = function(i) {36088 return this.putBytes(36089 String.fromCharCode(i >> 8 & 0xFF) +36090 String.fromCharCode(i & 0xFF));36091};36092/**36093 * Puts a 24-bit integer in this buffer in big-endian order.36094 *36095 * @param i the 24-bit integer.36096 *36097 * @return this buffer.36098 */36099util.ByteStringBuffer.prototype.putInt24 = function(i) {36100 return this.putBytes(36101 String.fromCharCode(i >> 16 & 0xFF) +36102 String.fromCharCode(i >> 8 & 0xFF) +36103 String.fromCharCode(i & 0xFF));36104};36105/**36106 * Puts a 32-bit integer in this buffer in big-endian order.36107 *36108 * @param i the 32-bit integer.36109 *36110 * @return this buffer.36111 */36112util.ByteStringBuffer.prototype.putInt32 = function(i) {36113 return this.putBytes(36114 String.fromCharCode(i >> 24 & 0xFF) +36115 String.fromCharCode(i >> 16 & 0xFF) +36116 String.fromCharCode(i >> 8 & 0xFF) +36117 String.fromCharCode(i & 0xFF));36118};36119/**36120 * Puts a 16-bit integer in this buffer in little-endian order.36121 *36122 * @param i the 16-bit integer.36123 *36124 * @return this buffer.36125 */36126util.ByteStringBuffer.prototype.putInt16Le = function(i) {36127 return this.putBytes(36128 String.fromCharCode(i & 0xFF) +36129 String.fromCharCode(i >> 8 & 0xFF));36130};36131/**36132 * Puts a 24-bit integer in this buffer in little-endian order.36133 *36134 * @param i the 24-bit integer.36135 *36136 * @return this buffer.36137 */36138util.ByteStringBuffer.prototype.putInt24Le = function(i) {36139 return this.putBytes(36140 String.fromCharCode(i & 0xFF) +36141 String.fromCharCode(i >> 8 & 0xFF) +36142 String.fromCharCode(i >> 16 & 0xFF));36143};36144/**36145 * Puts a 32-bit integer in this buffer in little-endian order.36146 *36147 * @param i the 32-bit integer.36148 *36149 * @return this buffer.36150 */36151util.ByteStringBuffer.prototype.putInt32Le = function(i) {36152 return this.putBytes(36153 String.fromCharCode(i & 0xFF) +36154 String.fromCharCode(i >> 8 & 0xFF) +36155 String.fromCharCode(i >> 16 & 0xFF) +36156 String.fromCharCode(i >> 24 & 0xFF));36157};36158/**36159 * Puts an n-bit integer in this buffer in big-endian order.36160 *36161 * @param i the n-bit integer.36162 * @param n the number of bits in the integer (8, 16, 24, or 32).36163 *36164 * @return this buffer.36165 */36166util.ByteStringBuffer.prototype.putInt = function(i, n) {36167 _checkBitsParam(n);36168 var bytes = '';36169 do {36170 n -= 8;36171 bytes += String.fromCharCode((i >> n) & 0xFF);36172 } while(n > 0);36173 return this.putBytes(bytes);36174};36175/**36176 * Puts a signed n-bit integer in this buffer in big-endian order. Two's36177 * complement representation is used.36178 *36179 * @param i the n-bit integer.36180 * @param n the number of bits in the integer (8, 16, 24, or 32).36181 *36182 * @return this buffer.36183 */36184util.ByteStringBuffer.prototype.putSignedInt = function(i, n) {36185 // putInt checks n36186 if(i < 0) {36187 i += 2 << (n - 1);36188 }36189 return this.putInt(i, n);36190};36191/**36192 * Puts the given buffer into this buffer.36193 *36194 * @param buffer the buffer to put into this one.36195 *36196 * @return this buffer.36197 */36198util.ByteStringBuffer.prototype.putBuffer = function(buffer) {36199 return this.putBytes(buffer.getBytes());36200};36201/**36202 * Gets a byte from this buffer and advances the read pointer by 1.36203 *36204 * @return the byte.36205 */36206util.ByteStringBuffer.prototype.getByte = function() {36207 return this.data.charCodeAt(this.read++);36208};36209/**36210 * Gets a uint16 from this buffer in big-endian order and advances the read36211 * pointer by 2.36212 *36213 * @return the uint16.36214 */36215util.ByteStringBuffer.prototype.getInt16 = function() {36216 var rval = (36217 this.data.charCodeAt(this.read) << 8 ^36218 this.data.charCodeAt(this.read + 1));36219 this.read += 2;36220 return rval;36221};36222/**36223 * Gets a uint24 from this buffer in big-endian order and advances the read36224 * pointer by 3.36225 *36226 * @return the uint24.36227 */36228util.ByteStringBuffer.prototype.getInt24 = function() {36229 var rval = (36230 this.data.charCodeAt(this.read) << 16 ^36231 this.data.charCodeAt(this.read + 1) << 8 ^36232 this.data.charCodeAt(this.read + 2));36233 this.read += 3;36234 return rval;36235};36236/**36237 * Gets a uint32 from this buffer in big-endian order and advances the read36238 * pointer by 4.36239 *36240 * @return the word.36241 */36242util.ByteStringBuffer.prototype.getInt32 = function() {36243 var rval = (36244 this.data.charCodeAt(this.read) << 24 ^36245 this.data.charCodeAt(this.read + 1) << 16 ^36246 this.data.charCodeAt(this.read + 2) << 8 ^36247 this.data.charCodeAt(this.read + 3));36248 this.read += 4;36249 return rval;36250};36251/**36252 * Gets a uint16 from this buffer in little-endian order and advances the read36253 * pointer by 2.36254 *36255 * @return the uint16.36256 */36257util.ByteStringBuffer.prototype.getInt16Le = function() {36258 var rval = (36259 this.data.charCodeAt(this.read) ^36260 this.data.charCodeAt(this.read + 1) << 8);36261 this.read += 2;36262 return rval;36263};36264/**36265 * Gets a uint24 from this buffer in little-endian order and advances the read36266 * pointer by 3.36267 *36268 * @return the uint24.36269 */36270util.ByteStringBuffer.prototype.getInt24Le = function() {36271 var rval = (36272 this.data.charCodeAt(this.read) ^36273 this.data.charCodeAt(this.read + 1) << 8 ^36274 this.data.charCodeAt(this.read + 2) << 16);36275 this.read += 3;36276 return rval;36277};36278/**36279 * Gets a uint32 from this buffer in little-endian order and advances the read36280 * pointer by 4.36281 *36282 * @return the word.36283 */36284util.ByteStringBuffer.prototype.getInt32Le = function() {36285 var rval = (36286 this.data.charCodeAt(this.read) ^36287 this.data.charCodeAt(this.read + 1) << 8 ^36288 this.data.charCodeAt(this.read + 2) << 16 ^36289 this.data.charCodeAt(this.read + 3) << 24);36290 this.read += 4;36291 return rval;36292};36293/**36294 * Gets an n-bit integer from this buffer in big-endian order and advances the36295 * read pointer by ceil(n/8).36296 *36297 * @param n the number of bits in the integer (8, 16, 24, or 32).36298 *36299 * @return the integer.36300 */36301util.ByteStringBuffer.prototype.getInt = function(n) {36302 _checkBitsParam(n);36303 var rval = 0;36304 do {36305 // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.36306 rval = (rval << 8) + this.data.charCodeAt(this.read++);36307 n -= 8;36308 } while(n > 0);36309 return rval;36310};36311/**36312 * Gets a signed n-bit integer from this buffer in big-endian order, using36313 * two's complement, and advances the read pointer by n/8.36314 *36315 * @param n the number of bits in the integer (8, 16, 24, or 32).36316 *36317 * @return the integer.36318 */36319util.ByteStringBuffer.prototype.getSignedInt = function(n) {36320 // getInt checks n36321 var x = this.getInt(n);36322 var max = 2 << (n - 2);36323 if(x >= max) {36324 x -= max << 1;36325 }36326 return x;36327};36328/**36329 * Reads bytes out as a binary encoded string and clears them from the36330 * buffer. Note that the resulting string is binary encoded (in node.js this36331 * encoding is referred to as `binary`, it is *not* `utf8`).36332 *36333 * @param count the number of bytes to read, undefined or null for all.36334 *36335 * @return a binary encoded string of bytes.36336 */36337util.ByteStringBuffer.prototype.getBytes = function(count) {36338 var rval;36339 if(count) {36340 // read count bytes36341 count = Math.min(this.length(), count);36342 rval = this.data.slice(this.read, this.read + count);36343 this.read += count;36344 } else if(count === 0) {36345 rval = '';36346 } else {36347 // read all bytes, optimize to only copy when needed36348 rval = (this.read === 0) ? this.data : this.data.slice(this.read);36349 this.clear();36350 }36351 return rval;36352};36353/**36354 * Gets a binary encoded string of the bytes from this buffer without36355 * modifying the read pointer.36356 *36357 * @param count the number of bytes to get, omit to get all.36358 *36359 * @return a string full of binary encoded characters.36360 */36361util.ByteStringBuffer.prototype.bytes = function(count) {36362 return (typeof(count) === 'undefined' ?36363 this.data.slice(this.read) :36364 this.data.slice(this.read, this.read + count));36365};36366/**36367 * Gets a byte at the given index without modifying the read pointer.36368 *36369 * @param i the byte index.36370 *36371 * @return the byte.36372 */36373util.ByteStringBuffer.prototype.at = function(i) {36374 return this.data.charCodeAt(this.read + i);36375};36376/**36377 * Puts a byte at the given index without modifying the read pointer.36378 *36379 * @param i the byte index.36380 * @param b the byte to put.36381 *36382 * @return this buffer.36383 */36384util.ByteStringBuffer.prototype.setAt = function(i, b) {36385 this.data = this.data.substr(0, this.read + i) +36386 String.fromCharCode(b) +36387 this.data.substr(this.read + i + 1);36388 return this;36389};36390/**36391 * Gets the last byte without modifying the read pointer.36392 *36393 * @return the last byte.36394 */36395util.ByteStringBuffer.prototype.last = function() {36396 return this.data.charCodeAt(this.data.length - 1);36397};36398/**36399 * Creates a copy of this buffer.36400 *36401 * @return the copy.36402 */36403util.ByteStringBuffer.prototype.copy = function() {36404 var c = util.createBuffer(this.data);36405 c.read = this.read;36406 return c;36407};36408/**36409 * Compacts this buffer.36410 *36411 * @return this buffer.36412 */36413util.ByteStringBuffer.prototype.compact = function() {36414 if(this.read > 0) {36415 this.data = this.data.slice(this.read);36416 this.read = 0;36417 }36418 return this;36419};36420/**36421 * Clears this buffer.36422 *36423 * @return this buffer.36424 */36425util.ByteStringBuffer.prototype.clear = function() {36426 this.data = '';36427 this.read = 0;36428 return this;36429};36430/**36431 * Shortens this buffer by triming bytes off of the end of this buffer.36432 *36433 * @param count the number of bytes to trim off.36434 *36435 * @return this buffer.36436 */36437util.ByteStringBuffer.prototype.truncate = function(count) {36438 var len = Math.max(0, this.length() - count);36439 this.data = this.data.substr(this.read, len);36440 this.read = 0;36441 return this;36442};36443/**36444 * Converts this buffer to a hexadecimal string.36445 *36446 * @return a hexadecimal string.36447 */36448util.ByteStringBuffer.prototype.toHex = function() {36449 var rval = '';36450 for(var i = this.read; i < this.data.length; ++i) {36451 var b = this.data.charCodeAt(i);36452 if(b < 16) {36453 rval += '0';36454 }36455 rval += b.toString(16);36456 }36457 return rval;36458};36459/**36460 * Converts this buffer to a UTF-16 string (standard JavaScript string).36461 *36462 * @return a UTF-16 string.36463 */36464util.ByteStringBuffer.prototype.toString = function() {36465 return util.decodeUtf8(this.bytes());36466};36467/** End Buffer w/BinaryString backing */36468/** Buffer w/UInt8Array backing */36469/**36470 * FIXME: Experimental. Do not use yet.36471 *36472 * Constructor for an ArrayBuffer-backed byte buffer.36473 *36474 * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a36475 * TypedArray.36476 *36477 * If a string is given, its encoding should be provided as an option,36478 * otherwise it will default to 'binary'. A 'binary' string is encoded such36479 * that each character is one byte in length and size.36480 *36481 * If an ArrayBuffer, DataView, or TypedArray is given, it will be used36482 * *directly* without any copying. Note that, if a write to the buffer requires36483 * more space, the buffer will allocate a new backing ArrayBuffer to36484 * accommodate. The starting read and write offsets for the buffer may be36485 * given as options.36486 *36487 * @param [b] the initial bytes for this buffer.36488 * @param options the options to use:36489 * [readOffset] the starting read offset to use (default: 0).36490 * [writeOffset] the starting write offset to use (default: the36491 * length of the first parameter).36492 * [growSize] the minimum amount, in bytes, to grow the buffer by to36493 * accommodate writes (default: 1024).36494 * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the36495 * first parameter, if it is a string (default: 'binary').36496 */36497function DataBuffer(b, options) {36498 // default options36499 options = options || {};36500 // pointers for read from/write to buffer36501 this.read = options.readOffset || 0;36502 this.growSize = options.growSize || 1024;36503 var isArrayBuffer = util.isArrayBuffer(b);36504 var isArrayBufferView = util.isArrayBufferView(b);36505 if(isArrayBuffer || isArrayBufferView) {36506 // use ArrayBuffer directly36507 if(isArrayBuffer) {36508 this.data = new DataView(b);36509 } else {36510 // TODO: adjust read/write offset based on the type of view36511 // or specify that this must be done in the options ... that the36512 // offsets are byte-based36513 this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);36514 }36515 this.write = ('writeOffset' in options ?36516 options.writeOffset : this.data.byteLength);36517 return;36518 }36519 // initialize to empty array buffer and add any given bytes using putBytes36520 this.data = new DataView(new ArrayBuffer(0));36521 this.write = 0;36522 if(b !== null && b !== undefined) {36523 this.putBytes(b);36524 }36525 if('writeOffset' in options) {36526 this.write = options.writeOffset;36527 }36528}36529util.DataBuffer = DataBuffer;36530/**36531 * Gets the number of bytes in this buffer.36532 *36533 * @return the number of bytes in this buffer.36534 */36535util.DataBuffer.prototype.length = function() {36536 return this.write - this.read;36537};36538/**36539 * Gets whether or not this buffer is empty.36540 *36541 * @return true if this buffer is empty, false if not.36542 */36543util.DataBuffer.prototype.isEmpty = function() {36544 return this.length() <= 0;36545};36546/**36547 * Ensures this buffer has enough empty space to accommodate the given number36548 * of bytes. An optional parameter may be given that indicates a minimum36549 * amount to grow the buffer if necessary. If the parameter is not given,36550 * the buffer will be grown by some previously-specified default amount36551 * or heuristic.36552 *36553 * @param amount the number of bytes to accommodate.36554 * @param [growSize] the minimum amount, in bytes, to grow the buffer by if36555 * necessary.36556 */36557util.DataBuffer.prototype.accommodate = function(amount, growSize) {36558 if(this.length() >= amount) {36559 return this;36560 }36561 growSize = Math.max(growSize || this.growSize, amount);36562 // grow buffer36563 var src = new Uint8Array(36564 this.data.buffer, this.data.byteOffset, this.data.byteLength);36565 var dst = new Uint8Array(this.length() + growSize);36566 dst.set(src);36567 this.data = new DataView(dst.buffer);36568 return this;36569};36570/**36571 * Puts a byte in this buffer.36572 *36573 * @param b the byte to put.36574 *36575 * @return this buffer.36576 */36577util.DataBuffer.prototype.putByte = function(b) {36578 this.accommodate(1);36579 this.data.setUint8(this.write++, b);36580 return this;36581};36582/**36583 * Puts a byte in this buffer N times.36584 *36585 * @param b the byte to put.36586 * @param n the number of bytes of value b to put.36587 *36588 * @return this buffer.36589 */36590util.DataBuffer.prototype.fillWithByte = function(b, n) {36591 this.accommodate(n);36592 for(var i = 0; i < n; ++i) {36593 this.data.setUint8(b);36594 }36595 return this;36596};36597/**36598 * Puts bytes in this buffer. The bytes may be given as a string, an36599 * ArrayBuffer, a DataView, or a TypedArray.36600 *36601 * @param bytes the bytes to put.36602 * @param [encoding] the encoding for the first parameter ('binary', 'utf8',36603 * 'utf16', 'hex'), if it is a string (default: 'binary').36604 *36605 * @return this buffer.36606 */36607util.DataBuffer.prototype.putBytes = function(bytes, encoding) {36608 if(util.isArrayBufferView(bytes)) {36609 var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);36610 var len = src.byteLength - src.byteOffset;36611 this.accommodate(len);36612 var dst = new Uint8Array(this.data.buffer, this.write);36613 dst.set(src);36614 this.write += len;36615 return this;36616 }36617 if(util.isArrayBuffer(bytes)) {36618 var src = new Uint8Array(bytes);36619 this.accommodate(src.byteLength);36620 var dst = new Uint8Array(this.data.buffer);36621 dst.set(src, this.write);36622 this.write += src.byteLength;36623 return this;36624 }36625 // bytes is a util.DataBuffer or equivalent36626 if(bytes instanceof util.DataBuffer ||36627 (typeof bytes === 'object' &&36628 typeof bytes.read === 'number' && typeof bytes.write === 'number' &&36629 util.isArrayBufferView(bytes.data))) {36630 var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());36631 this.accommodate(src.byteLength);36632 var dst = new Uint8Array(bytes.data.byteLength, this.write);36633 dst.set(src);36634 this.write += src.byteLength;36635 return this;36636 }36637 if(bytes instanceof util.ByteStringBuffer) {36638 // copy binary string and process as the same as a string parameter below36639 bytes = bytes.data;36640 encoding = 'binary';36641 }36642 // string conversion36643 encoding = encoding || 'binary';36644 if(typeof bytes === 'string') {36645 var view;36646 // decode from string36647 if(encoding === 'hex') {36648 this.accommodate(Math.ceil(bytes.length / 2));36649 view = new Uint8Array(this.data.buffer, this.write);36650 this.write += util.binary.hex.decode(bytes, view, this.write);36651 return this;36652 }36653 if(encoding === 'base64') {36654 this.accommodate(Math.ceil(bytes.length / 4) * 3);36655 view = new Uint8Array(this.data.buffer, this.write);36656 this.write += util.binary.base64.decode(bytes, view, this.write);36657 return this;36658 }36659 // encode text as UTF-8 bytes36660 if(encoding === 'utf8') {36661 // encode as UTF-8 then decode string as raw binary36662 bytes = util.encodeUtf8(bytes);36663 encoding = 'binary';36664 }36665 // decode string as raw binary36666 if(encoding === 'binary' || encoding === 'raw') {36667 // one byte per character36668 this.accommodate(bytes.length);36669 view = new Uint8Array(this.data.buffer, this.write);36670 this.write += util.binary.raw.decode(view);36671 return this;36672 }36673 // encode text as UTF-16 bytes36674 if(encoding === 'utf16') {36675 // two bytes per character36676 this.accommodate(bytes.length * 2);36677 view = new Uint16Array(this.data.buffer, this.write);36678 this.write += util.text.utf16.encode(view);36679 return this;36680 }36681 throw new Error('Invalid encoding: ' + encoding);36682 }36683 throw Error('Invalid parameter: ' + bytes);36684};36685/**36686 * Puts the given buffer into this buffer.36687 *36688 * @param buffer the buffer to put into this one.36689 *36690 * @return this buffer.36691 */36692util.DataBuffer.prototype.putBuffer = function(buffer) {36693 this.putBytes(buffer);36694 buffer.clear();36695 return this;36696};36697/**36698 * Puts a string into this buffer.36699 *36700 * @param str the string to put.36701 * @param [encoding] the encoding for the string (default: 'utf16').36702 *36703 * @return this buffer.36704 */36705util.DataBuffer.prototype.putString = function(str) {36706 return this.putBytes(str, 'utf16');36707};36708/**36709 * Puts a 16-bit integer in this buffer in big-endian order.36710 *36711 * @param i the 16-bit integer.36712 *36713 * @return this buffer.36714 */36715util.DataBuffer.prototype.putInt16 = function(i) {36716 this.accommodate(2);36717 this.data.setInt16(this.write, i);36718 this.write += 2;36719 return this;36720};36721/**36722 * Puts a 24-bit integer in this buffer in big-endian order.36723 *36724 * @param i the 24-bit integer.36725 *36726 * @return this buffer.36727 */36728util.DataBuffer.prototype.putInt24 = function(i) {36729 this.accommodate(3);36730 this.data.setInt16(this.write, i >> 8 & 0xFFFF);36731 this.data.setInt8(this.write, i >> 16 & 0xFF);36732 this.write += 3;36733 return this;36734};36735/**36736 * Puts a 32-bit integer in this buffer in big-endian order.36737 *36738 * @param i the 32-bit integer.36739 *36740 * @return this buffer.36741 */36742util.DataBuffer.prototype.putInt32 = function(i) {36743 this.accommodate(4);36744 this.data.setInt32(this.write, i);36745 this.write += 4;36746 return this;36747};36748/**36749 * Puts a 16-bit integer in this buffer in little-endian order.36750 *36751 * @param i the 16-bit integer.36752 *36753 * @return this buffer.36754 */36755util.DataBuffer.prototype.putInt16Le = function(i) {36756 this.accommodate(2);36757 this.data.setInt16(this.write, i, true);36758 this.write += 2;36759 return this;36760};36761/**36762 * Puts a 24-bit integer in this buffer in little-endian order.36763 *36764 * @param i the 24-bit integer.36765 *36766 * @return this buffer.36767 */36768util.DataBuffer.prototype.putInt24Le = function(i) {36769 this.accommodate(3);36770 this.data.setInt8(this.write, i >> 16 & 0xFF);36771 this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);36772 this.write += 3;36773 return this;36774};36775/**36776 * Puts a 32-bit integer in this buffer in little-endian order.36777 *36778 * @param i the 32-bit integer.36779 *36780 * @return this buffer.36781 */36782util.DataBuffer.prototype.putInt32Le = function(i) {36783 this.accommodate(4);36784 this.data.setInt32(this.write, i, true);36785 this.write += 4;36786 return this;36787};36788/**36789 * Puts an n-bit integer in this buffer in big-endian order.36790 *36791 * @param i the n-bit integer.36792 * @param n the number of bits in the integer (8, 16, 24, or 32).36793 *36794 * @return this buffer.36795 */36796util.DataBuffer.prototype.putInt = function(i, n) {36797 _checkBitsParam(n);36798 this.accommodate(n / 8);36799 do {36800 n -= 8;36801 this.data.setInt8(this.write++, (i >> n) & 0xFF);36802 } while(n > 0);36803 return this;36804};36805/**36806 * Puts a signed n-bit integer in this buffer in big-endian order. Two's36807 * complement representation is used.36808 *36809 * @param i the n-bit integer.36810 * @param n the number of bits in the integer.36811 *36812 * @return this buffer.36813 */36814util.DataBuffer.prototype.putSignedInt = function(i, n) {36815 _checkBitsParam(n);36816 this.accommodate(n / 8);36817 if(i < 0) {36818 i += 2 << (n - 1);36819 }36820 return this.putInt(i, n);36821};36822/**36823 * Gets a byte from this buffer and advances the read pointer by 1.36824 *36825 * @return the byte.36826 */36827util.DataBuffer.prototype.getByte = function() {36828 return this.data.getInt8(this.read++);36829};36830/**36831 * Gets a uint16 from this buffer in big-endian order and advances the read36832 * pointer by 2.36833 *36834 * @return the uint16.36835 */36836util.DataBuffer.prototype.getInt16 = function() {36837 var rval = this.data.getInt16(this.read);36838 this.read += 2;36839 return rval;36840};36841/**36842 * Gets a uint24 from this buffer in big-endian order and advances the read36843 * pointer by 3.36844 *36845 * @return the uint24.36846 */36847util.DataBuffer.prototype.getInt24 = function() {36848 var rval = (36849 this.data.getInt16(this.read) << 8 ^36850 this.data.getInt8(this.read + 2));36851 this.read += 3;36852 return rval;36853};36854/**36855 * Gets a uint32 from this buffer in big-endian order and advances the read36856 * pointer by 4.36857 *36858 * @return the word.36859 */36860util.DataBuffer.prototype.getInt32 = function() {36861 var rval = this.data.getInt32(this.read);36862 this.read += 4;36863 return rval;36864};36865/**36866 * Gets a uint16 from this buffer in little-endian order and advances the read36867 * pointer by 2.36868 *36869 * @return the uint16.36870 */36871util.DataBuffer.prototype.getInt16Le = function() {36872 var rval = this.data.getInt16(this.read, true);36873 this.read += 2;36874 return rval;36875};36876/**36877 * Gets a uint24 from this buffer in little-endian order and advances the read36878 * pointer by 3.36879 *36880 * @return the uint24.36881 */36882util.DataBuffer.prototype.getInt24Le = function() {36883 var rval = (36884 this.data.getInt8(this.read) ^36885 this.data.getInt16(this.read + 1, true) << 8);36886 this.read += 3;36887 return rval;36888};36889/**36890 * Gets a uint32 from this buffer in little-endian order and advances the read36891 * pointer by 4.36892 *36893 * @return the word.36894 */36895util.DataBuffer.prototype.getInt32Le = function() {36896 var rval = this.data.getInt32(this.read, true);36897 this.read += 4;36898 return rval;36899};36900/**36901 * Gets an n-bit integer from this buffer in big-endian order and advances the36902 * read pointer by n/8.36903 *36904 * @param n the number of bits in the integer (8, 16, 24, or 32).36905 *36906 * @return the integer.36907 */36908util.DataBuffer.prototype.getInt = function(n) {36909 _checkBitsParam(n);36910 var rval = 0;36911 do {36912 // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.36913 rval = (rval << 8) + this.data.getInt8(this.read++);36914 n -= 8;36915 } while(n > 0);36916 return rval;36917};36918/**36919 * Gets a signed n-bit integer from this buffer in big-endian order, using36920 * two's complement, and advances the read pointer by n/8.36921 *36922 * @param n the number of bits in the integer (8, 16, 24, or 32).36923 *36924 * @return the integer.36925 */36926util.DataBuffer.prototype.getSignedInt = function(n) {36927 // getInt checks n36928 var x = this.getInt(n);36929 var max = 2 << (n - 2);36930 if(x >= max) {36931 x -= max << 1;36932 }36933 return x;36934};36935/**36936 * Reads bytes out as a binary encoded string and clears them from the36937 * buffer.36938 *36939 * @param count the number of bytes to read, undefined or null for all.36940 *36941 * @return a binary encoded string of bytes.36942 */36943util.DataBuffer.prototype.getBytes = function(count) {36944 // TODO: deprecate this method, it is poorly named and36945 // this.toString('binary') replaces it36946 // add a toTypedArray()/toArrayBuffer() function36947 var rval;36948 if(count) {36949 // read count bytes36950 count = Math.min(this.length(), count);36951 rval = this.data.slice(this.read, this.read + count);36952 this.read += count;36953 } else if(count === 0) {36954 rval = '';36955 } else {36956 // read all bytes, optimize to only copy when needed36957 rval = (this.read === 0) ? this.data : this.data.slice(this.read);36958 this.clear();36959 }36960 return rval;36961};36962/**36963 * Gets a binary encoded string of the bytes from this buffer without36964 * modifying the read pointer.36965 *36966 * @param count the number of bytes to get, omit to get all.36967 *36968 * @return a string full of binary encoded characters.36969 */36970util.DataBuffer.prototype.bytes = function(count) {36971 // TODO: deprecate this method, it is poorly named, add "getString()"36972 return (typeof(count) === 'undefined' ?36973 this.data.slice(this.read) :36974 this.data.slice(this.read, this.read + count));36975};36976/**36977 * Gets a byte at the given index without modifying the read pointer.36978 *36979 * @param i the byte index.36980 *36981 * @return the byte.36982 */36983util.DataBuffer.prototype.at = function(i) {36984 return this.data.getUint8(this.read + i);36985};36986/**36987 * Puts a byte at the given index without modifying the read pointer.36988 *36989 * @param i the byte index.36990 * @param b the byte to put.36991 *36992 * @return this buffer.36993 */36994util.DataBuffer.prototype.setAt = function(i, b) {36995 this.data.setUint8(i, b);36996 return this;36997};36998/**36999 * Gets the last byte without modifying the read pointer.37000 *37001 * @return the last byte.37002 */37003util.DataBuffer.prototype.last = function() {37004 return this.data.getUint8(this.write - 1);37005};37006/**37007 * Creates a copy of this buffer.37008 *37009 * @return the copy.37010 */37011util.DataBuffer.prototype.copy = function() {37012 return new util.DataBuffer(this);37013};37014/**37015 * Compacts this buffer.37016 *37017 * @return this buffer.37018 */37019util.DataBuffer.prototype.compact = function() {37020 if(this.read > 0) {37021 var src = new Uint8Array(this.data.buffer, this.read);37022 var dst = new Uint8Array(src.byteLength);37023 dst.set(src);37024 this.data = new DataView(dst);37025 this.write -= this.read;37026 this.read = 0;37027 }37028 return this;37029};37030/**37031 * Clears this buffer.37032 *37033 * @return this buffer.37034 */37035util.DataBuffer.prototype.clear = function() {37036 this.data = new DataView(new ArrayBuffer(0));37037 this.read = this.write = 0;37038 return this;37039};37040/**37041 * Shortens this buffer by triming bytes off of the end of this buffer.37042 *37043 * @param count the number of bytes to trim off.37044 *37045 * @return this buffer.37046 */37047util.DataBuffer.prototype.truncate = function(count) {37048 this.write = Math.max(0, this.length() - count);37049 this.read = Math.min(this.read, this.write);37050 return this;37051};37052/**37053 * Converts this buffer to a hexadecimal string.37054 *37055 * @return a hexadecimal string.37056 */37057util.DataBuffer.prototype.toHex = function() {37058 var rval = '';37059 for(var i = this.read; i < this.data.byteLength; ++i) {37060 var b = this.data.getUint8(i);37061 if(b < 16) {37062 rval += '0';37063 }37064 rval += b.toString(16);37065 }37066 return rval;37067};37068/**37069 * Converts this buffer to a string, using the given encoding. If no37070 * encoding is given, 'utf8' (UTF-8) is used.37071 *37072 * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',37073 * 'base64' (default: 'utf8').37074 *37075 * @return a string representation of the bytes in this buffer.37076 */37077util.DataBuffer.prototype.toString = function(encoding) {37078 var view = new Uint8Array(this.data, this.read, this.length());37079 encoding = encoding || 'utf8';37080 // encode to string37081 if(encoding === 'binary' || encoding === 'raw') {37082 return util.binary.raw.encode(view);37083 }37084 if(encoding === 'hex') {37085 return util.binary.hex.encode(view);37086 }37087 if(encoding === 'base64') {37088 return util.binary.base64.encode(view);37089 }37090 // decode to text37091 if(encoding === 'utf8') {37092 return util.text.utf8.decode(view);37093 }37094 if(encoding === 'utf16') {37095 return util.text.utf16.decode(view);37096 }37097 throw new Error('Invalid encoding: ' + encoding);37098};37099/** End Buffer w/UInt8Array backing */37100/**37101 * Creates a buffer that stores bytes. A value may be given to populate the37102 * buffer with data. This value can either be string of encoded bytes or a37103 * regular string of characters. When passing a string of binary encoded37104 * bytes, the encoding `raw` should be given. This is also the default. When37105 * passing a string of characters, the encoding `utf8` should be given.37106 *37107 * @param [input] a string with encoded bytes to store in the buffer.37108 * @param [encoding] (default: 'raw', other: 'utf8').37109 */37110util.createBuffer = function(input, encoding) {37111 // TODO: deprecate, use new ByteBuffer() instead37112 encoding = encoding || 'raw';37113 if(input !== undefined && encoding === 'utf8') {37114 input = util.encodeUtf8(input);37115 }37116 return new util.ByteBuffer(input);37117};37118/**37119 * Fills a string with a particular value. If you want the string to be a byte37120 * string, pass in String.fromCharCode(theByte).37121 *37122 * @param c the character to fill the string with, use String.fromCharCode37123 * to fill the string with a byte value.37124 * @param n the number of characters of value c to fill with.37125 *37126 * @return the filled string.37127 */37128util.fillString = function(c, n) {37129 var s = '';37130 while(n > 0) {37131 if(n & 1) {37132 s += c;37133 }37134 n >>>= 1;37135 if(n > 0) {37136 c += c;37137 }37138 }37139 return s;37140};37141/**37142 * Performs a per byte XOR between two byte strings and returns the result as a37143 * string of bytes.37144 *37145 * @param s1 first string of bytes.37146 * @param s2 second string of bytes.37147 * @param n the number of bytes to XOR.37148 *37149 * @return the XOR'd result.37150 */37151util.xorBytes = function(s1, s2, n) {37152 var s3 = '';37153 var b = '';37154 var t = '';37155 var i = 0;37156 var c = 0;37157 for(; n > 0; --n, ++i) {37158 b = s1.charCodeAt(i) ^ s2.charCodeAt(i);37159 if(c >= 10) {37160 s3 += t;37161 t = '';37162 c = 0;37163 }37164 t += String.fromCharCode(b);37165 ++c;37166 }37167 s3 += t;37168 return s3;37169};37170/**37171 * Converts a hex string into a 'binary' encoded string of bytes.37172 *37173 * @param hex the hexadecimal string to convert.37174 *37175 * @return the binary-encoded string of bytes.37176 */37177util.hexToBytes = function(hex) {37178 // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead."37179 var rval = '';37180 var i = 0;37181 if(hex.length & 1 == 1) {37182 // odd number of characters, convert first character alone37183 i = 1;37184 rval += String.fromCharCode(parseInt(hex[0], 16));37185 }37186 // convert 2 characters (1 byte) at a time37187 for(; i < hex.length; i += 2) {37188 rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));37189 }37190 return rval;37191};37192/**37193 * Converts a 'binary' encoded string of bytes to hex.37194 *37195 * @param bytes the byte string to convert.37196 *37197 * @return the string of hexadecimal characters.37198 */37199util.bytesToHex = function(bytes) {37200 // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead."37201 return util.createBuffer(bytes).toHex();37202};37203/**37204 * Converts an 32-bit integer to 4-big-endian byte string.37205 *37206 * @param i the integer.37207 *37208 * @return the byte string.37209 */37210util.int32ToBytes = function(i) {37211 return (37212 String.fromCharCode(i >> 24 & 0xFF) +37213 String.fromCharCode(i >> 16 & 0xFF) +37214 String.fromCharCode(i >> 8 & 0xFF) +37215 String.fromCharCode(i & 0xFF));37216};37217// base64 characters, reverse mapping37218var _base64 =37219 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';37220var _base64Idx = [37221/*43 -43 = 0*/37222/*'+', 1, 2, 3,'/' */37223 62, -1, -1, -1, 63,37224/*'0','1','2','3','4','5','6','7','8','9' */37225 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,37226/*15, 16, 17,'=', 19, 20, 21 */37227 -1, -1, -1, 64, -1, -1, -1,37228/*65 - 43 = 22*/37229/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */37230 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,37231/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */37232 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,37233/*91 - 43 = 48 */37234/*48, 49, 50, 51, 52, 53 */37235 -1, -1, -1, -1, -1, -1,37236/*97 - 43 = 54*/37237/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */37238 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,37239/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */37240 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 5137241];37242// base58 characters (Bitcoin alphabet)37243var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';37244/**37245 * Base64 encodes a 'binary' encoded string of bytes.37246 *37247 * @param input the binary encoded string of bytes to base64-encode.37248 * @param maxline the maximum number of encoded characters per line to use,37249 * defaults to none.37250 *37251 * @return the base64-encoded output.37252 */37253util.encode64 = function(input, maxline) {37254 // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead."37255 var line = '';37256 var output = '';37257 var chr1, chr2, chr3;37258 var i = 0;37259 while(i < input.length) {37260 chr1 = input.charCodeAt(i++);37261 chr2 = input.charCodeAt(i++);37262 chr3 = input.charCodeAt(i++);37263 // encode 4 character group37264 line += _base64.charAt(chr1 >> 2);37265 line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));37266 if(isNaN(chr2)) {37267 line += '==';37268 } else {37269 line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));37270 line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);37271 }37272 if(maxline && line.length > maxline) {37273 output += line.substr(0, maxline) + '\r\n';37274 line = line.substr(maxline);37275 }37276 }37277 output += line;37278 return output;37279};37280/**37281 * Base64 decodes a string into a 'binary' encoded string of bytes.37282 *37283 * @param input the base64-encoded input.37284 *37285 * @return the binary encoded string.37286 */37287util.decode64 = function(input) {37288 // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead."37289 // remove all non-base64 characters37290 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');37291 var output = '';37292 var enc1, enc2, enc3, enc4;37293 var i = 0;37294 while(i < input.length) {37295 enc1 = _base64Idx[input.charCodeAt(i++) - 43];37296 enc2 = _base64Idx[input.charCodeAt(i++) - 43];37297 enc3 = _base64Idx[input.charCodeAt(i++) - 43];37298 enc4 = _base64Idx[input.charCodeAt(i++) - 43];37299 output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));37300 if(enc3 !== 64) {37301 // decoded at least 2 bytes37302 output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));37303 if(enc4 !== 64) {37304 // decoded 3 bytes37305 output += String.fromCharCode(((enc3 & 3) << 6) | enc4);37306 }37307 }37308 }37309 return output;37310};37311/**37312 * Encodes the given string of characters (a standard JavaScript37313 * string) as a binary encoded string where the bytes represent37314 * a UTF-8 encoded string of characters. Non-ASCII characters will be37315 * encoded as multiple bytes according to UTF-8.37316 *37317 * @param str a standard string of characters to encode.37318 *37319 * @return the binary encoded string.37320 */37321util.encodeUtf8 = function(str) {37322 return unescape(encodeURIComponent(str));37323};37324/**37325 * Decodes a binary encoded string that contains bytes that37326 * represent a UTF-8 encoded string of characters -- into a37327 * string of characters (a standard JavaScript string).37328 *37329 * @param str the binary encoded string to decode.37330 *37331 * @return the resulting standard string of characters.37332 */37333util.decodeUtf8 = function(str) {37334 return decodeURIComponent(escape(str));37335};37336// binary encoding/decoding tools37337// FIXME: Experimental. Do not use yet.37338util.binary = {37339 raw: {},37340 hex: {},37341 base64: {},37342 base58: {},37343 baseN : {37344 encode: baseN.encode,37345 decode: baseN.decode37346 }37347};37348/**37349 * Encodes a Uint8Array as a binary-encoded string. This encoding uses37350 * a value between 0 and 255 for each character.37351 *37352 * @param bytes the Uint8Array to encode.37353 *37354 * @return the binary-encoded string.37355 */37356util.binary.raw.encode = function(bytes) {37357 return String.fromCharCode.apply(null, bytes);37358};37359/**37360 * Decodes a binary-encoded string to a Uint8Array. This encoding uses37361 * a value between 0 and 255 for each character.37362 *37363 * @param str the binary-encoded string to decode.37364 * @param [output] an optional Uint8Array to write the output to; if it37365 * is too small, an exception will be thrown.37366 * @param [offset] the start offset for writing to the output (default: 0).37367 *37368 * @return the Uint8Array or the number of bytes written if output was given.37369 */37370util.binary.raw.decode = function(str, output, offset) {37371 var out = output;37372 if(!out) {37373 out = new Uint8Array(str.length);37374 }37375 offset = offset || 0;37376 var j = offset;37377 for(var i = 0; i < str.length; ++i) {37378 out[j++] = str.charCodeAt(i);37379 }37380 return output ? (j - offset) : out;37381};37382/**37383 * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or37384 * ByteBuffer as a string of hexadecimal characters.37385 *37386 * @param bytes the bytes to convert.37387 *37388 * @return the string of hexadecimal characters.37389 */37390util.binary.hex.encode = util.bytesToHex;37391/**37392 * Decodes a hex-encoded string to a Uint8Array.37393 *37394 * @param hex the hexadecimal string to convert.37395 * @param [output] an optional Uint8Array to write the output to; if it37396 * is too small, an exception will be thrown.37397 * @param [offset] the start offset for writing to the output (default: 0).37398 *37399 * @return the Uint8Array or the number of bytes written if output was given.37400 */37401util.binary.hex.decode = function(hex, output, offset) {37402 var out = output;37403 if(!out) {37404 out = new Uint8Array(Math.ceil(hex.length / 2));37405 }37406 offset = offset || 0;37407 var i = 0, j = offset;37408 if(hex.length & 1) {37409 // odd number of characters, convert first character alone37410 i = 1;37411 out[j++] = parseInt(hex[0], 16);37412 }37413 // convert 2 characters (1 byte) at a time37414 for(; i < hex.length; i += 2) {37415 out[j++] = parseInt(hex.substr(i, 2), 16);37416 }37417 return output ? (j - offset) : out;37418};37419/**37420 * Base64-encodes a Uint8Array.37421 *37422 * @param input the Uint8Array to encode.37423 * @param maxline the maximum number of encoded characters per line to use,37424 * defaults to none.37425 *37426 * @return the base64-encoded output string.37427 */37428util.binary.base64.encode = function(input, maxline) {37429 var line = '';37430 var output = '';37431 var chr1, chr2, chr3;37432 var i = 0;37433 while(i < input.byteLength) {37434 chr1 = input[i++];37435 chr2 = input[i++];37436 chr3 = input[i++];37437 // encode 4 character group37438 line += _base64.charAt(chr1 >> 2);37439 line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));37440 if(isNaN(chr2)) {37441 line += '==';37442 } else {37443 line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));37444 line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);37445 }37446 if(maxline && line.length > maxline) {37447 output += line.substr(0, maxline) + '\r\n';37448 line = line.substr(maxline);37449 }37450 }37451 output += line;37452 return output;37453};37454/**37455 * Decodes a base64-encoded string to a Uint8Array.37456 *37457 * @param input the base64-encoded input string.37458 * @param [output] an optional Uint8Array to write the output to; if it37459 * is too small, an exception will be thrown.37460 * @param [offset] the start offset for writing to the output (default: 0).37461 *37462 * @return the Uint8Array or the number of bytes written if output was given.37463 */37464util.binary.base64.decode = function(input, output, offset) {37465 var out = output;37466 if(!out) {37467 out = new Uint8Array(Math.ceil(input.length / 4) * 3);37468 }37469 // remove all non-base64 characters37470 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');37471 offset = offset || 0;37472 var enc1, enc2, enc3, enc4;37473 var i = 0, j = offset;37474 while(i < input.length) {37475 enc1 = _base64Idx[input.charCodeAt(i++) - 43];37476 enc2 = _base64Idx[input.charCodeAt(i++) - 43];37477 enc3 = _base64Idx[input.charCodeAt(i++) - 43];37478 enc4 = _base64Idx[input.charCodeAt(i++) - 43];37479 out[j++] = (enc1 << 2) | (enc2 >> 4);37480 if(enc3 !== 64) {37481 // decoded at least 2 bytes37482 out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);37483 if(enc4 !== 64) {37484 // decoded 3 bytes37485 out[j++] = ((enc3 & 3) << 6) | enc4;37486 }37487 }37488 }37489 // make sure result is the exact decoded length37490 return output ? (j - offset) : out.subarray(0, j);37491};37492// add support for base58 encoding/decoding with Bitcoin alphabet37493util.binary.base58.encode = function(input, maxline) {37494 return util.binary.baseN.encode(input, _base58, maxline);37495};37496util.binary.base58.decode = function(input, maxline) {37497 return util.binary.baseN.decode(input, _base58, maxline);37498};37499// text encoding/decoding tools37500// FIXME: Experimental. Do not use yet.37501util.text = {37502 utf8: {},37503 utf16: {}37504};37505/**37506 * Encodes the given string as UTF-8 in a Uint8Array.37507 *37508 * @param str the string to encode.37509 * @param [output] an optional Uint8Array to write the output to; if it37510 * is too small, an exception will be thrown.37511 * @param [offset] the start offset for writing to the output (default: 0).37512 *37513 * @return the Uint8Array or the number of bytes written if output was given.37514 */37515util.text.utf8.encode = function(str, output, offset) {37516 str = util.encodeUtf8(str);37517 var out = output;37518 if(!out) {37519 out = new Uint8Array(str.length);37520 }37521 offset = offset || 0;37522 var j = offset;37523 for(var i = 0; i < str.length; ++i) {37524 out[j++] = str.charCodeAt(i);37525 }37526 return output ? (j - offset) : out;37527};37528/**37529 * Decodes the UTF-8 contents from a Uint8Array.37530 *37531 * @param bytes the Uint8Array to decode.37532 *37533 * @return the resulting string.37534 */37535util.text.utf8.decode = function(bytes) {37536 return util.decodeUtf8(String.fromCharCode.apply(null, bytes));37537};37538/**37539 * Encodes the given string as UTF-16 in a Uint8Array.37540 *37541 * @param str the string to encode.37542 * @param [output] an optional Uint8Array to write the output to; if it37543 * is too small, an exception will be thrown.37544 * @param [offset] the start offset for writing to the output (default: 0).37545 *37546 * @return the Uint8Array or the number of bytes written if output was given.37547 */37548util.text.utf16.encode = function(str, output, offset) {37549 var out = output;37550 if(!out) {37551 out = new Uint8Array(str.length * 2);37552 }37553 var view = new Uint16Array(out.buffer);37554 offset = offset || 0;37555 var j = offset;37556 var k = offset;37557 for(var i = 0; i < str.length; ++i) {37558 view[k++] = str.charCodeAt(i);37559 j += 2;37560 }37561 return output ? (j - offset) : out;37562};37563/**37564 * Decodes the UTF-16 contents from a Uint8Array.37565 *37566 * @param bytes the Uint8Array to decode.37567 *37568 * @return the resulting string.37569 */37570util.text.utf16.decode = function(bytes) {37571 return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));37572};37573/**37574 * Deflates the given data using a flash interface.37575 *37576 * @param api the flash interface.37577 * @param bytes the data.37578 * @param raw true to return only raw deflate data, false to include zlib37579 * header and trailer.37580 *37581 * @return the deflated data as a string.37582 */37583util.deflate = function(api, bytes, raw) {37584 bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);37585 // strip zlib header and trailer if necessary37586 if(raw) {37587 // zlib header is 2 bytes (CMF,FLG) where FLG indicates that37588 // there is a 4-byte DICT (alder-32) block before the data if37589 // its 5th bit is set37590 var start = 2;37591 var flg = bytes.charCodeAt(1);37592 if(flg & 0x20) {37593 start = 6;37594 }37595 // zlib trailer is 4 bytes of adler-3237596 bytes = bytes.substring(start, bytes.length - 4);37597 }37598 return bytes;37599};37600/**37601 * Inflates the given data using a flash interface.37602 *37603 * @param api the flash interface.37604 * @param bytes the data.37605 * @param raw true if the incoming data has no zlib header or trailer and is37606 * raw DEFLATE data.37607 *37608 * @return the inflated data as a string, null on error.37609 */37610util.inflate = function(api, bytes, raw) {37611 // TODO: add zlib header and trailer if necessary/possible37612 var rval = api.inflate(util.encode64(bytes)).rval;37613 return (rval === null) ? null : util.decode64(rval);37614};37615/**37616 * Sets a storage object.37617 *37618 * @param api the storage interface.37619 * @param id the storage ID to use.37620 * @param obj the storage object, null to remove.37621 */37622var _setStorageObject = function(api, id, obj) {37623 if(!api) {37624 throw new Error('WebStorage not available.');37625 }37626 var rval;37627 if(obj === null) {37628 rval = api.removeItem(id);37629 } else {37630 // json-encode and base64-encode object37631 obj = util.encode64(JSON.stringify(obj));37632 rval = api.setItem(id, obj);37633 }37634 // handle potential flash error37635 if(typeof(rval) !== 'undefined' && rval.rval !== true) {37636 var error = new Error(rval.error.message);37637 error.id = rval.error.id;37638 error.name = rval.error.name;37639 throw error;37640 }37641};37642/**37643 * Gets a storage object.37644 *37645 * @param api the storage interface.37646 * @param id the storage ID to use.37647 *37648 * @return the storage object entry or null if none exists.37649 */37650var _getStorageObject = function(api, id) {37651 if(!api) {37652 throw new Error('WebStorage not available.');37653 }37654 // get the existing entry37655 var rval = api.getItem(id);37656 /* Note: We check api.init because we can't do (api == localStorage)37657 on IE because of "Class doesn't support Automation" exception. Only37658 the flash api has an init method so this works too, but we need a37659 better solution in the future. */37660 // flash returns item wrapped in an object, handle special case37661 if(api.init) {37662 if(rval.rval === null) {37663 if(rval.error) {37664 var error = new Error(rval.error.message);37665 error.id = rval.error.id;37666 error.name = rval.error.name;37667 throw error;37668 }37669 // no error, but also no item37670 rval = null;37671 } else {37672 rval = rval.rval;37673 }37674 }37675 // handle decoding37676 if(rval !== null) {37677 // base64-decode and json-decode data37678 rval = JSON.parse(util.decode64(rval));37679 }37680 return rval;37681};37682/**37683 * Stores an item in local storage.37684 *37685 * @param api the storage interface.37686 * @param id the storage ID to use.37687 * @param key the key for the item.37688 * @param data the data for the item (any javascript object/primitive).37689 */37690var _setItem = function(api, id, key, data) {37691 // get storage object37692 var obj = _getStorageObject(api, id);37693 if(obj === null) {37694 // create a new storage object37695 obj = {};37696 }37697 // update key37698 obj[key] = data;37699 // set storage object37700 _setStorageObject(api, id, obj);37701};37702/**37703 * Gets an item from local storage.37704 *37705 * @param api the storage interface.37706 * @param id the storage ID to use.37707 * @param key the key for the item.37708 *37709 * @return the item.37710 */37711var _getItem = function(api, id, key) {37712 // get storage object37713 var rval = _getStorageObject(api, id);37714 if(rval !== null) {37715 // return data at key37716 rval = (key in rval) ? rval[key] : null;37717 }37718 return rval;37719};37720/**37721 * Removes an item from local storage.37722 *37723 * @param api the storage interface.37724 * @param id the storage ID to use.37725 * @param key the key for the item.37726 */37727var _removeItem = function(api, id, key) {37728 // get storage object37729 var obj = _getStorageObject(api, id);37730 if(obj !== null && key in obj) {37731 // remove key37732 delete obj[key];37733 // see if entry has no keys remaining37734 var empty = true;37735 for(var prop in obj) {37736 empty = false;37737 break;37738 }37739 if(empty) {37740 // remove entry entirely if no keys are left37741 obj = null;37742 }37743 // set storage object37744 _setStorageObject(api, id, obj);37745 }37746};37747/**37748 * Clears the local disk storage identified by the given ID.37749 *37750 * @param api the storage interface.37751 * @param id the storage ID to use.37752 */37753var _clearItems = function(api, id) {37754 _setStorageObject(api, id, null);37755};37756/**37757 * Calls a storage function.37758 *37759 * @param func the function to call.37760 * @param args the arguments for the function.37761 * @param location the location argument.37762 *37763 * @return the return value from the function.37764 */37765var _callStorageFunction = function(func, args, location) {37766 var rval = null;37767 // default storage types37768 if(typeof(location) === 'undefined') {37769 location = ['web', 'flash'];37770 }37771 // apply storage types in order of preference37772 var type;37773 var done = false;37774 var exception = null;37775 for(var idx in location) {37776 type = location[idx];37777 try {37778 if(type === 'flash' || type === 'both') {37779 if(args[0] === null) {37780 throw new Error('Flash local storage not available.');37781 }37782 rval = func.apply(this, args);37783 done = (type === 'flash');37784 }37785 if(type === 'web' || type === 'both') {37786 args[0] = localStorage;37787 rval = func.apply(this, args);37788 done = true;37789 }37790 } catch(ex) {37791 exception = ex;37792 }37793 if(done) {37794 break;37795 }37796 }37797 if(!done) {37798 throw exception;37799 }37800 return rval;37801};37802/**37803 * Stores an item on local disk.37804 *37805 * The available types of local storage include 'flash', 'web', and 'both'.37806 *37807 * The type 'flash' refers to flash local storage (SharedObject). In order37808 * to use flash local storage, the 'api' parameter must be valid. The type37809 * 'web' refers to WebStorage, if supported by the browser. The type 'both'37810 * refers to storing using both 'flash' and 'web', not just one or the37811 * other.37812 *37813 * The location array should list the storage types to use in order of37814 * preference:37815 *37816 * ['flash']: flash only storage37817 * ['web']: web only storage37818 * ['both']: try to store in both37819 * ['flash','web']: store in flash first, but if not available, 'web'37820 * ['web','flash']: store in web first, but if not available, 'flash'37821 *37822 * The location array defaults to: ['web', 'flash']37823 *37824 * @param api the flash interface, null to use only WebStorage.37825 * @param id the storage ID to use.37826 * @param key the key for the item.37827 * @param data the data for the item (any javascript object/primitive).37828 * @param location an array with the preferred types of storage to use.37829 */37830util.setItem = function(api, id, key, data, location) {37831 _callStorageFunction(_setItem, arguments, location);37832};37833/**37834 * Gets an item on local disk.37835 *37836 * Set setItem() for details on storage types.37837 *37838 * @param api the flash interface, null to use only WebStorage.37839 * @param id the storage ID to use.37840 * @param key the key for the item.37841 * @param location an array with the preferred types of storage to use.37842 *37843 * @return the item.37844 */37845util.getItem = function(api, id, key, location) {37846 return _callStorageFunction(_getItem, arguments, location);37847};37848/**37849 * Removes an item on local disk.37850 *37851 * Set setItem() for details on storage types.37852 *37853 * @param api the flash interface.37854 * @param id the storage ID to use.37855 * @param key the key for the item.37856 * @param location an array with the preferred types of storage to use.37857 */37858util.removeItem = function(api, id, key, location) {37859 _callStorageFunction(_removeItem, arguments, location);37860};37861/**37862 * Clears the local disk storage identified by the given ID.37863 *37864 * Set setItem() for details on storage types.37865 *37866 * @param api the flash interface if flash is available.37867 * @param id the storage ID to use.37868 * @param location an array with the preferred types of storage to use.37869 */37870util.clearItems = function(api, id, location) {37871 _callStorageFunction(_clearItems, arguments, location);37872};37873/**37874 * Check if an object is empty.37875 *37876 * Taken from:37877 * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#67993737878 *37879 * @param object the object to check.37880 */37881util.isEmpty = function(obj) {37882 for(var prop in obj) {37883 if(obj.hasOwnProperty(prop)) {37884 return false;37885 }37886 }37887 return true;37888};37889/**37890 * Format with simple printf-style interpolation.37891 *37892 * %%: literal '%'37893 * %s,%o: convert next argument into a string.37894 *37895 * @param format the string to format.37896 * @param ... arguments to interpolate into the format string.37897 */37898util.format = function(format) {37899 var re = /%./g;37900 // current match37901 var match;37902 // current part37903 var part;37904 // current arg index37905 var argi = 0;37906 // collected parts to recombine later37907 var parts = [];37908 // last index found37909 var last = 0;37910 // loop while matches remain37911 while((match = re.exec(format))) {37912 part = format.substring(last, re.lastIndex - 2);37913 // don't add empty strings (ie, parts between %s%s)37914 if(part.length > 0) {37915 parts.push(part);37916 }37917 last = re.lastIndex;37918 // switch on % code37919 var code = match[0][1];37920 switch(code) {37921 case 's':37922 case 'o':37923 // check if enough arguments were given37924 if(argi < arguments.length) {37925 parts.push(arguments[argi++ + 1]);37926 } else {37927 parts.push('<?>');37928 }37929 break;37930 // FIXME: do proper formating for numbers, etc37931 //case 'f':37932 //case 'd':37933 case '%':37934 parts.push('%');37935 break;37936 default:37937 parts.push('<%' + code + '?>');37938 }37939 }37940 // add trailing part of format string37941 parts.push(format.substring(last));37942 return parts.join('');37943};37944/**37945 * Formats a number.37946 *37947 * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/37948 */37949util.formatNumber = function(number, decimals, dec_point, thousands_sep) {37950 // http://kevin.vanzonneveld.net37951 // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)37952 // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)37953 // + bugfix by: Michael White (http://crestidg.com)37954 // + bugfix by: Benjamin Lupton37955 // + bugfix by: Allan Jensen (http://www.winternet.no)37956 // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)37957 // * example 1: number_format(1234.5678, 2, '.', '');37958 // * returns 1: 1234.5737959 var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;37960 var d = dec_point === undefined ? ',' : dec_point;37961 var t = thousands_sep === undefined ?37962 '.' : thousands_sep, s = n < 0 ? '-' : '';37963 var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';37964 var j = (i.length > 3) ? i.length % 3 : 0;37965 return s + (j ? i.substr(0, j) + t : '') +37966 i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) +37967 (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');37968};37969/**37970 * Formats a byte size.37971 *37972 * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/37973 */37974util.formatSize = function(size) {37975 if(size >= 1073741824) {37976 size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';37977 } else if(size >= 1048576) {37978 size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';37979 } else if(size >= 1024) {37980 size = util.formatNumber(size / 1024, 0) + ' KiB';37981 } else {37982 size = util.formatNumber(size, 0) + ' bytes';37983 }37984 return size;37985};37986/**37987 * Converts an IPv4 or IPv6 string representation into bytes (in network order).37988 *37989 * @param ip the IPv4 or IPv6 address to convert.37990 *37991 * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't37992 * be parsed.37993 */37994util.bytesFromIP = function(ip) {37995 if(ip.indexOf('.') !== -1) {37996 return util.bytesFromIPv4(ip);37997 }37998 if(ip.indexOf(':') !== -1) {37999 return util.bytesFromIPv6(ip);38000 }38001 return null;38002};38003/**38004 * Converts an IPv4 string representation into bytes (in network order).38005 *38006 * @param ip the IPv4 address to convert.38007 *38008 * @return the 4-byte address or null if the address can't be parsed.38009 */38010util.bytesFromIPv4 = function(ip) {38011 ip = ip.split('.');38012 if(ip.length !== 4) {38013 return null;38014 }38015 var b = util.createBuffer();38016 for(var i = 0; i < ip.length; ++i) {38017 var num = parseInt(ip[i], 10);38018 if(isNaN(num)) {38019 return null;38020 }38021 b.putByte(num);38022 }38023 return b.getBytes();38024};38025/**38026 * Converts an IPv6 string representation into bytes (in network order).38027 *38028 * @param ip the IPv6 address to convert.38029 *38030 * @return the 16-byte address or null if the address can't be parsed.38031 */38032util.bytesFromIPv6 = function(ip) {38033 var blanks = 0;38034 ip = ip.split(':').filter(function(e) {38035 if(e.length === 0) ++blanks;38036 return true;38037 });38038 var zeros = (8 - ip.length + blanks) * 2;38039 var b = util.createBuffer();38040 for(var i = 0; i < 8; ++i) {38041 if(!ip[i] || ip[i].length === 0) {38042 b.fillWithByte(0, zeros);38043 zeros = 0;38044 continue;38045 }38046 var bytes = util.hexToBytes(ip[i]);38047 if(bytes.length < 2) {38048 b.putByte(0);38049 }38050 b.putBytes(bytes);38051 }38052 return b.getBytes();38053};38054/**38055 * Converts 4-bytes into an IPv4 string representation or 16-bytes into38056 * an IPv6 string representation. The bytes must be in network order.38057 *38058 * @param bytes the bytes to convert.38059 *38060 * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,38061 * respectively, are given, otherwise null.38062 */38063util.bytesToIP = function(bytes) {38064 if(bytes.length === 4) {38065 return util.bytesToIPv4(bytes);38066 }38067 if(bytes.length === 16) {38068 return util.bytesToIPv6(bytes);38069 }38070 return null;38071};38072/**38073 * Converts 4-bytes into an IPv4 string representation. The bytes must be38074 * in network order.38075 *38076 * @param bytes the bytes to convert.38077 *38078 * @return the IPv4 string representation or null for an invalid # of bytes.38079 */38080util.bytesToIPv4 = function(bytes) {38081 if(bytes.length !== 4) {38082 return null;38083 }38084 var ip = [];38085 for(var i = 0; i < bytes.length; ++i) {38086 ip.push(bytes.charCodeAt(i));38087 }38088 return ip.join('.');38089};38090/**38091 * Converts 16-bytes into an IPv16 string representation. The bytes must be38092 * in network order.38093 *38094 * @param bytes the bytes to convert.38095 *38096 * @return the IPv16 string representation or null for an invalid # of bytes.38097 */38098util.bytesToIPv6 = function(bytes) {38099 if(bytes.length !== 16) {38100 return null;38101 }38102 var ip = [];38103 var zeroGroups = [];38104 var zeroMaxGroup = 0;38105 for(var i = 0; i < bytes.length; i += 2) {38106 var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);38107 // canonicalize zero representation38108 while(hex[0] === '0' && hex !== '0') {38109 hex = hex.substr(1);38110 }38111 if(hex === '0') {38112 var last = zeroGroups[zeroGroups.length - 1];38113 var idx = ip.length;38114 if(!last || idx !== last.end + 1) {38115 zeroGroups.push({start: idx, end: idx});38116 } else {38117 last.end = idx;38118 if((last.end - last.start) >38119 (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {38120 zeroMaxGroup = zeroGroups.length - 1;38121 }38122 }38123 }38124 ip.push(hex);38125 }38126 if(zeroGroups.length > 0) {38127 var group = zeroGroups[zeroMaxGroup];38128 // only shorten group of length > 038129 if(group.end - group.start > 0) {38130 ip.splice(group.start, group.end - group.start + 1, '');38131 if(group.start === 0) {38132 ip.unshift('');38133 }38134 if(group.end === 7) {38135 ip.push('');38136 }38137 }38138 }38139 return ip.join(':');38140};38141/**38142 * Estimates the number of processes that can be run concurrently. If38143 * creating Web Workers, keep in mind that the main JavaScript process needs38144 * its own core.38145 *38146 * @param options the options to use:38147 * update true to force an update (not use the cached value).38148 * @param callback(err, max) called once the operation completes.38149 */38150util.estimateCores = function(options, callback) {38151 if(typeof options === 'function') {38152 callback = options;38153 options = {};38154 }38155 options = options || {};38156 if('cores' in util && !options.update) {38157 return callback(null, util.cores);38158 }38159 if(typeof navigator !== 'undefined' &&38160 'hardwareConcurrency' in navigator &&38161 navigator.hardwareConcurrency > 0) {38162 util.cores = navigator.hardwareConcurrency;38163 return callback(null, util.cores);38164 }38165 if(typeof Worker === 'undefined') {38166 // workers not available38167 util.cores = 1;38168 return callback(null, util.cores);38169 }38170 if(typeof Blob === 'undefined') {38171 // can't estimate, default to 238172 util.cores = 2;38173 return callback(null, util.cores);38174 }38175 // create worker concurrency estimation code as blob38176 var blobUrl = URL.createObjectURL(new Blob(['(',38177 function() {38178 self.addEventListener('message', function(e) {38179 // run worker for 4 ms38180 var st = Date.now();38181 var et = st + 4;38182 while(Date.now() < et);38183 self.postMessage({st: st, et: et});38184 });38185 }.toString(),38186 ')()'], {type: 'application/javascript'}));38187 // take 5 samples using 16 workers38188 sample([], 5, 16);38189 function sample(max, samples, numWorkers) {38190 if(samples === 0) {38191 // get overlap average38192 var avg = Math.floor(max.reduce(function(avg, x) {38193 return avg + x;38194 }, 0) / max.length);38195 util.cores = Math.max(1, avg);38196 URL.revokeObjectURL(blobUrl);38197 return callback(null, util.cores);38198 }38199 map(numWorkers, function(err, results) {38200 max.push(reduce(numWorkers, results));38201 sample(max, samples - 1, numWorkers);38202 });38203 }38204 function map(numWorkers, callback) {38205 var workers = [];38206 var results = [];38207 for(var i = 0; i < numWorkers; ++i) {38208 var worker = new Worker(blobUrl);38209 worker.addEventListener('message', function(e) {38210 results.push(e.data);38211 if(results.length === numWorkers) {38212 for(var i = 0; i < numWorkers; ++i) {38213 workers[i].terminate();38214 }38215 callback(null, results);38216 }38217 });38218 workers.push(worker);38219 }38220 for(var i = 0; i < numWorkers; ++i) {38221 workers[i].postMessage(i);38222 }38223 }38224 function reduce(numWorkers, results) {38225 // find overlapping time windows38226 var overlaps = [];38227 for(var n = 0; n < numWorkers; ++n) {38228 var r1 = results[n];38229 var overlap = overlaps[n] = [];38230 for(var i = 0; i < numWorkers; ++i) {38231 if(n === i) {38232 continue;38233 }38234 var r2 = results[i];38235 if((r1.st > r2.st && r1.st < r2.et) ||38236 (r2.st > r1.st && r2.st < r1.et)) {38237 overlap.push(i);38238 }38239 }38240 }38241 // get maximum overlaps ... don't include overlapping worker itself38242 // as the main JS process was also being scheduled during the work and38243 // would have to be subtracted from the estimate anyway38244 return overlaps.reduce(function(max, overlap) {38245 return Math.max(max, overlap.length);38246 }, 0);38247 }38248};38249/***/ }),38250/***/ 8180:38251/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {38252/**38253 * Javascript implementation of X.509 and related components (such as38254 * Certification Signing Requests) of a Public Key Infrastructure.38255 *38256 * @author Dave Longley38257 *38258 * Copyright (c) 2010-2014 Digital Bazaar, Inc.38259 *38260 * The ASN.1 representation of an X.509v3 certificate is as follows38261 * (see RFC 2459):38262 *38263 * Certificate ::= SEQUENCE {38264 * tbsCertificate TBSCertificate,38265 * signatureAlgorithm AlgorithmIdentifier,38266 * signatureValue BIT STRING38267 * }38268 *38269 * TBSCertificate ::= SEQUENCE {38270 * version [0] EXPLICIT Version DEFAULT v1,38271 * serialNumber CertificateSerialNumber,38272 * signature AlgorithmIdentifier,38273 * issuer Name,38274 * validity Validity,38275 * subject Name,38276 * subjectPublicKeyInfo SubjectPublicKeyInfo,38277 * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,38278 * -- If present, version shall be v2 or v338279 * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,38280 * -- If present, version shall be v2 or v338281 * extensions [3] EXPLICIT Extensions OPTIONAL38282 * -- If present, version shall be v338283 * }38284 *38285 * Version ::= INTEGER { v1(0), v2(1), v3(2) }38286 *38287 * CertificateSerialNumber ::= INTEGER38288 *38289 * Name ::= CHOICE {38290 * // only one possible choice for now38291 * RDNSequence38292 * }38293 *38294 * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName38295 *38296 * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue38297 *38298 * AttributeTypeAndValue ::= SEQUENCE {38299 * type AttributeType,38300 * value AttributeValue38301 * }38302 * AttributeType ::= OBJECT IDENTIFIER38303 * AttributeValue ::= ANY DEFINED BY AttributeType38304 *38305 * Validity ::= SEQUENCE {38306 * notBefore Time,38307 * notAfter Time38308 * }38309 *38310 * Time ::= CHOICE {38311 * utcTime UTCTime,38312 * generalTime GeneralizedTime38313 * }38314 *38315 * UniqueIdentifier ::= BIT STRING38316 *38317 * SubjectPublicKeyInfo ::= SEQUENCE {38318 * algorithm AlgorithmIdentifier,38319 * subjectPublicKey BIT STRING38320 * }38321 *38322 * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension38323 *38324 * Extension ::= SEQUENCE {38325 * extnID OBJECT IDENTIFIER,38326 * critical BOOLEAN DEFAULT FALSE,38327 * extnValue OCTET STRING38328 * }38329 *38330 * The only key algorithm currently supported for PKI is RSA.38331 *38332 * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.38333 *38334 * PKCS#10 v1.7 describes certificate signing requests:38335 *38336 * CertificationRequestInfo:38337 *38338 * CertificationRequestInfo ::= SEQUENCE {38339 * version INTEGER { v1(0) } (v1,...),38340 * subject Name,38341 * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},38342 * attributes [0] Attributes{{ CRIAttributes }}38343 * }38344 *38345 * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}38346 *38347 * CRIAttributes ATTRIBUTE ::= {38348 * ... -- add any locally defined attributes here -- }38349 *38350 * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {38351 * type ATTRIBUTE.&id({IOSet}),38352 * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})38353 * }38354 *38355 * CertificationRequest ::= SEQUENCE {38356 * certificationRequestInfo CertificationRequestInfo,38357 * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},38358 * signature BIT STRING38359 * }38360 */38361var forge = __nccwpck_require__(9177);38362__nccwpck_require__(7994);38363__nccwpck_require__(9549);38364__nccwpck_require__(7157);38365__nccwpck_require__(6231);38366__nccwpck_require__(7973);38367__nccwpck_require__(1925);38368__nccwpck_require__(154);38369__nccwpck_require__(4376);38370__nccwpck_require__(3921);38371__nccwpck_require__(8339);38372// shortcut for asn.1 API38373var asn1 = forge.asn1;38374/* Public Key Infrastructure (PKI) implementation. */38375var pki = module.exports = forge.pki = forge.pki || {};38376var oids = pki.oids;38377// short name OID mappings38378var _shortNames = {};38379_shortNames['CN'] = oids['commonName'];38380_shortNames['commonName'] = 'CN';38381_shortNames['C'] = oids['countryName'];38382_shortNames['countryName'] = 'C';38383_shortNames['L'] = oids['localityName'];38384_shortNames['localityName'] = 'L';38385_shortNames['ST'] = oids['stateOrProvinceName'];38386_shortNames['stateOrProvinceName'] = 'ST';38387_shortNames['O'] = oids['organizationName'];38388_shortNames['organizationName'] = 'O';38389_shortNames['OU'] = oids['organizationalUnitName'];38390_shortNames['organizationalUnitName'] = 'OU';38391_shortNames['E'] = oids['emailAddress'];38392_shortNames['emailAddress'] = 'E';38393// validator for an SubjectPublicKeyInfo structure38394// Note: Currently only works with an RSA public key38395var publicKeyValidator = forge.pki.rsa.publicKeyValidator;38396// validator for an X.509v3 certificate38397var x509CertificateValidator = {38398 name: 'Certificate',38399 tagClass: asn1.Class.UNIVERSAL,38400 type: asn1.Type.SEQUENCE,38401 constructed: true,38402 value: [{38403 name: 'Certificate.TBSCertificate',38404 tagClass: asn1.Class.UNIVERSAL,38405 type: asn1.Type.SEQUENCE,38406 constructed: true,38407 captureAsn1: 'tbsCertificate',38408 value: [{38409 name: 'Certificate.TBSCertificate.version',38410 tagClass: asn1.Class.CONTEXT_SPECIFIC,38411 type: 0,38412 constructed: true,38413 optional: true,38414 value: [{38415 name: 'Certificate.TBSCertificate.version.integer',38416 tagClass: asn1.Class.UNIVERSAL,38417 type: asn1.Type.INTEGER,38418 constructed: false,38419 capture: 'certVersion'38420 }]38421 }, {38422 name: 'Certificate.TBSCertificate.serialNumber',38423 tagClass: asn1.Class.UNIVERSAL,38424 type: asn1.Type.INTEGER,38425 constructed: false,38426 capture: 'certSerialNumber'38427 }, {38428 name: 'Certificate.TBSCertificate.signature',38429 tagClass: asn1.Class.UNIVERSAL,38430 type: asn1.Type.SEQUENCE,38431 constructed: true,38432 value: [{38433 name: 'Certificate.TBSCertificate.signature.algorithm',38434 tagClass: asn1.Class.UNIVERSAL,38435 type: asn1.Type.OID,38436 constructed: false,38437 capture: 'certinfoSignatureOid'38438 }, {38439 name: 'Certificate.TBSCertificate.signature.parameters',38440 tagClass: asn1.Class.UNIVERSAL,38441 optional: true,38442 captureAsn1: 'certinfoSignatureParams'38443 }]38444 }, {38445 name: 'Certificate.TBSCertificate.issuer',38446 tagClass: asn1.Class.UNIVERSAL,38447 type: asn1.Type.SEQUENCE,38448 constructed: true,38449 captureAsn1: 'certIssuer'38450 }, {38451 name: 'Certificate.TBSCertificate.validity',38452 tagClass: asn1.Class.UNIVERSAL,38453 type: asn1.Type.SEQUENCE,38454 constructed: true,38455 // Note: UTC and generalized times may both appear so the capture38456 // names are based on their detected order, the names used below38457 // are only for the common case, which validity time really means38458 // "notBefore" and which means "notAfter" will be determined by order38459 value: [{38460 // notBefore (Time) (UTC time case)38461 name: 'Certificate.TBSCertificate.validity.notBefore (utc)',38462 tagClass: asn1.Class.UNIVERSAL,38463 type: asn1.Type.UTCTIME,38464 constructed: false,38465 optional: true,38466 capture: 'certValidity1UTCTime'38467 }, {38468 // notBefore (Time) (generalized time case)38469 name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',38470 tagClass: asn1.Class.UNIVERSAL,38471 type: asn1.Type.GENERALIZEDTIME,38472 constructed: false,38473 optional: true,38474 capture: 'certValidity2GeneralizedTime'38475 }, {38476 // notAfter (Time) (only UTC time is supported)38477 name: 'Certificate.TBSCertificate.validity.notAfter (utc)',38478 tagClass: asn1.Class.UNIVERSAL,38479 type: asn1.Type.UTCTIME,38480 constructed: false,38481 optional: true,38482 capture: 'certValidity3UTCTime'38483 }, {38484 // notAfter (Time) (only UTC time is supported)38485 name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',38486 tagClass: asn1.Class.UNIVERSAL,38487 type: asn1.Type.GENERALIZEDTIME,38488 constructed: false,38489 optional: true,38490 capture: 'certValidity4GeneralizedTime'38491 }]38492 }, {38493 // Name (subject) (RDNSequence)38494 name: 'Certificate.TBSCertificate.subject',38495 tagClass: asn1.Class.UNIVERSAL,38496 type: asn1.Type.SEQUENCE,38497 constructed: true,38498 captureAsn1: 'certSubject'38499 },38500 // SubjectPublicKeyInfo38501 publicKeyValidator,38502 {38503 // issuerUniqueID (optional)38504 name: 'Certificate.TBSCertificate.issuerUniqueID',38505 tagClass: asn1.Class.CONTEXT_SPECIFIC,38506 type: 1,38507 constructed: true,38508 optional: true,38509 value: [{38510 name: 'Certificate.TBSCertificate.issuerUniqueID.id',38511 tagClass: asn1.Class.UNIVERSAL,38512 type: asn1.Type.BITSTRING,38513 constructed: false,38514 // TODO: support arbitrary bit length ids38515 captureBitStringValue: 'certIssuerUniqueId'38516 }]38517 }, {38518 // subjectUniqueID (optional)38519 name: 'Certificate.TBSCertificate.subjectUniqueID',38520 tagClass: asn1.Class.CONTEXT_SPECIFIC,38521 type: 2,38522 constructed: true,38523 optional: true,38524 value: [{38525 name: 'Certificate.TBSCertificate.subjectUniqueID.id',38526 tagClass: asn1.Class.UNIVERSAL,38527 type: asn1.Type.BITSTRING,38528 constructed: false,38529 // TODO: support arbitrary bit length ids38530 captureBitStringValue: 'certSubjectUniqueId'38531 }]38532 }, {38533 // Extensions (optional)38534 name: 'Certificate.TBSCertificate.extensions',38535 tagClass: asn1.Class.CONTEXT_SPECIFIC,38536 type: 3,38537 constructed: true,38538 captureAsn1: 'certExtensions',38539 optional: true38540 }]38541 }, {38542 // AlgorithmIdentifier (signature algorithm)38543 name: 'Certificate.signatureAlgorithm',38544 tagClass: asn1.Class.UNIVERSAL,38545 type: asn1.Type.SEQUENCE,38546 constructed: true,38547 value: [{38548 // algorithm38549 name: 'Certificate.signatureAlgorithm.algorithm',38550 tagClass: asn1.Class.UNIVERSAL,38551 type: asn1.Type.OID,38552 constructed: false,38553 capture: 'certSignatureOid'38554 }, {38555 name: 'Certificate.TBSCertificate.signature.parameters',38556 tagClass: asn1.Class.UNIVERSAL,38557 optional: true,38558 captureAsn1: 'certSignatureParams'38559 }]38560 }, {38561 // SignatureValue38562 name: 'Certificate.signatureValue',38563 tagClass: asn1.Class.UNIVERSAL,38564 type: asn1.Type.BITSTRING,38565 constructed: false,38566 captureBitStringValue: 'certSignature'38567 }]38568};38569var rsassaPssParameterValidator = {38570 name: 'rsapss',38571 tagClass: asn1.Class.UNIVERSAL,38572 type: asn1.Type.SEQUENCE,38573 constructed: true,38574 value: [{38575 name: 'rsapss.hashAlgorithm',38576 tagClass: asn1.Class.CONTEXT_SPECIFIC,38577 type: 0,38578 constructed: true,38579 value: [{38580 name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',38581 tagClass: asn1.Class.UNIVERSAL,38582 type: asn1.Class.SEQUENCE,38583 constructed: true,38584 optional: true,38585 value: [{38586 name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',38587 tagClass: asn1.Class.UNIVERSAL,38588 type: asn1.Type.OID,38589 constructed: false,38590 capture: 'hashOid'38591 /* parameter block omitted, for SHA1 NULL anyhow. */38592 }]38593 }]38594 }, {38595 name: 'rsapss.maskGenAlgorithm',38596 tagClass: asn1.Class.CONTEXT_SPECIFIC,38597 type: 1,38598 constructed: true,38599 value: [{38600 name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',38601 tagClass: asn1.Class.UNIVERSAL,38602 type: asn1.Class.SEQUENCE,38603 constructed: true,38604 optional: true,38605 value: [{38606 name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',38607 tagClass: asn1.Class.UNIVERSAL,38608 type: asn1.Type.OID,38609 constructed: false,38610 capture: 'maskGenOid'38611 }, {38612 name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',38613 tagClass: asn1.Class.UNIVERSAL,38614 type: asn1.Type.SEQUENCE,38615 constructed: true,38616 value: [{38617 name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',38618 tagClass: asn1.Class.UNIVERSAL,38619 type: asn1.Type.OID,38620 constructed: false,38621 capture: 'maskGenHashOid'38622 /* parameter block omitted, for SHA1 NULL anyhow. */38623 }]38624 }]38625 }]38626 }, {38627 name: 'rsapss.saltLength',38628 tagClass: asn1.Class.CONTEXT_SPECIFIC,38629 type: 2,38630 optional: true,38631 value: [{38632 name: 'rsapss.saltLength.saltLength',38633 tagClass: asn1.Class.UNIVERSAL,38634 type: asn1.Class.INTEGER,38635 constructed: false,38636 capture: 'saltLength'38637 }]38638 }, {38639 name: 'rsapss.trailerField',38640 tagClass: asn1.Class.CONTEXT_SPECIFIC,38641 type: 3,38642 optional: true,38643 value: [{38644 name: 'rsapss.trailer.trailer',38645 tagClass: asn1.Class.UNIVERSAL,38646 type: asn1.Class.INTEGER,38647 constructed: false,38648 capture: 'trailer'38649 }]38650 }]38651};38652// validator for a CertificationRequestInfo structure38653var certificationRequestInfoValidator = {38654 name: 'CertificationRequestInfo',38655 tagClass: asn1.Class.UNIVERSAL,38656 type: asn1.Type.SEQUENCE,38657 constructed: true,38658 captureAsn1: 'certificationRequestInfo',38659 value: [{38660 name: 'CertificationRequestInfo.integer',38661 tagClass: asn1.Class.UNIVERSAL,38662 type: asn1.Type.INTEGER,38663 constructed: false,38664 capture: 'certificationRequestInfoVersion'38665 }, {38666 // Name (subject) (RDNSequence)38667 name: 'CertificationRequestInfo.subject',38668 tagClass: asn1.Class.UNIVERSAL,38669 type: asn1.Type.SEQUENCE,38670 constructed: true,38671 captureAsn1: 'certificationRequestInfoSubject'38672 },38673 // SubjectPublicKeyInfo38674 publicKeyValidator,38675 {38676 name: 'CertificationRequestInfo.attributes',38677 tagClass: asn1.Class.CONTEXT_SPECIFIC,38678 type: 0,38679 constructed: true,38680 optional: true,38681 capture: 'certificationRequestInfoAttributes',38682 value: [{38683 name: 'CertificationRequestInfo.attributes',38684 tagClass: asn1.Class.UNIVERSAL,38685 type: asn1.Type.SEQUENCE,38686 constructed: true,38687 value: [{38688 name: 'CertificationRequestInfo.attributes.type',38689 tagClass: asn1.Class.UNIVERSAL,38690 type: asn1.Type.OID,38691 constructed: false38692 }, {38693 name: 'CertificationRequestInfo.attributes.value',38694 tagClass: asn1.Class.UNIVERSAL,38695 type: asn1.Type.SET,38696 constructed: true38697 }]38698 }]38699 }]38700};38701// validator for a CertificationRequest structure38702var certificationRequestValidator = {38703 name: 'CertificationRequest',38704 tagClass: asn1.Class.UNIVERSAL,38705 type: asn1.Type.SEQUENCE,38706 constructed: true,38707 captureAsn1: 'csr',38708 value: [38709 certificationRequestInfoValidator, {38710 // AlgorithmIdentifier (signature algorithm)38711 name: 'CertificationRequest.signatureAlgorithm',38712 tagClass: asn1.Class.UNIVERSAL,38713 type: asn1.Type.SEQUENCE,38714 constructed: true,38715 value: [{38716 // algorithm38717 name: 'CertificationRequest.signatureAlgorithm.algorithm',38718 tagClass: asn1.Class.UNIVERSAL,38719 type: asn1.Type.OID,38720 constructed: false,38721 capture: 'csrSignatureOid'38722 }, {38723 name: 'CertificationRequest.signatureAlgorithm.parameters',38724 tagClass: asn1.Class.UNIVERSAL,38725 optional: true,38726 captureAsn1: 'csrSignatureParams'38727 }]38728 }, {38729 // signature38730 name: 'CertificationRequest.signature',38731 tagClass: asn1.Class.UNIVERSAL,38732 type: asn1.Type.BITSTRING,38733 constructed: false,38734 captureBitStringValue: 'csrSignature'38735 }38736 ]38737};38738/**38739 * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName38740 * sets into an array with objects that have type and value properties.38741 *38742 * @param rdn the RDNSequence to convert.38743 * @param md a message digest to append type and value to if provided.38744 */38745pki.RDNAttributesAsArray = function(rdn, md) {38746 var rval = [];38747 // each value in 'rdn' in is a SET of RelativeDistinguishedName38748 var set, attr, obj;38749 for(var si = 0; si < rdn.value.length; ++si) {38750 // get the RelativeDistinguishedName set38751 set = rdn.value[si];38752 // each value in the SET is an AttributeTypeAndValue sequence38753 // containing first a type (an OID) and second a value (defined by38754 // the OID)38755 for(var i = 0; i < set.value.length; ++i) {38756 obj = {};38757 attr = set.value[i];38758 obj.type = asn1.derToOid(attr.value[0].value);38759 obj.value = attr.value[1].value;38760 obj.valueTagClass = attr.value[1].type;38761 // if the OID is known, get its name and short name38762 if(obj.type in oids) {38763 obj.name = oids[obj.type];38764 if(obj.name in _shortNames) {38765 obj.shortName = _shortNames[obj.name];38766 }38767 }38768 if(md) {38769 md.update(obj.type);38770 md.update(obj.value);38771 }38772 rval.push(obj);38773 }38774 }38775 return rval;38776};38777/**38778 * Converts ASN.1 CRIAttributes into an array with objects that have type and38779 * value properties.38780 *38781 * @param attributes the CRIAttributes to convert.38782 */38783pki.CRIAttributesAsArray = function(attributes) {38784 var rval = [];38785 // each value in 'attributes' in is a SEQUENCE with an OID and a SET38786 for(var si = 0; si < attributes.length; ++si) {38787 // get the attribute sequence38788 var seq = attributes[si];38789 // each value in the SEQUENCE containing first a type (an OID) and38790 // second a set of values (defined by the OID)38791 var type = asn1.derToOid(seq.value[0].value);38792 var values = seq.value[1].value;38793 for(var vi = 0; vi < values.length; ++vi) {38794 var obj = {};38795 obj.type = type;38796 obj.value = values[vi].value;38797 obj.valueTagClass = values[vi].type;38798 // if the OID is known, get its name and short name38799 if(obj.type in oids) {38800 obj.name = oids[obj.type];38801 if(obj.name in _shortNames) {38802 obj.shortName = _shortNames[obj.name];38803 }38804 }38805 // parse extensions38806 if(obj.type === oids.extensionRequest) {38807 obj.extensions = [];38808 for(var ei = 0; ei < obj.value.length; ++ei) {38809 obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));38810 }38811 }38812 rval.push(obj);38813 }38814 }38815 return rval;38816};38817/**38818 * Gets an issuer or subject attribute from its name, type, or short name.38819 *38820 * @param obj the issuer or subject object.38821 * @param options a short name string or an object with:38822 * shortName the short name for the attribute.38823 * name the name for the attribute.38824 * type the type for the attribute.38825 *38826 * @return the attribute.38827 */38828function _getAttribute(obj, options) {38829 if(typeof options === 'string') {38830 options = {shortName: options};38831 }38832 var rval = null;38833 var attr;38834 for(var i = 0; rval === null && i < obj.attributes.length; ++i) {38835 attr = obj.attributes[i];38836 if(options.type && options.type === attr.type) {38837 rval = attr;38838 } else if(options.name && options.name === attr.name) {38839 rval = attr;38840 } else if(options.shortName && options.shortName === attr.shortName) {38841 rval = attr;38842 }38843 }38844 return rval;38845}38846/**38847 * Converts signature parameters from ASN.1 structure.38848 *38849 * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had38850 * no parameters.38851 *38852 * RSASSA-PSS-params ::= SEQUENCE {38853 * hashAlgorithm [0] HashAlgorithm DEFAULT38854 * sha1Identifier,38855 * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT38856 * mgf1SHA1Identifier,38857 * saltLength [2] INTEGER DEFAULT 20,38858 * trailerField [3] INTEGER DEFAULT 138859 * }38860 *38861 * HashAlgorithm ::= AlgorithmIdentifier38862 *38863 * MaskGenAlgorithm ::= AlgorithmIdentifier38864 *38865 * AlgorithmIdentifer ::= SEQUENCE {38866 * algorithm OBJECT IDENTIFIER,38867 * parameters ANY DEFINED BY algorithm OPTIONAL38868 * }38869 *38870 * @param oid The OID specifying the signature algorithm38871 * @param obj The ASN.1 structure holding the parameters38872 * @param fillDefaults Whether to use return default values where omitted38873 * @return signature parameter object38874 */38875var _readSignatureParameters = function(oid, obj, fillDefaults) {38876 var params = {};38877 if(oid !== oids['RSASSA-PSS']) {38878 return params;38879 }38880 if(fillDefaults) {38881 params = {38882 hash: {38883 algorithmOid: oids['sha1']38884 },38885 mgf: {38886 algorithmOid: oids['mgf1'],38887 hash: {38888 algorithmOid: oids['sha1']38889 }38890 },38891 saltLength: 2038892 };38893 }38894 var capture = {};38895 var errors = [];38896 if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {38897 var error = new Error('Cannot read RSASSA-PSS parameter block.');38898 error.errors = errors;38899 throw error;38900 }38901 if(capture.hashOid !== undefined) {38902 params.hash = params.hash || {};38903 params.hash.algorithmOid = asn1.derToOid(capture.hashOid);38904 }38905 if(capture.maskGenOid !== undefined) {38906 params.mgf = params.mgf || {};38907 params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);38908 params.mgf.hash = params.mgf.hash || {};38909 params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);38910 }38911 if(capture.saltLength !== undefined) {38912 params.saltLength = capture.saltLength.charCodeAt(0);38913 }38914 return params;38915};38916/**38917 * Create signature digest for OID.38918 *38919 * @param options38920 * signatureOid: the OID specifying the signature algorithm.38921 * type: a human readable type for error messages38922 * @return a created md instance. throws if unknown oid.38923 */38924var _createSignatureDigest = function(options) {38925 switch(oids[options.signatureOid]) {38926 case 'sha1WithRSAEncryption':38927 // deprecated alias38928 case 'sha1WithRSASignature':38929 return forge.md.sha1.create();38930 case 'md5WithRSAEncryption':38931 return forge.md.md5.create();38932 case 'sha256WithRSAEncryption':38933 return forge.md.sha256.create();38934 case 'sha384WithRSAEncryption':38935 return forge.md.sha384.create();38936 case 'sha512WithRSAEncryption':38937 return forge.md.sha512.create();38938 case 'RSASSA-PSS':38939 return forge.md.sha256.create();38940 default:38941 var error = new Error(38942 'Could not compute ' + options.type + ' digest. ' +38943 'Unknown signature OID.');38944 error.signatureOid = options.signatureOid;38945 throw error;38946 }38947};38948/**38949 * Verify signature on certificate or CSR.38950 *38951 * @param options:38952 * certificate the certificate or CSR to verify.38953 * md the signature digest.38954 * signature the signature38955 * @return a created md instance. throws if unknown oid.38956 */38957var _verifySignature = function(options) {38958 var cert = options.certificate;38959 var scheme;38960 switch(cert.signatureOid) {38961 case oids.sha1WithRSAEncryption:38962 // deprecated alias38963 case oids.sha1WithRSASignature:38964 /* use PKCS#1 v1.5 padding scheme */38965 break;38966 case oids['RSASSA-PSS']:38967 var hash, mgf;38968 /* initialize mgf */38969 hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];38970 if(hash === undefined || forge.md[hash] === undefined) {38971 var error = new Error('Unsupported MGF hash function.');38972 error.oid = cert.signatureParameters.mgf.hash.algorithmOid;38973 error.name = hash;38974 throw error;38975 }38976 mgf = oids[cert.signatureParameters.mgf.algorithmOid];38977 if(mgf === undefined || forge.mgf[mgf] === undefined) {38978 var error = new Error('Unsupported MGF function.');38979 error.oid = cert.signatureParameters.mgf.algorithmOid;38980 error.name = mgf;38981 throw error;38982 }38983 mgf = forge.mgf[mgf].create(forge.md[hash].create());38984 /* initialize hash function */38985 hash = oids[cert.signatureParameters.hash.algorithmOid];38986 if(hash === undefined || forge.md[hash] === undefined) {38987 var error = new Error('Unsupported RSASSA-PSS hash function.');38988 error.oid = cert.signatureParameters.hash.algorithmOid;38989 error.name = hash;38990 throw error;38991 }38992 scheme = forge.pss.create(38993 forge.md[hash].create(), mgf, cert.signatureParameters.saltLength38994 );38995 break;38996 }38997 // verify signature on cert using public key38998 return cert.publicKey.verify(38999 options.md.digest().getBytes(), options.signature, scheme39000 );39001};39002/**39003 * Converts an X.509 certificate from PEM format.39004 *39005 * Note: If the certificate is to be verified then compute hash should39006 * be set to true. This will scan the TBSCertificate part of the ASN.139007 * object while it is converted so it doesn't need to be converted back39008 * to ASN.1-DER-encoding later.39009 *39010 * @param pem the PEM-formatted certificate.39011 * @param computeHash true to compute the hash for verification.39012 * @param strict true to be strict when checking ASN.1 value lengths, false to39013 * allow truncated values (default: true).39014 *39015 * @return the certificate.39016 */39017pki.certificateFromPem = function(pem, computeHash, strict) {39018 var msg = forge.pem.decode(pem)[0];39019 if(msg.type !== 'CERTIFICATE' &&39020 msg.type !== 'X509 CERTIFICATE' &&39021 msg.type !== 'TRUSTED CERTIFICATE') {39022 var error = new Error(39023 'Could not convert certificate from PEM; PEM header type ' +39024 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');39025 error.headerType = msg.type;39026 throw error;39027 }39028 if(msg.procType && msg.procType.type === 'ENCRYPTED') {39029 throw new Error(39030 'Could not convert certificate from PEM; PEM is encrypted.');39031 }39032 // convert DER to ASN.1 object39033 var obj = asn1.fromDer(msg.body, strict);39034 return pki.certificateFromAsn1(obj, computeHash);39035};39036/**39037 * Converts an X.509 certificate to PEM format.39038 *39039 * @param cert the certificate.39040 * @param maxline the maximum characters per line, defaults to 64.39041 *39042 * @return the PEM-formatted certificate.39043 */39044pki.certificateToPem = function(cert, maxline) {39045 // convert to ASN.1, then DER, then PEM-encode39046 var msg = {39047 type: 'CERTIFICATE',39048 body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()39049 };39050 return forge.pem.encode(msg, {maxline: maxline});39051};39052/**39053 * Converts an RSA public key from PEM format.39054 *39055 * @param pem the PEM-formatted public key.39056 *39057 * @return the public key.39058 */39059pki.publicKeyFromPem = function(pem) {39060 var msg = forge.pem.decode(pem)[0];39061 if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {39062 var error = new Error('Could not convert public key from PEM; PEM header ' +39063 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');39064 error.headerType = msg.type;39065 throw error;39066 }39067 if(msg.procType && msg.procType.type === 'ENCRYPTED') {39068 throw new Error('Could not convert public key from PEM; PEM is encrypted.');39069 }39070 // convert DER to ASN.1 object39071 var obj = asn1.fromDer(msg.body);39072 return pki.publicKeyFromAsn1(obj);39073};39074/**39075 * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).39076 *39077 * @param key the public key.39078 * @param maxline the maximum characters per line, defaults to 64.39079 *39080 * @return the PEM-formatted public key.39081 */39082pki.publicKeyToPem = function(key, maxline) {39083 // convert to ASN.1, then DER, then PEM-encode39084 var msg = {39085 type: 'PUBLIC KEY',39086 body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()39087 };39088 return forge.pem.encode(msg, {maxline: maxline});39089};39090/**39091 * Converts an RSA public key to PEM format (using an RSAPublicKey).39092 *39093 * @param key the public key.39094 * @param maxline the maximum characters per line, defaults to 64.39095 *39096 * @return the PEM-formatted public key.39097 */39098pki.publicKeyToRSAPublicKeyPem = function(key, maxline) {39099 // convert to ASN.1, then DER, then PEM-encode39100 var msg = {39101 type: 'RSA PUBLIC KEY',39102 body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()39103 };39104 return forge.pem.encode(msg, {maxline: maxline});39105};39106/**39107 * Gets a fingerprint for the given public key.39108 *39109 * @param options the options to use.39110 * [md] the message digest object to use (defaults to forge.md.sha1).39111 * [type] the type of fingerprint, such as 'RSAPublicKey',39112 * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').39113 * [encoding] an alternative output encoding, such as 'hex'39114 * (defaults to none, outputs a byte buffer).39115 * [delimiter] the delimiter to use between bytes for 'hex' encoded39116 * output, eg: ':' (defaults to none).39117 *39118 * @return the fingerprint as a byte buffer or other encoding based on options.39119 */39120pki.getPublicKeyFingerprint = function(key, options) {39121 options = options || {};39122 var md = options.md || forge.md.sha1.create();39123 var type = options.type || 'RSAPublicKey';39124 var bytes;39125 switch(type) {39126 case 'RSAPublicKey':39127 bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();39128 break;39129 case 'SubjectPublicKeyInfo':39130 bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();39131 break;39132 default:39133 throw new Error('Unknown fingerprint type "' + options.type + '".');39134 }39135 // hash public key bytes39136 md.start();39137 md.update(bytes);39138 var digest = md.digest();39139 if(options.encoding === 'hex') {39140 var hex = digest.toHex();39141 if(options.delimiter) {39142 return hex.match(/.{2}/g).join(options.delimiter);39143 }39144 return hex;39145 } else if(options.encoding === 'binary') {39146 return digest.getBytes();39147 } else if(options.encoding) {39148 throw new Error('Unknown encoding "' + options.encoding + '".');39149 }39150 return digest;39151};39152/**39153 * Converts a PKCS#10 certification request (CSR) from PEM format.39154 *39155 * Note: If the certification request is to be verified then compute hash39156 * should be set to true. This will scan the CertificationRequestInfo part of39157 * the ASN.1 object while it is converted so it doesn't need to be converted39158 * back to ASN.1-DER-encoding later.39159 *39160 * @param pem the PEM-formatted certificate.39161 * @param computeHash true to compute the hash for verification.39162 * @param strict true to be strict when checking ASN.1 value lengths, false to39163 * allow truncated values (default: true).39164 *39165 * @return the certification request (CSR).39166 */39167pki.certificationRequestFromPem = function(pem, computeHash, strict) {39168 var msg = forge.pem.decode(pem)[0];39169 if(msg.type !== 'CERTIFICATE REQUEST') {39170 var error = new Error('Could not convert certification request from PEM; ' +39171 'PEM header type is not "CERTIFICATE REQUEST".');39172 error.headerType = msg.type;39173 throw error;39174 }39175 if(msg.procType && msg.procType.type === 'ENCRYPTED') {39176 throw new Error('Could not convert certification request from PEM; ' +39177 'PEM is encrypted.');39178 }39179 // convert DER to ASN.1 object39180 var obj = asn1.fromDer(msg.body, strict);39181 return pki.certificationRequestFromAsn1(obj, computeHash);39182};39183/**39184 * Converts a PKCS#10 certification request (CSR) to PEM format.39185 *39186 * @param csr the certification request.39187 * @param maxline the maximum characters per line, defaults to 64.39188 *39189 * @return the PEM-formatted certification request.39190 */39191pki.certificationRequestToPem = function(csr, maxline) {39192 // convert to ASN.1, then DER, then PEM-encode39193 var msg = {39194 type: 'CERTIFICATE REQUEST',39195 body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()39196 };39197 return forge.pem.encode(msg, {maxline: maxline});39198};39199/**39200 * Creates an empty X.509v3 RSA certificate.39201 *39202 * @return the certificate.39203 */39204pki.createCertificate = function() {39205 var cert = {};39206 cert.version = 0x02;39207 cert.serialNumber = '00';39208 cert.signatureOid = null;39209 cert.signature = null;39210 cert.siginfo = {};39211 cert.siginfo.algorithmOid = null;39212 cert.validity = {};39213 cert.validity.notBefore = new Date();39214 cert.validity.notAfter = new Date();39215 cert.issuer = {};39216 cert.issuer.getField = function(sn) {39217 return _getAttribute(cert.issuer, sn);39218 };39219 cert.issuer.addField = function(attr) {39220 _fillMissingFields([attr]);39221 cert.issuer.attributes.push(attr);39222 };39223 cert.issuer.attributes = [];39224 cert.issuer.hash = null;39225 cert.subject = {};39226 cert.subject.getField = function(sn) {39227 return _getAttribute(cert.subject, sn);39228 };39229 cert.subject.addField = function(attr) {39230 _fillMissingFields([attr]);39231 cert.subject.attributes.push(attr);39232 };39233 cert.subject.attributes = [];39234 cert.subject.hash = null;39235 cert.extensions = [];39236 cert.publicKey = null;39237 cert.md = null;39238 /**39239 * Sets the subject of this certificate.39240 *39241 * @param attrs the array of subject attributes to use.39242 * @param uniqueId an optional a unique ID to use.39243 */39244 cert.setSubject = function(attrs, uniqueId) {39245 // set new attributes, clear hash39246 _fillMissingFields(attrs);39247 cert.subject.attributes = attrs;39248 delete cert.subject.uniqueId;39249 if(uniqueId) {39250 // TODO: support arbitrary bit length ids39251 cert.subject.uniqueId = uniqueId;39252 }39253 cert.subject.hash = null;39254 };39255 /**39256 * Sets the issuer of this certificate.39257 *39258 * @param attrs the array of issuer attributes to use.39259 * @param uniqueId an optional a unique ID to use.39260 */39261 cert.setIssuer = function(attrs, uniqueId) {39262 // set new attributes, clear hash39263 _fillMissingFields(attrs);39264 cert.issuer.attributes = attrs;39265 delete cert.issuer.uniqueId;39266 if(uniqueId) {39267 // TODO: support arbitrary bit length ids39268 cert.issuer.uniqueId = uniqueId;39269 }39270 cert.issuer.hash = null;39271 };39272 /**39273 * Sets the extensions of this certificate.39274 *39275 * @param exts the array of extensions to use.39276 */39277 cert.setExtensions = function(exts) {39278 for(var i = 0; i < exts.length; ++i) {39279 _fillMissingExtensionFields(exts[i], {cert: cert});39280 }39281 // set new extensions39282 cert.extensions = exts;39283 };39284 /**39285 * Gets an extension by its name or id.39286 *39287 * @param options the name to use or an object with:39288 * name the name to use.39289 * id the id to use.39290 *39291 * @return the extension or null if not found.39292 */39293 cert.getExtension = function(options) {39294 if(typeof options === 'string') {39295 options = {name: options};39296 }39297 var rval = null;39298 var ext;39299 for(var i = 0; rval === null && i < cert.extensions.length; ++i) {39300 ext = cert.extensions[i];39301 if(options.id && ext.id === options.id) {39302 rval = ext;39303 } else if(options.name && ext.name === options.name) {39304 rval = ext;39305 }39306 }39307 return rval;39308 };39309 /**39310 * Signs this certificate using the given private key.39311 *39312 * @param key the private key to sign with.39313 * @param md the message digest object to use (defaults to forge.md.sha1).39314 */39315 cert.sign = function(key, md) {39316 // TODO: get signature OID from private key39317 cert.md = md || forge.md.sha1.create();39318 var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];39319 if(!algorithmOid) {39320 var error = new Error('Could not compute certificate digest. ' +39321 'Unknown message digest algorithm OID.');39322 error.algorithm = cert.md.algorithm;39323 throw error;39324 }39325 cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;39326 // get TBSCertificate, convert to DER39327 cert.tbsCertificate = pki.getTBSCertificate(cert);39328 var bytes = asn1.toDer(cert.tbsCertificate);39329 // digest and sign39330 cert.md.update(bytes.getBytes());39331 cert.signature = key.sign(cert.md);39332 };39333 /**39334 * Attempts verify the signature on the passed certificate using this39335 * certificate's public key.39336 *39337 * @param child the certificate to verify.39338 *39339 * @return true if verified, false if not.39340 */39341 cert.verify = function(child) {39342 var rval = false;39343 if(!cert.issued(child)) {39344 var issuer = child.issuer;39345 var subject = cert.subject;39346 var error = new Error(39347 'The parent certificate did not issue the given child ' +39348 'certificate; the child certificate\'s issuer does not match the ' +39349 'parent\'s subject.');39350 error.expectedIssuer = subject.attributes;39351 error.actualIssuer = issuer.attributes;39352 throw error;39353 }39354 var md = child.md;39355 if(md === null) {39356 // create digest for OID signature types39357 md = _createSignatureDigest({39358 signatureOid: child.signatureOid,39359 type: 'certificate'39360 });39361 // produce DER formatted TBSCertificate and digest it39362 var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);39363 var bytes = asn1.toDer(tbsCertificate);39364 md.update(bytes.getBytes());39365 }39366 if(md !== null) {39367 rval = _verifySignature({39368 certificate: cert, md: md, signature: child.signature39369 });39370 }39371 return rval;39372 };39373 /**39374 * Returns true if this certificate's issuer matches the passed39375 * certificate's subject. Note that no signature check is performed.39376 *39377 * @param parent the certificate to check.39378 *39379 * @return true if this certificate's issuer matches the passed certificate's39380 * subject.39381 */39382 cert.isIssuer = function(parent) {39383 var rval = false;39384 var i = cert.issuer;39385 var s = parent.subject;39386 // compare hashes if present39387 if(i.hash && s.hash) {39388 rval = (i.hash === s.hash);39389 } else if(i.attributes.length === s.attributes.length) {39390 // all attributes are the same so issuer matches subject39391 rval = true;39392 var iattr, sattr;39393 for(var n = 0; rval && n < i.attributes.length; ++n) {39394 iattr = i.attributes[n];39395 sattr = s.attributes[n];39396 if(iattr.type !== sattr.type || iattr.value !== sattr.value) {39397 // attribute mismatch39398 rval = false;39399 }39400 }39401 }39402 return rval;39403 };39404 /**39405 * Returns true if this certificate's subject matches the issuer of the39406 * given certificate). Note that not signature check is performed.39407 *39408 * @param child the certificate to check.39409 *39410 * @return true if this certificate's subject matches the passed39411 * certificate's issuer.39412 */39413 cert.issued = function(child) {39414 return child.isIssuer(cert);39415 };39416 /**39417 * Generates the subjectKeyIdentifier for this certificate as byte buffer.39418 *39419 * @return the subjectKeyIdentifier for this certificate as byte buffer.39420 */39421 cert.generateSubjectKeyIdentifier = function() {39422 /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:39423 (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the39424 value of the BIT STRING subjectPublicKey (excluding the tag,39425 length, and number of unused bits).39426 (2) The keyIdentifier is composed of a four bit type field with39427 the value 0100 followed by the least significant 60 bits of the39428 SHA-1 hash of the value of the BIT STRING subjectPublicKey39429 (excluding the tag, length, and number of unused bit string bits).39430 */39431 // skipping the tag, length, and number of unused bits is the same39432 // as just using the RSAPublicKey (for RSA keys, which are the39433 // only ones supported)39434 return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});39435 };39436 /**39437 * Verifies the subjectKeyIdentifier extension value for this certificate39438 * against its public key. If no extension is found, false will be39439 * returned.39440 *39441 * @return true if verified, false if not.39442 */39443 cert.verifySubjectKeyIdentifier = function() {39444 var oid = oids['subjectKeyIdentifier'];39445 for(var i = 0; i < cert.extensions.length; ++i) {39446 var ext = cert.extensions[i];39447 if(ext.id === oid) {39448 var ski = cert.generateSubjectKeyIdentifier().getBytes();39449 return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);39450 }39451 }39452 return false;39453 };39454 return cert;39455};39456/**39457 * Converts an X.509v3 RSA certificate from an ASN.1 object.39458 *39459 * Note: If the certificate is to be verified then compute hash should39460 * be set to true. There is currently no implementation for converting39461 * a certificate back to ASN.1 so the TBSCertificate part of the ASN.139462 * object needs to be scanned before the cert object is created.39463 *39464 * @param obj the asn1 representation of an X.509v3 RSA certificate.39465 * @param computeHash true to compute the hash for verification.39466 *39467 * @return the certificate.39468 */39469pki.certificateFromAsn1 = function(obj, computeHash) {39470 // validate certificate and capture data39471 var capture = {};39472 var errors = [];39473 if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {39474 var error = new Error('Cannot read X.509 certificate. ' +39475 'ASN.1 object is not an X509v3 Certificate.');39476 error.errors = errors;39477 throw error;39478 }39479 // get oid39480 var oid = asn1.derToOid(capture.publicKeyOid);39481 if(oid !== pki.oids.rsaEncryption) {39482 throw new Error('Cannot read public key. OID is not RSA.');39483 }39484 // create certificate39485 var cert = pki.createCertificate();39486 cert.version = capture.certVersion ?39487 capture.certVersion.charCodeAt(0) : 0;39488 var serial = forge.util.createBuffer(capture.certSerialNumber);39489 cert.serialNumber = serial.toHex();39490 cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);39491 cert.signatureParameters = _readSignatureParameters(39492 cert.signatureOid, capture.certSignatureParams, true);39493 cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);39494 cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,39495 capture.certinfoSignatureParams, false);39496 cert.signature = capture.certSignature;39497 var validity = [];39498 if(capture.certValidity1UTCTime !== undefined) {39499 validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));39500 }39501 if(capture.certValidity2GeneralizedTime !== undefined) {39502 validity.push(asn1.generalizedTimeToDate(39503 capture.certValidity2GeneralizedTime));39504 }39505 if(capture.certValidity3UTCTime !== undefined) {39506 validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));39507 }39508 if(capture.certValidity4GeneralizedTime !== undefined) {39509 validity.push(asn1.generalizedTimeToDate(39510 capture.certValidity4GeneralizedTime));39511 }39512 if(validity.length > 2) {39513 throw new Error('Cannot read notBefore/notAfter validity times; more ' +39514 'than two times were provided in the certificate.');39515 }39516 if(validity.length < 2) {39517 throw new Error('Cannot read notBefore/notAfter validity times; they ' +39518 'were not provided as either UTCTime or GeneralizedTime.');39519 }39520 cert.validity.notBefore = validity[0];39521 cert.validity.notAfter = validity[1];39522 // keep TBSCertificate to preserve signature when exporting39523 cert.tbsCertificate = capture.tbsCertificate;39524 if(computeHash) {39525 // create digest for OID signature type39526 cert.md = _createSignatureDigest({39527 signatureOid: cert.signatureOid,39528 type: 'certificate'39529 });39530 // produce DER formatted TBSCertificate and digest it39531 var bytes = asn1.toDer(cert.tbsCertificate);39532 cert.md.update(bytes.getBytes());39533 }39534 // handle issuer, build issuer message digest39535 var imd = forge.md.sha1.create();39536 var ibytes = asn1.toDer(capture.certIssuer);39537 imd.update(ibytes.getBytes());39538 cert.issuer.getField = function(sn) {39539 return _getAttribute(cert.issuer, sn);39540 };39541 cert.issuer.addField = function(attr) {39542 _fillMissingFields([attr]);39543 cert.issuer.attributes.push(attr);39544 };39545 cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);39546 if(capture.certIssuerUniqueId) {39547 cert.issuer.uniqueId = capture.certIssuerUniqueId;39548 }39549 cert.issuer.hash = imd.digest().toHex();39550 // handle subject, build subject message digest39551 var smd = forge.md.sha1.create();39552 var sbytes = asn1.toDer(capture.certSubject);39553 smd.update(sbytes.getBytes());39554 cert.subject.getField = function(sn) {39555 return _getAttribute(cert.subject, sn);39556 };39557 cert.subject.addField = function(attr) {39558 _fillMissingFields([attr]);39559 cert.subject.attributes.push(attr);39560 };39561 cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);39562 if(capture.certSubjectUniqueId) {39563 cert.subject.uniqueId = capture.certSubjectUniqueId;39564 }39565 cert.subject.hash = smd.digest().toHex();39566 // handle extensions39567 if(capture.certExtensions) {39568 cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);39569 } else {39570 cert.extensions = [];39571 }39572 // convert RSA public key from ASN.139573 cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);39574 return cert;39575};39576/**39577 * Converts an ASN.1 extensions object (with extension sequences as its39578 * values) into an array of extension objects with types and values.39579 *39580 * Supported extensions:39581 *39582 * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }39583 * KeyUsage ::= BIT STRING {39584 * digitalSignature (0),39585 * nonRepudiation (1),39586 * keyEncipherment (2),39587 * dataEncipherment (3),39588 * keyAgreement (4),39589 * keyCertSign (5),39590 * cRLSign (6),39591 * encipherOnly (7),39592 * decipherOnly (8)39593 * }39594 *39595 * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }39596 * BasicConstraints ::= SEQUENCE {39597 * cA BOOLEAN DEFAULT FALSE,39598 * pathLenConstraint INTEGER (0..MAX) OPTIONAL39599 * }39600 *39601 * subjectAltName EXTENSION ::= {39602 * SYNTAX GeneralNames39603 * IDENTIFIED BY id-ce-subjectAltName39604 * }39605 *39606 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName39607 *39608 * GeneralName ::= CHOICE {39609 * otherName [0] INSTANCE OF OTHER-NAME,39610 * rfc822Name [1] IA5String,39611 * dNSName [2] IA5String,39612 * x400Address [3] ORAddress,39613 * directoryName [4] Name,39614 * ediPartyName [5] EDIPartyName,39615 * uniformResourceIdentifier [6] IA5String,39616 * IPAddress [7] OCTET STRING,39617 * registeredID [8] OBJECT IDENTIFIER39618 * }39619 *39620 * OTHER-NAME ::= TYPE-IDENTIFIER39621 *39622 * EDIPartyName ::= SEQUENCE {39623 * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,39624 * partyName [1] DirectoryString {ub-name}39625 * }39626 *39627 * @param exts the extensions ASN.1 with extension sequences to parse.39628 *39629 * @return the array.39630 */39631pki.certificateExtensionsFromAsn1 = function(exts) {39632 var rval = [];39633 for(var i = 0; i < exts.value.length; ++i) {39634 // get extension sequence39635 var extseq = exts.value[i];39636 for(var ei = 0; ei < extseq.value.length; ++ei) {39637 rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));39638 }39639 }39640 return rval;39641};39642/**39643 * Parses a single certificate extension from ASN.1.39644 *39645 * @param ext the extension in ASN.1 format.39646 *39647 * @return the parsed extension as an object.39648 */39649pki.certificateExtensionFromAsn1 = function(ext) {39650 // an extension has:39651 // [0] extnID OBJECT IDENTIFIER39652 // [1] critical BOOLEAN DEFAULT FALSE39653 // [2] extnValue OCTET STRING39654 var e = {};39655 e.id = asn1.derToOid(ext.value[0].value);39656 e.critical = false;39657 if(ext.value[1].type === asn1.Type.BOOLEAN) {39658 e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);39659 e.value = ext.value[2].value;39660 } else {39661 e.value = ext.value[1].value;39662 }39663 // if the oid is known, get its name39664 if(e.id in oids) {39665 e.name = oids[e.id];39666 // handle key usage39667 if(e.name === 'keyUsage') {39668 // get value as BIT STRING39669 var ev = asn1.fromDer(e.value);39670 var b2 = 0x00;39671 var b3 = 0x00;39672 if(ev.value.length > 1) {39673 // skip first byte, just indicates unused bits which39674 // will be padded with 0s anyway39675 // get bytes with flag bits39676 b2 = ev.value.charCodeAt(1);39677 b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;39678 }39679 // set flags39680 e.digitalSignature = (b2 & 0x80) === 0x80;39681 e.nonRepudiation = (b2 & 0x40) === 0x40;39682 e.keyEncipherment = (b2 & 0x20) === 0x20;39683 e.dataEncipherment = (b2 & 0x10) === 0x10;39684 e.keyAgreement = (b2 & 0x08) === 0x08;39685 e.keyCertSign = (b2 & 0x04) === 0x04;39686 e.cRLSign = (b2 & 0x02) === 0x02;39687 e.encipherOnly = (b2 & 0x01) === 0x01;39688 e.decipherOnly = (b3 & 0x80) === 0x80;39689 } else if(e.name === 'basicConstraints') {39690 // handle basic constraints39691 // get value as SEQUENCE39692 var ev = asn1.fromDer(e.value);39693 // get cA BOOLEAN flag (defaults to false)39694 if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {39695 e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);39696 } else {39697 e.cA = false;39698 }39699 // get path length constraint39700 var value = null;39701 if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {39702 value = ev.value[0].value;39703 } else if(ev.value.length > 1) {39704 value = ev.value[1].value;39705 }39706 if(value !== null) {39707 e.pathLenConstraint = asn1.derToInteger(value);39708 }39709 } else if(e.name === 'extKeyUsage') {39710 // handle extKeyUsage39711 // value is a SEQUENCE of OIDs39712 var ev = asn1.fromDer(e.value);39713 for(var vi = 0; vi < ev.value.length; ++vi) {39714 var oid = asn1.derToOid(ev.value[vi].value);39715 if(oid in oids) {39716 e[oids[oid]] = true;39717 } else {39718 e[oid] = true;39719 }39720 }39721 } else if(e.name === 'nsCertType') {39722 // handle nsCertType39723 // get value as BIT STRING39724 var ev = asn1.fromDer(e.value);39725 var b2 = 0x00;39726 if(ev.value.length > 1) {39727 // skip first byte, just indicates unused bits which39728 // will be padded with 0s anyway39729 // get bytes with flag bits39730 b2 = ev.value.charCodeAt(1);39731 }39732 // set flags39733 e.client = (b2 & 0x80) === 0x80;39734 e.server = (b2 & 0x40) === 0x40;39735 e.email = (b2 & 0x20) === 0x20;39736 e.objsign = (b2 & 0x10) === 0x10;39737 e.reserved = (b2 & 0x08) === 0x08;39738 e.sslCA = (b2 & 0x04) === 0x04;39739 e.emailCA = (b2 & 0x02) === 0x02;39740 e.objCA = (b2 & 0x01) === 0x01;39741 } else if(39742 e.name === 'subjectAltName' ||39743 e.name === 'issuerAltName') {39744 // handle subjectAltName/issuerAltName39745 e.altNames = [];39746 // ev is a SYNTAX SEQUENCE39747 var gn;39748 var ev = asn1.fromDer(e.value);39749 for(var n = 0; n < ev.value.length; ++n) {39750 // get GeneralName39751 gn = ev.value[n];39752 var altName = {39753 type: gn.type,39754 value: gn.value39755 };39756 e.altNames.push(altName);39757 // Note: Support for types 1,2,6,7,839758 switch(gn.type) {39759 // rfc822Name39760 case 1:39761 // dNSName39762 case 2:39763 // uniformResourceIdentifier (URI)39764 case 6:39765 break;39766 // IPAddress39767 case 7:39768 // convert to IPv4/IPv6 string representation39769 altName.ip = forge.util.bytesToIP(gn.value);39770 break;39771 // registeredID39772 case 8:39773 altName.oid = asn1.derToOid(gn.value);39774 break;39775 default:39776 // unsupported39777 }39778 }39779 } else if(e.name === 'subjectKeyIdentifier') {39780 // value is an OCTETSTRING w/the hash of the key-type specific39781 // public key structure (eg: RSAPublicKey)39782 var ev = asn1.fromDer(e.value);39783 e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);39784 }39785 }39786 return e;39787};39788/**39789 * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.39790 *39791 * Note: If the certification request is to be verified then compute hash39792 * should be set to true. There is currently no implementation for converting39793 * a certificate back to ASN.1 so the CertificationRequestInfo part of the39794 * ASN.1 object needs to be scanned before the csr object is created.39795 *39796 * @param obj the asn1 representation of a PKCS#10 certification request (CSR).39797 * @param computeHash true to compute the hash for verification.39798 *39799 * @return the certification request (CSR).39800 */39801pki.certificationRequestFromAsn1 = function(obj, computeHash) {39802 // validate certification request and capture data39803 var capture = {};39804 var errors = [];39805 if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {39806 var error = new Error('Cannot read PKCS#10 certificate request. ' +39807 'ASN.1 object is not a PKCS#10 CertificationRequest.');39808 error.errors = errors;39809 throw error;39810 }39811 // get oid39812 var oid = asn1.derToOid(capture.publicKeyOid);39813 if(oid !== pki.oids.rsaEncryption) {39814 throw new Error('Cannot read public key. OID is not RSA.');39815 }39816 // create certification request39817 var csr = pki.createCertificationRequest();39818 csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;39819 csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);39820 csr.signatureParameters = _readSignatureParameters(39821 csr.signatureOid, capture.csrSignatureParams, true);39822 csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);39823 csr.siginfo.parameters = _readSignatureParameters(39824 csr.siginfo.algorithmOid, capture.csrSignatureParams, false);39825 csr.signature = capture.csrSignature;39826 // keep CertificationRequestInfo to preserve signature when exporting39827 csr.certificationRequestInfo = capture.certificationRequestInfo;39828 if(computeHash) {39829 // create digest for OID signature type39830 csr.md = _createSignatureDigest({39831 signatureOid: csr.signatureOid,39832 type: 'certification request'39833 });39834 // produce DER formatted CertificationRequestInfo and digest it39835 var bytes = asn1.toDer(csr.certificationRequestInfo);39836 csr.md.update(bytes.getBytes());39837 }39838 // handle subject, build subject message digest39839 var smd = forge.md.sha1.create();39840 csr.subject.getField = function(sn) {39841 return _getAttribute(csr.subject, sn);39842 };39843 csr.subject.addField = function(attr) {39844 _fillMissingFields([attr]);39845 csr.subject.attributes.push(attr);39846 };39847 csr.subject.attributes = pki.RDNAttributesAsArray(39848 capture.certificationRequestInfoSubject, smd);39849 csr.subject.hash = smd.digest().toHex();39850 // convert RSA public key from ASN.139851 csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);39852 // convert attributes from ASN.139853 csr.getAttribute = function(sn) {39854 return _getAttribute(csr, sn);39855 };39856 csr.addAttribute = function(attr) {39857 _fillMissingFields([attr]);39858 csr.attributes.push(attr);39859 };39860 csr.attributes = pki.CRIAttributesAsArray(39861 capture.certificationRequestInfoAttributes || []);39862 return csr;39863};39864/**39865 * Creates an empty certification request (a CSR or certificate signing39866 * request). Once created, its public key and attributes can be set and then39867 * it can be signed.39868 *39869 * @return the empty certification request.39870 */39871pki.createCertificationRequest = function() {39872 var csr = {};39873 csr.version = 0x00;39874 csr.signatureOid = null;39875 csr.signature = null;39876 csr.siginfo = {};39877 csr.siginfo.algorithmOid = null;39878 csr.subject = {};39879 csr.subject.getField = function(sn) {39880 return _getAttribute(csr.subject, sn);39881 };39882 csr.subject.addField = function(attr) {39883 _fillMissingFields([attr]);39884 csr.subject.attributes.push(attr);39885 };39886 csr.subject.attributes = [];39887 csr.subject.hash = null;39888 csr.publicKey = null;39889 csr.attributes = [];39890 csr.getAttribute = function(sn) {39891 return _getAttribute(csr, sn);39892 };39893 csr.addAttribute = function(attr) {39894 _fillMissingFields([attr]);39895 csr.attributes.push(attr);39896 };39897 csr.md = null;39898 /**39899 * Sets the subject of this certification request.39900 *39901 * @param attrs the array of subject attributes to use.39902 */39903 csr.setSubject = function(attrs) {39904 // set new attributes39905 _fillMissingFields(attrs);39906 csr.subject.attributes = attrs;39907 csr.subject.hash = null;39908 };39909 /**39910 * Sets the attributes of this certification request.39911 *39912 * @param attrs the array of attributes to use.39913 */39914 csr.setAttributes = function(attrs) {39915 // set new attributes39916 _fillMissingFields(attrs);39917 csr.attributes = attrs;39918 };39919 /**39920 * Signs this certification request using the given private key.39921 *39922 * @param key the private key to sign with.39923 * @param md the message digest object to use (defaults to forge.md.sha1).39924 */39925 csr.sign = function(key, md) {39926 // TODO: get signature OID from private key39927 csr.md = md || forge.md.sha1.create();39928 var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];39929 if(!algorithmOid) {39930 var error = new Error('Could not compute certification request digest. ' +39931 'Unknown message digest algorithm OID.');39932 error.algorithm = csr.md.algorithm;39933 throw error;39934 }39935 csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;39936 // get CertificationRequestInfo, convert to DER39937 csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);39938 var bytes = asn1.toDer(csr.certificationRequestInfo);39939 // digest and sign39940 csr.md.update(bytes.getBytes());39941 csr.signature = key.sign(csr.md);39942 };39943 /**39944 * Attempts verify the signature on the passed certification request using39945 * its public key.39946 *39947 * A CSR that has been exported to a file in PEM format can be verified using39948 * OpenSSL using this command:39949 *39950 * openssl req -in <the-csr-pem-file> -verify -noout -text39951 *39952 * @return true if verified, false if not.39953 */39954 csr.verify = function() {39955 var rval = false;39956 var md = csr.md;39957 if(md === null) {39958 md = _createSignatureDigest({39959 signatureOid: csr.signatureOid,39960 type: 'certification request'39961 });39962 // produce DER formatted CertificationRequestInfo and digest it39963 var cri = csr.certificationRequestInfo ||39964 pki.getCertificationRequestInfo(csr);39965 var bytes = asn1.toDer(cri);39966 md.update(bytes.getBytes());39967 }39968 if(md !== null) {39969 rval = _verifySignature({39970 certificate: csr, md: md, signature: csr.signature39971 });39972 }39973 return rval;39974 };39975 return csr;39976};39977/**39978 * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.39979 *39980 * @param obj the subject or issuer (distinguished name).39981 *39982 * @return the ASN.1 RDNSequence.39983 */39984function _dnToAsn1(obj) {39985 // create an empty RDNSequence39986 var rval = asn1.create(39987 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);39988 // iterate over attributes39989 var attr, set;39990 var attrs = obj.attributes;39991 for(var i = 0; i < attrs.length; ++i) {39992 attr = attrs[i];39993 var value = attr.value;39994 // reuse tag class for attribute value if available39995 var valueTagClass = asn1.Type.PRINTABLESTRING;39996 if('valueTagClass' in attr) {39997 valueTagClass = attr.valueTagClass;39998 if(valueTagClass === asn1.Type.UTF8) {39999 value = forge.util.encodeUtf8(value);40000 }40001 // FIXME: handle more encodings40002 }40003 // create a RelativeDistinguishedName set40004 // each value in the set is an AttributeTypeAndValue first40005 // containing the type (an OID) and second the value40006 set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [40007 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40008 // AttributeType40009 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,40010 asn1.oidToDer(attr.type).getBytes()),40011 // AttributeValue40012 asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)40013 ])40014 ]);40015 rval.value.push(set);40016 }40017 return rval;40018}40019/**40020 * Gets all printable attributes (typically of an issuer or subject) in a40021 * simplified JSON format for display.40022 *40023 * @param attrs the attributes.40024 *40025 * @return the JSON for display.40026 */40027function _getAttributesAsJson(attrs) {40028 var rval = {};40029 for(var i = 0; i < attrs.length; ++i) {40030 var attr = attrs[i];40031 if(attr.shortName && (40032 attr.valueTagClass === asn1.Type.UTF8 ||40033 attr.valueTagClass === asn1.Type.PRINTABLESTRING ||40034 attr.valueTagClass === asn1.Type.IA5STRING)) {40035 var value = attr.value;40036 if(attr.valueTagClass === asn1.Type.UTF8) {40037 value = forge.util.encodeUtf8(attr.value);40038 }40039 if(!(attr.shortName in rval)) {40040 rval[attr.shortName] = value;40041 } else if(forge.util.isArray(rval[attr.shortName])) {40042 rval[attr.shortName].push(value);40043 } else {40044 rval[attr.shortName] = [rval[attr.shortName], value];40045 }40046 }40047 }40048 return rval;40049}40050/**40051 * Fills in missing fields in attributes.40052 *40053 * @param attrs the attributes to fill missing fields in.40054 */40055function _fillMissingFields(attrs) {40056 var attr;40057 for(var i = 0; i < attrs.length; ++i) {40058 attr = attrs[i];40059 // populate missing name40060 if(typeof attr.name === 'undefined') {40061 if(attr.type && attr.type in pki.oids) {40062 attr.name = pki.oids[attr.type];40063 } else if(attr.shortName && attr.shortName in _shortNames) {40064 attr.name = pki.oids[_shortNames[attr.shortName]];40065 }40066 }40067 // populate missing type (OID)40068 if(typeof attr.type === 'undefined') {40069 if(attr.name && attr.name in pki.oids) {40070 attr.type = pki.oids[attr.name];40071 } else {40072 var error = new Error('Attribute type not specified.');40073 error.attribute = attr;40074 throw error;40075 }40076 }40077 // populate missing shortname40078 if(typeof attr.shortName === 'undefined') {40079 if(attr.name && attr.name in _shortNames) {40080 attr.shortName = _shortNames[attr.name];40081 }40082 }40083 // convert extensions to value40084 if(attr.type === oids.extensionRequest) {40085 attr.valueConstructed = true;40086 attr.valueTagClass = asn1.Type.SEQUENCE;40087 if(!attr.value && attr.extensions) {40088 attr.value = [];40089 for(var ei = 0; ei < attr.extensions.length; ++ei) {40090 attr.value.push(pki.certificateExtensionToAsn1(40091 _fillMissingExtensionFields(attr.extensions[ei])));40092 }40093 }40094 }40095 if(typeof attr.value === 'undefined') {40096 var error = new Error('Attribute value not specified.');40097 error.attribute = attr;40098 throw error;40099 }40100 }40101}40102/**40103 * Fills in missing fields in certificate extensions.40104 *40105 * @param e the extension.40106 * @param [options] the options to use.40107 * [cert] the certificate the extensions are for.40108 *40109 * @return the extension.40110 */40111function _fillMissingExtensionFields(e, options) {40112 options = options || {};40113 // populate missing name40114 if(typeof e.name === 'undefined') {40115 if(e.id && e.id in pki.oids) {40116 e.name = pki.oids[e.id];40117 }40118 }40119 // populate missing id40120 if(typeof e.id === 'undefined') {40121 if(e.name && e.name in pki.oids) {40122 e.id = pki.oids[e.name];40123 } else {40124 var error = new Error('Extension ID not specified.');40125 error.extension = e;40126 throw error;40127 }40128 }40129 if(typeof e.value !== 'undefined') {40130 return e;40131 }40132 // handle missing value:40133 // value is a BIT STRING40134 if(e.name === 'keyUsage') {40135 // build flags40136 var unused = 0;40137 var b2 = 0x00;40138 var b3 = 0x00;40139 if(e.digitalSignature) {40140 b2 |= 0x80;40141 unused = 7;40142 }40143 if(e.nonRepudiation) {40144 b2 |= 0x40;40145 unused = 6;40146 }40147 if(e.keyEncipherment) {40148 b2 |= 0x20;40149 unused = 5;40150 }40151 if(e.dataEncipherment) {40152 b2 |= 0x10;40153 unused = 4;40154 }40155 if(e.keyAgreement) {40156 b2 |= 0x08;40157 unused = 3;40158 }40159 if(e.keyCertSign) {40160 b2 |= 0x04;40161 unused = 2;40162 }40163 if(e.cRLSign) {40164 b2 |= 0x02;40165 unused = 1;40166 }40167 if(e.encipherOnly) {40168 b2 |= 0x01;40169 unused = 0;40170 }40171 if(e.decipherOnly) {40172 b3 |= 0x80;40173 unused = 7;40174 }40175 // create bit string40176 var value = String.fromCharCode(unused);40177 if(b3 !== 0) {40178 value += String.fromCharCode(b2) + String.fromCharCode(b3);40179 } else if(b2 !== 0) {40180 value += String.fromCharCode(b2);40181 }40182 e.value = asn1.create(40183 asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);40184 } else if(e.name === 'basicConstraints') {40185 // basicConstraints is a SEQUENCE40186 e.value = asn1.create(40187 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);40188 // cA BOOLEAN flag defaults to false40189 if(e.cA) {40190 e.value.value.push(asn1.create(40191 asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,40192 String.fromCharCode(0xFF)));40193 }40194 if('pathLenConstraint' in e) {40195 e.value.value.push(asn1.create(40196 asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,40197 asn1.integerToDer(e.pathLenConstraint).getBytes()));40198 }40199 } else if(e.name === 'extKeyUsage') {40200 // extKeyUsage is a SEQUENCE of OIDs40201 e.value = asn1.create(40202 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);40203 var seq = e.value.value;40204 for(var key in e) {40205 if(e[key] !== true) {40206 continue;40207 }40208 // key is name in OID map40209 if(key in oids) {40210 seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,40211 false, asn1.oidToDer(oids[key]).getBytes()));40212 } else if(key.indexOf('.') !== -1) {40213 // assume key is an OID40214 seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,40215 false, asn1.oidToDer(key).getBytes()));40216 }40217 }40218 } else if(e.name === 'nsCertType') {40219 // nsCertType is a BIT STRING40220 // build flags40221 var unused = 0;40222 var b2 = 0x00;40223 if(e.client) {40224 b2 |= 0x80;40225 unused = 7;40226 }40227 if(e.server) {40228 b2 |= 0x40;40229 unused = 6;40230 }40231 if(e.email) {40232 b2 |= 0x20;40233 unused = 5;40234 }40235 if(e.objsign) {40236 b2 |= 0x10;40237 unused = 4;40238 }40239 if(e.reserved) {40240 b2 |= 0x08;40241 unused = 3;40242 }40243 if(e.sslCA) {40244 b2 |= 0x04;40245 unused = 2;40246 }40247 if(e.emailCA) {40248 b2 |= 0x02;40249 unused = 1;40250 }40251 if(e.objCA) {40252 b2 |= 0x01;40253 unused = 0;40254 }40255 // create bit string40256 var value = String.fromCharCode(unused);40257 if(b2 !== 0) {40258 value += String.fromCharCode(b2);40259 }40260 e.value = asn1.create(40261 asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);40262 } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {40263 // SYNTAX SEQUENCE40264 e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);40265 var altName;40266 for(var n = 0; n < e.altNames.length; ++n) {40267 altName = e.altNames[n];40268 var value = altName.value;40269 // handle IP40270 if(altName.type === 7 && altName.ip) {40271 value = forge.util.bytesFromIP(altName.ip);40272 if(value === null) {40273 var error = new Error(40274 'Extension "ip" value is not a valid IPv4 or IPv6 address.');40275 error.extension = e;40276 throw error;40277 }40278 } else if(altName.type === 8) {40279 // handle OID40280 if(altName.oid) {40281 value = asn1.oidToDer(asn1.oidToDer(altName.oid));40282 } else {40283 // deprecated ... convert value to OID40284 value = asn1.oidToDer(value);40285 }40286 }40287 e.value.value.push(asn1.create(40288 asn1.Class.CONTEXT_SPECIFIC, altName.type, false,40289 value));40290 }40291 } else if(e.name === 'nsComment' && options.cert) {40292 // sanity check value is ASCII (req'd) and not too big40293 if(!(/^[\x00-\x7F]*$/.test(e.comment)) ||40294 (e.comment.length < 1) || (e.comment.length > 128)) {40295 throw new Error('Invalid "nsComment" content.');40296 }40297 // IA5STRING opaque comment40298 e.value = asn1.create(40299 asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);40300 } else if(e.name === 'subjectKeyIdentifier' && options.cert) {40301 var ski = options.cert.generateSubjectKeyIdentifier();40302 e.subjectKeyIdentifier = ski.toHex();40303 // OCTETSTRING w/digest40304 e.value = asn1.create(40305 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());40306 } else if(e.name === 'authorityKeyIdentifier' && options.cert) {40307 // SYNTAX SEQUENCE40308 e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);40309 var seq = e.value.value;40310 if(e.keyIdentifier) {40311 var keyIdentifier = (e.keyIdentifier === true ?40312 options.cert.generateSubjectKeyIdentifier().getBytes() :40313 e.keyIdentifier);40314 seq.push(40315 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));40316 }40317 if(e.authorityCertIssuer) {40318 var authorityCertIssuer = [40319 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [40320 _dnToAsn1(e.authorityCertIssuer === true ?40321 options.cert.issuer : e.authorityCertIssuer)40322 ])40323 ];40324 seq.push(40325 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));40326 }40327 if(e.serialNumber) {40328 var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?40329 options.cert.serialNumber : e.serialNumber);40330 seq.push(40331 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));40332 }40333 } else if(e.name === 'cRLDistributionPoints') {40334 e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);40335 var seq = e.value.value;40336 // Create sub SEQUENCE of DistributionPointName40337 var subSeq = asn1.create(40338 asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);40339 // Create fullName CHOICE40340 var fullNameGeneralNames = asn1.create(40341 asn1.Class.CONTEXT_SPECIFIC, 0, true, []);40342 var altName;40343 for(var n = 0; n < e.altNames.length; ++n) {40344 altName = e.altNames[n];40345 var value = altName.value;40346 // handle IP40347 if(altName.type === 7 && altName.ip) {40348 value = forge.util.bytesFromIP(altName.ip);40349 if(value === null) {40350 var error = new Error(40351 'Extension "ip" value is not a valid IPv4 or IPv6 address.');40352 error.extension = e;40353 throw error;40354 }40355 } else if(altName.type === 8) {40356 // handle OID40357 if(altName.oid) {40358 value = asn1.oidToDer(asn1.oidToDer(altName.oid));40359 } else {40360 // deprecated ... convert value to OID40361 value = asn1.oidToDer(value);40362 }40363 }40364 fullNameGeneralNames.value.push(asn1.create(40365 asn1.Class.CONTEXT_SPECIFIC, altName.type, false,40366 value));40367 }40368 // Add to the parent SEQUENCE40369 subSeq.value.push(asn1.create(40370 asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));40371 seq.push(subSeq);40372 }40373 // ensure value has been defined by now40374 if(typeof e.value === 'undefined') {40375 var error = new Error('Extension value not specified.');40376 error.extension = e;40377 throw error;40378 }40379 return e;40380}40381/**40382 * Convert signature parameters object to ASN.140383 *40384 * @param {String} oid Signature algorithm OID40385 * @param params The signature parametrs object40386 * @return ASN.1 object representing signature parameters40387 */40388function _signatureParametersToAsn1(oid, params) {40389 switch(oid) {40390 case oids['RSASSA-PSS']:40391 var parts = [];40392 if(params.hash.algorithmOid !== undefined) {40393 parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [40394 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40395 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,40396 asn1.oidToDer(params.hash.algorithmOid).getBytes()),40397 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')40398 ])40399 ]));40400 }40401 if(params.mgf.algorithmOid !== undefined) {40402 parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [40403 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40404 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,40405 asn1.oidToDer(params.mgf.algorithmOid).getBytes()),40406 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40407 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,40408 asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),40409 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')40410 ])40411 ])40412 ]));40413 }40414 if(params.saltLength !== undefined) {40415 parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [40416 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,40417 asn1.integerToDer(params.saltLength).getBytes())40418 ]));40419 }40420 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);40421 default:40422 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');40423 }40424}40425/**40426 * Converts a certification request's attributes to an ASN.1 set of40427 * CRIAttributes.40428 *40429 * @param csr certification request.40430 *40431 * @return the ASN.1 set of CRIAttributes.40432 */40433function _CRIAttributesToAsn1(csr) {40434 // create an empty context-specific container40435 var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);40436 // no attributes, return empty container40437 if(csr.attributes.length === 0) {40438 return rval;40439 }40440 // each attribute has a sequence with a type and a set of values40441 var attrs = csr.attributes;40442 for(var i = 0; i < attrs.length; ++i) {40443 var attr = attrs[i];40444 var value = attr.value;40445 // reuse tag class for attribute value if available40446 var valueTagClass = asn1.Type.UTF8;40447 if('valueTagClass' in attr) {40448 valueTagClass = attr.valueTagClass;40449 }40450 if(valueTagClass === asn1.Type.UTF8) {40451 value = forge.util.encodeUtf8(value);40452 }40453 var valueConstructed = false;40454 if('valueConstructed' in attr) {40455 valueConstructed = attr.valueConstructed;40456 }40457 // FIXME: handle more encodings40458 // create a RelativeDistinguishedName set40459 // each value in the set is an AttributeTypeAndValue first40460 // containing the type (an OID) and second the value40461 var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40462 // AttributeType40463 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,40464 asn1.oidToDer(attr.type).getBytes()),40465 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [40466 // AttributeValue40467 asn1.create(40468 asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)40469 ])40470 ]);40471 rval.value.push(seq);40472 }40473 return rval;40474}40475var jan_1_1950 = new Date('1950-01-01T00:00:00Z');40476var jan_1_2050 = new Date('2050-01-01T00:00:00Z');40477/**40478 * Converts a Date object to ASN.140479 * Handles the different format before and after 1st January 205040480 *40481 * @param date date object.40482 *40483 * @return the ASN.1 object representing the date.40484 */40485function _dateToAsn1(date) {40486 if(date >= jan_1_1950 && date < jan_1_2050) {40487 return asn1.create(40488 asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,40489 asn1.dateToUtcTime(date));40490 } else {40491 return asn1.create(40492 asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,40493 asn1.dateToGeneralizedTime(date));40494 }40495}40496/**40497 * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.40498 *40499 * @param cert the certificate.40500 *40501 * @return the asn1 TBSCertificate.40502 */40503pki.getTBSCertificate = function(cert) {40504 // TBSCertificate40505 var notBefore = _dateToAsn1(cert.validity.notBefore);40506 var notAfter = _dateToAsn1(cert.validity.notAfter);40507 var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40508 // version40509 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [40510 // integer40511 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,40512 asn1.integerToDer(cert.version).getBytes())40513 ]),40514 // serialNumber40515 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,40516 forge.util.hexToBytes(cert.serialNumber)),40517 // signature40518 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40519 // algorithm40520 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,40521 asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),40522 // parameters40523 _signatureParametersToAsn1(40524 cert.siginfo.algorithmOid, cert.siginfo.parameters)40525 ]),40526 // issuer40527 _dnToAsn1(cert.issuer),40528 // validity40529 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40530 notBefore,40531 notAfter40532 ]),40533 // subject40534 _dnToAsn1(cert.subject),40535 // SubjectPublicKeyInfo40536 pki.publicKeyToAsn1(cert.publicKey)40537 ]);40538 if(cert.issuer.uniqueId) {40539 // issuerUniqueID (optional)40540 tbs.value.push(40541 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [40542 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,40543 // TODO: support arbitrary bit length ids40544 String.fromCharCode(0x00) +40545 cert.issuer.uniqueId40546 )40547 ])40548 );40549 }40550 if(cert.subject.uniqueId) {40551 // subjectUniqueID (optional)40552 tbs.value.push(40553 asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [40554 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,40555 // TODO: support arbitrary bit length ids40556 String.fromCharCode(0x00) +40557 cert.subject.uniqueId40558 )40559 ])40560 );40561 }40562 if(cert.extensions.length > 0) {40563 // extensions (optional)40564 tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));40565 }40566 return tbs;40567};40568/**40569 * Gets the ASN.1 CertificationRequestInfo part of a40570 * PKCS#10 CertificationRequest.40571 *40572 * @param csr the certification request.40573 *40574 * @return the asn1 CertificationRequestInfo.40575 */40576pki.getCertificationRequestInfo = function(csr) {40577 // CertificationRequestInfo40578 var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40579 // version40580 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,40581 asn1.integerToDer(csr.version).getBytes()),40582 // subject40583 _dnToAsn1(csr.subject),40584 // SubjectPublicKeyInfo40585 pki.publicKeyToAsn1(csr.publicKey),40586 // attributes40587 _CRIAttributesToAsn1(csr)40588 ]);40589 return cri;40590};40591/**40592 * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.40593 *40594 * @param dn the DistinguishedName.40595 *40596 * @return the asn1 representation of a DistinguishedName.40597 */40598pki.distinguishedNameToAsn1 = function(dn) {40599 return _dnToAsn1(dn);40600};40601/**40602 * Converts an X.509v3 RSA certificate to an ASN.1 object.40603 *40604 * @param cert the certificate.40605 *40606 * @return the asn1 representation of an X.509v3 RSA certificate.40607 */40608pki.certificateToAsn1 = function(cert) {40609 // prefer cached TBSCertificate over generating one40610 var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);40611 // Certificate40612 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40613 // TBSCertificate40614 tbsCertificate,40615 // AlgorithmIdentifier (signature algorithm)40616 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40617 // algorithm40618 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,40619 asn1.oidToDer(cert.signatureOid).getBytes()),40620 // parameters40621 _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)40622 ]),40623 // SignatureValue40624 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,40625 String.fromCharCode(0x00) + cert.signature)40626 ]);40627};40628/**40629 * Converts X.509v3 certificate extensions to ASN.1.40630 *40631 * @param exts the extensions to convert.40632 *40633 * @return the extensions in ASN.1 format.40634 */40635pki.certificateExtensionsToAsn1 = function(exts) {40636 // create top-level extension container40637 var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);40638 // create extension sequence (stores a sequence for each extension)40639 var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);40640 rval.value.push(seq);40641 for(var i = 0; i < exts.length; ++i) {40642 seq.value.push(pki.certificateExtensionToAsn1(exts[i]));40643 }40644 return rval;40645};40646/**40647 * Converts a single certificate extension to ASN.1.40648 *40649 * @param ext the extension to convert.40650 *40651 * @return the extension in ASN.1 format.40652 */40653pki.certificateExtensionToAsn1 = function(ext) {40654 // create a sequence for each extension40655 var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);40656 // extnID (OID)40657 extseq.value.push(asn1.create(40658 asn1.Class.UNIVERSAL, asn1.Type.OID, false,40659 asn1.oidToDer(ext.id).getBytes()));40660 // critical defaults to false40661 if(ext.critical) {40662 // critical BOOLEAN DEFAULT FALSE40663 extseq.value.push(asn1.create(40664 asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,40665 String.fromCharCode(0xFF)));40666 }40667 var value = ext.value;40668 if(typeof ext.value !== 'string') {40669 // value is asn.140670 value = asn1.toDer(value).getBytes();40671 }40672 // extnValue (OCTET STRING)40673 extseq.value.push(asn1.create(40674 asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));40675 return extseq;40676};40677/**40678 * Converts a PKCS#10 certification request to an ASN.1 object.40679 *40680 * @param csr the certification request.40681 *40682 * @return the asn1 representation of a certification request.40683 */40684pki.certificationRequestToAsn1 = function(csr) {40685 // prefer cached CertificationRequestInfo over generating one40686 var cri = csr.certificationRequestInfo ||40687 pki.getCertificationRequestInfo(csr);40688 // Certificate40689 return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40690 // CertificationRequestInfo40691 cri,40692 // AlgorithmIdentifier (signature algorithm)40693 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [40694 // algorithm40695 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,40696 asn1.oidToDer(csr.signatureOid).getBytes()),40697 // parameters40698 _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)40699 ]),40700 // signature40701 asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,40702 String.fromCharCode(0x00) + csr.signature)40703 ]);40704};40705/**40706 * Creates a CA store.40707 *40708 * @param certs an optional array of certificate objects or PEM-formatted40709 * certificate strings to add to the CA store.40710 *40711 * @return the CA store.40712 */40713pki.createCaStore = function(certs) {40714 // create CA store40715 var caStore = {40716 // stored certificates40717 certs: {}40718 };40719 /**40720 * Gets the certificate that issued the passed certificate or its40721 * 'parent'.40722 *40723 * @param cert the certificate to get the parent for.40724 *40725 * @return the parent certificate or null if none was found.40726 */40727 caStore.getIssuer = function(cert) {40728 var rval = getBySubject(cert.issuer);40729 // see if there are multiple matches40730 /*if(forge.util.isArray(rval)) {40731 // TODO: resolve multiple matches by checking40732 // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.40733 // FIXME: or alternatively do authority key mapping40734 // if possible (X.509v1 certs can't work?)40735 throw new Error('Resolving multiple issuer matches not implemented yet.');40736 }*/40737 return rval;40738 };40739 /**40740 * Adds a trusted certificate to the store.40741 *40742 * @param cert the certificate to add as a trusted certificate (either a40743 * pki.certificate object or a PEM-formatted certificate).40744 */40745 caStore.addCertificate = function(cert) {40746 // convert from pem if necessary40747 if(typeof cert === 'string') {40748 cert = forge.pki.certificateFromPem(cert);40749 }40750 ensureSubjectHasHash(cert.subject);40751 if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store40752 if(cert.subject.hash in caStore.certs) {40753 // subject hash already exists, append to array40754 var tmp = caStore.certs[cert.subject.hash];40755 if(!forge.util.isArray(tmp)) {40756 tmp = [tmp];40757 }40758 tmp.push(cert);40759 caStore.certs[cert.subject.hash] = tmp;40760 } else {40761 caStore.certs[cert.subject.hash] = cert;40762 }40763 }40764 };40765 /**40766 * Checks to see if the given certificate is in the store.40767 *40768 * @param cert the certificate to check (either a pki.certificate or a40769 * PEM-formatted certificate).40770 *40771 * @return true if the certificate is in the store, false if not.40772 */40773 caStore.hasCertificate = function(cert) {40774 // convert from pem if necessary40775 if(typeof cert === 'string') {40776 cert = forge.pki.certificateFromPem(cert);40777 }40778 var match = getBySubject(cert.subject);40779 if(!match) {40780 return false;40781 }40782 if(!forge.util.isArray(match)) {40783 match = [match];40784 }40785 // compare DER-encoding of certificates40786 var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();40787 for(var i = 0; i < match.length; ++i) {40788 var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();40789 if(der1 === der2) {40790 return true;40791 }40792 }40793 return false;40794 };40795 /**40796 * Lists all of the certificates kept in the store.40797 *40798 * @return an array of all of the pki.certificate objects in the store.40799 */40800 caStore.listAllCertificates = function() {40801 var certList = [];40802 for(var hash in caStore.certs) {40803 if(caStore.certs.hasOwnProperty(hash)) {40804 var value = caStore.certs[hash];40805 if(!forge.util.isArray(value)) {40806 certList.push(value);40807 } else {40808 for(var i = 0; i < value.length; ++i) {40809 certList.push(value[i]);40810 }40811 }40812 }40813 }40814 return certList;40815 };40816 /**40817 * Removes a certificate from the store.40818 *40819 * @param cert the certificate to remove (either a pki.certificate or a40820 * PEM-formatted certificate).40821 *40822 * @return the certificate that was removed or null if the certificate40823 * wasn't in store.40824 */40825 caStore.removeCertificate = function(cert) {40826 var result;40827 // convert from pem if necessary40828 if(typeof cert === 'string') {40829 cert = forge.pki.certificateFromPem(cert);40830 }40831 ensureSubjectHasHash(cert.subject);40832 if(!caStore.hasCertificate(cert)) {40833 return null;40834 }40835 var match = getBySubject(cert.subject);40836 if(!forge.util.isArray(match)) {40837 result = caStore.certs[cert.subject.hash];40838 delete caStore.certs[cert.subject.hash];40839 return result;40840 }40841 // compare DER-encoding of certificates40842 var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();40843 for(var i = 0; i < match.length; ++i) {40844 var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();40845 if(der1 === der2) {40846 result = match[i];40847 match.splice(i, 1);40848 }40849 }40850 if(match.length === 0) {40851 delete caStore.certs[cert.subject.hash];40852 }40853 return result;40854 };40855 function getBySubject(subject) {40856 ensureSubjectHasHash(subject);40857 return caStore.certs[subject.hash] || null;40858 }40859 function ensureSubjectHasHash(subject) {40860 // produce subject hash if it doesn't exist40861 if(!subject.hash) {40862 var md = forge.md.sha1.create();40863 subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);40864 subject.hash = md.digest().toHex();40865 }40866 }40867 // auto-add passed in certs40868 if(certs) {40869 // parse PEM-formatted certificates as necessary40870 for(var i = 0; i < certs.length; ++i) {40871 var cert = certs[i];40872 caStore.addCertificate(cert);40873 }40874 }40875 return caStore;40876};40877/**40878 * Certificate verification errors, based on TLS.40879 */40880pki.certificateError = {40881 bad_certificate: 'forge.pki.BadCertificate',40882 unsupported_certificate: 'forge.pki.UnsupportedCertificate',40883 certificate_revoked: 'forge.pki.CertificateRevoked',40884 certificate_expired: 'forge.pki.CertificateExpired',40885 certificate_unknown: 'forge.pki.CertificateUnknown',40886 unknown_ca: 'forge.pki.UnknownCertificateAuthority'40887};40888/**40889 * Verifies a certificate chain against the given Certificate Authority store40890 * with an optional custom verify callback.40891 *40892 * @param caStore a certificate store to verify against.40893 * @param chain the certificate chain to verify, with the root or highest40894 * authority at the end (an array of certificates).40895 * @param options a callback to be called for every certificate in the chain or40896 * an object with:40897 * verify a callback to be called for every certificate in the40898 * chain40899 * validityCheckDate the date against which the certificate40900 * validity period should be checked. Pass null to not check40901 * the validity period. By default, the current date is used.40902 *40903 * The verify callback has the following signature:40904 *40905 * verified - Set to true if certificate was verified, otherwise the40906 * pki.certificateError for why the certificate failed.40907 * depth - The current index in the chain, where 0 is the end point's cert.40908 * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous40909 * end point.40910 *40911 * The function returns true on success and on failure either the appropriate40912 * pki.certificateError or an object with 'error' set to the appropriate40913 * pki.certificateError and 'message' set to a custom error message.40914 *40915 * @return true if successful, error thrown if not.40916 */40917pki.verifyCertificateChain = function(caStore, chain, options) {40918 /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate40919 Section 6: Certification Path Validation40920 See inline parentheticals related to this particular implementation.40921 The primary goal of path validation is to verify the binding between40922 a subject distinguished name or a subject alternative name and subject40923 public key, as represented in the end entity certificate, based on the40924 public key of the trust anchor. This requires obtaining a sequence of40925 certificates that support that binding. That sequence should be provided40926 in the passed 'chain'. The trust anchor should be in the given CA40927 store. The 'end entity' certificate is the certificate provided by the40928 end point (typically a server) and is the first in the chain.40929 To meet this goal, the path validation process verifies, among other40930 things, that a prospective certification path (a sequence of n40931 certificates or a 'chain') satisfies the following conditions:40932 (a) for all x in {1, ..., n-1}, the subject of certificate x is40933 the issuer of certificate x+1;40934 (b) certificate 1 is issued by the trust anchor;40935 (c) certificate n is the certificate to be validated; and40936 (d) for all x in {1, ..., n}, the certificate was valid at the40937 time in question.40938 Note that here 'n' is index 0 in the chain and 1 is the last certificate40939 in the chain and it must be signed by a certificate in the connection's40940 CA store.40941 The path validation process also determines the set of certificate40942 policies that are valid for this path, based on the certificate policies40943 extension, policy mapping extension, policy constraints extension, and40944 inhibit any-policy extension.40945 Note: Policy mapping extension not supported (Not Required).40946 Note: If the certificate has an unsupported critical extension, then it40947 must be rejected.40948 Note: A certificate is self-issued if the DNs that appear in the subject40949 and issuer fields are identical and are not empty.40950 The path validation algorithm assumes the following seven inputs are40951 provided to the path processing logic. What this specific implementation40952 will use is provided parenthetically:40953 (a) a prospective certification path of length n (the 'chain')40954 (b) the current date/time: ('now').40955 (c) user-initial-policy-set: A set of certificate policy identifiers40956 naming the policies that are acceptable to the certificate user.40957 The user-initial-policy-set contains the special value any-policy40958 if the user is not concerned about certificate policy40959 (Not implemented. Any policy is accepted).40960 (d) trust anchor information, describing a CA that serves as a trust40961 anchor for the certification path. The trust anchor information40962 includes:40963 (1) the trusted issuer name,40964 (2) the trusted public key algorithm,40965 (3) the trusted public key, and40966 (4) optionally, the trusted public key parameters associated40967 with the public key.40968 (Trust anchors are provided via certificates in the CA store).40969 The trust anchor information may be provided to the path processing40970 procedure in the form of a self-signed certificate. The trusted anchor40971 information is trusted because it was delivered to the path processing40972 procedure by some trustworthy out-of-band procedure. If the trusted40973 public key algorithm requires parameters, then the parameters are40974 provided along with the trusted public key (No parameters used in this40975 implementation).40976 (e) initial-policy-mapping-inhibit, which indicates if policy mapping is40977 allowed in the certification path.40978 (Not implemented, no policy checking)40979 (f) initial-explicit-policy, which indicates if the path must be valid40980 for at least one of the certificate policies in the user-initial-40981 policy-set.40982 (Not implemented, no policy checking)40983 (g) initial-any-policy-inhibit, which indicates whether the40984 anyPolicy OID should be processed if it is included in a40985 certificate.40986 (Not implemented, so any policy is valid provided that it is40987 not marked as critical) */40988 /* Basic Path Processing:40989 For each certificate in the 'chain', the following is checked:40990 1. The certificate validity period includes the current time.40991 2. The certificate was signed by its parent (where the parent is either40992 the next in the chain or from the CA store). Allow processing to40993 continue to the next step if no parent is found but the certificate is40994 in the CA store.40995 3. TODO: The certificate has not been revoked.40996 4. The certificate issuer name matches the parent's subject name.40997 5. TODO: If the certificate is self-issued and not the final certificate40998 in the chain, skip this step, otherwise verify that the subject name40999 is within one of the permitted subtrees of X.500 distinguished names41000 and that each of the alternative names in the subjectAltName extension41001 (critical or non-critical) is within one of the permitted subtrees for41002 that name type.41003 6. TODO: If the certificate is self-issued and not the final certificate41004 in the chain, skip this step, otherwise verify that the subject name41005 is not within one of the excluded subtrees for X.500 distinguished41006 names and none of the subjectAltName extension names are excluded for41007 that name type.41008 7. The other steps in the algorithm for basic path processing involve41009 handling the policy extension which is not presently supported in this41010 implementation. Instead, if a critical policy extension is found, the41011 certificate is rejected as not supported.41012 8. If the certificate is not the first or if its the only certificate in41013 the chain (having no parent from the CA store or is self-signed) and it41014 has a critical key usage extension, verify that the keyCertSign bit is41015 set. If the key usage extension exists, verify that the basic41016 constraints extension exists. If the basic constraints extension exists,41017 verify that the cA flag is set. If pathLenConstraint is set, ensure that41018 the number of certificates that precede in the chain (come earlier41019 in the chain as implemented below), excluding the very first in the41020 chain (typically the end-entity one), isn't greater than the41021 pathLenConstraint. This constraint limits the number of intermediate41022 CAs that may appear below a CA before only end-entity certificates41023 may be issued. */41024 // if a verify callback is passed as the third parameter, package it within41025 // the options object. This is to support a legacy function signature that41026 // expected the verify callback as the third parameter.41027 if(typeof options === 'function') {41028 options = {verify: options};41029 }41030 options = options || {};41031 // copy cert chain references to another array to protect against changes41032 // in verify callback41033 chain = chain.slice(0);41034 var certs = chain.slice(0);41035 var validityCheckDate = options.validityCheckDate;41036 // if no validityCheckDate is specified, default to the current date. Make41037 // sure to maintain the value null because it indicates that the validity41038 // period should not be checked.41039 if(typeof validityCheckDate === 'undefined') {41040 validityCheckDate = new Date();41041 }41042 // verify each cert in the chain using its parent, where the parent41043 // is either the next in the chain or from the CA store41044 var first = true;41045 var error = null;41046 var depth = 0;41047 do {41048 var cert = chain.shift();41049 var parent = null;41050 var selfSigned = false;41051 if(validityCheckDate) {41052 // 1. check valid time41053 if(validityCheckDate < cert.validity.notBefore ||41054 validityCheckDate > cert.validity.notAfter) {41055 error = {41056 message: 'Certificate is not valid yet or has expired.',41057 error: pki.certificateError.certificate_expired,41058 notBefore: cert.validity.notBefore,41059 notAfter: cert.validity.notAfter,41060 // TODO: we might want to reconsider renaming 'now' to41061 // 'validityCheckDate' should this API be changed in the future.41062 now: validityCheckDate41063 };41064 }41065 }41066 // 2. verify with parent from chain or CA store41067 if(error === null) {41068 parent = chain[0] || caStore.getIssuer(cert);41069 if(parent === null) {41070 // check for self-signed cert41071 if(cert.isIssuer(cert)) {41072 selfSigned = true;41073 parent = cert;41074 }41075 }41076 if(parent) {41077 // FIXME: current CA store implementation might have multiple41078 // certificates where the issuer can't be determined from the41079 // certificate (happens rarely with, eg: old certificates) so normalize41080 // by always putting parents into an array41081 // TODO: there's may be an extreme degenerate case currently uncovered41082 // where an old intermediate certificate seems to have a matching parent41083 // but none of the parents actually verify ... but the intermediate41084 // is in the CA and it should pass this check; needs investigation41085 var parents = parent;41086 if(!forge.util.isArray(parents)) {41087 parents = [parents];41088 }41089 // try to verify with each possible parent (typically only one)41090 var verified = false;41091 while(!verified && parents.length > 0) {41092 parent = parents.shift();41093 try {41094 verified = parent.verify(cert);41095 } catch(ex) {41096 // failure to verify, don't care why, try next one41097 }41098 }41099 if(!verified) {41100 error = {41101 message: 'Certificate signature is invalid.',41102 error: pki.certificateError.bad_certificate41103 };41104 }41105 }41106 if(error === null && (!parent || selfSigned) &&41107 !caStore.hasCertificate(cert)) {41108 // no parent issuer and certificate itself is not trusted41109 error = {41110 message: 'Certificate is not trusted.',41111 error: pki.certificateError.unknown_ca41112 };41113 }41114 }41115 // TODO: 3. check revoked41116 // 4. check for matching issuer/subject41117 if(error === null && parent && !cert.isIssuer(parent)) {41118 // parent is not issuer41119 error = {41120 message: 'Certificate issuer is invalid.',41121 error: pki.certificateError.bad_certificate41122 };41123 }41124 // 5. TODO: check names with permitted names tree41125 // 6. TODO: check names against excluded names tree41126 // 7. check for unsupported critical extensions41127 if(error === null) {41128 // supported extensions41129 var se = {41130 keyUsage: true,41131 basicConstraints: true41132 };41133 for(var i = 0; error === null && i < cert.extensions.length; ++i) {41134 var ext = cert.extensions[i];41135 if(ext.critical && !(ext.name in se)) {41136 error = {41137 message:41138 'Certificate has an unsupported critical extension.',41139 error: pki.certificateError.unsupported_certificate41140 };41141 }41142 }41143 }41144 // 8. check for CA if cert is not first or is the only certificate41145 // remaining in chain with no parent or is self-signed41146 if(error === null &&41147 (!first || (chain.length === 0 && (!parent || selfSigned)))) {41148 // first check keyUsage extension and then basic constraints41149 var bcExt = cert.getExtension('basicConstraints');41150 var keyUsageExt = cert.getExtension('keyUsage');41151 if(keyUsageExt !== null) {41152 // keyCertSign must be true and there must be a basic41153 // constraints extension41154 if(!keyUsageExt.keyCertSign || bcExt === null) {41155 // bad certificate41156 error = {41157 message:41158 'Certificate keyUsage or basicConstraints conflict ' +41159 'or indicate that the certificate is not a CA. ' +41160 'If the certificate is the only one in the chain or ' +41161 'isn\'t the first then the certificate must be a ' +41162 'valid CA.',41163 error: pki.certificateError.bad_certificate41164 };41165 }41166 }41167 // basic constraints cA flag must be set41168 if(error === null && bcExt !== null && !bcExt.cA) {41169 // bad certificate41170 error = {41171 message:41172 'Certificate basicConstraints indicates the certificate ' +41173 'is not a CA.',41174 error: pki.certificateError.bad_certificate41175 };41176 }41177 // if error is not null and keyUsage is available, then we know it41178 // has keyCertSign and there is a basic constraints extension too,41179 // which means we can check pathLenConstraint (if it exists)41180 if(error === null && keyUsageExt !== null &&41181 'pathLenConstraint' in bcExt) {41182 // pathLen is the maximum # of intermediate CA certs that can be41183 // found between the current certificate and the end-entity (depth 0)41184 // certificate; this number does not include the end-entity (depth 0,41185 // last in the chain) even if it happens to be a CA certificate itself41186 var pathLen = depth - 1;41187 if(pathLen > bcExt.pathLenConstraint) {41188 // pathLenConstraint violated, bad certificate41189 error = {41190 message:41191 'Certificate basicConstraints pathLenConstraint violated.',41192 error: pki.certificateError.bad_certificate41193 };41194 }41195 }41196 }41197 // call application callback41198 var vfd = (error === null) ? true : error.error;41199 var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;41200 if(ret === true) {41201 // clear any set error41202 error = null;41203 } else {41204 // if passed basic tests, set default message and alert41205 if(vfd === true) {41206 error = {41207 message: 'The application rejected the certificate.',41208 error: pki.certificateError.bad_certificate41209 };41210 }41211 // check for custom error info41212 if(ret || ret === 0) {41213 // set custom message and error41214 if(typeof ret === 'object' && !forge.util.isArray(ret)) {41215 if(ret.message) {41216 error.message = ret.message;41217 }41218 if(ret.error) {41219 error.error = ret.error;41220 }41221 } else if(typeof ret === 'string') {41222 // set custom error41223 error.error = ret;41224 }41225 }41226 // throw error41227 throw error;41228 }41229 // no longer first cert in chain41230 first = false;41231 ++depth;41232 } while(chain.length > 0);41233 return true;41234};41235/***/ }),41236/***/ 1867:41237/***/ ((module, exports, __nccwpck_require__) => {41238/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */41239/* eslint-disable node/no-deprecated-api */41240var buffer = __nccwpck_require__(4300)41241var Buffer = buffer.Buffer41242// alternative to using Object.keys for old browsers41243function copyProps (src, dst) {41244 for (var key in src) {41245 dst[key] = src[key]41246 }41247}41248if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {41249 module.exports = buffer41250} else {41251 // Copy properties from require('buffer')41252 copyProps(buffer, exports)41253 exports.Buffer = SafeBuffer41254}41255function SafeBuffer (arg, encodingOrOffset, length) {41256 return Buffer(arg, encodingOrOffset, length)41257}41258SafeBuffer.prototype = Object.create(Buffer.prototype)41259// Copy static methods from Buffer41260copyProps(Buffer, SafeBuffer)41261SafeBuffer.from = function (arg, encodingOrOffset, length) {41262 if (typeof arg === 'number') {41263 throw new TypeError('Argument must not be a number')41264 }41265 return Buffer(arg, encodingOrOffset, length)41266}41267SafeBuffer.alloc = function (size, fill, encoding) {41268 if (typeof size !== 'number') {41269 throw new TypeError('Argument must be a number')41270 }41271 var buf = Buffer(size)41272 if (fill !== undefined) {41273 if (typeof encoding === 'string') {41274 buf.fill(fill, encoding)41275 } else {41276 buf.fill(fill)41277 }41278 } else {41279 buf.fill(0)41280 }41281 return buf41282}41283SafeBuffer.allocUnsafe = function (size) {41284 if (typeof size !== 'number') {41285 throw new TypeError('Argument must be a number')41286 }41287 return Buffer(size)41288}41289SafeBuffer.allocUnsafeSlow = function (size) {41290 if (typeof size !== 'number') {41291 throw new TypeError('Argument must be a number')41292 }41293 return buffer.SlowBuffer(size)41294}41295/***/ }),41296/***/ 4256:41297/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {41298"use strict";41299var punycode = __nccwpck_require__(5477);41300var mappingTable = __nccwpck_require__(2020);41301var PROCESSING_OPTIONS = {41302 TRANSITIONAL: 0,41303 NONTRANSITIONAL: 141304};41305function normalize(str) { // fix bug in v841306 return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000');41307}41308function findStatus(val) {41309 var start = 0;41310 var end = mappingTable.length - 1;41311 while (start <= end) {41312 var mid = Math.floor((start + end) / 2);41313 var target = mappingTable[mid];41314 if (target[0][0] <= val && target[0][1] >= val) {41315 return target;41316 } else if (target[0][0] > val) {41317 end = mid - 1;41318 } else {41319 start = mid + 1;41320 }41321 }41322 return null;41323}41324var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;41325function countSymbols(string) {41326 return string41327 // replace every surrogate pair with a BMP symbol41328 .replace(regexAstralSymbols, '_')41329 // then get the length41330 .length;41331}41332function mapChars(domain_name, useSTD3, processing_option) {41333 var hasError = false;41334 var processed = "";41335 var len = countSymbols(domain_name);41336 for (var i = 0; i < len; ++i) {41337 var codePoint = domain_name.codePointAt(i);41338 var status = findStatus(codePoint);41339 switch (status[1]) {41340 case "disallowed":41341 hasError = true;41342 processed += String.fromCodePoint(codePoint);41343 break;41344 case "ignored":41345 break;41346 case "mapped":41347 processed += String.fromCodePoint.apply(String, status[2]);41348 break;41349 case "deviation":41350 if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) {41351 processed += String.fromCodePoint.apply(String, status[2]);41352 } else {41353 processed += String.fromCodePoint(codePoint);41354 }41355 break;41356 case "valid":41357 processed += String.fromCodePoint(codePoint);41358 break;41359 case "disallowed_STD3_mapped":41360 if (useSTD3) {41361 hasError = true;41362 processed += String.fromCodePoint(codePoint);41363 } else {41364 processed += String.fromCodePoint.apply(String, status[2]);41365 }41366 break;41367 case "disallowed_STD3_valid":41368 if (useSTD3) {41369 hasError = true;41370 }41371 processed += String.fromCodePoint(codePoint);41372 break;41373 }41374 }41375 return {41376 string: processed,41377 error: hasError41378 };41379}41380var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/;41381function validateLabel(label, processing_option) {41382 if (label.substr(0, 4) === "xn--") {41383 label = punycode.toUnicode(label);41384 processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;41385 }41386 var error = false;41387 if (normalize(label) !== label ||41388 (label[3] === "-" && label[4] === "-") ||41389 label[0] === "-" || label[label.length - 1] === "-" ||41390 label.indexOf(".") !== -1 ||41391 label.search(combiningMarksRegex) === 0) {41392 error = true;41393 }41394 var len = countSymbols(label);41395 for (var i = 0; i < len; ++i) {41396 var status = findStatus(label.codePointAt(i));41397 if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") ||41398 (processing === PROCESSING_OPTIONS.NONTRANSITIONAL &&41399 status[1] !== "valid" && status[1] !== "deviation")) {41400 error = true;41401 break;41402 }41403 }41404 return {41405 label: label,41406 error: error41407 };41408}41409function processing(domain_name, useSTD3, processing_option) {41410 var result = mapChars(domain_name, useSTD3, processing_option);41411 result.string = normalize(result.string);41412 var labels = result.string.split(".");41413 for (var i = 0; i < labels.length; ++i) {41414 try {41415 var validation = validateLabel(labels[i]);41416 labels[i] = validation.label;41417 result.error = result.error || validation.error;41418 } catch(e) {41419 result.error = true;41420 }41421 }41422 return {41423 string: labels.join("."),41424 error: result.error41425 };41426}41427module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) {41428 var result = processing(domain_name, useSTD3, processing_option);41429 var labels = result.string.split(".");41430 labels = labels.map(function(l) {41431 try {41432 return punycode.toASCII(l);41433 } catch(e) {41434 result.error = true;41435 return l;41436 }41437 });41438 if (verifyDnsLength) {41439 var total = labels.slice(0, labels.length - 1).join(".").length;41440 if (total.length > 253 || total.length === 0) {41441 result.error = true;41442 }41443 for (var i=0; i < labels.length; ++i) {41444 if (labels.length > 63 || labels.length === 0) {41445 result.error = true;41446 break;41447 }41448 }41449 }41450 if (result.error) return null;41451 return labels.join(".");41452};41453module.exports.toUnicode = function(domain_name, useSTD3) {41454 var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL);41455 return {41456 domain: result.string,41457 error: result.error41458 };41459};41460module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS;41461/***/ }),41462/***/ 4294:41463/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {41464module.exports = __nccwpck_require__(4219);41465/***/ }),41466/***/ 4219:41467/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {41468"use strict";41469var net = __nccwpck_require__(1808);41470var tls = __nccwpck_require__(4404);41471var http = __nccwpck_require__(3685);41472var https = __nccwpck_require__(5687);41473var events = __nccwpck_require__(2361);41474var assert = __nccwpck_require__(9491);41475var util = __nccwpck_require__(3837);41476exports.httpOverHttp = httpOverHttp;41477exports.httpsOverHttp = httpsOverHttp;41478exports.httpOverHttps = httpOverHttps;41479exports.httpsOverHttps = httpsOverHttps;41480function httpOverHttp(options) {41481 var agent = new TunnelingAgent(options);41482 agent.request = http.request;41483 return agent;41484}41485function httpsOverHttp(options) {41486 var agent = new TunnelingAgent(options);41487 agent.request = http.request;41488 agent.createSocket = createSecureSocket;41489 agent.defaultPort = 443;41490 return agent;41491}41492function httpOverHttps(options) {41493 var agent = new TunnelingAgent(options);41494 agent.request = https.request;41495 return agent;41496}41497function httpsOverHttps(options) {41498 var agent = new TunnelingAgent(options);41499 agent.request = https.request;41500 agent.createSocket = createSecureSocket;41501 agent.defaultPort = 443;41502 return agent;41503}41504function TunnelingAgent(options) {41505 var self = this;41506 self.options = options || {};41507 self.proxyOptions = self.options.proxy || {};41508 self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;41509 self.requests = [];41510 self.sockets = [];41511 self.on('free', function onFree(socket, host, port, localAddress) {41512 var options = toOptions(host, port, localAddress);41513 for (var i = 0, len = self.requests.length; i < len; ++i) {41514 var pending = self.requests[i];41515 if (pending.host === options.host && pending.port === options.port) {41516 // Detect the request to connect same origin server,41517 // reuse the connection.41518 self.requests.splice(i, 1);41519 pending.request.onSocket(socket);41520 return;41521 }41522 }41523 socket.destroy();41524 self.removeSocket(socket);41525 });41526}41527util.inherits(TunnelingAgent, events.EventEmitter);41528TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {41529 var self = this;41530 var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));41531 if (self.sockets.length >= this.maxSockets) {41532 // We are over limit so we'll add it to the queue.41533 self.requests.push(options);41534 return;41535 }41536 // If we are under maxSockets create a new one.41537 self.createSocket(options, function(socket) {41538 socket.on('free', onFree);41539 socket.on('close', onCloseOrRemove);41540 socket.on('agentRemove', onCloseOrRemove);41541 req.onSocket(socket);41542 function onFree() {41543 self.emit('free', socket, options);41544 }41545 function onCloseOrRemove(err) {41546 self.removeSocket(socket);41547 socket.removeListener('free', onFree);41548 socket.removeListener('close', onCloseOrRemove);41549 socket.removeListener('agentRemove', onCloseOrRemove);41550 }41551 });41552};41553TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {41554 var self = this;41555 var placeholder = {};41556 self.sockets.push(placeholder);41557 var connectOptions = mergeOptions({}, self.proxyOptions, {41558 method: 'CONNECT',41559 path: options.host + ':' + options.port,41560 agent: false,41561 headers: {41562 host: options.host + ':' + options.port41563 }41564 });41565 if (options.localAddress) {41566 connectOptions.localAddress = options.localAddress;41567 }41568 if (connectOptions.proxyAuth) {41569 connectOptions.headers = connectOptions.headers || {};41570 connectOptions.headers['Proxy-Authorization'] = 'Basic ' +41571 new Buffer(connectOptions.proxyAuth).toString('base64');41572 }41573 debug('making CONNECT request');41574 var connectReq = self.request(connectOptions);41575 connectReq.useChunkedEncodingByDefault = false; // for v0.641576 connectReq.once('response', onResponse); // for v0.641577 connectReq.once('upgrade', onUpgrade); // for v0.641578 connectReq.once('connect', onConnect); // for v0.7 or later41579 connectReq.once('error', onError);41580 connectReq.end();41581 function onResponse(res) {41582 // Very hacky. This is necessary to avoid http-parser leaks.41583 res.upgrade = true;41584 }41585 function onUpgrade(res, socket, head) {41586 // Hacky.41587 process.nextTick(function() {41588 onConnect(res, socket, head);41589 });41590 }41591 function onConnect(res, socket, head) {41592 connectReq.removeAllListeners();41593 socket.removeAllListeners();41594 if (res.statusCode !== 200) {41595 debug('tunneling socket could not be established, statusCode=%d',41596 res.statusCode);41597 socket.destroy();41598 var error = new Error('tunneling socket could not be established, ' +41599 'statusCode=' + res.statusCode);41600 error.code = 'ECONNRESET';41601 options.request.emit('error', error);41602 self.removeSocket(placeholder);41603 return;41604 }41605 if (head.length > 0) {41606 debug('got illegal response body from proxy');41607 socket.destroy();41608 var error = new Error('got illegal response body from proxy');41609 error.code = 'ECONNRESET';41610 options.request.emit('error', error);41611 self.removeSocket(placeholder);41612 return;41613 }41614 debug('tunneling connection has established');41615 self.sockets[self.sockets.indexOf(placeholder)] = socket;41616 return cb(socket);41617 }41618 function onError(cause) {41619 connectReq.removeAllListeners();41620 debug('tunneling socket could not be established, cause=%s\n',41621 cause.message, cause.stack);41622 var error = new Error('tunneling socket could not be established, ' +41623 'cause=' + cause.message);41624 error.code = 'ECONNRESET';41625 options.request.emit('error', error);41626 self.removeSocket(placeholder);41627 }41628};41629TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {41630 var pos = this.sockets.indexOf(socket)41631 if (pos === -1) {41632 return;41633 }41634 this.sockets.splice(pos, 1);41635 var pending = this.requests.shift();41636 if (pending) {41637 // If we have pending requests and a socket gets closed a new one41638 // needs to be created to take over in the pool for the one that closed.41639 this.createSocket(pending, function(socket) {41640 pending.request.onSocket(socket);41641 });41642 }41643};41644function createSecureSocket(options, cb) {41645 var self = this;41646 TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {41647 var hostHeader = options.request.getHeader('host');41648 var tlsOptions = mergeOptions({}, self.options, {41649 socket: socket,41650 servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host41651 });41652 // 0 is dummy port for v0.641653 var secureSocket = tls.connect(0, tlsOptions);41654 self.sockets[self.sockets.indexOf(socket)] = secureSocket;41655 cb(secureSocket);41656 });41657}41658function toOptions(host, port, localAddress) {41659 if (typeof host === 'string') { // since v0.1041660 return {41661 host: host,41662 port: port,41663 localAddress: localAddress41664 };41665 }41666 return host; // for v0.11 or later41667}41668function mergeOptions(target) {41669 for (var i = 1, len = arguments.length; i < len; ++i) {41670 var overrides = arguments[i];41671 if (typeof overrides === 'object') {41672 var keys = Object.keys(overrides);41673 for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {41674 var k = keys[j];41675 if (overrides[k] !== undefined) {41676 target[k] = overrides[k];41677 }41678 }41679 }41680 }41681 return target;41682}41683var debug;41684if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {41685 debug = function() {41686 var args = Array.prototype.slice.call(arguments);41687 if (typeof args[0] === 'string') {41688 args[0] = 'TUNNEL: ' + args[0];41689 } else {41690 args.unshift('TUNNEL:');41691 }41692 console.error.apply(console, args);41693 }41694} else {41695 debug = function() {};41696}41697exports.debug = debug; // for test41698/***/ }),41699/***/ 5840:41700/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {41701"use strict";41702Object.defineProperty(exports, "__esModule", ({41703 value: true41704}));41705Object.defineProperty(exports, "v1", ({41706 enumerable: true,41707 get: function () {41708 return _v.default;41709 }41710}));41711Object.defineProperty(exports, "v3", ({41712 enumerable: true,41713 get: function () {41714 return _v2.default;41715 }41716}));41717Object.defineProperty(exports, "v4", ({41718 enumerable: true,41719 get: function () {41720 return _v3.default;41721 }41722}));41723Object.defineProperty(exports, "v5", ({41724 enumerable: true,41725 get: function () {41726 return _v4.default;41727 }41728}));41729Object.defineProperty(exports, "NIL", ({41730 enumerable: true,41731 get: function () {41732 return _nil.default;41733 }41734}));41735Object.defineProperty(exports, "version", ({41736 enumerable: true,41737 get: function () {41738 return _version.default;41739 }41740}));41741Object.defineProperty(exports, "validate", ({41742 enumerable: true,41743 get: function () {41744 return _validate.default;41745 }41746}));41747Object.defineProperty(exports, "stringify", ({41748 enumerable: true,41749 get: function () {41750 return _stringify.default;41751 }41752}));41753Object.defineProperty(exports, "parse", ({41754 enumerable: true,41755 get: function () {41756 return _parse.default;41757 }41758}));41759var _v = _interopRequireDefault(__nccwpck_require__(8628));41760var _v2 = _interopRequireDefault(__nccwpck_require__(6409));41761var _v3 = _interopRequireDefault(__nccwpck_require__(5122));41762var _v4 = _interopRequireDefault(__nccwpck_require__(9120));41763var _nil = _interopRequireDefault(__nccwpck_require__(5332));41764var _version = _interopRequireDefault(__nccwpck_require__(1595));41765var _validate = _interopRequireDefault(__nccwpck_require__(6900));41766var _stringify = _interopRequireDefault(__nccwpck_require__(8950));41767var _parse = _interopRequireDefault(__nccwpck_require__(2746));41768function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }41769/***/ }),41770/***/ 4569:41771/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {41772"use strict";41773Object.defineProperty(exports, "__esModule", ({41774 value: true41775}));41776exports["default"] = void 0;41777var _crypto = _interopRequireDefault(__nccwpck_require__(6113));41778function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }41779function md5(bytes) {41780 if (Array.isArray(bytes)) {41781 bytes = Buffer.from(bytes);41782 } else if (typeof bytes === 'string') {41783 bytes = Buffer.from(bytes, 'utf8');41784 }41785 return _crypto.default.createHash('md5').update(bytes).digest();41786}41787var _default = md5;41788exports["default"] = _default;41789/***/ }),41790/***/ 5332:41791/***/ ((__unused_webpack_module, exports) => {41792"use strict";41793Object.defineProperty(exports, "__esModule", ({41794 value: true41795}));41796exports["default"] = void 0;41797var _default = '00000000-0000-0000-0000-000000000000';41798exports["default"] = _default;41799/***/ }),41800/***/ 2746:41801/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {41802"use strict";41803Object.defineProperty(exports, "__esModule", ({41804 value: true41805}));41806exports["default"] = void 0;41807var _validate = _interopRequireDefault(__nccwpck_require__(6900));41808function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }41809function parse(uuid) {41810 if (!(0, _validate.default)(uuid)) {41811 throw TypeError('Invalid UUID');41812 }41813 let v;41814 const arr = new Uint8Array(16); // Parse ########-....-....-....-............41815 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;41816 arr[1] = v >>> 16 & 0xff;41817 arr[2] = v >>> 8 & 0xff;41818 arr[3] = v & 0xff; // Parse ........-####-....-....-............41819 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;41820 arr[5] = v & 0xff; // Parse ........-....-####-....-............41821 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;41822 arr[7] = v & 0xff; // Parse ........-....-....-####-............41823 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;41824 arr[9] = v & 0xff; // Parse ........-....-....-....-############41825 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)41826 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;41827 arr[11] = v / 0x100000000 & 0xff;41828 arr[12] = v >>> 24 & 0xff;41829 arr[13] = v >>> 16 & 0xff;41830 arr[14] = v >>> 8 & 0xff;41831 arr[15] = v & 0xff;41832 return arr;41833}41834var _default = parse;41835exports["default"] = _default;41836/***/ }),41837/***/ 814:41838/***/ ((__unused_webpack_module, exports) => {41839"use strict";41840Object.defineProperty(exports, "__esModule", ({41841 value: true41842}));41843exports["default"] = void 0;41844var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;41845exports["default"] = _default;41846/***/ }),41847/***/ 807:41848/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {41849"use strict";41850Object.defineProperty(exports, "__esModule", ({41851 value: true41852}));41853exports["default"] = rng;41854var _crypto = _interopRequireDefault(__nccwpck_require__(6113));41855function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }41856const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate41857let poolPtr = rnds8Pool.length;41858function rng() {41859 if (poolPtr > rnds8Pool.length - 16) {41860 _crypto.default.randomFillSync(rnds8Pool);41861 poolPtr = 0;41862 }41863 return rnds8Pool.slice(poolPtr, poolPtr += 16);41864}41865/***/ }),41866/***/ 5274:41867/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {41868"use strict";41869Object.defineProperty(exports, "__esModule", ({41870 value: true41871}));41872exports["default"] = void 0;41873var _crypto = _interopRequireDefault(__nccwpck_require__(6113));41874function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }41875function sha1(bytes) {41876 if (Array.isArray(bytes)) {41877 bytes = Buffer.from(bytes);41878 } else if (typeof bytes === 'string') {41879 bytes = Buffer.from(bytes, 'utf8');41880 }41881 return _crypto.default.createHash('sha1').update(bytes).digest();41882}41883var _default = sha1;41884exports["default"] = _default;41885/***/ }),41886/***/ 8950:41887/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {41888"use strict";41889Object.defineProperty(exports, "__esModule", ({41890 value: true41891}));41892exports["default"] = void 0;41893var _validate = _interopRequireDefault(__nccwpck_require__(6900));41894function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }41895/**41896 * Convert array of 16 byte values to UUID string format of the form:41897 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX41898 */41899const byteToHex = [];41900for (let i = 0; i < 256; ++i) {41901 byteToHex.push((i + 0x100).toString(16).substr(1));41902}41903function stringify(arr, offset = 0) {41904 // Note: Be careful editing this code! It's been tuned for performance41905 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/43441906 const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one41907 // of the following:41908 // - One or more input array values don't map to a hex octet (leading to41909 // "undefined" in the uuid)41910 // - Invalid input values for the RFC `version` or `variant` fields41911 if (!(0, _validate.default)(uuid)) {41912 throw TypeError('Stringified UUID is invalid');41913 }41914 return uuid;41915}41916var _default = stringify;41917exports["default"] = _default;41918/***/ }),41919/***/ 8628:41920/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {41921"use strict";41922Object.defineProperty(exports, "__esModule", ({41923 value: true41924}));41925exports["default"] = void 0;41926var _rng = _interopRequireDefault(__nccwpck_require__(807));41927var _stringify = _interopRequireDefault(__nccwpck_require__(8950));41928function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }41929// **`v1()` - Generate time-based UUID**41930//41931// Inspired by https://github.com/LiosK/UUID.js41932// and http://docs.python.org/library/uuid.html41933let _nodeId;41934let _clockseq; // Previous uuid creation time41935let _lastMSecs = 0;41936let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details41937function v1(options, buf, offset) {41938 let i = buf && offset || 0;41939 const b = buf || new Array(16);41940 options = options || {};41941 let node = options.node || _nodeId;41942 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not41943 // specified. We do this lazily to minimize issues related to insufficient41944 // system entropy. See #18941945 if (node == null || clockseq == null) {41946 const seedBytes = options.random || (options.rng || _rng.default)();41947 if (node == null) {41948 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)41949 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];41950 }41951 if (clockseq == null) {41952 // Per 4.2.2, randomize (14 bit) clockseq41953 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;41954 }41955 } // UUID timestamps are 100 nano-second units since the Gregorian epoch,41956 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so41957 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'41958 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.41959 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock41960 // cycle to simulate higher resolution clock41961 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)41962 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression41963 if (dt < 0 && options.clockseq === undefined) {41964 clockseq = clockseq + 1 & 0x3fff;41965 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new41966 // time interval41967 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {41968 nsecs = 0;41969 } // Per 4.2.1.2 Throw error if too many uuids are requested41970 if (nsecs >= 10000) {41971 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");41972 }41973 _lastMSecs = msecs;41974 _lastNSecs = nsecs;41975 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch41976 msecs += 12219292800000; // `time_low`41977 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;41978 b[i++] = tl >>> 24 & 0xff;41979 b[i++] = tl >>> 16 & 0xff;41980 b[i++] = tl >>> 8 & 0xff;41981 b[i++] = tl & 0xff; // `time_mid`41982 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;41983 b[i++] = tmh >>> 8 & 0xff;41984 b[i++] = tmh & 0xff; // `time_high_and_version`41985 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version41986 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)41987 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`41988 b[i++] = clockseq & 0xff; // `node`41989 for (let n = 0; n < 6; ++n) {41990 b[i + n] = node[n];41991 }41992 return buf || (0, _stringify.default)(b);41993}41994var _default = v1;41995exports["default"] = _default;41996/***/ }),41997/***/ 6409:41998/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {41999"use strict";42000Object.defineProperty(exports, "__esModule", ({42001 value: true42002}));42003exports["default"] = void 0;42004var _v = _interopRequireDefault(__nccwpck_require__(5998));42005var _md = _interopRequireDefault(__nccwpck_require__(4569));42006function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }42007const v3 = (0, _v.default)('v3', 0x30, _md.default);42008var _default = v3;42009exports["default"] = _default;42010/***/ }),42011/***/ 5998:42012/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {42013"use strict";42014Object.defineProperty(exports, "__esModule", ({42015 value: true42016}));42017exports["default"] = _default;42018exports.URL = exports.DNS = void 0;42019var _stringify = _interopRequireDefault(__nccwpck_require__(8950));42020var _parse = _interopRequireDefault(__nccwpck_require__(2746));42021function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }42022function stringToBytes(str) {42023 str = unescape(encodeURIComponent(str)); // UTF8 escape42024 const bytes = [];42025 for (let i = 0; i < str.length; ++i) {42026 bytes.push(str.charCodeAt(i));42027 }42028 return bytes;42029}42030const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';42031exports.DNS = DNS;42032const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';42033exports.URL = URL;42034function _default(name, version, hashfunc) {42035 function generateUUID(value, namespace, buf, offset) {42036 if (typeof value === 'string') {42037 value = stringToBytes(value);42038 }42039 if (typeof namespace === 'string') {42040 namespace = (0, _parse.default)(namespace);42041 }42042 if (namespace.length !== 16) {42043 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');42044 } // Compute hash of namespace and value, Per 4.342045 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =42046 // hashfunc([...namespace, ... value])`42047 let bytes = new Uint8Array(16 + value.length);42048 bytes.set(namespace);42049 bytes.set(value, namespace.length);42050 bytes = hashfunc(bytes);42051 bytes[6] = bytes[6] & 0x0f | version;42052 bytes[8] = bytes[8] & 0x3f | 0x80;42053 if (buf) {42054 offset = offset || 0;42055 for (let i = 0; i < 16; ++i) {42056 buf[offset + i] = bytes[i];42057 }42058 return buf;42059 }42060 return (0, _stringify.default)(bytes);42061 } // Function#name is not settable on some platforms (#270)42062 try {42063 generateUUID.name = name; // eslint-disable-next-line no-empty42064 } catch (err) {} // For CommonJS default export support42065 generateUUID.DNS = DNS;42066 generateUUID.URL = URL;42067 return generateUUID;42068}42069/***/ }),42070/***/ 5122:42071/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {42072"use strict";42073Object.defineProperty(exports, "__esModule", ({42074 value: true42075}));42076exports["default"] = void 0;42077var _rng = _interopRequireDefault(__nccwpck_require__(807));42078var _stringify = _interopRequireDefault(__nccwpck_require__(8950));42079function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }42080function v4(options, buf, offset) {42081 options = options || {};42082 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`42083 rnds[6] = rnds[6] & 0x0f | 0x40;42084 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided42085 if (buf) {42086 offset = offset || 0;42087 for (let i = 0; i < 16; ++i) {42088 buf[offset + i] = rnds[i];42089 }42090 return buf;42091 }42092 return (0, _stringify.default)(rnds);42093}42094var _default = v4;42095exports["default"] = _default;42096/***/ }),42097/***/ 9120:42098/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {42099"use strict";42100Object.defineProperty(exports, "__esModule", ({42101 value: true42102}));42103exports["default"] = void 0;42104var _v = _interopRequireDefault(__nccwpck_require__(5998));42105var _sha = _interopRequireDefault(__nccwpck_require__(5274));42106function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }42107const v5 = (0, _v.default)('v5', 0x50, _sha.default);42108var _default = v5;42109exports["default"] = _default;42110/***/ }),42111/***/ 6900:42112/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {42113"use strict";42114Object.defineProperty(exports, "__esModule", ({42115 value: true42116}));42117exports["default"] = void 0;42118var _regex = _interopRequireDefault(__nccwpck_require__(814));42119function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }42120function validate(uuid) {42121 return typeof uuid === 'string' && _regex.default.test(uuid);42122}42123var _default = validate;42124exports["default"] = _default;42125/***/ }),42126/***/ 1595:42127/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {42128"use strict";42129Object.defineProperty(exports, "__esModule", ({42130 value: true42131}));42132exports["default"] = void 0;42133var _validate = _interopRequireDefault(__nccwpck_require__(6900));42134function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }42135function version(uuid) {42136 if (!(0, _validate.default)(uuid)) {42137 throw TypeError('Invalid UUID');42138 }42139 return parseInt(uuid.substr(14, 1), 16);42140}42141var _default = version;42142exports["default"] = _default;42143/***/ }),42144/***/ 4886:42145/***/ ((module) => {42146"use strict";42147var conversions = {};42148module.exports = conversions;42149function sign(x) {42150 return x < 0 ? -1 : 1;42151}42152function evenRound(x) {42153 // Round x to the nearest integer, choosing the even integer if it lies halfway between two.42154 if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor)42155 return Math.floor(x);42156 } else {42157 return Math.round(x);42158 }42159}42160function createNumberConversion(bitLength, typeOpts) {42161 if (!typeOpts.unsigned) {42162 --bitLength;42163 }42164 const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength);42165 const upperBound = Math.pow(2, bitLength) - 1;42166 const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength);42167 const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1);42168 return function(V, opts) {42169 if (!opts) opts = {};42170 let x = +V;42171 if (opts.enforceRange) {42172 if (!Number.isFinite(x)) {42173 throw new TypeError("Argument is not a finite number");42174 }42175 x = sign(x) * Math.floor(Math.abs(x));42176 if (x < lowerBound || x > upperBound) {42177 throw new TypeError("Argument is not in byte range");42178 }42179 return x;42180 }42181 if (!isNaN(x) && opts.clamp) {42182 x = evenRound(x);42183 if (x < lowerBound) x = lowerBound;42184 if (x > upperBound) x = upperBound;42185 return x;42186 }42187 if (!Number.isFinite(x) || x === 0) {42188 return 0;42189 }42190 x = sign(x) * Math.floor(Math.abs(x));42191 x = x % moduloVal;42192 if (!typeOpts.unsigned && x >= moduloBound) {42193 return x - moduloVal;42194 } else if (typeOpts.unsigned) {42195 if (x < 0) {42196 x += moduloVal;42197 } else if (x === -0) { // don't return negative zero42198 return 0;42199 }42200 }42201 return x;42202 }42203}42204conversions["void"] = function () {42205 return undefined;42206};42207conversions["boolean"] = function (val) {42208 return !!val;42209};42210conversions["byte"] = createNumberConversion(8, { unsigned: false });42211conversions["octet"] = createNumberConversion(8, { unsigned: true });42212conversions["short"] = createNumberConversion(16, { unsigned: false });42213conversions["unsigned short"] = createNumberConversion(16, { unsigned: true });42214conversions["long"] = createNumberConversion(32, { unsigned: false });42215conversions["unsigned long"] = createNumberConversion(32, { unsigned: true });42216conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 });42217conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 });42218conversions["double"] = function (V) {42219 const x = +V;42220 if (!Number.isFinite(x)) {42221 throw new TypeError("Argument is not a finite floating-point value");42222 }42223 return x;42224};42225conversions["unrestricted double"] = function (V) {42226 const x = +V;42227 if (isNaN(x)) {42228 throw new TypeError("Argument is NaN");42229 }42230 return x;42231};42232// not quite valid, but good enough for JS42233conversions["float"] = conversions["double"];42234conversions["unrestricted float"] = conversions["unrestricted double"];42235conversions["DOMString"] = function (V, opts) {42236 if (!opts) opts = {};42237 if (opts.treatNullAsEmptyString && V === null) {42238 return "";42239 }42240 return String(V);42241};42242conversions["ByteString"] = function (V, opts) {42243 const x = String(V);42244 let c = undefined;42245 for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) {42246 if (c > 255) {42247 throw new TypeError("Argument is not a valid bytestring");42248 }42249 }42250 return x;42251};42252conversions["USVString"] = function (V) {42253 const S = String(V);42254 const n = S.length;42255 const U = [];42256 for (let i = 0; i < n; ++i) {42257 const c = S.charCodeAt(i);42258 if (c < 0xD800 || c > 0xDFFF) {42259 U.push(String.fromCodePoint(c));42260 } else if (0xDC00 <= c && c <= 0xDFFF) {42261 U.push(String.fromCodePoint(0xFFFD));42262 } else {42263 if (i === n - 1) {42264 U.push(String.fromCodePoint(0xFFFD));42265 } else {42266 const d = S.charCodeAt(i + 1);42267 if (0xDC00 <= d && d <= 0xDFFF) {42268 const a = c & 0x3FF;42269 const b = d & 0x3FF;42270 U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));42271 ++i;42272 } else {42273 U.push(String.fromCodePoint(0xFFFD));42274 }42275 }42276 }42277 }42278 return U.join('');42279};42280conversions["Date"] = function (V, opts) {42281 if (!(V instanceof Date)) {42282 throw new TypeError("Argument is not a Date object");42283 }42284 if (isNaN(V)) {42285 return undefined;42286 }42287 return V;42288};42289conversions["RegExp"] = function (V, opts) {42290 if (!(V instanceof RegExp)) {42291 V = new RegExp(V);42292 }42293 return V;42294};42295/***/ }),42296/***/ 7537:42297/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {42298"use strict";42299const usm = __nccwpck_require__(2158);42300exports.implementation = class URLImpl {42301 constructor(constructorArgs) {42302 const url = constructorArgs[0];42303 const base = constructorArgs[1];42304 let parsedBase = null;42305 if (base !== undefined) {42306 parsedBase = usm.basicURLParse(base);42307 if (parsedBase === "failure") {42308 throw new TypeError("Invalid base URL");42309 }42310 }42311 const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase });42312 if (parsedURL === "failure") {42313 throw new TypeError("Invalid URL");42314 }42315 this._url = parsedURL;42316 // TODO: query stuff42317 }42318 get href() {42319 return usm.serializeURL(this._url);42320 }42321 set href(v) {42322 const parsedURL = usm.basicURLParse(v);42323 if (parsedURL === "failure") {42324 throw new TypeError("Invalid URL");42325 }42326 this._url = parsedURL;42327 }42328 get origin() {42329 return usm.serializeURLOrigin(this._url);42330 }42331 get protocol() {42332 return this._url.scheme + ":";42333 }42334 set protocol(v) {42335 usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });42336 }42337 get username() {42338 return this._url.username;42339 }42340 set username(v) {42341 if (usm.cannotHaveAUsernamePasswordPort(this._url)) {42342 return;42343 }42344 usm.setTheUsername(this._url, v);42345 }42346 get password() {42347 return this._url.password;42348 }42349 set password(v) {42350 if (usm.cannotHaveAUsernamePasswordPort(this._url)) {42351 return;42352 }42353 usm.setThePassword(this._url, v);42354 }42355 get host() {42356 const url = this._url;42357 if (url.host === null) {42358 return "";42359 }42360 if (url.port === null) {42361 return usm.serializeHost(url.host);42362 }42363 return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port);42364 }42365 set host(v) {42366 if (this._url.cannotBeABaseURL) {42367 return;42368 }42369 usm.basicURLParse(v, { url: this._url, stateOverride: "host" });42370 }42371 get hostname() {42372 if (this._url.host === null) {42373 return "";42374 }42375 return usm.serializeHost(this._url.host);42376 }42377 set hostname(v) {42378 if (this._url.cannotBeABaseURL) {42379 return;42380 }42381 usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });42382 }42383 get port() {42384 if (this._url.port === null) {42385 return "";42386 }42387 return usm.serializeInteger(this._url.port);42388 }42389 set port(v) {42390 if (usm.cannotHaveAUsernamePasswordPort(this._url)) {42391 return;42392 }42393 if (v === "") {42394 this._url.port = null;42395 } else {42396 usm.basicURLParse(v, { url: this._url, stateOverride: "port" });42397 }42398 }42399 get pathname() {42400 if (this._url.cannotBeABaseURL) {42401 return this._url.path[0];42402 }42403 if (this._url.path.length === 0) {42404 return "";42405 }42406 return "/" + this._url.path.join("/");42407 }42408 set pathname(v) {42409 if (this._url.cannotBeABaseURL) {42410 return;42411 }42412 this._url.path = [];42413 usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });42414 }42415 get search() {42416 if (this._url.query === null || this._url.query === "") {42417 return "";42418 }42419 return "?" + this._url.query;42420 }42421 set search(v) {42422 // TODO: query stuff42423 const url = this._url;42424 if (v === "") {42425 url.query = null;42426 return;42427 }42428 const input = v[0] === "?" ? v.substring(1) : v;42429 url.query = "";42430 usm.basicURLParse(input, { url, stateOverride: "query" });42431 }42432 get hash() {42433 if (this._url.fragment === null || this._url.fragment === "") {42434 return "";42435 }42436 return "#" + this._url.fragment;42437 }42438 set hash(v) {42439 if (v === "") {42440 this._url.fragment = null;42441 return;42442 }42443 const input = v[0] === "#" ? v.substring(1) : v;42444 this._url.fragment = "";42445 usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });42446 }42447 toJSON() {42448 return this.href;42449 }42450};42451/***/ }),42452/***/ 3394:42453/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {42454"use strict";42455const conversions = __nccwpck_require__(4886);42456const utils = __nccwpck_require__(3185);42457const Impl = __nccwpck_require__(7537);42458const impl = utils.implSymbol;42459function URL(url) {42460 if (!this || this[impl] || !(this instanceof URL)) {42461 throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");42462 }42463 if (arguments.length < 1) {42464 throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present.");42465 }42466 const args = [];42467 for (let i = 0; i < arguments.length && i < 2; ++i) {42468 args[i] = arguments[i];42469 }42470 args[0] = conversions["USVString"](args[0]);42471 if (args[1] !== undefined) {42472 args[1] = conversions["USVString"](args[1]);42473 }42474 module.exports.setup(this, args);42475}42476URL.prototype.toJSON = function toJSON() {42477 if (!this || !module.exports.is(this)) {42478 throw new TypeError("Illegal invocation");42479 }42480 const args = [];42481 for (let i = 0; i < arguments.length && i < 0; ++i) {42482 args[i] = arguments[i];42483 }42484 return this[impl].toJSON.apply(this[impl], args);42485};42486Object.defineProperty(URL.prototype, "href", {42487 get() {42488 return this[impl].href;42489 },42490 set(V) {42491 V = conversions["USVString"](V);42492 this[impl].href = V;42493 },42494 enumerable: true,42495 configurable: true42496});42497URL.prototype.toString = function () {42498 if (!this || !module.exports.is(this)) {42499 throw new TypeError("Illegal invocation");42500 }42501 return this.href;42502};42503Object.defineProperty(URL.prototype, "origin", {42504 get() {42505 return this[impl].origin;42506 },42507 enumerable: true,42508 configurable: true42509});42510Object.defineProperty(URL.prototype, "protocol", {42511 get() {42512 return this[impl].protocol;42513 },42514 set(V) {42515 V = conversions["USVString"](V);42516 this[impl].protocol = V;42517 },42518 enumerable: true,42519 configurable: true42520});42521Object.defineProperty(URL.prototype, "username", {42522 get() {42523 return this[impl].username;42524 },42525 set(V) {42526 V = conversions["USVString"](V);42527 this[impl].username = V;42528 },42529 enumerable: true,42530 configurable: true42531});42532Object.defineProperty(URL.prototype, "password", {42533 get() {42534 return this[impl].password;42535 },42536 set(V) {42537 V = conversions["USVString"](V);42538 this[impl].password = V;42539 },42540 enumerable: true,42541 configurable: true42542});42543Object.defineProperty(URL.prototype, "host", {42544 get() {42545 return this[impl].host;42546 },42547 set(V) {42548 V = conversions["USVString"](V);42549 this[impl].host = V;42550 },42551 enumerable: true,42552 configurable: true42553});42554Object.defineProperty(URL.prototype, "hostname", {42555 get() {42556 return this[impl].hostname;42557 },42558 set(V) {42559 V = conversions["USVString"](V);42560 this[impl].hostname = V;42561 },42562 enumerable: true,42563 configurable: true42564});42565Object.defineProperty(URL.prototype, "port", {42566 get() {42567 return this[impl].port;42568 },42569 set(V) {42570 V = conversions["USVString"](V);42571 this[impl].port = V;42572 },42573 enumerable: true,42574 configurable: true42575});42576Object.defineProperty(URL.prototype, "pathname", {42577 get() {42578 return this[impl].pathname;42579 },42580 set(V) {42581 V = conversions["USVString"](V);42582 this[impl].pathname = V;42583 },42584 enumerable: true,42585 configurable: true42586});42587Object.defineProperty(URL.prototype, "search", {42588 get() {42589 return this[impl].search;42590 },42591 set(V) {42592 V = conversions["USVString"](V);42593 this[impl].search = V;42594 },42595 enumerable: true,42596 configurable: true42597});42598Object.defineProperty(URL.prototype, "hash", {42599 get() {42600 return this[impl].hash;42601 },42602 set(V) {42603 V = conversions["USVString"](V);42604 this[impl].hash = V;42605 },42606 enumerable: true,42607 configurable: true42608});42609module.exports = {42610 is(obj) {42611 return !!obj && obj[impl] instanceof Impl.implementation;42612 },42613 create(constructorArgs, privateData) {42614 let obj = Object.create(URL.prototype);42615 this.setup(obj, constructorArgs, privateData);42616 return obj;42617 },42618 setup(obj, constructorArgs, privateData) {42619 if (!privateData) privateData = {};42620 privateData.wrapper = obj;42621 obj[impl] = new Impl.implementation(constructorArgs, privateData);42622 obj[impl][utils.wrapperSymbol] = obj;42623 },42624 interface: URL,42625 expose: {42626 Window: { URL: URL },42627 Worker: { URL: URL }42628 }42629};42630/***/ }),42631/***/ 8665:42632/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {42633"use strict";42634exports.URL = __nccwpck_require__(3394)["interface"];42635exports.serializeURL = __nccwpck_require__(2158).serializeURL;42636exports.serializeURLOrigin = __nccwpck_require__(2158).serializeURLOrigin;42637exports.basicURLParse = __nccwpck_require__(2158).basicURLParse;42638exports.setTheUsername = __nccwpck_require__(2158).setTheUsername;42639exports.setThePassword = __nccwpck_require__(2158).setThePassword;42640exports.serializeHost = __nccwpck_require__(2158).serializeHost;42641exports.serializeInteger = __nccwpck_require__(2158).serializeInteger;42642exports.parseURL = __nccwpck_require__(2158).parseURL;42643/***/ }),42644/***/ 2158:42645/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {42646"use strict";42647const punycode = __nccwpck_require__(5477);42648const tr46 = __nccwpck_require__(4256);42649const specialSchemes = {42650 ftp: 21,42651 file: null,42652 gopher: 70,42653 http: 80,42654 https: 443,42655 ws: 80,42656 wss: 44342657};42658const failure = Symbol("failure");42659function countSymbols(str) {42660 return punycode.ucs2.decode(str).length;42661}42662function at(input, idx) {42663 const c = input[idx];42664 return isNaN(c) ? undefined : String.fromCodePoint(c);42665}42666function isASCIIDigit(c) {42667 return c >= 0x30 && c <= 0x39;42668}42669function isASCIIAlpha(c) {42670 return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A);42671}42672function isASCIIAlphanumeric(c) {42673 return isASCIIAlpha(c) || isASCIIDigit(c);42674}42675function isASCIIHex(c) {42676 return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66);42677}42678function isSingleDot(buffer) {42679 return buffer === "." || buffer.toLowerCase() === "%2e";42680}42681function isDoubleDot(buffer) {42682 buffer = buffer.toLowerCase();42683 return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";42684}42685function isWindowsDriveLetterCodePoints(cp1, cp2) {42686 return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124);42687}42688function isWindowsDriveLetterString(string) {42689 return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");42690}42691function isNormalizedWindowsDriveLetterString(string) {42692 return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":";42693}42694function containsForbiddenHostCodePoint(string) {42695 return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1;42696}42697function containsForbiddenHostCodePointExcludingPercent(string) {42698 return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1;42699}42700function isSpecialScheme(scheme) {42701 return specialSchemes[scheme] !== undefined;42702}42703function isSpecial(url) {42704 return isSpecialScheme(url.scheme);42705}42706function defaultPort(scheme) {42707 return specialSchemes[scheme];42708}42709function percentEncode(c) {42710 let hex = c.toString(16).toUpperCase();42711 if (hex.length === 1) {42712 hex = "0" + hex;42713 }42714 return "%" + hex;42715}42716function utf8PercentEncode(c) {42717 const buf = new Buffer(c);42718 let str = "";42719 for (let i = 0; i < buf.length; ++i) {42720 str += percentEncode(buf[i]);42721 }42722 return str;42723}42724function utf8PercentDecode(str) {42725 const input = new Buffer(str);42726 const output = [];42727 for (let i = 0; i < input.length; ++i) {42728 if (input[i] !== 37) {42729 output.push(input[i]);42730 } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) {42731 output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16));42732 i += 2;42733 } else {42734 output.push(input[i]);42735 }42736 }42737 return new Buffer(output).toString();42738}42739function isC0ControlPercentEncode(c) {42740 return c <= 0x1F || c > 0x7E;42741}42742const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]);42743function isPathPercentEncode(c) {42744 return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c);42745}42746const extraUserinfoPercentEncodeSet =42747 new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);42748function isUserinfoPercentEncode(c) {42749 return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);42750}42751function percentEncodeChar(c, encodeSetPredicate) {42752 const cStr = String.fromCodePoint(c);42753 if (encodeSetPredicate(c)) {42754 return utf8PercentEncode(cStr);42755 }42756 return cStr;42757}42758function parseIPv4Number(input) {42759 let R = 10;42760 if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {42761 input = input.substring(2);42762 R = 16;42763 } else if (input.length >= 2 && input.charAt(0) === "0") {42764 input = input.substring(1);42765 R = 8;42766 }42767 if (input === "") {42768 return 0;42769 }42770 const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/);42771 if (regex.test(input)) {42772 return failure;42773 }42774 return parseInt(input, R);42775}42776function parseIPv4(input) {42777 const parts = input.split(".");42778 if (parts[parts.length - 1] === "") {42779 if (parts.length > 1) {42780 parts.pop();42781 }42782 }42783 if (parts.length > 4) {42784 return input;42785 }42786 const numbers = [];42787 for (const part of parts) {42788 if (part === "") {42789 return input;42790 }42791 const n = parseIPv4Number(part);42792 if (n === failure) {42793 return input;42794 }42795 numbers.push(n);42796 }42797 for (let i = 0; i < numbers.length - 1; ++i) {42798 if (numbers[i] > 255) {42799 return failure;42800 }42801 }42802 if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {42803 return failure;42804 }42805 let ipv4 = numbers.pop();42806 let counter = 0;42807 for (const n of numbers) {42808 ipv4 += n * Math.pow(256, 3 - counter);42809 ++counter;42810 }42811 return ipv4;42812}42813function serializeIPv4(address) {42814 let output = "";42815 let n = address;42816 for (let i = 1; i <= 4; ++i) {42817 output = String(n % 256) + output;42818 if (i !== 4) {42819 output = "." + output;42820 }42821 n = Math.floor(n / 256);42822 }42823 return output;42824}42825function parseIPv6(input) {42826 const address = [0, 0, 0, 0, 0, 0, 0, 0];42827 let pieceIndex = 0;42828 let compress = null;42829 let pointer = 0;42830 input = punycode.ucs2.decode(input);42831 if (input[pointer] === 58) {42832 if (input[pointer + 1] !== 58) {42833 return failure;42834 }42835 pointer += 2;42836 ++pieceIndex;42837 compress = pieceIndex;42838 }42839 while (pointer < input.length) {42840 if (pieceIndex === 8) {42841 return failure;42842 }42843 if (input[pointer] === 58) {42844 if (compress !== null) {42845 return failure;42846 }42847 ++pointer;42848 ++pieceIndex;42849 compress = pieceIndex;42850 continue;42851 }42852 let value = 0;42853 let length = 0;42854 while (length < 4 && isASCIIHex(input[pointer])) {42855 value = value * 0x10 + parseInt(at(input, pointer), 16);42856 ++pointer;42857 ++length;42858 }42859 if (input[pointer] === 46) {42860 if (length === 0) {42861 return failure;42862 }42863 pointer -= length;42864 if (pieceIndex > 6) {42865 return failure;42866 }42867 let numbersSeen = 0;42868 while (input[pointer] !== undefined) {42869 let ipv4Piece = null;42870 if (numbersSeen > 0) {42871 if (input[pointer] === 46 && numbersSeen < 4) {42872 ++pointer;42873 } else {42874 return failure;42875 }42876 }42877 if (!isASCIIDigit(input[pointer])) {42878 return failure;42879 }42880 while (isASCIIDigit(input[pointer])) {42881 const number = parseInt(at(input, pointer));42882 if (ipv4Piece === null) {42883 ipv4Piece = number;42884 } else if (ipv4Piece === 0) {42885 return failure;42886 } else {42887 ipv4Piece = ipv4Piece * 10 + number;42888 }42889 if (ipv4Piece > 255) {42890 return failure;42891 }42892 ++pointer;42893 }42894 address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece;42895 ++numbersSeen;42896 if (numbersSeen === 2 || numbersSeen === 4) {42897 ++pieceIndex;42898 }42899 }42900 if (numbersSeen !== 4) {42901 return failure;42902 }42903 break;42904 } else if (input[pointer] === 58) {42905 ++pointer;42906 if (input[pointer] === undefined) {42907 return failure;42908 }42909 } else if (input[pointer] !== undefined) {42910 return failure;42911 }42912 address[pieceIndex] = value;42913 ++pieceIndex;42914 }42915 if (compress !== null) {42916 let swaps = pieceIndex - compress;42917 pieceIndex = 7;42918 while (pieceIndex !== 0 && swaps > 0) {42919 const temp = address[compress + swaps - 1];42920 address[compress + swaps - 1] = address[pieceIndex];42921 address[pieceIndex] = temp;42922 --pieceIndex;42923 --swaps;42924 }42925 } else if (compress === null && pieceIndex !== 8) {42926 return failure;42927 }42928 return address;42929}42930function serializeIPv6(address) {42931 let output = "";42932 const seqResult = findLongestZeroSequence(address);42933 const compress = seqResult.idx;42934 let ignore0 = false;42935 for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {42936 if (ignore0 && address[pieceIndex] === 0) {42937 continue;42938 } else if (ignore0) {42939 ignore0 = false;42940 }42941 if (compress === pieceIndex) {42942 const separator = pieceIndex === 0 ? "::" : ":";42943 output += separator;42944 ignore0 = true;42945 continue;42946 }42947 output += address[pieceIndex].toString(16);42948 if (pieceIndex !== 7) {42949 output += ":";42950 }42951 }42952 return output;42953}42954function parseHost(input, isSpecialArg) {42955 if (input[0] === "[") {42956 if (input[input.length - 1] !== "]") {42957 return failure;42958 }42959 return parseIPv6(input.substring(1, input.length - 1));42960 }42961 if (!isSpecialArg) {42962 return parseOpaqueHost(input);42963 }42964 const domain = utf8PercentDecode(input);42965 const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false);42966 if (asciiDomain === null) {42967 return failure;42968 }42969 if (containsForbiddenHostCodePoint(asciiDomain)) {42970 return failure;42971 }42972 const ipv4Host = parseIPv4(asciiDomain);42973 if (typeof ipv4Host === "number" || ipv4Host === failure) {42974 return ipv4Host;42975 }42976 return asciiDomain;42977}42978function parseOpaqueHost(input) {42979 if (containsForbiddenHostCodePointExcludingPercent(input)) {42980 return failure;42981 }42982 let output = "";42983 const decoded = punycode.ucs2.decode(input);42984 for (let i = 0; i < decoded.length; ++i) {42985 output += percentEncodeChar(decoded[i], isC0ControlPercentEncode);42986 }42987 return output;42988}42989function findLongestZeroSequence(arr) {42990 let maxIdx = null;42991 let maxLen = 1; // only find elements > 142992 let currStart = null;42993 let currLen = 0;42994 for (let i = 0; i < arr.length; ++i) {42995 if (arr[i] !== 0) {42996 if (currLen > maxLen) {42997 maxIdx = currStart;42998 maxLen = currLen;42999 }43000 currStart = null;43001 currLen = 0;43002 } else {43003 if (currStart === null) {43004 currStart = i;43005 }43006 ++currLen;43007 }43008 }43009 // if trailing zeros43010 if (currLen > maxLen) {43011 maxIdx = currStart;43012 maxLen = currLen;43013 }43014 return {43015 idx: maxIdx,43016 len: maxLen43017 };43018}43019function serializeHost(host) {43020 if (typeof host === "number") {43021 return serializeIPv4(host);43022 }43023 // IPv6 serializer43024 if (host instanceof Array) {43025 return "[" + serializeIPv6(host) + "]";43026 }43027 return host;43028}43029function trimControlChars(url) {43030 return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, "");43031}43032function trimTabAndNewline(url) {43033 return url.replace(/\u0009|\u000A|\u000D/g, "");43034}43035function shortenPath(url) {43036 const path = url.path;43037 if (path.length === 0) {43038 return;43039 }43040 if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {43041 return;43042 }43043 path.pop();43044}43045function includesCredentials(url) {43046 return url.username !== "" || url.password !== "";43047}43048function cannotHaveAUsernamePasswordPort(url) {43049 return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file";43050}43051function isNormalizedWindowsDriveLetter(string) {43052 return /^[A-Za-z]:$/.test(string);43053}43054function URLStateMachine(input, base, encodingOverride, url, stateOverride) {43055 this.pointer = 0;43056 this.input = input;43057 this.base = base || null;43058 this.encodingOverride = encodingOverride || "utf-8";43059 this.stateOverride = stateOverride;43060 this.url = url;43061 this.failure = false;43062 this.parseError = false;43063 if (!this.url) {43064 this.url = {43065 scheme: "",43066 username: "",43067 password: "",43068 host: null,43069 port: null,43070 path: [],43071 query: null,43072 fragment: null,43073 cannotBeABaseURL: false43074 };43075 const res = trimControlChars(this.input);43076 if (res !== this.input) {43077 this.parseError = true;43078 }43079 this.input = res;43080 }43081 const res = trimTabAndNewline(this.input);43082 if (res !== this.input) {43083 this.parseError = true;43084 }43085 this.input = res;43086 this.state = stateOverride || "scheme start";43087 this.buffer = "";43088 this.atFlag = false;43089 this.arrFlag = false;43090 this.passwordTokenSeenFlag = false;43091 this.input = punycode.ucs2.decode(this.input);43092 for (; this.pointer <= this.input.length; ++this.pointer) {43093 const c = this.input[this.pointer];43094 const cStr = isNaN(c) ? undefined : String.fromCodePoint(c);43095 // exec state machine43096 const ret = this["parse " + this.state](c, cStr);43097 if (!ret) {43098 break; // terminate algorithm43099 } else if (ret === failure) {43100 this.failure = true;43101 break;43102 }43103 }43104}43105URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) {43106 if (isASCIIAlpha(c)) {43107 this.buffer += cStr.toLowerCase();43108 this.state = "scheme";43109 } else if (!this.stateOverride) {43110 this.state = "no scheme";43111 --this.pointer;43112 } else {43113 this.parseError = true;43114 return failure;43115 }43116 return true;43117};43118URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) {43119 if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) {43120 this.buffer += cStr.toLowerCase();43121 } else if (c === 58) {43122 if (this.stateOverride) {43123 if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {43124 return false;43125 }43126 if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {43127 return false;43128 }43129 if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {43130 return false;43131 }43132 if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) {43133 return false;43134 }43135 }43136 this.url.scheme = this.buffer;43137 this.buffer = "";43138 if (this.stateOverride) {43139 return false;43140 }43141 if (this.url.scheme === "file") {43142 if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) {43143 this.parseError = true;43144 }43145 this.state = "file";43146 } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {43147 this.state = "special relative or authority";43148 } else if (isSpecial(this.url)) {43149 this.state = "special authority slashes";43150 } else if (this.input[this.pointer + 1] === 47) {43151 this.state = "path or authority";43152 ++this.pointer;43153 } else {43154 this.url.cannotBeABaseURL = true;43155 this.url.path.push("");43156 this.state = "cannot-be-a-base-URL path";43157 }43158 } else if (!this.stateOverride) {43159 this.buffer = "";43160 this.state = "no scheme";43161 this.pointer = -1;43162 } else {43163 this.parseError = true;43164 return failure;43165 }43166 return true;43167};43168URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) {43169 if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) {43170 return failure;43171 } else if (this.base.cannotBeABaseURL && c === 35) {43172 this.url.scheme = this.base.scheme;43173 this.url.path = this.base.path.slice();43174 this.url.query = this.base.query;43175 this.url.fragment = "";43176 this.url.cannotBeABaseURL = true;43177 this.state = "fragment";43178 } else if (this.base.scheme === "file") {43179 this.state = "file";43180 --this.pointer;43181 } else {43182 this.state = "relative";43183 --this.pointer;43184 }43185 return true;43186};43187URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) {43188 if (c === 47 && this.input[this.pointer + 1] === 47) {43189 this.state = "special authority ignore slashes";43190 ++this.pointer;43191 } else {43192 this.parseError = true;43193 this.state = "relative";43194 --this.pointer;43195 }43196 return true;43197};43198URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) {43199 if (c === 47) {43200 this.state = "authority";43201 } else {43202 this.state = "path";43203 --this.pointer;43204 }43205 return true;43206};43207URLStateMachine.prototype["parse relative"] = function parseRelative(c) {43208 this.url.scheme = this.base.scheme;43209 if (isNaN(c)) {43210 this.url.username = this.base.username;43211 this.url.password = this.base.password;43212 this.url.host = this.base.host;43213 this.url.port = this.base.port;43214 this.url.path = this.base.path.slice();43215 this.url.query = this.base.query;43216 } else if (c === 47) {43217 this.state = "relative slash";43218 } else if (c === 63) {43219 this.url.username = this.base.username;43220 this.url.password = this.base.password;43221 this.url.host = this.base.host;43222 this.url.port = this.base.port;43223 this.url.path = this.base.path.slice();43224 this.url.query = "";43225 this.state = "query";43226 } else if (c === 35) {43227 this.url.username = this.base.username;43228 this.url.password = this.base.password;43229 this.url.host = this.base.host;43230 this.url.port = this.base.port;43231 this.url.path = this.base.path.slice();43232 this.url.query = this.base.query;43233 this.url.fragment = "";43234 this.state = "fragment";43235 } else if (isSpecial(this.url) && c === 92) {43236 this.parseError = true;43237 this.state = "relative slash";43238 } else {43239 this.url.username = this.base.username;43240 this.url.password = this.base.password;43241 this.url.host = this.base.host;43242 this.url.port = this.base.port;43243 this.url.path = this.base.path.slice(0, this.base.path.length - 1);43244 this.state = "path";43245 --this.pointer;43246 }43247 return true;43248};43249URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) {43250 if (isSpecial(this.url) && (c === 47 || c === 92)) {43251 if (c === 92) {43252 this.parseError = true;43253 }43254 this.state = "special authority ignore slashes";43255 } else if (c === 47) {43256 this.state = "authority";43257 } else {43258 this.url.username = this.base.username;43259 this.url.password = this.base.password;43260 this.url.host = this.base.host;43261 this.url.port = this.base.port;43262 this.state = "path";43263 --this.pointer;43264 }43265 return true;43266};43267URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) {43268 if (c === 47 && this.input[this.pointer + 1] === 47) {43269 this.state = "special authority ignore slashes";43270 ++this.pointer;43271 } else {43272 this.parseError = true;43273 this.state = "special authority ignore slashes";43274 --this.pointer;43275 }43276 return true;43277};43278URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) {43279 if (c !== 47 && c !== 92) {43280 this.state = "authority";43281 --this.pointer;43282 } else {43283 this.parseError = true;43284 }43285 return true;43286};43287URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) {43288 if (c === 64) {43289 this.parseError = true;43290 if (this.atFlag) {43291 this.buffer = "%40" + this.buffer;43292 }43293 this.atFlag = true;43294 // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars43295 const len = countSymbols(this.buffer);43296 for (let pointer = 0; pointer < len; ++pointer) {43297 const codePoint = this.buffer.codePointAt(pointer);43298 if (codePoint === 58 && !this.passwordTokenSeenFlag) {43299 this.passwordTokenSeenFlag = true;43300 continue;43301 }43302 const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode);43303 if (this.passwordTokenSeenFlag) {43304 this.url.password += encodedCodePoints;43305 } else {43306 this.url.username += encodedCodePoints;43307 }43308 }43309 this.buffer = "";43310 } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||43311 (isSpecial(this.url) && c === 92)) {43312 if (this.atFlag && this.buffer === "") {43313 this.parseError = true;43314 return failure;43315 }43316 this.pointer -= countSymbols(this.buffer) + 1;43317 this.buffer = "";43318 this.state = "host";43319 } else {43320 this.buffer += cStr;43321 }43322 return true;43323};43324URLStateMachine.prototype["parse hostname"] =43325URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) {43326 if (this.stateOverride && this.url.scheme === "file") {43327 --this.pointer;43328 this.state = "file host";43329 } else if (c === 58 && !this.arrFlag) {43330 if (this.buffer === "") {43331 this.parseError = true;43332 return failure;43333 }43334 const host = parseHost(this.buffer, isSpecial(this.url));43335 if (host === failure) {43336 return failure;43337 }43338 this.url.host = host;43339 this.buffer = "";43340 this.state = "port";43341 if (this.stateOverride === "hostname") {43342 return false;43343 }43344 } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||43345 (isSpecial(this.url) && c === 92)) {43346 --this.pointer;43347 if (isSpecial(this.url) && this.buffer === "") {43348 this.parseError = true;43349 return failure;43350 } else if (this.stateOverride && this.buffer === "" &&43351 (includesCredentials(this.url) || this.url.port !== null)) {43352 this.parseError = true;43353 return false;43354 }43355 const host = parseHost(this.buffer, isSpecial(this.url));43356 if (host === failure) {43357 return failure;43358 }43359 this.url.host = host;43360 this.buffer = "";43361 this.state = "path start";43362 if (this.stateOverride) {43363 return false;43364 }43365 } else {43366 if (c === 91) {43367 this.arrFlag = true;43368 } else if (c === 93) {43369 this.arrFlag = false;43370 }43371 this.buffer += cStr;43372 }43373 return true;43374};43375URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) {43376 if (isASCIIDigit(c)) {43377 this.buffer += cStr;43378 } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||43379 (isSpecial(this.url) && c === 92) ||43380 this.stateOverride) {43381 if (this.buffer !== "") {43382 const port = parseInt(this.buffer);43383 if (port > Math.pow(2, 16) - 1) {43384 this.parseError = true;43385 return failure;43386 }43387 this.url.port = port === defaultPort(this.url.scheme) ? null : port;43388 this.buffer = "";43389 }43390 if (this.stateOverride) {43391 return false;43392 }43393 this.state = "path start";43394 --this.pointer;43395 } else {43396 this.parseError = true;43397 return failure;43398 }43399 return true;43400};43401const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]);43402URLStateMachine.prototype["parse file"] = function parseFile(c) {43403 this.url.scheme = "file";43404 if (c === 47 || c === 92) {43405 if (c === 92) {43406 this.parseError = true;43407 }43408 this.state = "file slash";43409 } else if (this.base !== null && this.base.scheme === "file") {43410 if (isNaN(c)) {43411 this.url.host = this.base.host;43412 this.url.path = this.base.path.slice();43413 this.url.query = this.base.query;43414 } else if (c === 63) {43415 this.url.host = this.base.host;43416 this.url.path = this.base.path.slice();43417 this.url.query = "";43418 this.state = "query";43419 } else if (c === 35) {43420 this.url.host = this.base.host;43421 this.url.path = this.base.path.slice();43422 this.url.query = this.base.query;43423 this.url.fragment = "";43424 this.state = "fragment";43425 } else {43426 if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points43427 !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) ||43428 (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points43429 !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) {43430 this.url.host = this.base.host;43431 this.url.path = this.base.path.slice();43432 shortenPath(this.url);43433 } else {43434 this.parseError = true;43435 }43436 this.state = "path";43437 --this.pointer;43438 }43439 } else {43440 this.state = "path";43441 --this.pointer;43442 }43443 return true;43444};43445URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) {43446 if (c === 47 || c === 92) {43447 if (c === 92) {43448 this.parseError = true;43449 }43450 this.state = "file host";43451 } else {43452 if (this.base !== null && this.base.scheme === "file") {43453 if (isNormalizedWindowsDriveLetterString(this.base.path[0])) {43454 this.url.path.push(this.base.path[0]);43455 } else {43456 this.url.host = this.base.host;43457 }43458 }43459 this.state = "path";43460 --this.pointer;43461 }43462 return true;43463};43464URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) {43465 if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) {43466 --this.pointer;43467 if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {43468 this.parseError = true;43469 this.state = "path";43470 } else if (this.buffer === "") {43471 this.url.host = "";43472 if (this.stateOverride) {43473 return false;43474 }43475 this.state = "path start";43476 } else {43477 let host = parseHost(this.buffer, isSpecial(this.url));43478 if (host === failure) {43479 return failure;43480 }43481 if (host === "localhost") {43482 host = "";43483 }43484 this.url.host = host;43485 if (this.stateOverride) {43486 return false;43487 }43488 this.buffer = "";43489 this.state = "path start";43490 }43491 } else {43492 this.buffer += cStr;43493 }43494 return true;43495};43496URLStateMachine.prototype["parse path start"] = function parsePathStart(c) {43497 if (isSpecial(this.url)) {43498 if (c === 92) {43499 this.parseError = true;43500 }43501 this.state = "path";43502 if (c !== 47 && c !== 92) {43503 --this.pointer;43504 }43505 } else if (!this.stateOverride && c === 63) {43506 this.url.query = "";43507 this.state = "query";43508 } else if (!this.stateOverride && c === 35) {43509 this.url.fragment = "";43510 this.state = "fragment";43511 } else if (c !== undefined) {43512 this.state = "path";43513 if (c !== 47) {43514 --this.pointer;43515 }43516 }43517 return true;43518};43519URLStateMachine.prototype["parse path"] = function parsePath(c) {43520 if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) ||43521 (!this.stateOverride && (c === 63 || c === 35))) {43522 if (isSpecial(this.url) && c === 92) {43523 this.parseError = true;43524 }43525 if (isDoubleDot(this.buffer)) {43526 shortenPath(this.url);43527 if (c !== 47 && !(isSpecial(this.url) && c === 92)) {43528 this.url.path.push("");43529 }43530 } else if (isSingleDot(this.buffer) && c !== 47 &&43531 !(isSpecial(this.url) && c === 92)) {43532 this.url.path.push("");43533 } else if (!isSingleDot(this.buffer)) {43534 if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) {43535 if (this.url.host !== "" && this.url.host !== null) {43536 this.parseError = true;43537 this.url.host = "";43538 }43539 this.buffer = this.buffer[0] + ":";43540 }43541 this.url.path.push(this.buffer);43542 }43543 this.buffer = "";43544 if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) {43545 while (this.url.path.length > 1 && this.url.path[0] === "") {43546 this.parseError = true;43547 this.url.path.shift();43548 }43549 }43550 if (c === 63) {43551 this.url.query = "";43552 this.state = "query";43553 }43554 if (c === 35) {43555 this.url.fragment = "";43556 this.state = "fragment";43557 }43558 } else {43559 // TODO: If c is not a URL code point and not "%", parse error.43560 if (c === 37 &&43561 (!isASCIIHex(this.input[this.pointer + 1]) ||43562 !isASCIIHex(this.input[this.pointer + 2]))) {43563 this.parseError = true;43564 }43565 this.buffer += percentEncodeChar(c, isPathPercentEncode);43566 }43567 return true;43568};43569URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) {43570 if (c === 63) {43571 this.url.query = "";43572 this.state = "query";43573 } else if (c === 35) {43574 this.url.fragment = "";43575 this.state = "fragment";43576 } else {43577 // TODO: Add: not a URL code point43578 if (!isNaN(c) && c !== 37) {43579 this.parseError = true;43580 }43581 if (c === 37 &&43582 (!isASCIIHex(this.input[this.pointer + 1]) ||43583 !isASCIIHex(this.input[this.pointer + 2]))) {43584 this.parseError = true;43585 }43586 if (!isNaN(c)) {43587 this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode);43588 }43589 }43590 return true;43591};43592URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) {43593 if (isNaN(c) || (!this.stateOverride && c === 35)) {43594 if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") {43595 this.encodingOverride = "utf-8";43596 }43597 const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead43598 for (let i = 0; i < buffer.length; ++i) {43599 if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 ||43600 buffer[i] === 0x3C || buffer[i] === 0x3E) {43601 this.url.query += percentEncode(buffer[i]);43602 } else {43603 this.url.query += String.fromCodePoint(buffer[i]);43604 }43605 }43606 this.buffer = "";43607 if (c === 35) {43608 this.url.fragment = "";43609 this.state = "fragment";43610 }43611 } else {43612 // TODO: If c is not a URL code point and not "%", parse error.43613 if (c === 37 &&43614 (!isASCIIHex(this.input[this.pointer + 1]) ||43615 !isASCIIHex(this.input[this.pointer + 2]))) {43616 this.parseError = true;43617 }43618 this.buffer += cStr;43619 }43620 return true;43621};43622URLStateMachine.prototype["parse fragment"] = function parseFragment(c) {43623 if (isNaN(c)) { // do nothing43624 } else if (c === 0x0) {43625 this.parseError = true;43626 } else {43627 // TODO: If c is not a URL code point and not "%", parse error.43628 if (c === 37 &&43629 (!isASCIIHex(this.input[this.pointer + 1]) ||43630 !isASCIIHex(this.input[this.pointer + 2]))) {43631 this.parseError = true;43632 }43633 this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode);43634 }43635 return true;43636};43637function serializeURL(url, excludeFragment) {43638 let output = url.scheme + ":";43639 if (url.host !== null) {43640 output += "//";43641 if (url.username !== "" || url.password !== "") {43642 output += url.username;43643 if (url.password !== "") {43644 output += ":" + url.password;43645 }43646 output += "@";43647 }43648 output += serializeHost(url.host);43649 if (url.port !== null) {43650 output += ":" + url.port;43651 }43652 } else if (url.host === null && url.scheme === "file") {43653 output += "//";43654 }43655 if (url.cannotBeABaseURL) {43656 output += url.path[0];43657 } else {43658 for (const string of url.path) {43659 output += "/" + string;43660 }43661 }43662 if (url.query !== null) {43663 output += "?" + url.query;43664 }43665 if (!excludeFragment && url.fragment !== null) {43666 output += "#" + url.fragment;43667 }43668 return output;43669}43670function serializeOrigin(tuple) {43671 let result = tuple.scheme + "://";43672 result += serializeHost(tuple.host);43673 if (tuple.port !== null) {43674 result += ":" + tuple.port;43675 }43676 return result;43677}43678module.exports.serializeURL = serializeURL;43679module.exports.serializeURLOrigin = function (url) {43680 // https://url.spec.whatwg.org/#concept-url-origin43681 switch (url.scheme) {43682 case "blob":43683 try {43684 return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0]));43685 } catch (e) {43686 // serializing an opaque origin returns "null"43687 return "null";43688 }43689 case "ftp":43690 case "gopher":43691 case "http":43692 case "https":43693 case "ws":43694 case "wss":43695 return serializeOrigin({43696 scheme: url.scheme,43697 host: url.host,43698 port: url.port43699 });43700 case "file":43701 // spec says "exercise to the reader", chrome says "file://"43702 return "file://";43703 default:43704 // serializing an opaque origin returns "null"43705 return "null";43706 }43707};43708module.exports.basicURLParse = function (input, options) {43709 if (options === undefined) {43710 options = {};43711 }43712 const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride);43713 if (usm.failure) {43714 return "failure";43715 }43716 return usm.url;43717};43718module.exports.setTheUsername = function (url, username) {43719 url.username = "";43720 const decoded = punycode.ucs2.decode(username);43721 for (let i = 0; i < decoded.length; ++i) {43722 url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode);43723 }43724};43725module.exports.setThePassword = function (url, password) {43726 url.password = "";43727 const decoded = punycode.ucs2.decode(password);43728 for (let i = 0; i < decoded.length; ++i) {43729 url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode);43730 }43731};43732module.exports.serializeHost = serializeHost;43733module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort;43734module.exports.serializeInteger = function (integer) {43735 return String(integer);43736};43737module.exports.parseURL = function (input, options) {43738 if (options === undefined) {43739 options = {};43740 }43741 // We don't handle blobs, so this just delegates:43742 return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride });43743};43744/***/ }),43745/***/ 3185:43746/***/ ((module) => {43747"use strict";43748module.exports.mixin = function mixin(target, source) {43749 const keys = Object.getOwnPropertyNames(source);43750 for (let i = 0; i < keys.length; ++i) {43751 Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));43752 }43753};43754module.exports.wrapperSymbol = Symbol("wrapper");43755module.exports.implSymbol = Symbol("impl");43756module.exports.wrapperForImpl = function (impl) {43757 return impl[module.exports.wrapperSymbol];43758};43759module.exports.implForWrapper = function (wrapper) {43760 return wrapper[module.exports.implSymbol];43761};43762/***/ }),43763/***/ 4091:43764/***/ ((module) => {43765"use strict";43766module.exports = function (Yallist) {43767 Yallist.prototype[Symbol.iterator] = function* () {43768 for (let walker = this.head; walker; walker = walker.next) {43769 yield walker.value43770 }43771 }43772}43773/***/ }),43774/***/ 665:43775/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {43776"use strict";43777module.exports = Yallist43778Yallist.Node = Node43779Yallist.create = Yallist43780function Yallist (list) {43781 var self = this43782 if (!(self instanceof Yallist)) {43783 self = new Yallist()43784 }43785 self.tail = null43786 self.head = null43787 self.length = 043788 if (list && typeof list.forEach === 'function') {43789 list.forEach(function (item) {43790 self.push(item)43791 })43792 } else if (arguments.length > 0) {43793 for (var i = 0, l = arguments.length; i < l; i++) {43794 self.push(arguments[i])43795 }43796 }43797 return self43798}43799Yallist.prototype.removeNode = function (node) {43800 if (node.list !== this) {43801 throw new Error('removing node which does not belong to this list')43802 }43803 var next = node.next43804 var prev = node.prev43805 if (next) {43806 next.prev = prev43807 }43808 if (prev) {43809 prev.next = next43810 }43811 if (node === this.head) {43812 this.head = next43813 }43814 if (node === this.tail) {43815 this.tail = prev43816 }43817 node.list.length--43818 node.next = null43819 node.prev = null43820 node.list = null43821 return next43822}43823Yallist.prototype.unshiftNode = function (node) {43824 if (node === this.head) {43825 return43826 }43827 if (node.list) {43828 node.list.removeNode(node)43829 }43830 var head = this.head43831 node.list = this43832 node.next = head43833 if (head) {43834 head.prev = node43835 }43836 this.head = node43837 if (!this.tail) {43838 this.tail = node43839 }43840 this.length++43841}43842Yallist.prototype.pushNode = function (node) {43843 if (node === this.tail) {43844 return43845 }43846 if (node.list) {43847 node.list.removeNode(node)43848 }43849 var tail = this.tail43850 node.list = this43851 node.prev = tail43852 if (tail) {43853 tail.next = node43854 }43855 this.tail = node43856 if (!this.head) {43857 this.head = node43858 }43859 this.length++43860}43861Yallist.prototype.push = function () {43862 for (var i = 0, l = arguments.length; i < l; i++) {43863 push(this, arguments[i])43864 }43865 return this.length43866}43867Yallist.prototype.unshift = function () {43868 for (var i = 0, l = arguments.length; i < l; i++) {43869 unshift(this, arguments[i])43870 }43871 return this.length43872}43873Yallist.prototype.pop = function () {43874 if (!this.tail) {43875 return undefined43876 }43877 var res = this.tail.value43878 this.tail = this.tail.prev43879 if (this.tail) {43880 this.tail.next = null43881 } else {43882 this.head = null43883 }43884 this.length--43885 return res43886}43887Yallist.prototype.shift = function () {43888 if (!this.head) {43889 return undefined43890 }43891 var res = this.head.value43892 this.head = this.head.next43893 if (this.head) {43894 this.head.prev = null43895 } else {43896 this.tail = null43897 }43898 this.length--43899 return res43900}43901Yallist.prototype.forEach = function (fn, thisp) {43902 thisp = thisp || this43903 for (var walker = this.head, i = 0; walker !== null; i++) {43904 fn.call(thisp, walker.value, i, this)43905 walker = walker.next43906 }43907}43908Yallist.prototype.forEachReverse = function (fn, thisp) {43909 thisp = thisp || this43910 for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {43911 fn.call(thisp, walker.value, i, this)43912 walker = walker.prev43913 }43914}43915Yallist.prototype.get = function (n) {43916 for (var i = 0, walker = this.head; walker !== null && i < n; i++) {43917 // abort out of the list early if we hit a cycle43918 walker = walker.next43919 }43920 if (i === n && walker !== null) {43921 return walker.value43922 }43923}43924Yallist.prototype.getReverse = function (n) {43925 for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {43926 // abort out of the list early if we hit a cycle43927 walker = walker.prev43928 }43929 if (i === n && walker !== null) {43930 return walker.value43931 }43932}43933Yallist.prototype.map = function (fn, thisp) {43934 thisp = thisp || this43935 var res = new Yallist()43936 for (var walker = this.head; walker !== null;) {43937 res.push(fn.call(thisp, walker.value, this))43938 walker = walker.next43939 }43940 return res43941}43942Yallist.prototype.mapReverse = function (fn, thisp) {43943 thisp = thisp || this43944 var res = new Yallist()43945 for (var walker = this.tail; walker !== null;) {43946 res.push(fn.call(thisp, walker.value, this))43947 walker = walker.prev43948 }43949 return res43950}43951Yallist.prototype.reduce = function (fn, initial) {43952 var acc43953 var walker = this.head43954 if (arguments.length > 1) {43955 acc = initial43956 } else if (this.head) {43957 walker = this.head.next43958 acc = this.head.value43959 } else {43960 throw new TypeError('Reduce of empty list with no initial value')43961 }43962 for (var i = 0; walker !== null; i++) {43963 acc = fn(acc, walker.value, i)43964 walker = walker.next43965 }43966 return acc43967}43968Yallist.prototype.reduceReverse = function (fn, initial) {43969 var acc43970 var walker = this.tail43971 if (arguments.length > 1) {43972 acc = initial43973 } else if (this.tail) {43974 walker = this.tail.prev43975 acc = this.tail.value43976 } else {43977 throw new TypeError('Reduce of empty list with no initial value')43978 }43979 for (var i = this.length - 1; walker !== null; i--) {43980 acc = fn(acc, walker.value, i)43981 walker = walker.prev43982 }43983 return acc43984}43985Yallist.prototype.toArray = function () {43986 var arr = new Array(this.length)43987 for (var i = 0, walker = this.head; walker !== null; i++) {43988 arr[i] = walker.value43989 walker = walker.next43990 }43991 return arr43992}43993Yallist.prototype.toArrayReverse = function () {43994 var arr = new Array(this.length)43995 for (var i = 0, walker = this.tail; walker !== null; i++) {43996 arr[i] = walker.value43997 walker = walker.prev43998 }43999 return arr44000}44001Yallist.prototype.slice = function (from, to) {44002 to = to || this.length44003 if (to < 0) {44004 to += this.length44005 }44006 from = from || 044007 if (from < 0) {44008 from += this.length44009 }44010 var ret = new Yallist()44011 if (to < from || to < 0) {44012 return ret44013 }44014 if (from < 0) {44015 from = 044016 }44017 if (to > this.length) {44018 to = this.length44019 }44020 for (var i = 0, walker = this.head; walker !== null && i < from; i++) {44021 walker = walker.next44022 }44023 for (; walker !== null && i < to; i++, walker = walker.next) {44024 ret.push(walker.value)44025 }44026 return ret44027}44028Yallist.prototype.sliceReverse = function (from, to) {44029 to = to || this.length44030 if (to < 0) {44031 to += this.length44032 }44033 from = from || 044034 if (from < 0) {44035 from += this.length44036 }44037 var ret = new Yallist()44038 if (to < from || to < 0) {44039 return ret44040 }44041 if (from < 0) {44042 from = 044043 }44044 if (to > this.length) {44045 to = this.length44046 }44047 for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {44048 walker = walker.prev44049 }44050 for (; walker !== null && i > from; i--, walker = walker.prev) {44051 ret.push(walker.value)44052 }44053 return ret44054}44055Yallist.prototype.splice = function (start, deleteCount, ...nodes) {44056 if (start > this.length) {44057 start = this.length - 144058 }44059 if (start < 0) {44060 start = this.length + start;44061 }44062 for (var i = 0, walker = this.head; walker !== null && i < start; i++) {44063 walker = walker.next44064 }44065 var ret = []44066 for (var i = 0; walker && i < deleteCount; i++) {44067 ret.push(walker.value)44068 walker = this.removeNode(walker)44069 }44070 if (walker === null) {44071 walker = this.tail44072 }44073 if (walker !== this.head && walker !== this.tail) {44074 walker = walker.prev44075 }44076 for (var i = 0; i < nodes.length; i++) {44077 walker = insert(this, walker, nodes[i])44078 }44079 return ret;44080}44081Yallist.prototype.reverse = function () {44082 var head = this.head44083 var tail = this.tail44084 for (var walker = head; walker !== null; walker = walker.prev) {44085 var p = walker.prev44086 walker.prev = walker.next44087 walker.next = p44088 }44089 this.head = tail44090 this.tail = head44091 return this44092}44093function insert (self, node, value) {44094 var inserted = node === self.head ?44095 new Node(value, null, node, self) :44096 new Node(value, node, node.next, self)44097 if (inserted.next === null) {44098 self.tail = inserted44099 }44100 if (inserted.prev === null) {44101 self.head = inserted44102 }44103 self.length++44104 return inserted44105}44106function push (self, item) {44107 self.tail = new Node(item, self.tail, null, self)44108 if (!self.head) {44109 self.head = self.tail44110 }44111 self.length++44112}44113function unshift (self, item) {44114 self.head = new Node(item, null, self.head, self)44115 if (!self.tail) {44116 self.tail = self.head44117 }44118 self.length++44119}44120function Node (value, prev, next, list) {44121 if (!(this instanceof Node)) {44122 return new Node(value, prev, next, list)44123 }44124 this.list = list44125 this.value = value44126 if (prev) {44127 prev.next = this44128 this.prev = prev44129 } else {44130 this.prev = null44131 }44132 if (next) {44133 next.prev = this44134 this.next = next44135 } else {44136 this.next = null44137 }44138}44139try {44140 // add if support for Symbol.iterator is present44141 __nccwpck_require__(4091)(Yallist)44142} catch (er) {}44143/***/ }),44144/***/ 1661:44145/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {44146"use strict";44147var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {44148 if (k2 === undefined) k2 = k;44149 var desc = Object.getOwnPropertyDescriptor(m, k);44150 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {44151 desc = { enumerable: true, get: function() { return m[k]; } };44152 }44153 Object.defineProperty(o, k2, desc);44154}) : (function(o, m, k, k2) {44155 if (k2 === undefined) k2 = k;44156 o[k2] = m[k];44157}));44158var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {44159 Object.defineProperty(o, "default", { enumerable: true, value: v });44160}) : function(o, v) {44161 o["default"] = v;44162});44163var __importStar = (this && this.__importStar) || function (mod) {44164 if (mod && mod.__esModule) return mod;44165 var result = {};44166 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);44167 __setModuleDefault(result, mod);44168 return result;44169};44170var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {44171 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }44172 return new (P || (P = Promise))(function (resolve, reject) {44173 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }44174 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }44175 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }44176 step((generator = generator.apply(thisArg, _arguments || [])).next());44177 });44178};44179Object.defineProperty(exports, "__esModule", ({ value: true }));44180exports.TemplateProcessor = void 0;44181const fs = __importStar(__nccwpck_require__(7147));44182const GoogleSecretManagerReference_1 = __nccwpck_require__(238);44183class TemplateProcessor {44184 constructor(googleClient) {44185 this.extractRegex = /\{\{\s*([a-zA-Z0-9-_/]+)\s*}}/g;44186 this.googleClient = googleClient;44187 }44188 processFile(file, keysPrefix) {44189 return __awaiter(this, void 0, void 0, function* () {44190 this.applySecrets(file, yield this.extractSecrets(file, keysPrefix));44191 });44192 }44193 extractSecrets(file, keysPrefix) {44194 return __awaiter(this, void 0, void 0, function* () {44195 const secretKeys = this.extractSecretKeys(file);44196 const secretsMap = {};44197 for (let key of secretKeys) {44198 secretsMap[key] = yield this.googleClient.accessSecret(new GoogleSecretManagerReference_1.GoogleSecretManagerReference(keysPrefix + key).selfLink());44199 }44200 return secretsMap;44201 });44202 }44203 applySecretsInString(input, data) {44204 let content = input;44205 for (let key in data) {44206 content = content.replace(this.replaceRegex(key), data[key]);44207 }44208 return content;44209 }44210 replaceRegex(key) {44211 return new RegExp(`\\{\\{\\s*${key}\\s*}}`, 'g');44212 }44213 extractSecretKeys(file) {44214 const content = fs.readFileSync(file).toString();44215 const matches = content.matchAll(this.extractRegex);44216 const keys = [...matches].map(m => m[1]);44217 return [...new Set(keys)];44218 }44219 applySecrets(file, data) {44220 let content = this.applySecretsInString(fs.readFileSync(file).toString(), data);44221 fs.writeFileSync(file, content);44222 }44223}44224exports.TemplateProcessor = TemplateProcessor;44225/***/ }),44226/***/ 3246:44227/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {44228"use strict";44229/*44230 * Copyright 2020 Google LLC44231 *44232 * Licensed under the Apache License, Version 2.0 (the "License");44233 * you may not use this file except in compliance with the License.44234 * You may obtain a copy of the License at44235 *44236 * http://www.apache.org/licenses/LICENSE-2.044237 *44238 * Unless required by applicable law or agreed to in writing, software44239 * distributed under the License is distributed on an "AS IS" BASIS,44240 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.44241 * See the License for the specific language governing permissions and44242 * limitations under the License.44243 *44244 * Copied from: https://github.com/google-github-actions/get-secretmanager-secrets/blob/main/src/client.ts44245 * Changes: remove deprecation message44246 */44247var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {44248 if (k2 === undefined) k2 = k;44249 var desc = Object.getOwnPropertyDescriptor(m, k);44250 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {44251 desc = { enumerable: true, get: function() { return m[k]; } };44252 }44253 Object.defineProperty(o, k2, desc);44254}) : (function(o, m, k, k2) {44255 if (k2 === undefined) k2 = k;44256 o[k2] = m[k];44257}));44258var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {44259 Object.defineProperty(o, "default", { enumerable: true, value: v });44260}) : function(o, v) {44261 o["default"] = v;44262});44263var __importStar = (this && this.__importStar) || function (mod) {44264 if (mod && mod.__esModule) return mod;44265 var result = {};44266 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);44267 __setModuleDefault(result, mod);44268 return result;44269};44270var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {44271 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }44272 return new (P || (P = Promise))(function (resolve, reject) {44273 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }44274 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }44275 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }44276 step((generator = generator.apply(thisArg, _arguments || [])).next());44277 });44278};44279Object.defineProperty(exports, "__esModule", ({ value: true }));44280exports.GoogleSecretManagerClient = void 0;44281const google_auth_library_1 = __nccwpck_require__(810);44282const actions_utils_1 = __nccwpck_require__(308);44283const http_client_1 = __nccwpck_require__(6255);44284const core = __importStar(__nccwpck_require__(2186));44285const userAgent = `google-github-actions:get-secretmanager-secrets/0.5.3`;44286/**44287 * Wraps interactions with the Google Secret Manager API, handling credential44288 * lookup and registration.44289 *44290 * @param opts list of ClientOptions44291 * @returns GoogleSecretManagerClient44292 */44293class GoogleSecretManagerClient {44294 constructor(opts) {44295 this.defaultEndpoint = 'https://secretmanager.googleapis.com/v1';44296 this.defaultScope = 'https://www.googleapis.com/auth/cloud-platform';44297 this.endpoint = (opts === null || opts === void 0 ? void 0 : opts.endpoint) || this.defaultEndpoint;44298 this.auth = new google_auth_library_1.GoogleAuth({44299 scopes: [this.defaultScope],44300 credentials: opts === null || opts === void 0 ? void 0 : opts.credentials,44301 });44302 this.client = new http_client_1.HttpClient(userAgent);44303 }44304 /**44305 * Retrieves the secret by name.44306 *44307 * @param ref String of the full secret reference.44308 * @returns string secret contents.44309 */44310 accessSecret(ref) {44311 return __awaiter(this, void 0, void 0, function* () {44312 if (!ref) {44313 throw new Error(`Secret ref "${ref}" is empty!`);44314 }44315 try {44316 const token = yield this.auth.getAccessToken();44317 const response = yield this.client.get(`${this.endpoint}/${ref}:access`, {44318 'Authorization': `Bearer ${token}`,44319 'User-Agent': userAgent,44320 });44321 const body = yield response.readBody();44322 const statusCode = response.message.statusCode || 500;44323 if (statusCode >= 400) {44324 throw new Error(`(${statusCode}) ${body}`);44325 }44326 const parsed = JSON.parse(body);44327 const b64data = parsed.payload.data;44328 if (!b64data) {44329 throw new Error(`Secret "${ref}" returned no data!`);44330 }44331 const value = (0, actions_utils_1.fromBase64)(b64data);44332 core.setSecret(value);44333 return value;44334 }44335 catch (err) {44336 const msg = (0, actions_utils_1.errorMessage)(err);44337 throw new Error(`Failed to access secret "${ref}": ${msg}`);44338 }44339 });44340 }44341}44342exports.GoogleSecretManagerClient = GoogleSecretManagerClient;44343/***/ }),44344/***/ 238:44345/***/ ((__unused_webpack_module, exports) => {44346"use strict";44347/*44348 * Copyright 2020 Google LLC44349 *44350 * Licensed under the Apache License, Version 2.0 (the "License");44351 * you may not use this file except in compliance with the License.44352 * You may obtain a copy of the License at44353 *44354 * http://www.apache.org/licenses/LICENSE-2.044355 *44356 * Unless required by applicable law or agreed to in writing, software44357 * distributed under the License is distributed on an "AS IS" BASIS,44358 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.44359 * See the License for the specific language governing permissions and44360 * limitations under the License.44361 *44362 * Copied from: https://github.com/google-github-actions/get-secretmanager-secrets/blob/3686c350e6e4d637b9d23a67a3d6d8f0120f36d4/src/reference.ts44363 */44364Object.defineProperty(exports, "__esModule", ({ value: true }));44365exports.GoogleSecretManagerReference = void 0;44366/**44367 * Parses a string of the format `outout:secret`. For example:44368 *44369 * output:project/secret/version44370 *44371 * @param s String reference to parse44372 * @returns Reference44373 */44374class GoogleSecretManagerReference {44375 constructor(s) {44376 const refParts = s.split('/');44377 switch (refParts.length) {44378 // projects/<p>/secrets/<s>/versions/<v>44379 case 6: {44380 this.project = refParts[1];44381 this.name = refParts[3];44382 this.version = refParts[5];44383 break;44384 }44385 // projects/<p>/secrets/<s>44386 case 4: {44387 this.project = refParts[1];44388 this.name = refParts[3];44389 this.version = 'latest';44390 break;44391 }44392 // <p>/<s>/<v>44393 case 3: {44394 this.project = refParts[0];44395 this.name = refParts[1];44396 this.version = refParts[2];44397 break;44398 }44399 // <p>/<s>44400 case 2: {44401 this.project = refParts[0];44402 this.name = refParts[1];44403 this.version = 'latest';44404 break;44405 }44406 default: {44407 throw new TypeError(`Invalid reference "${s}" - unknown format`);44408 }44409 }44410 }44411 /**44412 * Returns the full GCP self link.44413 *44414 * @returns String self link.44415 */44416 selfLink() {44417 return `projects/${this.project}/secrets/${this.name}/versions/${this.version}`;44418 }44419}44420exports.GoogleSecretManagerReference = GoogleSecretManagerReference;44421/***/ }),44422/***/ 399:44423/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {44424"use strict";44425var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {44426 if (k2 === undefined) k2 = k;44427 var desc = Object.getOwnPropertyDescriptor(m, k);44428 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {44429 desc = { enumerable: true, get: function() { return m[k]; } };44430 }44431 Object.defineProperty(o, k2, desc);44432}) : (function(o, m, k, k2) {44433 if (k2 === undefined) k2 = k;44434 o[k2] = m[k];44435}));44436var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {44437 Object.defineProperty(o, "default", { enumerable: true, value: v });44438}) : function(o, v) {44439 o["default"] = v;44440});44441var __importStar = (this && this.__importStar) || function (mod) {44442 if (mod && mod.__esModule) return mod;44443 var result = {};44444 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);44445 __setModuleDefault(result, mod);44446 return result;44447};44448var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {44449 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }44450 return new (P || (P = Promise))(function (resolve, reject) {44451 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }44452 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }44453 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }44454 step((generator = generator.apply(thisArg, _arguments || [])).next());44455 });44456};44457Object.defineProperty(exports, "__esModule", ({ value: true }));44458const core = __importStar(__nccwpck_require__(2186));44459const actions_utils_1 = __nccwpck_require__(308);44460const options_1 = __importStar(__nccwpck_require__(6159));44461const TemplateProcessor_1 = __nccwpck_require__(1661);44462const GoogleSecretManagerClient_1 = __nccwpck_require__(3246);44463const main = () => __awaiter(void 0, void 0, void 0, function* () {44464 const options = (0, options_1.default)();44465 if (!(0, options_1.validateOptions)(options)) {44466 process.exit(1);44467 }44468 const credentials = options.gcpCredentialsJson ? (0, actions_utils_1.parseCredential)(options.gcpCredentialsJson) : undefined;44469 const client = new GoogleSecretManagerClient_1.GoogleSecretManagerClient({ credentials });44470 const processor = new TemplateProcessor_1.TemplateProcessor(client);44471 if (options.templateFile) {44472 yield processor.processFile(options.templateFile, options.keyPrefix);44473 }44474 if (options.envFile) {44475 const result = (__nccwpck_require__(2437).config)({ path: options.envFile, override: true });44476 if (result.error || !result.parsed) {44477 core.setFailed(`failed to parse the env file: ${result.error}`);44478 process.exit(1);44479 }44480 const secrets = yield processor.extractSecrets(options.envFile, options.keyPrefix);44481 for (const key in result.parsed) {44482 core.exportVariable(key, processor.applySecretsInString(result.parsed[key], secrets));44483 }44484 yield processor.processFile(options.envFile, options.keyPrefix);44485 }44486});44487try {44488 main();44489}44490catch (error) {44491 core.setFailed(`${error}`);44492}44493/***/ }),44494/***/ 6159:...

Full Screen

Full Screen

validate.ts

Source:validate.ts Github

copy

Full Screen

...58 *59 * @publicApi60 */61export function isValidObject(data: any): boolean {62 return isValid(data) && isObject(data) && Object.keys(data).length > 0;63}64/**65 * Checks if the data is Stream.66 *67 * @param data The data to be check.68 *69 * @publicApi70 */71export function isValidStream(data: any) {72 return isValid(data) && data instanceof Stream;73}74/**75 * Checks if the data is Buffer.76 *...

Full Screen

Full Screen

main.ts

Source:main.ts Github

copy

Full Screen

...3import getOptions, {Options, validateOptions} from './options'4import {TemplateProcessor} from './TemplateProcessor';5import {GoogleSecretManagerClient} from './gcp/GoogleSecretManagerClient';6const main = async () => {7 const options: Options = getOptions()8 if (!validateOptions(options)) {9 process.exit(1)10 }11 const credentials = options.gcpCredentialsJson ? parseCredential(options.gcpCredentialsJson) : undefined12 const client = new GoogleSecretManagerClient({credentials})13 const processor = new TemplateProcessor(client)14 if (options.templateFile) {15 await processor.processFile(options.templateFile, options.keyPrefix)16 }17 if (options.envFile) {18 const result = require('dotenv').config({path: options.envFile, override: true})19 if (result.error || !result.parsed) {20 core.setFailed(`failed to parse the env file: ${result.error}`)21 process.exit(1)22 }23 const secrets = await processor.extractSecrets(options.envFile, options.keyPrefix)24 for (const key in result.parsed) {25 core.exportVariable(key, processor.applySecretsInString(result.parsed[key], secrets))26 }27 await processor.processFile(options.envFile, options.keyPrefix)28 }29}30try {31 main()32} catch (error) {33 core.setFailed(`${error}`)...

Full Screen

Full Screen

request.js

Source:request.js Github

copy

Full Screen

1import axios from 'axios'2import { MessageBox, Message } from 'element-ui'3import cookie from 'js-cookie'4// 创建axios实例5const service = axios.create({6 // baseURL: 'http://127.0.0.1:10012/',7 baseURL: 'https://houduan.yituliu.site/',8 timeout: 150000 // 请求超时时间9})10// http request 拦截器11service.interceptors.request.use(12 config => {13 config.headers['Access-Control-Max-Age'] = 8640014 // token 先不处理,后续使用时在完善15 return config16},17 err => {18 return Promise.reject(err)19})20// http response 拦截器21service.interceptors.response.use(22 response => {23 if (response.data.code !== 200) {24 Message({25 message: response.data.msg,26 type: 'error',27 duration: 5 * 100028 })29 return Promise.reject(response.data)30 } else {31 return response.data32 }33 },34 error => {35 return Promise.reject(error.response)36})...

Full Screen

Full Screen

building.js

Source:building.js Github

copy

Full Screen

1import request from '@/api/request'2const api_name = `/tool`3export default {4 //保存排班5 maaBuildingJsonCreated(data,id) {6 return request({7 url: `${api_name}/building/schedule/save?id=${id}`,8 method: 'post',9 data:data10 })11 },12 retrieveSchedule(id){13 return request({14 url: `${api_name}/building/schedule/retrieve/${id}`,15 method: 'get',16 17 })18 },19 ...

Full Screen

Full Screen

hello.js

Source:hello.js Github

copy

Full Screen

1// Next.js API route support: https://nextjs.org/docs/api-routes/introduction2export default function handler(req, res) {3 res.status(200).json({ name: 'John Doe' })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { s } = require('fast-check-monorepo');2const { s } = require('my-monorepo');3const { s } = require('fast-check-monorepo');4const { s } = require('my-monorepo');5const { s } = require('fast-check-monorepo');6const { s } = require('my-monorepo');7const { s } = require('fast-check-monorepo');8const { s } = require('my-monorepo');9const { s } = require('fast-check-monorepo');10const { s } = require('my-monorepo');11const { s } = require('fast-check-monorepo');12const { s } = require('my-monorepo');13const { s } = require('fast-check-monorepo');14const { s } = require('my-monorepo');15const { s } = require('fast-check-monorepo');16const { s } = require('my-monorepo');17const { s } = require('fast-check-monorepo');18const { s } = require('my-monorepo');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { s } from 'fast-check-monorepo';2s()3import { s } from 'fast-check-monorepo';4s();5- [s](#s)6MIT © [julien-f](

Full Screen

Using AI Code Generation

copy

Full Screen

1const s = require('fast-check-monorepo').s;2const fc = require('fast-check');3const arb = s(fc.nat, fc.string);4fc.assert(fc.property(arb, ([n, s]) => {5}));6const s = require('fast-check-monorepo').s;7const fc = require('fast-check');8const arb = s(fc.nat, fc.string);9fc.assert(fc.property(arb, ([n, s]) => {10}));

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const s = require('fast-check-monorepo').s;3test('s', () => {4 fc.assert(5 fc.property(s(), (s) => {6 expect(s).toBe('s');7 })8 );9});10const fc = require('fast-check');11const s = require('fast-check-monorepo').s;12test('s', () => {13 fc.assert(14 fc.property(s(), (s) => {15 expect(s).toBe('s');16 })17 );18});19const fc = require('fast-check');20const s = require('fast-check-monorepo').s;21test('s', () => {22 fc.assert(23 fc.property(s(), (s) => {24 expect(s).toBe('s');25 })26 );27});28const fc = require('fast-check');29const s = require('fast-check-monorepo').s;30test('s', () => {31 fc.assert(32 fc.property(s(), (s) => {33 expect(s).toBe('s');34 })35 );36});37const fc = require('fast-check');38const s = require('fast-check-monorepo').s;39test('s', () => {40 fc.assert(41 fc.property(s(), (s) => {42 expect(s).toBe('s');43 })44 );45});46const fc = require('fast-check');47const s = require('fast-check-monorepo').s;48test('s', () => {49 fc.assert(50 fc.property(s(), (s) => {51 expect(s).toBe('s');52 })53 );54});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fast-check-monorepo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful