From 91c365b0daa34874735d7e951e4d7b27b08f7fb3 Mon Sep 17 00:00:00 2001 From: Nigel Bradley Date: Fri, 29 May 2026 12:55:07 -0400 Subject: [PATCH] Add optional input no-upload and ability to run scan without uploading results to veracode platform if set to true --- README.md | 5 + action.yml | 4 + dist/index.js | 6734 +++++++++++++++++++++---------------------- src/action.ts | 1 + src/options.d.ts | 1 + src/srcclr.ts | 2 +- src/test/testRun.ts | 1 + 7 files changed, 3380 insertions(+), 3368 deletions(-) diff --git a/README.md b/README.md index ee2bd13..e9efd42 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,11 @@ __Optional__ - do not include dependency graphs in the JSON output. Default Value: __false__ +### `no-upload` +__Optional__ - run the Veracode SCA scan with `--no-upload` to skip uploading scan results to the Veracode platform. + +Default Value: __false__ + ## Examples ### Scan your repository with textual output diff --git a/action.yml b/action.yml index 87ad43d..c5beafc 100644 --- a/action.yml +++ b/action.yml @@ -57,6 +57,10 @@ inputs: description: "Run the SRCCLR with the `--no-graphs` option" required: false default: "false" + no-upload: + description: "Run the SRCCLR with the `--no-upload` option to skip uploading scan results to the Veracode platform" + required: false + default: "false" platformType: description: 'Specifies the platform environment type — use CLOUD for GitHub.com or ENTERPRISE for GitHub Enterprise Server (GHES).' default: 'CLOUD' diff --git a/dist/index.js b/dist/index.js index fbbcd4e..c41e14b 100755 --- a/dist/index.js +++ b/dist/index.js @@ -1,5 +1,4 @@ -#!/usr/bin/env node -/******/ (() => { // webpackBootstrap +#!/usr/bin/env node /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 20166: @@ -79194,430 +79193,430 @@ function copy (src) { /***/ 61860: /***/ ((module) => { -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, Symbol, Reflect, Promise, SuppressedError */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __esDecorate; -var __runInitializers; -var __propKey; -var __setFunctionName; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __classPrivateFieldIn; -var __createBinding; -var __addDisposableResource; -var __disposeResources; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } - else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; - }; - - __runInitializers = function (thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; - }; - - __propKey = function (x) { - return typeof x === "symbol" ? x : "".concat(x); - }; - - __setFunctionName = function (f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; - function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } - function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; - }; - - __classPrivateFieldIn = function (state, receiver) { - if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - }; - - __addDisposableResource = function (env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; - env.stack.push({ value: value, dispose: dispose, async: async }); - } - else if (async) { - env.stack.push({ async: true }); - } - return value; - }; - - var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; - }; - - __disposeResources = function (env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - function next() { - while (env.stack.length) { - var rec = env.stack.pop(); - try { - var result = rec.dispose && rec.dispose.call(rec.value); - if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); - } - catch (e) { - fail(e); - } - } - if (env.hasError) throw env.error; - } - return next(); - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__esDecorate", __esDecorate); - exporter("__runInitializers", __runInitializers); - exporter("__propKey", __propKey); - exporter("__setFunctionName", __setFunctionName); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); - exporter("__classPrivateFieldIn", __classPrivateFieldIn); - exporter("__addDisposableResource", __addDisposableResource); - exporter("__disposeResources", __disposeResources); -}); +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, Symbol, Reflect, Promise, SuppressedError */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __classPrivateFieldIn; +var __createBinding; +var __addDisposableResource; +var __disposeResources; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + + __addDisposableResource = function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + }; + + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + __disposeResources = function (env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); + exporter("__addDisposableResource", __addDisposableResource); + exporter("__disposeResources", __disposeResources); +}); /***/ }), @@ -104438,3045 +104437,3046 @@ exports.parseURL = __nccwpck_require__(20905).parseURL; /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; + +const punycode = __nccwpck_require__(24876); +const tr46 = __nccwpck_require__(1552); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; -const punycode = __nccwpck_require__(24876); -const tr46 = __nccwpck_require__(1552); - -const specialSchemes = { - ftp: 21, - file: null, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443 -}; - -const failure = Symbol("failure"); - -function countSymbols(str) { - return punycode.ucs2.decode(str).length; -} - -function at(input, idx) { - const c = input[idx]; - return isNaN(c) ? undefined : String.fromCodePoint(c); -} - -function isASCIIDigit(c) { - return c >= 0x30 && c <= 0x39; -} - -function isASCIIAlpha(c) { - return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); -} - -function isASCIIAlphanumeric(c) { - return isASCIIAlpha(c) || isASCIIDigit(c); -} - -function isASCIIHex(c) { - return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); -} -function isSingleDot(buffer) { - return buffer === "." || buffer.toLowerCase() === "%2e"; -} +/***/ }), -function isDoubleDot(buffer) { - buffer = buffer.toLowerCase(); - return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; -} +/***/ 39857: +/***/ ((module) => { -function isWindowsDriveLetterCodePoints(cp1, cp2) { - return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); -} +"use strict"; -function isWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); -} -function isNormalizedWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; -} +module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +}; -function containsForbiddenHostCodePoint(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; -} +module.exports.wrapperSymbol = Symbol("wrapper"); +module.exports.implSymbol = Symbol("impl"); -function containsForbiddenHostCodePointExcludingPercent(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; -} +module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; +}; -function isSpecialScheme(scheme) { - return specialSchemes[scheme] !== undefined; -} +module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; +}; -function isSpecial(url) { - return isSpecialScheme(url.scheme); -} -function defaultPort(scheme) { - return specialSchemes[scheme]; -} -function percentEncode(c) { - let hex = c.toString(16).toUpperCase(); - if (hex.length === 1) { - hex = "0" + hex; - } +/***/ }), - return "%" + hex; -} +/***/ 58264: +/***/ ((module) => { -function utf8PercentEncode(c) { - const buf = new Buffer(c); +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) - let str = ""; + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') - for (let i = 0; i < buf.length; ++i) { - str += percentEncode(buf[i]); - } + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) - return str; -} + return wrapper -function utf8PercentDecode(str) { - const input = new Buffer(str); - const output = []; - for (let i = 0; i < input.length; ++i) { - if (input[i] !== 37) { - output.push(input[i]); - } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { - output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); - i += 2; - } else { - output.push(input[i]); + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) } + return ret } - return new Buffer(output).toString(); -} - -function isC0ControlPercentEncode(c) { - return c <= 0x1F || c > 0x7E; -} - -const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); -function isPathPercentEncode(c) { - return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); } -const extraUserinfoPercentEncodeSet = - new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); -function isUserinfoPercentEncode(c) { - return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); -} -function percentEncodeChar(c, encodeSetPredicate) { - const cStr = String.fromCodePoint(c); +/***/ }), - if (encodeSetPredicate(c)) { - return utf8PercentEncode(cStr); - } +/***/ 41622: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return cStr; -} +/** + * ZipStream + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-zip-stream/blob/master/LICENSE} + * @copyright (c) 2014 Chris Talkington, contributors. + */ +var inherits = (__nccwpck_require__(39023).inherits); -function parseIPv4Number(input) { - let R = 10; +var ZipArchiveOutputStream = (__nccwpck_require__(47544).ZipArchiveOutputStream); +var ZipArchiveEntry = (__nccwpck_require__(47544).ZipArchiveEntry); - if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { - input = input.substring(2); - R = 16; - } else if (input.length >= 2 && input.charAt(0) === "0") { - input = input.substring(1); - R = 8; - } +var util = __nccwpck_require__(53296); - if (input === "") { - return 0; +/** + * @constructor + * @extends external:ZipArchiveOutputStream + * @param {Object} [options] + * @param {String} [options.comment] Sets the zip archive comment. + * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC. + * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers. + * @param {Boolean} [options.store=false] Sets the compression method to STORE. + * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + * to control compression. + */ +var ZipStream = module.exports = function(options) { + if (!(this instanceof ZipStream)) { + return new ZipStream(options); } - const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); - if (regex.test(input)) { - return failure; - } + options = this.options = options || {}; + options.zlib = options.zlib || {}; - return parseInt(input, R); -} + ZipArchiveOutputStream.call(this, options); -function parseIPv4(input) { - const parts = input.split("."); - if (parts[parts.length - 1] === "") { - if (parts.length > 1) { - parts.pop(); - } + if (typeof options.level === 'number' && options.level >= 0) { + options.zlib.level = options.level; + delete options.level; } - if (parts.length > 4) { - return input; + if (!options.forceZip64 && typeof options.zlib.level === 'number' && options.zlib.level === 0) { + options.store = true; } - const numbers = []; - for (const part of parts) { - if (part === "") { - return input; - } - const n = parseIPv4Number(part); - if (n === failure) { - return input; - } - - numbers.push(n); - } + options.namePrependSlash = options.namePrependSlash || false; - for (let i = 0; i < numbers.length - 1; ++i) { - if (numbers[i] > 255) { - return failure; - } - } - if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { - return failure; + if (options.comment && options.comment.length > 0) { + this.setComment(options.comment); } +}; - let ipv4 = numbers.pop(); - let counter = 0; +inherits(ZipStream, ZipArchiveOutputStream); - for (const n of numbers) { - ipv4 += n * Math.pow(256, 3 - counter); - ++counter; - } +/** + * Normalizes entry data with fallbacks for key properties. + * + * @private + * @param {Object} data + * @return {Object} + */ +ZipStream.prototype._normalizeFileData = function(data) { + data = util.defaults(data, { + type: 'file', + name: null, + namePrependSlash: this.options.namePrependSlash, + linkname: null, + date: null, + mode: null, + store: this.options.store, + comment: '' + }); - return ipv4; -} + var isDir = data.type === 'directory'; + var isSymlink = data.type === 'symlink'; -function serializeIPv4(address) { - let output = ""; - let n = address; + if (data.name) { + data.name = util.sanitizePath(data.name); - for (let i = 1; i <= 4; ++i) { - output = String(n % 256) + output; - if (i !== 4) { - output = "." + output; + if (!isSymlink && data.name.slice(-1) === '/') { + isDir = true; + data.type = 'directory'; + } else if (isDir) { + data.name += '/'; } - n = Math.floor(n / 256); } - return output; -} - -function parseIPv6(input) { - const address = [0, 0, 0, 0, 0, 0, 0, 0]; - let pieceIndex = 0; - let compress = null; - let pointer = 0; - - input = punycode.ucs2.decode(input); - - if (input[pointer] === 58) { - if (input[pointer + 1] !== 58) { - return failure; - } - - pointer += 2; - ++pieceIndex; - compress = pieceIndex; + if (isDir || isSymlink) { + data.store = true; } - while (pointer < input.length) { - if (pieceIndex === 8) { - return failure; - } - - if (input[pointer] === 58) { - if (compress !== null) { - return failure; - } - ++pointer; - ++pieceIndex; - compress = pieceIndex; - continue; - } - - let value = 0; - let length = 0; - - while (length < 4 && isASCIIHex(input[pointer])) { - value = value * 0x10 + parseInt(at(input, pointer), 16); - ++pointer; - ++length; - } - - if (input[pointer] === 46) { - if (length === 0) { - return failure; - } - - pointer -= length; - - if (pieceIndex > 6) { - return failure; - } - - let numbersSeen = 0; - - while (input[pointer] !== undefined) { - let ipv4Piece = null; - - if (numbersSeen > 0) { - if (input[pointer] === 46 && numbersSeen < 4) { - ++pointer; - } else { - return failure; - } - } - - if (!isASCIIDigit(input[pointer])) { - return failure; - } - - while (isASCIIDigit(input[pointer])) { - const number = parseInt(at(input, pointer)); - if (ipv4Piece === null) { - ipv4Piece = number; - } else if (ipv4Piece === 0) { - return failure; - } else { - ipv4Piece = ipv4Piece * 10 + number; - } - if (ipv4Piece > 255) { - return failure; - } - ++pointer; - } - - address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; - - ++numbersSeen; - - if (numbersSeen === 2 || numbersSeen === 4) { - ++pieceIndex; - } - } - - if (numbersSeen !== 4) { - return failure; - } - - break; - } else if (input[pointer] === 58) { - ++pointer; - if (input[pointer] === undefined) { - return failure; - } - } else if (input[pointer] !== undefined) { - return failure; - } + data.date = util.dateify(data.date); - address[pieceIndex] = value; - ++pieceIndex; - } + return data; +}; - if (compress !== null) { - let swaps = pieceIndex - compress; - pieceIndex = 7; - while (pieceIndex !== 0 && swaps > 0) { - const temp = address[compress + swaps - 1]; - address[compress + swaps - 1] = address[pieceIndex]; - address[pieceIndex] = temp; - --pieceIndex; - --swaps; - } - } else if (compress === null && pieceIndex !== 8) { - return failure; +/** + * Appends an entry given an input source (text string, buffer, or stream). + * + * @param {(Buffer|Stream|String)} source The input source. + * @param {Object} data + * @param {String} data.name Sets the entry name including internal path. + * @param {String} [data.comment] Sets the entry comment. + * @param {(String|Date)} [data.date=NOW()] Sets the entry date. + * @param {Number} [data.mode=D:0755/F:0644] Sets the entry permissions. + * @param {Boolean} [data.store=options.store] Sets the compression method to STORE. + * @param {String} [data.type=file] Sets the entry type. Defaults to `directory` + * if name ends with trailing slash. + * @param {Function} callback + * @return this + */ +ZipStream.prototype.entry = function(source, data, callback) { + if (typeof callback !== 'function') { + callback = this._emitErrorCallback.bind(this); } - return address; -} - -function serializeIPv6(address) { - let output = ""; - const seqResult = findLongestZeroSequence(address); - const compress = seqResult.idx; - let ignore0 = false; - - for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { - if (ignore0 && address[pieceIndex] === 0) { - continue; - } else if (ignore0) { - ignore0 = false; - } - - if (compress === pieceIndex) { - const separator = pieceIndex === 0 ? "::" : ":"; - output += separator; - ignore0 = true; - continue; - } - - output += address[pieceIndex].toString(16); + data = this._normalizeFileData(data); - if (pieceIndex !== 7) { - output += ":"; - } + if (data.type !== 'file' && data.type !== 'directory' && data.type !== 'symlink') { + callback(new Error(data.type + ' entries not currently supported')); + return; } - return output; -} - -function parseHost(input, isSpecialArg) { - if (input[0] === "[") { - if (input[input.length - 1] !== "]") { - return failure; - } - - return parseIPv6(input.substring(1, input.length - 1)); + if (typeof data.name !== 'string' || data.name.length === 0) { + callback(new Error('entry name must be a non-empty string value')); + return; } - if (!isSpecialArg) { - return parseOpaqueHost(input); + if (data.type === 'symlink' && typeof data.linkname !== 'string') { + callback(new Error('entry linkname must be a non-empty string value when type equals symlink')); + return; } - const domain = utf8PercentDecode(input); - const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); - if (asciiDomain === null) { - return failure; - } + var entry = new ZipArchiveEntry(data.name); + entry.setTime(data.date, this.options.forceLocalTime); - if (containsForbiddenHostCodePoint(asciiDomain)) { - return failure; + if (data.namePrependSlash) { + entry.setName(data.name, true); } - const ipv4Host = parseIPv4(asciiDomain); - if (typeof ipv4Host === "number" || ipv4Host === failure) { - return ipv4Host; + if (data.store) { + entry.setMethod(0); } - return asciiDomain; -} - -function parseOpaqueHost(input) { - if (containsForbiddenHostCodePointExcludingPercent(input)) { - return failure; + if (data.comment.length > 0) { + entry.setComment(data.comment); } - let output = ""; - const decoded = punycode.ucs2.decode(input); - for (let i = 0; i < decoded.length; ++i) { - output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + if (data.type === 'symlink' && typeof data.mode !== 'number') { + data.mode = 40960; // 0120000 } - return output; -} - -function findLongestZeroSequence(arr) { - let maxIdx = null; - let maxLen = 1; // only find elements > 1 - let currStart = null; - let currLen = 0; - for (let i = 0; i < arr.length; ++i) { - if (arr[i] !== 0) { - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - currStart = null; - currLen = 0; - } else { - if (currStart === null) { - currStart = i; - } - ++currLen; + if (typeof data.mode === 'number') { + if (data.type === 'symlink') { + data.mode |= 40960; } - } - - // if trailing zeros - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - return { - idx: maxIdx, - len: maxLen - }; -} - -function serializeHost(host) { - if (typeof host === "number") { - return serializeIPv4(host); - } - // IPv6 serializer - if (host instanceof Array) { - return "[" + serializeIPv6(host) + "]"; - } - - return host; -} - -function trimControlChars(url) { - return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); -} - -function trimTabAndNewline(url) { - return url.replace(/\u0009|\u000A|\u000D/g, ""); -} - -function shortenPath(url) { - const path = url.path; - if (path.length === 0) { - return; - } - if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { - return; + entry.setUnixMode(data.mode); } - path.pop(); -} - -function includesCredentials(url) { - return url.username !== "" || url.password !== ""; -} - -function cannotHaveAUsernamePasswordPort(url) { - return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; -} - -function isNormalizedWindowsDriveLetter(string) { - return /^[A-Za-z]:$/.test(string); -} - -function URLStateMachine(input, base, encodingOverride, url, stateOverride) { - this.pointer = 0; - this.input = input; - this.base = base || null; - this.encodingOverride = encodingOverride || "utf-8"; - this.stateOverride = stateOverride; - this.url = url; - this.failure = false; - this.parseError = false; - - if (!this.url) { - this.url = { - scheme: "", - username: "", - password: "", - host: null, - port: null, - path: [], - query: null, - fragment: null, - - cannotBeABaseURL: false - }; - - const res = trimControlChars(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; + if (data.type === 'symlink' && typeof data.linkname === 'string') { + source = Buffer.from(data.linkname); } - const res = trimTabAndNewline(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; + return ZipArchiveOutputStream.prototype.entry.call(this, entry, source, callback); +}; - this.state = stateOverride || "scheme start"; +/** + * Finalizes the instance and prevents further appending to the archive + * structure (queue will continue til drained). + * + * @return void + */ +ZipStream.prototype.finalize = function() { + this.finish(); +}; - this.buffer = ""; - this.atFlag = false; - this.arrFlag = false; - this.passwordTokenSeenFlag = false; +/** + * Returns the current number of bytes written to this stream. + * @function ZipStream#getBytesWritten + * @returns {Number} + */ - this.input = punycode.ucs2.decode(this.input); +/** + * Compress Commons ZipArchiveOutputStream + * @external ZipArchiveOutputStream + * @see {@link https://github.com/archiverjs/node-compress-commons} + */ - for (; this.pointer <= this.input.length; ++this.pointer) { - const c = this.input[this.pointer]; - const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); - // exec state machine - const ret = this["parse " + this.state](c, cStr); - if (!ret) { - break; // terminate algorithm - } else if (ret === failure) { - this.failure = true; - break; - } - } -} +/***/ }), -URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { - if (isASCIIAlpha(c)) { - this.buffer += cStr.toLowerCase(); - this.state = "scheme"; - } else if (!this.stateOverride) { - this.state = "no scheme"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } +/***/ 22929: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return true; -}; +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(37484)); +const srcclr_1 = __nccwpck_require__(47038); +const options = { + quick: core.getBooleanInput('quick'), + updateAdvisor: core.getBooleanInput('update_advisor'), + minCVSSForIssue: parseFloat(core.getInput('min-cvss-for-issue')) || 0, + url: core.getInput('url'), + github_token: core.getInput('github_token', { required: true }), + createIssues: core.getBooleanInput('create-issues'), + allowDirty: core.getBooleanInput('allow-dirty'), + failOnCVSS: parseFloat(core.getInput('fail-on-cvss')) || 10, + path: core.getInput('path', { trimWhitespace: true }) || '.', + debug: core.getBooleanInput('debug'), + "skip-vms": core.getBooleanInput('skip-vms'), + "no-graphs": core.getBooleanInput('no-graphs'), + noUpload: core.getBooleanInput('no-upload'), + recursive: core.getBooleanInput('recursive'), + "skip-collectors": core.getInput('skip-collectors').split(','), + "scan-collectors": core.getInput('scan-collectors').split(','), + platformType: core.getInput('platformType'), + breakBuildOnPolicyFindings: core.getInput('breakBuildOnPolicyFindings'), + scaFixEnabled: core.getBooleanInput('sca_fix_enabled'), + profileName: core.getInput('profile_name'), + prNumber: parseInt(core.getInput('pr_number'), 10) +}; +try { + (0, srcclr_1.runAction)(options); +} +catch (error) { + core.setFailed(error instanceof Error ? error.message : String(error)); +} -URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { - if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { - this.buffer += cStr.toLowerCase(); - } else if (c === 58) { - if (this.stateOverride) { - if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { - return false; - } - if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { - return false; - } +/***/ }), - if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { - return false; - } +/***/ 39015: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { - return false; - } - } - this.url.scheme = this.buffer; - this.buffer = ""; - if (this.stateOverride) { - return false; - } - if (this.url.scheme === "file") { - if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { - this.parseError = true; - } - this.state = "file"; - } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { - this.state = "special relative or authority"; - } else if (isSpecial(this.url)) { - this.state = "special authority slashes"; - } else if (this.input[this.pointer + 1] === 47) { - this.state = "path or authority"; - ++this.pointer; - } else { - this.url.cannotBeABaseURL = true; - this.url.path.push(""); - this.state = "cannot-be-a-base-URL path"; - } - } else if (!this.stateOverride) { - this.buffer = ""; - this.state = "no scheme"; - this.pointer = -1; - } else { - this.parseError = true; - return failure; - } +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GithubHandler = void 0; +const github_1 = __nccwpck_require__(93228); +const labels_1 = __nccwpck_require__(94584); +const ISSUES_PULL_COUNT = 100; +class GithubHandler { + constructor(token) { + this.token = token; + const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; + this.client = (0, github_1.getOctokit)(token, { baseUrl }); + } + getVeracodeLabel() { + return __awaiter(this, void 0, void 0, function* () { + console.log('getVeracodeLabel - START'); + let veracodeLabel = {}; + try { + veracodeLabel = yield this.client.rest + .issues.getLabel({ + owner: github_1.context.repo.owner, + repo: github_1.context.repo.repo, + name: labels_1.VERACODE_LABEL.name + }); + console.log('Veracode Labels already exist'); + } + catch (e) { + console.log('======================= ERROR ==============================='); + console.log(e); + } + console.log('getVeracodeLabel - END'); + return veracodeLabel; + }); + } + createVeracodeLabels() { + return __awaiter(this, void 0, void 0, function* () { + console.log('createVeracodeLabels - END'); + try { + // Creating the severity labels + for (var label of Object.values(labels_1.SEVERITY_LABELS)) { + yield this.client.rest.issues.createLabel({ + owner: github_1.context.repo.owner, + repo: github_1.context.repo.repo, + name: label.name, + color: label.color, + description: label.description + }); + } + // Creating the base label + yield this.client.rest.issues.createLabel({ + owner: github_1.context.repo.owner, + repo: github_1.context.repo.repo, + name: labels_1.VERACODE_LABEL.name, + color: labels_1.VERACODE_LABEL.color, + description: labels_1.VERACODE_LABEL.description + }); + //this.client.paginate(this.client.graphql,""); + } + catch (e) { + console.log('======================= ERROR ==============================='); + console.log(e); + } + console.log('createVeracodeLabels - END'); + }); + } + createIssue(reportedIssue) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.client.rest.issues.create({ + owner: github_1.context.repo.owner, + repo: github_1.context.repo.repo, + title: reportedIssue.title, + body: reportedIssue.description, + labels: reportedIssue.labels + }); + }); + } + listExistingOpenIssues() { + return __awaiter(this, void 0, void 0, function* () { + console.log('getIssues - START'); + const query = `query IsslesTitle($organization: String!,$repo: String!, $count: Int!,$label: String!) { + repository(name: $repo, owner: $organization) { + issues(first: $count,filterBy: {labels: [$label], states: OPEN}) { + edges { + node { + title + number + } + } + pageInfo { + hasNextPage + endCursor + } + } + } + }`; + const nextQuery = `query IsslesTitle($organization: String!,$repo: String!, $count: Int!, $endCursor: String!,$label: String!) { + repository(name: $repo, owner: $organization) { + issues(first: $count,after: $endCursor,filterBy: {labels: [$label], states: OPEN}) { + edges { + node { + title + number + } + } + pageInfo { + hasNextPage + endCursor + } + } + } + }`; + let issues = []; + try { + let issuesRes = yield this.client.graphql({ + headers: { + authorization: `token ${this.token}` + }, + query, + count: ISSUES_PULL_COUNT, + organization: github_1.context.repo.owner, + repo: github_1.context.repo.repo, + label: labels_1.VERACODE_LABEL.name + }); + issues = issues.concat(issuesRes.repository.issues.edges); + while (issuesRes.repository.issues.pageInfo.hasNextPage) { + console.log('iterating for fetching more related open issues'); + const endCursor = issuesRes.repository.issues.pageInfo.endCursor; + issuesRes = yield this.client.graphql({ + headers: { + authorization: `token ${this.token}` + }, + query: nextQuery, + count: ISSUES_PULL_COUNT, + endCursor, + organization: github_1.context.repo.owner, + repo: github_1.context.repo.repo, + label: labels_1.VERACODE_LABEL.name + }); + issues = issues.concat(issuesRes.repository.issues.edges); + } + } + catch (e) { + console.log('======================= ERROR ==============================='); + console.log(e); + } + console.log('getIssues - END'); + return issues; + }); + } +} +exports.GithubHandler = GithubHandler; - return true; -}; -URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { - if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { - return failure; - } else if (this.base.cannotBeABaseURL && c === 35) { - this.url.scheme = this.base.scheme; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.url.cannotBeABaseURL = true; - this.state = "fragment"; - } else if (this.base.scheme === "file") { - this.state = "file"; - --this.pointer; - } else { - this.state = "relative"; - --this.pointer; - } +/***/ }), - return true; -}; +/***/ 79407: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "relative"; - --this.pointer; - } +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.runText = exports.run = exports.SCA_OUTPUT_FILE = void 0; +//import {getOctokit,context} from '@actions/github'; +const fs_1 = __nccwpck_require__(79896); +const labels_1 = __nccwpck_require__(94584); +const githubRequestHandler_1 = __nccwpck_require__(39015); +const core = __importStar(__nccwpck_require__(37484)); +const { request } = __nccwpck_require__(66255); +const github = __nccwpck_require__(93228); +exports.SCA_OUTPUT_FILE = 'scaResults.json'; +const librariesWithIssues = {}; +let githubHandler; +function run(options, msgFunc) { + return __awaiter(this, void 0, void 0, function* () { + if (!(0, fs_1.existsSync)(exports.SCA_OUTPUT_FILE)) { + core.setFailed('SCA Output file was not found - cannot proceed with creating issues.\nPlease check prior execution errors.'); + return; + } + const scaResultsTxt = (0, fs_1.readFileSync)(exports.SCA_OUTPUT_FILE); + const scaResJson = JSON.parse(scaResultsTxt.toString('utf-8')); + const vulnerabilities = scaResJson.records[0].vulnerabilities; + const libraries = scaResJson.records[0].libraries; + vulnerabilities + //.filter((vul:any) => vul.cvssScore>=options.minCVSSForIssue) + .forEach((vulr) => { + //console.log('------- in each ------'); + const libref = vulr.libraries[0]._links.ref; + //core.info('libref: '+libref) + const libId = libref.split('/')[4]; + //core.info('libId: '+libId) + const lib = libraries[libId]; + //core.info('lib: '+JSON.stringify(lib)) + const details = createIssueDetails(vulr, lib); + addIssueToLibrary(libId, lib, details); + }); + githubHandler = new githubRequestHandler_1.GithubHandler(options.github_token); + if (Object.keys(librariesWithIssues).length > 0) { + yield verifyLabels(); + yield syncExistingOpenIssues(options); + // check for failing the step + /* + const failingVul = vulnerabilities.filter(vul => vul.cvssScore>=options.failOnCVSS); + if (failingVul.length>0) { + core.setFailed(`Found Vulnerability with CVSS equal or greater than ${options.failOnCVSS}`); + } else { + msgFunc(`No 3rd party library found with Vulnerability of CVSS equal or greater than ${options.failOnCVSS}`); + } + */ + } + msgFunc(`Scan finished.\nFull Report Details: ${scaResJson.records[0].metadata.report}`); + }); +} +exports.run = run; +const addIssueToLibrary = (libId, lib, details) => { + let libWithIssues = librariesWithIssues[libId] || { lib, issues: [] }; + libWithIssues.issues.push(details); + librariesWithIssues[libId] = libWithIssues; +}; +const syncExistingOpenIssues = (options) => __awaiter(void 0, void 0, void 0, function* () { + const existingOpenIssues = yield githubHandler.listExistingOpenIssues(); + const lenghtOfLibs = Object.keys(librariesWithIssues).length; + core.info('Libraries with issues found: ' + lenghtOfLibs); + let createIssue; + let openIssueTitle; + let openIssueNumber; + //Check if we run on a PR + core.info('check if we run on a pull request'); + let pullRequest = process.env.GITHUB_REF; + let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); + const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; + const customRequest = request.defaults({ + baseUrl + }); + for (var key in librariesWithIssues) { + core.info('Library ' + key + ' - ' + librariesWithIssues[key]['lib']['name']); + var issueLength = Object.keys(librariesWithIssues[key]['issues']).length; + core.info(issueLength + ' Issues found on Library'); + for (let j = 0; j < issueLength; j++) { + var libraryTitle = librariesWithIssues[key]['issues'][j]['title']; + core.info('Isuse Title ' + j + ': ' + libraryTitle); + var openIssueLenght = existingOpenIssues.length; + core.info("Open issues found: " + openIssueLenght); + for (let k = 0; k < openIssueLenght; k++) { + openIssueTitle = existingOpenIssues[k]['node']['title']; + openIssueNumber = existingOpenIssues[k]['node']['number']; + //core.info('Open Isssue: '+openIssueTitle+' --- '+openIssueNumber) + if (libraryTitle == openIssueTitle) { + core.info('Issue \n' + libraryTitle + '\n' + openIssueTitle + '\nalready exists - skipping'); + createIssue = false; + break; + } + } + if (createIssue == false) { + core.info('Issue already exists - skipping --- ' + libraryTitle + ' ---- ' + openIssueTitle); + if (isPR >= 1) { + core.info('We run on a PR, link issue to PR'); + let pr_context = github.context; + let pr_commentID = pr_context.payload.pull_request.number; + var authToken = 'token ' + options.github_token; + const owner = github.context.repo.owner; + const repo = github.context.repo.repo; + var pr_link = `Veracode issue link to PR: https://github.com/` + owner + `/` + repo + `/pull/` + pr_commentID; + console.log('Adding PR to the issue now.'); + yield customRequest('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', { + headers: { + authorization: authToken + }, + owner: owner, + repo: repo, + issue_number: openIssueNumber, + data: { + "body": pr_link + } + }); + } + } + else { + core.info('Issue needs to be created. --- ' + libraryTitle); + const ghResponse = yield githubHandler.createIssue(librariesWithIssues[key]['issues'][j]); + //core.info('Issue creation response: '+JSON.stringify(ghResponse)) + var issueNumber = ghResponse.data.number; + if (isPR >= 1) { + core.info('We run on a PR, link issue to PR'); + let pr_context = github.context; + let pr_commentID = pr_context.payload.pull_request.number; + var authToken = 'token ' + options.github_token; + const owner = github.context.repo.owner; + const repo = github.context.repo.repo; + var pr_link = `Veracode issue link to PR: https://github.com/` + owner + `/` + repo + `/pull/` + pr_commentID; + console.log('Adding PR to the issue now.'); + yield customRequest('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', { + headers: { + authorization: authToken + }, + owner: owner, + repo: repo, + issue_number: issueNumber, + data: { + "body": pr_link + } + }); + } + } + } + } +}); +const createIssueDetails = (vuln, lib) => { + const vulnLibDetails = vuln.libraries[0].details[0]; + const sevLabel = getSeverityName(vuln.cvssScore); + const myCVE = vuln.cve || '0000-0000'; + const versionsFound = lib.versions.map(version => version.version); + var title = "CVE: " + myCVE + " found in " + lib.name + " - Version: " + versionsFound + " [" + vuln.language + "]"; + var labels = [labels_1.VERACODE_LABEL, sevLabel]; + var description = "Veracode Software Composition Analysis" + + " \n===============================\n" + + " \n Attribute | Details" + + " \n| --- | --- |" + + " \nLibrary | " + lib.name + + " \nDescription | " + lib.description + + " \nLanguage | " + vuln.language + + " \nVulnerability | " + vuln.title + + " \nVulnerability description | " + (vuln.overview ? vuln.overview.trim() : "") + + " \nCVE | " + vuln.cve + + " \nCVSS score | " + vuln.cvssScore + + " \nVulnerability present in version/s | " + vulnLibDetails.versionRange + + " \nFound library version/s | " + versionsFound + + " \nVulnerability fixed in version | " + vulnLibDetails.updateToVersion + + " \nLibrary latest version | " + lib.latestRelease + + " \nFix | " + vulnLibDetails.fixText + + " \n" + + " \nLinks:" + + " \n- " + lib.versions[0]._links.html + + " \n- " + vuln._links.html + + " \n- Patch: " + vulnLibDetails.patch; + return { + title, description, labels + }; +}; +const getSeverityName = (cvss) => { + var weight = Math.floor(cvss); + let label = labels_1.SEVERITY_LABELS.Unknown; + if (weight == 0) + label = labels_1.SEVERITY_LABELS.Informational; + else if (weight >= 0.1 && weight < 1.9) + label = labels_1.SEVERITY_LABELS['Very Low']; + else if (weight >= 2.0 && weight < 3.9) + label = labels_1.SEVERITY_LABELS.Low; + else if (weight >= 4.0 && weight < 5.9) + label = labels_1.SEVERITY_LABELS.Medium; + else if (weight >= 6.0 && weight < 7.9) + label = labels_1.SEVERITY_LABELS.High; + else if (weight >= 8.0) + label = labels_1.SEVERITY_LABELS['Very High']; + return label; +}; +const verifyLabels = () => __awaiter(void 0, void 0, void 0, function* () { + const baseLabel = yield githubHandler.getVeracodeLabel(); + if (!baseLabel || !baseLabel.data) { + yield githubHandler.createVeracodeLabels(); + } +}); +function runText(options, output, msgFunc) { + return __awaiter(this, void 0, void 0, function* () { + const vulnerabilityLinePattern = /^\d+\s+Vulnerability\s+([\d\.]+)\s+.+/; + const splitLines = output.split(/\r?\n/); + let failed = false; + for (var line of splitLines) { + if (vulnerabilityLinePattern.test(line)) { + const match = line.match(vulnerabilityLinePattern); + if (match) { + const cvss = parseFloat(match[1]); + if (cvss >= options.failOnCVSS) { + failed = true; + } + } + } + } + if (failed) { + core.setFailed(`Found Vulnerability with CVSS equal or greater than ${options.failOnCVSS}`); + } + else { + msgFunc(`No 3rd party library found with Vulnerability of CVSS equal or greater than ${options.failOnCVSS}`); + } + }); +} +exports.runText = runText; - return true; -}; -URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { - if (c === 47) { - this.state = "authority"; - } else { - this.state = "path"; - --this.pointer; - } +/***/ }), - return true; -}; +/***/ 94584: +/***/ ((__unused_webpack_module, exports) => { -URLStateMachine.prototype["parse relative"] = function parseRelative(c) { - this.url.scheme = this.base.scheme; - if (isNaN(c)) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 47) { - this.state = "relative slash"; - } else if (c === 63) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else if (isSpecial(this.url) && c === 92) { - this.parseError = true; - this.state = "relative slash"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(0, this.base.path.length - 1); +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VERACODE_LABEL = exports.SEVERITY_LABELS = void 0; +exports.SEVERITY_LABELS = { + "Very High": { + 'name': 'Severity: Very High', + 'color': 'A90533', + 'description': 'Very High severity', + }, + High: { + 'name': 'Severity: High', + 'color': 'DD3B35', + 'description': 'High severity' + }, + Medium: { + 'name': 'Severity: Medium', + 'color': 'FF7D00', + 'description': 'Medium severity' + }, + Low: { + 'name': 'Severity: Low', + 'color': 'FFBE00', + 'description': 'Low severity' + }, + "Very Low": { + 'name': 'Severity: Very Low', + 'color': '33ADD2', + 'description': 'Very Low severity', + }, + Informational: { + 'name': 'Severity: Informational', + 'color': '0270D3', + 'description': 'Informational severity', + }, + Unknown: { + 'name': 'Severity: Unknown', + 'color': '0270D3', + 'description': 'Unknown severity', + } +}; +exports.VERACODE_LABEL = { + 'name': 'Veracode Dependency Scanning', + 'color': '0AA2DC', + 'description': 'A Veracode identified vulnerability' +}; - this.state = "path"; - --this.pointer; - } - return true; -}; +/***/ }), -URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { - if (isSpecial(this.url) && (c === 47 || c === 92)) { - if (c === 92) { - this.parseError = true; - } - this.state = "special authority ignore slashes"; - } else if (c === 47) { - this.state = "authority"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "special authority ignore slashes"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { - if (c !== 47 && c !== 92) { - this.state = "authority"; - --this.pointer; - } else { - this.parseError = true; - } - - return true; -}; - -URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { - if (c === 64) { - this.parseError = true; - if (this.atFlag) { - this.buffer = "%40" + this.buffer; - } - this.atFlag = true; - - // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars - const len = countSymbols(this.buffer); - for (let pointer = 0; pointer < len; ++pointer) { - const codePoint = this.buffer.codePointAt(pointer); - - if (codePoint === 58 && !this.passwordTokenSeenFlag) { - this.passwordTokenSeenFlag = true; - continue; - } - const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); - if (this.passwordTokenSeenFlag) { - this.url.password += encodedCodePoints; - } else { - this.url.username += encodedCodePoints; - } - } - this.buffer = ""; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - if (this.atFlag && this.buffer === "") { - this.parseError = true; - return failure; - } - this.pointer -= countSymbols(this.buffer) + 1; - this.buffer = ""; - this.state = "host"; - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse hostname"] = -URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { - if (this.stateOverride && this.url.scheme === "file") { - --this.pointer; - this.state = "file host"; - } else if (c === 58 && !this.arrFlag) { - if (this.buffer === "") { - this.parseError = true; - return failure; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "port"; - if (this.stateOverride === "hostname") { - return false; - } - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - --this.pointer; - if (isSpecial(this.url) && this.buffer === "") { - this.parseError = true; - return failure; - } else if (this.stateOverride && this.buffer === "" && - (includesCredentials(this.url) || this.url.port !== null)) { - this.parseError = true; - return false; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "path start"; - if (this.stateOverride) { - return false; - } - } else { - if (c === 91) { - this.arrFlag = true; - } else if (c === 93) { - this.arrFlag = false; - } - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { - if (isASCIIDigit(c)) { - this.buffer += cStr; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92) || - this.stateOverride) { - if (this.buffer !== "") { - const port = parseInt(this.buffer); - if (port > Math.pow(2, 16) - 1) { - this.parseError = true; - return failure; - } - this.url.port = port === defaultPort(this.url.scheme) ? null : port; - this.buffer = ""; - } - if (this.stateOverride) { - return false; - } - this.state = "path start"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); - -URLStateMachine.prototype["parse file"] = function parseFile(c) { - this.url.scheme = "file"; - - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file slash"; - } else if (this.base !== null && this.base.scheme === "file") { - if (isNaN(c)) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 63) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else { - if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points - !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || - (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points - !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - shortenPath(this.url); - } else { - this.parseError = true; - } - - this.state = "path"; - --this.pointer; - } - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file host"; - } else { - if (this.base !== null && this.base.scheme === "file") { - if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { - this.url.path.push(this.base.path[0]); - } else { - this.url.host = this.base.host; - } - } - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { - if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { - --this.pointer; - if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { - this.parseError = true; - this.state = "path"; - } else if (this.buffer === "") { - this.url.host = ""; - if (this.stateOverride) { - return false; - } - this.state = "path start"; - } else { - let host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - if (host === "localhost") { - host = ""; - } - this.url.host = host; - - if (this.stateOverride) { - return false; - } - - this.buffer = ""; - this.state = "path start"; - } - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { - if (isSpecial(this.url)) { - if (c === 92) { - this.parseError = true; - } - this.state = "path"; - - if (c !== 47 && c !== 92) { - --this.pointer; - } - } else if (!this.stateOverride && c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (!this.stateOverride && c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else if (c !== undefined) { - this.state = "path"; - if (c !== 47) { - --this.pointer; - } - } - - return true; -}; - -URLStateMachine.prototype["parse path"] = function parsePath(c) { - if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || - (!this.stateOverride && (c === 63 || c === 35))) { - if (isSpecial(this.url) && c === 92) { - this.parseError = true; - } - - if (isDoubleDot(this.buffer)) { - shortenPath(this.url); - if (c !== 47 && !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } - } else if (isSingleDot(this.buffer) && c !== 47 && - !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } else if (!isSingleDot(this.buffer)) { - if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { - if (this.url.host !== "" && this.url.host !== null) { - this.parseError = true; - this.url.host = ""; - } - this.buffer = this.buffer[0] + ":"; - } - this.url.path.push(this.buffer); - } - this.buffer = ""; - if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { - while (this.url.path.length > 1 && this.url.path[0] === "") { - this.parseError = true; - this.url.path.shift(); - } - } - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += percentEncodeChar(c, isPathPercentEncode); - } - - return true; -}; - -URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else { - // TODO: Add: not a URL code point - if (!isNaN(c) && c !== 37) { - this.parseError = true; - } - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - if (!isNaN(c)) { - this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); - } - } - - return true; -}; - -URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { - if (isNaN(c) || (!this.stateOverride && c === 35)) { - if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { - this.encodingOverride = "utf-8"; - } - - const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead - for (let i = 0; i < buffer.length; ++i) { - if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || - buffer[i] === 0x3C || buffer[i] === 0x3E) { - this.url.query += percentEncode(buffer[i]); - } else { - this.url.query += String.fromCodePoint(buffer[i]); - } - } - - this.buffer = ""; - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { - if (isNaN(c)) { // do nothing - } else if (c === 0x0) { - this.parseError = true; - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); - } - - return true; -}; - -function serializeURL(url, excludeFragment) { - let output = url.scheme + ":"; - if (url.host !== null) { - output += "//"; - - if (url.username !== "" || url.password !== "") { - output += url.username; - if (url.password !== "") { - output += ":" + url.password; - } - output += "@"; - } - - output += serializeHost(url.host); - - if (url.port !== null) { - output += ":" + url.port; - } - } else if (url.host === null && url.scheme === "file") { - output += "//"; - } - - if (url.cannotBeABaseURL) { - output += url.path[0]; - } else { - for (const string of url.path) { - output += "/" + string; - } - } - - if (url.query !== null) { - output += "?" + url.query; - } - - if (!excludeFragment && url.fragment !== null) { - output += "#" + url.fragment; - } - - return output; -} - -function serializeOrigin(tuple) { - let result = tuple.scheme + "://"; - result += serializeHost(tuple.host); - - if (tuple.port !== null) { - result += ":" + tuple.port; - } - - return result; -} - -module.exports.serializeURL = serializeURL; - -module.exports.serializeURLOrigin = function (url) { - // https://url.spec.whatwg.org/#concept-url-origin - switch (url.scheme) { - case "blob": - try { - return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); - } catch (e) { - // serializing an opaque origin returns "null" - return "null"; - } - case "ftp": - case "gopher": - case "http": - case "https": - case "ws": - case "wss": - return serializeOrigin({ - scheme: url.scheme, - host: url.host, - port: url.port - }); - case "file": - // spec says "exercise to the reader", chrome says "file://" - return "file://"; - default: - // serializing an opaque origin returns "null" - return "null"; - } -}; - -module.exports.basicURLParse = function (input, options) { - if (options === undefined) { - options = {}; - } - - const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); - if (usm.failure) { - return "failure"; - } - - return usm.url; -}; - -module.exports.setTheUsername = function (url, username) { - url.username = ""; - const decoded = punycode.ucs2.decode(username); - for (let i = 0; i < decoded.length; ++i) { - url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.setThePassword = function (url, password) { - url.password = ""; - const decoded = punycode.ucs2.decode(password); - for (let i = 0; i < decoded.length; ++i) { - url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.serializeHost = serializeHost; - -module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; - -module.exports.serializeInteger = function (integer) { - return String(integer); -}; - -module.exports.parseURL = function (input, options) { - if (options === undefined) { - options = {}; - } - - // We don't handle blobs, so this just delegates: - return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); -}; - - -/***/ }), - -/***/ 39857: -/***/ ((module) => { +/***/ 47038: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - - -module.exports.mixin = function mixin(target, source) { - const keys = Object.getOwnPropertyNames(source); - for (let i = 0; i < keys.length; ++i) { - Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); - } -}; - -module.exports.wrapperSymbol = Symbol("wrapper"); -module.exports.implSymbol = Symbol("impl"); - -module.exports.wrapperForImpl = function (impl) { - return impl[module.exports.wrapperSymbol]; -}; - -module.exports.implForWrapper = function (wrapper) { - return wrapper[module.exports.implSymbol]; -}; - - - -/***/ }), - -/***/ 58264: -/***/ ((module) => { - -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) - - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') - - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) - - return wrapper - - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) - } - return ret - } -} - - -/***/ }), - -/***/ 41622: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/** - * ZipStream - * - * @ignore - * @license [MIT]{@link https://github.com/archiverjs/node-zip-stream/blob/master/LICENSE} - * @copyright (c) 2014 Chris Talkington, contributors. - */ -var inherits = (__nccwpck_require__(39023).inherits); - -var ZipArchiveOutputStream = (__nccwpck_require__(47544).ZipArchiveOutputStream); -var ZipArchiveEntry = (__nccwpck_require__(47544).ZipArchiveEntry); - -var util = __nccwpck_require__(53296); - -/** - * @constructor - * @extends external:ZipArchiveOutputStream - * @param {Object} [options] - * @param {String} [options.comment] Sets the zip archive comment. - * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC. - * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers. - * @param {Boolean} [options.store=false] Sets the compression method to STORE. - * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} - * to control compression. - */ -var ZipStream = module.exports = function(options) { - if (!(this instanceof ZipStream)) { - return new ZipStream(options); - } - - options = this.options = options || {}; - options.zlib = options.zlib || {}; - - ZipArchiveOutputStream.call(this, options); - - if (typeof options.level === 'number' && options.level >= 0) { - options.zlib.level = options.level; - delete options.level; - } - - if (!options.forceZip64 && typeof options.zlib.level === 'number' && options.zlib.level === 0) { - options.store = true; - } - - options.namePrependSlash = options.namePrependSlash || false; - - if (options.comment && options.comment.length > 0) { - this.setComment(options.comment); - } -}; - -inherits(ZipStream, ZipArchiveOutputStream); - -/** - * Normalizes entry data with fallbacks for key properties. - * - * @private - * @param {Object} data - * @return {Object} - */ -ZipStream.prototype._normalizeFileData = function(data) { - data = util.defaults(data, { - type: 'file', - name: null, - namePrependSlash: this.options.namePrependSlash, - linkname: null, - date: null, - mode: null, - store: this.options.store, - comment: '' - }); - - var isDir = data.type === 'directory'; - var isSymlink = data.type === 'symlink'; - - if (data.name) { - data.name = util.sanitizePath(data.name); - - if (!isSymlink && data.name.slice(-1) === '/') { - isDir = true; - data.type = 'directory'; - } else if (isDir) { - data.name += '/'; - } - } - - if (isDir || isSymlink) { - data.store = true; - } - - data.date = util.dateify(data.date); - - return data; -}; - -/** - * Appends an entry given an input source (text string, buffer, or stream). - * - * @param {(Buffer|Stream|String)} source The input source. - * @param {Object} data - * @param {String} data.name Sets the entry name including internal path. - * @param {String} [data.comment] Sets the entry comment. - * @param {(String|Date)} [data.date=NOW()] Sets the entry date. - * @param {Number} [data.mode=D:0755/F:0644] Sets the entry permissions. - * @param {Boolean} [data.store=options.store] Sets the compression method to STORE. - * @param {String} [data.type=file] Sets the entry type. Defaults to `directory` - * if name ends with trailing slash. - * @param {Function} callback - * @return this - */ -ZipStream.prototype.entry = function(source, data, callback) { - if (typeof callback !== 'function') { - callback = this._emitErrorCallback.bind(this); - } - - data = this._normalizeFileData(data); - - if (data.type !== 'file' && data.type !== 'directory' && data.type !== 'symlink') { - callback(new Error(data.type + ' entries not currently supported')); - return; - } - - if (typeof data.name !== 'string' || data.name.length === 0) { - callback(new Error('entry name must be a non-empty string value')); - return; - } - - if (data.type === 'symlink' && typeof data.linkname !== 'string') { - callback(new Error('entry linkname must be a non-empty string value when type equals symlink')); - return; - } - - var entry = new ZipArchiveEntry(data.name); - entry.setTime(data.date, this.options.forceLocalTime); - - if (data.namePrependSlash) { - entry.setName(data.name, true); - } - - if (data.store) { - entry.setMethod(0); - } - - if (data.comment.length > 0) { - entry.setComment(data.comment); - } - - if (data.type === 'symlink' && typeof data.mode !== 'number') { - data.mode = 40960; // 0120000 - } - - if (typeof data.mode === 'number') { - if (data.type === 'symlink') { - data.mode |= 40960; - } - - entry.setUnixMode(data.mode); - } - - if (data.type === 'symlink' && typeof data.linkname === 'string') { - source = Buffer.from(data.linkname); - } - - return ZipArchiveOutputStream.prototype.entry.call(this, entry, source, callback); -}; - -/** - * Finalizes the instance and prevents further appending to the archive - * structure (queue will continue til drained). - * - * @return void - */ -ZipStream.prototype.finalize = function() { - this.finish(); -}; - -/** - * Returns the current number of bytes written to this stream. - * @function ZipStream#getBytesWritten - * @returns {Number} - */ - -/** - * Compress Commons ZipArchiveOutputStream - * @external ZipArchiveOutputStream - * @see {@link https://github.com/archiverjs/node-compress-commons} - */ - - -/***/ }), - -/***/ 22929: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(37484)); -const srcclr_1 = __nccwpck_require__(47038); -const options = { - quick: core.getBooleanInput('quick'), - updateAdvisor: core.getBooleanInput('update_advisor'), - minCVSSForIssue: parseFloat(core.getInput('min-cvss-for-issue')) || 0, - url: core.getInput('url'), - github_token: core.getInput('github_token', { required: true }), - createIssues: core.getBooleanInput('create-issues'), - allowDirty: core.getBooleanInput('allow-dirty'), - failOnCVSS: parseFloat(core.getInput('fail-on-cvss')) || 10, - path: core.getInput('path', { trimWhitespace: true }) || '.', - debug: core.getBooleanInput('debug'), - "skip-vms": core.getBooleanInput('skip-vms'), - "no-graphs": core.getBooleanInput('no-graphs'), - recursive: core.getBooleanInput('recursive'), - "skip-collectors": core.getInput('skip-collectors').split(','), - "scan-collectors": core.getInput('scan-collectors').split(','), - platformType: core.getInput('platformType'), - breakBuildOnPolicyFindings: core.getInput('breakBuildOnPolicyFindings'), - scaFixEnabled: core.getBooleanInput('sca_fix_enabled'), - profileName: core.getInput('profile_name'), - prNumber: parseInt(core.getInput('pr_number'), 10) -}; -try { - (0, srcclr_1.runAction)(options); -} -catch (error) { - core.setFailed(error instanceof Error ? error.message : String(error)); -} - - -/***/ }), - -/***/ 39015: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GithubHandler = void 0; -const github_1 = __nccwpck_require__(93228); -const labels_1 = __nccwpck_require__(94584); -const ISSUES_PULL_COUNT = 100; -class GithubHandler { - constructor(token) { - this.token = token; - const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; - this.client = (0, github_1.getOctokit)(token, { baseUrl }); - } - getVeracodeLabel() { - return __awaiter(this, void 0, void 0, function* () { - console.log('getVeracodeLabel - START'); - let veracodeLabel = {}; - try { - veracodeLabel = yield this.client.rest - .issues.getLabel({ - owner: github_1.context.repo.owner, - repo: github_1.context.repo.repo, - name: labels_1.VERACODE_LABEL.name - }); - console.log('Veracode Labels already exist'); - } - catch (e) { - console.log('======================= ERROR ==============================='); - console.log(e); - } - console.log('getVeracodeLabel - END'); - return veracodeLabel; - }); - } - createVeracodeLabels() { - return __awaiter(this, void 0, void 0, function* () { - console.log('createVeracodeLabels - END'); - try { - // Creating the severity labels - for (var label of Object.values(labels_1.SEVERITY_LABELS)) { - yield this.client.rest.issues.createLabel({ - owner: github_1.context.repo.owner, - repo: github_1.context.repo.repo, - name: label.name, - color: label.color, - description: label.description - }); - } - // Creating the base label - yield this.client.rest.issues.createLabel({ - owner: github_1.context.repo.owner, - repo: github_1.context.repo.repo, - name: labels_1.VERACODE_LABEL.name, - color: labels_1.VERACODE_LABEL.color, - description: labels_1.VERACODE_LABEL.description - }); - //this.client.paginate(this.client.graphql,""); - } - catch (e) { - console.log('======================= ERROR ==============================='); - console.log(e); - } - console.log('createVeracodeLabels - END'); - }); - } - createIssue(reportedIssue) { - return __awaiter(this, void 0, void 0, function* () { - return yield this.client.rest.issues.create({ - owner: github_1.context.repo.owner, - repo: github_1.context.repo.repo, - title: reportedIssue.title, - body: reportedIssue.description, - labels: reportedIssue.labels - }); - }); - } - listExistingOpenIssues() { - return __awaiter(this, void 0, void 0, function* () { - console.log('getIssues - START'); - const query = `query IsslesTitle($organization: String!,$repo: String!, $count: Int!,$label: String!) { - repository(name: $repo, owner: $organization) { - issues(first: $count,filterBy: {labels: [$label], states: OPEN}) { - edges { - node { - title - number - } - } - pageInfo { - hasNextPage - endCursor - } - } - } - }`; - const nextQuery = `query IsslesTitle($organization: String!,$repo: String!, $count: Int!, $endCursor: String!,$label: String!) { - repository(name: $repo, owner: $organization) { - issues(first: $count,after: $endCursor,filterBy: {labels: [$label], states: OPEN}) { - edges { - node { - title - number - } - } - pageInfo { - hasNextPage - endCursor - } - } - } - }`; - let issues = []; - try { - let issuesRes = yield this.client.graphql({ - headers: { - authorization: `token ${this.token}` - }, - query, - count: ISSUES_PULL_COUNT, - organization: github_1.context.repo.owner, - repo: github_1.context.repo.repo, - label: labels_1.VERACODE_LABEL.name - }); - issues = issues.concat(issuesRes.repository.issues.edges); - while (issuesRes.repository.issues.pageInfo.hasNextPage) { - console.log('iterating for fetching more related open issues'); - const endCursor = issuesRes.repository.issues.pageInfo.endCursor; - issuesRes = yield this.client.graphql({ - headers: { - authorization: `token ${this.token}` - }, - query: nextQuery, - count: ISSUES_PULL_COUNT, - endCursor, - organization: github_1.context.repo.owner, - repo: github_1.context.repo.repo, - label: labels_1.VERACODE_LABEL.name - }); - issues = issues.concat(issuesRes.repository.issues.edges); - } - } - catch (e) { - console.log('======================= ERROR ==============================='); - console.log(e); - } - console.log('getIssues - END'); - return issues; - }); - } -} -exports.GithubHandler = GithubHandler; - - -/***/ }), - -/***/ 79407: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.runText = exports.run = exports.SCA_OUTPUT_FILE = void 0; -//import {getOctokit,context} from '@actions/github'; -const fs_1 = __nccwpck_require__(79896); -const labels_1 = __nccwpck_require__(94584); -const githubRequestHandler_1 = __nccwpck_require__(39015); -const core = __importStar(__nccwpck_require__(37484)); -const { request } = __nccwpck_require__(66255); -const github = __nccwpck_require__(93228); -exports.SCA_OUTPUT_FILE = 'scaResults.json'; -const librariesWithIssues = {}; -let githubHandler; -function run(options, msgFunc) { - return __awaiter(this, void 0, void 0, function* () { - if (!(0, fs_1.existsSync)(exports.SCA_OUTPUT_FILE)) { - core.setFailed('SCA Output file was not found - cannot proceed with creating issues.\nPlease check prior execution errors.'); - return; - } - const scaResultsTxt = (0, fs_1.readFileSync)(exports.SCA_OUTPUT_FILE); - const scaResJson = JSON.parse(scaResultsTxt.toString('utf-8')); - const vulnerabilities = scaResJson.records[0].vulnerabilities; - const libraries = scaResJson.records[0].libraries; - vulnerabilities - //.filter((vul:any) => vul.cvssScore>=options.minCVSSForIssue) - .forEach((vulr) => { - //console.log('------- in each ------'); - const libref = vulr.libraries[0]._links.ref; - //core.info('libref: '+libref) - const libId = libref.split('/')[4]; - //core.info('libId: '+libId) - const lib = libraries[libId]; - //core.info('lib: '+JSON.stringify(lib)) - const details = createIssueDetails(vulr, lib); - addIssueToLibrary(libId, lib, details); - }); - githubHandler = new githubRequestHandler_1.GithubHandler(options.github_token); - if (Object.keys(librariesWithIssues).length > 0) { - yield verifyLabels(); - yield syncExistingOpenIssues(options); - // check for failing the step - /* - const failingVul = vulnerabilities.filter(vul => vul.cvssScore>=options.failOnCVSS); - if (failingVul.length>0) { - core.setFailed(`Found Vulnerability with CVSS equal or greater than ${options.failOnCVSS}`); - } else { - msgFunc(`No 3rd party library found with Vulnerability of CVSS equal or greater than ${options.failOnCVSS}`); - } - */ - } - msgFunc(`Scan finished.\nFull Report Details: ${scaResJson.records[0].metadata.report}`); - }); -} -exports.run = run; -const addIssueToLibrary = (libId, lib, details) => { - let libWithIssues = librariesWithIssues[libId] || { lib, issues: [] }; - libWithIssues.issues.push(details); - librariesWithIssues[libId] = libWithIssues; -}; -const syncExistingOpenIssues = (options) => __awaiter(void 0, void 0, void 0, function* () { - const existingOpenIssues = yield githubHandler.listExistingOpenIssues(); - const lenghtOfLibs = Object.keys(librariesWithIssues).length; - core.info('Libraries with issues found: ' + lenghtOfLibs); - let createIssue; - let openIssueTitle; - let openIssueNumber; - //Check if we run on a PR - core.info('check if we run on a pull request'); - let pullRequest = process.env.GITHUB_REF; - let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); - const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; - const customRequest = request.defaults({ - baseUrl - }); - for (var key in librariesWithIssues) { - core.info('Library ' + key + ' - ' + librariesWithIssues[key]['lib']['name']); - var issueLength = Object.keys(librariesWithIssues[key]['issues']).length; - core.info(issueLength + ' Issues found on Library'); - for (let j = 0; j < issueLength; j++) { - var libraryTitle = librariesWithIssues[key]['issues'][j]['title']; - core.info('Isuse Title ' + j + ': ' + libraryTitle); - var openIssueLenght = existingOpenIssues.length; - core.info("Open issues found: " + openIssueLenght); - for (let k = 0; k < openIssueLenght; k++) { - openIssueTitle = existingOpenIssues[k]['node']['title']; - openIssueNumber = existingOpenIssues[k]['node']['number']; - //core.info('Open Isssue: '+openIssueTitle+' --- '+openIssueNumber) - if (libraryTitle == openIssueTitle) { - core.info('Issue \n' + libraryTitle + '\n' + openIssueTitle + '\nalready exists - skipping'); - createIssue = false; - break; - } - } - if (createIssue == false) { - core.info('Issue already exists - skipping --- ' + libraryTitle + ' ---- ' + openIssueTitle); - if (isPR >= 1) { - core.info('We run on a PR, link issue to PR'); - let pr_context = github.context; - let pr_commentID = pr_context.payload.pull_request.number; - var authToken = 'token ' + options.github_token; - const owner = github.context.repo.owner; - const repo = github.context.repo.repo; - var pr_link = `Veracode issue link to PR: https://github.com/` + owner + `/` + repo + `/pull/` + pr_commentID; - console.log('Adding PR to the issue now.'); - yield customRequest('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', { - headers: { - authorization: authToken - }, - owner: owner, - repo: repo, - issue_number: openIssueNumber, - data: { - "body": pr_link - } - }); - } - } - else { - core.info('Issue needs to be created. --- ' + libraryTitle); - const ghResponse = yield githubHandler.createIssue(librariesWithIssues[key]['issues'][j]); - //core.info('Issue creation response: '+JSON.stringify(ghResponse)) - var issueNumber = ghResponse.data.number; - if (isPR >= 1) { - core.info('We run on a PR, link issue to PR'); - let pr_context = github.context; - let pr_commentID = pr_context.payload.pull_request.number; - var authToken = 'token ' + options.github_token; - const owner = github.context.repo.owner; - const repo = github.context.repo.repo; - var pr_link = `Veracode issue link to PR: https://github.com/` + owner + `/` + repo + `/pull/` + pr_commentID; - console.log('Adding PR to the issue now.'); - yield customRequest('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', { - headers: { - authorization: authToken - }, - owner: owner, - repo: repo, - issue_number: issueNumber, - data: { - "body": pr_link - } - }); - } - } - } - } -}); -const createIssueDetails = (vuln, lib) => { - const vulnLibDetails = vuln.libraries[0].details[0]; - const sevLabel = getSeverityName(vuln.cvssScore); - const myCVE = vuln.cve || '0000-0000'; - const versionsFound = lib.versions.map(version => version.version); - var title = "CVE: " + myCVE + " found in " + lib.name + " - Version: " + versionsFound + " [" + vuln.language + "]"; - var labels = [labels_1.VERACODE_LABEL, sevLabel]; - var description = "Veracode Software Composition Analysis" + - " \n===============================\n" + - " \n Attribute | Details" + - " \n| --- | --- |" + - " \nLibrary | " + lib.name + - " \nDescription | " + lib.description + - " \nLanguage | " + vuln.language + - " \nVulnerability | " + vuln.title + - " \nVulnerability description | " + (vuln.overview ? vuln.overview.trim() : "") + - " \nCVE | " + vuln.cve + - " \nCVSS score | " + vuln.cvssScore + - " \nVulnerability present in version/s | " + vulnLibDetails.versionRange + - " \nFound library version/s | " + versionsFound + - " \nVulnerability fixed in version | " + vulnLibDetails.updateToVersion + - " \nLibrary latest version | " + lib.latestRelease + - " \nFix | " + vulnLibDetails.fixText + - " \n" + - " \nLinks:" + - " \n- " + lib.versions[0]._links.html + - " \n- " + vuln._links.html + - " \n- Patch: " + vulnLibDetails.patch; - return { - title, description, labels - }; -}; -const getSeverityName = (cvss) => { - var weight = Math.floor(cvss); - let label = labels_1.SEVERITY_LABELS.Unknown; - if (weight == 0) - label = labels_1.SEVERITY_LABELS.Informational; - else if (weight >= 0.1 && weight < 1.9) - label = labels_1.SEVERITY_LABELS['Very Low']; - else if (weight >= 2.0 && weight < 3.9) - label = labels_1.SEVERITY_LABELS.Low; - else if (weight >= 4.0 && weight < 5.9) - label = labels_1.SEVERITY_LABELS.Medium; - else if (weight >= 6.0 && weight < 7.9) - label = labels_1.SEVERITY_LABELS.High; - else if (weight >= 8.0) - label = labels_1.SEVERITY_LABELS['Very High']; - return label; -}; -const verifyLabels = () => __awaiter(void 0, void 0, void 0, function* () { - const baseLabel = yield githubHandler.getVeracodeLabel(); - if (!baseLabel || !baseLabel.data) { - yield githubHandler.createVeracodeLabels(); - } -}); -function runText(options, output, msgFunc) { - return __awaiter(this, void 0, void 0, function* () { - const vulnerabilityLinePattern = /^\d+\s+Vulnerability\s+([\d\.]+)\s+.+/; - const splitLines = output.split(/\r?\n/); - let failed = false; - for (var line of splitLines) { - if (vulnerabilityLinePattern.test(line)) { - const match = line.match(vulnerabilityLinePattern); - if (match) { - const cvss = parseFloat(match[1]); - if (cvss >= options.failOnCVSS) { - failed = true; - } - } - } - } - if (failed) { - core.setFailed(`Found Vulnerability with CVSS equal or greater than ${options.failOnCVSS}`); - } - else { - msgFunc(`No 3rd party library found with Vulnerability of CVSS equal or greater than ${options.failOnCVSS}`); - } - }); -} -exports.runText = runText; - - -/***/ }), - -/***/ 94584: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.VERACODE_LABEL = exports.SEVERITY_LABELS = void 0; -exports.SEVERITY_LABELS = { - "Very High": { - 'name': 'Severity: Very High', - 'color': 'A90533', - 'description': 'Very High severity', - }, - High: { - 'name': 'Severity: High', - 'color': 'DD3B35', - 'description': 'High severity' - }, - Medium: { - 'name': 'Severity: Medium', - 'color': 'FF7D00', - 'description': 'Medium severity' - }, - Low: { - 'name': 'Severity: Low', - 'color': 'FFBE00', - 'description': 'Low severity' - }, - "Very Low": { - 'name': 'Severity: Very Low', - 'color': '33ADD2', - 'description': 'Very Low severity', - }, - Informational: { - 'name': 'Severity: Informational', - 'color': '0270D3', - 'description': 'Informational severity', - }, - Unknown: { - 'name': 'Severity: Unknown', - 'color': '0270D3', - 'description': 'Unknown severity', - } -}; -exports.VERACODE_LABEL = { - 'name': 'Veracode Dependency Scanning', - 'color': '0AA2DC', - 'description': 'A Veracode identified vulnerability' -}; - - -/***/ }), - -/***/ 47038: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.runAction = void 0; -const child_process_1 = __nccwpck_require__(35317); -const core = __importStar(__nccwpck_require__(37484)); -const index_1 = __nccwpck_require__(79407); -const github = __importStar(__nccwpck_require__(93228)); -const fs_1 = __nccwpck_require__(79896); -const fs_2 = __nccwpck_require__(79896); -const runnerOS = process.env.RUNNER_OS; -const cleanCollectors = (inputArr) => { - let allowed = []; - for (var input of inputArr) { - if (input && collectors.indexOf(input.trim().toLowerCase()) > -1) { - allowed.push(input.trim().toLowerCase()); - } - } - return allowed; -}; -/** - * Extracts the scan URL from the Veracode SCA output - * Looks for a line containing "Full Report Details" followed by a URL - * Also tries to extract from JSON metadata if available - */ -const extractScanUrl = (output) => { - core.info('=== Starting URL extraction ==='); - if (!output) { - core.info('extractScanUrl: output is empty or null'); - return null; - } - core.info(`extractScanUrl: Output length is ${output.length} characters`); - // Pattern to match: "Full Report Details" followed by whitespace and a URL - // More flexible pattern that handles various whitespace amounts - // Matches: "Full Report Details" followed by any whitespace and then a URL starting with http:// or https:// - const patterns = [ - /Full\s+Report\s+Details\s+(https?:\/\/[^\s\r\n]+)/i, - /Full\s+Report\s+Details[:\s]+(https?:\/\/[^\s\r\n]+)/i, - /Full\s+Report\s+Details\s+(\S+)/i, - /Full\s+Report\s+Details[:\s]+(https?:\/\/[^\r\n]+)/i, // Handle newlines - ]; - // First, check if "Full Report Details" appears in the output at all - const hasFullReport = /Full\s+Report\s+Details/i.test(output); - core.info(`extractScanUrl: "Full Report Details" found in output: ${hasFullReport}`); - if (hasFullReport) { - // Find the line containing "Full Report Details" - const lines = output.split('\n'); - const fullReportLine = lines.find(line => /Full\s+Report\s+Details/i.test(line)); - if (fullReportLine) { - core.info(`extractScanUrl: Found line: "${fullReportLine.trim()}"`); - } - } - for (let i = 0; i < patterns.length; i++) { - const pattern = patterns[i]; - const match = output.match(pattern); - if (match && match[1]) { - const url = match[1].trim(); - // Validate it's a URL - if (url.startsWith('http://') || url.startsWith('https://')) { - core.info(`extractScanUrl: ✓ Found URL using pattern ${i + 1}: ${url}`); - return url; - } - else { - core.info(`extractScanUrl: Pattern ${i + 1} matched but result is not a URL: ${url}`); - } - } - } - core.info('extractScanUrl: No URL found in text output, trying JSON fallback'); - // Fallback: Try to extract from JSON if available - try { - if ((0, fs_1.existsSync)(index_1.SCA_OUTPUT_FILE)) { - core.info(`extractScanUrl: JSON file exists, attempting to read: ${index_1.SCA_OUTPUT_FILE}`); - const scaResultsTxt = (0, fs_1.readFileSync)(index_1.SCA_OUTPUT_FILE); - const scaResJson = JSON.parse(scaResultsTxt.toString('utf-8')); - if (scaResJson.records && scaResJson.records[0] && scaResJson.records[0].metadata && scaResJson.records[0].metadata.report) { - const url = scaResJson.records[0].metadata.report; - if (url.startsWith('http://') || url.startsWith('https://')) { - core.info(`extractScanUrl: ✓ Found URL in JSON metadata: ${url}`); - return url; - } - } - else { - core.info('extractScanUrl: JSON file exists but does not contain report URL in expected structure'); - } - } - else { - core.info(`extractScanUrl: JSON file does not exist: ${index_1.SCA_OUTPUT_FILE}`); - } - } - catch (error) { - core.info(`extractScanUrl: Error reading JSON fallback: ${error.message || error}`); - } - core.info('extractScanUrl: ✗ No URL found in output or JSON'); - core.info('=== URL extraction complete ==='); - return null; -}; -/** - * Upload SCA scan artifacts - * @param artifactClient - GitHub Actions artifact client - * @param artifactName - Name of the artifact to create - * @param files - Array of file paths to include in artifact - */ -function uploadArtifacts(artifactClient, artifactName, files) { - return __awaiter(this, void 0, void 0, function* () { - const fileList = files.join(', '); - core.info(`Uploading artifact '${artifactName}' with files: ${fileList}`); - try { - yield artifactClient.uploadArtifact(artifactName, files, process.cwd(), { continueOnError: true }); - core.info(`✓ Successfully uploaded artifact with ${files.length} file(s)`); - } - catch (error) { - core.warning(`Failed to upload artifact: ${error.message || error}`); - } - }); -} -/** - * When using --show-cli flag, both JSON and CLI text are produced - * This helper writes the CLI output (stdout) to scaResults.txt - * @param cliOutput - The stdout from the scan command - */ -function writeCliOutputToFile(cliOutput) { - return __awaiter(this, void 0, void 0, function* () { - try { - (0, fs_2.writeFileSync)('scaResults.txt', cliOutput); - core.info('CLI output written to scaResults.txt'); - } - catch (error) { - core.warning(`Failed to write CLI output to file: ${error.message || error}`); - } - }); -} -/** - * Runs a unified scan with --show-cli flag when sca_fix_enabled - * When sca_fix_enabled=true: Generates both JSON and CLI text output in one scan - * When sca_fix_enabled=false: Generates output based on createIssues/jsonOutput flags - * @param options - Scan options - */ -function runScan(options) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - try { - core.info('Start command'); - let extraCommands = ''; - if (options.url.length > 0) { - extraCommands = `--url ${options.url} `; - } - else { - extraCommands = `${options.path} `; - } - const skip = cleanCollectors(options["skip-collectors"]); - let skipCollectorsAttr = ''; - if (skip.length > 0) { - skipCollectorsAttr = `--skip-collectors ${skip.toString()} `; - } - const scan = cleanCollectors(options["scan-collectors"]); - let scanCollectorsAttr = ''; - if (scan.length > 0) { - scanCollectorsAttr = `--scan-collectors ${scan.toString()} `; - } - const noGraphs = options["no-graphs"]; - const skipVMS = options["skip-vms"]; - // Generate JSON when sca_fix_enabled (uses --show-cli for both JSON and CLI text in single scan) - // or when createIssues is true (JSON for issue creation) - const shouldGenerateJson = options.createIssues || options.scaFixEnabled; - let commandOutput = ''; - if (options.scaFixEnabled) { - // Use --json --show-cli for unified output (JSON to file, CLI text to stdout) - commandOutput = `--json=${index_1.SCA_OUTPUT_FILE} --show-cli`; - } - else if (options.createIssues) { - // JSON output for issue creation - commandOutput = `--json=${index_1.SCA_OUTPUT_FILE}`; - } - // Always use the base artifact name regardless of output format - // (whether it contains JSON+TXT with --show-cli or TXT only) - const artifactNameBase = 'Veracode Agent Based SCA Results'; - extraCommands = `${extraCommands}${options.recursive ? '--recursive ' : ''}${options.quick ? '--quick ' : ''}${options.allowDirty ? '--allow-dirty ' : ''}${options.updateAdvisor ? '--update-advisor ' : ''}${skipVMS ? '--skip-vms ' : ''}${noGraphs ? '--no-graphs ' : ''}${options.debug ? '--debug ' : ''}${skipCollectorsAttr}${scanCollectorsAttr}`; - if (runnerOS == 'Windows') { - const powershellCommand = `powershell -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest https://sca-downloads.veracode.com/ci.ps1 -OutFile $env:TEMP\\ci.ps1; & $env:TEMP\\ci.ps1 -s -- scan ${extraCommands} ${commandOutput}"`; - if (shouldGenerateJson) { - core.info('Starting the scan'); - let output = ''; - try { - output = (0, child_process_1.execSync)(powershellCommand, { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 10 }); //10MB - if (options.createIssues) { - core.info('Create issue "true" - on close'); - } - if (core.isDebug()) { - core.info(output); - } - // Extract and set scan URL output - const scanUrl = extractScanUrl(output); - if (scanUrl) { - core.setOutput('scan-url', scanUrl); - core.info(`Scan URL extracted: ${scanUrl}`); - } - else { - core.info('Scan URL not found in output'); - } - } - catch (error) { - if (error.status != null && error.status > 0 && (options.breakBuildOnPolicyFindings == 'true')) { - let summary_info = "Veracode SCA Scan failed with exit code " + error.statuscode + "\n"; - core.info(output); - core.setFailed(summary_info); - } - // Try to extract URL even if there was an error - const scanUrl = extractScanUrl(output); - if (scanUrl) { - core.setOutput('scan-url', scanUrl); - core.info(`Scan URL extracted: ${scanUrl}`); - } - } - // PR decoration and issue generation (only if createIssues is enabled) - if (options.createIssues) { - //Pull request decoration - core.info('check if we run on a pull request'); - let pullRequest = process.env.GITHUB_REF; - let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); - let summary_message = ""; - if (isPR >= 1) { - core.info('We run on a PR, add more messaging'); - const context = github.context; - const repository = process.env.GITHUB_REPOSITORY; - const repo = repository.split("/"); - const commentID = (_a = context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.number; - let pr_header = '
![](https://www.veracode.com/themes/veracode_new/library/img/veracode-black-hires.svg)
'; - summary_message = `Veracode SCA Scan finished. Please review created and linked issues`; - try { - const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; - const octokit = github.getOctokit(options.github_token, { baseUrl }); - const { data: comment } = yield octokit.rest.issues.createComment({ - owner: repo[0], - repo: repo[1], - issue_number: commentID, - body: pr_header + summary_message, - }); - core.info('Adding scan results message as comment to PR #' + commentID); - } - catch (error) { - core.info(error); - } - } - else { - summary_message = `Veracode SCA Scan finished. Please review created issues`; - } - //Generate issues - (0, index_1.run)(options, core.info); - core.info(summary_message); - } - // Store output files as artifacts - const { DefaultArtifactClient } = __nccwpck_require__(76846); - const artifactV1 = __nccwpck_require__(20166); - let artifactClient; - if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { - artifactClient = artifactV1.create(); - core.info(`Initialized the artifact object using version V1.`); - } - else { - artifactClient = new DefaultArtifactClient(); - core.info(`Initialized the artifact object using version V2.`); - } - // When --show-cli is used, we also have CLI output that needs to be saved - if (options.scaFixEnabled) { - // Write the CLI output (stdout) to scaResults.txt - yield writeCliOutputToFile(output); - // Upload both JSON and TXT files - yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.json', 'scaResults.txt']); - } - else { - // JSON-only upload for create-issues - yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.json']); - } - core.info('Finish command'); - } - else { - core.info('Command to run: ' + powershellCommand); - let output = ''; - let stderrOutput = ''; - try { - // execSync captures both stdout and stderr by default, but let's be explicit - output = (0, child_process_1.execSync)(powershellCommand, { - encoding: 'utf-8', - maxBuffer: 1024 * 1024 * 10, - stdio: ['pipe', 'pipe', 'pipe'] // stdin, stdout, stderr - }); //10MB - core.info(output); - core.info(`Attempting to extract scan URL from output (length: ${output.length} chars)`); - // Extract and set scan URL output - const scanUrl = extractScanUrl(output); - if (scanUrl) { - core.setOutput('scan-url', scanUrl); - core.info(`✓✓✓ SUCCESS: Scan URL extracted and set as output: ${scanUrl}`); - } - else { - core.warning('✗✗✗ FAILED: Scan URL not found in output'); - // Try to find the line with "Full Report Details" for debugging - const lines = output.split('\n'); - const fullReportLine = lines.find(line => line.toLowerCase().includes('full report details')); - if (fullReportLine) { - core.info(`Found "Full Report Details" line: ${fullReportLine}`); - } - else { - core.info('"Full Report Details" line not found in output'); - } - } - } - catch (error) { - // execSync throws on non-zero exit, but output might still be in error.stdout or error.stderr - if (error.stdout) { - output = error.stdout.toString(); - } - if (error.stderr) { - stderrOutput = error.stderr.toString(); - } - if (error.status != null && error.status > 0 && (options.breakBuildOnPolicyFindings == 'true')) { - let summary_info = "Veracode SCA Scan failed with exit code " + error.statuscode + "\n"; - core.setFailed(summary_info); - } - // Try to extract URL from combined output even if there was an error - const combinedOutput = `${output}${stderrOutput}`; - const scanUrl = extractScanUrl(combinedOutput); - if (scanUrl) { - core.setOutput('scan-url', scanUrl); - core.info(`Scan URL extracted from error output: ${scanUrl}`); - } - else if (core.isDebug()) { - core.info(`Could not extract URL. Output length: ${output.length}, stderr length: ${stderrOutput.length}`); - } - } - //write output to file - // writeFile('scaResults.txt', output, (err) => { - // if (err) throw err; - // console.log('The file has been saved!'); - // }); - try { - (0, fs_2.writeFileSync)('scaResults.txt', output); - console.log('The file has been saved!'); - } - catch (err) { - console.error('Error writing file:', err); - } - // core.info('reading file') - // try { - // const data = readFileSync('scaResults.txt', 'utf8'); - // console.log('Full file output: '+data); - // } catch (err) { - // console.error(err); - // } - // Store output files as artifacts (skip if in dual-scan mode) - const { DefaultArtifactClient } = __nccwpck_require__(76846); - const artifactV1 = __nccwpck_require__(20166); - let artifactClient; - if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { - artifactClient = artifactV1.create(); - core.info(`Initialized the artifact object using version V1.`); - } - else { - artifactClient = new DefaultArtifactClient(); - core.info(`Initialized the artifact object using version V2.`); - } - yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.txt']); - //Pull request decoration - core.info('check if we run on a pull request'); - let pullRequest = process.env.GITHUB_REF; - let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); - if (isPR >= 1) { - core.info("This run is part of a PR, should add some PR comment"); - const context = github.context; - const repository = process.env.GITHUB_REPOSITORY; - const repo = repository.split("/"); - const commentID = (_b = context.payload.pull_request) === null || _b === void 0 ? void 0 : _b.number; - let commentBody = '
![](https://www.veracode.com/sites/default/files/2022-04/logo_1.svg)
'; - commentBody += "
Veracode SCA Scan finished" + "\n";
-                        commentBody += '\n
Veracode SCA Scan details

\n'; - commentBody += output; //.replace(/ /g, '    '); - commentBody += '

\n
'; - try { - const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; - const octokit = github.getOctokit(options.github_token, { baseUrl }); - const { data: comment } = yield octokit.rest.issues.createComment({ - owner: repo[0], - repo: repo[1], - issue_number: commentID, - body: commentBody, - }); - core.info('Adding scan results as comment to PR #' + commentID); - } - catch (error) { - core.info(error); - } - } - //run(options,core.info); - core.info('Finish command'); - } - } - else { - const command = `curl -sSL https://download.sourceclear.com/ci.sh | sh -s -- scan ${extraCommands} ${commandOutput}`; - core.info(command); - if (shouldGenerateJson) { - core.info('Starting the scan'); - yield new Promise((resolve, reject) => { - const execution = (0, child_process_1.spawn)('sh', ['-c', command], { - stdio: "pipe", - shell: false - }); - execution.on('error', (data) => { - core.error(data); - reject(data); - }); - let output = ''; - let stderrOutput = ''; - execution.stdout.on('data', (data) => { - output = `${output}${data}`; - }); - execution.stderr.on('data', (data) => { - const dataStr = data.toString(); - stderrOutput = `${stderrOutput}${dataStr}`; - core.error(`stderr: ${dataStr}`); - }); - execution.on('close', (code) => __awaiter(this, void 0, void 0, function* () { - var _a; - if (options.createIssues) { - core.info('Create issue "true" - on close'); - } - if (core.isDebug()) { - core.info(output); - } - // Combine stdout and stderr for URL extraction (URL might be in either) - const combinedOutput = `${output}${stderrOutput}`; - core.info(`Attempting to extract scan URL from combined output (stdout: ${output.length} chars, stderr: ${stderrOutput.length} chars)`); - // Extract and set scan URL output from combined output - const scanUrl = extractScanUrl(combinedOutput); - if (scanUrl) { - core.setOutput('scan-url', scanUrl); - core.info(`✓✓✓ SUCCESS: Scan URL extracted and set as output: ${scanUrl}`); - } - else { - core.warning('✗✗✗ FAILED: Scan URL not found in output'); - core.info(`Output length: ${output.length}, stderr length: ${stderrOutput.length}, combined: ${combinedOutput.length}`); - // Log a sample of the output to help debug - const fullReportIndex = combinedOutput.indexOf('Full Report'); - if (fullReportIndex >= 0) { - const sampleOutput = combinedOutput.substring(Math.max(0, fullReportIndex - 50), Math.min(combinedOutput.length, fullReportIndex + 200)); - core.info(`Sample output around "Full Report" (index ${fullReportIndex}): ${sampleOutput}`); - } - else { - core.info('"Full Report" text not found in combined output'); - } - } - // PR decoration and issue generation (only if createIssues is enabled) - let summary_message = ""; - if (options.createIssues) { - //Pull request decoration - core.info('check if we run on a pull request'); - let pullRequest = process.env.GITHUB_REF; - let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); - if (isPR >= 1) { - core.info('We run on a PR, add more messaging'); - const context = github.context; - const repository = process.env.GITHUB_REPOSITORY; - const repo = repository.split("/"); - const commentID = (_a = context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.number; - let pr_header = '
![](https://www.veracode.com/themes/veracode_new/library/img/veracode-black-hires.svg)
'; - summary_message = `Veracode SCA Scan finished with exit code: ${code}. Please review created and linked issues`; - try { - const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; - const octokit = github.getOctokit(options.github_token, { baseUrl }); - const { data: comment } = yield octokit.rest.issues.createComment({ - owner: repo[0], - repo: repo[1], - issue_number: commentID, - body: pr_header + summary_message, - }); - core.info('Adding scan results message as comment to PR #' + commentID); - } - catch (error) { - core.info(error); - } - } - else { - summary_message = `Veracode SCA Scan finished with exit code: ${code}. Please review created issues`; - } - //Generate issues - (0, index_1.run)(options, core.info); - core.info(summary_message); - } - // if scan was set to fail the pipeline should fail and show a summary of the scan results - if (code != null && code > 0 && (options.breakBuildOnPolicyFindings == 'true')) { - let summary_info = "Veracode SCA Scan failed with exit code " + code + "\n"; - core.setFailed(summary_info); - } - // Store output files as artifacts - const { DefaultArtifactClient } = __nccwpck_require__(76846); - const artifactV1 = __nccwpck_require__(20166); - let artifactClient; - if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { - artifactClient = artifactV1.create(); - core.info(`Initialized the artifact object using version V1.`); - } - else { - artifactClient = new DefaultArtifactClient(); - core.info(`Initialized the artifact object using version V2.`); - } - // When --show-cli is used, we also have CLI output that needs to be saved - if (options.scaFixEnabled) { - // Write the CLI output (stdout) to scaResults.txt - yield writeCliOutputToFile(output); - // Upload both JSON and TXT files - yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.json', 'scaResults.txt']); - } - else { - // Traditional JSON-only upload - yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.json']); - } - core.info('Finish command'); - resolve(); - })); - }); - } - else { - core.info('Command to run: ' + command); - yield new Promise((resolve, reject) => { - const execution = (0, child_process_1.spawn)('sh', ['-c', command], { - stdio: "pipe", - shell: false - }); - execution.on('error', (data) => { - core.error(data); - reject(data); - }); - let output = ''; - let stderrOutput = ''; - execution.stdout.on('data', (data) => { - const dataStr = data.toString(); - output = `${output}${dataStr}`; - // Also log to see output in real-time - core.info(dataStr); - }); - execution.stderr.on('data', (data) => { - const dataStr = data.toString(); - stderrOutput = `${stderrOutput}${dataStr}`; - core.error(`stderr: ${dataStr}`); - }); - execution.on('close', (code) => __awaiter(this, void 0, void 0, function* () { - var _a; - //core.info(output); - core.info(`Scan finished with exit code: ${code}`); - // Combine stdout and stderr for URL extraction (URL might be in either) - const combinedOutput = `${output}${stderrOutput}`; - core.info(`Attempting to extract scan URL from combined output (stdout: ${output.length} chars, stderr: ${stderrOutput.length} chars)`); - // Extract and set scan URL output from combined output - const scanUrl = extractScanUrl(combinedOutput); - if (scanUrl) { - core.setOutput('scan-url', scanUrl); - core.info(`✓✓✓ SUCCESS: Scan URL extracted and set as output: ${scanUrl}`); - } - else { - core.warning('✗✗✗ FAILED: Scan URL not found in output'); - core.info(`Output length: ${output.length}, stderr length: ${stderrOutput.length}, combined: ${combinedOutput.length}`); - // Log a sample of the output to help debug - const fullReportIndex = combinedOutput.indexOf('Full Report'); - if (fullReportIndex >= 0) { - const sampleOutput = combinedOutput.substring(Math.max(0, fullReportIndex - 50), Math.min(combinedOutput.length, fullReportIndex + 200)); - core.info(`Sample output around "Full Report" (index ${fullReportIndex}): ${sampleOutput}`); - } - else { - core.info('"Full Report" text not found in combined output'); - } - } - //write output to file - // writeFile('scaResults.txt', output, (err) => { - // if (err) throw err; - // console.log('The file has been saved!'); - // }); - try { - (0, fs_2.writeFileSync)('scaResults.txt', combinedOutput); - console.log('The file has been saved!'); - } - catch (err) { - console.error('Error writing file:', err); - } - // Try to extract URL from the file as well (in case output variable missed something) - let fileOutput = combinedOutput; - try { - if ((0, fs_1.existsSync)('scaResults.txt')) { - const fileContent = (0, fs_1.readFileSync)('scaResults.txt', 'utf8'); - if (fileContent && fileContent.length > combinedOutput.length) { - fileOutput = fileContent; - if (core.isDebug()) { - core.info('Using file content for URL extraction (file is larger than captured output)'); - } - } - } - } - catch (err) { - // Ignore file read errors - } - // Re-extract URL from file output if not found in combined output - if (!scanUrl) { - const scanUrlFromFile = extractScanUrl(fileOutput); - if (scanUrlFromFile) { - core.setOutput('scan-url', scanUrlFromFile); - core.info(`Scan URL extracted from file: ${scanUrlFromFile}`); - } - } - // Store output files as artifacts (skip if in dual-scan mode) - const { DefaultArtifactClient } = __nccwpck_require__(76846); - const artifactV1 = __nccwpck_require__(20166); - let artifactClient; - if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { - artifactClient = artifactV1.create(); - core.info(`Initialized the artifact object using version V1.`); - } - else { - artifactClient = new DefaultArtifactClient(); - core.info(`Initialized the artifact object using version V2.`); - } - yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.txt']); - //Pull request decoration - core.info('check if we run on a pull request'); - let pullRequest = process.env.GITHUB_REF; - let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); - if (isPR >= 1) { - core.info("This run is part of a PR, should add some PR comment"); - const context = github.context; - const repository = process.env.GITHUB_REPOSITORY; - const repo = repository.split("/"); - const commentID = (_a = context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.number; - let commentBody = '
![](https://www.veracode.com/sites/default/files/2022-04/logo_1.svg)
'; - commentBody += "
Veracode SCA Scan finished with exit code " + code + "\n";
-                                commentBody += '\n
Veracode SCA Scan details

\n'; - commentBody += output; //.replace(/ /g, '    '); - commentBody += '

\n
'; - try { - const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; - const octokit = github.getOctokit(options.github_token, { baseUrl }); - const { data: comment } = yield octokit.rest.issues.createComment({ - owner: repo[0], - repo: repo[1], - issue_number: commentID, - body: commentBody, - }); - core.info('Adding scan results as comment to PR #' + commentID); - } - catch (error) { - core.info(error); - } - } - // if scan was set to fail the pipeline should fail and show a summary of the scan results - if (code != null && code > 0 && (options.breakBuildOnPolicyFindings == 'true')) { - let summary_info = "Veracode SCA Scan failed with exit code " + code + "\n"; - core.setFailed(summary_info); - } - //run(options,core.info); - core.info('Finish command'); - resolve(); - })); - }); - } - } - // Generate vulnerability list after scan completes - yield generateVulnList(options); - } - catch (error) { - if (error instanceof Error) { - core.info('Running scan failed.'); - //const output = stdout.toString(); - core.info(error.message); - //core.setFailed(error.message); - } - else { - core.setFailed("unknown error"); - console.log(error); - } - } - }); -} -/** - * Main entry point - runs a single unified scan - */ -function runAction(options) { - return __awaiter(this, void 0, void 0, function* () { - try { - // Single unified scan: when sca_fix_enabled, includes --show-cli for both JSON and CLI output - yield runScan(options); - } - catch (error) { - if (error instanceof Error) { - core.setFailed(error.message); - } - else { - core.setFailed("Unknown error during scan execution"); - } - } - }); -} -exports.runAction = runAction; -/** - * Generates SCA vulnerability list using Veracode CLI - * This function is called at the end of runAction when sca_fix_enabled is true - */ -function generateVulnList(options) { - return __awaiter(this, void 0, void 0, function* () { - try { - core.info('=== Starting SCA Vulnerability List Generation ==='); - // Check if sca_fix_enabled is true - if (!options.scaFixEnabled) { - core.info('veracode-sca-fix is NOT enabled, skipping vulnerability list generation'); - return; - } - core.info('veracode-sca-fix is enabled, proceeding with vulnerability list generation'); - // Check if PR number exists in options - if (!options.prNumber || options.prNumber === 0 || isNaN(options.prNumber)) { - core.info('No PR number found in options, skipping vulnerability list generation'); - return; - } - const prNumber = options.prNumber; - core.info(`PR number found: ${prNumber}`); - // Check if scaResults.json exists - if (!(0, fs_1.existsSync)(index_1.SCA_OUTPUT_FILE)) { - core.warning(`SCA results file not found: ${index_1.SCA_OUTPUT_FILE}. Skipping vulnerability list generation.`); - return; - } - // Check for required environment variables - const veracodeApiKeyId = process.env.VERACODE_API_KEY_ID; - const veracodeApiKeySecret = process.env.VERACODE_API_KEY_SECRET; - if (!veracodeApiKeyId || !veracodeApiKeySecret) { - core.warning('VERACODE_API_KEY_ID or VERACODE_API_KEY_SECRET not set. Skipping vulnerability list generation.'); - return; - } - const workingDir = process.cwd(); - core.info(`Working directory: ${workingDir}`); - // Check if helper/cli directory exists - const helperCliPath = runnerOS === 'Windows' - ? `${workingDir}\\veracode-helper\\helper\\cli` - : `${workingDir}/veracode-helper/helper/cli`; - if (!(0, fs_1.existsSync)(helperCliPath)) { - core.warning(`Helper CLI directory not found at ${helperCliPath}. Skipping vulnerability list generation.`); - return; - } - let cliExecutablePath = ''; - let veracodeCommand; - const vulnListingFile = 'veracode-cli.vuln.listing.json'; - if (runnerOS === 'Windows') { - // Windows implementation - // Find the CLI ps1 installer file - const findPs1Command = `powershell -NoProfile -ExecutionPolicy Bypass -Command "Get-ChildItem -Path '${helperCliPath}' -Filter *.ps1 | Select-Object -First 1 -ExpandProperty FullName"`; - const installerFile = (0, child_process_1.execSync)(findPs1Command, { encoding: 'utf-8' }).trim(); - if (!installerFile || installerFile === '') { - core.warning(`No CLI ps1 installer file found in ${helperCliPath}. Skipping vulnerability list generation.`); - return; - } - core.info(`Found CLI installer: ${installerFile}`); - // Run the installer to install Veracode CLI - core.info('Running Veracode CLI installer...'); - try { - const installCommand = `powershell -NoProfile -ExecutionPolicy Bypass -File "${installerFile}"`; - const installOutput = (0, child_process_1.execSync)(installCommand, { encoding: 'utf-8' }); - core.info('Veracode CLI installation completed'); - if (core.isDebug()) { - core.info(installOutput); - } - } - catch (error) { - core.warning(`Failed to install Veracode CLI: ${error.message}`); - return; - } - // Check where veracode command is located using Get-Command - core.info('Set veracode.exe command location...'); - const appDataPath = process.env.APPDATA || ''; - if (!appDataPath) { - core.warning('APPDATA environment variable not found. Skipping vulnerability list generation.'); - return; - } - cliExecutablePath = `${appDataPath}\\veracode\\veracode.exe`; - core.info(`Expected Veracode CLI installation path: ${cliExecutablePath}`); - // Verify the CLI was installed - if (!(0, fs_1.existsSync)(cliExecutablePath)) { - core.warning(`Veracode CLI not found at ${cliExecutablePath}. Installation may have failed.`); - return; - } - core.info(`Veracode CLI successfully installed and verified at: ${cliExecutablePath}`); - // Build the veracode fix sca command for Windows using full path - veracodeCommand = `"${cliExecutablePath}" fix sca "${workingDir}" -r "${workingDir}\\${index_1.SCA_OUTPUT_FILE}" --list-only --transitive --json "${vulnListingFile}"`; - core.info(`Running command: ${veracodeCommand}`); - } - else { - // Linux/Unix implementation - // Find the CLI tar.gz file - const cliFiles = (0, child_process_1.execSync)(`ls -1 ${helperCliPath}/*.tar.gz 2>/dev/null || echo ""`, { encoding: 'utf-8' }).trim(); - if (!cliFiles) { - core.warning(`No CLI tar.gz file found in ${helperCliPath}. Skipping vulnerability list generation.`); - return; - } - const cliFile = cliFiles.split('\n')[0]; // Get first file - const cliFileName = cliFile.replace('.tar.gz', '').split('/').pop(); - core.info(`Found CLI file: ${cliFile}`); - core.info(`Extracting to: ${cliFileName}`); - // Extract the CLI - (0, child_process_1.execSync)(`cd ${helperCliPath} && tar -zxf ${cliFile.split('/').pop()}`, { encoding: 'utf-8' }); - cliExecutablePath = `${helperCliPath}/${cliFileName}`; - core.info(`CLI executable path: ${cliExecutablePath}`); - // Build the veracode fix sca command - veracodeCommand = `${cliExecutablePath}/veracode fix sca "${workingDir}" -r "${workingDir}/${index_1.SCA_OUTPUT_FILE}" --list-only --transitive --json "${vulnListingFile}"`; - core.info(`Running command: ${veracodeCommand}`); - } - // Run the veracode fix sca command - try { - const output = (0, child_process_1.execSync)(veracodeCommand, { - encoding: 'utf-8', - env: Object.assign(Object.assign({}, process.env), { VERACODE_API_KEY_ID: veracodeApiKeyId, VERACODE_API_KEY_SECRET: veracodeApiKeySecret }) - }); - core.info('Veracode CLI execution successful'); - if (core.isDebug()) { - core.info(output); - } - // Check if vulnerability listing file was created - if (!(0, fs_1.existsSync)(vulnListingFile)) { - core.warning(`Vulnerability listing file not created: ${vulnListingFile}`); - return; - } - // Upload the vulnerability listing JSON as artifact - core.info('Uploading SCA vulnerability listing JSON as artifact'); - const { DefaultArtifactClient } = __nccwpck_require__(76846); - const artifactV1 = __nccwpck_require__(20166); - let artifactClient; - if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { - artifactClient = artifactV1.create(); - core.info('Initialized artifact client using version V1'); - } - else { - artifactClient = new DefaultArtifactClient(); - core.info('Initialized artifact client using version V2'); - } - const artifactName = 'sca-vuln-listing-json'; - const files = [vulnListingFile]; - const rootDirectory = workingDir; - const artifactOptions = { - continueOnError: true - }; - yield artifactClient.uploadArtifact(artifactName, files, rootDirectory, artifactOptions); - core.info('Successfully uploaded vulnerability listing JSON'); - core.info('=== SCA Vulnerability List Generation Complete ==='); - } - catch (error) { - core.error('Failed to run Veracode CLI command'); - core.error(error.message || error); - if (error.stdout) { - core.error(`stdout: ${error.stdout}`); - } - if (error.stderr) { - core.error(`stderr: ${error.stderr}`); - } - // Don't fail the entire action, just log the error - core.warning('Vulnerability list generation failed, but continuing action execution'); - } - } - catch (error) { - core.error('Error during vulnerability list generation'); - core.error(error.message || error); - core.warning('Vulnerability list generation failed, but continuing action execution'); - // Don't fail the action if vulnerability list generation fails - } - }); -} -const collectors = [ - "maven", - "gradle", - "ant", - "jar", - "sbt", - "glide", - "go get", - "go mod", - "godep", - "dep", - "govendor", - "trash", - "pip", - "pipenv", - "bower", - "yarn", - "npm", - "cocoapods", - "gem", - "composer", - "makefile", - "dll", - "msbuilddotnet", -]; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.runAction = void 0; +const child_process_1 = __nccwpck_require__(35317); +const core = __importStar(__nccwpck_require__(37484)); +const index_1 = __nccwpck_require__(79407); +const github = __importStar(__nccwpck_require__(93228)); +const fs_1 = __nccwpck_require__(79896); +const fs_2 = __nccwpck_require__(79896); +const runnerOS = process.env.RUNNER_OS; +const cleanCollectors = (inputArr) => { + let allowed = []; + for (var input of inputArr) { + if (input && collectors.indexOf(input.trim().toLowerCase()) > -1) { + allowed.push(input.trim().toLowerCase()); + } + } + return allowed; +}; +/** + * Extracts the scan URL from the Veracode SCA output + * Looks for a line containing "Full Report Details" followed by a URL + * Also tries to extract from JSON metadata if available + */ +const extractScanUrl = (output) => { + core.info('=== Starting URL extraction ==='); + if (!output) { + core.info('extractScanUrl: output is empty or null'); + return null; + } + core.info(`extractScanUrl: Output length is ${output.length} characters`); + // Pattern to match: "Full Report Details" followed by whitespace and a URL + // More flexible pattern that handles various whitespace amounts + // Matches: "Full Report Details" followed by any whitespace and then a URL starting with http:// or https:// + const patterns = [ + /Full\s+Report\s+Details\s+(https?:\/\/[^\s\r\n]+)/i, + /Full\s+Report\s+Details[:\s]+(https?:\/\/[^\s\r\n]+)/i, + /Full\s+Report\s+Details\s+(\S+)/i, + /Full\s+Report\s+Details[:\s]+(https?:\/\/[^\r\n]+)/i, // Handle newlines + ]; + // First, check if "Full Report Details" appears in the output at all + const hasFullReport = /Full\s+Report\s+Details/i.test(output); + core.info(`extractScanUrl: "Full Report Details" found in output: ${hasFullReport}`); + if (hasFullReport) { + // Find the line containing "Full Report Details" + const lines = output.split('\n'); + const fullReportLine = lines.find(line => /Full\s+Report\s+Details/i.test(line)); + if (fullReportLine) { + core.info(`extractScanUrl: Found line: "${fullReportLine.trim()}"`); + } + } + for (let i = 0; i < patterns.length; i++) { + const pattern = patterns[i]; + const match = output.match(pattern); + if (match && match[1]) { + const url = match[1].trim(); + // Validate it's a URL + if (url.startsWith('http://') || url.startsWith('https://')) { + core.info(`extractScanUrl: ✓ Found URL using pattern ${i + 1}: ${url}`); + return url; + } + else { + core.info(`extractScanUrl: Pattern ${i + 1} matched but result is not a URL: ${url}`); + } + } + } + core.info('extractScanUrl: No URL found in text output, trying JSON fallback'); + // Fallback: Try to extract from JSON if available + try { + if ((0, fs_1.existsSync)(index_1.SCA_OUTPUT_FILE)) { + core.info(`extractScanUrl: JSON file exists, attempting to read: ${index_1.SCA_OUTPUT_FILE}`); + const scaResultsTxt = (0, fs_1.readFileSync)(index_1.SCA_OUTPUT_FILE); + const scaResJson = JSON.parse(scaResultsTxt.toString('utf-8')); + if (scaResJson.records && scaResJson.records[0] && scaResJson.records[0].metadata && scaResJson.records[0].metadata.report) { + const url = scaResJson.records[0].metadata.report; + if (url.startsWith('http://') || url.startsWith('https://')) { + core.info(`extractScanUrl: ✓ Found URL in JSON metadata: ${url}`); + return url; + } + } + else { + core.info('extractScanUrl: JSON file exists but does not contain report URL in expected structure'); + } + } + else { + core.info(`extractScanUrl: JSON file does not exist: ${index_1.SCA_OUTPUT_FILE}`); + } + } + catch (error) { + core.info(`extractScanUrl: Error reading JSON fallback: ${error.message || error}`); + } + core.info('extractScanUrl: ✗ No URL found in output or JSON'); + core.info('=== URL extraction complete ==='); + return null; +}; +/** + * Upload SCA scan artifacts + * @param artifactClient - GitHub Actions artifact client + * @param artifactName - Name of the artifact to create + * @param files - Array of file paths to include in artifact + */ +function uploadArtifacts(artifactClient, artifactName, files) { + return __awaiter(this, void 0, void 0, function* () { + const fileList = files.join(', '); + core.info(`Uploading artifact '${artifactName}' with files: ${fileList}`); + try { + yield artifactClient.uploadArtifact(artifactName, files, process.cwd(), { continueOnError: true }); + core.info(`✓ Successfully uploaded artifact with ${files.length} file(s)`); + } + catch (error) { + core.warning(`Failed to upload artifact: ${error.message || error}`); + } + }); +} +/** + * When using --show-cli flag, both JSON and CLI text are produced + * This helper writes the CLI output (stdout) to scaResults.txt + * @param cliOutput - The stdout from the scan command + */ +function writeCliOutputToFile(cliOutput) { + return __awaiter(this, void 0, void 0, function* () { + try { + (0, fs_2.writeFileSync)('scaResults.txt', cliOutput); + core.info('CLI output written to scaResults.txt'); + } + catch (error) { + core.warning(`Failed to write CLI output to file: ${error.message || error}`); + } + }); +} +/** + * Runs a unified scan with --show-cli flag when sca_fix_enabled + * When sca_fix_enabled=true: Generates both JSON and CLI text output in one scan + * When sca_fix_enabled=false: Generates output based on createIssues/jsonOutput flags + * @param options - Scan options + */ +function runScan(options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + try { + core.info('Start command'); + let extraCommands = ''; + if (options.url.length > 0) { + extraCommands = `--url ${options.url} `; + } + else { + extraCommands = `${options.path} `; + } + const skip = cleanCollectors(options["skip-collectors"]); + let skipCollectorsAttr = ''; + if (skip.length > 0) { + skipCollectorsAttr = `--skip-collectors ${skip.toString()} `; + } + const scan = cleanCollectors(options["scan-collectors"]); + let scanCollectorsAttr = ''; + if (scan.length > 0) { + scanCollectorsAttr = `--scan-collectors ${scan.toString()} `; + } + const noGraphs = options["no-graphs"]; + const skipVMS = options["skip-vms"]; + // Generate JSON when sca_fix_enabled (uses --show-cli for both JSON and CLI text in single scan) + // or when createIssues is true (JSON for issue creation) + const shouldGenerateJson = options.createIssues || options.scaFixEnabled; + let commandOutput = ''; + if (options.scaFixEnabled) { + // Use --json --show-cli for unified output (JSON to file, CLI text to stdout) + commandOutput = `--json=${index_1.SCA_OUTPUT_FILE} --show-cli`; + } + else if (options.createIssues) { + // JSON output for issue creation + commandOutput = `--json=${index_1.SCA_OUTPUT_FILE}`; + } + // Always use the base artifact name regardless of output format + // (whether it contains JSON+TXT with --show-cli or TXT only) + const artifactNameBase = 'Veracode Agent Based SCA Results'; + extraCommands = `${extraCommands}${options.recursive ? '--recursive ' : ''}${options.quick ? '--quick ' : ''}${options.allowDirty ? '--allow-dirty ' : ''}${options.updateAdvisor ? '--update-advisor ' : ''}${skipVMS ? '--skip-vms ' : ''}${noGraphs ? '--no-graphs ' : ''}${options.noUpload ? '--no-upload ' : ''}${options.debug ? '--debug ' : ''}${skipCollectorsAttr}${scanCollectorsAttr}`; + if (runnerOS == 'Windows') { + const powershellCommand = `powershell -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest https://sca-downloads.veracode.com/ci.ps1 -OutFile $env:TEMP\\ci.ps1; & $env:TEMP\\ci.ps1 -s -- scan ${extraCommands} ${commandOutput}"`; + if (shouldGenerateJson) { + core.info('Starting the scan'); + let output = ''; + try { + output = (0, child_process_1.execSync)(powershellCommand, { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 10 }); //10MB + if (options.createIssues) { + core.info('Create issue "true" - on close'); + } + if (core.isDebug()) { + core.info(output); + } + // Extract and set scan URL output + const scanUrl = extractScanUrl(output); + if (scanUrl) { + core.setOutput('scan-url', scanUrl); + core.info(`Scan URL extracted: ${scanUrl}`); + } + else { + core.info('Scan URL not found in output'); + } + } + catch (error) { + if (error.status != null && error.status > 0 && (options.breakBuildOnPolicyFindings == 'true')) { + let summary_info = "Veracode SCA Scan failed with exit code " + error.statuscode + "\n"; + core.info(output); + core.setFailed(summary_info); + } + // Try to extract URL even if there was an error + const scanUrl = extractScanUrl(output); + if (scanUrl) { + core.setOutput('scan-url', scanUrl); + core.info(`Scan URL extracted: ${scanUrl}`); + } + } + // PR decoration and issue generation (only if createIssues is enabled) + if (options.createIssues) { + //Pull request decoration + core.info('check if we run on a pull request'); + let pullRequest = process.env.GITHUB_REF; + let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); + let summary_message = ""; + if (isPR >= 1) { + core.info('We run on a PR, add more messaging'); + const context = github.context; + const repository = process.env.GITHUB_REPOSITORY; + const repo = repository.split("/"); + const commentID = (_a = context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.number; + let pr_header = '
![](https://www.veracode.com/themes/veracode_new/library/img/veracode-black-hires.svg)
'; + summary_message = `Veracode SCA Scan finished. Please review created and linked issues`; + try { + const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; + const octokit = github.getOctokit(options.github_token, { baseUrl }); + const { data: comment } = yield octokit.rest.issues.createComment({ + owner: repo[0], + repo: repo[1], + issue_number: commentID, + body: pr_header + summary_message, + }); + core.info('Adding scan results message as comment to PR #' + commentID); + } + catch (error) { + core.info(error); + } + } + else { + summary_message = `Veracode SCA Scan finished. Please review created issues`; + } + //Generate issues + (0, index_1.run)(options, core.info); + core.info(summary_message); + } + // Store output files as artifacts + const { DefaultArtifactClient } = __nccwpck_require__(76846); + const artifactV1 = __nccwpck_require__(20166); + let artifactClient; + if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { + artifactClient = artifactV1.create(); + core.info(`Initialized the artifact object using version V1.`); + } + else { + artifactClient = new DefaultArtifactClient(); + core.info(`Initialized the artifact object using version V2.`); + } + // When --show-cli is used, we also have CLI output that needs to be saved + if (options.scaFixEnabled) { + // Write the CLI output (stdout) to scaResults.txt + yield writeCliOutputToFile(output); + // Upload both JSON and TXT files + yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.json', 'scaResults.txt']); + } + else { + // JSON-only upload for create-issues + yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.json']); + } + core.info('Finish command'); + } + else { + core.info('Command to run: ' + powershellCommand); + let output = ''; + let stderrOutput = ''; + try { + // execSync captures both stdout and stderr by default, but let's be explicit + output = (0, child_process_1.execSync)(powershellCommand, { + encoding: 'utf-8', + maxBuffer: 1024 * 1024 * 10, + stdio: ['pipe', 'pipe', 'pipe'] // stdin, stdout, stderr + }); //10MB + core.info(output); + core.info(`Attempting to extract scan URL from output (length: ${output.length} chars)`); + // Extract and set scan URL output + const scanUrl = extractScanUrl(output); + if (scanUrl) { + core.setOutput('scan-url', scanUrl); + core.info(`✓✓✓ SUCCESS: Scan URL extracted and set as output: ${scanUrl}`); + } + else { + core.warning('✗✗✗ FAILED: Scan URL not found in output'); + // Try to find the line with "Full Report Details" for debugging + const lines = output.split('\n'); + const fullReportLine = lines.find(line => line.toLowerCase().includes('full report details')); + if (fullReportLine) { + core.info(`Found "Full Report Details" line: ${fullReportLine}`); + } + else { + core.info('"Full Report Details" line not found in output'); + } + } + } + catch (error) { + // execSync throws on non-zero exit, but output might still be in error.stdout or error.stderr + if (error.stdout) { + output = error.stdout.toString(); + } + if (error.stderr) { + stderrOutput = error.stderr.toString(); + } + if (error.status != null && error.status > 0 && (options.breakBuildOnPolicyFindings == 'true')) { + let summary_info = "Veracode SCA Scan failed with exit code " + error.statuscode + "\n"; + core.setFailed(summary_info); + } + // Try to extract URL from combined output even if there was an error + const combinedOutput = `${output}${stderrOutput}`; + const scanUrl = extractScanUrl(combinedOutput); + if (scanUrl) { + core.setOutput('scan-url', scanUrl); + core.info(`Scan URL extracted from error output: ${scanUrl}`); + } + else if (core.isDebug()) { + core.info(`Could not extract URL. Output length: ${output.length}, stderr length: ${stderrOutput.length}`); + } + } + //write output to file + // writeFile('scaResults.txt', output, (err) => { + // if (err) throw err; + // console.log('The file has been saved!'); + // }); + try { + (0, fs_2.writeFileSync)('scaResults.txt', output); + console.log('The file has been saved!'); + } + catch (err) { + console.error('Error writing file:', err); + } + // core.info('reading file') + // try { + // const data = readFileSync('scaResults.txt', 'utf8'); + // console.log('Full file output: '+data); + // } catch (err) { + // console.error(err); + // } + // Store output files as artifacts (skip if in dual-scan mode) + const { DefaultArtifactClient } = __nccwpck_require__(76846); + const artifactV1 = __nccwpck_require__(20166); + let artifactClient; + if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { + artifactClient = artifactV1.create(); + core.info(`Initialized the artifact object using version V1.`); + } + else { + artifactClient = new DefaultArtifactClient(); + core.info(`Initialized the artifact object using version V2.`); + } + yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.txt']); + //Pull request decoration + core.info('check if we run on a pull request'); + let pullRequest = process.env.GITHUB_REF; + let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); + if (isPR >= 1) { + core.info("This run is part of a PR, should add some PR comment"); + const context = github.context; + const repository = process.env.GITHUB_REPOSITORY; + const repo = repository.split("/"); + const commentID = (_b = context.payload.pull_request) === null || _b === void 0 ? void 0 : _b.number; + let commentBody = '
![](https://www.veracode.com/sites/default/files/2022-04/logo_1.svg)
'; + commentBody += "
Veracode SCA Scan finished" + "\n";
+                        commentBody += '\n
Veracode SCA Scan details

\n'; + commentBody += output; //.replace(/ /g, '    '); + commentBody += '

\n
'; + try { + const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; + const octokit = github.getOctokit(options.github_token, { baseUrl }); + const { data: comment } = yield octokit.rest.issues.createComment({ + owner: repo[0], + repo: repo[1], + issue_number: commentID, + body: commentBody, + }); + core.info('Adding scan results as comment to PR #' + commentID); + } + catch (error) { + core.info(error); + } + } + //run(options,core.info); + core.info('Finish command'); + } + } + else { + const command = `curl -sSL https://download.sourceclear.com/ci.sh | sh -s -- scan ${extraCommands} ${commandOutput}`; + core.info(command); + if (shouldGenerateJson) { + core.info('Starting the scan'); + yield new Promise((resolve, reject) => { + const execution = (0, child_process_1.spawn)('sh', ['-c', command], { + stdio: "pipe", + shell: false + }); + execution.on('error', (data) => { + core.error(data); + reject(data); + }); + let output = ''; + let stderrOutput = ''; + execution.stdout.on('data', (data) => { + output = `${output}${data}`; + }); + execution.stderr.on('data', (data) => { + const dataStr = data.toString(); + stderrOutput = `${stderrOutput}${dataStr}`; + core.error(`stderr: ${dataStr}`); + }); + execution.on('close', (code) => __awaiter(this, void 0, void 0, function* () { + var _a; + if (options.createIssues) { + core.info('Create issue "true" - on close'); + } + if (core.isDebug()) { + core.info(output); + } + // Combine stdout and stderr for URL extraction (URL might be in either) + const combinedOutput = `${output}${stderrOutput}`; + core.info(`Attempting to extract scan URL from combined output (stdout: ${output.length} chars, stderr: ${stderrOutput.length} chars)`); + // Extract and set scan URL output from combined output + const scanUrl = extractScanUrl(combinedOutput); + if (scanUrl) { + core.setOutput('scan-url', scanUrl); + core.info(`✓✓✓ SUCCESS: Scan URL extracted and set as output: ${scanUrl}`); + } + else { + core.warning('✗✗✗ FAILED: Scan URL not found in output'); + core.info(`Output length: ${output.length}, stderr length: ${stderrOutput.length}, combined: ${combinedOutput.length}`); + // Log a sample of the output to help debug + const fullReportIndex = combinedOutput.indexOf('Full Report'); + if (fullReportIndex >= 0) { + const sampleOutput = combinedOutput.substring(Math.max(0, fullReportIndex - 50), Math.min(combinedOutput.length, fullReportIndex + 200)); + core.info(`Sample output around "Full Report" (index ${fullReportIndex}): ${sampleOutput}`); + } + else { + core.info('"Full Report" text not found in combined output'); + } + } + // PR decoration and issue generation (only if createIssues is enabled) + let summary_message = ""; + if (options.createIssues) { + //Pull request decoration + core.info('check if we run on a pull request'); + let pullRequest = process.env.GITHUB_REF; + let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); + if (isPR >= 1) { + core.info('We run on a PR, add more messaging'); + const context = github.context; + const repository = process.env.GITHUB_REPOSITORY; + const repo = repository.split("/"); + const commentID = (_a = context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.number; + let pr_header = '
![](https://www.veracode.com/themes/veracode_new/library/img/veracode-black-hires.svg)
'; + summary_message = `Veracode SCA Scan finished with exit code: ${code}. Please review created and linked issues`; + try { + const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; + const octokit = github.getOctokit(options.github_token, { baseUrl }); + const { data: comment } = yield octokit.rest.issues.createComment({ + owner: repo[0], + repo: repo[1], + issue_number: commentID, + body: pr_header + summary_message, + }); + core.info('Adding scan results message as comment to PR #' + commentID); + } + catch (error) { + core.info(error); + } + } + else { + summary_message = `Veracode SCA Scan finished with exit code: ${code}. Please review created issues`; + } + //Generate issues + (0, index_1.run)(options, core.info); + core.info(summary_message); + } + // if scan was set to fail the pipeline should fail and show a summary of the scan results + if (code != null && code > 0 && (options.breakBuildOnPolicyFindings == 'true')) { + let summary_info = "Veracode SCA Scan failed with exit code " + code + "\n"; + core.setFailed(summary_info); + } + // Store output files as artifacts + const { DefaultArtifactClient } = __nccwpck_require__(76846); + const artifactV1 = __nccwpck_require__(20166); + let artifactClient; + if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { + artifactClient = artifactV1.create(); + core.info(`Initialized the artifact object using version V1.`); + } + else { + artifactClient = new DefaultArtifactClient(); + core.info(`Initialized the artifact object using version V2.`); + } + // When --show-cli is used, we also have CLI output that needs to be saved + if (options.scaFixEnabled) { + // Write the CLI output (stdout) to scaResults.txt + yield writeCliOutputToFile(output); + // Upload both JSON and TXT files + yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.json', 'scaResults.txt']); + } + else { + // Traditional JSON-only upload + yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.json']); + } + core.info('Finish command'); + resolve(); + })); + }); + } + else { + core.info('Command to run: ' + command); + yield new Promise((resolve, reject) => { + const execution = (0, child_process_1.spawn)('sh', ['-c', command], { + stdio: "pipe", + shell: false + }); + execution.on('error', (data) => { + core.error(data); + reject(data); + }); + let output = ''; + let stderrOutput = ''; + execution.stdout.on('data', (data) => { + const dataStr = data.toString(); + output = `${output}${dataStr}`; + // Also log to see output in real-time + core.info(dataStr); + }); + execution.stderr.on('data', (data) => { + const dataStr = data.toString(); + stderrOutput = `${stderrOutput}${dataStr}`; + core.error(`stderr: ${dataStr}`); + }); + execution.on('close', (code) => __awaiter(this, void 0, void 0, function* () { + var _a; + //core.info(output); + core.info(`Scan finished with exit code: ${code}`); + // Combine stdout and stderr for URL extraction (URL might be in either) + const combinedOutput = `${output}${stderrOutput}`; + core.info(`Attempting to extract scan URL from combined output (stdout: ${output.length} chars, stderr: ${stderrOutput.length} chars)`); + // Extract and set scan URL output from combined output + const scanUrl = extractScanUrl(combinedOutput); + if (scanUrl) { + core.setOutput('scan-url', scanUrl); + core.info(`✓✓✓ SUCCESS: Scan URL extracted and set as output: ${scanUrl}`); + } + else { + core.warning('✗✗✗ FAILED: Scan URL not found in output'); + core.info(`Output length: ${output.length}, stderr length: ${stderrOutput.length}, combined: ${combinedOutput.length}`); + // Log a sample of the output to help debug + const fullReportIndex = combinedOutput.indexOf('Full Report'); + if (fullReportIndex >= 0) { + const sampleOutput = combinedOutput.substring(Math.max(0, fullReportIndex - 50), Math.min(combinedOutput.length, fullReportIndex + 200)); + core.info(`Sample output around "Full Report" (index ${fullReportIndex}): ${sampleOutput}`); + } + else { + core.info('"Full Report" text not found in combined output'); + } + } + //write output to file + // writeFile('scaResults.txt', output, (err) => { + // if (err) throw err; + // console.log('The file has been saved!'); + // }); + try { + (0, fs_2.writeFileSync)('scaResults.txt', combinedOutput); + console.log('The file has been saved!'); + } + catch (err) { + console.error('Error writing file:', err); + } + // Try to extract URL from the file as well (in case output variable missed something) + let fileOutput = combinedOutput; + try { + if ((0, fs_1.existsSync)('scaResults.txt')) { + const fileContent = (0, fs_1.readFileSync)('scaResults.txt', 'utf8'); + if (fileContent && fileContent.length > combinedOutput.length) { + fileOutput = fileContent; + if (core.isDebug()) { + core.info('Using file content for URL extraction (file is larger than captured output)'); + } + } + } + } + catch (err) { + // Ignore file read errors + } + // Re-extract URL from file output if not found in combined output + if (!scanUrl) { + const scanUrlFromFile = extractScanUrl(fileOutput); + if (scanUrlFromFile) { + core.setOutput('scan-url', scanUrlFromFile); + core.info(`Scan URL extracted from file: ${scanUrlFromFile}`); + } + } + // Store output files as artifacts (skip if in dual-scan mode) + const { DefaultArtifactClient } = __nccwpck_require__(76846); + const artifactV1 = __nccwpck_require__(20166); + let artifactClient; + if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { + artifactClient = artifactV1.create(); + core.info(`Initialized the artifact object using version V1.`); + } + else { + artifactClient = new DefaultArtifactClient(); + core.info(`Initialized the artifact object using version V2.`); + } + yield uploadArtifacts(artifactClient, artifactNameBase, ['scaResults.txt']); + //Pull request decoration + core.info('check if we run on a pull request'); + let pullRequest = process.env.GITHUB_REF; + let isPR = pullRequest === null || pullRequest === void 0 ? void 0 : pullRequest.indexOf("pull"); + if (isPR >= 1) { + core.info("This run is part of a PR, should add some PR comment"); + const context = github.context; + const repository = process.env.GITHUB_REPOSITORY; + const repo = repository.split("/"); + const commentID = (_a = context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.number; + let commentBody = '
![](https://www.veracode.com/sites/default/files/2022-04/logo_1.svg)
'; + commentBody += "
Veracode SCA Scan finished with exit code " + code + "\n";
+                                commentBody += '\n
Veracode SCA Scan details

\n'; + commentBody += output; //.replace(/ /g, '    '); + commentBody += '

\n
'; + try { + const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com'; + const octokit = github.getOctokit(options.github_token, { baseUrl }); + const { data: comment } = yield octokit.rest.issues.createComment({ + owner: repo[0], + repo: repo[1], + issue_number: commentID, + body: commentBody, + }); + core.info('Adding scan results as comment to PR #' + commentID); + } + catch (error) { + core.info(error); + } + } + // if scan was set to fail the pipeline should fail and show a summary of the scan results + if (code != null && code > 0 && (options.breakBuildOnPolicyFindings == 'true')) { + let summary_info = "Veracode SCA Scan failed with exit code " + code + "\n"; + core.setFailed(summary_info); + } + //run(options,core.info); + core.info('Finish command'); + resolve(); + })); + }); + } + } + // Generate vulnerability list after scan completes + yield generateVulnList(options); + } + catch (error) { + if (error instanceof Error) { + core.info('Running scan failed.'); + //const output = stdout.toString(); + core.info(error.message); + //core.setFailed(error.message); + } + else { + core.setFailed("unknown error"); + console.log(error); + } + } + }); +} +/** + * Main entry point - runs a single unified scan + */ +function runAction(options) { + return __awaiter(this, void 0, void 0, function* () { + try { + // Single unified scan: when sca_fix_enabled, includes --show-cli for both JSON and CLI output + yield runScan(options); + } + catch (error) { + if (error instanceof Error) { + core.setFailed(error.message); + } + else { + core.setFailed("Unknown error during scan execution"); + } + } + }); +} +exports.runAction = runAction; +/** + * Generates SCA vulnerability list using Veracode CLI + * This function is called at the end of runAction when sca_fix_enabled is true + */ +function generateVulnList(options) { + return __awaiter(this, void 0, void 0, function* () { + try { + core.info('=== Starting SCA Vulnerability List Generation ==='); + // Check if sca_fix_enabled is true + if (!options.scaFixEnabled) { + core.info('veracode-sca-fix is NOT enabled, skipping vulnerability list generation'); + return; + } + core.info('veracode-sca-fix is enabled, proceeding with vulnerability list generation'); + // Check if PR number exists in options + if (!options.prNumber || options.prNumber === 0 || isNaN(options.prNumber)) { + core.info('No PR number found in options, skipping vulnerability list generation'); + return; + } + const prNumber = options.prNumber; + core.info(`PR number found: ${prNumber}`); + // Check if scaResults.json exists + if (!(0, fs_1.existsSync)(index_1.SCA_OUTPUT_FILE)) { + core.warning(`SCA results file not found: ${index_1.SCA_OUTPUT_FILE}. Skipping vulnerability list generation.`); + return; + } + // Check for required environment variables + const veracodeApiKeyId = process.env.VERACODE_API_KEY_ID; + const veracodeApiKeySecret = process.env.VERACODE_API_KEY_SECRET; + if (!veracodeApiKeyId || !veracodeApiKeySecret) { + core.warning('VERACODE_API_KEY_ID or VERACODE_API_KEY_SECRET not set. Skipping vulnerability list generation.'); + return; + } + const workingDir = process.cwd(); + core.info(`Working directory: ${workingDir}`); + // Check if helper/cli directory exists + const helperCliPath = runnerOS === 'Windows' + ? `${workingDir}\\veracode-helper\\helper\\cli` + : `${workingDir}/veracode-helper/helper/cli`; + if (!(0, fs_1.existsSync)(helperCliPath)) { + core.warning(`Helper CLI directory not found at ${helperCliPath}. Skipping vulnerability list generation.`); + return; + } + let cliExecutablePath = ''; + let veracodeCommand; + const vulnListingFile = 'veracode-cli.vuln.listing.json'; + if (runnerOS === 'Windows') { + // Windows implementation + // Find the CLI ps1 installer file + const findPs1Command = `powershell -NoProfile -ExecutionPolicy Bypass -Command "Get-ChildItem -Path '${helperCliPath}' -Filter *.ps1 | Select-Object -First 1 -ExpandProperty FullName"`; + const installerFile = (0, child_process_1.execSync)(findPs1Command, { encoding: 'utf-8' }).trim(); + if (!installerFile || installerFile === '') { + core.warning(`No CLI ps1 installer file found in ${helperCliPath}. Skipping vulnerability list generation.`); + return; + } + core.info(`Found CLI installer: ${installerFile}`); + // Run the installer to install Veracode CLI + core.info('Running Veracode CLI installer...'); + try { + const installCommand = `powershell -NoProfile -ExecutionPolicy Bypass -File "${installerFile}"`; + const installOutput = (0, child_process_1.execSync)(installCommand, { encoding: 'utf-8' }); + core.info('Veracode CLI installation completed'); + if (core.isDebug()) { + core.info(installOutput); + } + } + catch (error) { + core.warning(`Failed to install Veracode CLI: ${error.message}`); + return; + } + // Check where veracode command is located using Get-Command + core.info('Set veracode.exe command location...'); + const appDataPath = process.env.APPDATA || ''; + if (!appDataPath) { + core.warning('APPDATA environment variable not found. Skipping vulnerability list generation.'); + return; + } + cliExecutablePath = `${appDataPath}\\veracode\\veracode.exe`; + core.info(`Expected Veracode CLI installation path: ${cliExecutablePath}`); + // Verify the CLI was installed + if (!(0, fs_1.existsSync)(cliExecutablePath)) { + core.warning(`Veracode CLI not found at ${cliExecutablePath}. Installation may have failed.`); + return; + } + core.info(`Veracode CLI successfully installed and verified at: ${cliExecutablePath}`); + // Build the veracode fix sca command for Windows using full path + veracodeCommand = `"${cliExecutablePath}" fix sca "${workingDir}" -r "${workingDir}\\${index_1.SCA_OUTPUT_FILE}" --list-only --transitive --json "${vulnListingFile}"`; + core.info(`Running command: ${veracodeCommand}`); + } + else { + // Linux/Unix implementation + // Find the CLI tar.gz file + const cliFiles = (0, child_process_1.execSync)(`ls -1 ${helperCliPath}/*.tar.gz 2>/dev/null || echo ""`, { encoding: 'utf-8' }).trim(); + if (!cliFiles) { + core.warning(`No CLI tar.gz file found in ${helperCliPath}. Skipping vulnerability list generation.`); + return; + } + const cliFile = cliFiles.split('\n')[0]; // Get first file + const cliFileName = cliFile.replace('.tar.gz', '').split('/').pop(); + core.info(`Found CLI file: ${cliFile}`); + core.info(`Extracting to: ${cliFileName}`); + // Extract the CLI + (0, child_process_1.execSync)(`cd ${helperCliPath} && tar -zxf ${cliFile.split('/').pop()}`, { encoding: 'utf-8' }); + cliExecutablePath = `${helperCliPath}/${cliFileName}`; + core.info(`CLI executable path: ${cliExecutablePath}`); + // Build the veracode fix sca command + veracodeCommand = `${cliExecutablePath}/veracode fix sca "${workingDir}" -r "${workingDir}/${index_1.SCA_OUTPUT_FILE}" --list-only --transitive --json "${vulnListingFile}"`; + core.info(`Running command: ${veracodeCommand}`); + } + // Run the veracode fix sca command + try { + const output = (0, child_process_1.execSync)(veracodeCommand, { + encoding: 'utf-8', + env: Object.assign(Object.assign({}, process.env), { VERACODE_API_KEY_ID: veracodeApiKeyId, VERACODE_API_KEY_SECRET: veracodeApiKeySecret }) + }); + core.info('Veracode CLI execution successful'); + if (core.isDebug()) { + core.info(output); + } + // Check if vulnerability listing file was created + if (!(0, fs_1.existsSync)(vulnListingFile)) { + core.warning(`Vulnerability listing file not created: ${vulnListingFile}`); + return; + } + // Upload the vulnerability listing JSON as artifact + core.info('Uploading SCA vulnerability listing JSON as artifact'); + const { DefaultArtifactClient } = __nccwpck_require__(76846); + const artifactV1 = __nccwpck_require__(20166); + let artifactClient; + if ((options === null || options === void 0 ? void 0 : options.platformType) === 'ENTERPRISE') { + artifactClient = artifactV1.create(); + core.info('Initialized artifact client using version V1'); + } + else { + artifactClient = new DefaultArtifactClient(); + core.info('Initialized artifact client using version V2'); + } + const artifactName = 'sca-vuln-listing-json'; + const files = [vulnListingFile]; + const rootDirectory = workingDir; + const artifactOptions = { + continueOnError: true + }; + yield artifactClient.uploadArtifact(artifactName, files, rootDirectory, artifactOptions); + core.info('Successfully uploaded vulnerability listing JSON'); + core.info('=== SCA Vulnerability List Generation Complete ==='); + } + catch (error) { + core.error('Failed to run Veracode CLI command'); + core.error(error.message || error); + if (error.stdout) { + core.error(`stdout: ${error.stdout}`); + } + if (error.stderr) { + core.error(`stderr: ${error.stderr}`); + } + // Don't fail the entire action, just log the error + core.warning('Vulnerability list generation failed, but continuing action execution'); + } + } + catch (error) { + core.error('Error during vulnerability list generation'); + core.error(error.message || error); + core.warning('Vulnerability list generation failed, but continuing action execution'); + // Don't fail the action if vulnerability list generation fails + } + }); +} +const collectors = [ + "maven", + "gradle", + "ant", + "jar", + "sbt", + "glide", + "go get", + "go mod", + "godep", + "dep", + "govendor", + "trash", + "pip", + "pipenv", + "bower", + "yarn", + "npm", + "cocoapods", + "gem", + "composer", + "makefile", + "dll", + "msbuilddotnet", +]; /***/ }), diff --git a/src/action.ts b/src/action.ts index ed7b070..9e3b9bf 100644 --- a/src/action.ts +++ b/src/action.ts @@ -18,6 +18,7 @@ const options: Options = { debug: core.getBooleanInput('debug'), "skip-vms": core.getBooleanInput('skip-vms'), "no-graphs": core.getBooleanInput('no-graphs'), + noUpload: core.getBooleanInput('no-upload'), recursive: core.getBooleanInput('recursive'), "skip-collectors": core.getInput('skip-collectors').split(','), "scan-collectors": core.getInput('scan-collectors').split(','), diff --git a/src/options.d.ts b/src/options.d.ts index 1ca0195..bde7ac3 100644 --- a/src/options.d.ts +++ b/src/options.d.ts @@ -12,6 +12,7 @@ export interface Options { recursive:boolean, "skip-vms":boolean, "no-graphs":boolean, + noUpload: boolean, "skip-collectors": Array, "scan-collectors": Array platformType: string, diff --git a/src/srcclr.ts b/src/srcclr.ts index a22ae6b..3b24eac 100644 --- a/src/srcclr.ts +++ b/src/srcclr.ts @@ -188,7 +188,7 @@ async function runScan(options: Options): Promise { // Always use the base artifact name regardless of output format // (whether it contains JSON+TXT with --show-cli or TXT only) const artifactNameBase = 'Veracode Agent Based SCA Results'; - extraCommands = `${extraCommands}${options.recursive ? '--recursive ' : ''}${options.quick ? '--quick ' : ''}${options.allowDirty ? '--allow-dirty ' : ''}${options.updateAdvisor ? '--update-advisor ' : ''}${skipVMS ? '--skip-vms ' : ''}${noGraphs ? '--no-graphs ' : ''}${options.debug ? '--debug ' : ''}${skipCollectorsAttr}${scanCollectorsAttr}`; + extraCommands = `${extraCommands}${options.recursive ? '--recursive ' : ''}${options.quick ? '--quick ' : ''}${options.allowDirty ? '--allow-dirty ' : ''}${options.updateAdvisor ? '--update-advisor ' : ''}${skipVMS ? '--skip-vms ' : ''}${noGraphs ? '--no-graphs ' : ''}${options.noUpload ? '--no-upload ' : ''}${options.debug ? '--debug ' : ''}${skipCollectorsAttr}${scanCollectorsAttr}`; if (runnerOS == 'Windows') { const powershellCommand = `powershell -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest https://sca-downloads.veracode.com/ci.ps1 -OutFile $env:TEMP\\ci.ps1; & $env:TEMP\\ci.ps1 -s -- scan ${extraCommands} ${commandOutput}"` diff --git a/src/test/testRun.ts b/src/test/testRun.ts index 7537320..a95cb87 100644 --- a/src/test/testRun.ts +++ b/src/test/testRun.ts @@ -19,6 +19,7 @@ const options: Options = { recursive:false, "skip-vms":false, "no-graphs":false, + noUpload: false, platformType:'CLOUD', breakBuildOnPolicyFindings:'false', scaFixEnabled: false,