@conterra/vuln-scan 1.0.9 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ht=Object.create;var Xe=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Jt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var Qe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var zt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of qt(t))!Yt.call(e,i)&&i!==r&&Xe(e,i,{get:()=>t[i],enumerable:!(n=Gt(t,i))||n.enumerable});return e};var Y=(e,t,r)=>(r=e!=null?Ht(Jt(e)):{},zt(t||!e||!e.__esModule?Xe(r,"default",{value:e,enumerable:!0}):r,e));var ft=Qe((hn,ut)=>{"use strict";ut.exports=ur;function cr(e){let t={defaultWidth:0,output:process.stdout,tty:require("tty")};return e?(Object.keys(t).forEach(function(r){e[r]||(e[r]=t[r])}),e):t}function ur(e){let t=cr(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return t.defaultWidth}});var It=Qe((Tn,Tt)=>{var Rr=require("stream"),ke=class extends Rr{#r=null;constructor(t={}){super(t),this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=t.replace,this._prompt=t.prompt||null,this._hadControl=!1}#t(t,r){return this._dest?this._dest[t]:this._src?this._src[t]:r}#e(t,...r){typeof this._dest?.[t]=="function"&&this._dest[t](...r),typeof this._src?.[t]=="function"&&this._src[t](...r)}get isTTY(){return this.#r!==null?this.#r:this.#t("isTTY",!1)}set isTTY(t){this.#r=t}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(t){this._src=t}pipe(t,r){return this._dest=t,super.pipe(t,r)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(t){if(this.muted){if(!this.replace)return!0;if(t.match(/^\u001b/))return t.indexOf(this._prompt)===0&&(t=t.slice(this._prompt.length),t=t.replace(/./g,this.replace),t=this._prompt+t),this._hadControl=!0,this.emit("data",t);this._prompt&&this._hadControl&&t.indexOf(this._prompt)===0&&(this._hadControl=!1,this.emit("data",this._prompt),t=t.slice(this._prompt.length)),t=t.toString().replace(/./g,this.replace)}this.emit("data",t)}end(t){this.muted&&(t&&this.replace?t=t.toString().replace(/./g,this.replace):t=null),t&&this.emit("data",t),this.emit("end")}destroy(...t){return this.#e("destroy",...t)}destroySoon(...t){return this.#e("destroySoon",...t)}close(...t){return this.#e("close",...t)}};Tt.exports=ke});var pe=Y(require("path"));var C=require("fs/promises");async function de(e){try{return await Xt(e)?JSON.parse(await(0,C.readFile)(e,{encoding:"utf-8"})):void 0}catch(t){throw new Error(`Error reading JSON file ${e}: ${t}`,{cause:t})}}async function Ze(e,t){let r=JSON.stringify(t,null,4)+`
3
- `,n=await Qt(e,r);await(0,C.writeFile)(e,n,{encoding:"utf-8"})}async function Xt(e){try{return await(0,C.access)(e,C.constants.F_OK),!0}catch{return!1}}async function Qt(e,t){let r=await er();if(!r)return t;let n=await r.resolveConfig(e);return n?await r.format(t,{...n,filepath:e}):t}var Zt;function er(){return Zt??=import("prettier").catch(()=>{})}var Be;async function et(e){if(Be)return Be;let t="https://repository.conterra.de/repository/maven-mirror-ct",r=G(e.workingDir,"input/vex"),n=G(e.workingDir,"output"),i=G(e.workingDir,"cache"),a=["grype","trivy","ossindex"],s=G(e.workingDir,"vuln-scan-conf.json"),o=await de(s);if(!o)throw new Error(`Missing project configuration file '${s}'`);let m=o.findNoLongerDetectedVulnerabilitiesOnlyForSnapshots??!1;return Be={projectConfigFileLocation:s,onNewVulnerabilities:o.onNewVulnerabilities??(o.failOnNewVulnerabilities?"fail":"warn"),onNoLongerDetectedVulnerabilities:o.onNoLongerDetectedVulnerabilities??"ignore",reportNoLongerDetectedVulnerabilities:o.reportNoLongerDetectedVulnerabilities??!0,consoleReport:o.consoleReport||"BY_PROJECT_DETAILED",createSubDirsForProject:o.createSubDirsForProject??!0,mavenRepo:o.mavenRepo??t,vexUrls:o.vexUrls??[],vexDir:G(e.workingDir,o.vexDir)??r,outDir:G(e.workingDir,o.outDir)??n,cacheDir:G(e.workingDir,o.cacheDir)??i,scanners:(o.scanners??a).map(p=>{if(typeof p!="string")throw new Error(`Invalid scanner name '${p}' in configuration file '${s}'`);let c=p.split("@");if(c.length>2)throw new Error(`Invalid scanner name '${p}' in configuration file '${s}'`);let l=c[0],f=c[1]??"";return{name:l,version:f}}),projects:(o.projects??[]).map(p=>{let c=p;if(!c.name)throw new Error("Project name is missing on entry:"+JSON.stringify(c));if(!c.version)throw new Error("Project version is missing on entry:"+JSON.stringify(c));if(!c.purl)throw new Error("Project purl is missing on entry:"+JSON.stringify(c));return c.purlAliases||(c.purlAliases=[]),c.enabled==null&&(c.enabled=!0),c.silent==null&&(c.silent=!1),c.minimumSeverity||(c.minimumSeverity="UNKNOWN"),c.sbomFile?{...c,sbomFile:G(e.workingDir,c.sbomFile)}:(c.detectNoLongerUsedVulnerabilities=m?c.purl.endsWith("-SNAPSHOT"):!0,p)})}}function G(e,t){if(t)return pe.default.isAbsolute(t)?t:(0,pe.resolve)(e,t)}var Vt=require("path");var Kt=require("crypto");var j=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",z=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n",Te=e=>e.name==="space",oe=e=>e.name==="backspace",se=e=>e.name==="tab",le=e=>"1234567890".includes(e.name),$=e=>e.name==="enter"||e.name==="return";var he=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},me=class extends Error{name="CancelPromptError";message="Prompt was canceled"},ae=class extends Error{name="ExitPromptError"},ge=class extends Error{name="HookError"},q=class extends Error{name="ValidationError"};var it=require("node:async_hooks");var be=require("node:async_hooks");var tt=new be.AsyncLocalStorage;function tr(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function rt(e,t){let r=tr(e);return tt.run(r,()=>{function n(i){r.handleChange=()=>{r.index=0,i()},r.handleChange()}return t(n)})}function X(){let e=tt.getStore();if(!e)throw new ge("[Inquirer] Hook functions can only be called from within a prompt");return e}function Ie(){return X().rl}function Fe(e){let t=(...r)=>{let n=X(),i=!1,a=n.handleChange;n.handleChange=()=>{i=!0};let s=e(...r);return i&&a(),n.handleChange=a,s};return be.AsyncResource.bind(t)}function re(e){let t=X(),{index:r}=t,n={get(){return t.hooks[r]},set(a){t.hooks[r]=a},initialized:r in t.hooks},i=e(n);return t.index++,i}function nt(){X().handleChange()}var Q={queue(e){let t=X(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let n=e(Ie());if(n!=null&&typeof n!="function")throw new q("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=n})},run(){let e=X();Fe(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=X();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function rr(e){return typeof e=="function"}function L(e){return re(t=>{let r=it.AsyncResource.bind(function(a){t.get()!==a&&(t.set(a),nt())});if(t.initialized)return[t.get(),r];let n=rr(e)?e():e;return t.set(n),[n,r]})}function M(e,t){re(r=>{let n=r.get();(!Array.isArray(n)||t.some((a,s)=>!Object.is(a,n[s])))&&Q.queue(e),r.set(t)})}var v=require("node:util");var P=Y(require("node:process"),1);function nr(){return P.default.platform.startsWith("win")?!!P.default.env.CI||!!P.default.env.WT_SESSION||!!P.default.env.TERMINUS_SUBLIME||P.default.env.ConEmuTask==="{cmd::Cmder}"||P.default.env.TERM_PROGRAM==="Terminus-Sublime"||P.default.env.TERM_PROGRAM==="vscode"||P.default.env.TERM==="xterm-256color"||P.default.env.TERM==="alacritty"||P.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm":P.default.env.TERM!=="linux"}var ot={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},st={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},ir={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},or={...ot,...st},sr={...ot,...ir},lr=nr(),ar=lr?or:sr,N=ar,Yr=Object.entries(st);var lt={prefix:{idle:(0,v.styleText)("blue","?"),done:(0,v.styleText)("green",N.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>(0,v.styleText)("yellow",e))},style:{answer:e=>(0,v.styleText)("cyan",e),message:e=>(0,v.styleText)("bold",e),error:e=>(0,v.styleText)("red",`> ${e}`),defaultAnswer:e=>(0,v.styleText)("dim",`(${e})`),help:e=>(0,v.styleText)("dim",e),highlight:e=>(0,v.styleText)("cyan",e),key:e=>(0,v.styleText)("cyan",(0,v.styleText)("bold",`<${e}>`))}};function at(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function ct(...e){let t={};for(let r of e)for(let[n,i]of Object.entries(r)){let a=t[n];t[n]=at(a)&&at(i)?ct(a,i):i}return t}function A(...e){let t=[lt,...e.filter(r=>r!=null)];return ct(...t)}function W({status:e="idle",theme:t}){let[r,n]=L(!1),[i,a]=L(0),{prefix:s,spinner:o}=A(t);return M(()=>{if(e==="loading"){let p,c=-1,l=setTimeout(()=>{n(!0),p=setInterval(()=>{c=c+1,a(c%o.frames.length)},o.interval)},300);return()=>{clearTimeout(l),clearInterval(p)}}else n(!1)},[e]),r?o.frames[i]:typeof s=="string"?s:s[e==="loading"?"idle":e]??s.idle}function Z(e,t){return re(r=>{let n=r.get();if(!n||n.dependencies.length!==t.length||n.dependencies.some((i,a)=>i!==t[a])){let i=e();return r.set({value:i,dependencies:t}),i}return n.value})}function ee(e){return L({current:e})[0]}function V(e){let t=ee(e);t.current=e,M(r=>{let n=!1,i=Fe((a,s)=>{n||t.current(s,r)});return r.input.on("keypress",i),()=>{n=!0,r.input.removeListener("keypress",i)}},[])}var Bt=Y(ft(),1);var dt=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let r=0;for(e.lastIndex=0;e.test(t);)r+=1;return t.length-r}})(),pt=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ht=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var fr=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,dr=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,mt=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,pr=/\t{1,1000}/y,gt=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),hr=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,mr=new RegExp("\\p{M}+","gu"),gr={limit:1/0,ellipsis:""},bt=(e,t={},r={})=>{let n=t.limit??1/0,i=t.ellipsis??"",a=t?.ellipsisWidth??(i?bt(i,gr,r).width:0),s=0,o=r.controlWidth??0,m=r.tabWidth??8,p=r.emojiWidth??2,c=2,l=r.regularWidth??1,f=r.wideWidth??c,w=[[hr,l],[fr,s],[dr,o],[pr,m],[gt,p],[mt,f]],d=0,h=0,g=e.length,D=0,b=!1,E=g,R=Math.max(0,n-a),T=0,_=0,I=0,F=0;e:for(;;){if(_>T||h>=g&&h>d){let u=e.slice(T,_)||e.slice(d,h);D=0;for(let x of u.replaceAll(mr,"")){let S=x.codePointAt(0)||0;if(pt(S)?F=c:ht(S)?F=f:F=l,I+F>R&&(E=Math.min(E,Math.max(T,d)+D)),I+F>n){b=!0;break e}D+=x.length,I+=F}T=_=0}if(h>=g)break e;for(let u=0,x=w.length;u<x;u++){let[S,y]=w[u];if(S.lastIndex=h,S.test(e)){if(D=S===mt?dt(e.slice(h,S.lastIndex)):S===gt?1:S.lastIndex-h,F=D*y,I+F>R&&(E=Math.min(E,h+Math.floor((R-I)/y))),I+F>n){b=!0;break e}I+=F,T=d,_=h,h=d=S.lastIndex;continue e}}h+=1}return{width:b?R:I,index:b?E:g,truncated:b,ellipsed:b&&n>=a}},wt=bt;var br={limit:1/0,ellipsis:"",ellipsisWidth:0},wr=(e,t={})=>wt(e,br,t).width,K=wr;var we="\x1B",yt="\x9B",xr=39,Pe="\x07",Lt="[",Dr="]",Rt="m",ve=`${Dr}8;;`,xt=new RegExp(`(?:\\${Lt}(?<code>\\d+)m|\\${ve}(?<uri>.*)${Pe})`,"y"),Dt=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},St=e=>`${we}${Lt}${e}${Rt}`,Et=e=>`${we}${ve}${e}${Pe}`,Ue=(e,t,r)=>{let n=t[Symbol.iterator](),i=!1,a=!1,s=e.at(-1),o=s===void 0?0:K(s),m=n.next(),p=n.next(),c=0;for(;!m.done;){let l=m.value,f=K(l);o+f<=r?e[e.length-1]+=l:(e.push(l),o=0),(l===we||l===yt)&&(i=!0,a=t.startsWith(ve,c+1)),i?a?l===Pe&&(i=!1,a=!1):l===Rt&&(i=!1):(o+=f,o===r&&!p.done&&(e.push(""),o=0)),m=p,p=n.next(),c+=l.length}s=e.at(-1),!o&&s!==void 0&&s.length&&e.length>1&&(e[e.length-2]+=e.pop())},Sr=e=>{let t=e.split(" "),r=t.length;for(;r&&!K(t[r-1]);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},Er=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,a,s=e.split(" "),o=[""],m=0;for(let l=0;l<s.length;l++){let f=s[l];if(r.trim!==!1){let d=o.at(-1)??"",h=d.trimStart();d.length!==h.length&&(o[o.length-1]=h,m=K(h))}l!==0&&(m>=t&&(r.wordWrap===!1||r.trim===!1)&&(o.push(""),m=0),(m||r.trim===!1)&&(o[o.length-1]+=" ",m++));let w=K(f);if(r.hard&&w>t){let d=t-m,h=1+Math.floor((w-d-1)/t);Math.floor((w-1)/t)<h&&o.push(""),Ue(o,f,t),m=K(o.at(-1)??"");continue}if(m+w>t&&m&&w){if(r.wordWrap===!1&&m<t){Ue(o,f,t),m=K(o.at(-1)??"");continue}o.push(""),m=0}if(m+w>t&&r.wordWrap===!1){Ue(o,f,t),m=K(o.at(-1)??"");continue}o[o.length-1]+=f,m+=w}r.trim!==!1&&(o=o.map(l=>Sr(l)));let p=o.join(`
4
- `),c=!1;for(let l=0;l<p.length;l++){let f=p[l];if(n+=f,c)c=!1;else if(c=f>="\uD800"&&f<="\uDBFF",c)continue;if(f===we||f===yt){xt.lastIndex=l+1;let d=xt.exec(p)?.groups;if(d?.code!==void 0){let h=Number.parseFloat(d.code);i=h===xr?void 0:h}else d?.uri!==void 0&&(a=d.uri.length===0?void 0:d.uri)}if(p[l+1]===`
5
- `){a&&(n+=Et(""));let w=i?Dt(i):void 0;i&&w&&(n+=St(w))}else f===`
6
- `&&(i&&Dt(i)&&(n+=St(i)),a&&(n+=Et(a)))}return n},yr=/\r?\n/;function _t(e,t,r){return String(e).normalize().split(yr).map(n=>Er(n,t,r)).join(`
7
- `)}function ce(e,t){return e.split(`
8
- `).flatMap(r=>_t(r,t,{trim:!1,hard:!0}).split(`
2
+ "use strict";var Zt=Object.create;var rt=Object.defineProperty;var er=Object.getOwnPropertyDescriptor;var tr=Object.getOwnPropertyNames;var rr=Object.getPrototypeOf,nr=Object.prototype.hasOwnProperty;var nt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ir=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of tr(e))!nr.call(t,i)&&i!==r&&rt(t,i,{get:()=>e[i],enumerable:!(n=er(e,i))||n.enumerable});return t};var X=(t,e,r)=>(r=t!=null?Zt(rr(t)):{},ir(e||!t||!t.__esModule?rt(r,"default",{value:t,enumerable:!0}):r,t));var bt=nt((Un,xt)=>{"use strict";xt.exports=xr;function wr(t){let e={defaultWidth:0,output:process.stdout,tty:require("tty")};return t?(Object.keys(e).forEach(function(r){t[r]||(t[r]=e[r])}),t):e}function xr(t){let e=wr(t);if(e.output.getWindowSize)return e.output.getWindowSize()[0]||e.defaultWidth;if(e.tty.getWindowSize)return e.tty.getWindowSize()[1]||e.defaultWidth;if(e.output.columns)return e.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return e.defaultWidth}});var kt=nt((Jn,At)=>{var Ur=require("stream"),je=class extends Ur{#r=null;constructor(e={}){super(e),this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,r){return this._dest?this._dest[e]:this._src?this._src[e]:r}#e(e,...r){typeof this._dest?.[e]=="function"&&this._dest[e](...r),typeof this._src?.[e]=="function"&&this._src[e](...r)}get isTTY(){return this.#r!==null?this.#r:this.#t("isTTY",!1)}set isTTY(e){this.#r=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,r){return this._dest=e,super.pipe(e,r)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/))return e.indexOf(this._prompt)===0&&(e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e),this._hadControl=!0,this.emit("data",e);this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0&&(this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length)),e=e.toString().replace(/./g,this.replace)}this.emit("data",e)}end(e){this.muted&&(e&&this.replace?e=e.toString().replace(/./g,this.replace):e=null),e&&this.emit("data",e),this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}};At.exports=je});var G=X(require("path")),_e=require("fs/promises");var N=require("fs/promises");async function me(t){try{return await or(t)?JSON.parse(await(0,N.readFile)(t,{encoding:"utf-8"})):void 0}catch(e){throw new Error(`Error reading JSON file ${t}: ${e}`,{cause:e})}}async function it(t,e){let r=JSON.stringify(e,null,4)+`
3
+ `,n=await sr(t,r);await(0,N.writeFile)(t,n,{encoding:"utf-8"})}async function or(t){try{return await(0,N.access)(t,N.constants.F_OK),!0}catch{return!1}}async function sr(t,e){let r=await lr();if(!r)return e;let n=await r.resolveConfig(t);return n?await r.format(e,{...n,filepath:t}):e}var ar;function lr(){return ar??=import("prettier").catch(()=>{})}var oe=["UNKNOWN","LOW","MEDIUM","HIGH","CRITICAL"];var Be=class t{constructor(e){this.workingDir=e}workingDir;static DEFAULT_MAVEN_REPO="https://repository.conterra.de/repository/maven-mirror-ct";static DEFAULT_VEX_SUBDIR="input/vex";static DEFAULT_OUT_SUBDIR="output";static DEFAULT_CACHE_SUBDIR="cache";static DEFAULT_SCANNERS=["grype","trivy","ossindex"];normalize(e,r){let n=e.findNoLongerDetectedVulnerabilitiesOnlyForSnapshots??!1;return{projectConfigFileLocation:r,onNewVulnerabilities:e.onNewVulnerabilities??(e.failOnNewVulnerabilities?"fail":"warn"),onNoLongerDetectedVulnerabilities:e.onNoLongerDetectedVulnerabilities??"ignore",reportNoLongerDetectedVulnerabilities:e.reportNoLongerDetectedVulnerabilities??!0,consoleReport:e.consoleReport??"BY_PROJECT_DETAILED",createSubDirsForProject:e.createSubDirsForProject??!0,mavenRepo:e.mavenRepo??t.DEFAULT_MAVEN_REPO,vexUrls:e.vexUrls??[],vexDir:this.resolvePath(e.vexDir)??(0,G.resolve)(this.workingDir,t.DEFAULT_VEX_SUBDIR),outDir:this.resolvePath(e.outDir)??(0,G.resolve)(this.workingDir,t.DEFAULT_OUT_SUBDIR),cacheDir:this.resolvePath(e.cacheDir)??(0,G.resolve)(this.workingDir,t.DEFAULT_CACHE_SUBDIR),scanners:this.normalizeScanners(e.scanners,r),projects:this.normalizeProjects(e.projects??[],n)}}normalizeScanners(e,r){return(e??t.DEFAULT_SCANNERS).map(i=>{if(typeof i!="string")throw new Error(`Invalid scanner name '${String(i)}' in configuration file '${r}'`);let o=i.split("@");if(o.length>2)throw new Error(`Invalid scanner name '${i}' in configuration file '${r}'`);return{name:o[0],version:o[1]??""}})}normalizeProjects(e,r){return e.map(n=>{let i=n;if(!i.name)throw new Error("Project name is missing on entry: "+JSON.stringify(i));if(!i.version)throw new Error("Project version is missing on entry: "+JSON.stringify(i));if(!i.purl)throw new Error("Project purl is missing on entry: "+JSON.stringify(i));let o={...i,purlAliases:i.purlAliases??[],enabled:i.enabled??!0,silent:i.silent??!1,minimumSeverity:i.minimumSeverity??"UNKNOWN"};return o.sbomFile?{...o,sbomFile:this.resolvePath(o.sbomFile)??o.sbomFile}:{...o,detectNoLongerUsedVulnerabilities:r?o.purl.endsWith("-SNAPSHOT"):!0}})}resolvePath(e){if(e)return G.default.isAbsolute(e)?e:(0,G.resolve)(this.workingDir,e)}},he=class{constructor(e){this.workingDir=e;this.normalizer=new Be(e)}workingDir;normalizer;projectConfigCache;async loadProjectConfig(){return this.projectConfigCache??=this.doLoadProjectConfig(),this.projectConfigCache}async doLoadProjectConfig(){let e=(0,G.resolve)(this.workingDir,"vuln-scan-conf.json"),r=await me(e);if(!r)throw new Error(`Missing project configuration file '${e}'`);return this.normalizer.normalize(r,e)}async loadJiraConfig(e){let r=await(0,_e.readFile)(e,"utf8"),n=JSON.parse(r);if(!n.issues&&n.issue&&(n.issues=n.issue),!n.jiraUrl||typeof n.jiraUrl!="string")throw new Error("jira-conf.json: missing or invalid 'jiraUrl' field");if(!Array.isArray(n.issues))throw new Error("jira-conf.json: missing or invalid 'issues' array");this.validateAutoCloseSeverity(n.autoCloseBelowSeverity,"jira-conf.json: invalid 'autoCloseBelowSeverity'");for(let[i,o]of n.issues.entries())o&&typeof o=="object"&&this.validateAutoCloseSeverity(o.autoCloseBelowSeverity,`jira-conf.json: invalid 'issues[${i}].autoCloseBelowSeverity'`);return n}validateAutoCloseSeverity(e,r){if(e!==void 0&&!oe.includes(e))throw new Error(`${r} value '${String(e)}'. Must be one of: ${oe.join(", ")}`)}async loadAutoVexConfig(e){let r=await(0,_e.readFile)(e,"utf8"),n=JSON.parse(r);if(!n.impactStatement||typeof n.impactStatement!="string")throw new Error("auto-vex-conf.json: missing or invalid 'impactStatement' field (must be a non-empty string)");if(n.maxSeverity!==void 0&&!oe.includes(n.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'maxSeverity' value '${String(n.maxSeverity)}'. Must be one of: ${oe.join(", ")}`);return n}};var Qt=require("path");var ot=require("crypto");function st(t){let{cveName:e,purls:r,status:n,impactStatement:i,actionStatement:o,statusNotes:a,justification:s,timestamp:p=new Date().toISOString()}=t,u={vulnerability:{name:e},timestamp:p,products:r.map(h=>({"@id":h})),status:n};return i&&(u.impact_statement=i),o&&(u.action_statement=o),a&&(u.status_notes=a),s&&(u.justification=s),u}var cr="https://openvex.dev/ns/v0.2.0";function at(t,e="conterra"){let n=`https://openvex.dev/docs/public/vex-${(0,ot.randomUUID)()}`,i=t.timestamp??new Date().toISOString();return{"@context":cr,"@id":n,author:e,timestamp:i,last_updated:i,version:1,statements:[t]}}function lt(t,e){let r=e.timestamp??new Date().toISOString();return{...t,last_updated:r,version:t.version+1,statements:[...t.statements,e]}}var ge=require("fs/promises"),Se=require("path");function ct(t){let e=t.vulnerability.name;return new Set([e,...t.vulnerability.aliases??[]])}var se=class{constructor(e){this.location=e}location;_content=void 0;_exists=!1;get exists(){return this._exists}get content(){return this._content}set content(e){this._content=e,this._exists=e!==void 0}async read(){let e=await me(this.location);this._content=e??void 0,this._exists=this._content!==void 0}async write(){if(this._content===void 0)throw new Error(`Cannot write VexFile: content is undefined (${this.location})`);await(0,ge.mkdir)((0,Se.dirname)((0,Se.resolve)(this.location)),{recursive:!0}),await it(this.location,this._content)}async delete(){await(0,ge.unlink)(this.location),this._exists=!1}upsert(e,r){return this._content===void 0?(this._content=at(e,r),this._exists=!0,{created:!0}):(this._content=lt(this._content,e),{created:!1})}addProductId(e,r){this.assertContentLoaded("addProductId");let n=!1;for(let i of this._content.statements){if(!i.products||i.products.some(a=>a["@id"]===r))continue;let o=i.products.findIndex(a=>a["@id"]===e);o!==-1&&(i.products.splice(o+1,0,{"@id":r}),n=!0)}return n}removeProductId(e,r){this.assertContentLoaded("removeProductId");let n=this._content.statements,i=[],o=!1;for(let a of n){if(r&&!ct(a).has(r)||!a.products)continue;let s=a.products.findIndex(p=>p["@id"]===e);s!==-1&&(a.products.splice(s,1),o=!0,a.products.length===0&&i.push(a))}if(!o)return"unchanged";for(let a of i)n.splice(n.indexOf(a),1);return n.length===0?"emptied":"changed"}hasStatementForProduct(e){return this.assertContentLoaded("hasStatementForProduct"),this._content.statements.some(r=>r.products?.some(n=>n["@id"]===e)??!1)}assertContentLoaded(e){if(this._content===void 0)throw new Error(`VexFile.${e}(): content is not loaded. Call read() first (${this.location})`)}};var j=(t,e=[])=>t.name==="up"||e.includes("vim")&&t.name==="k"||e.includes("emacs")&&t.ctrl&&t.name==="p",z=(t,e=[])=>t.name==="down"||e.includes("vim")&&t.name==="j"||e.includes("emacs")&&t.ctrl&&t.name==="n",Fe=t=>t.name==="space",ae=t=>t.name==="backspace",le=t=>t.name==="tab",ce=t=>"1234567890".includes(t.name),V=t=>t.name==="enter"||t.name==="return";var we=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}},xe=class extends Error{name="CancelPromptError";message="Prompt was canceled"},ue=class extends Error{name="ExitPromptError"},be=class extends Error{name="HookError"},q=class extends Error{name="ValidationError"};var pt=require("node:async_hooks");var ye=require("node:async_hooks");var ut=new ye.AsyncLocalStorage;function ur(t){return{rl:t,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function dt(t,e){let r=ur(t);return ut.run(r,()=>{function n(i){r.handleChange=()=>{r.index=0,i()},r.handleChange()}return e(n)})}function Y(){let t=ut.getStore();if(!t)throw new be("[Inquirer] Hook functions can only be called from within a prompt");return t}function Ue(){return Y().rl}function Ne(t){let e=(...r)=>{let n=Y(),i=!1,o=n.handleChange;n.handleChange=()=>{i=!0};let a=t(...r);return i&&o(),n.handleChange=o,a};return ye.AsyncResource.bind(e)}function re(t){let e=Y(),{index:r}=e,n={get(){return e.hooks[r]},set(o){e.hooks[r]=o},initialized:r in e.hooks},i=t(n);return e.index++,i}function ft(){Y().handleChange()}var Q={queue(t){let e=Y(),{index:r}=e;e.hooksEffect.push(()=>{e.hooksCleanup[r]?.();let n=t(Ue());if(n!=null&&typeof n!="function")throw new q("useEffect return value must be a cleanup function or nothing.");e.hooksCleanup[r]=n})},run(){let t=Y();Ne(()=>{t.hooksEffect.forEach(e=>{e()}),t.hooksEffect.length=0})()},clearAll(){let t=Y();t.hooksCleanup.forEach(e=>{e?.()}),t.hooksEffect.length=0,t.hooksCleanup.length=0}};function dr(t){return typeof t=="function"}function v(t){return re(e=>{let r=pt.AsyncResource.bind(function(o){e.get()!==o&&(e.set(o),ft())});if(e.initialized)return[e.get(),r];let n=dr(t)?t():t;return e.set(n),[n,r]})}function $(t,e){re(r=>{let n=r.get();(!Array.isArray(n)||e.some((o,a)=>!Object.is(o,n[a])))&&Q.queue(t),r.set(e)})}var F=require("node:util");var B=X(require("node:process"),1);function fr(){return B.default.platform.startsWith("win")?!!B.default.env.CI||!!B.default.env.WT_SESSION||!!B.default.env.TERMINUS_SUBLIME||B.default.env.ConEmuTask==="{cmd::Cmder}"||B.default.env.TERM_PROGRAM==="Terminus-Sublime"||B.default.env.TERM_PROGRAM==="vscode"||B.default.env.TERM==="xterm-256color"||B.default.env.TERM==="alacritty"||B.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm":B.default.env.TERM!=="linux"}var mt={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},ht={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},pr={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},mr={...mt,...ht},hr={...mt,...pr},gr=fr(),Sr=gr?mr:hr,O=Sr,gn=Object.entries(ht);var gt={prefix:{idle:(0,F.styleText)("blue","?"),done:(0,F.styleText)("green",O.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(t=>(0,F.styleText)("yellow",t))},style:{answer:t=>(0,F.styleText)("cyan",t),message:t=>(0,F.styleText)("bold",t),error:t=>(0,F.styleText)("red",`> ${t}`),defaultAnswer:t=>(0,F.styleText)("dim",`(${t})`),help:t=>(0,F.styleText)("dim",t),highlight:t=>(0,F.styleText)("cyan",t),key:t=>(0,F.styleText)("cyan",(0,F.styleText)("bold",`<${t}>`))}};function St(t){if(typeof t!="object"||t===null)return!1;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function wt(...t){let e={};for(let r of t)for(let[n,i]of Object.entries(r)){let o=e[n];e[n]=St(o)&&St(i)?wt(o,i):i}return e}function A(...t){let e=[gt,...t.filter(r=>r!=null)];return wt(...e)}function M({status:t="idle",theme:e}){let[r,n]=v(!1),[i,o]=v(0),{prefix:a,spinner:s}=A(e);return $(()=>{if(t==="loading"){let u,h=-1,l=setTimeout(()=>{n(!0),u=setInterval(()=>{h=h+1,o(h%s.frames.length)},s.interval)},300);return()=>{clearTimeout(l),clearInterval(u)}}else n(!1)},[t]),r?s.frames[i]:typeof a=="string"?a:a[t==="loading"?"idle":t]??a.idle}function Z(t,e){return re(r=>{let n=r.get();if(!n||n.dependencies.length!==e.length||n.dependencies.some((i,o)=>i!==e[o])){let i=t();return r.set({value:i,dependencies:e}),i}return n.value})}function ee(t){return v({current:t})[0]}function W(t){let e=ee(t);e.current=t,$(r=>{let n=!1,i=Ne((o,a)=>{n||e.current(a,r)});return r.input.on("keypress",i),()=>{n=!0,r.input.removeListener("keypress",i)}},[])}var Ot=X(bt(),1);var yt=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let r=0;for(t.lastIndex=0;t.test(e);)r+=1;return e.length-r}})(),Et=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Dt=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var br=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,yr=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,vt=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Er=/\t{1,1000}/y,Lt=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Dr=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,vr=new RegExp("\\p{M}+","gu"),Lr={limit:1/0,ellipsis:""},Pt=(t,e={},r={})=>{let n=e.limit??1/0,i=e.ellipsis??"",o=e?.ellipsisWidth??(i?Pt(i,Lr,r).width:0),a=0,s=r.controlWidth??0,p=r.tabWidth??8,u=r.emojiWidth??2,h=2,l=r.regularWidth??1,d=r.wideWidth??h,g=[[Dr,l],[br,a],[yr,s],[Er,p],[Lt,u],[vt,d]],f=0,m=0,S=t.length,b=0,w=!1,E=S,L=Math.max(0,n-o),R=0,P=0,T=0,C=0;e:for(;;){if(P>R||m>=S&&m>f){let c=t.slice(R,P)||t.slice(f,m);b=0;for(let x of c.replaceAll(vr,"")){let y=x.codePointAt(0)||0;if(Et(y)?C=h:Dt(y)?C=d:C=l,T+C>L&&(E=Math.min(E,Math.max(R,f)+b)),T+C>n){w=!0;break e}b+=x.length,T+=C}R=P=0}if(m>=S)break e;for(let c=0,x=g.length;c<x;c++){let[y,D]=g[c];if(y.lastIndex=m,y.test(t)){if(b=y===vt?yt(t.slice(m,y.lastIndex)):y===Lt?1:y.lastIndex-m,C=b*D,T+C>L&&(E=Math.min(E,m+Math.floor((L-T)/D))),T+C>n){w=!0;break e}T+=C,R=f,P=m,m=f=y.lastIndex;continue e}}m+=1}return{width:w?L:T,index:w?E:S,truncated:w,ellipsed:w&&n>=o}},It=Pt;var Pr={limit:1/0,ellipsis:"",ellipsisWidth:0},Ir=(t,e={})=>It(t,Pr,e).width,K=Ir;var Ee="\x1B",Bt="\x9B",Rr=39,Ae="\x07",Ft="[",Tr="]",Ut="m",ke=`${Tr}8;;`,Rt=new RegExp(`(?:\\${Ft}(?<code>\\d+)m|\\${ke}(?<uri>.*)${Ae})`,"y"),Tt=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Ct=t=>`${Ee}${Ft}${t}${Ut}`,_t=t=>`${Ee}${ke}${t}${Ae}`,Oe=(t,e,r)=>{let n=e[Symbol.iterator](),i=!1,o=!1,a=t.at(-1),s=a===void 0?0:K(a),p=n.next(),u=n.next(),h=0;for(;!p.done;){let l=p.value,d=K(l);s+d<=r?t[t.length-1]+=l:(t.push(l),s=0),(l===Ee||l===Bt)&&(i=!0,o=e.startsWith(ke,h+1)),i?o?l===Ae&&(i=!1,o=!1):l===Ut&&(i=!1):(s+=d,s===r&&!u.done&&(t.push(""),s=0)),p=u,u=n.next(),h+=l.length}a=t.at(-1),!s&&a!==void 0&&a.length&&t.length>1&&(t[t.length-2]+=t.pop())},Cr=t=>{let e=t.split(" "),r=e.length;for(;r&&!K(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},_r=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",i,o,a=t.split(" "),s=[""],p=0;for(let l=0;l<a.length;l++){let d=a[l];if(r.trim!==!1){let f=s.at(-1)??"",m=f.trimStart();f.length!==m.length&&(s[s.length-1]=m,p=K(m))}l!==0&&(p>=e&&(r.wordWrap===!1||r.trim===!1)&&(s.push(""),p=0),(p||r.trim===!1)&&(s[s.length-1]+=" ",p++));let g=K(d);if(r.hard&&g>e){let f=e-p,m=1+Math.floor((g-f-1)/e);Math.floor((g-1)/e)<m&&s.push(""),Oe(s,d,e),p=K(s.at(-1)??"");continue}if(p+g>e&&p&&g){if(r.wordWrap===!1&&p<e){Oe(s,d,e),p=K(s.at(-1)??"");continue}s.push(""),p=0}if(p+g>e&&r.wordWrap===!1){Oe(s,d,e),p=K(s.at(-1)??"");continue}s[s.length-1]+=d,p+=g}r.trim!==!1&&(s=s.map(l=>Cr(l)));let u=s.join(`
4
+ `),h=!1;for(let l=0;l<u.length;l++){let d=u[l];if(n+=d,h)h=!1;else if(h=d>="\uD800"&&d<="\uDBFF",h)continue;if(d===Ee||d===Bt){Rt.lastIndex=l+1;let f=Rt.exec(u)?.groups;if(f?.code!==void 0){let m=Number.parseFloat(f.code);i=m===Rr?void 0:m}else f?.uri!==void 0&&(o=f.uri.length===0?void 0:f.uri)}if(u[l+1]===`
5
+ `){o&&(n+=_t(""));let g=i?Tt(i):void 0;i&&g&&(n+=Ct(g))}else d===`
6
+ `&&(i&&Tt(i)&&(n+=Ct(i)),o&&(n+=_t(o)))}return n},Br=/\r?\n/;function Nt(t,e,r){return String(t).normalize().split(Br).map(n=>_r(n,e,r)).join(`
7
+ `)}function de(t,e){return t.split(`
8
+ `).flatMap(r=>Nt(r,e,{trim:!1,hard:!0}).split(`
9
9
  `).map(n=>n.trimEnd())).join(`
10
- `)}function xe(){return(0,Bt.default)({defaultWidth:80,output:Ie().output})}function Lr({active:e,renderedItems:t,pageSize:r,loop:n}){let i=ee({lastPointer:e,lastActive:void 0}),{lastPointer:a,lastActive:s}=i.current,o=Math.floor(r/2),m=t.reduce((l,f)=>l+f.length,0),p=t.slice(0,e).reduce((l,f)=>l+f.length,0),c=p;if(m>r)if(n)c=a,s!=null&&s<e&&e-s<r&&(c=Math.min(o,Math.abs(e-s)===1?Math.min(a+(t[s]?.length??0),Math.max(p,a)):a+e-s));else{let l=t.slice(e).reduce((f,w)=>f+w.length,0);c=l<r-o?r-l:Math.min(p,o)}return i.current.lastPointer=c,i.current.lastActive=e,c}function ue({items:e,active:t,renderItem:r,pageSize:n,loop:i=!0}){let a=xe(),s=D=>(D%e.length+e.length)%e.length,o=e.map((D,b)=>D==null?[]:ce(r({item:D,index:b,isActive:b===t}),a).split(`
11
- `)),m=o.reduce((D,b)=>D+b.length,0),p=D=>o[D]??[],c=Lr({active:t,renderedItems:o,pageSize:n,loop:i}),l=p(t).slice(0,n),f=c+l.length<=n?c:n-l.length,w=Array.from({length:n});w.splice(f,l.length,...l);let d=new Set([t]),h=f+l.length,g=s(t+1);for(;h<n&&!d.has(g)&&(i&&m>n?g!==t:g>t);){let b=p(g).slice(0,n-h);w.splice(h,b.length,...b),d.add(g),h+=b.length,g=s(g+1)}for(h=f-1,g=s(t-1);h>=0&&!d.has(g)&&(i&&m>n?g!==t:g<t);){let D=p(g),b=D.slice(Math.max(0,D.length-h-1));w.splice(h-b.length+1,b.length,...b),d.add(g),h-=b.length,g=s(g-1)}return w.filter(D=>typeof D=="string").join(`
12
- `)}var Ct=Y(require("node:readline"),1),Nt=require("node:async_hooks"),At=Y(It(),1);var te=[];te.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&te.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&te.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var De=e=>!!e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function",Ce=Symbol.for("signal-exit emitter"),Ne=globalThis,_r=Object.defineProperty.bind(Object),Ae=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ne[Ce])return Ne[Ce];_r(Ne,Ce,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(t,r){this.listeners[t].push(r)}removeListener(t,r){let n=this.listeners[t],i=n.indexOf(r);i!==-1&&(i===0&&n.length===1?n.length=0:n.splice(i,1))}emit(t,r,n){if(this.emitted[t])return!1;this.emitted[t]=!0;let i=!1;for(let a of this.listeners[t])i=a(r,n)===!0||i;return t==="exit"&&(i=this.emit("afterExit",r,n)||i),i}},Se=class{},Br=e=>({onExit(t,r){return e.onExit(t,r)},load(){return e.load()},unload(){return e.unload()}}),Oe=class extends Se{onExit(){return()=>{}}load(){}unload(){}},je=class extends Se{#r=$e.platform==="win32"?"SIGINT":"SIGHUP";#t=new Ae;#e;#o;#s;#i={};#n=!1;constructor(t){super(),this.#e=t,this.#i={};for(let r of te)this.#i[r]=()=>{let n=this.#e.listeners(r),{count:i}=this.#t,a=t;if(typeof a.__signal_exit_emitter__=="object"&&typeof a.__signal_exit_emitter__.count=="number"&&(i+=a.__signal_exit_emitter__.count),n.length===i){this.unload();let s=this.#t.emit("exit",null,r),o=r==="SIGHUP"?this.#r:r;s||t.kill(t.pid,o)}};this.#s=t.reallyExit,this.#o=t.emit}onExit(t,r){if(!De(this.#e))return()=>{};this.#n===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#t.on(n,t),()=>{this.#t.removeListener(n,t),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#n){this.#n=!0,this.#t.count+=1;for(let t of te)try{let r=this.#i[t];r&&this.#e.on(t,r)}catch{}this.#e.emit=(t,...r)=>this.#a(t,...r),this.#e.reallyExit=t=>this.#l(t)}}unload(){this.#n&&(this.#n=!1,te.forEach(t=>{let r=this.#i[t];if(!r)throw new Error("Listener not defined for signal: "+t);try{this.#e.removeListener(t,r)}catch{}}),this.#e.emit=this.#o,this.#e.reallyExit=this.#s,this.#t.count-=1)}#l(t){return De(this.#e)?(this.#e.exitCode=t||0,this.#t.emit("exit",this.#e.exitCode,null),this.#s.call(this.#e,this.#e.exitCode)):0}#a(t,...r){let n=this.#o;if(t==="exit"&&De(this.#e)){typeof r[0]=="number"&&(this.#e.exitCode=r[0]);let i=n.call(this.#e,t,...r);return this.#t.emit("exit",this.#e.exitCode,null),i}else return n.call(this.#e,t,...r)}},$e=globalThis.process,{onExit:Ft,load:Un,unload:Pn}=Br(De($e)?new je($e):new Oe);var kt=require("node:util");var Ee="\x1B[?25l",Pt="\x1B[?25h",Me=(e=1)=>e>0?`\x1B[${e}A`:"",We=(e=1)=>e>0?`\x1B[${e}B`:"",Ve=(e,t)=>typeof t=="number"&&!Number.isNaN(t)?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`,Ut="\x1B[2K",Ke=e=>e>0?(Ut+Me(1)).repeat(e-1)+Ut+"\x1B[G":"";var vt=e=>e.split(`
13
- `).length,Tr=e=>e.split(`
14
- `).pop()??"",fe=class{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(t){this.rl=t,this.cursorPos=t.getCursorPos()}write(t){this.rl.output.unmute(),this.rl.output.write(t),this.rl.output.mute()}render(t,r=""){let n=Tr(t),i=(0,kt.stripVTControlCharacters)(n),a=i;this.rl.line.length>0&&(a=a.slice(0,-this.rl.line.length)),this.rl.setPrompt(a),this.cursorPos=this.rl.getCursorPos();let s=xe();t=ce(t,s),r=ce(r,s),i.length%s===0&&(t+=`
15
- `);let o=t+(r?`
16
- `+r:""),p=Math.floor(i.length/s)-this.cursorPos.rows+(r?vt(r):0);p>0&&(o+=Me(p)),o+=Ve(this.cursorPos.cols),this.write(We(this.extraLinesUnderPrompt)+Ke(this.height)+o),this.extraLinesUnderPrompt=p,this.height=vt(o)}checkCursorPos(){let t=this.rl.getCursorPos();t.cols!==this.cursorPos.cols&&(this.write(Ve(t.cols)),this.cursorPos=t)}done({clearContent:t}){this.rl.setPrompt("");let r=We(this.extraLinesUnderPrompt);r+=t?Ke(this.height):`
17
- `,r+=Pt,this.write(r),this.rl.close()}};var ye=class extends Promise{static withResolver(){let t,r;return{promise:new Promise((i,a)=>{t=i,r=a}),resolve:t,reject:r}}};var Ot=Y(require("node:path"),1),Ir=globalThis.setImmediate;function Fr(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(r,n)=>{let i=n.slice(1);return t=i,i},new Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function H(e){let t=Fr();return(n,i={})=>{let{input:a=process.stdin,signal:s}=i,o=new Set,m=new At.default;m.pipe(i.output??process.stdout);let p=Ct.createInterface({terminal:!0,input:a,output:m});m.mute();let c=new fe(p),{promise:l,resolve:f,reject:w}=ye.withResolver(),d=()=>w(new me);if(s){let g=()=>w(new he({cause:s.reason}));if(s.aborted)return g(),Object.assign(l,{cancel:d});s.addEventListener("abort",g),o.add(()=>s.removeEventListener("abort",g))}o.add(Ft((g,D)=>{w(new ae(`User force closed the prompt with ${g} ${D}`))}));let h=()=>w(new ae("User force closed the prompt with SIGINT"));return p.on("SIGINT",h),o.add(()=>p.removeListener("SIGINT",h)),rt(p,g=>{let D=Nt.AsyncResource.bind(()=>Q.clearAll());p.on("close",D),o.add(()=>p.removeListener("close",D));let b=()=>{let E=()=>c.checkCursorPos();p.input.on("keypress",E),o.add(()=>p.input.removeListener("keypress",E));let R=null;g(()=>{let T=!1;try{let _=e(n,u=>{T?f(u):R={value:u}});if(_===void 0){let u=t[1]?.getFileName();throw u&&!u.startsWith("file://")&&(u=Ot.default.resolve(u)),new Error(`Prompt functions must return a string.
18
- at ${u}`)}let[I,F]=typeof _=="string"?[_]:_;c.render(I,F),Q.run()}catch(_){w(_)}if(T=!0,R!==null){let{value:_}=R;R=null,f(_)}})};return"readableFlowing"in a?Ir(b):b(),Object.assign(l.then(E=>(Q.clearAll(),E),E=>{throw Q.clearAll(),E}).finally(()=>{o.forEach(E=>E()),c.done({clearContent:!!i.clearPromptOnDone}),m.end()}).then(()=>l),{cancel:d})})}}var jt=require("node:util");var B=class{separator=(0,jt.styleText)("dim",Array.from({length:15}).join(N.line));type="separator";constructor(t){t&&(this.separator=t)}static isSeparator(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="separator")}};var J=require("node:util");var Ur={icon:{checked:(0,J.styleText)("green",N.circleFilled),unchecked:N.circle,cursor:N.pointer,disabledChecked:(0,J.styleText)("green",N.circleDouble),disabledUnchecked:"-"},style:{disabled:e=>(0,J.styleText)("dim",e),renderSelectedChoices:e=>e.map(t=>t.short).join(", "),description:e=>(0,J.styleText)("cyan",e),keysHelpTip:e=>e.map(([t,r])=>`${(0,J.styleText)("bold",t)} ${(0,J.styleText)("dim",r)}`).join((0,J.styleText)("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be toggled."},keybindings:[]};function Le(e){return!B.isSeparator(e)&&!e.disabled}function He(e){return!B.isSeparator(e)}function $t(e){return!B.isSeparator(e)&&e.checked}function Ge(e){return Le(e)?{...e,checked:!e.checked}:e}function Pr(e){return function(t){return Le(t)?{...t,checked:e}:t}}function vr(e){return e.map(t=>{if(B.isSeparator(t))return t;if(typeof t!="object"||t===null||!("value"in t)){let i=String(t);return{value:t,name:i,short:i,checkedName:i,disabled:!1,checked:!1}}let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,checkedName:t.checkedName??r,disabled:t.disabled??!1,checked:t.checked??!1};return t.description&&(n.description=t.description),n})}var qe=H((e,t)=>{let{pageSize:r=7,loop:n=!0,required:i,validate:a=()=>!0}=e,s={all:"a",invert:"i",...e.shortcuts},o=A(Ur,e.theme),{keybindings:m}=o,[p,c]=L("idle"),l=W({status:p,theme:o}),[f,w]=L(vr(e.choices)),d=Z(()=>{let u=f.findIndex(He),x=f.findLastIndex(He);if(u===-1)throw new q("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:u,last:x}},[f]),[h,g]=L(d.first),[D,b]=L();V(async u=>{if($(u)){let x=f.filter($t),S=await a([...x]);i&&!x.length?b("At least one choice must be selected"):S===!0?(c("done"),t(x.map(y=>y.value))):b(S||"You must select a valid value")}else if(j(u,m)||z(u,m)){if(D&&b(void 0),n||j(u,m)&&h!==d.first||z(u,m)&&h!==d.last){let x=j(u,m)?-1:1,S=h;do S=(S+x+f.length)%f.length;while(!He(f[S]));g(S)}}else if(Te(u)){let x=f[h];x&&!B.isSeparator(x)&&(x.disabled?b(o.i18n.disabledError):(b(void 0),w(f.map((S,y)=>y===h?Ge(S):S))))}else if(u.name===s.all){let x=f.some(S=>Le(S)&&!S.checked);w(f.map(Pr(x)))}else if(u.name===s.invert)w(f.map(Ge));else if(le(u)){let x=Number(u.name)-1,S=-1,y=f.findIndex(O=>B.isSeparator(O)?!1:(S++,S===x)),U=f[y];U&&Le(U)&&(g(y),w(f.map((O,k)=>k===y?Ge(O):O)))}});let E=o.style.message(e.message,p),R,T=ue({items:f,active:h,renderItem({item:u,isActive:x}){if(B.isSeparator(u))return` ${u.separator}`;let S=x?o.icon.cursor:" ";if(u.disabled){let k=typeof u.disabled=="string"?u.disabled:"(disabled)",_e=u.checked?o.icon.disabledChecked:o.icon.disabledUnchecked;return o.style.disabled(`${S}${_e} ${u.name} ${k}`)}x&&(R=u.description);let y=u.checked?o.icon.checked:o.icon.unchecked,U=u.checked?u.checkedName:u.name;return(x?o.style.highlight:k=>k)(`${S}${y} ${U}`)},pageSize:r,loop:n});if(p==="done"){let u=f.filter($t),x=o.style.answer(o.style.renderSelectedChoices(u,f));return[l,E,x].filter(Boolean).join(" ")}let _=[["\u2191\u2193","navigate"],["space","select"]];s.all&&_.push([s.all,"all"]),s.invert&&_.push([s.invert,"invert"]),_.push(["\u23CE","submit"]);let I=o.style.keysHelpTip(_);return`${[[l,E].filter(Boolean).join(" "),T," ",R?o.style.description(R):"",D?o.style.error(D):"",I].filter(Boolean).join(`
19
- `).trimEnd()}${Ee}`});function Mt(e,t){let r=t!==!1;return/^(y|yes)/i.test(e)?r=!0:/^(n|no)/i.test(e)&&(r=!1),r}function Wt(e){return e?"Yes":"No"}var Je=H((e,t)=>{let{transformer:r=Wt}=e,[n,i]=L("idle"),[a,s]=L(""),o=A(e.theme),m=W({status:n,theme:o});V((f,w)=>{if(n==="idle")if($(f)){let d=Mt(a,e.default);s(r(d)),i("done"),t(d)}else if(se(f)){let d=Wt(!Mt(a,e.default));w.clearLine(0),w.write(d),s(d)}else s(w.line)});let p=a,c="";n==="done"?p=o.style.answer(a):c=` ${o.style.defaultAnswer(e.default===!1?"y/N":"Y/n")}`;let l=o.style.message(e.message,n);return`${m} ${l}${c} ${p}`});var kr={validationFailureMode:"keep"},ne=H((e,t)=>{let{prefill:r="tab"}=e,n=A(kr,e.theme),[i,a]=L("idle"),[s,o]=L(String(e.default??"")),[m,p]=L(),[c,l]=L(""),f=W({status:i,theme:n});async function w(b){let{required:E,pattern:R,patternError:T="Invalid input"}=e;return E&&!b?"You must provide a value":R&&!R.test(b)?T:typeof e.validate=="function"?await e.validate(b)||"You must provide a valid value":!0}V(async(b,E)=>{if(i==="idle")if($(b)){let R=c||s;a("loading");let T=await w(R);T===!0?(l(R),a("done"),t(R)):(n.validationFailureMode==="clear"?l(""):E.write(c),p(T),a("idle"))}else oe(b)&&!c?o(""):se(b)&&!c?(o(""),E.clearLine(0),E.write(s),l(s)):(l(E.line),p(void 0))}),M(b=>{r==="editable"&&s&&(b.write(s),l(s))},[]);let d=n.style.message(e.message,i),h=c;typeof e.transformer=="function"?h=e.transformer(c,{isFinal:i==="done"}):i==="done"&&(h=n.style.answer(c));let g;s&&i!=="done"&&!c&&(g=n.style.defaultAnswer(s));let D="";return m&&(D=n.style.error(m)),[[f,d,g,h].filter(b=>b!==void 0).join(" "),D]});var ie=require("node:util");var Cr={icon:{cursor:N.pointer},style:{disabled:e=>(0,ie.styleText)("dim",e),description:e=>(0,ie.styleText)("cyan",e),keysHelpTip:e=>e.map(([t,r])=>`${(0,ie.styleText)("bold",t)} ${(0,ie.styleText)("dim",r)}`).join((0,ie.styleText)("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden",keybindings:[]};function Ye(e){return!B.isSeparator(e)&&!e.disabled}function ze(e){return!B.isSeparator(e)}function Nr(e){return e.map(t=>{if(B.isSeparator(t))return t;if(typeof t!="object"||t===null||!("value"in t)){let i=String(t);return{value:t,name:i,short:i,disabled:!1}}let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};return t.description&&(n.description=t.description),n})}var Re=H((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=A(Cr,e.theme),{keybindings:a}=i,[s,o]=L("idle"),m=W({status:s,theme:i}),p=ee(),c=!a.includes("vim"),l=Z(()=>Nr(e.choices),[e.choices]),f=Z(()=>{let u=l.findIndex(ze),x=l.findLastIndex(ze);if(u===-1)throw new q("[select prompt] No selectable choices. All choices are disabled.");return{first:u,last:x}},[l]),w=Z(()=>"default"in e?l.findIndex(u=>Ye(u)&&u.value===e.default):-1,[e.default,l]),[d,h]=L(w===-1?f.first:w),g=l[d];if(g==null||B.isSeparator(g))throw new Error("Active index does not point to a choice");let[D,b]=L();V((u,x)=>{if(clearTimeout(p.current),D&&b(void 0),$(u))g.disabled?b(i.i18n.disabledError):(o("done"),t(g.value));else if(j(u,a)||z(u,a)){if(x.clearLine(0),r||j(u,a)&&d!==f.first||z(u,a)&&d!==f.last){let S=j(u,a)?-1:1,y=d;do y=(y+S+l.length)%l.length;while(!ze(l[y]));h(y)}}else if(le(u)&&!Number.isNaN(Number(x.line))){let S=Number(x.line)-1,y=-1,U=l.findIndex(k=>B.isSeparator(k)?!1:(y++,y===S)),O=l[U];O!=null&&Ye(O)&&h(U),p.current=setTimeout(()=>{x.clearLine(0)},700)}else if(oe(u))x.clearLine(0);else if(c){let S=x.line.toLowerCase(),y=l.findIndex(U=>B.isSeparator(U)||!Ye(U)?!1:U.name.toLowerCase().startsWith(S));y!==-1&&h(y),p.current=setTimeout(()=>{x.clearLine(0)},700)}}),M(()=>()=>{clearTimeout(p.current)},[]);let E=i.style.message(e.message,s),R=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),T=0,_=ue({items:l,active:d,renderItem({item:u,isActive:x,index:S}){if(B.isSeparator(u))return T++,` ${u.separator}`;let y=x?i.icon.cursor:" ",U=i.indexMode==="number"?`${S+1-T}. `:"";if(u.disabled){let k=typeof u.disabled=="string"?u.disabled:"(disabled)",_e=x?i.icon.cursor:"-";return i.style.disabled(`${_e} ${U}${u.name} ${k}`)}return(x?i.style.highlight:k=>k)(`${y} ${U}${u.name}`)},pageSize:n,loop:r});if(s==="done")return[m,E,i.style.answer(g.short)].filter(Boolean).join(" ");let{description:I}=g;return`${[[m,E].filter(Boolean).join(" "),_," ",I?i.style.description(I):"",D?i.style.error(D):"",R].filter(Boolean).join(`
20
- `).trimEnd()}${Ee}`});(async()=>{let t=!process.argv.slice(2).includes("--no-project-filter");try{let r=await et({workingDir:process.cwd()});console.info("## Add New VEX Statement ##");let n=await ne({message:"CVE name (e.g. CVE-2023-52070)",required:!0}),i=r.projects.filter(d=>!t||d.enabled&&!d.silent).map(d=>({name:`${d.name}@${d.version}`,value:d.purl}));i.sort((d,h)=>d.name.localeCompare(h.name));let a=await qe({message:"Projects to add",choices:i,required:!0,pageSize:15}),s=(0,Vt.resolve)(r.vexDir,`${n}.json`),o=await de(s),m=["under_investigation","affected","fixed","not_affected"],p=await Re({message:"Status?",choices:m.map(d=>({name:d,value:d})),default:m[m.length-1]}),c={};switch(p){case"affected":{let d=await ne({message:"Action statement?",required:!0});c.action_statement=d;break}case"not_affected":{let h=await Re({message:"Justification?",choices:["none","component_not_present","vulnerable_code_not_present","vulnerable_code_not_in_execute_path","vulnerable_code_cannot_be_controlled_by_adversary","inline_mitigations_already_exist"].map(D=>({name:D,value:D}))});h!=="none"&&(c.justification=h);let g=await ne({message:"Impact statement?",required:h==="none"});g&&(c.impact_statement=g);break}case"fixed":{let d=await ne({message:"Status note?"});d&&(c.status_notes=d);break}}let l=new Date().toISOString(),f={vulnerability:{name:n},timestamp:l,products:Array.from(a).map(d=>({"@id":d})),status:p,...c};await Je({message:`Following statement will be added to ${s}:
21
- ${JSON.stringify(f,null,2)}
10
+ `)}function De(){return(0,Ot.default)({defaultWidth:80,output:Ue().output})}function Fr({active:t,renderedItems:e,pageSize:r,loop:n}){let i=ee({lastPointer:t,lastActive:void 0}),{lastPointer:o,lastActive:a}=i.current,s=Math.floor(r/2),p=e.reduce((l,d)=>l+d.length,0),u=e.slice(0,t).reduce((l,d)=>l+d.length,0),h=u;if(p>r)if(n)h=o,a!=null&&a<t&&t-a<r&&(h=Math.min(s,Math.abs(t-a)===1?Math.min(o+(e[a]?.length??0),Math.max(u,o)):o+t-a));else{let l=e.slice(t).reduce((d,g)=>d+g.length,0);h=l<r-s?r-l:Math.min(u,s)}return i.current.lastPointer=h,i.current.lastActive=t,h}function fe({items:t,active:e,renderItem:r,pageSize:n,loop:i=!0}){let o=De(),a=b=>(b%t.length+t.length)%t.length,s=t.map((b,w)=>b==null?[]:de(r({item:b,index:w,isActive:w===e}),o).split(`
11
+ `)),p=s.reduce((b,w)=>b+w.length,0),u=b=>s[b]??[],h=Fr({active:e,renderedItems:s,pageSize:n,loop:i}),l=u(e).slice(0,n),d=h+l.length<=n?h:n-l.length,g=Array.from({length:n});g.splice(d,l.length,...l);let f=new Set([e]),m=d+l.length,S=a(e+1);for(;m<n&&!f.has(S)&&(i&&p>n?S!==e:S>e);){let w=u(S).slice(0,n-m);g.splice(m,w.length,...w),f.add(S),m+=w.length,S=a(S+1)}for(m=d-1,S=a(e-1);m>=0&&!f.has(S)&&(i&&p>n?S!==e:S<e);){let b=u(S),w=b.slice(Math.max(0,b.length-m-1));g.splice(m-w.length+1,w.length,...w),f.add(S),m-=w.length,S=a(S-1)}return g.filter(b=>typeof b=="string").join(`
12
+ `)}var Kt=X(require("node:readline"),1),Ht=require("node:async_hooks"),Gt=X(kt(),1);var te=[];te.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&te.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&te.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var ve=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",Ve=Symbol.for("signal-exit emitter"),$e=globalThis,Nr=Object.defineProperty.bind(Object),Me=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if($e[Ve])return $e[Ve];Nr($e,Ve,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,r){this.listeners[e].push(r)}removeListener(e,r){let n=this.listeners[e],i=n.indexOf(r);i!==-1&&(i===0&&n.length===1?n.length=0:n.splice(i,1))}emit(e,r,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let o of this.listeners[e])i=o(r,n)===!0||i;return e==="exit"&&(i=this.emit("afterExit",r,n)||i),i}},Le=class{},Or=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),We=class extends Le{onExit(){return()=>{}}load(){}unload(){}},Ke=class extends Le{#r=He.platform==="win32"?"SIGINT":"SIGHUP";#t=new Me;#e;#o;#s;#i={};#n=!1;constructor(e){super(),this.#e=e,this.#i={};for(let r of te)this.#i[r]=()=>{let n=this.#e.listeners(r),{count:i}=this.#t,o=e;if(typeof o.__signal_exit_emitter__=="object"&&typeof o.__signal_exit_emitter__.count=="number"&&(i+=o.__signal_exit_emitter__.count),n.length===i){this.unload();let a=this.#t.emit("exit",null,r),s=r==="SIGHUP"?this.#r:r;a||e.kill(e.pid,s)}};this.#s=e.reallyExit,this.#o=e.emit}onExit(e,r){if(!ve(this.#e))return()=>{};this.#n===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#n){this.#n=!0,this.#t.count+=1;for(let e of te)try{let r=this.#i[e];r&&this.#e.on(e,r)}catch{}this.#e.emit=(e,...r)=>this.#l(e,...r),this.#e.reallyExit=e=>this.#a(e)}}unload(){this.#n&&(this.#n=!1,te.forEach(e=>{let r=this.#i[e];if(!r)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,r)}catch{}}),this.#e.emit=this.#o,this.#e.reallyExit=this.#s,this.#t.count-=1)}#a(e){return ve(this.#e)?(this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#s.call(this.#e,this.#e.exitCode)):0}#l(e,...r){let n=this.#o;if(e==="exit"&&ve(this.#e)){typeof r[0]=="number"&&(this.#e.exitCode=r[0]);let i=n.call(this.#e,e,...r);return this.#t.emit("exit",this.#e.exitCode,null),i}else return n.call(this.#e,e,...r)}},He=globalThis.process,{onExit:jt,load:Yn,unload:Qn}=Or(ve(He)?new Ke(He):new We);var Wt=require("node:util");var Pe="\x1B[?25l",$t="\x1B[?25h",Ge=(t=1)=>t>0?`\x1B[${t}A`:"",qe=(t=1)=>t>0?`\x1B[${t}B`:"",Je=(t,e)=>typeof e=="number"&&!Number.isNaN(e)?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`,Vt="\x1B[2K",Xe=t=>t>0?(Vt+Ge(1)).repeat(t-1)+Vt+"\x1B[G":"";var Mt=t=>t.split(`
13
+ `).length,Ar=t=>t.split(`
14
+ `).pop()??"",pe=class{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,r=""){let n=Ar(e),i=(0,Wt.stripVTControlCharacters)(n),o=i;this.rl.line.length>0&&(o=o.slice(0,-this.rl.line.length)),this.rl.setPrompt(o),this.cursorPos=this.rl.getCursorPos();let a=De();e=de(e,a),r=de(r,a),i.length%a===0&&(e+=`
15
+ `);let s=e+(r?`
16
+ `+r:""),u=Math.floor(i.length/a)-this.cursorPos.rows+(r?Mt(r):0);u>0&&(s+=Ge(u)),s+=Je(this.cursorPos.cols),this.write(qe(this.extraLinesUnderPrompt)+Xe(this.height)+s),this.extraLinesUnderPrompt=u,this.height=Mt(s)}checkCursorPos(){let e=this.rl.getCursorPos();e.cols!==this.cursorPos.cols&&(this.write(Je(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt("");let r=qe(this.extraLinesUnderPrompt);r+=e?Xe(this.height):`
17
+ `,r+=$t,this.write(r),this.rl.close()}};var Ie=class extends Promise{static withResolver(){let e,r;return{promise:new Promise((i,o)=>{e=i,r=o}),resolve:e,reject:r}}};var qt=X(require("node:path"),1),kr=globalThis.setImmediate;function jr(){let t=Error.prepareStackTrace,e=[];try{Error.prepareStackTrace=(r,n)=>{let i=n.slice(1);return e=i,i},new Error().stack}catch{return e}return Error.prepareStackTrace=t,e}function H(t){let e=jr();return(n,i={})=>{let{input:o=process.stdin,signal:a}=i,s=new Set,p=new Gt.default;p.pipe(i.output??process.stdout);let u=Kt.createInterface({terminal:!0,input:o,output:p});p.mute();let h=new pe(u),{promise:l,resolve:d,reject:g}=Ie.withResolver(),f=()=>g(new xe);if(a){let S=()=>g(new we({cause:a.reason}));if(a.aborted)return S(),Object.assign(l,{cancel:f});a.addEventListener("abort",S),s.add(()=>a.removeEventListener("abort",S))}s.add(jt((S,b)=>{g(new ue(`User force closed the prompt with ${S} ${b}`))}));let m=()=>g(new ue("User force closed the prompt with SIGINT"));return u.on("SIGINT",m),s.add(()=>u.removeListener("SIGINT",m)),dt(u,S=>{let b=Ht.AsyncResource.bind(()=>Q.clearAll());u.on("close",b),s.add(()=>u.removeListener("close",b));let w=()=>{let E=()=>h.checkCursorPos();u.input.on("keypress",E),s.add(()=>u.input.removeListener("keypress",E));let L=null;S(()=>{let R=!1;try{let P=t(n,c=>{R?d(c):L={value:c}});if(P===void 0){let c=e[1]?.getFileName();throw c&&!c.startsWith("file://")&&(c=qt.default.resolve(c)),new Error(`Prompt functions must return a string.
18
+ at ${c}`)}let[T,C]=typeof P=="string"?[P]:P;h.render(T,C),Q.run()}catch(P){g(P)}if(R=!0,L!==null){let{value:P}=L;L=null,d(P)}})};return"readableFlowing"in o?kr(w):w(),Object.assign(l.then(E=>(Q.clearAll(),E),E=>{throw Q.clearAll(),E}).finally(()=>{s.forEach(E=>E()),h.done({clearContent:!!i.clearPromptOnDone}),p.end()}).then(()=>l),{cancel:f})})}}var Jt=require("node:util");var I=class{separator=(0,Jt.styleText)("dim",Array.from({length:15}).join(O.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="separator")}};var J=require("node:util");var Vr={icon:{checked:(0,J.styleText)("green",O.circleFilled),unchecked:O.circle,cursor:O.pointer,disabledChecked:(0,J.styleText)("green",O.circleDouble),disabledUnchecked:"-"},style:{disabled:t=>(0,J.styleText)("dim",t),renderSelectedChoices:t=>t.map(e=>e.short).join(", "),description:t=>(0,J.styleText)("cyan",t),keysHelpTip:t=>t.map(([e,r])=>`${(0,J.styleText)("bold",e)} ${(0,J.styleText)("dim",r)}`).join((0,J.styleText)("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be toggled."},keybindings:[]};function Re(t){return!I.isSeparator(t)&&!t.disabled}function ze(t){return!I.isSeparator(t)}function Xt(t){return!I.isSeparator(t)&&t.checked}function Ye(t){return Re(t)?{...t,checked:!t.checked}:t}function $r(t){return function(e){return Re(e)?{...e,checked:t}:e}}function Mr(t){return t.map(e=>{if(I.isSeparator(e))return e;if(typeof e!="object"||e===null||!("value"in e)){let i=String(e);return{value:e,name:i,short:i,checkedName:i,disabled:!1,checked:!1}}let r=e.name??String(e.value),n={value:e.value,name:r,short:e.short??r,checkedName:e.checkedName??r,disabled:e.disabled??!1,checked:e.checked??!1};return e.description&&(n.description=e.description),n})}var Qe=H((t,e)=>{let{pageSize:r=7,loop:n=!0,required:i,validate:o=()=>!0}=t,a={all:"a",invert:"i",...t.shortcuts},s=A(Vr,t.theme),{keybindings:p}=s,[u,h]=v("idle"),l=M({status:u,theme:s}),[d,g]=v(Mr(t.choices)),f=Z(()=>{let c=d.findIndex(ze),x=d.findLastIndex(ze);if(c===-1)throw new q("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:c,last:x}},[d]),[m,S]=v(f.first),[b,w]=v();W(async c=>{if(V(c)){let x=d.filter(Xt),y=await o([...x]);i&&!x.length?w("At least one choice must be selected"):y===!0?(h("done"),e(x.map(D=>D.value))):w(y||"You must select a valid value")}else if(j(c,p)||z(c,p)){if(b&&w(void 0),n||j(c,p)&&m!==f.first||z(c,p)&&m!==f.last){let x=j(c,p)?-1:1,y=m;do y=(y+x+d.length)%d.length;while(!ze(d[y]));S(y)}}else if(Fe(c)){let x=d[m];x&&!I.isSeparator(x)&&(x.disabled?w(s.i18n.disabledError):(w(void 0),g(d.map((y,D)=>D===m?Ye(y):y))))}else if(c.name===a.all){let x=d.some(y=>Re(y)&&!y.checked);g(d.map($r(x)))}else if(c.name===a.invert)g(d.map(Ye));else if(ce(c)){let x=Number(c.name)-1,y=-1,D=d.findIndex(k=>I.isSeparator(k)?!1:(y++,y===x)),_=d[D];_&&Re(_)&&(S(D),g(d.map((k,U)=>U===D?Ye(k):k)))}});let E=s.style.message(t.message,u),L,R=fe({items:d,active:m,renderItem({item:c,isActive:x}){if(I.isSeparator(c))return` ${c.separator}`;let y=x?s.icon.cursor:" ";if(c.disabled){let U=typeof c.disabled=="string"?c.disabled:"(disabled)",Ce=c.checked?s.icon.disabledChecked:s.icon.disabledUnchecked;return s.style.disabled(`${y}${Ce} ${c.name} ${U}`)}x&&(L=c.description);let D=c.checked?s.icon.checked:s.icon.unchecked,_=c.checked?c.checkedName:c.name;return(x?s.style.highlight:U=>U)(`${y}${D} ${_}`)},pageSize:r,loop:n});if(u==="done"){let c=d.filter(Xt),x=s.style.answer(s.style.renderSelectedChoices(c,d));return[l,E,x].filter(Boolean).join(" ")}let P=[["\u2191\u2193","navigate"],["space","select"]];a.all&&P.push([a.all,"all"]),a.invert&&P.push([a.invert,"invert"]),P.push(["\u23CE","submit"]);let T=s.style.keysHelpTip(P);return`${[[l,E].filter(Boolean).join(" "),R," ",L?s.style.description(L):"",b?s.style.error(b):"",T].filter(Boolean).join(`
19
+ `).trimEnd()}${Pe}`});function zt(t,e){let r=e!==!1;return/^(y|yes)/i.test(t)?r=!0:/^(n|no)/i.test(t)&&(r=!1),r}function Yt(t){return t?"Yes":"No"}var Ze=H((t,e)=>{let{transformer:r=Yt}=t,[n,i]=v("idle"),[o,a]=v(""),s=A(t.theme),p=M({status:n,theme:s});W((d,g)=>{if(n==="idle")if(V(d)){let f=zt(o,t.default);a(r(f)),i("done"),e(f)}else if(le(d)){let f=Yt(!zt(o,t.default));g.clearLine(0),g.write(f),a(f)}else a(g.line)});let u=o,h="";n==="done"?u=s.style.answer(o):h=` ${s.style.defaultAnswer(t.default===!1?"y/N":"Y/n")}`;let l=s.style.message(t.message,n);return`${p} ${l}${h} ${u}`});var Wr={validationFailureMode:"keep"},ne=H((t,e)=>{let{prefill:r="tab"}=t,n=A(Wr,t.theme),[i,o]=v("idle"),[a,s]=v(String(t.default??"")),[p,u]=v(),[h,l]=v(""),d=M({status:i,theme:n});async function g(w){let{required:E,pattern:L,patternError:R="Invalid input"}=t;return E&&!w?"You must provide a value":L&&!L.test(w)?R:typeof t.validate=="function"?await t.validate(w)||"You must provide a valid value":!0}W(async(w,E)=>{if(i==="idle")if(V(w)){let L=h||a;o("loading");let R=await g(L);R===!0?(l(L),o("done"),e(L)):(n.validationFailureMode==="clear"?l(""):E.write(h),u(R),o("idle"))}else ae(w)&&!h?s(""):le(w)&&!h?(s(""),E.clearLine(0),E.write(a),l(a)):(l(E.line),u(void 0))}),$(w=>{r==="editable"&&a&&(w.write(a),l(a))},[]);let f=n.style.message(t.message,i),m=h;typeof t.transformer=="function"?m=t.transformer(h,{isFinal:i==="done"}):i==="done"&&(m=n.style.answer(h));let S;a&&i!=="done"&&!h&&(S=n.style.defaultAnswer(a));let b="";return p&&(b=n.style.error(p)),[[d,f,S,m].filter(w=>w!==void 0).join(" "),b]});var ie=require("node:util");var Kr={icon:{cursor:O.pointer},style:{disabled:t=>(0,ie.styleText)("dim",t),description:t=>(0,ie.styleText)("cyan",t),keysHelpTip:t=>t.map(([e,r])=>`${(0,ie.styleText)("bold",e)} ${(0,ie.styleText)("dim",r)}`).join((0,ie.styleText)("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden",keybindings:[]};function et(t){return!I.isSeparator(t)&&!t.disabled}function tt(t){return!I.isSeparator(t)}function Hr(t){return t.map(e=>{if(I.isSeparator(e))return e;if(typeof e!="object"||e===null||!("value"in e)){let i=String(e);return{value:e,name:i,short:i,disabled:!1}}let r=e.name??String(e.value),n={value:e.value,name:r,short:e.short??r,disabled:e.disabled??!1};return e.description&&(n.description=e.description),n})}var Te=H((t,e)=>{let{loop:r=!0,pageSize:n=7}=t,i=A(Kr,t.theme),{keybindings:o}=i,[a,s]=v("idle"),p=M({status:a,theme:i}),u=ee(),h=!o.includes("vim"),l=Z(()=>Hr(t.choices),[t.choices]),d=Z(()=>{let c=l.findIndex(tt),x=l.findLastIndex(tt);if(c===-1)throw new q("[select prompt] No selectable choices. All choices are disabled.");return{first:c,last:x}},[l]),g=Z(()=>"default"in t?l.findIndex(c=>et(c)&&c.value===t.default):-1,[t.default,l]),[f,m]=v(g===-1?d.first:g),S=l[f];if(S==null||I.isSeparator(S))throw new Error("Active index does not point to a choice");let[b,w]=v();W((c,x)=>{if(clearTimeout(u.current),b&&w(void 0),V(c))S.disabled?w(i.i18n.disabledError):(s("done"),e(S.value));else if(j(c,o)||z(c,o)){if(x.clearLine(0),r||j(c,o)&&f!==d.first||z(c,o)&&f!==d.last){let y=j(c,o)?-1:1,D=f;do D=(D+y+l.length)%l.length;while(!tt(l[D]));m(D)}}else if(ce(c)&&!Number.isNaN(Number(x.line))){let y=Number(x.line)-1,D=-1,_=l.findIndex(U=>I.isSeparator(U)?!1:(D++,D===y)),k=l[_];k!=null&&et(k)&&m(_),u.current=setTimeout(()=>{x.clearLine(0)},700)}else if(ae(c))x.clearLine(0);else if(h){let y=x.line.toLowerCase(),D=l.findIndex(_=>I.isSeparator(_)||!et(_)?!1:_.name.toLowerCase().startsWith(y));D!==-1&&m(D),u.current=setTimeout(()=>{x.clearLine(0)},700)}}),$(()=>()=>{clearTimeout(u.current)},[]);let E=i.style.message(t.message,a),L=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),R=0,P=fe({items:l,active:f,renderItem({item:c,isActive:x,index:y}){if(I.isSeparator(c))return R++,` ${c.separator}`;let D=x?i.icon.cursor:" ",_=i.indexMode==="number"?`${y+1-R}. `:"";if(c.disabled){let U=typeof c.disabled=="string"?c.disabled:"(disabled)",Ce=x?i.icon.cursor:"-";return i.style.disabled(`${Ce} ${_}${c.name} ${U}`)}return(x?i.style.highlight:U=>U)(`${D} ${_}${c.name}`)},pageSize:n,loop:r});if(a==="done")return[p,E,i.style.answer(S.short)].filter(Boolean).join(" ");let{description:T}=S;return`${[[p,E].filter(Boolean).join(" "),P," ",T?i.style.description(T):"",b?i.style.error(b):"",L].filter(Boolean).join(`
20
+ `).trimEnd()}${Pe}`});(async()=>{let e=!process.argv.slice(2).includes("--no-project-filter");try{let r=await new he(process.cwd()).loadProjectConfig();console.info("## Add New VEX Statement ##");let n=await ne({message:"CVE name (e.g. CVE-2023-52070)",required:!0}),i=r.projects.filter(f=>!e||f.enabled&&!f.silent).map(f=>({name:`${f.name}@${f.version}`,value:f.purl}));i.sort((f,m)=>f.name.localeCompare(m.name));let o=await Qe({message:"Projects to add",choices:i,required:!0,pageSize:15}),a=(0,Qt.resolve)(r.vexDir,`${n}.json`),s=["under_investigation","affected","fixed","not_affected"],p=await Te({message:"Status?",choices:s.map(f=>({name:f,value:f})),default:s[s.length-1]}),u={};switch(p){case"affected":{let f=await ne({message:"Action statement?",required:!0});u.actionStatement=f;break}case"not_affected":{let m=await Te({message:"Justification?",choices:["none","component_not_present","vulnerable_code_not_present","vulnerable_code_not_in_execute_path","vulnerable_code_cannot_be_controlled_by_adversary","inline_mitigations_already_exist"].map(b=>({name:b,value:b}))});m!=="none"&&(u.justification=m);let S=await ne({message:"Impact statement?",required:m==="none"});S&&(u.impactStatement=S);break}case"fixed":{let f=await ne({message:"Status note?"});f&&(u.statusNotes=f);break}}let h=new Date().toISOString(),l=st({cveName:n,purls:Array.from(o),status:p,timestamp:h,...u});await Ze({message:`Following statement will be added to ${a}:
21
+ ${JSON.stringify(l,null,2)}
22
22
 
23
- Do you want to proceed?`})||(console.log("Aborted."),process.exit(0)),o?(o.last_updated=l,o.version+=1,o.statements.push(f)):o={"@context":"https://openvex.dev/ns/v0.2.0","@id":`https://openvex.dev/docs/public/vex-${(0,Kt.randomUUID)()}`,author:"conterra",timestamp:l,last_updated:l,version:1,statements:[f]},await Ze(s,o)}catch(r){console.log(`Aborted: ${r}`),process.exit(0)}})();
23
+ Do you want to proceed?`})||(console.log("Aborted."),process.exit(0));let g=new se(a);await g.read(),g.upsert(l),await g.write()}catch(r){console.error(`Error: ${r}`),process.exitCode=1}})();
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var Y=Object.create;var $=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var et=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Q(t))!tt.call(n,i)&&i!==e&&$(n,i,{get:()=>t[i],enumerable:!(r=q(t,i))||r.enumerable});return n};var T=(n,t,e)=>(e=n!=null?Y(Z(n)):{},et(t||!n||!n.__esModule?$(e,"default",{value:n,enumerable:!0}):e,n));var D=require("path");var m=T(require("path")),N=require("fs/promises");var u=require("fs/promises");async function x(n){try{return await rt(n)?JSON.parse(await(0,u.readFile)(n,{encoding:"utf-8"})):void 0}catch(t){throw new Error(`Error reading JSON file ${n}: ${t}`,{cause:t})}}async function L(n,t){let e=JSON.stringify(t,null,4)+`
3
+ `,r=await nt(n,e);await(0,u.writeFile)(n,r,{encoding:"utf-8"})}async function rt(n){try{return await(0,u.access)(n,u.constants.F_OK),!0}catch{return!1}}async function nt(n,t){let e=await ot();if(!e)return t;let r=await e.resolveConfig(n);return r?await e.format(t,{...r,filepath:n}):t}var it;function ot(){return it??=import("prettier").catch(()=>{})}var R={UNKNOWN:0,LOW:1,MEDIUM:2,HIGH:3,CRITICAL:4},v=["UNKNOWN","LOW","MEDIUM","HIGH","CRITICAL"];function U(n,t){return R[n]<R[t]}var O=class n{constructor(t){this.workingDir=t}workingDir;static DEFAULT_MAVEN_REPO="https://repository.conterra.de/repository/maven-mirror-ct";static DEFAULT_VEX_SUBDIR="input/vex";static DEFAULT_OUT_SUBDIR="output";static DEFAULT_CACHE_SUBDIR="cache";static DEFAULT_SCANNERS=["grype","trivy","ossindex"];normalize(t,e){let r=t.findNoLongerDetectedVulnerabilitiesOnlyForSnapshots??!1;return{projectConfigFileLocation:e,onNewVulnerabilities:t.onNewVulnerabilities??(t.failOnNewVulnerabilities?"fail":"warn"),onNoLongerDetectedVulnerabilities:t.onNoLongerDetectedVulnerabilities??"ignore",reportNoLongerDetectedVulnerabilities:t.reportNoLongerDetectedVulnerabilities??!0,consoleReport:t.consoleReport??"BY_PROJECT_DETAILED",createSubDirsForProject:t.createSubDirsForProject??!0,mavenRepo:t.mavenRepo??n.DEFAULT_MAVEN_REPO,vexUrls:t.vexUrls??[],vexDir:this.resolvePath(t.vexDir)??(0,m.resolve)(this.workingDir,n.DEFAULT_VEX_SUBDIR),outDir:this.resolvePath(t.outDir)??(0,m.resolve)(this.workingDir,n.DEFAULT_OUT_SUBDIR),cacheDir:this.resolvePath(t.cacheDir)??(0,m.resolve)(this.workingDir,n.DEFAULT_CACHE_SUBDIR),scanners:this.normalizeScanners(t.scanners,e),projects:this.normalizeProjects(t.projects??[],r)}}normalizeScanners(t,e){return(t??n.DEFAULT_SCANNERS).map(i=>{if(typeof i!="string")throw new Error(`Invalid scanner name '${String(i)}' in configuration file '${e}'`);let o=i.split("@");if(o.length>2)throw new Error(`Invalid scanner name '${i}' in configuration file '${e}'`);return{name:o[0],version:o[1]??""}})}normalizeProjects(t,e){return t.map(r=>{let i=r;if(!i.name)throw new Error("Project name is missing on entry: "+JSON.stringify(i));if(!i.version)throw new Error("Project version is missing on entry: "+JSON.stringify(i));if(!i.purl)throw new Error("Project purl is missing on entry: "+JSON.stringify(i));let o={...i,purlAliases:i.purlAliases??[],enabled:i.enabled??!0,silent:i.silent??!1,minimumSeverity:i.minimumSeverity??"UNKNOWN"};return o.sbomFile?{...o,sbomFile:this.resolvePath(o.sbomFile)??o.sbomFile}:{...o,detectNoLongerUsedVulnerabilities:e?o.purl.endsWith("-SNAPSHOT"):!0}})}resolvePath(t){if(t)return m.default.isAbsolute(t)?t:(0,m.resolve)(this.workingDir,t)}},f=class{constructor(t){this.workingDir=t;this.normalizer=new O(t)}workingDir;normalizer;projectConfigCache;async loadProjectConfig(){return this.projectConfigCache??=this.doLoadProjectConfig(),this.projectConfigCache}async doLoadProjectConfig(){let t=(0,m.resolve)(this.workingDir,"vuln-scan-conf.json"),e=await x(t);if(!e)throw new Error(`Missing project configuration file '${t}'`);return this.normalizer.normalize(e,t)}async loadJiraConfig(t){let e=await(0,N.readFile)(t,"utf8"),r=JSON.parse(e);if(!r.issues&&r.issue&&(r.issues=r.issue),!r.jiraUrl||typeof r.jiraUrl!="string")throw new Error("jira-conf.json: missing or invalid 'jiraUrl' field");if(!Array.isArray(r.issues))throw new Error("jira-conf.json: missing or invalid 'issues' array");this.validateAutoCloseSeverity(r.autoCloseBelowSeverity,"jira-conf.json: invalid 'autoCloseBelowSeverity'");for(let[i,o]of r.issues.entries())o&&typeof o=="object"&&this.validateAutoCloseSeverity(o.autoCloseBelowSeverity,`jira-conf.json: invalid 'issues[${i}].autoCloseBelowSeverity'`);return r}validateAutoCloseSeverity(t,e){if(t!==void 0&&!v.includes(t))throw new Error(`${e} value '${String(t)}'. Must be one of: ${v.join(", ")}`)}async loadAutoVexConfig(t){let e=await(0,N.readFile)(t,"utf8"),r=JSON.parse(e);if(!r.impactStatement||typeof r.impactStatement!="string")throw new Error("auto-vex-conf.json: missing or invalid 'impactStatement' field (must be a non-empty string)");if(r.maxSeverity!==void 0&&!v.includes(r.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'maxSeverity' value '${String(r.maxSeverity)}'. Must be one of: ${v.join(", ")}`);return r}};var k=require("fs/promises"),j=require("path");var _=require("crypto");function M(n){let{cveName:t,purls:e,status:r,impactStatement:i,actionStatement:o,statusNotes:s,justification:l,timestamp:c=new Date().toISOString()}=n,d={vulnerability:{name:t},timestamp:c,products:e.map(y=>({"@id":y})),status:r};return i&&(d.impact_statement=i),o&&(d.action_statement=o),s&&(d.status_notes=s),l&&(d.justification=l),d}var st="https://openvex.dev/ns/v0.2.0";function H(n,t="conterra"){let r=`https://openvex.dev/docs/public/vex-${(0,_.randomUUID)()}`,i=n.timestamp??new Date().toISOString();return{"@context":st,"@id":r,author:t,timestamp:i,last_updated:i,version:1,statements:[n]}}function X(n,t){let e=t.timestamp??new Date().toISOString();return{...n,last_updated:e,version:n.version+1,statements:[...n.statements,t]}}var P=require("fs/promises"),V=require("path");function B(n){let t=n.vulnerability.name;return new Set([t,...n.vulnerability.aliases??[]])}var S=class{constructor(t){this.location=t}location;_content=void 0;_exists=!1;get exists(){return this._exists}get content(){return this._content}set content(t){this._content=t,this._exists=t!==void 0}async read(){let t=await x(this.location);this._content=t??void 0,this._exists=this._content!==void 0}async write(){if(this._content===void 0)throw new Error(`Cannot write VexFile: content is undefined (${this.location})`);await(0,P.mkdir)((0,V.dirname)((0,V.resolve)(this.location)),{recursive:!0}),await L(this.location,this._content)}async delete(){await(0,P.unlink)(this.location),this._exists=!1}upsert(t,e){return this._content===void 0?(this._content=H(t,e),this._exists=!0,{created:!0}):(this._content=X(this._content,t),{created:!1})}addProductId(t,e){this.assertContentLoaded("addProductId");let r=!1;for(let i of this._content.statements){if(!i.products||i.products.some(s=>s["@id"]===e))continue;let o=i.products.findIndex(s=>s["@id"]===t);o!==-1&&(i.products.splice(o+1,0,{"@id":e}),r=!0)}return r}removeProductId(t,e){this.assertContentLoaded("removeProductId");let r=this._content.statements,i=[],o=!1;for(let s of r){if(e&&!B(s).has(e)||!s.products)continue;let l=s.products.findIndex(c=>c["@id"]===t);l!==-1&&(s.products.splice(l,1),o=!0,s.products.length===0&&i.push(s))}if(!o)return"unchanged";for(let s of i)r.splice(r.indexOf(s),1);return r.length===0?"emptied":"changed"}hasStatementForProduct(t){return this.assertContentLoaded("hasStatementForProduct"),this._content.statements.some(e=>e.products?.some(r=>r["@id"]===t)??!1)}assertContentLoaded(t){if(this._content===void 0)throw new Error(`VexFile.${t}(): content is not loaded. Call read() first (${this.location})`)}};var at="HIGH";async function W(n){let{scanSummaryPath:t,autoVexConfigPath:e,vexDir:r,dryRun:i=!1}=n,o=new f(process.cwd()),[s,l,c]=await Promise.all([ct(t),o.loadProjectConfig(),o.loadAutoVexConfig(e)]),d=new Map(l.projects.map(a=>[`${a.name}@${a.version}`,a.purl])),y=c.maxSeverity??at,J=c.subDir??"auto",z=(0,j.resolve)(r,J),p={created:[],updated:[],errors:[]};for(let[a,b]of Object.entries(s.vulnerabilities))try{if(!U(b.severity,y)){console.log(`[skip] ${a}: severity ${b.severity} is not below ${y}`);continue}let g=(0,j.resolve)(z,`${a}.json`),h=s.vulnerabilityToProject[a]??[];if(h.length===0){console.warn(`[warn] ${a}: no affected projects found in summary, skipping`);continue}let w=[];for(let A of h){let F=d.get(A);F===void 0?console.warn(`[warn] ${a}: project "${A}" not found in vuln-scan-conf.json, skipping product`):w.push(F)}if(w.length===0){console.warn(`[warn] ${a}: no resolvable project PURLs, skipping`);continue}if(i){console.log(`[dry-run] Would write auto VEX for ${a} (severity: ${b.severity}) \u2192 ${g}`),console.log(` Affected projects: ${w.join(", ")}`),p.created.push(a);continue}let G=new Date().toISOString(),K=M({cveName:a,purls:w,status:"not_affected",impactStatement:c.impactStatement,timestamp:G}),E=new S(g);await E.read();let{created:I}=E.upsert(K,c.author);await E.write(),console.log(`${I?"[created]":"[updated]"} Auto VEX for ${a} -> ${g}`),I?p.created.push(a):p.updated.push(a)}catch(g){let h=`Failed to process ${a}: ${String(g)}`;console.error(`[error] ${h}`),p.errors.push(h)}return p}async function ct(n){let t=await(0,k.readFile)(n,"utf8");return JSON.parse(t)}var C=class{specs;commandName;helpLines;constructor(t,e,r=[]){this.commandName=t,this.specs=e,this.helpLines=r}parse(t){let e=t.slice(2),r=new Map(this.specs.map(o=>[o.flag,o.defaultValue])),i=!1;for(let o=0;o<e.length;o++){let s=e[o];if(s==="--dry-run"){i=!0;continue}(s==="--help"||s==="-h")&&(this.printHelp(),process.exit(0));let l=this.specs.find(c=>c.flag===s||c.alias===s);l&&e[o+1]?r.set(l.flag,e[++o]):(console.error(`Unknown argument: ${s}`),this.printHelp(),process.exit(1))}return{values:r,dryRun:i}}printHelp(){let t=this.specs.map(e=>` ${(e.alias?`${e.alias}, ${e.flag} <path>`:` ${e.flag} <path>`).padEnd(38)}${e.description}
4
+ ${"".padEnd(42)}(default: ${e.defaultValue})`);console.log([`Usage: ${this.commandName} [options]`,"","Options:",...t," --dry-run"+" ".repeat(29)+"Print what would happen without making changes"," -h, --help"+" ".repeat(32)+"Show this help message",...this.helpLines].join(`
5
+ `))}};var ut=new C("ct-vuln-auto-vex",[{flag:"--auto-vex-config",alias:"-c",description:"Path to auto-vex-conf.json configuration file",defaultValue:(0,D.join)(process.cwd(),"auto-vex-conf.json")},{flag:"--summary",alias:"-s",description:"Path to scan-summary.json produced by ct-vuln-scan",defaultValue:(0,D.join)(process.cwd(),"output","scan-summary.json")}],["","Configuration (auto-vex-conf.json):"," impactStatement Required. Text written as impact_statement in each VEX statement."," maxSeverity Optional. Exclusive severity threshold. CVEs with a severity"," strictly below this level receive an auto-generated statement."," Values: UNKNOWN | LOW | MEDIUM | HIGH | CRITICAL (default: HIGH)"," author Optional. Author field in the OpenVEX document (default: conterra)"," subDir Optional. Sub-directory of vexDir for auto files (default: auto)"]);(async()=>{let{values:n,dryRun:t}=ut.parse(process.argv),e=n.get("--auto-vex-config"),r=n.get("--summary"),i=process.cwd();console.log(`Auto VEX Creator${t?" [dry-run]":""}`),console.log(` auto-vex-config: ${e}`),console.log(` summary: ${r}`),console.log("");try{let o=await new f(i).loadProjectConfig(),s=await W({scanSummaryPath:r,autoVexConfigPath:e,vexDir:o.vexDir,dryRun:t});console.log(""),console.log("=== Auto VEX Creator Summary ==="),console.log(` Created : ${s.created.length}`),console.log(` Updated : ${s.updated.length}`),console.log(` Errors : ${s.errors.length}`),s.errors.length>0&&(process.exitCode=1)}catch(o){console.error(`Fatal error: ${String(o)}`),process.exit(1)}})();
@@ -1,20 +1,9 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var J=require("path"),V=require("zx");var R=require("fs/promises");function E(r,e=""){return O(r,e,new Set,new Set)}function O(r,e="",n,t){let s=`${e}- ${r.purl}`;if(n.has(r.purl))return s+=" (cycle detected)",s;if(t.has(r.purl))return s+=" (deduplicated)",s;t.add(r.purl),n.add(r.purl);let i=n.size===1;for(let o of r.usedBy){let a=O(o,e+(i?" ":" "),n,t);a!==""&&(s+=`
3
- `,s+=a)}return n.delete(r.purl),s}async function U(r){let{scanSummaryPath:e,jiraConfigPath:n,jiraUser:t,jiraApiToken:s,dryRun:i=!1}=r,[o,a]=await Promise.all([W(e),q(n)]),c={created:[],skipped:[],errors:[]},u=new I(a.jiraUrl,t,s),C=new Map;for(let[f,T]of Object.entries(o.vulnerabilities)){let K=o.vulnerabilityToProject[f]??[];for(let l of a.issues){let w=K.filter(h=>M(h,l.reportProjects));if(w.length===0)continue;let S=X(T);try{let h=await u.issueExists(l.jiraProject,f);if(h){console.log(`[skip] Issue for ${f} already exists: ${h}`),c.skipped.push(`${l.jiraProject}::${f}`);continue}if(i){console.log(`[dry-run] Would create issue in ${l.jiraProject}: "${S}"`),console.log(` Matching projects: ${w.join(", ")}`),c.created.push(`${l.jiraProject}::${f}`);continue}let b,k=[],v=!1;for(let p of l.addToBoard??[]){let m=p.matchProjects??["*"];if(w.some(d=>M(d,m)))if(p.sprintBoardId!=null){if(!v){v=!0;let d=p.sprintBoardId;if(!C.has(d)){let P=await u.getActiveSprintId(d).catch(H=>(console.warn(`[warn] Could not resolve active sprint for boardId ${d}: ${String(H)}`),null));C.set(d,P)}b=C.get(d)??void 0,p.issueLabels&&k.push(...p.issueLabels)}}else p.issueLabels&&k.push(...p.issueLabels)}let B=[...l.issueLabels??[],...k],j=new Map;if(o.projectsToComponents)for(let p of w){let m=o.projectsToComponents[p]??{},x=[];for(let d of T.components){let P=m[d];P&&x.push(P)}x.length>0&&j.set(p,x)}let _=ne(T,w,j),$=await u.createIssue({projectKey:l.jiraProject,issueType:l.issueType,summary:S,description:_,labels:B.length>0?B:void 0,sprintId:b});if(j.size>0){let p=re(f,j);if(p){let m=`${f}-dependency-trees.md`;await u.attachMarkdown($,m,p),console.log(`[attached] ${m} to ${$}`)}}console.log(`[created] ${$} in ${l.jiraProject}: "${S}"`),c.created.push($)}catch(h){let b=`Failed to process ${f} for project ${l.jiraProject}: ${String(h)}`;console.error(`[error] ${b}`),c.errors.push(b)}}}return c}async function W(r){let e=await(0,R.readFile)(r,"utf8");return JSON.parse(e)}async function q(r){let e=await(0,R.readFile)(r,"utf8"),n=JSON.parse(e);if(!n.issues&&n.issue&&(n.issues=n.issue),!n.jiraUrl||typeof n.jiraUrl!="string")throw new Error("jira-conf.json: missing or invalid 'jiraUrl' field");if(!Array.isArray(n.issues))throw new Error("jira-conf.json: missing or invalid 'issues' array");return n}function G(r){return r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function Q(r,e){let n=e.split("*").map(G).join(".*");return new RegExp(`^${n}$`).test(r)}function M(r,e){return e.some(n=>Q(r,n))}function X(r){let e=r.title?`: ${r.title}`:"";return`[${r.severity}] ${r.id}${e}`}function Y(...r){return{type:"doc",version:1,content:r}}function g(r,e){return{type:"heading",attrs:{level:r},content:[{type:"text",text:e}]}}function Z(r){let e=r.split(/\r?\n/),n=[],t=0;for(;t<e.length;){let s=e[t],i=s.match(/^```(\w*)$/);if(i){let c=i[1]??"text",u=[];for(t++;t<e.length&&!e[t].startsWith("```");)u.push(e[t]),t++;t++,n.push(L(u.join(`
4
- `),c));continue}let o=s.match(/^(#{1,3})\s+(.+)$/);if(o){let c=Math.min(o[1].length,3);n.push(g(c,o[2].trim())),t++;continue}if(/^[-*]\s/.test(s)){let c=[];for(;t<e.length&&/^[-*]\s/.test(e[t]);){let u=e[t].replace(/^[-*]\s+/,"");c.push({type:"listItem",content:[{type:"paragraph",content:A(u)}]}),t++}n.push({type:"bulletList",content:c});continue}if(/^\d+\.\s/.test(s)){let c=[];for(;t<e.length&&/^\d+\.\s/.test(e[t]);){let u=e[t].replace(/^\d+\.\s+/,"");c.push({type:"listItem",content:[{type:"paragraph",content:A(u)}]}),t++}n.push({type:"orderedList",content:c});continue}if(s.trim()===""){t++;continue}let a=[];for(;t<e.length&&e[t].trim()!==""&&!/^(#{1,3}\s|[-*]\s|\d+\.\s|```)/.test(e[t]);)a.push(e[t]),t++;if(a.length>0){let c=[];for(let u=0;u<a.length;u++)c.push(...A(a[u])),u<a.length-1&&c.push({type:"hardBreak"});n.push({type:"paragraph",content:c})}}return n}function A(r){let e=[],n=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`|_(.+?)_)/g,t=0,s;for(;(s=n.exec(r))!==null;)s.index>t&&e.push({type:"text",text:r.slice(t,s.index)}),s[2]!==void 0?e.push({type:"text",text:s[2],marks:[{type:"strong"}]}):s[3]!==void 0?e.push({type:"text",text:s[3],marks:[{type:"em"}]}):s[4]!==void 0?e.push({type:"text",text:s[4],marks:[{type:"code"}]}):s[5]!==void 0&&e.push({type:"text",text:s[5],marks:[{type:"em"}]}),t=s.index+s[0].length;return t<r.length&&e.push({type:"text",text:r.slice(t)}),e.length>0?e:[{type:"text",text:r}]}function L(r,e="text"){return{type:"codeBlock",attrs:{language:e},content:[{type:"text",text:r}]}}function ee(r){return{type:"bulletList",content:r.map(e=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:e}]}]}))}}function te(r){return{type:"bulletList",content:r.map(e=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:e,marks:[{type:"link",attrs:{href:e}}]}]}]}))}}function N(r,...e){return{type:"expand",attrs:{title:r},content:e}}function y(r){return{type:"paragraph",content:[{type:"text",text:r,marks:[{type:"em"}]}]}}function D(r){return!r||r.length===0?"":r.map(e=>E(e,"")).join(`
2
+ "use strict";var ce=Object.create;var F=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty;var fe=(o,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of de(e))!ue.call(o,n)&&n!==r&&F(o,n,{get:()=>e[n],enumerable:!(t=le(e,n))||t.enumerable});return o};var me=(o,e,r)=>(r=o!=null?ce(pe(o)):{},fe(e||!o||!o.__esModule?F(r,"default",{value:o,enumerable:!0}):r,o));var O=require("path"),ie=require("zx");var ne=require("fs/promises");var V={UNKNOWN:0,LOW:1,MEDIUM:2,HIGH:3,CRITICAL:4},b=["UNKNOWN","LOW","MEDIUM","HIGH","CRITICAL"];function R(o,e){return V[o]<V[e]}function v(...o){return{type:"doc",version:1,content:o}}function f(o,e){return{type:"heading",attrs:{level:o},content:[{type:"text",text:e}]}}function j(o,e="text"){return{type:"codeBlock",attrs:{language:e},content:[{type:"text",text:o}]}}function _(o){return{type:"bulletList",content:o.map(e=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:e}]}]}))}}function W(o){return{type:"bulletList",content:o.map(e=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:e,marks:[{type:"link",attrs:{href:e}}]}]}]}))}}function P(o,...e){return{type:"expand",attrs:{title:o},content:e}}function p(o){return{type:"paragraph",content:[{type:"text",text:o,marks:[{type:"em"}]}]}}var u=require("fs/promises");async function H(o){try{return await ge(o)?JSON.parse(await(0,u.readFile)(o,{encoding:"utf-8"})):void 0}catch(e){throw new Error(`Error reading JSON file ${o}: ${e}`,{cause:e})}}async function ge(o){try{return await(0,u.access)(o,u.constants.F_OK),!0}catch{return!1}}function z(o,e){return`Basic ${Buffer.from(`${o}:${e}`).toString("base64")}`}var N=class{authHeader;baseUrl;constructor(e,r,t){this.baseUrl=e.replace(/\/$/,""),this.authHeader=z(r,t)}get headers(){return{Authorization:this.authHeader,"Content-Type":"application/json",Accept:"application/json"}}async safeJson(e,r){let t=await e.text();try{return JSON.parse(t)}catch{let n=t.slice(0,500).replace(/\s+/g," ").trim();throw new Error(`${r}: expected JSON but got (HTTP ${e.status}): ${n}`)}}async findExistingIssue(e,r){let t=e.replace(/"/g,'\\"'),n=r.replace(/"/g,'\\"'),s=`project = "${t}" AND summary ~ "\\"${n}\\""`,a=`${this.baseUrl}/rest/api/3/search/jql?jql=${encodeURIComponent(s)}&maxResults=1&fields=summary,labels,status`,i=await fetch(a,{method:"GET",headers:this.headers});if(!i.ok){let d=await i.text();throw new Error(`Jira search failed (${i.status}): ${d}`)}let c=(await this.safeJson(i,"Jira search")).issues[0];return c?{key:c.key,labels:c.fields?.labels??[],statusCategory:c.fields?.status?.statusCategory?.key??"new"}:null}async createIssue(e){let r={project:{key:e.projectKey},issuetype:{name:e.issueType},summary:e.summary,description:e.description};e.labels&&e.labels.length>0&&(r.labels=e.labels),e.sprintId!=null&&(r.customfield_10020=e.sprintId);let t={fields:r},n=await fetch(`${this.baseUrl}/rest/api/3/issue`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});if(!n.ok){let a=await n.text();throw new Error(`Jira create issue failed (${n.status}): ${a}`)}return(await this.safeJson(n,"Jira create issue")).key}async addLabels(e,r){if(r.length===0)return;let t={update:{labels:r.map(s=>({add:s}))}},n=await fetch(`${this.baseUrl}/rest/api/3/issue/${e}`,{method:"PUT",headers:this.headers,body:JSON.stringify(t)});if(!n.ok){let s=await n.text();throw new Error(`Jira add labels failed (${n.status}): ${s}`)}}async setSprint(e,r){let t={fields:{customfield_10020:r}},n=await fetch(`${this.baseUrl}/rest/api/3/issue/${e}`,{method:"PUT",headers:this.headers,body:JSON.stringify(t)});if(!n.ok){let s=await n.text();throw new Error(`Jira set sprint failed (${n.status}): ${s}`)}}async addComment(e,r){let t=await fetch(`${this.baseUrl}/rest/api/3/issue/${e}/comment`,{method:"POST",headers:this.headers,body:JSON.stringify({body:r})});if(!t.ok){let n=await t.text();throw new Error(`Jira add comment failed (${t.status}): ${n}`)}}async getTransitions(e){let r=await fetch(`${this.baseUrl}/rest/api/3/issue/${e}/transitions`,{method:"GET",headers:this.headers});if(!r.ok){let n=await r.text();throw new Error(`Jira get transitions failed (${r.status}): ${n}`)}return(await this.safeJson(r,"Jira transitions lookup")).transitions.map(n=>({id:n.id,name:n.name,toStatusName:n.to?.name??"",toStatusCategory:n.to?.statusCategory?.key??""}))}async transitionIssue(e,r){let t=await fetch(`${this.baseUrl}/rest/api/3/issue/${e}/transitions`,{method:"POST",headers:this.headers,body:JSON.stringify({transition:{id:r}})});if(!t.ok){let n=await t.text();throw new Error(`Jira transition issue failed (${t.status}): ${n}`)}}async attachMarkdown(e,r,t){let n=`${this.baseUrl}/rest/api/3/issue/${e}/attachments`,s=new FormData;s.append("file",new Blob([t],{type:"text/markdown"}),r);let a=await fetch(n,{method:"POST",headers:{Authorization:this.authHeader,"X-Atlassian-Token":"no-check"},body:s});if(!a.ok){let i=await a.text();throw new Error(`Jira attach file failed (${a.status}): ${i}`)}}async getActiveSprintId(e){let r=`${this.baseUrl}/rest/agile/1.0/board/${e}/sprint?state=active&maxResults=1`,t=await fetch(r,{method:"GET",headers:this.headers});if(!t.ok){let s=await t.text();throw new Error(`Jira agile sprint lookup failed (${t.status}): ${s}`)}return(await this.safeJson(t,"Jira sprint lookup")).values[0]?.id??null}};function he(o){return o.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function ye(o,e){let r=e.split("*").map(he).join(".*");return new RegExp(`^${r}$`).test(o)}function E(o,e){return e.some(r=>ye(o,r))}function G(o,e=""){return q(o,e,new Set,new Set)}function q(o,e="",r,t){let n=`${e}- ${o.purl}`;if(r.has(o.purl))return n+=" (cycle detected)",n;if(t.has(o.purl))return n+=" (deduplicated)",n;t.add(o.purl),r.add(o.purl);let s=r.size===1;for(let a of o.usedBy){let i=q(a,e+(s?" ":" "),r,t);i!==""&&(n+=`
3
+ `,n+=i)}return r.delete(o.purl),n}function X(o){let e=o.split(/\r?\n/),r=[],t=0;for(;t<e.length;){let n=e[t],s=n.match(/^```(\w*)$/);if(s){let l=s[1]??"text",c=[];for(t++;t<e.length&&!e[t].startsWith("```");)c.push(e[t]),t++;t++,r.push(j(c.join(`
4
+ `),l));continue}let a=n.match(/^(#{1,3})\s+(.+)$/);if(a){let l=Math.min(a[1].length,3);r.push({type:"heading",attrs:{level:l},content:[{type:"text",text:a[2].trim()}]}),t++;continue}if(/^[-*]\s/.test(n)){let l=[];for(;t<e.length&&/^[-*]\s/.test(e[t]);){let c=e[t].replace(/^[-*]\s+/,"");l.push({type:"listItem",content:[{type:"paragraph",content:J(c)}]}),t++}r.push({type:"bulletList",content:l});continue}if(/^\d+\.\s/.test(n)){let l=[];for(;t<e.length&&/^\d+\.\s/.test(e[t]);){let c=e[t].replace(/^\d+\.\s+/,"");l.push({type:"listItem",content:[{type:"paragraph",content:J(c)}]}),t++}r.push({type:"orderedList",content:l});continue}if(n.trim()===""){t++;continue}let i=[];for(;t<e.length&&e[t].trim()!==""&&!/^(#{1,3}\s|[-*]\s|\d+\.\s|```)/.test(e[t]);)i.push(e[t]),t++;if(i.length>0){let l=[];for(let c=0;c<i.length;c++)l.push(...J(i[c])),c<i.length-1&&l.push({type:"hardBreak"});r.push({type:"paragraph",content:l})}}return r}function J(o){let e=[],r=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`|_(.+?)_)/g,t=0,n;for(;(n=r.exec(o))!==null;)n.index>t&&e.push({type:"text",text:o.slice(t,n.index)}),n[2]!==void 0?e.push({type:"text",text:n[2],marks:[{type:"strong"}]}):n[3]!==void 0?e.push({type:"text",text:n[3],marks:[{type:"em"}]}):n[4]!==void 0?e.push({type:"text",text:n[4],marks:[{type:"code"}]}):n[5]!==void 0&&e.push({type:"text",text:n[5],marks:[{type:"em"}]}),t=n.index+n[0].length;return t<o.length&&e.push({type:"text",text:o.slice(t)}),e.length>0?e:[{type:"text",text:o}]}var we=2e4;function K(o){let e=o.title?`: ${o.title}`:"";return`[${o.severity}] ${o.id}${e}`}function Q(o,e,r=new Map){let t=[];if(t.push(f(1,"Informationen zur Schwachstelle")),t.push(p("Diese Informationen wurden automatisch generiert.")),o.refs&&o.refs.length>0&&t.push(W(o.refs)),o.description){let n=X(o.description);t.push(P("Beschreibung",...n))}return t.push(f(2,"Betroffene Artefakte")),o.components&&o.components.length>0?t.push(_(o.components)):t.push(p("Keine Komponenten bekannt.")),t.push(f(2,"Gemeldet f\xFCr")),Z(t,e,r),t.push(f(1,"Einwertung")),t.push(p("Einwertung des CVE in Bezug auf die gemeldeten Projekte/Produkte. Dies kann eine Bewertung der Schwere, der Auswirkungen und der Wahrscheinlichkeit eines Angriffs umfassen.")),t.push(f(1,"Betroffen sind")),t.push(p("Abschlie\xDFende Darstellung, welche Projekte/Produkte tats\xE4chlich betroffen oder nicht betroffen sind.")),t.push(f(1,"Ma\xDFnahmen")),t.push(p("\xDCbersicht der zu ergreifenden Ma\xDFnahmen, um den CVE zu beheben oder zu mitigieren. Dies kann Patches, Updates oder Konfigurations\xE4nderungen umfassen.")),v(...t)}function Y(o,e=new Map){let r=[];return r.push(p("Diese Projekte sind ebenfalls von dieser Schwachstelle betroffen und wurden automatisch erg\xE4nzt.")),r.push(f(2,"Zus\xE4tzlich gemeldet f\xFCr")),Z(r,o,e),v(...r)}function Z(o,e,r){let t=0;for(let n of e.slice().sort()){o.push({type:"paragraph",content:[{type:"text",text:n,marks:[{type:"strong"}]}]});let s=r.get(n);if(s&&s.length>0){let a=te(s);a&&(t+=a.length,t>we?o.push(P("Verwendungsbaum",p("Gesamtgr\xF6\xDFe der Verwendungsb\xE4ume \xFCberschreitet Limit. Siehe Issue-Attachments f\xFCr vollst\xE4ndige B\xE4ume."))):o.push(P("Verwendungsbaum",j(a))))}}}function ee(o,e){if(e.size===0)return"";let r=[`# Verwendungsb\xE4ume f\xFCr ${o}`,""];for(let[t,n]of[...e.entries()].sort(([s],[a])=>s.localeCompare(a))){r.push(`## ${t}`,"");let s=te(n);s&&r.push("```",s,"```"),r.push("")}return r.join(`
5
+ `)}function te(o){return!o||o.length===0?"":o.map(e=>G(e,"")).join(`
5
6
 
6
- `)}function re(r,e){if(e.size===0)return"";let n=[`# Verwendungsb\xE4ume f\xFCr ${r}`,""];for(let[t,s]of[...e.entries()].sort(([i],[o])=>i.localeCompare(o))){n.push(`## ${t}`,"");let i=D(s);i&&n.push("```",i,"```"),n.push("")}return n.join(`
7
- `)}function ne(r,e,n=new Map){let t=[],i=0;if(t.push(g(1,"Informationen zur Schwachstelle")),t.push(y("Diese Informationen wurden automatisch generiert.")),r.refs&&r.refs.length>0&&t.push(te(r.refs)),r.description){let o=Z(r.description);t.push(N("Beschreibung",...o))}t.push(g(2,"Betroffene Artefakte")),r.components&&r.components.length>0?t.push(ee(r.components)):t.push(y("Keine Komponenten bekannt.")),t.push(g(2,"Gemeldet f\xFCr"));for(let o of e.slice().sort()){t.push({type:"paragraph",content:[{type:"text",text:o,marks:[{type:"strong"}]}]});let a=n.get(o);if(a&&a.length>0){let c=D(a);c&&(i+=c.length,i>2e4?t.push(N("Verwendungsbaum",y("Gesamtgr\xF6\xDFe der Verwendungsb\xE4ume \xFCberschreitet Limit. Siehe Issue-Attachments f\xFCr vollst\xE4ndige B\xE4ume."))):t.push(N("Verwendungsbaum",L(c))))}}return t.push(g(1,"Einwertung")),t.push(y("Einwertung des CVE in Bezug auf die gemeldeten Projekte/Produkte. Dies kann eine Bewertung der Schwere, der Auswirkungen und der Wahrscheinlichkeit eines Angriffs umfassen.")),t.push(g(1,"Betroffen sind")),t.push(y("Abschlie\xDFende Darstellung, welche Projekte/Produkte tats\xE4chlich betroffen oder nicht betroffen sind.")),t.push(g(1,"Ma\xDFnahmen")),t.push(y("\xDCbersicht der zu ergreifenden Ma\xDFnahmen, um den CVE zu beheben oder zu mitigieren. Dies kann Patches, Updates oder Konfigurations\xE4nderungen umfassen.")),Y(...t)}var I=class{authHeader;baseUrl;constructor(e,n,t){this.baseUrl=e.replace(/\/$/,""),this.authHeader=`Basic ${Buffer.from(`${n}:${t}`).toString("base64")}`}get headers(){return{Authorization:this.authHeader,"Content-Type":"application/json",Accept:"application/json"}}async safeJson(e,n){let t=await e.text();try{return JSON.parse(t)}catch{let s=t.slice(0,500).replace(/\s+/g," ").trim();throw new Error(`${n}: expected JSON but got (HTTP ${e.status}): ${s}`)}}async issueExists(e,n){let t=n.replace(/"/g,'\\"'),s=`project = "${e}" AND summary ~ "\\"${t}\\""`,i=`${this.baseUrl}/rest/api/3/search/jql?jql=${encodeURIComponent(s)}&maxResults=1&fields=summary`,o=await fetch(i,{method:"GET",headers:this.headers});if(!o.ok){let c=await o.text();throw new Error(`Jira search failed (${o.status}): ${c}`)}return(await this.safeJson(o,"Jira search")).issues[0]?.key??null}async createIssue(e){let n={project:{key:e.projectKey},issuetype:{name:e.issueType},summary:e.summary,description:e.description};e.labels&&e.labels.length>0&&(n.labels=e.labels),e.sprintId!=null&&(n.customfield_10020=e.sprintId);let t={fields:n},s=await fetch(`${this.baseUrl}/rest/api/3/issue`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});if(!s.ok){let o=await s.text();throw new Error(`Jira create issue failed (${s.status}): ${o}`)}return(await this.safeJson(s,"Jira create issue")).key}async attachMarkdown(e,n,t){let s=`${this.baseUrl}/rest/api/3/issue/${e}/attachments`,i=new FormData;i.append("file",new Blob([t],{type:"text/markdown"}),n);let o=await fetch(s,{method:"POST",headers:{Authorization:this.authHeader,"X-Atlassian-Token":"no-check"},body:i});if(!o.ok){let a=await o.text();throw new Error(`Jira attach file failed (${o.status}): ${a}`)}}async getActiveSprintId(e){let n=`${this.baseUrl}/rest/agile/1.0/board/${e}/sprint?state=active&maxResults=1`,t=await fetch(n,{method:"GET",headers:this.headers});if(!t.ok){let i=await t.text();throw new Error(`Jira agile sprint lookup failed (${t.status}): ${i}`)}return(await this.safeJson(t,"Jira sprint lookup")).values[0]?.id??null}};V.dotenv.config();var F=process.env;function se(r){let e=r.slice(2),n=process.cwd(),t=(0,J.join)(n,"jira-conf.json"),s=(0,J.join)(n,"output","scan-summary.json"),i=!1;for(let o=0;o<e.length;o++){let a=e[o];(a==="--jira-config"||a==="-c")&&e[o+1]?t=e[++o]:(a==="--summary"||a==="-s")&&e[o+1]?s=e[++o]:a==="--dry-run"?i=!0:a==="--help"||a==="-h"?(z(),process.exit(0)):(console.error(`Unknown argument: ${a}`),z(),process.exit(1))}return{jiraConfigPath:t,scanSummaryPath:s,dryRun:i}}function z(){console.log(`Usage: ct-vuln-jira-report [options]
8
-
9
- Options:
10
- -c, --jira-config <path> Path to jira-conf.json configuration file
11
- (default: ./jira-conf.json)
12
- -s, --summary <path> Path to scan-summary.json produced by ct-vuln-scan
13
- (default: ./output/scan-summary.json)
14
- --dry-run Print what would be created without calling Jira
15
- -h, --help Show this help message
16
-
17
- Required environment variables:
18
- JIRA_USER Jira account e-mail address
19
- JIRA_API_TOKEN Jira API token (see https://id.atlassian.com/manage-profile/security/api-tokens)
20
- `)}(async()=>{let{jiraConfigPath:r,scanSummaryPath:e,dryRun:n}=se(process.argv),t=F.JIRA_USER,s=F.JIRA_API_TOKEN;(!t||!s)&&(console.error("Error: JIRA_USER and JIRA_API_TOKEN environment variables must be set."),process.exit(1)),console.log(`Jira reporter${n?" [dry-run]":""}`),console.log(` config: ${r}`),console.log(` summary: ${e}`),console.log("");try{let i=await U({scanSummaryPath:e,jiraConfigPath:r,jiraUser:t,jiraApiToken:s,dryRun:n});console.log(""),console.log("=== Jira Report Summary ==="),console.log(` Created : ${i.created.length}`),console.log(` Skipped : ${i.skipped.length}`),console.log(` Errors : ${i.errors.length}`),i.errors.length>0&&(process.exitCode=1)}catch(i){console.error(`Fatal error: ${String(i)}`),process.exit(1)}})();
7
+ `)}var L="proj:";function U(o){let e=o.replace(/@/g,"_v").replace(/\s+/g,"_");return`${L}${e}`}function Se(o){if(!o.startsWith(L))return null;let e=o.slice(L.length),r=e.lastIndexOf("_v");return r<0?e:e.slice(0,r)+"@"+e.slice(r+2)}function re(o){let e=new Set;if(!o)return e;for(let r of o){let t=Se(r);t!==null&&e.add(t)}return e}var T=class{constructor(e,r,t){this.config=e;this.client=new N(e.jiraUrl,r,t)}config;client;activeSprintCache=new Map;async report(e,r){let t={created:[],updated:[],skipped:[],errors:[]};for(let[n,s]of Object.entries(e.vulnerabilities)){let a=e.vulnerabilityToProject[n]??[];for(let i of this.config.issues){let l=a.filter(c=>E(c,i.reportProjects));if(l.length!==0)try{let c=await this.client.findExistingIssue(i.jiraProject,n);c?await this.handleExistingIssue(e,s,c,i,l,r,t):await this.handleNewIssue(e,n,s,i,l,r,t)}catch(c){let d=`Failed to process ${n} for project ${i.jiraProject}: ${String(c)}`;console.error(`[error] ${d}`),t.errors.push(d)}}}return t}async handleNewIssue(e,r,t,n,s,a,i){let l=K(t),c=this.resolveAutoCloseThreshold(n),d=c!=null&&R(t.severity,c);if(a){console.log(`[dry-run] Would create issue in ${n.jiraProject}: "${l}"`),console.log(` Matching projects: ${s.join(", ")}`),d&&console.log(`[dry-run] Would auto-close ${n.jiraProject}::${r} (severity=${t.severity} below ${c})`),i.created.push(`${n.jiraProject}::${r}`);return}let{activeSprintId:g,allLabels:y}=await this.resolveBoardRouting(n,s),w=this.collectProjectComponentTrees(e,s,t.components),k=Q(t,s,w),C=[...y,...s.map(U)],h=await this.client.createIssue({projectKey:n.jiraProject,issueType:n.issueType,summary:l,description:k,labels:C.length>0?C:void 0,sprintId:g});if(w.size>0){let $=ee(r,w);if($){let x=`${r}-dependency-trees.md`;await this.client.attachMarkdown(h,x,$),console.log(`[attached] ${x} to ${h}`)}}console.log(`[created] ${h} in ${n.jiraProject}: "${l}"`),i.created.push(h),d&&await this.autoCloseIssue(h,t.severity,c)}async handleExistingIssue(e,r,t,n,s,a,i){let l=re(t.labels),c=s.filter(S=>!l.has(S));if(c.length===0){console.log(`[skip] ${t.key} already covers all matching projects`),i.skipped.push(t.key);return}let d=t.statusCategory==="done",g=this.resolveAutoCloseThreshold(n),y=g!=null&&R(r.severity,g),w=d&&!y;if(a){let S=w?" and re-open + re-add to active sprint":d?" (kept closed: sub-threshold)":"";console.log(`[dry-run] Would update ${t.key}: add project tag(s) ${c.join(", ")}`+S),i.updated.push(t.key);return}let{activeSprintId:k,allLabels:C}=await this.resolveBoardRouting(n,s),h=this.collectProjectComponentTrees(e,c,r.components),$=[...C,...c.map(U)],x=new Set(t.labels),M=$.filter(S=>!x.has(S));M.length>0&&await this.client.addLabels(t.key,M);let ae=Y(c,h);await this.client.addComment(t.key,ae),console.log(`[updated] ${t.key}: added project(s) ${c.join(", ")}`),d&&y?console.log(`[kept-closed] ${t.key} (severity ${r.severity} below auto-close threshold ${g})`):d&&await this.reopenAndReassignSprint(t.key,k),i.updated.push(t.key)}async reopenAndReassignSprint(e,r){let t;try{t=await this.client.getTransitions(e)}catch(s){console.warn(`[warn] Could not list transitions for ${e}: ${String(s)}`);return}let n=t.find(s=>s.toStatusCategory==="new");if(!n){console.warn(`[warn] ${e} is closed but no transition leading to a non-done status is available; leaving status unchanged`);return}try{await this.client.transitionIssue(e,n.id),console.log(`[reopened] ${e} via transition "${n.name}"`)}catch(s){console.warn(`[warn] Could not transition ${e} to a non-done status: ${String(s)}`);return}if(r!=null)try{await this.client.setSprint(e,r),console.log(`[sprint] ${e} added to active sprint ${r}`)}catch(s){console.warn(`[warn] Could not set sprint for ${e}: ${String(s)}`)}}resolveAutoCloseThreshold(e){return e.autoCloseBelowSeverity??this.config.autoCloseBelowSeverity}async autoCloseIssue(e,r,t){let n;try{n=await this.client.getTransitions(e)}catch(i){console.warn(`[warn] Could not list transitions for ${e} (auto-close): ${String(i)}`);return}let s=n.filter(i=>i.toStatusCategory==="done"),a=s.find(i=>i.toStatusName.toLowerCase()==="closed")??s.find(i=>{let l=i.name.toLowerCase();return l==="close"||l==="closed"})??s[0];if(!a){console.warn(`[warn] ${e} has no transition leading to a done status; cannot auto-close`);return}try{await this.client.transitionIssue(e,a.id),console.log(`[auto-closed] ${e} (severity=${r}, threshold=${t}) via transition "${a.name}"`)}catch(i){console.warn(`[warn] Could not transition ${e} to a done status: ${String(i)}`);return}try{let i=v(p(`Automatisch geschlossen: Schwere ${r} liegt unterhalb der konfigurierten Auto-Close-Schwelle ${t}.`));await this.client.addComment(e,i)}catch(i){console.warn(`[warn] Could not post auto-close comment on ${e}: ${String(i)}`)}}async resolveBoardRouting(e,r){let t,n=[],s=!1;for(let i of e.addToBoard??[]){let l=i.matchProjects??["*"];if(r.some(d=>E(d,l)))if(i.sprintBoardId!=null){if(!s){s=!0;let d=i.sprintBoardId;if(!this.activeSprintCache.has(d)){let g=await this.client.getActiveSprintId(d).catch(y=>(console.warn(`[warn] Could not resolve active sprint for boardId ${d}: ${String(y)}`),null));this.activeSprintCache.set(d,g)}t=this.activeSprintCache.get(d)??void 0,i.issueLabels&&n.push(...i.issueLabels)}}else i.issueLabels&&n.push(...i.issueLabels)}let a=[...e.issueLabels??[],...n];return{activeSprintId:t,allLabels:a}}collectProjectComponentTrees(e,r,t){let n=new Map;if(!e.projectsToComponents)return n;for(let s of r){let a=e.projectsToComponents[s]??{},i=[];for(let l of t){let c=a[l];c&&i.push(c)}i.length>0&&n.set(s,i)}return n}};var m=me(require("path")),B=require("fs/promises");var D=class o{constructor(e){this.workingDir=e}workingDir;static DEFAULT_MAVEN_REPO="https://repository.conterra.de/repository/maven-mirror-ct";static DEFAULT_VEX_SUBDIR="input/vex";static DEFAULT_OUT_SUBDIR="output";static DEFAULT_CACHE_SUBDIR="cache";static DEFAULT_SCANNERS=["grype","trivy","ossindex"];normalize(e,r){let t=e.findNoLongerDetectedVulnerabilitiesOnlyForSnapshots??!1;return{projectConfigFileLocation:r,onNewVulnerabilities:e.onNewVulnerabilities??(e.failOnNewVulnerabilities?"fail":"warn"),onNoLongerDetectedVulnerabilities:e.onNoLongerDetectedVulnerabilities??"ignore",reportNoLongerDetectedVulnerabilities:e.reportNoLongerDetectedVulnerabilities??!0,consoleReport:e.consoleReport??"BY_PROJECT_DETAILED",createSubDirsForProject:e.createSubDirsForProject??!0,mavenRepo:e.mavenRepo??o.DEFAULT_MAVEN_REPO,vexUrls:e.vexUrls??[],vexDir:this.resolvePath(e.vexDir)??(0,m.resolve)(this.workingDir,o.DEFAULT_VEX_SUBDIR),outDir:this.resolvePath(e.outDir)??(0,m.resolve)(this.workingDir,o.DEFAULT_OUT_SUBDIR),cacheDir:this.resolvePath(e.cacheDir)??(0,m.resolve)(this.workingDir,o.DEFAULT_CACHE_SUBDIR),scanners:this.normalizeScanners(e.scanners,r),projects:this.normalizeProjects(e.projects??[],t)}}normalizeScanners(e,r){return(e??o.DEFAULT_SCANNERS).map(n=>{if(typeof n!="string")throw new Error(`Invalid scanner name '${String(n)}' in configuration file '${r}'`);let s=n.split("@");if(s.length>2)throw new Error(`Invalid scanner name '${n}' in configuration file '${r}'`);return{name:s[0],version:s[1]??""}})}normalizeProjects(e,r){return e.map(t=>{let n=t;if(!n.name)throw new Error("Project name is missing on entry: "+JSON.stringify(n));if(!n.version)throw new Error("Project version is missing on entry: "+JSON.stringify(n));if(!n.purl)throw new Error("Project purl is missing on entry: "+JSON.stringify(n));let s={...n,purlAliases:n.purlAliases??[],enabled:n.enabled??!0,silent:n.silent??!1,minimumSeverity:n.minimumSeverity??"UNKNOWN"};return s.sbomFile?{...s,sbomFile:this.resolvePath(s.sbomFile)??s.sbomFile}:{...s,detectNoLongerUsedVulnerabilities:r?s.purl.endsWith("-SNAPSHOT"):!0}})}resolvePath(e){if(e)return m.default.isAbsolute(e)?e:(0,m.resolve)(this.workingDir,e)}},I=class{constructor(e){this.workingDir=e;this.normalizer=new D(e)}workingDir;normalizer;projectConfigCache;async loadProjectConfig(){return this.projectConfigCache??=this.doLoadProjectConfig(),this.projectConfigCache}async doLoadProjectConfig(){let e=(0,m.resolve)(this.workingDir,"vuln-scan-conf.json"),r=await H(e);if(!r)throw new Error(`Missing project configuration file '${e}'`);return this.normalizer.normalize(r,e)}async loadJiraConfig(e){let r=await(0,B.readFile)(e,"utf8"),t=JSON.parse(r);if(!t.issues&&t.issue&&(t.issues=t.issue),!t.jiraUrl||typeof t.jiraUrl!="string")throw new Error("jira-conf.json: missing or invalid 'jiraUrl' field");if(!Array.isArray(t.issues))throw new Error("jira-conf.json: missing or invalid 'issues' array");this.validateAutoCloseSeverity(t.autoCloseBelowSeverity,"jira-conf.json: invalid 'autoCloseBelowSeverity'");for(let[n,s]of t.issues.entries())s&&typeof s=="object"&&this.validateAutoCloseSeverity(s.autoCloseBelowSeverity,`jira-conf.json: invalid 'issues[${n}].autoCloseBelowSeverity'`);return t}validateAutoCloseSeverity(e,r){if(e!==void 0&&!b.includes(e))throw new Error(`${r} value '${String(e)}'. Must be one of: ${b.join(", ")}`)}async loadAutoVexConfig(e){let r=await(0,B.readFile)(e,"utf8"),t=JSON.parse(r);if(!t.impactStatement||typeof t.impactStatement!="string")throw new Error("auto-vex-conf.json: missing or invalid 'impactStatement' field (must be a non-empty string)");if(t.maxSeverity!==void 0&&!b.includes(t.maxSeverity))throw new Error(`auto-vex-conf.json: invalid 'maxSeverity' value '${String(t.maxSeverity)}'. Must be one of: ${b.join(", ")}`);return t}};async function oe(o){let{scanSummaryPath:e,jiraConfigPath:r,jiraUser:t,jiraApiToken:n,dryRun:s=!1}=o,a=new I(process.cwd()),[i,l]=await Promise.all([be(e),a.loadJiraConfig(r)]);return new T(l,t,n).report(i,s)}async function be(o){let e=await(0,ne.readFile)(o,"utf8");return JSON.parse(e)}var A=class{specs;commandName;helpLines;constructor(e,r,t=[]){this.commandName=e,this.specs=r,this.helpLines=t}parse(e){let r=e.slice(2),t=new Map(this.specs.map(s=>[s.flag,s.defaultValue])),n=!1;for(let s=0;s<r.length;s++){let a=r[s];if(a==="--dry-run"){n=!0;continue}(a==="--help"||a==="-h")&&(this.printHelp(),process.exit(0));let i=this.specs.find(l=>l.flag===a||l.alias===a);i&&r[s+1]?t.set(i.flag,r[++s]):(console.error(`Unknown argument: ${a}`),this.printHelp(),process.exit(1))}return{values:t,dryRun:n}}printHelp(){let e=this.specs.map(r=>` ${(r.alias?`${r.alias}, ${r.flag} <path>`:` ${r.flag} <path>`).padEnd(38)}${r.description}
8
+ ${"".padEnd(42)}(default: ${r.defaultValue})`);console.log([`Usage: ${this.commandName} [options]`,"","Options:",...e," --dry-run"+" ".repeat(29)+"Print what would happen without making changes"," -h, --help"+" ".repeat(32)+"Show this help message",...this.helpLines].join(`
9
+ `))}};ie.dotenv.config();var se=process.env,ve=new A("ct-vuln-jira-report",[{flag:"--jira-config",alias:"-c",description:"Path to jira-conf.json configuration file",defaultValue:(0,O.join)(process.cwd(),"jira-conf.json")},{flag:"--summary",alias:"-s",description:"Path to scan-summary.json produced by ct-vuln-scan",defaultValue:(0,O.join)(process.cwd(),"output","scan-summary.json")}],["","Required environment variables:"," JIRA_USER Jira account e-mail address"," JIRA_API_TOKEN Jira API token (see https://id.atlassian.com/manage-profile/security/api-tokens)"]);(async()=>{let{values:o,dryRun:e}=ve.parse(process.argv),r=o.get("--jira-config"),t=o.get("--summary"),n=se.JIRA_USER,s=se.JIRA_API_TOKEN;(!n||!s)&&(console.error("Error: JIRA_USER and JIRA_API_TOKEN environment variables must be set."),process.exit(1)),console.log(`Jira reporter${e?" [dry-run]":""}`),console.log(` config: ${r}`),console.log(` summary: ${t}`),console.log("");try{let a=await oe({scanSummaryPath:t,jiraConfigPath:r,jiraUser:n,jiraApiToken:s,dryRun:e});console.log(""),console.log("=== Jira Report Summary ==="),console.log(` Created : ${a.created.length}`),console.log(` Updated : ${a.updated.length}`),console.log(` Skipped : ${a.skipped.length}`),console.log(` Errors : ${a.errors.length}`),a.errors.length>0&&(process.exitCode=1)}catch(a){console.error(`Fatal error: ${String(a)}`),process.exit(1)}})();