@reason-machines/cli-linux-x64 0.2.503 → 0.2.505

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.
Files changed (167) hide show
  1. package/THIRD_PARTY_NOTICES.txt +7 -8
  2. package/bin/reason +2 -2
  3. package/bin/runtime/srt/sandbox-runtime.mjs +52 -52
  4. package/bin/vm-hands/api-credentials-23k36ayh.js +2 -0
  5. package/bin/vm-hands/api-jd29p2kc.js +2 -0
  6. package/bin/vm-hands/ask-relay-zpp0rkhg.js +4 -0
  7. package/bin/vm-hands/connect-cli-xyxgcg6z.js +2 -0
  8. package/bin/vm-hands/credentials-byna24dv.js +2 -0
  9. package/bin/vm-hands/custom-endpoint-device-p2agcsk0.js +2 -0
  10. package/bin/vm-hands/desktop-account-z16mmkxg.js +2 -0
  11. package/bin/vm-hands/device-workspace-y0tk3ne8.js +2 -0
  12. package/bin/vm-hands/hands-worker-source-0qa16xzj.js +2 -0
  13. package/bin/vm-hands/index-h6xkz48h.js +12818 -0
  14. package/bin/vm-hands/install-receipt-nnragt7p.js +2 -0
  15. package/bin/vm-hands/local-automation-xbpca0f3.js +2 -0
  16. package/bin/vm-hands/local-capabilities-30m8pzpv.js +2 -0
  17. package/bin/vm-hands/local-desktop-users-gxfywsan.js +2 -0
  18. package/bin/vm-hands/local-display-mac-n236gkpe.js +2 -0
  19. package/bin/vm-hands/local-display-session-ddafdm8k.js +2 -0
  20. package/bin/vm-hands/local-display-video-gha54xwa.js +2 -0
  21. package/bin/vm-hands/local-managed-process-0zwxyqxd.js +2 -0
  22. package/bin/vm-hands/local-pty-session-w1yrmjm0.js +2 -0
  23. package/bin/vm-hands/managed-runtime-8y90twae.js +2 -0
  24. package/bin/vm-hands/network-contract-v0fkg94d.js +2 -0
  25. package/bin/vm-hands/network-sign-in-3dkdkh3a.js +34 -0
  26. package/bin/vm-hands/package-z2dk6xva.js +2 -0
  27. package/bin/vm-hands/permissions-ga1ax8wd.js +2 -0
  28. package/bin/vm-hands/reason-hands-protocol-vzgxd159.js +2 -0
  29. package/bin/vm-hands/serve-service-42nqanvr.js +2 -0
  30. package/bin/vm-hands/status-m0g7k47a.js +96 -0
  31. package/bin/vm-hands/version-ye6800p2.js +2 -0
  32. package/bin/vm-hands/vm-hands-entry-lite-00y3kn86.js +7 -0
  33. package/bin/vm-hands/vm-hands-entry-lite-0572m6cr.js +344 -0
  34. package/bin/vm-hands/vm-hands-entry-lite-07q2xvk1.js +5 -0
  35. package/bin/vm-hands/vm-hands-entry-lite-0a4cy8gw.js +5 -0
  36. package/bin/vm-hands/vm-hands-entry-lite-1nj03gbj.js +4 -0
  37. package/bin/vm-hands/vm-hands-entry-lite-26xb026c.js +3 -0
  38. package/bin/vm-hands/vm-hands-entry-lite-33h8294z.js +3 -0
  39. package/bin/vm-hands/vm-hands-entry-lite-3882raa5.js +3 -0
  40. package/bin/vm-hands/vm-hands-entry-lite-3rg3znp8.js +3 -0
  41. package/bin/vm-hands/vm-hands-entry-lite-4swa18qz.js +10 -0
  42. package/bin/vm-hands/vm-hands-entry-lite-56v9haps.js +3 -0
  43. package/bin/vm-hands/vm-hands-entry-lite-6x5pj2y0.js +4 -0
  44. package/bin/vm-hands/{vm-hands-entry-lite-fcvf8md1.js → vm-hands-entry-lite-8p8hz0j1.js} +2 -2
  45. package/bin/vm-hands/vm-hands-entry-lite-8twscwtw.js +112 -0
  46. package/bin/vm-hands/vm-hands-entry-lite-8xe0wzp9.js +3 -0
  47. package/bin/vm-hands/vm-hands-entry-lite-ah2ep922.js +4 -0
  48. package/bin/vm-hands/vm-hands-entry-lite-b0p8f295.js +52 -0
  49. package/bin/vm-hands/{vm-hands-entry-lite-3gztfxwt.js → vm-hands-entry-lite-b7wy89y0.js} +54 -54
  50. package/bin/vm-hands/vm-hands-entry-lite-c5gt0086.js +3 -0
  51. package/bin/vm-hands/{vm-hands-entry-lite-wrvz9jxy.js → vm-hands-entry-lite-c8bf82tx.js} +2 -2
  52. package/bin/vm-hands/vm-hands-entry-lite-dgmap6z4.js +5 -0
  53. package/bin/vm-hands/vm-hands-entry-lite-dhqmbqsh.js +9 -0
  54. package/bin/vm-hands/vm-hands-entry-lite-e1xjfj57.js +3 -0
  55. package/bin/vm-hands/vm-hands-entry-lite-e4hwb89r.js +66 -0
  56. package/bin/vm-hands/vm-hands-entry-lite-g6r5xrk0.js +105 -0
  57. package/bin/vm-hands/vm-hands-entry-lite-ghhpgt3v.js +3 -0
  58. package/bin/vm-hands/vm-hands-entry-lite-h5smacqn.js +3 -0
  59. package/bin/vm-hands/vm-hands-entry-lite-jd31as70.js +3 -0
  60. package/bin/vm-hands/vm-hands-entry-lite-k9n1pk42.js +4 -0
  61. package/bin/vm-hands/vm-hands-entry-lite-kqbats5n.js +3 -0
  62. package/bin/vm-hands/vm-hands-entry-lite-p9fwt68c.js +42 -0
  63. package/bin/vm-hands/vm-hands-entry-lite-pkk555dx.js +3 -0
  64. package/bin/vm-hands/vm-hands-entry-lite-pmw3ycgc.js +5 -0
  65. package/bin/vm-hands/vm-hands-entry-lite-q9g11dbj.js +3 -0
  66. package/bin/vm-hands/vm-hands-entry-lite-r374pchj.js +9 -0
  67. package/bin/vm-hands/vm-hands-entry-lite-r665z809.js +4 -0
  68. package/bin/vm-hands/vm-hands-entry-lite-rck5h8fr.js +3 -0
  69. package/bin/vm-hands/vm-hands-entry-lite-rj8yq6gp.js +3 -0
  70. package/bin/vm-hands/{vm-hands-entry-lite-w0hqa0d3.js → vm-hands-entry-lite-s8ty42st.js} +9 -5
  71. package/bin/vm-hands/vm-hands-entry-lite-s8zfzv0k.js +6 -0
  72. package/bin/vm-hands/vm-hands-entry-lite-tafgty5k.js +4 -0
  73. package/bin/vm-hands/vm-hands-entry-lite-tbdcmq09.js +3 -0
  74. package/bin/vm-hands/vm-hands-entry-lite-td309c1y.js +5 -0
  75. package/bin/vm-hands/vm-hands-entry-lite-v0bp1v66.js +128 -0
  76. package/bin/vm-hands/vm-hands-entry-lite-v0k8b768.js +452 -0
  77. package/bin/vm-hands/vm-hands-entry-lite-v4r1fggm.js +3 -0
  78. package/bin/vm-hands/vm-hands-entry-lite-vqr3zrqr.js +539 -0
  79. package/bin/vm-hands/vm-hands-entry-lite-wbfmc0xn.js +3 -0
  80. package/bin/vm-hands/vm-hands-entry-lite-x3pbyg92.js +3 -0
  81. package/bin/vm-hands/{vm-hands-entry-lite-rfz60hb3.js → vm-hands-entry-lite-xd2dn3n8.js} +2 -2
  82. package/bin/vm-hands/vm-hands-entry-lite-yqn8h1p0.js +3 -0
  83. package/bin/vm-hands/vm-hands-entry-lite-zj3hb5jk.js +127 -0
  84. package/bin/vm-hands/vm-hands-entry-lite-zz8tr0bm.js +12 -0
  85. package/bin/vm-hands/vm-hands-entry-lite.js +1 -3
  86. package/bin/vm-hands/vm-hands-executor-6tncheya.js +12 -0
  87. package/bin/vm-hands/vm-hands-op-runner-s1ghsym7.js +2 -0
  88. package/bin/vm-hands/vm-hands-runtime-k6egwk2t.js +4 -0
  89. package/bin/vm-hands/worker-preview-readiness-wh0yg1dz.js +2 -0
  90. package/bin/vm-hands/worker-sandbox-s054x4zw.js +2 -0
  91. package/package.json +1 -1
  92. package/bin/vm-hands/api-3khds2ds.js +0 -2
  93. package/bin/vm-hands/api-credentials-qm62bpjs.js +0 -2
  94. package/bin/vm-hands/connect-cli-aqjq32ax.js +0 -2
  95. package/bin/vm-hands/credentials-drj5ktpt.js +0 -2
  96. package/bin/vm-hands/custom-endpoint-device-389h3q6n.js +0 -2
  97. package/bin/vm-hands/desktop-account-tjf36aya.js +0 -2
  98. package/bin/vm-hands/device-workspace-pt07525s.js +0 -2
  99. package/bin/vm-hands/fsevents-s0cwdhcq.js +0 -2
  100. package/bin/vm-hands/hands-worker-source-wrj180b5.js +0 -2
  101. package/bin/vm-hands/index-w9sxzata.js +0 -12818
  102. package/bin/vm-hands/install-receipt-9bv4vth9.js +0 -2
  103. package/bin/vm-hands/local-automation-0h4gspef.js +0 -2
  104. package/bin/vm-hands/local-capabilities-bq62be6s.js +0 -2
  105. package/bin/vm-hands/local-desktop-users-tqagws7p.js +0 -2
  106. package/bin/vm-hands/local-display-mac-w792g9g3.js +0 -2
  107. package/bin/vm-hands/local-display-session-jdapy5nj.js +0 -2
  108. package/bin/vm-hands/local-display-video-zaahvqys.js +0 -2
  109. package/bin/vm-hands/local-managed-process-8xfcpy62.js +0 -2
  110. package/bin/vm-hands/local-pty-session-rdv5wv5g.js +0 -2
  111. package/bin/vm-hands/managed-runtime-b2c3ybmw.js +0 -2
  112. package/bin/vm-hands/network-contract-h6s7ptm5.js +0 -2
  113. package/bin/vm-hands/package-yy8qcwwn.js +0 -2
  114. package/bin/vm-hands/permissions-bkncrfej.js +0 -2
  115. package/bin/vm-hands/reason-hands-protocol-vw2dbdse.js +0 -2
  116. package/bin/vm-hands/serve-service-zq91vepg.js +0 -2
  117. package/bin/vm-hands/status-zqgrfjee.js +0 -10
  118. package/bin/vm-hands/version-p5nf1t3k.js +0 -2
  119. package/bin/vm-hands/vm-hands-entry-lite-13rapgf5.js +0 -3
  120. package/bin/vm-hands/vm-hands-entry-lite-1e1cmyyr.js +0 -4
  121. package/bin/vm-hands/vm-hands-entry-lite-1g1v87ky.js +0 -4
  122. package/bin/vm-hands/vm-hands-entry-lite-2dx4pnz7.js +0 -3
  123. package/bin/vm-hands/vm-hands-entry-lite-2jadtgms.js +0 -3
  124. package/bin/vm-hands/vm-hands-entry-lite-2k2b78mv.js +0 -2
  125. package/bin/vm-hands/vm-hands-entry-lite-38g65s5x.js +0 -3
  126. package/bin/vm-hands/vm-hands-entry-lite-3y7jrsta.js +0 -3
  127. package/bin/vm-hands/vm-hands-entry-lite-5fqjftez.js +0 -5
  128. package/bin/vm-hands/vm-hands-entry-lite-61yxnt1v.js +0 -128
  129. package/bin/vm-hands/vm-hands-entry-lite-64z2tjpg.js +0 -2
  130. package/bin/vm-hands/vm-hands-entry-lite-6x1an7es.js +0 -7
  131. package/bin/vm-hands/vm-hands-entry-lite-7777m86y.js +0 -3
  132. package/bin/vm-hands/vm-hands-entry-lite-87vmbt38.js +0 -3
  133. package/bin/vm-hands/vm-hands-entry-lite-88x7p823.js +0 -2
  134. package/bin/vm-hands/vm-hands-entry-lite-8e388a7s.js +0 -539
  135. package/bin/vm-hands/vm-hands-entry-lite-8qhz89mt.js +0 -4
  136. package/bin/vm-hands/vm-hands-entry-lite-9wa2y4x0.js +0 -42
  137. package/bin/vm-hands/vm-hands-entry-lite-a1xa7s06.js +0 -65
  138. package/bin/vm-hands/vm-hands-entry-lite-asvarhpz.js +0 -105
  139. package/bin/vm-hands/vm-hands-entry-lite-azpzxdzz.js +0 -3
  140. package/bin/vm-hands/vm-hands-entry-lite-dw558ggz.js +0 -2
  141. package/bin/vm-hands/vm-hands-entry-lite-e4c6z5t3.js +0 -2
  142. package/bin/vm-hands/vm-hands-entry-lite-f62fvme8.js +0 -5
  143. package/bin/vm-hands/vm-hands-entry-lite-f69t48dj.js +0 -4
  144. package/bin/vm-hands/vm-hands-entry-lite-gc7550c0.js +0 -5
  145. package/bin/vm-hands/vm-hands-entry-lite-hhhc7xx3.js +0 -9
  146. package/bin/vm-hands/vm-hands-entry-lite-krm8w7wp.js +0 -3
  147. package/bin/vm-hands/vm-hands-entry-lite-mcjca0ez.js +0 -3
  148. package/bin/vm-hands/vm-hands-entry-lite-n11hd729.js +0 -52
  149. package/bin/vm-hands/vm-hands-entry-lite-n4xgpgkw.js +0 -5
  150. package/bin/vm-hands/vm-hands-entry-lite-np07qyeq.js +0 -3
  151. package/bin/vm-hands/vm-hands-entry-lite-nqdstx24.js +0 -3
  152. package/bin/vm-hands/vm-hands-entry-lite-p7cqhtyg.js +0 -126
  153. package/bin/vm-hands/vm-hands-entry-lite-psywfz8m.js +0 -9
  154. package/bin/vm-hands/vm-hands-entry-lite-qy9xg6em.js +0 -3
  155. package/bin/vm-hands/vm-hands-entry-lite-r602gdfm.js +0 -14
  156. package/bin/vm-hands/vm-hands-entry-lite-swrymqj9.js +0 -3
  157. package/bin/vm-hands/vm-hands-entry-lite-tebh7dcm.js +0 -6
  158. package/bin/vm-hands/vm-hands-entry-lite-txd50spx.js +0 -3
  159. package/bin/vm-hands/vm-hands-entry-lite-w0pegc58.js +0 -112
  160. package/bin/vm-hands/vm-hands-entry-lite-yas2db7h.js +0 -452
  161. package/bin/vm-hands/vm-hands-entry-lite-yretc2th.js +0 -3
  162. package/bin/vm-hands/vm-hands-entry-lite-zce4hftk.js +0 -3
  163. package/bin/vm-hands/vm-hands-executor-seqvbxb7.js +0 -12
  164. package/bin/vm-hands/vm-hands-op-runner-mh0haxhr.js +0 -2
  165. package/bin/vm-hands/vm-hands-runtime-hg3yrdp9.js +0 -4
  166. package/bin/vm-hands/worker-preview-readiness-m2dn9mmn.js +0 -2
  167. package/bin/vm-hands/worker-sandbox-k4cfh0ya.js +0 -2
@@ -1,71 +1,71 @@
1
1
  // @bun
2
- var Qh=Object.create;var{getPrototypeOf:Xh,defineProperty:Rc,getOwnPropertyNames:Yh}=Object;var Bc=Object.prototype.hasOwnProperty;function Jh(e){return this[e]}var Zh,e0,zs=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?Zh??=new WeakMap:e0??=new WeakMap,a=i.get(e);if(a)return a}n=e!=null?Qh(Xh(e)):{};let s=t||!e||!e.__esModule||!Bc.call(e,"default")?Rc(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let o of Yh(e))if(!Bc.call(s,o))Rc(s,o,{get:Jh.bind(e,o),enumerable:!0})}if(r)i.set(e,s);return s};var de=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var li=import.meta.require;var me=de(function(OC,Lc){Lc.exports={options:{usePureJavaScript:!1}}});var Vc=de(function(UC,Uc){var Ys={};Uc.exports=Ys;var Oc={};Ys.encode=function(e,t,n){if(typeof t!=="string")throw TypeError('"alphabet" must be a string.');if(n!==void 0&&typeof n!=="number")throw TypeError('"maxline" must be a number.');var r="";if(!(e instanceof Uint8Array))r=l0(e,t);else{var i=0,a=t.length,s=t.charAt(0),o=[0];for(i=0;i<e.length;++i){for(var l=0,c=e[i];l<o.length;++l)c+=o[l]<<8,o[l]=c%a,c=c/a|0;while(c>0)o.push(c%a),c=c/a|0}for(i=0;e[i]===0&&i<e.length-1;++i)r+=s;for(i=o.length-1;i>=0;--i)r+=t[o[i]]}if(n){var u=new RegExp(".{1,"+n+"}","g");r=r.match(u).join(`\r
3
- `)}return r};Ys.decode=function(e,t){if(typeof e!=="string")throw TypeError('"input" must be a string.');if(typeof t!=="string")throw TypeError('"alphabet" must be a string.');var n=Oc[t];if(!n){n=Oc[t]=[];for(var r=0;r<t.length;++r)n[t.charCodeAt(r)]=r}e=e.replace(/\s/g,"");var i=t.length,a=t.charAt(0),s=[0];for(var r=0;r<e.length;r++){var o=n[e.charCodeAt(r)];if(o===void 0)return;for(var l=0,c=o;l<s.length;++l)c+=s[l]*i,s[l]=c&255,c>>=8;while(c>0)s.push(c&255),c>>=8}for(var u=0;e[u]===a&&u<e.length-1;++u)s.push(0);if(typeof Buffer<"u")return Buffer.from(s.reverse());return new Uint8Array(s.reverse())};function l0(e,t){var n=0,r=t.length,i=t.charAt(0),a=[0];for(n=0;n<e.length();++n){for(var s=0,o=e.at(n);s<a.length;++s)o+=a[s]<<8,a[s]=o%r,o=o/r|0;while(o>0)a.push(o%r),o=o/r|0}var l="";for(n=0;e.at(n)===0&&n<e.length()-1;++n)l+=i;for(n=a.length-1;n>=0;--n)l+=t[a[n]];return l}});var Pe=de(function(VC,$c){var Fc=me(),Mc=Vc(),T=$c.exports=Fc.util=Fc.util||{};(function(){if(typeof process<"u"&&process.nextTick){if(T.nextTick=process.nextTick,typeof setImmediate==="function")T.setImmediate=setImmediate;else T.setImmediate=T.nextTick;return}if(typeof setImmediate==="function"){T.setImmediate=function(){return setImmediate.apply(void 0,arguments)},T.nextTick=function(o){return setImmediate(o)};return}if(T.setImmediate=function(o){setTimeout(o,0)},typeof window<"u"&&typeof window.postMessage==="function"){let o=function(l){if(l.source===window&&l.data===e){l.stopPropagation();var c=t.slice();t.length=0,c.forEach(function(u){u()})}};var s=o,e="forge.setImmediate",t=[];T.setImmediate=function(l){if(t.push(l),t.length===1)window.postMessage(e,"*")},window.addEventListener("message",o,!0)}if(typeof MutationObserver<"u"){var n=Date.now(),r=!0,i=document.createElement("div"),t=[];new MutationObserver(function(){var l=t.slice();t.length=0,l.forEach(function(c){c()})}).observe(i,{attributes:!0});var a=T.setImmediate;T.setImmediate=function(l){if(Date.now()-n>15)n=Date.now(),a(l);else if(t.push(l),t.length===1)i.setAttribute("a",r=!r)}}T.nextTick=T.setImmediate})();T.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;T.globalScope=function(){if(T.isNodejs)return global;return typeof self>"u"?window:self}();T.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};T.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};T.isArrayBufferView=function(e){return e&&T.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function hi(e){if(!(e===8||e===16||e===24||e===32))throw Error("Only 8, 16, 24, or 32 bits supported: "+e)}T.ByteBuffer=Js;function Js(e){if(this.data="",this.read=0,typeof e==="string")this.data=e;else if(T.isArrayBuffer(e)||T.isArrayBufferView(e))if(typeof Buffer<"u"&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(r){for(var n=0;n<t.length;++n)this.putByte(t[n])}}else if(e instanceof Js||typeof e==="object"&&typeof e.data==="string"&&typeof e.read==="number")this.data=e.data,this.read=e.read;this._constructedStringLength=0}T.ByteStringBuffer=Js;var c0=4096;T.ByteStringBuffer.prototype._optimizeConstructedString=function(e){if(this._constructedStringLength+=e,this._constructedStringLength>c0)this.data.substr(0,1),this._constructedStringLength=0};T.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};T.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};T.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};T.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);var n=this.data;while(t>0){if(t&1)n+=e;if(t>>>=1,t>0)e+=e}return this.data=n,this._optimizeConstructedString(t),this};T.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};T.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(T.encodeUtf8(e))};T.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};T.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};T.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};T.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};T.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};T.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))};T.ByteStringBuffer.prototype.putInt=function(e,t){hi(t);var n="";do t-=8,n+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(n)};T.ByteStringBuffer.prototype.putSignedInt=function(e,t){if(e<0)e+=2<<t-1;return this.putInt(e,t)};T.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};T.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};T.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};T.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e};T.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e};T.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};T.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e};T.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e};T.ByteStringBuffer.prototype.getInt=function(e){hi(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};T.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};T.ByteStringBuffer.prototype.getBytes=function(e){var t;if(e)e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e;else if(e===0)t="";else t=this.read===0?this.data:this.data.slice(this.read),this.clear();return t};T.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};T.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};T.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this};T.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};T.ByteStringBuffer.prototype.copy=function(){var e=T.createBuffer(this.data);return e.read=this.read,e};T.ByteStringBuffer.prototype.compact=function(){if(this.read>0)this.data=this.data.slice(this.read),this.read=0;return this};T.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};T.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this};T.ByteStringBuffer.prototype.toHex=function(){var e="";for(var t=this.read;t<this.data.length;++t){var n=this.data.charCodeAt(t);if(n<16)e+="0";e+=n.toString(16)}return e};T.ByteStringBuffer.prototype.toString=function(){return T.decodeUtf8(this.bytes())};function u0(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var n=T.isArrayBuffer(e),r=T.isArrayBufferView(e);if(n||r){if(n)this.data=new DataView(e);else this.data=new DataView(e.buffer,e.byteOffset,e.byteLength);this.write="writeOffset"in t?t.writeOffset:this.data.byteLength;return}if(this.data=new DataView(new ArrayBuffer(0)),this.write=0,e!==null&&e!==void 0)this.putBytes(e);if("writeOffset"in t)this.write=t.writeOffset}T.DataBuffer=u0;T.DataBuffer.prototype.length=function(){return this.write-this.read};T.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};T.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var n=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),r=new Uint8Array(this.length()+t);return r.set(n),this.data=new DataView(r.buffer),this};T.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};T.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var n=0;n<t;++n)this.data.setUint8(e);return this};T.DataBuffer.prototype.putBytes=function(e,t){if(T.isArrayBufferView(e)){var n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=n.byteLength-n.byteOffset;this.accommodate(r);var i=new Uint8Array(this.data.buffer,this.write);return i.set(n),this.write+=r,this}if(T.isArrayBuffer(e)){var n=new Uint8Array(e);this.accommodate(n.byteLength);var i=new Uint8Array(this.data.buffer);return i.set(n,this.write),this.write+=n.byteLength,this}if(e instanceof T.DataBuffer||typeof e==="object"&&typeof e.read==="number"&&typeof e.write==="number"&&T.isArrayBufferView(e.data)){var n=new Uint8Array(e.data.byteLength,e.read,e.length());this.accommodate(n.byteLength);var i=new Uint8Array(e.data.byteLength,this.write);return i.set(n),this.write+=n.byteLength,this}if(e instanceof T.ByteStringBuffer)e=e.data,t="binary";if(t=t||"binary",typeof e==="string"){var a;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),a=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.hex.decode(e,a,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),a=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.base64.decode(e,a,this.write),this;if(t==="utf8")e=T.encodeUtf8(e),t="binary";if(t==="binary"||t==="raw")return this.accommodate(e.length),a=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.raw.decode(a),this;if(t==="utf16")return this.accommodate(e.length*2),a=new Uint16Array(this.data.buffer,this.write),this.write+=T.text.utf16.encode(a),this;throw Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};T.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};T.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};T.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};T.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this};T.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};T.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};T.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this};T.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};T.DataBuffer.prototype.putInt=function(e,t){hi(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};T.DataBuffer.prototype.putSignedInt=function(e,t){if(hi(t),this.accommodate(t/8),e<0)e+=2<<t-1;return this.putInt(e,t)};T.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};T.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};T.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};T.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};T.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};T.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};T.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};T.DataBuffer.prototype.getInt=function(e){hi(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};T.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};T.DataBuffer.prototype.getBytes=function(e){var t;if(e)e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e;else if(e===0)t="";else t=this.read===0?this.data:this.data.slice(this.read),this.clear();return t};T.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};T.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};T.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};T.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};T.DataBuffer.prototype.copy=function(){return new T.DataBuffer(this)};T.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this};T.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};T.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};T.DataBuffer.prototype.toHex=function(){var e="";for(var t=this.read;t<this.data.byteLength;++t){var n=this.data.getUint8(t);if(n<16)e+="0";e+=n.toString(16)}return e};T.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return T.binary.raw.encode(t);if(e==="hex")return T.binary.hex.encode(t);if(e==="base64")return T.binary.base64.encode(t);if(e==="utf8")return T.text.utf8.decode(t);if(e==="utf16")return T.text.utf16.decode(t);throw Error("Invalid encoding: "+e)};T.createBuffer=function(e,t){if(t=t||"raw",e!==void 0&&t==="utf8")e=T.encodeUtf8(e);return new T.ByteBuffer(e)};T.fillString=function(e,t){var n="";while(t>0){if(t&1)n+=e;if(t>>>=1,t>0)e+=e}return n};T.xorBytes=function(e,t,n){var r="",i="",a="",s=0,o=0;for(;n>0;--n,++s){if(i=e.charCodeAt(s)^t.charCodeAt(s),o>=10)r+=a,a="",o=0;a+=String.fromCharCode(i),++o}return r+=a,r};T.hexToBytes=function(e){var t="",n=0;if(e.length&!0)n=1,t+=String.fromCharCode(parseInt(e[0],16));for(;n<e.length;n+=2)t+=String.fromCharCode(parseInt(e.substr(n,2),16));return t};T.bytesToHex=function(e){return T.createBuffer(e).toHex()};T.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var Pr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Nr=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],Wc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";T.encode64=function(e,t){var n="",r="",i,a,s,o=0;while(o<e.length){if(i=e.charCodeAt(o++),a=e.charCodeAt(o++),s=e.charCodeAt(o++),n+=Pr.charAt(i>>2),n+=Pr.charAt((i&3)<<4|a>>4),isNaN(a))n+="==";else n+=Pr.charAt((a&15)<<2|s>>6),n+=isNaN(s)?"=":Pr.charAt(s&63);if(t&&n.length>t)r+=n.substr(0,t)+`\r
4
- `,n=n.substr(t)}return r+=n,r};T.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");var t="",n,r,i,a,s=0;while(s<e.length)if(n=Nr[e.charCodeAt(s++)-43],r=Nr[e.charCodeAt(s++)-43],i=Nr[e.charCodeAt(s++)-43],a=Nr[e.charCodeAt(s++)-43],t+=String.fromCharCode(n<<2|r>>4),i!==64){if(t+=String.fromCharCode((r&15)<<4|i>>2),a!==64)t+=String.fromCharCode((i&3)<<6|a)}return t};T.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};T.decodeUtf8=function(e){return decodeURIComponent(escape(e))};T.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Mc.encode,decode:Mc.decode}};T.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};T.binary.raw.decode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(e.length);n=n||0;var i=n;for(var a=0;a<e.length;++a)r[i++]=e.charCodeAt(a);return t?i-n:r};T.binary.hex.encode=T.bytesToHex;T.binary.hex.decode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(Math.ceil(e.length/2));n=n||0;var i=0,a=n;if(e.length&1)i=1,r[a++]=parseInt(e[0],16);for(;i<e.length;i+=2)r[a++]=parseInt(e.substr(i,2),16);return t?a-n:r};T.binary.base64.encode=function(e,t){var n="",r="",i,a,s,o=0;while(o<e.byteLength){if(i=e[o++],a=e[o++],s=e[o++],n+=Pr.charAt(i>>2),n+=Pr.charAt((i&3)<<4|a>>4),isNaN(a))n+="==";else n+=Pr.charAt((a&15)<<2|s>>6),n+=isNaN(s)?"=":Pr.charAt(s&63);if(t&&n.length>t)r+=n.substr(0,t)+`\r
5
- `,n=n.substr(t)}return r+=n,r};T.binary.base64.decode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(Math.ceil(e.length/4)*3);e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),n=n||0;var i,a,s,o,l=0,c=n;while(l<e.length)if(i=Nr[e.charCodeAt(l++)-43],a=Nr[e.charCodeAt(l++)-43],s=Nr[e.charCodeAt(l++)-43],o=Nr[e.charCodeAt(l++)-43],r[c++]=i<<2|a>>4,s!==64){if(r[c++]=(a&15)<<4|s>>2,o!==64)r[c++]=(s&3)<<6|o}return t?c-n:r.subarray(0,c)};T.binary.base58.encode=function(e,t){return T.binary.baseN.encode(e,Wc,t)};T.binary.base58.decode=function(e,t){return T.binary.baseN.decode(e,Wc,t)};T.text={utf8:{},utf16:{}};T.text.utf8.encode=function(e,t,n){e=T.encodeUtf8(e);var r=t;if(!r)r=new Uint8Array(e.length);n=n||0;var i=n;for(var a=0;a<e.length;++a)r[i++]=e.charCodeAt(a);return t?i-n:r};T.text.utf8.decode=function(e){return T.decodeUtf8(String.fromCharCode.apply(null,e))};T.text.utf16.encode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(e.length*2);var i=new Uint16Array(r.buffer);n=n||0;var a=n,s=n;for(var o=0;o<e.length;++o)i[s++]=e.charCodeAt(o),a+=2;return t?a-n:r};T.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};T.deflate=function(e,t,n){if(t=T.decode64(e.deflate(T.encode64(t)).rval),n){var r=2,i=t.charCodeAt(1);if(i&32)r=6;t=t.substring(r,t.length-4)}return t};T.inflate=function(e,t,n){var r=e.inflate(T.encode64(t)).rval;return r===null?null:T.decode64(r)};var Zs=function(e,t,n){if(!e)throw Error("WebStorage not available.");var r;if(n===null)r=e.removeItem(t);else n=T.encode64(JSON.stringify(n)),r=e.setItem(t,n);if(typeof r<"u"&&r.rval!==!0){var i=Error(r.error.message);throw i.id=r.error.id,i.name=r.error.name,i}},eo=function(e,t){if(!e)throw Error("WebStorage not available.");var n=e.getItem(t);if(e.init)if(n.rval===null){if(n.error){var r=Error(n.error.message);throw r.id=n.error.id,r.name=n.error.name,r}n=null}else n=n.rval;if(n!==null)n=JSON.parse(T.decode64(n));return n},d0=function(e,t,n,r){var i=eo(e,t);if(i===null)i={};i[n]=r,Zs(e,t,i)},f0=function(e,t,n){var r=eo(e,t);if(r!==null)r=n in r?r[n]:null;return r},p0=function(e,t,n){var r=eo(e,t);if(r!==null&&n in r){delete r[n];var i=!0;for(var a in r){i=!1;break}if(i)r=null;Zs(e,t,r)}},h0=function(e,t){Zs(e,t,null)},Sa=function(e,t,n){var r=null;if(typeof n>"u")n=["web","flash"];var i,a=!1,s=null;for(var o in n){i=n[o];try{if(i==="flash"||i==="both"){if(t[0]===null)throw Error("Flash local storage not available.");r=e.apply(this,t),a=i==="flash"}if(i==="web"||i==="both")t[0]=localStorage,r=e.apply(this,t),a=!0}catch(l){s=l}if(a)break}if(!a)throw s;return r};T.setItem=function(e,t,n,r,i){Sa(d0,arguments,i)};T.getItem=function(e,t,n,r){return Sa(f0,arguments,r)};T.removeItem=function(e,t,n,r){Sa(p0,arguments,r)};T.clearItems=function(e,t,n){Sa(h0,arguments,n)};T.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};T.format=function(e){var t=/%./g,n,r,i=0,a=[],s=0;while(n=t.exec(e)){if(r=e.substring(s,t.lastIndex-2),r.length>0)a.push(r);s=t.lastIndex;var o=n[0][1];switch(o){case"s":case"o":if(i<arguments.length)a.push(arguments[i+++1]);else a.push("<?>");break;case"%":a.push("%");break;default:a.push("<%"+o+"?>")}}return a.push(e.substring(s)),a.join("")};T.formatNumber=function(e,t,n,r){var i=e,a=isNaN(t=Math.abs(t))?2:t,s=n===void 0?",":n,o=r===void 0?".":r,l=i<0?"-":"",c=parseInt(i=Math.abs(+i||0).toFixed(a),10)+"",u=c.length>3?c.length%3:0;return l+(u?c.substr(0,u)+o:"")+c.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+o)+(a?s+Math.abs(i-c).toFixed(a).slice(2):"")};T.formatSize=function(e){if(e>=1073741824)e=T.formatNumber(e/1073741824,2,".","")+" GiB";else if(e>=1048576)e=T.formatNumber(e/1048576,2,".","")+" MiB";else if(e>=1024)e=T.formatNumber(e/1024,0)+" KiB";else e=T.formatNumber(e,0)+" bytes";return e};T.bytesFromIP=function(e){if(e.indexOf(".")!==-1)return T.bytesFromIPv4(e);if(e.indexOf(":")!==-1)return T.bytesFromIPv6(e);return null};T.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;var t=T.createBuffer();for(var n=0;n<e.length;++n){var r=parseInt(e[n],10);if(isNaN(r))return null;t.putByte(r)}return t.getBytes()};T.bytesFromIPv6=function(e){var t=0;e=e.split(":").filter(function(s){if(s.length===0)++t;return!0});var n=(8-e.length+t)*2,r=T.createBuffer();for(var i=0;i<8;++i){if(!e[i]||e[i].length===0){r.fillWithByte(0,n),n=0;continue}var a=T.hexToBytes(e[i]);if(a.length<2)r.putByte(0);r.putBytes(a)}return r.getBytes()};T.bytesToIP=function(e){if(e.length===4)return T.bytesToIPv4(e);if(e.length===16)return T.bytesToIPv6(e);return null};T.bytesToIPv4=function(e){if(e.length!==4)return null;var t=[];for(var n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t.join(".")};T.bytesToIPv6=function(e){if(e.length!==16)return null;var t=[],n=[],r=0;for(var i=0;i<e.length;i+=2){var a=T.bytesToHex(e[i]+e[i+1]);while(a[0]==="0"&&a!=="0")a=a.substr(1);if(a==="0"){var s=n[n.length-1],o=t.length;if(!s||o!==s.end+1)n.push({start:o,end:o});else if(s.end=o,s.end-s.start>n[r].end-n[r].start)r=n.length-1}t.push(a)}if(n.length>0){var l=n[r];if(l.end-l.start>0){if(t.splice(l.start,l.end-l.start+1,""),l.start===0)t.unshift("");if(l.end===7)t.push("")}}return t.join(":")};T.estimateCores=function(e,t){if(typeof e==="function")t=e,e={};if(e=e||{},"cores"in T&&!e.update)return t(null,T.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return T.cores=navigator.hardwareConcurrency,t(null,T.cores);if(typeof Worker>"u")return T.cores=1,t(null,T.cores);if(typeof Blob>"u")return T.cores=2,t(null,T.cores);var n=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(s){var o=Date.now(),l=o+4;while(Date.now()<l);self.postMessage({st:o,et:l})})}.toString(),")()"],{type:"application/javascript"}));r([],5,16);function r(s,o,l){if(o===0){var c=Math.floor(s.reduce(function(u,d){return u+d},0)/s.length);return T.cores=Math.max(1,c),URL.revokeObjectURL(n),t(null,T.cores)}i(l,function(u,d){s.push(a(l,d)),r(s,o-1,l)})}function i(s,o){var l=[],c=[];for(var u=0;u<s;++u){var d=new Worker(n);d.addEventListener("message",function(f){if(c.push(f.data),c.length===s){for(var y=0;y<s;++y)l[y].terminate();o(null,c)}}),l.push(d)}for(var u=0;u<s;++u)l[u].postMessage(u)}function a(s,o){var l=[];for(var c=0;c<s;++c){var u=o[c],d=l[c]=[];for(var f=0;f<s;++f){if(c===f)continue;var y=o[f];if(u.st>y.st&&u.st<y.et||y.st>u.st&&y.st<u.et)d.push(f)}}return l.reduce(function(p,v){return Math.max(p,v.length)},0)}}});var ba=de(function(FC,Hc){var ut=me();Pe();Hc.exports=ut.cipher=ut.cipher||{};ut.cipher.algorithms=ut.cipher.algorithms||{};ut.cipher.createCipher=function(e,t){var n=e;if(typeof n==="string"){if(n=ut.cipher.getAlgorithm(n),n)n=n()}if(!n)throw Error("Unsupported algorithm: "+e);return new ut.cipher.BlockCipher({algorithm:n,key:t,decrypt:!1})};ut.cipher.createDecipher=function(e,t){var n=e;if(typeof n==="string"){if(n=ut.cipher.getAlgorithm(n),n)n=n()}if(!n)throw Error("Unsupported algorithm: "+e);return new ut.cipher.BlockCipher({algorithm:n,key:t,decrypt:!0})};ut.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),ut.cipher.algorithms[e]=t};ut.cipher.getAlgorithm=function(e){if(e=e.toUpperCase(),e in ut.cipher.algorithms)return ut.cipher.algorithms[e];return null};var to=ut.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};to.prototype.start=function(e){e=e||{};var t={};for(var n in e)t[n]=e[n];t.decrypt=this._decrypt,this._finish=!1,this._input=ut.util.createBuffer(),this.output=e.output||ut.util.createBuffer(),this.mode.start(t)};to.prototype.update=function(e){if(e)this._input.putBuffer(e);while(!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish);this._input.compact()};to.prototype.finish=function(e){if(e&&(this.mode.name==="ECB"||this.mode.name==="CBC"))this.mode.pad=function(n){return e(this.blockSize,n,!1)},this.mode.unpad=function(n){return e(this.blockSize,n,!0)};var t={};if(t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!this._decrypt&&this.mode.pad){if(!this.mode.pad(this._input,t))return!1}if(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad){if(!this.mode.unpad(this.output,t))return!1}if(this.mode.afterFinish){if(!this.mode.afterFinish(this.output,t))return!1}return!0}});var no=de(function(MC,Kc){var dt=me();Pe();dt.cipher=dt.cipher||{};var be=Kc.exports=dt.cipher.modes=dt.cipher.modes||{};be.ecb=function(e){e=e||{},this.name="ECB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints)};be.ecb.prototype.start=function(e){};be.ecb.prototype.encrypt=function(e,t,n){if(e.length()<this.blockSize&&!(n&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r])};be.ecb.prototype.decrypt=function(e,t,n){if(e.length()<this.blockSize&&!(n&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r])};be.ecb.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};be.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var n=e.length(),r=e.at(n-1);if(r>this.blockSize<<2)return!1;return e.truncate(r),!0};be.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints)};be.cbc.prototype.start=function(e){if(e.iv===null){if(!this._prev)throw Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if(!("iv"in e))throw Error("Invalid IV parameter.");else this._iv=Ca(e.iv,this.blockSize),this._prev=this._iv.slice(0)};be.cbc.prototype.encrypt=function(e,t,n){if(e.length()<this.blockSize&&!(n&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=this._prev[r]^e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r]);this._prev=this._outBlock};be.cbc.prototype.decrypt=function(e,t,n){if(e.length()<this.blockSize&&!(n&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._prev[r]^this._outBlock[r]);this._prev=this._inBlock.slice(0)};be.cbc.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};be.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var n=e.length(),r=e.at(n-1);if(r>this.blockSize<<2)return!1;return e.truncate(r),!0};be.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0};be.cfb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Ca(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};be.cfb.prototype.encrypt=function(e,t,n){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var i=0;i<this._ints;++i)this._inBlock[i]=e.getInt32()^this._outBlock[i],t.putInt32(this._inBlock[i]);return}var a=(this.blockSize-r)%this.blockSize;if(a>0)a=this.blockSize-a;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialBlock[i]=e.getInt32()^this._outBlock[i],this._partialOutput.putInt32(this._partialBlock[i]);if(a>0)e.read-=this.blockSize;else for(var i=0;i<this._ints;++i)this._inBlock[i]=this._partialBlock[i];if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(a>0&&!n)return t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};be.cfb.prototype.decrypt=function(e,t,n){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var i=0;i<this._ints;++i)this._inBlock[i]=e.getInt32(),t.putInt32(this._inBlock[i]^this._outBlock[i]);return}var a=(this.blockSize-r)%this.blockSize;if(a>0)a=this.blockSize-a;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialBlock[i]=e.getInt32(),this._partialOutput.putInt32(this._partialBlock[i]^this._outBlock[i]);if(a>0)e.read-=this.blockSize;else for(var i=0;i<this._ints;++i)this._inBlock[i]=this._partialBlock[i];if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(a>0&&!n)return t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};be.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0};be.ofb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Ca(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};be.ofb.prototype.encrypt=function(e,t,n){var r=e.length();if(e.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var i=0;i<this._ints;++i)t.putInt32(e.getInt32()^this._outBlock[i]),this._inBlock[i]=this._outBlock[i];return}var a=(this.blockSize-r)%this.blockSize;if(a>0)a=this.blockSize-a;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(a>0)e.read-=this.blockSize;else for(var i=0;i<this._ints;++i)this._inBlock[i]=this._outBlock[i];if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(a>0&&!n)return t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};be.ofb.prototype.decrypt=be.ofb.prototype.encrypt;be.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0};be.ctr.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Ca(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};be.ctr.prototype.encrypt=function(e,t,n){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize)for(var i=0;i<this._ints;++i)t.putInt32(e.getInt32()^this._outBlock[i]);else{var a=(this.blockSize-r)%this.blockSize;if(a>0)a=this.blockSize-a;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(a>0)e.read-=this.blockSize;if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(a>0&&!n)return t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}Ea(this._inBlock)};be.ctr.prototype.decrypt=be.ctr.prototype.encrypt;be.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0,this._R=3774873600};be.gcm.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");var t=dt.util.createBuffer(e.iv);this._cipherLength=0;var n;if("additionalData"in e)n=dt.util.createBuffer(e.additionalData);else n=dt.util.createBuffer();if("tagLength"in e)this._tagLength=e.tagLength;else this._tagLength=128;if(this._tag=null,e.decrypt){if(this._tag=dt.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8)throw Error("Authentication tag does not match tag length.")}this._hashBlock=Array(this._ints),this.tag=null,this._hashSubkey=Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var r=t.length();if(r===12)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{this._j0=[0,0,0,0];while(t.length()>0)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(ro(r*8)))}this._inBlock=this._j0.slice(0),Ea(this._inBlock),this._partialBytes=0,n=dt.util.createBuffer(n),this._aDataLength=ro(n.length()*8);var i=n.length()%this.blockSize;if(i)n.fillWithByte(0,this.blockSize-i);this._s=[0,0,0,0];while(n.length()>0)this._s=this.ghash(this._hashSubkey,this._s,[n.getInt32(),n.getInt32(),n.getInt32(),n.getInt32()])};be.gcm.prototype.encrypt=function(e,t,n){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var i=0;i<this._ints;++i)t.putInt32(this._outBlock[i]^=e.getInt32());this._cipherLength+=this.blockSize}else{var a=(this.blockSize-r)%this.blockSize;if(a>0)a=this.blockSize-a;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(a<=0||n){if(n){var s=r%this.blockSize;this._cipherLength+=s,this._partialOutput.truncate(this.blockSize-s)}else this._cipherLength+=this.blockSize;for(var i=0;i<this._ints;++i)this._outBlock[i]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(a>0&&!n)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),Ea(this._inBlock)};be.gcm.prototype.decrypt=function(e,t,n){var r=e.length();if(r<this.blockSize&&!(n&&r>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),Ea(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i<this._ints;++i)t.putInt32(this._outBlock[i]^this._hashBlock[i]);if(r<this.blockSize)this._cipherLength+=r%this.blockSize;else this._cipherLength+=this.blockSize};be.gcm.prototype.afterFinish=function(e,t){var n=!0;if(t.decrypt&&t.overflow)e.truncate(this.blockSize-t.overflow);this.tag=dt.util.createBuffer();var r=this._aDataLength.concat(ro(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,r);var i=[];this.cipher.encrypt(this._j0,i);for(var a=0;a<this._ints;++a)this.tag.putInt32(this._s[a]^i[a]);if(this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag)n=!1;return n};be.gcm.prototype.multiply=function(e,t){var n=[0,0,0,0],r=t.slice(0);for(var i=0;i<128;++i){var a=e[i/32|0]&1<<31-i%32;if(a)n[0]^=r[0],n[1]^=r[1],n[2]^=r[2],n[3]^=r[3];this.pow(r,r)}return n};be.gcm.prototype.pow=function(e,t){var n=e[3]&1;for(var r=3;r>0;--r)t[r]=e[r]>>>1|(e[r-1]&1)<<31;if(t[0]=e[0]>>>1,n)t[0]^=this._R};be.gcm.prototype.tableMultiply=function(e){var t=[0,0,0,0];for(var n=0;n<32;++n){var r=n/8|0,i=e[r]>>>(7-n%8)*4&15,a=this._m[n][i];t[0]^=a[0],t[1]^=a[1],t[2]^=a[2],t[3]^=a[3]}return t};be.gcm.prototype.ghash=function(e,t,n){return t[0]^=n[0],t[1]^=n[1],t[2]^=n[2],t[3]^=n[3],this.tableMultiply(t)};be.gcm.prototype.generateHashTable=function(e,t){var n=8/t,r=4*n,i=16*n,a=Array(i);for(var s=0;s<i;++s){var o=[0,0,0,0],l=s/r|0,c=(r-1-s%r)*t;o[l]=1<<t-1<<c,a[s]=this.generateSubHashTable(this.multiply(o,e),t)}return a};be.gcm.prototype.generateSubHashTable=function(e,t){var n=1<<t,r=n>>>1,i=Array(n);i[r]=e.slice(0);var a=r>>>1;while(a>0)this.pow(i[2*a],i[a]=[]),a>>=1;a=2;while(a<r){for(var s=1;s<a;++s){var o=i[a],l=i[s];i[a+s]=[o[0]^l[0],o[1]^l[1],o[2]^l[2],o[3]^l[3]]}a*=2}i[0]=[0,0,0,0];for(a=r+1;a<n;++a){var c=i[a^r];i[a]=[e[0]^c[0],e[1]^c[1],e[2]^c[2],e[3]^c[3]]}return i};function Ca(e,t){if(typeof e==="string")e=dt.util.createBuffer(e);if(dt.util.isArray(e)&&e.length>4){var n=e;e=dt.util.createBuffer();for(var r=0;r<n.length;++r)e.putByte(n[r])}if(e.length()<t)throw Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!dt.util.isArray(e)){var i=[],a=t/4;for(var r=0;r<a;++r)i.push(e.getInt32());e=i}return e}function Ea(e){e[e.length-1]=e[e.length-1]+1&4294967295}function ro(e){return[e/4294967296|0,e&4294967295]}});var Dr=de(function(WC,zc){var $e=me();ba();no();Pe();zc.exports=$e.aes=$e.aes||{};$e.aes.startEncrypting=function(e,t,n,r){var i=wa({key:e,output:n,decrypt:!1,mode:r});return i.start(t),i};$e.aes.createEncryptionCipher=function(e,t){return wa({key:e,output:null,decrypt:!1,mode:t})};$e.aes.startDecrypting=function(e,t,n,r){var i=wa({key:e,output:n,decrypt:!0,mode:r});return i.start(t),i};$e.aes.createDecryptionCipher=function(e,t){return wa({key:e,output:null,decrypt:!0,mode:t})};$e.aes.Algorithm=function(e,t){if(!so)Gc();var n=this;n.name=e,n.mode=new t({blockSize:16,cipher:{encrypt:function(r,i){return ao(n._w,r,i,!1)},decrypt:function(r,i){return ao(n._w,r,i,!0)}}}),n._init=!1};$e.aes.Algorithm.prototype.initialize=function(e){if(this._init)return;var t=e.key,n;if(typeof t==="string"&&(t.length===16||t.length===24||t.length===32))t=$e.util.createBuffer(t);else if($e.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){n=t,t=$e.util.createBuffer();for(var r=0;r<n.length;++r)t.putByte(n[r])}if(!$e.util.isArray(t)){n=t,t=[];var i=n.length();if(i===16||i===24||i===32){i=i>>>2;for(var r=0;r<i;++r)t.push(n.getInt32())}}if(!$e.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw Error("Invalid key parameter.");var a=this.mode.name,s=["CFB","OFB","CTR","GCM"].indexOf(a)!==-1;this._w=jc(t,e.decrypt&&!s),this._init=!0};$e.aes._expandKey=function(e,t){if(!so)Gc();return jc(e,t)};$e.aes._updateBlock=ao;Tn("AES-ECB",$e.cipher.modes.ecb);Tn("AES-CBC",$e.cipher.modes.cbc);Tn("AES-CFB",$e.cipher.modes.cfb);Tn("AES-OFB",$e.cipher.modes.ofb);Tn("AES-CTR",$e.cipher.modes.ctr);Tn("AES-GCM",$e.cipher.modes.gcm);function Tn(e,t){var n=function(){return new $e.aes.Algorithm(e,t)};$e.cipher.registerAlgorithm(e,n)}var so=!1,wn=4,St,io,qc,nn,Kt;function Gc(){so=!0,qc=[0,1,2,4,8,16,32,64,128,27,54];var e=Array(256);for(var t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;St=Array(256),io=Array(256),nn=[,,,,],Kt=[,,,,];for(var t=0;t<4;++t)nn[t]=Array(256),Kt[t]=Array(256);var n=0,r=0,i,a,s,o,l,c,u;for(var t=0;t<256;++t){o=r^r<<1^r<<2^r<<3^r<<4,o=o>>8^o&255^99,St[n]=o,io[o]=n,l=e[o],i=e[n],a=e[i],s=e[a],c=l<<24^o<<16^o<<8^(o^l),u=(i^a^s)<<24^(n^s)<<16^(n^a^s)<<8^(n^i^s);for(var d=0;d<4;++d)nn[d][n]=c,Kt[d][o]=u,c=c<<24|c>>>8,u=u<<24|u>>>8;if(n===0)n=r=1;else n=i^e[e[e[i^s]]],r^=e[e[r]]}}function jc(e,t){var n=e.slice(0),r,i=1,a=n.length,s=a+6+1,o=wn*s;for(var l=a;l<o;++l){if(r=n[l-1],l%a===0)r=St[r>>>16&255]<<24^St[r>>>8&255]<<16^St[r&255]<<8^St[r>>>24]^qc[i]<<24,i++;else if(a>6&&l%a===4)r=St[r>>>24]<<24^St[r>>>16&255]<<16^St[r>>>8&255]<<8^St[r&255];n[l]=n[l-a]^r}if(t){var c,u=Kt[0],d=Kt[1],f=Kt[2],y=Kt[3],p=n.slice(0);o=n.length;for(var l=0,v=o-wn;l<o;l+=wn,v-=wn)if(l===0||l===o-wn)p[l]=n[v],p[l+1]=n[v+3],p[l+2]=n[v+2],p[l+3]=n[v+1];else for(var x=0;x<wn;++x)c=n[v+x],p[l+(3&-x)]=u[St[c>>>24]]^d[St[c>>>16&255]]^f[St[c>>>8&255]]^y[St[c&255]];n=p}return n}function ao(e,t,n,r){var i=e.length/4-1,a,s,o,l,c;if(r)a=Kt[0],s=Kt[1],o=Kt[2],l=Kt[3],c=io;else a=nn[0],s=nn[1],o=nn[2],l=nn[3],c=St;var u,d,f,y,p,v,x;u=t[0]^e[0],d=t[r?3:1]^e[1],f=t[2]^e[2],y=t[r?1:3]^e[3];var b=3;for(var A=1;A<i;++A)p=a[u>>>24]^s[d>>>16&255]^o[f>>>8&255]^l[y&255]^e[++b],v=a[d>>>24]^s[f>>>16&255]^o[y>>>8&255]^l[u&255]^e[++b],x=a[f>>>24]^s[y>>>16&255]^o[u>>>8&255]^l[d&255]^e[++b],y=a[y>>>24]^s[u>>>16&255]^o[d>>>8&255]^l[f&255]^e[++b],u=p,d=v,f=x;n[0]=c[u>>>24]<<24^c[d>>>16&255]<<16^c[f>>>8&255]<<8^c[y&255]^e[++b],n[r?3:1]=c[d>>>24]<<24^c[f>>>16&255]<<16^c[y>>>8&255]<<8^c[u&255]^e[++b],n[2]=c[f>>>24]<<24^c[y>>>16&255]<<16^c[u>>>8&255]<<8^c[d&255]^e[++b],n[r?1:3]=c[y>>>24]<<24^c[u>>>16&255]<<16^c[d>>>8&255]<<8^c[f&255]^e[++b]}function wa(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="AES-"+t,r;if(e.decrypt)r=$e.cipher.createDecipher(n,e.key);else r=$e.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(a,s){var o=null;if(s instanceof $e.util.ByteBuffer)o=s,s={};s=s||{},s.output=o,s.iv=a,i.call(r,s)},r}});var Lr=de(function($C,Qc){var gi=me();gi.pki=gi.pki||{};var oo=Qc.exports=gi.pki.oids=gi.oids=gi.oids||{};function U(e,t){oo[e]=t,oo[t]=e}function Le(e,t){oo[e]=t}U("1.2.840.113549.1.1.1","rsaEncryption");U("1.2.840.113549.1.1.4","md5WithRSAEncryption");U("1.2.840.113549.1.1.5","sha1WithRSAEncryption");U("1.2.840.113549.1.1.7","RSAES-OAEP");U("1.2.840.113549.1.1.8","mgf1");U("1.2.840.113549.1.1.9","pSpecified");U("1.2.840.113549.1.1.10","RSASSA-PSS");U("1.2.840.113549.1.1.11","sha256WithRSAEncryption");U("1.2.840.113549.1.1.12","sha384WithRSAEncryption");U("1.2.840.113549.1.1.13","sha512WithRSAEncryption");U("1.3.101.112","EdDSA25519");U("1.2.840.10040.4.3","dsa-with-sha1");U("1.3.14.3.2.7","desCBC");U("1.3.14.3.2.26","sha1");U("1.3.14.3.2.29","sha1WithRSASignature");U("2.16.840.1.101.3.4.2.1","sha256");U("2.16.840.1.101.3.4.2.2","sha384");U("2.16.840.1.101.3.4.2.3","sha512");U("2.16.840.1.101.3.4.2.4","sha224");U("2.16.840.1.101.3.4.2.5","sha512-224");U("2.16.840.1.101.3.4.2.6","sha512-256");U("1.2.840.113549.2.2","md2");U("1.2.840.113549.2.5","md5");U("1.2.840.113549.1.7.1","data");U("1.2.840.113549.1.7.2","signedData");U("1.2.840.113549.1.7.3","envelopedData");U("1.2.840.113549.1.7.4","signedAndEnvelopedData");U("1.2.840.113549.1.7.5","digestedData");U("1.2.840.113549.1.7.6","encryptedData");U("1.2.840.113549.1.9.1","emailAddress");U("1.2.840.113549.1.9.2","unstructuredName");U("1.2.840.113549.1.9.3","contentType");U("1.2.840.113549.1.9.4","messageDigest");U("1.2.840.113549.1.9.5","signingTime");U("1.2.840.113549.1.9.6","counterSignature");U("1.2.840.113549.1.9.7","challengePassword");U("1.2.840.113549.1.9.8","unstructuredAddress");U("1.2.840.113549.1.9.14","extensionRequest");U("1.2.840.113549.1.9.20","friendlyName");U("1.2.840.113549.1.9.21","localKeyId");U("1.2.840.113549.1.9.22.1","x509Certificate");U("1.2.840.113549.1.12.10.1.1","keyBag");U("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");U("1.2.840.113549.1.12.10.1.3","certBag");U("1.2.840.113549.1.12.10.1.4","crlBag");U("1.2.840.113549.1.12.10.1.5","secretBag");U("1.2.840.113549.1.12.10.1.6","safeContentsBag");U("1.2.840.113549.1.5.13","pkcs5PBES2");U("1.2.840.113549.1.5.12","pkcs5PBKDF2");U("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");U("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");U("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");U("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");U("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");U("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");U("1.2.840.113549.2.7","hmacWithSHA1");U("1.2.840.113549.2.8","hmacWithSHA224");U("1.2.840.113549.2.9","hmacWithSHA256");U("1.2.840.113549.2.10","hmacWithSHA384");U("1.2.840.113549.2.11","hmacWithSHA512");U("1.2.840.113549.3.7","des-EDE3-CBC");U("2.16.840.1.101.3.4.1.2","aes128-CBC");U("2.16.840.1.101.3.4.1.22","aes192-CBC");U("2.16.840.1.101.3.4.1.42","aes256-CBC");U("2.5.4.3","commonName");U("2.5.4.4","surname");U("2.5.4.5","serialNumber");U("2.5.4.6","countryName");U("2.5.4.7","localityName");U("2.5.4.8","stateOrProvinceName");U("2.5.4.9","streetAddress");U("2.5.4.10","organizationName");U("2.5.4.11","organizationalUnitName");U("2.5.4.12","title");U("2.5.4.13","description");U("2.5.4.15","businessCategory");U("2.5.4.17","postalCode");U("2.5.4.42","givenName");U("2.5.4.65","pseudonym");U("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");U("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");U("2.16.840.1.113730.1.1","nsCertType");U("2.16.840.1.113730.1.13","nsComment");Le("2.5.29.1","authorityKeyIdentifier");Le("2.5.29.2","keyAttributes");Le("2.5.29.3","certificatePolicies");Le("2.5.29.4","keyUsageRestriction");Le("2.5.29.5","policyMapping");Le("2.5.29.6","subtreesConstraint");Le("2.5.29.7","subjectAltName");Le("2.5.29.8","issuerAltName");Le("2.5.29.9","subjectDirectoryAttributes");Le("2.5.29.10","basicConstraints");Le("2.5.29.11","nameConstraints");Le("2.5.29.12","policyConstraints");Le("2.5.29.13","basicConstraints");U("2.5.29.14","subjectKeyIdentifier");U("2.5.29.15","keyUsage");Le("2.5.29.16","privateKeyUsagePeriod");U("2.5.29.17","subjectAltName");U("2.5.29.18","issuerAltName");U("2.5.29.19","basicConstraints");Le("2.5.29.20","cRLNumber");Le("2.5.29.21","cRLReason");Le("2.5.29.22","expirationDate");Le("2.5.29.23","instructionCode");Le("2.5.29.24","invalidityDate");Le("2.5.29.25","cRLDistributionPoints");Le("2.5.29.26","issuingDistributionPoint");Le("2.5.29.27","deltaCRLIndicator");Le("2.5.29.28","issuingDistributionPoint");Le("2.5.29.29","certificateIssuer");Le("2.5.29.30","nameConstraints");U("2.5.29.31","cRLDistributionPoints");U("2.5.29.32","certificatePolicies");Le("2.5.29.33","policyMappings");Le("2.5.29.34","policyConstraints");U("2.5.29.35","authorityKeyIdentifier");Le("2.5.29.36","policyConstraints");U("2.5.29.37","extKeyUsage");Le("2.5.29.46","freshestCRL");Le("2.5.29.54","inhibitAnyPolicy");U("1.3.6.1.4.1.11129.2.4.2","timestampList");U("1.3.6.1.5.5.7.1.1","authorityInfoAccess");U("1.3.6.1.5.5.7.3.1","serverAuth");U("1.3.6.1.5.5.7.3.2","clientAuth");U("1.3.6.1.5.5.7.3.3","codeSigning");U("1.3.6.1.5.5.7.3.4","emailProtection");U("1.3.6.1.5.5.7.3.8","timeStamping")});var qt=de(function(HC,Yc){var Ke=me();Pe();Lr();var H=Yc.exports=Ke.asn1=Ke.asn1||{};H.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};H.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};H.maxDepth=256;H.create=function(e,t,n,r,i){if(Ke.util.isArray(r)){var a=[];for(var s=0;s<r.length;++s)if(r[s]!==void 0)a.push(r[s]);r=a}var o={tagClass:e,type:t,constructed:n,composed:n||Ke.util.isArray(r),value:r};if(i&&"bitStringContents"in i)o.bitStringContents=i.bitStringContents,o.original=H.copy(o);return o};H.copy=function(e,t){var n;if(Ke.util.isArray(e)){n=[];for(var r=0;r<e.length;++r)n.push(H.copy(e[r],t));return n}if(typeof e==="string")return e;if(n={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:H.copy(e.value,t)},t&&!t.excludeBitStringContents)n.bitStringContents=e.bitStringContents;return n};H.equals=function(e,t,n){if(Ke.util.isArray(e)){if(!Ke.util.isArray(t))return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;++r)if(!H.equals(e[r],t[r]))return!1;return!0}if(typeof e!==typeof t)return!1;if(typeof e==="string")return e===t;var i=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&H.equals(e.value,t.value);if(n&&n.includeBitStringContents)i=i&&e.bitStringContents===t.bitStringContents;return i};H.getBerValueLength=function(e){var t=e.getByte();if(t===128)return;var n,r=t&128;if(!r)n=t;else n=e.getInt((t&127)<<3);return n};function mi(e,t,n){if(n>t){var r=Error("Too few bytes to parse DER.");throw r.available=e.length(),r.remaining=t,r.requested=n,r}}var g0=function(e,t){var n=e.getByte();if(t--,n===128)return;var r,i=n&128;if(!i)r=n;else{var a=n&127;mi(e,t,a),r=e.getInt(a<<3)}if(r<0)throw Error("Negative length: "+r);return r};H.fromDer=function(e,t){if(t===void 0)t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0};if(typeof t==="boolean")t={strict:t,parseAllBytes:!0,decodeBitStrings:!0};if(!("strict"in t))t.strict=!0;if(!("parseAllBytes"in t))t.parseAllBytes=!0;if(!("decodeBitStrings"in t))t.decodeBitStrings=!0;if(!("maxDepth"in t))t.maxDepth=H.maxDepth;if(typeof e==="string")e=Ke.util.createBuffer(e);var n=e.length(),r=Ta(e,e.length(),0,t);if(t.parseAllBytes&&e.length()!==0){var i=Error("Unparsed DER bytes remain after ASN.1 parsing.");throw i.byteCount=n,i.remaining=e.length(),i}return r};function Ta(e,t,n,r){if(n>=r.maxDepth)throw Error("ASN.1 parsing error: Max depth exceeded.");var i;mi(e,t,2);var a=e.getByte();t--;var s=a&192,o=a&31;i=e.length();var l=g0(e,t);if(t-=i-e.length(),l!==void 0&&l>t){if(r.strict){var c=Error("Too few bytes to read ASN.1 value.");throw c.available=e.length(),c.remaining=t,c.requested=l,c}l=t}var u,d,f=(a&32)===32;if(f)if(u=[],l===void 0)for(;;){if(mi(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}i=e.length(),u.push(Ta(e,t,n+1,r)),t-=i-e.length()}else while(l>0)i=e.length(),u.push(Ta(e,l,n+1,r)),t-=i-e.length(),l-=i-e.length();if(u===void 0&&s===H.Class.UNIVERSAL&&o===H.Type.BITSTRING)d=e.bytes(l);if(u===void 0&&r.decodeBitStrings&&s===H.Class.UNIVERSAL&&o===H.Type.BITSTRING&&l>1){var y=e.read,p=t,v=0;if(o===H.Type.BITSTRING)mi(e,t,1),v=e.getByte(),t--;if(v===0)try{i=e.length();var x={strict:!0,decodeBitStrings:!0},b=Ta(e,t,n+1,x),A=i-e.length();if(t-=A,o==H.Type.BITSTRING)A++;var E=b.tagClass;if(A===l&&(E===H.Class.UNIVERSAL||E===H.Class.CONTEXT_SPECIFIC))u=[b]}catch(I){}if(u===void 0)e.read=y,t=p}if(u===void 0){if(l===void 0){if(r.strict)throw Error("Non-constructed ASN.1 object of indefinite length.");l=t}if(o===H.Type.BMPSTRING){u="";for(;l>0;l-=2)mi(e,t,2),u+=String.fromCharCode(e.getInt16()),t-=2}else u=e.getBytes(l),t-=l}var k=d===void 0?null:{bitStringContents:d};return H.create(s,o,f,u,k)}H.toDer=function(e){var t=Ke.util.createBuffer(),n=e.tagClass|e.type,r=Ke.util.createBuffer(),i=!1;if("bitStringContents"in e){if(i=!0,e.original)i=H.equals(e,e.original)}if(i)r.putBytes(e.bitStringContents);else if(e.composed){if(e.constructed)n|=32;else r.putByte(0);for(var a=0;a<e.value.length;++a)if(e.value[a]!==void 0)r.putBuffer(H.toDer(e.value[a]))}else if(e.type===H.Type.BMPSTRING)for(var a=0;a<e.value.length;++a)r.putInt16(e.value.charCodeAt(a));else if(e.type===H.Type.INTEGER&&e.value.length>1&&(e.value.charCodeAt(0)===0&&(e.value.charCodeAt(1)&128)===0||e.value.charCodeAt(0)===255&&(e.value.charCodeAt(1)&128)===128))r.putBytes(e.value.substr(1));else r.putBytes(e.value);if(t.putByte(n),r.length()<=127)t.putByte(r.length()&127);else{var s=r.length(),o="";do o+=String.fromCharCode(s&255),s=s>>>8;while(s>0);t.putByte(o.length|128);for(var a=o.length-1;a>=0;--a)t.putByte(o.charCodeAt(a))}return t.putBuffer(r),t};H.oidToDer=function(e){var t=e.split("."),n=Ke.util.createBuffer();n.putByte(40*parseInt(t[0],10)+parseInt(t[1],10));var r,i,a,s;for(var o=2;o<t.length;++o){if(r=!0,i=[],a=parseInt(t[o],10),a>4294967295)throw Error("OID value too large; max is 32-bits.");do{if(s=a&127,a=a>>>7,!r)s|=128;i.push(s),r=!1}while(a>0);for(var l=i.length-1;l>=0;--l)n.putByte(i[l])}return n};H.derToOid=function(e){var t;if(typeof e==="string")e=Ke.util.createBuffer(e);var n=e.getByte();t=Math.floor(n/40)+"."+n%40;var r=0;while(e.length()>0){if(r>70368744177663)throw Error("OID value too large; max is 53-bits.");if(n=e.getByte(),r=r*128,n&128)r+=n&127;else t+="."+(r+n),r=0}return t};H.utcTimeToDate=function(e){var t=new Date,n=parseInt(e.substr(0,2),10);n=n>=50?1900+n:2000+n;var r=parseInt(e.substr(2,2),10)-1,i=parseInt(e.substr(4,2),10),a=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var l=e.charAt(10),c=10;if(l!=="+"&&l!=="-")o=parseInt(e.substr(10,2),10),c+=2}if(t.setUTCFullYear(n,r,i),t.setUTCHours(a,s,o,0),c){if(l=e.charAt(c),l==="+"||l==="-"){var u=parseInt(e.substr(c+1,2),10),d=parseInt(e.substr(c+4,2),10),f=u*60+d;if(f*=60000,l==="+")t.setTime(+t-f);else t.setTime(+t+f)}}return t};H.generalizedTimeToDate=function(e){var t=new Date,n=parseInt(e.substr(0,4),10),r=parseInt(e.substr(4,2),10)-1,i=parseInt(e.substr(6,2),10),a=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),l=0,c=0,u=!1;if(e.charAt(e.length-1)==="Z")u=!0;var d=e.length-5,f=e.charAt(d);if(f==="+"||f==="-"){var y=parseInt(e.substr(d+1,2),10),p=parseInt(e.substr(d+4,2),10);if(c=y*60+p,c*=60000,f==="+")c*=-1;u=!0}if(e.charAt(14)===".")l=parseFloat(e.substr(14),10)*1000;if(u)t.setUTCFullYear(n,r,i),t.setUTCHours(a,s,o,l),t.setTime(+t+c);else t.setFullYear(n,r,i),t.setHours(a,s,o,l);return t};H.dateToUtcTime=function(e){if(typeof e==="string")return e;var t="",n=[];n.push((""+e.getUTCFullYear()).substr(2)),n.push(""+(e.getUTCMonth()+1)),n.push(""+e.getUTCDate()),n.push(""+e.getUTCHours()),n.push(""+e.getUTCMinutes()),n.push(""+e.getUTCSeconds());for(var r=0;r<n.length;++r){if(n[r].length<2)t+="0";t+=n[r]}return t+="Z",t};H.dateToGeneralizedTime=function(e){if(typeof e==="string")return e;var t="",n=[];n.push(""+e.getUTCFullYear()),n.push(""+(e.getUTCMonth()+1)),n.push(""+e.getUTCDate()),n.push(""+e.getUTCHours()),n.push(""+e.getUTCMinutes()),n.push(""+e.getUTCSeconds());for(var r=0;r<n.length;++r){if(n[r].length<2)t+="0";t+=n[r]}return t+="Z",t};H.integerToDer=function(e){var t=Ke.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var n=Error("Integer too large; max is 32-bits.");throw n.integer=e,n};H.derToInteger=function(e){if(typeof e==="string")e=Ke.util.createBuffer(e);var t=e.length()*8;if(t>32)throw Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};H.validate=function(e,t,n,r){var i=!1;if((e.tagClass===t.tagClass||typeof t.tagClass>"u")&&(e.type===t.type||typeof t.type>"u")){if(e.constructed===t.constructed||typeof t.constructed>"u"){if(i=!0,t.value&&Ke.util.isArray(t.value)){var a=0;for(var s=0;i&&s<t.value.length;++s){var o=t.value[s];i=!!o.optional;var l=e.value[a];if(!l){if(!o.optional){if(i=!1,r)r.push("["+t.name+'] Missing required element. Expected tag class "'+o.tagClass+'", type "'+o.type+'"')}continue}var c=typeof o.tagClass<"u"&&typeof o.type<"u";if(c&&(l.tagClass!==o.tagClass||l.type!==o.type))if(o.optional){i=!0;continue}else{if(i=!1,r)r.push("["+t.name+"] Tag mismatch. Expected ("+o.tagClass+","+o.type+"), got ("+l.tagClass+","+l.type+")");break}var u=H.validate(l,o,n,r);if(u)++a,i=!0;else if(o.optional)i=!0;else{i=!1;break}}}if(i&&n){if(t.capture)n[t.capture]=e.value;if(t.captureAsn1)n[t.captureAsn1]=e;if(t.captureBitStringContents&&"bitStringContents"in e)n[t.captureBitStringContents]=e.bitStringContents;if(t.captureBitStringValue&&"bitStringContents"in e){var d;if(e.bitStringContents.length<2)n[t.captureBitStringValue]="";else{var f=e.bitStringContents.charCodeAt(0);if(f!==0)throw Error("captureBitStringValue only supported for zero unused bits");n[t.captureBitStringValue]=e.bitStringContents.slice(1)}}}}else if(r)r.push("["+t.name+'] Expected constructed "'+t.constructed+'", got "'+e.constructed+'"')}else if(r){if(e.tagClass!==t.tagClass)r.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"');if(e.type!==t.type)r.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"')}return i};var Xc=/[^\\u0000-\\u00ff]/;H.prettyPrint=function(e,t,n){var r="";if(t=t||0,n=n||2,t>0)r+=`
6
- `;var i="";for(var a=0;a<t*n;++a)i+=" ";switch(r+=i+"Tag: ",e.tagClass){case H.Class.UNIVERSAL:r+="Universal:";break;case H.Class.APPLICATION:r+="Application:";break;case H.Class.CONTEXT_SPECIFIC:r+="Context-Specific:";break;case H.Class.PRIVATE:r+="Private:";break}if(e.tagClass===H.Class.UNIVERSAL)switch(r+=e.type,e.type){case H.Type.NONE:r+=" (None)";break;case H.Type.BOOLEAN:r+=" (Boolean)";break;case H.Type.INTEGER:r+=" (Integer)";break;case H.Type.BITSTRING:r+=" (Bit string)";break;case H.Type.OCTETSTRING:r+=" (Octet string)";break;case H.Type.NULL:r+=" (Null)";break;case H.Type.OID:r+=" (Object Identifier)";break;case H.Type.ODESC:r+=" (Object Descriptor)";break;case H.Type.EXTERNAL:r+=" (External or Instance of)";break;case H.Type.REAL:r+=" (Real)";break;case H.Type.ENUMERATED:r+=" (Enumerated)";break;case H.Type.EMBEDDED:r+=" (Embedded PDV)";break;case H.Type.UTF8:r+=" (UTF8)";break;case H.Type.ROID:r+=" (Relative Object Identifier)";break;case H.Type.SEQUENCE:r+=" (Sequence)";break;case H.Type.SET:r+=" (Set)";break;case H.Type.PRINTABLESTRING:r+=" (Printable String)";break;case H.Type.IA5String:r+=" (IA5String (ASCII))";break;case H.Type.UTCTIME:r+=" (UTC time)";break;case H.Type.GENERALIZEDTIME:r+=" (Generalized time)";break;case H.Type.BMPSTRING:r+=" (BMP String)";break}else r+=e.type;if(r+=`
7
- `,r+=i+"Constructed: "+e.constructed+`
8
- `,e.composed){var s=0,o="";for(var a=0;a<e.value.length;++a)if(e.value[a]!==void 0){if(s+=1,o+=H.prettyPrint(e.value[a],t+1,n),a+1<e.value.length)o+=","}r+=i+"Sub values: "+s+o}else{if(r+=i+"Value: ",e.type===H.Type.OID){var l=H.derToOid(e.value);if(r+=l,Ke.pki&&Ke.pki.oids){if(l in Ke.pki.oids)r+=" ("+Ke.pki.oids[l]+") "}}if(e.type===H.Type.INTEGER)try{r+=H.derToInteger(e.value)}catch(u){r+="0x"+Ke.util.bytesToHex(e.value)}else if(e.type===H.Type.BITSTRING){if(e.value.length>1)r+="0x"+Ke.util.bytesToHex(e.value.slice(1));else r+="(none)";if(e.value.length>0){var c=e.value.charCodeAt(0);if(c==1)r+=" (1 unused bit shown)";else if(c>1)r+=" ("+c+" unused bits shown)"}}else if(e.type===H.Type.OCTETSTRING){if(!Xc.test(e.value))r+="("+e.value+") ";r+="0x"+Ke.util.bytesToHex(e.value)}else if(e.type===H.Type.UTF8)try{r+=Ke.util.decodeUtf8(e.value)}catch(u){if(u.message==="URI malformed")r+="0x"+Ke.util.bytesToHex(e.value)+" (malformed UTF8)";else throw u}else if(e.type===H.Type.PRINTABLESTRING||e.type===H.Type.IA5String)r+=e.value;else if(Xc.test(e.value))r+="0x"+Ke.util.bytesToHex(e.value);else if(e.value.length===0)r+="[null]";else r+=e.value}return r}});var tr=de(function(KC,Jc){var Aa=me();Jc.exports=Aa.md=Aa.md||{};Aa.md.algorithms=Aa.md.algorithms||{}});var An=de(function(qC,Zc){var vr=me();tr();Pe();var m0=Zc.exports=vr.hmac=vr.hmac||{};m0.create=function(){var e=null,t=null,n=null,r=null,i={};return i.start=function(a,s){if(a!==null)if(typeof a==="string")if(a=a.toLowerCase(),a in vr.md.algorithms)t=vr.md.algorithms[a].create();else throw Error('Unknown hash algorithm "'+a+'"');else t=a;if(s===null)s=e;else{if(typeof s==="string")s=vr.util.createBuffer(s);else if(vr.util.isArray(s)){var o=s;s=vr.util.createBuffer();for(var l=0;l<o.length;++l)s.putByte(o[l])}var c=s.length();if(c>t.blockLength)t.start(),t.update(s.bytes()),s=t.digest();n=vr.util.createBuffer(),r=vr.util.createBuffer(),c=s.length();for(var l=0;l<c;++l){var o=s.at(l);n.putByte(54^o),r.putByte(92^o)}if(c<t.blockLength){var o=t.blockLength-c;for(var l=0;l<o;++l)n.putByte(54),r.putByte(92)}e=s,n=n.bytes(),r=r.bytes()}t.start(),t.update(n)},i.update=function(a){t.update(a)},i.getMac=function(){var a=t.digest().bytes();return t.start(),t.update(r),t.update(a),t.digest()},i.digest=i.getMac,i}});var ka=de(function(GC,nu){var rr=me();tr();Pe();var tu=nu.exports=rr.md5=rr.md5||{};rr.md.md5=rr.md.algorithms.md5=tu;tu.create=function(){if(!ru)y0();var e=null,t=rr.util.createBuffer(),n=Array(16),r={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];var i=r.messageLengthSize/4;for(var a=0;a<i;++a)r.fullMessageLength.push(0);return t=rr.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},r},r.start(),r.update=function(i,a){if(a==="utf8")i=rr.util.encodeUtf8(i);var s=i.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;if(t.putBytes(i),eu(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=rr.util.createBuffer();i.putBytes(t.bytes());var a=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=a&r.blockLength-1;i.putBytes(lo.substr(0,r.blockLength-s));var o,l=0;for(var c=r.fullMessageLength.length-1;c>=0;--c)o=r.fullMessageLength[c]*8+l,l=o/4294967296>>>0,i.putInt32Le(o>>>0);var u={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};eu(u,n,i);var d=rr.util.createBuffer();return d.putInt32Le(u.h0),d.putInt32Le(u.h1),d.putInt32Le(u.h2),d.putInt32Le(u.h3),d},r};var lo=null,_a=null,yi=null,_n=null,ru=!1;function y0(){lo=String.fromCharCode(128),lo+=rr.util.fillString(String.fromCharCode(0),64),_a=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],yi=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],_n=Array(64);for(var e=0;e<64;++e)_n[e]=Math.floor(Math.abs(Math.sin(e+1))*4294967296);ru=!0}function eu(e,t,n){var r,i,a,s,o,l,c,u,d=n.length();while(d>=64){i=e.h0,a=e.h1,s=e.h2,o=e.h3;for(u=0;u<16;++u)t[u]=n.getInt32Le(),l=o^a&(s^o),r=i+l+_n[u]+t[u],c=yi[u],i=o,o=s,s=a,a+=r<<c|r>>>32-c;for(;u<32;++u)l=s^o&(a^s),r=i+l+_n[u]+t[_a[u]],c=yi[u],i=o,o=s,s=a,a+=r<<c|r>>>32-c;for(;u<48;++u)l=a^s^o,r=i+l+_n[u]+t[_a[u]],c=yi[u],i=o,o=s,s=a,a+=r<<c|r>>>32-c;for(;u<64;++u)l=s^(a|~o),r=i+l+_n[u]+t[_a[u]],c=yi[u],i=o,o=s,s=a,a+=r<<c|r>>>32-c;e.h0=e.h0+i|0,e.h1=e.h1+a|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,d-=64}}});var an=de(function(jC,au){var Ra=me();Pe();var iu=au.exports=Ra.pem=Ra.pem||{};iu.encode=function(e,t){t=t||{};var n="-----BEGIN "+e.type+`-----\r
9
- `,r;if(e.procType)r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]},n+=Ia(r);if(e.contentDomain)r={name:"Content-Domain",values:[e.contentDomain]},n+=Ia(r);if(e.dekInfo){if(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters)r.values.push(e.dekInfo.parameters);n+=Ia(r)}if(e.headers)for(var i=0;i<e.headers.length;++i)n+=Ia(e.headers[i]);if(e.procType)n+=`\r
10
- `;return n+=Ra.util.encode64(e.body,t.maxline||64)+`\r
11
- `,n+="-----END "+e.type+`-----\r
12
- `,n};iu.decode=function(e){var t=[],n=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,r=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,i=/\r?\n/,a;while(!0){if(a=n.exec(e),!a)break;var s=a[1];if(s==="NEW CERTIFICATE REQUEST")s="CERTIFICATE REQUEST";var o={type:s,procType:null,contentDomain:null,dekInfo:null,headers:[],body:Ra.util.decode64(a[3])};if(t.push(o),!a[2])continue;var l=a[2].split(i),c=0;while(a&&c<l.length){var u=l[c].replace(/\s+$/,"");for(var d=c+1;d<l.length;++d){var f=l[d];if(!/\s/.test(f[0]))break;u+=f,c=d}if(a=u.match(r),a){var y={name:a[1],values:[]},p=a[2].split(",");for(var v=0;v<p.length;++v)y.values.push(v0(p[v]));if(!o.procType){if(y.name!=="Proc-Type")throw Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');else if(y.values.length!==2)throw Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');o.procType={version:p[0],type:p[1]}}else if(!o.contentDomain&&y.name==="Content-Domain")o.contentDomain=p[0]||"";else if(!o.dekInfo&&y.name==="DEK-Info"){if(y.values.length===0)throw Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');o.dekInfo={algorithm:p[0],parameters:p[1]||null}}else o.headers.push(y)}++c}if(o.procType==="ENCRYPTED"&&!o.dekInfo)throw Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}if(t.length===0)throw Error("Invalid PEM formatted message.");return t};function Ia(e){var t=e.name+": ",n=[],r=function(l,c){return" "+c};for(var i=0;i<e.values.length;++i)n.push(e.values[i].replace(/^(\S+\r\n)/,r));t+=n.join(",")+`\r
13
- `;var a=0,s=-1;for(var i=0;i<t.length;++i,++a)if(a>65&&s!==-1){var o=t[s];if(o===",")++s,t=t.substr(0,s)+`\r
14
- `+t.substr(s);else t=t.substr(0,s)+`\r
15
- `+o+t.substr(s+1);a=i-s-1,s=-1,++i}else if(t[i]===" "||t[i]==="\t"||t[i]===",")s=i;return t}function v0(e){return e.replace(/^\s+/,"")}});var vi=de(function(zC,ou){var Ge=me();ba();no();Pe();ou.exports=Ge.des=Ge.des||{};Ge.des.startEncrypting=function(e,t,n,r){var i=Ba({key:e,output:n,decrypt:!1,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};Ge.des.createEncryptionCipher=function(e,t){return Ba({key:e,output:null,decrypt:!1,mode:t})};Ge.des.startDecrypting=function(e,t,n,r){var i=Ba({key:e,output:n,decrypt:!0,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};Ge.des.createDecryptionCipher=function(e,t){return Ba({key:e,output:null,decrypt:!0,mode:t})};Ge.des.Algorithm=function(e,t){var n=this;n.name=e,n.mode=new t({blockSize:8,cipher:{encrypt:function(r,i){return su(n._keys,r,i,!1)},decrypt:function(r,i){return su(n._keys,r,i,!0)}}}),n._init=!1};Ge.des.Algorithm.prototype.initialize=function(e){if(this._init)return;var t=Ge.util.createBuffer(e.key);if(this.name.indexOf("3DES")===0){if(t.length()!==24)throw Error("Invalid Triple-DES key size: "+t.length()*8)}this._keys=_0(t),this._init=!0};nr("DES-ECB",Ge.cipher.modes.ecb);nr("DES-CBC",Ge.cipher.modes.cbc);nr("DES-CFB",Ge.cipher.modes.cfb);nr("DES-OFB",Ge.cipher.modes.ofb);nr("DES-CTR",Ge.cipher.modes.ctr);nr("3DES-ECB",Ge.cipher.modes.ecb);nr("3DES-CBC",Ge.cipher.modes.cbc);nr("3DES-CFB",Ge.cipher.modes.cfb);nr("3DES-OFB",Ge.cipher.modes.ofb);nr("3DES-CTR",Ge.cipher.modes.ctr);function nr(e,t){var n=function(){return new Ge.des.Algorithm(e,t)};Ge.cipher.registerAlgorithm(e,n)}var x0=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],S0=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],b0=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],C0=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],E0=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],w0=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],T0=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],A0=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function _0(e){var t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],n=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],r=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],a=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],c=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],u=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],f=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],y=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],p=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],v=e.length()>8?3:1,x=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],A=0,E;for(var k=0;k<v;k++){var I=e.getInt32(),R=e.getInt32();E=(I>>>4^R)&252645135,R^=E,I^=E<<4,E=(R>>>-16^I)&65535,I^=E,R^=E<<-16,E=(I>>>2^R)&858993459,R^=E,I^=E<<2,E=(R>>>-16^I)&65535,I^=E,R^=E<<-16,E=(I>>>1^R)&1431655765,R^=E,I^=E<<1,E=(R>>>8^I)&16711935,I^=E,R^=E<<8,E=(I>>>1^R)&1431655765,R^=E,I^=E<<1,E=I<<8|R>>>20&240,I=R<<24|R<<8&16711680|R>>>8&65280|R>>>24&240,R=E;for(var M=0;M<b.length;++M){if(b[M])I=I<<2|I>>>26,R=R<<2|R>>>26;else I=I<<1|I>>>27,R=R<<1|R>>>27;I&=-15,R&=-15;var ee=t[I>>>28]|n[I>>>24&15]|r[I>>>20&15]|i[I>>>16&15]|a[I>>>12&15]|s[I>>>8&15]|o[I>>>4&15],O=l[R>>>28]|c[R>>>24&15]|u[R>>>20&15]|d[R>>>16&15]|f[R>>>12&15]|y[R>>>8&15]|p[R>>>4&15];E=(O>>>16^ee)&65535,x[A++]=ee^E,x[A++]=O^E<<16}}return x}function su(e,t,n,r){var i=e.length===32?3:9,a;if(i===3)a=r?[30,-2,-2]:[0,32,2];else a=r?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,o=t[0],l=t[1];s=(o>>>4^l)&252645135,l^=s,o^=s<<4,s=(o>>>16^l)&65535,l^=s,o^=s<<16,s=(l>>>2^o)&858993459,o^=s,l^=s<<2,s=(l>>>8^o)&16711935,o^=s,l^=s<<8,s=(o>>>1^l)&1431655765,l^=s,o^=s<<1,o=o<<1|o>>>31,l=l<<1|l>>>31;for(var c=0;c<i;c+=3){var u=a[c+1],d=a[c+2];for(var f=a[c];f!=u;f+=d){var y=l^e[f],p=(l>>>4|l<<28)^e[f+1];s=o,o=l,l=s^(S0[y>>>24&63]|C0[y>>>16&63]|w0[y>>>8&63]|A0[y&63]|x0[p>>>24&63]|b0[p>>>16&63]|E0[p>>>8&63]|T0[p&63])}s=o,o=l,l=s}o=o>>>1|o<<31,l=l>>>1|l<<31,s=(o>>>1^l)&1431655765,l^=s,o^=s<<1,s=(l>>>8^o)&16711935,o^=s,l^=s<<8,s=(l>>>2^o)&858993459,o^=s,l^=s<<2,s=(o>>>16^l)&65535,l^=s,o^=s<<16,s=(o>>>4^l)&252645135,l^=s,o^=s<<4,n[0]=o,n[1]=l}function Ba(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="DES-"+t,r;if(e.decrypt)r=Ge.cipher.createDecipher(n,e.key);else r=Ge.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(a,s){var o=null;if(s instanceof Ge.util.ByteBuffer)o=s,s={};s=s||{},s.output=o,s.iv=a,i.call(r,s)},r}});var Pa=de(function(QC,lu){var bt=me();An();tr();Pe();var k0=bt.pkcs5=bt.pkcs5||{},xr;if(bt.util.isNodejs&&!bt.options.usePureJavaScript)xr=li("crypto");lu.exports=bt.pbkdf2=k0.pbkdf2=function(e,t,n,r,i,a){if(typeof i==="function")a=i,i=null;if(bt.util.isNodejs&&!bt.options.usePureJavaScript&&xr.pbkdf2&&(i===null||typeof i!=="object")&&(xr.pbkdf2Sync.length>4||(!i||i==="sha1"))){if(typeof i!=="string")i="sha1";if(e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),!a){if(xr.pbkdf2Sync.length===4)return xr.pbkdf2Sync(e,t,n,r).toString("binary");return xr.pbkdf2Sync(e,t,n,r,i).toString("binary")}if(xr.pbkdf2Sync.length===4)return xr.pbkdf2(e,t,n,r,function(E,k){if(E)return a(E);a(null,k.toString("binary"))});return xr.pbkdf2(e,t,n,r,i,function(E,k){if(E)return a(E);a(null,k.toString("binary"))})}if(typeof i>"u"||i===null)i="sha1";if(typeof i==="string"){if(!(i in bt.md.algorithms))throw Error("Unknown hash algorithm: "+i);i=bt.md[i].create()}var s=i.digestLength;if(r>4294967295*s){var o=Error("Derived key is too long.");if(a)return a(o);throw o}var l=Math.ceil(r/s),c=r-(l-1)*s,u=bt.hmac.create();u.start(i,e);var d="",f,y,p;if(!a){for(var v=1;v<=l;++v){u.start(null,null),u.update(t),u.update(bt.util.int32ToBytes(v)),f=p=u.digest().getBytes();for(var x=2;x<=n;++x)u.start(null,null),u.update(p),y=u.digest().getBytes(),f=bt.util.xorBytes(f,y,s),p=y;d+=v<l?f:f.substr(0,c)}return d}var v=1,x;function b(){if(v>l)return a(null,d);u.start(null,null),u.update(t),u.update(bt.util.int32ToBytes(v)),f=p=u.digest().getBytes(),x=2,A()}function A(){if(x<=n)return u.start(null,null),u.update(p),y=u.digest().getBytes(),f=bt.util.xorBytes(f,y,s),p=y,++x,bt.util.setImmediate(A);d+=v<l?f:f.substr(0,c),++v,b()}b()}});var uo=de(function(XC,pu){var ir=me();tr();Pe();var uu=pu.exports=ir.sha256=ir.sha256||{};ir.md.sha256=ir.md.algorithms.sha256=uu;uu.create=function(){if(!du)I0();var e=null,t=ir.util.createBuffer(),n=Array(64),r={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];var i=r.messageLengthSize/4;for(var a=0;a<i;++a)r.fullMessageLength.push(0);return t=ir.util.createBuffer(),e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},r},r.start(),r.update=function(i,a){if(a==="utf8")i=ir.util.encodeUtf8(i);var s=i.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;if(t.putBytes(i),cu(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=ir.util.createBuffer();i.putBytes(t.bytes());var a=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=a&r.blockLength-1;i.putBytes(co.substr(0,r.blockLength-s));var o,l,c=r.fullMessageLength[0]*8;for(var u=0;u<r.fullMessageLength.length-1;++u)o=r.fullMessageLength[u+1]*8,l=o/4294967296>>>0,c+=l,i.putInt32(c>>>0),c=o>>>0;i.putInt32(c);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};cu(d,n,i);var f=ir.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f.putInt32(d.h5),f.putInt32(d.h6),f.putInt32(d.h7),f},r};var co=null,du=!1,fu=null;function I0(){co=String.fromCharCode(128),co+=ir.util.fillString(String.fromCharCode(0),64),fu=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],du=!0}function cu(e,t,n){var r,i,a,s,o,l,c,u,d,f,y,p,v,x,b,A=n.length();while(A>=64){for(c=0;c<16;++c)t[c]=n.getInt32();for(;c<64;++c)r=t[c-2],r=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,i=t[c-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[c]=r+t[c-7]+i+t[c-16]|0;u=e.h0,d=e.h1,f=e.h2,y=e.h3,p=e.h4,v=e.h5,x=e.h6,b=e.h7;for(c=0;c<64;++c)s=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),o=x^p&(v^x),a=(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),l=u&d|f&(u^d),r=b+s+o+fu[c]+t[c],i=a+l,b=x,x=v,v=p,p=y+r>>>0,y=f,f=d,d=u,u=r+i>>>0;e.h0=e.h0+u|0,e.h1=e.h1+d|0,e.h2=e.h2+f|0,e.h3=e.h3+y|0,e.h4=e.h4+p|0,e.h5=e.h5+v|0,e.h6=e.h6+x|0,e.h7=e.h7+b|0,A-=64}}});var fo=de(function(YC,hu){var ar=me();Pe();var Na=null;if(ar.util.isNodejs&&!ar.options.usePureJavaScript&&!process.versions["node-webkit"])Na=li("crypto");var R0=hu.exports=ar.prng=ar.prng||{};R0.create=function(e){var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},n=e.md,r=Array(32);for(var i=0;i<32;++i)r[i]=n.create();t.pools=r,t.pool=0,t.generate=function(c,u){if(!u)return t.generateSync(c);var d=t.plugin.cipher,f=t.plugin.increment,y=t.plugin.formatKey,p=t.plugin.formatSeed,v=ar.util.createBuffer();t.key=null,x();function x(b){if(b)return u(b);if(v.length()>=c)return u(null,v.getBytes(c));if(t.generated>1048575)t.key=null;if(t.key===null)return ar.util.nextTick(function(){a(x)});var A=d(t.key,t.seed);t.generated+=A.length,v.putBytes(A),t.key=y(d(t.key,f(t.seed))),t.seed=p(d(t.key,t.seed)),ar.util.setImmediate(x)}},t.generateSync=function(c){var u=t.plugin.cipher,d=t.plugin.increment,f=t.plugin.formatKey,y=t.plugin.formatSeed;t.key=null;var p=ar.util.createBuffer();while(p.length()<c){if(t.generated>1048575)t.key=null;if(t.key===null)s();var v=u(t.key,t.seed);t.generated+=v.length,p.putBytes(v),t.key=f(u(t.key,d(t.seed))),t.seed=y(u(t.key,t.seed))}return p.getBytes(c)};function a(c){if(t.pools[0].messageLength>=32)return o(),c();var u=32-t.pools[0].messageLength<<5;t.seedFile(u,function(d,f){if(d)return c(d);t.collect(f),o(),c()})}function s(){if(t.pools[0].messageLength>=32)return o();var c=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(c)),o()}function o(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var c=t.plugin.md.create();c.update(t.keyBytes);var u=1;for(var d=0;d<32;++d){if(t.reseeds%u===0)c.update(t.pools[d].digest().getBytes()),t.pools[d].start();u=u<<1}t.keyBytes=c.digest().getBytes(),c.start(),c.update(t.keyBytes);var f=c.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(f),t.generated=0}function l(c){var u=null,d=ar.util.globalScope,f=d.crypto||d.msCrypto;if(f&&f.getRandomValues)u=function(I){return f.getRandomValues(I)};var y=ar.util.createBuffer();if(u)while(y.length()<c){var p=Math.max(1,Math.min(c-y.length(),65536)/4),v=new Uint32Array(Math.floor(p));try{u(v);for(var x=0;x<v.length;++x)y.putInt32(v[x])}catch(I){if(!(typeof QuotaExceededError<"u"&&I instanceof QuotaExceededError))throw I}}if(y.length()<c){var b,A,E,k=Math.floor(Math.random()*65536);while(y.length()<c){A=16807*(k&65535),b=16807*(k>>16),A+=(b&32767)<<16,A+=b>>15,A=(A&2147483647)+(A>>31),k=A&4294967295;for(var x=0;x<3;++x)E=k>>>(x<<3),E^=Math.floor(Math.random()*256),y.putByte(E&255)}}return y.getBytes(c)}if(Na)t.seedFile=function(c,u){Na.randomBytes(c,function(d,f){if(d)return u(d);u(null,f.toString())})},t.seedFileSync=function(c){return Na.randomBytes(c).toString()};else t.seedFile=function(c,u){try{u(null,l(c))}catch(d){u(d)}},t.seedFileSync=l;return t.collect=function(c){var u=c.length;for(var d=0;d<u;++d)t.pools[t.pool].update(c.substr(d,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(c,u){var d="";for(var f=0;f<u;f+=8)d+=String.fromCharCode(c>>f&255);t.collect(d)},t.registerWorker=function(c){if(c===self)t.seedFile=function(d,f){function y(p){var v=p.data;if(v.forge&&v.forge.prng)self.removeEventListener("message",y),f(v.forge.prng.err,v.forge.prng.bytes)}self.addEventListener("message",y),self.postMessage({forge:{prng:{needed:d}}})};else{var u=function(d){var f=d.data;if(f.forge&&f.forge.prng)t.seedFile(f.forge.prng.needed,function(y,p){c.postMessage({forge:{prng:{err:y,bytes:p}}})})};c.addEventListener("message",u)}},t}});var Dt=de(function(JC,po){var ft=me();Dr();uo();fo();Pe();(function(){if(ft.random&&ft.random.getBytes){po.exports=ft.random;return}(function(e){var t={},n=[,,,,],r=ft.util.createBuffer();t.formatKey=function(d){var f=ft.util.createBuffer(d);return d=[,,,,],d[0]=f.getInt32(),d[1]=f.getInt32(),d[2]=f.getInt32(),d[3]=f.getInt32(),ft.aes._expandKey(d,!1)},t.formatSeed=function(d){var f=ft.util.createBuffer(d);return d=[,,,,],d[0]=f.getInt32(),d[1]=f.getInt32(),d[2]=f.getInt32(),d[3]=f.getInt32(),d},t.cipher=function(d,f){return ft.aes._updateBlock(d,f,n,!1),r.putInt32(n[0]),r.putInt32(n[1]),r.putInt32(n[2]),r.putInt32(n[3]),r.getBytes()},t.increment=function(d){return++d[3],d},t.md=ft.md.sha256;function i(){var d=ft.prng.create(t);return d.getBytes=function(f,y){return d.generate(f,y)},d.getBytesSync=function(f){return d.generate(f)},d}var a=i(),s=null,o=ft.util.globalScope,l=o.crypto||o.msCrypto;if(l&&l.getRandomValues)s=function(d){return l.getRandomValues(d)};if(ft.options.usePureJavaScript||!ft.util.isNodejs&&!s){if(typeof window>"u"||window.document===void 0);if(a.collectInt(+new Date,32),typeof navigator<"u"){var c="";for(var u in navigator)try{if(typeof navigator[u]=="string")c+=navigator[u]}catch(d){}a.collect(c),c=null}if(e)e().mousemove(function(d){a.collectInt(d.clientX,16),a.collectInt(d.clientY,16)}),e().keypress(function(d){a.collectInt(d.charCode,8)})}if(!ft.random)ft.random=a;else for(var u in a)ft.random[u]=a[u];ft.random.createInstance=i,po.exports=ft.random})(typeof jQuery<"u"?jQuery:null)})()});var go=de(function(ZC,yu){var Tt=me();Pe();var ho=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],gu=[1,2,3,5],B0=function(e,t){return e<<t&65535|(e&65535)>>16-t},P0=function(e,t){return(e&65535)>>t|e<<16-t&65535};yu.exports=Tt.rc2=Tt.rc2||{};Tt.rc2.expandKey=function(e,t){if(typeof e==="string")e=Tt.util.createBuffer(e);t=t||128;var n=e,r=e.length(),i=t,a=Math.ceil(i/8),s=255>>(i&7),o;for(o=r;o<128;o++)n.putByte(ho[n.at(o-1)+n.at(o-r)&255]);n.setAt(128-a,ho[n.at(128-a)&s]);for(o=127-a;o>=0;o--)n.setAt(o,ho[n.at(o+1)^n.at(o+a)]);return n};var mu=function(e,t,n){var r=!1,i=null,a=null,s=null,o,l,c,u,d=[];e=Tt.rc2.expandKey(e,t);for(c=0;c<64;c++)d.push(e.getInt16Le());if(n)o=function(p){for(c=0;c<4;c++)p[c]+=d[u]+(p[(c+3)%4]&p[(c+2)%4])+(~p[(c+3)%4]&p[(c+1)%4]),p[c]=B0(p[c],gu[c]),u++},l=function(p){for(c=0;c<4;c++)p[c]+=d[p[(c+3)%4]&63]};else o=function(p){for(c=3;c>=0;c--)p[c]=P0(p[c],gu[c]),p[c]-=d[u]+(p[(c+3)%4]&p[(c+2)%4])+(~p[(c+3)%4]&p[(c+1)%4]),u--},l=function(p){for(c=3;c>=0;c--)p[c]-=d[p[(c+3)%4]&63]};var f=function(p){var v=[];for(c=0;c<4;c++){var x=i.getInt16Le();if(s!==null)if(n)x^=s.getInt16Le();else s.putInt16Le(x);v.push(x&65535)}u=n?0:63;for(var b=0;b<p.length;b++)for(var A=0;A<p[b][0];A++)p[b][1](v);for(c=0;c<4;c++){if(s!==null)if(n)s.putInt16Le(v[c]);else v[c]^=s.getInt16Le();a.putInt16Le(v[c])}},y=null;return y={start:function(p,v){if(p){if(typeof p==="string")p=Tt.util.createBuffer(p)}r=!1,i=Tt.util.createBuffer(),a=v||new Tt.util.createBuffer,s=p,y.output=a},update:function(p){if(!r)i.putBuffer(p);while(i.length()>=8)f([[5,o],[1,l],[6,o],[1,l],[5,o]])},finish:function(p){var v=!0;if(n)if(p)v=p(8,i,!n);else{var x=i.length()===8?8:8-i.length();i.fillWithByte(x,x)}if(v)r=!0,y.update();if(!n){if(v=i.length()===0,v)if(p)v=p(8,a,!n);else{var b=a.length(),A=a.at(b-1);if(A>b)v=!1;else a.truncate(A)}}return v}},y};Tt.rc2.startEncrypting=function(e,t,n){var r=Tt.rc2.createEncryptionCipher(e,128);return r.start(t,n),r};Tt.rc2.createEncryptionCipher=function(e,t){return mu(e,t,!0)};Tt.rc2.startDecrypting=function(e,t,n){var r=Tt.rc2.createDecryptionCipher(e,128);return r.start(t,n),r};Tt.rc2.createDecryptionCipher=function(e,t){return mu(e,t,!1)}});var Si=de(function(e1,Tu){var mo=me();Tu.exports=mo.jsbn=mo.jsbn||{};var Sr,N0=244837814094590,vu=(N0&16777215)==15715070;function D(e,t,n){if(this.data=[],e!=null)if(typeof e=="number")this.fromNumber(e,t,n);else if(t==null&&typeof e!="string")this.fromString(e,256);else this.fromString(e,t)}mo.jsbn.BigInteger=D;function Re(){return new D(null)}function D0(e,t,n,r,i,a){while(--a>=0){var s=t*this.data[e++]+n.data[r]+i;i=Math.floor(s/67108864),n.data[r++]=s&67108863}return i}function L0(e,t,n,r,i,a){var s=t&32767,o=t>>15;while(--a>=0){var l=this.data[e]&32767,c=this.data[e++]>>15,u=o*l+c*s;l=s*l+((u&32767)<<15)+n.data[r]+(i&1073741823),i=(l>>>30)+(u>>>15)+o*c+(i>>>30),n.data[r++]=l&1073741823}return i}function xu(e,t,n,r,i,a){var s=t&16383,o=t>>14;while(--a>=0){var l=this.data[e]&16383,c=this.data[e++]>>14,u=o*l+c*s;l=s*l+((u&16383)<<14)+n.data[r]+i,i=(l>>28)+(u>>14)+o*c,n.data[r++]=l&268435455}return i}if(typeof navigator>"u")D.prototype.am=xu,Sr=28;else if(vu&&navigator.appName=="Microsoft Internet Explorer")D.prototype.am=L0,Sr=30;else if(vu&&navigator.appName!="Netscape")D.prototype.am=D0,Sr=26;else D.prototype.am=xu,Sr=28;D.prototype.DB=Sr;D.prototype.DM=(1<<Sr)-1;D.prototype.DV=1<<Sr;var yo=52;D.prototype.FV=Math.pow(2,yo);D.prototype.F1=yo-Sr;D.prototype.F2=2*Sr-yo;var O0="0123456789abcdefghijklmnopqrstuvwxyz",Da=[],kn,Lt;kn=48;for(Lt=0;Lt<=9;++Lt)Da[kn++]=Lt;kn=97;for(Lt=10;Lt<36;++Lt)Da[kn++]=Lt;kn=65;for(Lt=10;Lt<36;++Lt)Da[kn++]=Lt;function Su(e){return O0.charAt(e)}function bu(e,t){var n=Da[e.charCodeAt(t)];return n==null?-1:n}function U0(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function V0(e){if(this.t=1,this.s=e<0?-1:0,e>0)this.data[0]=e;else if(e<-1)this.data[0]=e+this.DV;else this.t=0}function Or(e){var t=Re();return t.fromInt(e),t}function F0(e,t){var n;if(t==16)n=4;else if(t==8)n=3;else if(t==256)n=8;else if(t==2)n=1;else if(t==32)n=5;else if(t==4)n=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;var r=e.length,i=!1,a=0;while(--r>=0){var s=n==8?e[r]&255:bu(e,r);if(s<0){if(e.charAt(r)=="-")i=!0;continue}if(i=!1,a==0)this.data[this.t++]=s;else if(a+n>this.DB)this.data[this.t-1]|=(s&(1<<this.DB-a)-1)<<a,this.data[this.t++]=s>>this.DB-a;else this.data[this.t-1]|=s<<a;if(a+=n,a>=this.DB)a-=this.DB}if(n==8&&(e[0]&128)!=0){if(this.s=-1,a>0)this.data[this.t-1]|=(1<<this.DB-a)-1<<a}if(this.clamp(),i)D.ZERO.subTo(this,this)}function M0(){var e=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==e)--this.t}function W0(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else return this.toRadix(e);var n=(1<<t)-1,r,i=!1,a="",s=this.t,o=this.DB-s*this.DB%t;if(s-- >0){if(o<this.DB&&(r=this.data[s]>>o)>0)i=!0,a=Su(r);while(s>=0){if(o<t)r=(this.data[s]&(1<<o)-1)<<t-o,r|=this.data[--s]>>(o+=this.DB-t);else if(r=this.data[s]>>(o-=t)&n,o<=0)o+=this.DB,--s;if(r>0)i=!0;if(i)a+=Su(r)}}return i?a:"0"}function $0(){var e=Re();return D.ZERO.subTo(this,e),e}function H0(){return this.s<0?this.negate():this}function K0(e){var t=this.s-e.s;if(t!=0)return t;var n=this.t;if(t=n-e.t,t!=0)return this.s<0?-t:t;while(--n>=0)if((t=this.data[n]-e.data[n])!=0)return t;return 0}function La(e){var t=1,n;if((n=e>>>16)!=0)e=n,t+=16;if((n=e>>8)!=0)e=n,t+=8;if((n=e>>4)!=0)e=n,t+=4;if((n=e>>2)!=0)e=n,t+=2;if((n=e>>1)!=0)e=n,t+=1;return t}function q0(){if(this.t<=0)return 0;return this.DB*(this.t-1)+La(this.data[this.t-1]^this.s&this.DM)}function G0(e,t){var n;for(n=this.t-1;n>=0;--n)t.data[n+e]=this.data[n];for(n=e-1;n>=0;--n)t.data[n]=0;t.t=this.t+e,t.s=this.s}function j0(e,t){for(var n=e;n<this.t;++n)t.data[n-e]=this.data[n];t.t=Math.max(this.t-e,0),t.s=this.s}function z0(e,t){var n=e%this.DB,r=this.DB-n,i=(1<<r)-1,a=Math.floor(e/this.DB),s=this.s<<n&this.DM,o;for(o=this.t-1;o>=0;--o)t.data[o+a+1]=this.data[o]>>r|s,s=(this.data[o]&i)<<n;for(o=a-1;o>=0;--o)t.data[o]=0;t.data[a]=s,t.t=this.t+a+1,t.s=this.s,t.clamp()}function Q0(e,t){t.s=this.s;var n=Math.floor(e/this.DB);if(n>=this.t){t.t=0;return}var r=e%this.DB,i=this.DB-r,a=(1<<r)-1;t.data[0]=this.data[n]>>r;for(var s=n+1;s<this.t;++s)t.data[s-n-1]|=(this.data[s]&a)<<i,t.data[s-n]=this.data[s]>>r;if(r>0)t.data[this.t-n-1]|=(this.s&a)<<i;t.t=this.t-n,t.clamp()}function X0(e,t){var n=0,r=0,i=Math.min(e.t,this.t);while(n<i)r+=this.data[n]-e.data[n],t.data[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){r-=e.s;while(n<this.t)r+=this.data[n],t.data[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{r+=this.s;while(n<e.t)r-=e.data[n],t.data[n++]=r&this.DM,r>>=this.DB;r-=e.s}if(t.s=r<0?-1:0,r<-1)t.data[n++]=this.DV+r;else if(r>0)t.data[n++]=r;t.t=n,t.clamp()}function Y0(e,t){var n=this.abs(),r=e.abs(),i=n.t;t.t=i+r.t;while(--i>=0)t.data[i]=0;for(i=0;i<r.t;++i)t.data[i+n.t]=n.am(0,r.data[i],t,i,0,n.t);if(t.s=0,t.clamp(),this.s!=e.s)D.ZERO.subTo(t,t)}function J0(e){var t=this.abs(),n=e.t=2*t.t;while(--n>=0)e.data[n]=0;for(n=0;n<t.t-1;++n){var r=t.am(n,t.data[n],e,2*n,0,1);if((e.data[n+t.t]+=t.am(n+1,2*t.data[n],e,2*n+1,r,t.t-n-1))>=t.DV)e.data[n+t.t]-=t.DV,e.data[n+t.t+1]=1}if(e.t>0)e.data[e.t-1]+=t.am(n,t.data[n],e,2*n,0,1);e.s=0,e.clamp()}function Z0(e,t,n){var r=e.abs();if(r.t<=0)return;var i=this.abs();if(i.t<r.t){if(t!=null)t.fromInt(0);if(n!=null)this.copyTo(n);return}if(n==null)n=Re();var a=Re(),s=this.s,o=e.s,l=this.DB-La(r.data[r.t-1]);if(l>0)r.lShiftTo(l,a),i.lShiftTo(l,n);else r.copyTo(a),i.copyTo(n);var c=a.t,u=a.data[c-1];if(u==0)return;var d=u*(1<<this.F1)+(c>1?a.data[c-2]>>this.F2:0),f=this.FV/d,y=(1<<this.F1)/d,p=1<<this.F2,v=n.t,x=v-c,b=t==null?Re():t;if(a.dlShiftTo(x,b),n.compareTo(b)>=0)n.data[n.t++]=1,n.subTo(b,n);D.ONE.dlShiftTo(c,b),b.subTo(a,a);while(a.t<c)a.data[a.t++]=0;while(--x>=0){var A=n.data[--v]==u?this.DM:Math.floor(n.data[v]*f+(n.data[v-1]+p)*y);if((n.data[v]+=a.am(0,A,n,x,0,c))<A){a.dlShiftTo(x,b),n.subTo(b,n);while(n.data[v]<--A)n.subTo(b,n)}}if(t!=null){if(n.drShiftTo(c,t),s!=o)D.ZERO.subTo(t,t)}if(n.t=c,n.clamp(),l>0)n.rShiftTo(l,n);if(s<0)D.ZERO.subTo(n,n)}function eg(e){var t=Re();if(this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(D.ZERO)>0)e.subTo(t,t);return t}function sn(e){this.m=e}function tg(e){if(e.s<0||e.compareTo(this.m)>=0)return e.mod(this.m);else return e}function rg(e){return e}function ng(e){e.divRemTo(this.m,null,e)}function ig(e,t,n){e.multiplyTo(t,n),this.reduce(n)}function ag(e,t){e.squareTo(t),this.reduce(t)}sn.prototype.convert=tg;sn.prototype.revert=rg;sn.prototype.reduce=ng;sn.prototype.mulTo=ig;sn.prototype.sqrTo=ag;function sg(){if(this.t<1)return 0;var e=this.data[0];if((e&1)==0)return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function on(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function og(e){var t=Re();if(e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(D.ZERO)>0)this.m.subTo(t,t);return t}function lg(e){var t=Re();return e.copyTo(t),this.reduce(t),t}function cg(e){while(e.t<=this.mt2)e.data[e.t++]=0;for(var t=0;t<this.m.t;++t){var n=e.data[t]&32767,r=n*this.mpl+((n*this.mph+(e.data[t]>>15)*this.mpl&this.um)<<15)&e.DM;n=t+this.m.t,e.data[n]+=this.m.am(0,r,e,t,0,this.m.t);while(e.data[n]>=e.DV)e.data[n]-=e.DV,e.data[++n]++}if(e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0)e.subTo(this.m,e)}function ug(e,t){e.squareTo(t),this.reduce(t)}function dg(e,t,n){e.multiplyTo(t,n),this.reduce(n)}on.prototype.convert=og;on.prototype.revert=lg;on.prototype.reduce=cg;on.prototype.mulTo=dg;on.prototype.sqrTo=ug;function fg(){return(this.t>0?this.data[0]&1:this.s)==0}function pg(e,t){if(e>4294967295||e<1)return D.ONE;var n=Re(),r=Re(),i=t.convert(this),a=La(e)-1;i.copyTo(n);while(--a>=0)if(t.sqrTo(n,r),(e&1<<a)>0)t.mulTo(r,i,n);else{var s=n;n=r,r=s}return t.revert(n)}function hg(e,t){var n;if(e<256||t.isEven())n=new sn(t);else n=new on(t);return this.exp(e,n)}D.prototype.copyTo=U0;D.prototype.fromInt=V0;D.prototype.fromString=F0;D.prototype.clamp=M0;D.prototype.dlShiftTo=G0;D.prototype.drShiftTo=j0;D.prototype.lShiftTo=z0;D.prototype.rShiftTo=Q0;D.prototype.subTo=X0;D.prototype.multiplyTo=Y0;D.prototype.squareTo=J0;D.prototype.divRemTo=Z0;D.prototype.invDigit=sg;D.prototype.isEven=fg;D.prototype.exp=pg;D.prototype.toString=W0;D.prototype.negate=$0;D.prototype.abs=H0;D.prototype.compareTo=K0;D.prototype.bitLength=q0;D.prototype.mod=eg;D.prototype.modPowInt=hg;D.ZERO=Or(0);D.ONE=Or(1);function gg(){var e=Re();return this.copyTo(e),e}function mg(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this.data[0];else if(this.t==0)return 0;return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function yg(){return this.t==0?this.s:this.data[0]<<24>>24}function vg(){return this.t==0?this.s:this.data[0]<<16>>16}function xg(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function Sg(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function bg(e){if(e==null)e=10;if(this.signum()==0||e<2||e>36)return"0";var t=this.chunkSize(e),n=Math.pow(e,t),r=Or(n),i=Re(),a=Re(),s="";this.divRemTo(r,i,a);while(i.signum()>0)s=(n+a.intValue()).toString(e).substr(1)+s,i.divRemTo(r,i,a);return a.intValue().toString(e)+s}function Cg(e,t){if(this.fromInt(0),t==null)t=10;var n=this.chunkSize(t),r=Math.pow(t,n),i=!1,a=0,s=0;for(var o=0;o<e.length;++o){var l=bu(e,o);if(l<0){if(e.charAt(o)=="-"&&this.signum()==0)i=!0;continue}if(s=t*s+l,++a>=n)this.dMultiply(r),this.dAddOffset(s,0),a=0,s=0}if(a>0)this.dMultiply(Math.pow(t,a)),this.dAddOffset(s,0);if(i)D.ZERO.subTo(this,this)}function Eg(e,t,n){if(typeof t=="number")if(e<2)this.fromInt(1);else{if(this.fromNumber(e,n),!this.testBit(e-1))this.bitwiseTo(D.ONE.shiftLeft(e-1),vo,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(t))if(this.dAddOffset(2,0),this.bitLength()>e)this.subTo(D.ONE.shiftLeft(e-1),this)}else{var r=[],i=e&7;if(r.length=(e>>3)+1,t.nextBytes(r),i>0)r[0]&=(1<<i)-1;else r[0]=0;this.fromString(r,256)}}function wg(){var e=this.t,t=[];t[0]=this.s;var n=this.DB-e*this.DB%8,r,i=0;if(e-- >0){if(n<this.DB&&(r=this.data[e]>>n)!=(this.s&this.DM)>>n)t[i++]=r|this.s<<this.DB-n;while(e>=0){if(n<8)r=(this.data[e]&(1<<n)-1)<<8-n,r|=this.data[--e]>>(n+=this.DB-8);else if(r=this.data[e]>>(n-=8)&255,n<=0)n+=this.DB,--e;if((r&128)!=0)r|=-256;if(i==0&&(this.s&128)!=(r&128))++i;if(i>0||r!=this.s)t[i++]=r}}return t}function Tg(e){return this.compareTo(e)==0}function Ag(e){return this.compareTo(e)<0?this:e}function _g(e){return this.compareTo(e)>0?this:e}function kg(e,t,n){var r,i,a=Math.min(e.t,this.t);for(r=0;r<a;++r)n.data[r]=t(this.data[r],e.data[r]);if(e.t<this.t){i=e.s&this.DM;for(r=a;r<this.t;++r)n.data[r]=t(this.data[r],i);n.t=this.t}else{i=this.s&this.DM;for(r=a;r<e.t;++r)n.data[r]=t(i,e.data[r]);n.t=e.t}n.s=t(this.s,e.s),n.clamp()}function Ig(e,t){return e&t}function Rg(e){var t=Re();return this.bitwiseTo(e,Ig,t),t}function vo(e,t){return e|t}function Bg(e){var t=Re();return this.bitwiseTo(e,vo,t),t}function Cu(e,t){return e^t}function Pg(e){var t=Re();return this.bitwiseTo(e,Cu,t),t}function Eu(e,t){return e&~t}function Ng(e){var t=Re();return this.bitwiseTo(e,Eu,t),t}function Dg(){var e=Re();for(var t=0;t<this.t;++t)e.data[t]=this.DM&~this.data[t];return e.t=this.t,e.s=~this.s,e}function Lg(e){var t=Re();if(e<0)this.rShiftTo(-e,t);else this.lShiftTo(e,t);return t}function Og(e){var t=Re();if(e<0)this.lShiftTo(-e,t);else this.rShiftTo(e,t);return t}function Ug(e){if(e==0)return-1;var t=0;if((e&65535)==0)e>>=16,t+=16;if((e&255)==0)e>>=8,t+=8;if((e&15)==0)e>>=4,t+=4;if((e&3)==0)e>>=2,t+=2;if((e&1)==0)++t;return t}function Vg(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+Ug(this.data[e]);if(this.s<0)return this.t*this.DB;return-1}function Fg(e){var t=0;while(e!=0)e&=e-1,++t;return t}function Mg(){var e=0,t=this.s&this.DM;for(var n=0;n<this.t;++n)e+=Fg(this.data[n]^t);return e}function Wg(e){var t=Math.floor(e/this.DB);if(t>=this.t)return this.s!=0;return(this.data[t]&1<<e%this.DB)!=0}function $g(e,t){var n=D.ONE.shiftLeft(e);return this.bitwiseTo(n,t,n),n}function Hg(e){return this.changeBit(e,vo)}function Kg(e){return this.changeBit(e,Eu)}function qg(e){return this.changeBit(e,Cu)}function Gg(e,t){var n=0,r=0,i=Math.min(e.t,this.t);while(n<i)r+=this.data[n]+e.data[n],t.data[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){r+=e.s;while(n<this.t)r+=this.data[n],t.data[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{r+=this.s;while(n<e.t)r+=e.data[n],t.data[n++]=r&this.DM,r>>=this.DB;r+=e.s}if(t.s=r<0?-1:0,r>0)t.data[n++]=r;else if(r<-1)t.data[n++]=this.DV+r;t.t=n,t.clamp()}function jg(e){var t=Re();return this.addTo(e,t),t}function zg(e){var t=Re();return this.subTo(e,t),t}function Qg(e){var t=Re();return this.multiplyTo(e,t),t}function Xg(){var e=Re();return this.squareTo(e),e}function Yg(e){var t=Re();return this.divRemTo(e,t,null),t}function Jg(e){var t=Re();return this.divRemTo(e,null,t),t}function Zg(e){var t=Re(),n=Re();return this.divRemTo(e,t,n),[t,n]}function em(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function tm(e,t){if(e==0)return;while(this.t<=t)this.data[this.t++]=0;this.data[t]+=e;while(this.data[t]>=this.DV){if(this.data[t]-=this.DV,++t>=this.t)this.data[this.t++]=0;++this.data[t]}}function xi(){}function wu(e){return e}function rm(e,t,n){e.multiplyTo(t,n)}function nm(e,t){e.squareTo(t)}xi.prototype.convert=wu;xi.prototype.revert=wu;xi.prototype.mulTo=rm;xi.prototype.sqrTo=nm;function im(e){return this.exp(e,new xi)}function am(e,t,n){var r=Math.min(this.t+e.t,t);n.s=0,n.t=r;while(r>0)n.data[--r]=0;var i;for(i=n.t-this.t;r<i;++r)n.data[r+this.t]=this.am(0,e.data[r],n,r,0,this.t);for(i=Math.min(e.t,t);r<i;++r)this.am(0,e.data[r],n,r,0,t-r);n.clamp()}function sm(e,t,n){--t;var r=n.t=this.t+e.t-t;n.s=0;while(--r>=0)n.data[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)n.data[this.t+r-t]=this.am(t-r,e.data[r],n,0,0,this.t+r-t);n.clamp(),n.drShiftTo(1,n)}function In(e){this.r2=Re(),this.q3=Re(),D.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function om(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);else if(e.compareTo(this.m)<0)return e;else{var t=Re();return e.copyTo(t),this.reduce(t),t}}function lm(e){return e}function cm(e){if(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1)e.t=this.m.t+1,e.clamp();this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(e.compareTo(this.r2)<0)e.dAddOffset(1,this.m.t+1);e.subTo(this.r2,e);while(e.compareTo(this.m)>=0)e.subTo(this.m,e)}function um(e,t){e.squareTo(t),this.reduce(t)}function dm(e,t,n){e.multiplyTo(t,n),this.reduce(n)}In.prototype.convert=om;In.prototype.revert=lm;In.prototype.reduce=cm;In.prototype.mulTo=dm;In.prototype.sqrTo=um;function fm(e,t){var n=e.bitLength(),r,i=Or(1),a;if(n<=0)return i;else if(n<18)r=1;else if(n<48)r=3;else if(n<144)r=4;else if(n<768)r=5;else r=6;if(n<8)a=new sn(t);else if(t.isEven())a=new In(t);else a=new on(t);var s=[],o=3,l=r-1,c=(1<<r)-1;if(s[1]=a.convert(this),r>1){var u=Re();a.sqrTo(s[1],u);while(o<=c)s[o]=Re(),a.mulTo(u,s[o-2],s[o]),o+=2}var d=e.t-1,f,y=!0,p=Re(),v;n=La(e.data[d])-1;while(d>=0){if(n>=l)f=e.data[d]>>n-l&c;else if(f=(e.data[d]&(1<<n+1)-1)<<l-n,d>0)f|=e.data[d-1]>>this.DB+n-l;o=r;while((f&1)==0)f>>=1,--o;if((n-=o)<0)n+=this.DB,--d;if(y)s[f].copyTo(i),y=!1;else{while(o>1)a.sqrTo(i,p),a.sqrTo(p,i),o-=2;if(o>0)a.sqrTo(i,p);else v=i,i=p,p=v;a.mulTo(p,s[f],i)}while(d>=0&&(e.data[d]&1<<n)==0)if(a.sqrTo(i,p),v=i,i=p,p=v,--n<0)n=this.DB-1,--d}return a.revert(i)}function pm(e){var t=this.s<0?this.negate():this.clone(),n=e.s<0?e.negate():e.clone();if(t.compareTo(n)<0){var r=t;t=n,n=r}var i=t.getLowestSetBit(),a=n.getLowestSetBit();if(a<0)return t;if(i<a)a=i;if(a>0)t.rShiftTo(a,t),n.rShiftTo(a,n);while(t.signum()>0){if((i=t.getLowestSetBit())>0)t.rShiftTo(i,t);if((i=n.getLowestSetBit())>0)n.rShiftTo(i,n);if(t.compareTo(n)>=0)t.subTo(n,t),t.rShiftTo(1,t);else n.subTo(t,n),n.rShiftTo(1,n)}if(a>0)n.lShiftTo(a,n);return n}function hm(e){if(e<=0)return 0;var t=this.DV%e,n=this.s<0?e-1:0;if(this.t>0)if(t==0)n=this.data[0]%e;else for(var r=this.t-1;r>=0;--r)n=(t*n+this.data[r])%e;return n}function gm(e){if(this.signum()==0)return D.ZERO;var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return D.ZERO;var n=e.clone(),r=this.clone(),i=Or(1),a=Or(0),s=Or(0),o=Or(1);while(n.signum()!=0){while(n.isEven()){if(n.rShiftTo(1,n),t){if(!i.isEven()||!a.isEven())i.addTo(this,i),a.subTo(e,a);i.rShiftTo(1,i)}else if(!a.isEven())a.subTo(e,a);a.rShiftTo(1,a)}while(r.isEven()){if(r.rShiftTo(1,r),t){if(!s.isEven()||!o.isEven())s.addTo(this,s),o.subTo(e,o);s.rShiftTo(1,s)}else if(!o.isEven())o.subTo(e,o);o.rShiftTo(1,o)}if(n.compareTo(r)>=0){if(n.subTo(r,n),t)i.subTo(s,i);a.subTo(o,a)}else{if(r.subTo(n,r),t)s.subTo(i,s);o.subTo(a,o)}}if(r.compareTo(D.ONE)!=0)return D.ZERO;if(o.compareTo(e)>=0)return o.subtract(e);if(o.signum()<0)o.addTo(e,o);else return o;if(o.signum()<0)return o.add(e);else return o}var Gt=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],mm=67108864/Gt[Gt.length-1];function ym(e){var t,n=this.abs();if(n.t==1&&n.data[0]<=Gt[Gt.length-1]){for(t=0;t<Gt.length;++t)if(n.data[0]==Gt[t])return!0;return!1}if(n.isEven())return!1;t=1;while(t<Gt.length){var r=Gt[t],i=t+1;while(i<Gt.length&&r<mm)r*=Gt[i++];r=n.modInt(r);while(t<i)if(r%Gt[t++]==0)return!1}return n.millerRabin(e)}function vm(e){var t=this.subtract(D.ONE),n=t.getLowestSetBit();if(n<=0)return!1;var r=t.shiftRight(n),i=xm(),a;for(var s=0;s<e;++s){do a=new D(this.bitLength(),i);while(a.compareTo(D.ONE)<=0||a.compareTo(t)>=0);var o=a.modPow(r,this);if(o.compareTo(D.ONE)!=0&&o.compareTo(t)!=0){var l=1;while(l++<n&&o.compareTo(t)!=0)if(o=o.modPowInt(2,this),o.compareTo(D.ONE)==0)return!1;if(o.compareTo(t)!=0)return!1}}return!0}function xm(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}D.prototype.chunkSize=xg;D.prototype.toRadix=bg;D.prototype.fromRadix=Cg;D.prototype.fromNumber=Eg;D.prototype.bitwiseTo=kg;D.prototype.changeBit=$g;D.prototype.addTo=Gg;D.prototype.dMultiply=em;D.prototype.dAddOffset=tm;D.prototype.multiplyLowerTo=am;D.prototype.multiplyUpperTo=sm;D.prototype.modInt=hm;D.prototype.millerRabin=vm;D.prototype.clone=gg;D.prototype.intValue=mg;D.prototype.byteValue=yg;D.prototype.shortValue=vg;D.prototype.signum=Sg;D.prototype.toByteArray=wg;D.prototype.equals=Tg;D.prototype.min=Ag;D.prototype.max=_g;D.prototype.and=Rg;D.prototype.or=Bg;D.prototype.xor=Pg;D.prototype.andNot=Ng;D.prototype.not=Dg;D.prototype.shiftLeft=Lg;D.prototype.shiftRight=Og;D.prototype.getLowestSetBit=Vg;D.prototype.bitCount=Mg;D.prototype.testBit=Wg;D.prototype.setBit=Hg;D.prototype.clearBit=Kg;D.prototype.flipBit=qg;D.prototype.add=jg;D.prototype.subtract=zg;D.prototype.multiply=Qg;D.prototype.divide=Yg;D.prototype.remainder=Jg;D.prototype.divideAndRemainder=Zg;D.prototype.modPow=fm;D.prototype.modInverse=gm;D.prototype.pow=im;D.prototype.gcd=pm;D.prototype.isProbablePrime=ym;D.prototype.square=Xg});var Rn=de(function(t1,Iu){var sr=me();tr();Pe();var _u=Iu.exports=sr.sha1=sr.sha1||{};sr.md.sha1=sr.md.algorithms.sha1=_u;_u.create=function(){if(!ku)Sm();var e=null,t=sr.util.createBuffer(),n=Array(80),r={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];var i=r.messageLengthSize/4;for(var a=0;a<i;++a)r.fullMessageLength.push(0);return t=sr.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},r},r.start(),r.update=function(i,a){if(a==="utf8")i=sr.util.encodeUtf8(i);var s=i.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;if(t.putBytes(i),Au(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=sr.util.createBuffer();i.putBytes(t.bytes());var a=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=a&r.blockLength-1;i.putBytes(xo.substr(0,r.blockLength-s));var o,l,c=r.fullMessageLength[0]*8;for(var u=0;u<r.fullMessageLength.length-1;++u)o=r.fullMessageLength[u+1]*8,l=o/4294967296>>>0,c+=l,i.putInt32(c>>>0),c=o>>>0;i.putInt32(c);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};Au(d,n,i);var f=sr.util.createBuffer();return f.putInt32(d.h0),f.putInt32(d.h1),f.putInt32(d.h2),f.putInt32(d.h3),f.putInt32(d.h4),f},r};var xo=null,ku=!1;function Sm(){xo=String.fromCharCode(128),xo+=sr.util.fillString(String.fromCharCode(0),64),ku=!0}function Au(e,t,n){var r,i,a,s,o,l,c,u,d=n.length();while(d>=64){i=e.h0,a=e.h1,s=e.h2,o=e.h3,l=e.h4;for(u=0;u<16;++u)r=n.getInt32(),t[u]=r,c=o^a&(s^o),r=(i<<5|i>>>27)+c+l+1518500249+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=i,i=r;for(;u<20;++u)r=t[u-3]^t[u-8]^t[u-14]^t[u-16],r=r<<1|r>>>31,t[u]=r,c=o^a&(s^o),r=(i<<5|i>>>27)+c+l+1518500249+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=i,i=r;for(;u<32;++u)r=t[u-3]^t[u-8]^t[u-14]^t[u-16],r=r<<1|r>>>31,t[u]=r,c=a^s^o,r=(i<<5|i>>>27)+c+l+1859775393+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=i,i=r;for(;u<40;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,c=a^s^o,r=(i<<5|i>>>27)+c+l+1859775393+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=i,i=r;for(;u<60;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,c=a&s|o&(a^s),r=(i<<5|i>>>27)+c+l+2400959708+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=i,i=r;for(;u<80;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,c=a^s^o,r=(i<<5|i>>>27)+c+l+3395469782+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=i,i=r;e.h0=e.h0+i|0,e.h1=e.h1+a|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,e.h4=e.h4+l|0,d-=64}}});var So=de(function(r1,Bu){var or=me();Pe();Dt();Rn();var Ru=Bu.exports=or.pkcs1=or.pkcs1||{};Ru.encode_rsa_oaep=function(e,t,n){var r,i,a,s;if(typeof n==="string")r=n,i=arguments[3]||void 0,a=arguments[4]||void 0;else if(n){if(r=n.label||void 0,i=n.seed||void 0,a=n.md||void 0,n.mgf1&&n.mgf1.md)s=n.mgf1.md}if(!a)a=or.md.sha1.create();else a.start();if(!s)s=a;var o=Math.ceil(e.n.bitLength()/8),l=o-2*a.digestLength-2;if(t.length>l){var c=Error("RSAES-OAEP input message length is too long.");throw c.length=t.length,c.maxLength=l,c}if(!r)r="";a.update(r,"raw");var u=a.digest(),d="",f=l-t.length;for(var y=0;y<f;y++)d+="\x00";var p=u.getBytes()+d+"\x01"+t;if(!i)i=or.random.getBytes(a.digestLength);else if(i.length!==a.digestLength){var c=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw c.seedLength=i.length,c.digestLength=a.digestLength,c}var v=Oa(i,o-a.digestLength-1,s),x=or.util.xorBytes(p,v,p.length),b=Oa(x,a.digestLength,s),A=or.util.xorBytes(i,b,i.length);return"\x00"+A+x};Ru.decode_rsa_oaep=function(e,t,n){var r,i,a;if(typeof n==="string")r=n,i=arguments[3]||void 0;else if(n){if(r=n.label||void 0,i=n.md||void 0,n.mgf1&&n.mgf1.md)a=n.mgf1.md}var s=Math.ceil(e.n.bitLength()/8);if(t.length!==s){var x=Error("RSAES-OAEP encoded message length is invalid.");throw x.length=t.length,x.expectedLength=s,x}if(i===void 0)i=or.md.sha1.create();else i.start();if(!a)a=i;if(s<2*i.digestLength+2)throw Error("RSAES-OAEP key is too short for the hash function.");if(!r)r="";i.update(r,"raw");var o=i.digest().getBytes(),l=t.charAt(0),c=t.substring(1,i.digestLength+1),u=t.substring(1+i.digestLength),d=Oa(u,i.digestLength,a),f=or.util.xorBytes(c,d,c.length),y=Oa(f,s-i.digestLength-1,a),p=or.util.xorBytes(u,y,u.length),v=p.substring(0,i.digestLength),x=l!=="\x00";for(var b=0;b<i.digestLength;++b)x|=o.charAt(b)!==v.charAt(b);var A=1,E=i.digestLength;for(var k=i.digestLength;k<p.length;k++){var I=p.charCodeAt(k),R=I&1^1,M=A?65534:0;x|=I&M,A=A&R,E+=A}if(x||p.charCodeAt(E)!==1)throw Error("Invalid RSAES-OAEP padding.");return p.substring(E+1)};function Oa(e,t,n){if(!n)n=or.md.sha1.create();var r="",i=Math.ceil(t/n.digestLength);for(var a=0;a<i;++a){var s=String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255);n.start(),n.update(e+s),r+=n.digest().getBytes()}return r.substring(0,t)}});var Co=de(function(n1,bo){var Ur=me();Pe();Si();Dt();(function(){if(Ur.prime){bo.exports=Ur.prime;return}var e=bo.exports=Ur.prime=Ur.prime||{},t=Ur.jsbn.BigInteger,n=[6,4,2,4,2,4,6,2],r=new t(null);r.fromInt(30);var i=function(d,f){return d|f};e.generateProbablePrime=function(d,f,y){if(typeof f==="function")y=f,f={};f=f||{};var p=f.algorithm||"PRIMEINC";if(typeof p==="string")p={name:p};p.options=p.options||{};var v=f.prng||Ur.random,x={nextBytes:function(b){var A=v.getBytesSync(b.length);for(var E=0;E<b.length;++E)b[E]=A.charCodeAt(E)}};if(p.name==="PRIMEINC")return a(d,x,p.options,y);throw Error("Invalid prime generation algorithm: "+p.name)};function a(d,f,y,p){if("workers"in y)return l(d,f,y,p);return s(d,f,y,p)}function s(d,f,y,p){var v=c(d,f),x=0,b=u(v.bitLength());if("millerRabinTests"in y)b=y.millerRabinTests;var A=10;if("maxBlockTime"in y)A=y.maxBlockTime;o(v,d,f,x,b,A,p)}function o(d,f,y,p,v,x,b){var A=+new Date;do{if(d.bitLength()>f)d=c(f,y);if(d.isProbablePrime(v))return b(null,d);d.dAddOffset(n[p++%8],0)}while(x<0||+new Date-A<x);Ur.util.setImmediate(function(){o(d,f,y,p,v,x,b)})}function l(d,f,y,p){if(typeof Worker>"u")return s(d,f,y,p);var v=c(d,f),x=y.workers,b=y.workLoad||100,A=b*30/8,E=y.workerScript||"forge/prime.worker.js";if(x===-1)return Ur.util.estimateCores(function(I,R){if(I)R=2;x=R-1,k()});k();function k(){x=Math.max(1,x);var I=[];for(var R=0;R<x;++R)I[R]=new Worker(E);var M=x;for(var R=0;R<x;++R)I[R].addEventListener("message",O);var ee=!1;function O(K){if(ee)return;--M;var ie=K.data;if(ie.found){for(var ve=0;ve<I.length;++ve)I[ve].terminate();return ee=!0,p(null,new t(ie.prime,16))}if(v.bitLength()>d)v=c(d,f);var we=v.toString(16);K.target.postMessage({hex:we,workLoad:b}),v.dAddOffset(A,0)}}}function c(d,f){var y=new t(d,f),p=d-1;if(!y.testBit(p))y.bitwiseTo(t.ONE.shiftLeft(p),i,y);return y.dAddOffset(31-y.mod(r).byteValue(),0),y}function u(d){if(d<=100)return 27;if(d<=150)return 18;if(d<=200)return 15;if(d<=250)return 12;if(d<=300)return 9;if(d<=350)return 8;if(d<=400)return 7;if(d<=500)return 6;if(d<=600)return 5;if(d<=800)return 4;if(d<=1250)return 3;return 2}})()});var bi=de(function(i1,Vu){var re=me();qt();Si();Lr();So();Co();Dt();Pe();if(typeof ke>"u")ke=re.jsbn.BigInteger;var ke,Eo=re.util.isNodejs?li("crypto"):null,{asn1:_,util:Ot}=re;re.pki=re.pki||{};Vu.exports=re.pki.rsa=re.rsa=re.rsa||{};var fe=re.pki,bm=[6,4,2,4,2,4,6,2],Cm={name:"PrivateKeyInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},Em={name:"RSAPrivateKey",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},wm={name:"RSAPublicKey",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},Tm=re.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:_.Class.UNIVERSAL,type:_.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Am={name:"DigestInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:_.Class.UNIVERSAL,type:_.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:_.Class.UNIVERSAL,type:_.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:_.Class.UNIVERSAL,type:_.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},_m=function(e){var t;if(e.algorithm in fe.oids)t=fe.oids[e.algorithm];else{var n=Error("Unknown message digest algorithm.");throw n.algorithm=e.algorithm,n}var r=_.oidToDer(t).getBytes(),i=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[]),a=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[]);a.value.push(_.create(_.Class.UNIVERSAL,_.Type.OID,!1,r)),a.value.push(_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,""));var s=_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(a),i.value.push(s),_.toDer(i).getBytes()},Ou=function(e,t,n){if(n)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);if(!t.dP)t.dP=t.d.mod(t.p.subtract(ke.ONE));if(!t.dQ)t.dQ=t.d.mod(t.q.subtract(ke.ONE));if(!t.qInv)t.qInv=t.q.modInverse(t.p);var r;do r=new ke(re.util.bytesToHex(re.random.getBytes(t.n.bitLength()/8)),16);while(r.compareTo(t.n)>=0||!r.gcd(t.n).equals(ke.ONE));e=e.multiply(r.modPow(t.e,t.n)).mod(t.n);var i=e.mod(t.p).modPow(t.dP,t.p),a=e.mod(t.q).modPow(t.dQ,t.q);while(i.compareTo(a)<0)i=i.add(t.p);var s=i.subtract(a).multiply(t.qInv).mod(t.p).multiply(t.q).add(a);return s=s.multiply(r.modInverse(t.n)).mod(t.n),s};fe.rsa.encrypt=function(e,t,n){var r=n,i,a=Math.ceil(t.n.bitLength()/8);if(n!==!1&&n!==!0)r=n===2,i=Uu(e,t,n);else i=re.util.createBuffer(),i.putBytes(e);var s=new ke(i.toHex(),16),o=Ou(s,t,r),l=o.toString(16),c=re.util.createBuffer(),u=a-Math.ceil(l.length/2);while(u>0)c.putByte(0),--u;return c.putBytes(re.util.hexToBytes(l)),c.getBytes()};fe.rsa.decrypt=function(e,t,n,r){var i=Math.ceil(t.n.bitLength()/8);if(e.length!==i){var a=Error("Encrypted message length is invalid.");throw a.length=e.length,a.expected=i,a}var s=new ke(re.util.createBuffer(e).toHex(),16);if(s.compareTo(t.n)>=0)throw Error("Encrypted message is invalid.");var o=Ou(s,t,n),l=o.toString(16),c=re.util.createBuffer(),u=i-Math.ceil(l.length/2);while(u>0)c.putByte(0),--u;if(c.putBytes(re.util.hexToBytes(l)),r!==!1)return Ua(c.getBytes(),t,n);return c.getBytes()};fe.rsa.createKeyPairGenerationState=function(e,t,n){if(typeof e==="string")e=parseInt(e,10);e=e||2048,n=n||{};var r=n.prng||re.random,i={nextBytes:function(o){var l=r.getBytesSync(o.length);for(var c=0;c<o.length;++c)o[c]=l.charCodeAt(c)}},a=n.algorithm||"PRIMEINC",s;if(a==="PRIMEINC")s={algorithm:a,state:0,bits:e,rng:i,eInt:t||65537,e:new ke(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},s.e.fromInt(s.eInt);else throw Error("Invalid key generation algorithm: "+a);return s};fe.rsa.stepKeyPairGenerationState=function(e,t){if(!("algorithm"in e))e.algorithm="PRIMEINC";var n=new ke(null);n.fromInt(30);var r=0,i=function(d,f){return d|f},a=+new Date,s,o=0;while(e.keys===null&&(t<=0||o<t)){if(e.state===0){var l=e.p===null?e.pBits:e.qBits,c=l-1;if(e.pqState===0){if(e.num=new ke(l,e.rng),!e.num.testBit(c))e.num.bitwiseTo(ke.ONE.shiftLeft(c),i,e.num);e.num.dAddOffset(31-e.num.mod(n).byteValue(),0),r=0,++e.pqState}else if(e.pqState===1)if(e.num.bitLength()>l)e.pqState=0;else if(e.num.isProbablePrime(Im(e.num.bitLength())))++e.pqState;else e.num.dAddOffset(bm[r++%8],0);else if(e.pqState===2)e.pqState=e.num.subtract(ke.ONE).gcd(e.e).compareTo(ke.ONE)===0?3:0;else if(e.pqState===3){if(e.pqState=0,e.p===null)e.p=e.num;else e.q=e.num;if(e.p!==null&&e.q!==null)++e.state;e.num=null}}else if(e.state===1){if(e.p.compareTo(e.q)<0)e.num=e.p,e.p=e.q,e.q=e.num;++e.state}else if(e.state===2)e.p1=e.p.subtract(ke.ONE),e.q1=e.q.subtract(ke.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)if(e.phi.gcd(e.e).compareTo(ke.ONE)===0)++e.state;else e.p=null,e.q=null,e.state=0;else if(e.state===4)if(e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits)++e.state;else e.q=null,e.state=0;else if(e.state===5){var u=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)}}s=+new Date,o+=s-a,a=s}return e.keys!==null};fe.rsa.generateKeyPair=function(e,t,n,r){if(arguments.length===1){if(typeof e==="object")n=e,e=void 0;else if(typeof e==="function")r=e,e=void 0}else if(arguments.length===2)if(typeof e==="number"){if(typeof t==="function")r=t,t=void 0;else if(typeof t!=="number")n=t,t=void 0}else n=e,r=t,e=void 0,t=void 0;else if(arguments.length===3)if(typeof t==="number"){if(typeof n==="function")r=n,n=void 0}else r=n,n=t,t=void 0;if(n=n||{},e===void 0)e=n.bits||2048;if(t===void 0)t=n.e||65537;if(!re.options.usePureJavaScript&&!n.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(r){if(Pu("generateKeyPair"))return Eo.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(o,l,c){if(o)return r(o);r(null,{privateKey:fe.privateKeyFromPem(c),publicKey:fe.publicKeyFromPem(l)})});if(Nu("generateKey")&&Nu("exportKey"))return Ot.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Lu(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(o){return Ot.globalScope.crypto.subtle.exportKey("pkcs8",o.privateKey)}).then(void 0,function(o){r(o)}).then(function(o){if(o){var l=fe.privateKeyFromAsn1(_.fromDer(re.util.createBuffer(o)));r(null,{privateKey:l,publicKey:fe.setRsaPublicKey(l.n,l.e)})}});if(Du("generateKey")&&Du("exportKey")){var i=Ot.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Lu(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(o){var l=o.target.result,c=Ot.globalScope.msCrypto.subtle.exportKey("pkcs8",l.privateKey);c.oncomplete=function(u){var d=u.target.result,f=fe.privateKeyFromAsn1(_.fromDer(re.util.createBuffer(d)));r(null,{privateKey:f,publicKey:fe.setRsaPublicKey(f.n,f.e)})},c.onerror=function(u){r(u)}},i.onerror=function(o){r(o)};return}}else if(Pu("generateKeyPairSync")){var a=Eo.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:fe.privateKeyFromPem(a.privateKey),publicKey:fe.publicKeyFromPem(a.publicKey)}}}var s=fe.rsa.createKeyPairGenerationState(e,t,n);if(!r)return fe.rsa.stepKeyPairGenerationState(s,0),s.keys;km(s,n,r)};fe.setRsaPublicKey=fe.rsa.setPublicKey=function(e,t){var n={n:e,e:t};return n.encrypt=function(r,i,a){if(typeof i==="string")i=i.toUpperCase();else if(i===void 0)i="RSAES-PKCS1-V1_5";if(i==="RSAES-PKCS1-V1_5")i={encode:function(o,l,c){return Uu(o,l,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(o,l){return re.pkcs1.encode_rsa_oaep(l,o,a)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(o){return o}};else if(typeof i==="string")throw Error('Unsupported encryption scheme: "'+i+'".');var s=i.encode(r,n,!0);return fe.rsa.encrypt(s,n,!0)},n.verify=function(r,i,a,s){if(typeof a==="string")a=a.toUpperCase();else if(a===void 0)a="RSASSA-PKCS1-V1_5";if(s===void 0)s={_parseAllDigestBytes:!0,_skipPaddingChecks:!1};if(!("_parseAllDigestBytes"in s))s._parseAllDigestBytes=!0;if(!("_skipPaddingChecks"in s))s._skipPaddingChecks=!1;if(a==="RSASSA-PKCS1-V1_5")a={verify:function(l,c){c=Ua(c,n,!0,void 0,s);var u=_.fromDer(c,{parseAllBytes:s._parseAllDigestBytes}),d={},f=[];if(!_.validate(u,Am,d,f)||u.value.length!==2){var y=Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw y.errors=f,y}var p=_.derToOid(d.algorithmIdentifier);if(!(p===re.oids.md2||p===re.oids.md5||p===re.oids.sha1||p===re.oids.sha224||p===re.oids.sha256||p===re.oids.sha384||p===re.oids.sha512||p===re.oids["sha512-224"]||p===re.oids["sha512-256"])){var y=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw y.oid=p,y}if(p===re.oids.md2||p===re.oids.md5){if(!("parameters"in d))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}return l===d.digest}};else if(a==="NONE"||a==="NULL"||a===null)a={verify:function(l,c){return c=Ua(c,n,!0,void 0,s),l===c}};var o=fe.rsa.decrypt(i,n,!0,!1);return a.verify(r,o,n.n.bitLength())},n};fe.setRsaPrivateKey=fe.rsa.setPrivateKey=function(e,t,n,r,i,a,s,o){var l={n:e,e:t,d:n,p:r,q:i,dP:a,dQ:s,qInv:o};return l.decrypt=function(c,u,d){if(typeof u==="string")u=u.toUpperCase();else if(u===void 0)u="RSAES-PKCS1-V1_5";var f=fe.rsa.decrypt(c,l,!1,!1);if(u==="RSAES-PKCS1-V1_5")u={decode:Ua};else if(u==="RSA-OAEP"||u==="RSAES-OAEP")u={decode:function(y,p){return re.pkcs1.decode_rsa_oaep(p,y,d)}};else if(["RAW","NONE","NULL",null].indexOf(u)!==-1)u={decode:function(y){return y}};else throw Error('Unsupported encryption scheme: "'+u+'".');return u.decode(f,l,!1)},l.sign=function(c,u){var d=!1;if(typeof u==="string")u=u.toUpperCase();if(u===void 0||u==="RSASSA-PKCS1-V1_5")u={encode:_m},d=1;else if(u==="NONE"||u==="NULL"||u===null)u={encode:function(){return c}},d=1;var f=u.encode(c,l.n.bitLength());return fe.rsa.encrypt(f,l,d)},l};fe.wrapRsaPrivateKey=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(0).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(fe.oids.rsaEncryption).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")]),_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,_.toDer(e).getBytes())])};fe.privateKeyFromAsn1=function(e){var t={},n=[];if(_.validate(e,Cm,t,n))e=_.fromDer(re.util.createBuffer(t.privateKey));if(t={},n=[],!_.validate(e,Em,t,n)){var r=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw r.errors=n,r}var i,a,s,o,l,c,u,d;return i=re.util.createBuffer(t.privateKeyModulus).toHex(),a=re.util.createBuffer(t.privateKeyPublicExponent).toHex(),s=re.util.createBuffer(t.privateKeyPrivateExponent).toHex(),o=re.util.createBuffer(t.privateKeyPrime1).toHex(),l=re.util.createBuffer(t.privateKeyPrime2).toHex(),c=re.util.createBuffer(t.privateKeyExponent1).toHex(),u=re.util.createBuffer(t.privateKeyExponent2).toHex(),d=re.util.createBuffer(t.privateKeyCoefficient).toHex(),fe.setRsaPrivateKey(new ke(i,16),new ke(a,16),new ke(s,16),new ke(o,16),new ke(l,16),new ke(c,16),new ke(u,16),new ke(d,16))};fe.privateKeyToAsn1=fe.privateKeyToRSAPrivateKey=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(0).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.n)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.e)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.d)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.p)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.q)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.dP)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.dQ)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.qInv))])};fe.publicKeyFromAsn1=function(e){var t={},n=[];if(_.validate(e,Tm,t,n)){var r=_.derToOid(t.publicKeyOid);if(r!==fe.oids.rsaEncryption){var i=Error("Cannot read public key. Unknown OID.");throw i.oid=r,i}e=t.rsaPublicKey}if(n=[],!_.validate(e,wm,t,n)){var i=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=n,i}var a=re.util.createBuffer(t.publicKeyModulus).toHex(),s=re.util.createBuffer(t.publicKeyExponent).toHex();return fe.setRsaPublicKey(new ke(a,16),new ke(s,16))};fe.publicKeyToAsn1=fe.publicKeyToSubjectPublicKeyInfo=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(fe.oids.rsaEncryption).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")]),_.create(_.Class.UNIVERSAL,_.Type.BITSTRING,!1,[fe.publicKeyToRSAPublicKey(e)])])};fe.publicKeyToRSAPublicKey=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.n)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,lr(e.e))])};function Uu(e,t,n){var r=re.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var a=Error("Message is too long for PKCS#1 v1.5 padding.");throw a.length=e.length,a.max=i-11,a}r.putByte(0),r.putByte(n);var s=i-3-e.length,o;if(n===0||n===1){o=n===0?0:255;for(var l=0;l<s;++l)r.putByte(o)}else while(s>0){var c=0,u=re.random.getBytes(s);for(var l=0;l<s;++l)if(o=u.charCodeAt(l),o===0)++c;else r.putByte(o);s=c}return r.putByte(0),r.putBytes(e),r}function Ua(e,t,n,r,i){var a=Math.ceil(t.n.bitLength()/8),s=re.util.createBuffer(e),o=s.getByte(),l=s.getByte();if(o!==0||n&&l!==0&&l!==1||!n&&l!==2||n&&l===0&&typeof r>"u")throw Error("Encryption block is invalid.");var c=0;if(l===0){c=a-3-r;for(var u=0;u<c;++u)if(s.getByte()!==0)throw Error("Encryption block is invalid.")}else if(l===1){c=0;while(s.length()>1){if(s.getByte()!==255){--s.read;break}++c}if(c<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}else if(l===2){c=0;while(s.length()>1){if(s.getByte()===0){--s.read;break}++c}if(c<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}var d=s.getByte();if(d!==0||c!==a-3-s.length())throw Error("Encryption block is invalid.");return s.getBytes()}function km(e,t,n){if(typeof t==="function")n=t,t={};t=t||{};var r={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};if("prng"in t)r.prng=t.prng;i();function i(){a(e.pBits,function(o,l){if(o)return n(o);if(e.p=l,e.q!==null)return s(o,e.q);a(e.qBits,s)})}function a(o,l){re.prime.generateProbablePrime(o,r,l)}function s(o,l){if(o)return n(o);if(e.q=l,e.p.compareTo(e.q)<0){var c=e.p;e.p=e.q,e.q=c}if(e.p.subtract(ke.ONE).gcd(e.e).compareTo(ke.ONE)!==0){e.p=null,i();return}if(e.q.subtract(ke.ONE).gcd(e.e).compareTo(ke.ONE)!==0){e.q=null,a(e.qBits,s);return}if(e.p1=e.p.subtract(ke.ONE),e.q1=e.q.subtract(ke.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(ke.ONE)!==0){e.p=e.q=null,i();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,a(e.qBits,s);return}var u=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)},n(null,e.keys)}}function lr(e){var t=e.toString(16);if(t[0]>="8")t="00"+t;var n=re.util.hexToBytes(t);if(n.length>1&&(n.charCodeAt(0)===0&&(n.charCodeAt(1)&128)===0||n.charCodeAt(0)===255&&(n.charCodeAt(1)&128)===128))return n.substr(1);return n}function Im(e){if(e<=100)return 27;if(e<=150)return 18;if(e<=200)return 15;if(e<=250)return 12;if(e<=300)return 9;if(e<=350)return 8;if(e<=400)return 7;if(e<=500)return 6;if(e<=600)return 5;if(e<=800)return 4;if(e<=1250)return 3;return 2}function Pu(e){return re.util.isNodejs&&typeof Eo[e]==="function"}function Nu(e){return typeof Ot.globalScope<"u"&&typeof Ot.globalScope.crypto==="object"&&typeof Ot.globalScope.crypto.subtle==="object"&&typeof Ot.globalScope.crypto.subtle[e]==="function"}function Du(e){return typeof Ot.globalScope<"u"&&typeof Ot.globalScope.msCrypto==="object"&&typeof Ot.globalScope.msCrypto.subtle==="object"&&typeof Ot.globalScope.msCrypto.subtle[e]==="function"}function Lu(e){var t=re.util.hexToBytes(e.toString(16)),n=new Uint8Array(t.length);for(var r=0;r<t.length;++r)n[r]=t.charCodeAt(r);return n}});var To=de(function(a1,$u){var j=me();Dr();qt();vi();tr();Lr();Pa();an();Dt();go();bi();Pe();if(typeof wo>"u")wo=j.jsbn.BigInteger;var wo,B=j.asn1,ge=j.pki=j.pki||{};$u.exports=ge.pbe=j.pbe=j.pbe||{};var ln=ge.oids,Rm={name:"EncryptedPrivateKeyInfo",tagClass:B.Class.UNIVERSAL,type:B.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:B.Class.UNIVERSAL,type:B.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:B.Class.UNIVERSAL,type:B.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:B.Class.UNIVERSAL,type:B.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:B.Class.UNIVERSAL,type:B.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},Bm={name:"PBES2Algorithms",tagClass:B.Class.UNIVERSAL,type:B.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:B.Class.UNIVERSAL,type:B.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:B.Class.UNIVERSAL,type:B.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:B.Class.UNIVERSAL,type:B.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:B.Class.UNIVERSAL,type:B.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:B.Class.UNIVERSAL,type:B.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:B.Class.UNIVERSAL,type:B.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:B.Class.UNIVERSAL,type:B.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:B.Class.UNIVERSAL,type:B.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:B.Class.UNIVERSAL,type:B.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:B.Class.UNIVERSAL,type:B.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:B.Class.UNIVERSAL,type:B.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},Pm={name:"pkcs-12PbeParams",tagClass:B.Class.UNIVERSAL,type:B.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:B.Class.UNIVERSAL,type:B.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:B.Class.UNIVERSAL,type:B.Type.INTEGER,constructed:!1,capture:"iterations"}]};ge.encryptPrivateKeyInfo=function(e,t,n){n=n||{},n.saltSize=n.saltSize||8,n.count=n.count||2048,n.algorithm=n.algorithm||"aes128",n.prfAlgorithm=n.prfAlgorithm||"sha1";var r=j.random.getBytesSync(n.saltSize),i=n.count,a=B.integerToDer(i),s,o,l;if(n.algorithm.indexOf("aes")===0||n.algorithm==="des"){var c,u,d;switch(n.algorithm){case"aes128":s=16,c=16,u=ln["aes128-CBC"],d=j.aes.createEncryptionCipher;break;case"aes192":s=24,c=16,u=ln["aes192-CBC"],d=j.aes.createEncryptionCipher;break;case"aes256":s=32,c=16,u=ln["aes256-CBC"],d=j.aes.createEncryptionCipher;break;case"des":s=8,c=8,u=ln.desCBC,d=j.des.createEncryptionCipher;break;default:var f=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw f.algorithm=n.algorithm,f}var y="hmacWith"+n.prfAlgorithm.toUpperCase(),p=Wu(y),v=j.pkcs5.pbkdf2(t,r,i,s,p),x=j.random.getBytesSync(c),b=d(v);b.start(x),b.update(B.toDer(e)),b.finish(),l=b.output.getBytes();var A=Nm(r,a,s,y);o=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ln.pkcs5PBES2).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ln.pkcs5PBKDF2).getBytes()),A]),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(u).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,x)])])])}else if(n.algorithm==="3des"){s=24;var E=new j.util.ByteBuffer(r),v=ge.pbe.generatePkcs12Key(t,E,1,i,s),x=ge.pbe.generatePkcs12Key(t,E,2,i,s),b=j.des.createEncryptionCipher(v);b.start(x),b.update(B.toDer(e)),b.finish(),l=b.output.getBytes(),o=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ln["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,r),B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,a.getBytes())])])}else{var f=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw f.algorithm=n.algorithm,f}var k=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[o,B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,l)]);return k};ge.decryptPrivateKeyInfo=function(e,t){var n=null,r={},i=[];if(!B.validate(e,Rm,r,i)){var a=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw a.errors=i,a}var s=B.derToOid(r.encryptionOid),o=ge.pbe.getCipher(s,r.encryptionParams,t),l=j.util.createBuffer(r.encryptedData);if(o.update(l),o.finish())n=B.fromDer(o.output);return n};ge.encryptedPrivateKeyToPem=function(e,t){var n={type:"ENCRYPTED PRIVATE KEY",body:B.toDer(e).getBytes()};return j.pem.encode(n,{maxline:t})};ge.encryptedPrivateKeyFromPem=function(e){var t=j.pem.decode(e)[0];if(t.type!=="ENCRYPTED PRIVATE KEY"){var n=Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw n.headerType=t.type,n}if(t.procType&&t.procType.type==="ENCRYPTED")throw Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return B.fromDer(t.body)};ge.encryptRsaPrivateKey=function(e,t,n){if(n=n||{},!n.legacy){var r=ge.wrapRsaPrivateKey(ge.privateKeyToAsn1(e));return r=ge.encryptPrivateKeyInfo(r,t,n),ge.encryptedPrivateKeyToPem(r)}var i,a,s,o;switch(n.algorithm){case"aes128":i="AES-128-CBC",s=16,a=j.random.getBytesSync(16),o=j.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",s=24,a=j.random.getBytesSync(16),o=j.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",s=32,a=j.random.getBytesSync(16),o=j.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",s=24,a=j.random.getBytesSync(8),o=j.des.createEncryptionCipher;break;case"des":i="DES-CBC",s=8,a=j.random.getBytesSync(8),o=j.des.createEncryptionCipher;break;default:var l=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+n.algorithm+'".');throw l.algorithm=n.algorithm,l}var c=j.pbe.opensslDeriveBytes(t,a.substr(0,8),s),u=o(c);u.start(a),u.update(B.toDer(ge.privateKeyToAsn1(e))),u.finish();var d={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:j.util.bytesToHex(a).toUpperCase()},body:u.output.getBytes()};return j.pem.encode(d)};ge.decryptRsaPrivateKey=function(e,t){var n=null,r=j.pem.decode(e)[0];if(r.type!=="ENCRYPTED PRIVATE KEY"&&r.type!=="PRIVATE KEY"&&r.type!=="RSA PRIVATE KEY"){var i=Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw i.headerType=i,i}if(r.procType&&r.procType.type==="ENCRYPTED"){var a,s;switch(r.dekInfo.algorithm){case"DES-CBC":a=8,s=j.des.createDecryptionCipher;break;case"DES-EDE3-CBC":a=24,s=j.des.createDecryptionCipher;break;case"AES-128-CBC":a=16,s=j.aes.createDecryptionCipher;break;case"AES-192-CBC":a=24,s=j.aes.createDecryptionCipher;break;case"AES-256-CBC":a=32,s=j.aes.createDecryptionCipher;break;case"RC2-40-CBC":a=5,s=function(d){return j.rc2.createDecryptionCipher(d,40)};break;case"RC2-64-CBC":a=8,s=function(d){return j.rc2.createDecryptionCipher(d,64)};break;case"RC2-128-CBC":a=16,s=function(d){return j.rc2.createDecryptionCipher(d,128)};break;default:var i=Error('Could not decrypt private key; unsupported encryption algorithm "'+r.dekInfo.algorithm+'".');throw i.algorithm=r.dekInfo.algorithm,i}var o=j.util.hexToBytes(r.dekInfo.parameters),l=j.pbe.opensslDeriveBytes(t,o.substr(0,8),a),c=s(l);if(c.start(o),c.update(j.util.createBuffer(r.body)),c.finish())n=c.output.getBytes();else return n}else n=r.body;if(r.type==="ENCRYPTED PRIVATE KEY")n=ge.decryptPrivateKeyInfo(B.fromDer(n),t);else n=B.fromDer(n);if(n!==null)n=ge.privateKeyFromAsn1(n);return n};ge.pbe.generatePkcs12Key=function(e,t,n,r,i,a){var s,o;if(typeof a>"u"||a===null){if(!("sha1"in j.md))throw Error('"sha1" hash algorithm unavailable.');a=j.md.sha1.create()}var l=a.digestLength,c=a.blockLength,u=new j.util.ByteBuffer,d=new j.util.ByteBuffer;if(e!==null&&e!==void 0){for(o=0;o<e.length;o++)d.putInt16(e.charCodeAt(o));d.putInt16(0)}var f=d.length(),y=t.length(),p=new j.util.ByteBuffer;p.fillWithByte(n,c);var v=c*Math.ceil(y/c),x=new j.util.ByteBuffer;for(o=0;o<v;o++)x.putByte(t.at(o%y));var b=c*Math.ceil(f/c),A=new j.util.ByteBuffer;for(o=0;o<b;o++)A.putByte(d.at(o%f));var E=x;E.putBuffer(A);var k=Math.ceil(i/l);for(var I=1;I<=k;I++){var R=new j.util.ByteBuffer;R.putBytes(p.bytes()),R.putBytes(E.bytes());for(var M=0;M<r;M++)a.start(),a.update(R.getBytes()),R=a.digest();var ee=new j.util.ByteBuffer;for(o=0;o<c;o++)ee.putByte(R.at(o%l));var O=Math.ceil(y/c)+Math.ceil(f/c),K=new j.util.ByteBuffer;for(s=0;s<O;s++){var ie=new j.util.ByteBuffer(E.getBytes(c)),ve=511;for(o=ee.length()-1;o>=0;o--)ve=ve>>8,ve+=ee.at(o)+ie.at(o),ie.setAt(o,ve&255);K.putBuffer(ie)}E=K,u.putBuffer(R)}return u.truncate(u.length()-i),u};ge.pbe.getCipher=function(e,t,n){switch(e){case ge.oids.pkcs5PBES2:return ge.pbe.getCipherForPBES2(e,t,n);case ge.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case ge.oids["pbewithSHAAnd40BitRC2-CBC"]:return ge.pbe.getCipherForPKCS12PBE(e,t,n);default:var r=Error("Cannot read encrypted PBE data block. Unsupported OID.");throw r.oid=e,r.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],r}};ge.pbe.getCipherForPBES2=function(e,t,n){var r={},i=[];if(!B.validate(t,Bm,r,i)){var a=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw a.errors=i,a}if(e=B.derToOid(r.kdfOid),e!==ge.oids.pkcs5PBKDF2){var a=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw a.oid=e,a.supportedOids=["pkcs5PBKDF2"],a}if(e=B.derToOid(r.encOid),e!==ge.oids["aes128-CBC"]&&e!==ge.oids["aes192-CBC"]&&e!==ge.oids["aes256-CBC"]&&e!==ge.oids["des-EDE3-CBC"]&&e!==ge.oids.desCBC){var a=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw a.oid=e,a.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],a}var s=r.kdfSalt,o=j.util.createBuffer(r.kdfIterationCount);o=o.getInt(o.length()<<3);var l,c;switch(ge.oids[e]){case"aes128-CBC":l=16,c=j.aes.createDecryptionCipher;break;case"aes192-CBC":l=24,c=j.aes.createDecryptionCipher;break;case"aes256-CBC":l=32,c=j.aes.createDecryptionCipher;break;case"des-EDE3-CBC":l=24,c=j.des.createDecryptionCipher;break;case"desCBC":l=8,c=j.des.createDecryptionCipher;break}var u=Mu(r.prfOid),d=j.pkcs5.pbkdf2(n,s,o,l,u),f=r.encIv,y=c(d);return y.start(f),y};ge.pbe.getCipherForPKCS12PBE=function(e,t,n){var r={},i=[];if(!B.validate(t,Pm,r,i)){var a=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw a.errors=i,a}var s=j.util.createBuffer(r.salt),o=j.util.createBuffer(r.iterations);o=o.getInt(o.length()<<3);var l,c,u;switch(e){case ge.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:l=24,c=8,u=j.des.startDecrypting;break;case ge.oids["pbewithSHAAnd40BitRC2-CBC"]:l=5,c=8,u=function(v,x){var b=j.rc2.createDecryptionCipher(v,40);return b.start(x,null),b};break;default:var a=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw a.oid=e,a}var d=Mu(r.prfOid),f=ge.pbe.generatePkcs12Key(n,s,1,o,l,d);d.start();var y=ge.pbe.generatePkcs12Key(n,s,2,o,c,d);return u(f,y)};ge.pbe.opensslDeriveBytes=function(e,t,n,r){if(typeof r>"u"||r===null){if(!("md5"in j.md))throw Error('"md5" hash algorithm unavailable.');r=j.md.md5.create()}if(t===null)t="";var i=[Fu(r,e+t)];for(var a=16,s=1;a<n;++s,a+=16)i.push(Fu(r,i[s-1]+e+t));return i.join("").substr(0,n)};function Fu(e,t){return e.start().update(t).digest().getBytes()}function Mu(e){var t;if(!e)t="hmacWithSHA1";else if(t=ge.oids[B.derToOid(e)],!t){var n=Error("Unsupported PRF OID.");throw n.oid=e,n.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],n}return Wu(t)}function Wu(e){var t=j.md;switch(e){case"hmacWithSHA224":t=j.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var n=Error("Unsupported PRF algorithm.");throw n.algorithm=e,n.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],n}if(!t||!(e in t))throw Error("Unknown hash algorithm: "+e);return t[e].create()}function Nm(e,t,n,r){var i=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,e),B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,t.getBytes())]);if(r!=="hmacWithSHA1")i.value.push(B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,j.util.hexToBytes(n.toString(16))),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ge.oids[r]).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.NULL,!1,"")]));return i}});var Ao=de(function(s1,qu){var Bn=me();qt();Pe();var G=Bn.asn1,Pn=qu.exports=Bn.pkcs7asn1=Bn.pkcs7asn1||{};Bn.pkcs7=Bn.pkcs7||{};Bn.pkcs7.asn1=Pn;var Hu={name:"ContentInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};Pn.contentInfoValidator=Hu;var Ku={name:"EncryptedContentInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:G.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};Pn.envelopedDataValidator={name:"EnvelopedData",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:G.Class.UNIVERSAL,type:G.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(Ku)};Pn.encryptedDataValidator={name:"EncryptedData",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"}].concat(Ku)};var Dm={name:"SignerInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:G.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:G.Class.UNIVERSAL,type:G.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:G.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};Pn.signedDataValidator={name:"SignedData",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:G.Class.UNIVERSAL,type:G.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},Hu,{name:"SignedData.Certificates",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:G.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:G.Class.UNIVERSAL,type:G.Type.SET,capture:"signerInfos",optional:!0,value:[Dm]}]};Pn.recipientInfoValidator={name:"RecipientInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:G.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:G.Class.UNIVERSAL,type:G.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var _o=de(function(o1,Gu){var cn=me();Pe();cn.mgf=cn.mgf||{};var Lm=Gu.exports=cn.mgf.mgf1=cn.mgf1=cn.mgf1||{};Lm.create=function(e){var t={generate:function(n,r){var i=new cn.util.ByteBuffer,a=Math.ceil(r/e.digestLength);for(var s=0;s<a;s++){var o=new cn.util.ByteBuffer;o.putInt32(s),e.start(),e.update(n+o.getBytes()),i.putBuffer(e.digest())}return i.truncate(i.length()-r),i.getBytes()}};return t}});var zu=de(function(l1,ju){var Va=me();_o();ju.exports=Va.mgf=Va.mgf||{};Va.mgf.mgf1=Va.mgf1});var Fa=de(function(c1,Qu){var un=me();Dt();Pe();var Om=Qu.exports=un.pss=un.pss||{};Om.create=function(e){if(arguments.length===3)e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]};var t=e.md,n=e.mgf,r=t.digestLength,i=e.salt||null;if(typeof i==="string")i=un.util.createBuffer(i);var a;if("saltLength"in e)a=e.saltLength;else if(i!==null)a=i.length();else throw Error("Salt length not specified or specific salt not given.");if(i!==null&&i.length()!==a)throw Error("Given salt length does not match length of given salt.");var s=e.prng||un.random,o={};return o.encode=function(l,c){var u,d=c-1,f=Math.ceil(d/8),y=l.digest().getBytes();if(f<r+a+2)throw Error("Message is too long to encrypt.");var p;if(i===null)p=s.getBytesSync(a);else p=i.bytes();var v=new un.util.ByteBuffer;v.fillWithByte(0,8),v.putBytes(y),v.putBytes(p),t.start(),t.update(v.getBytes());var x=t.digest().getBytes(),b=new un.util.ByteBuffer;b.fillWithByte(0,f-a-r-2),b.putByte(1),b.putBytes(p);var A=b.getBytes(),E=f-r-1,k=n.generate(x,E),I="";for(u=0;u<E;u++)I+=String.fromCharCode(A.charCodeAt(u)^k.charCodeAt(u));var R=65280>>8*f-d&255;return I=String.fromCharCode(I.charCodeAt(0)&~R)+I.substr(1),I+x+String.fromCharCode(188)},o.verify=function(l,c,u){var d,f=u-1,y=Math.ceil(f/8);if(c=c.substr(-y),y<r+a+2)throw Error("Inconsistent parameters to PSS signature verification.");if(c.charCodeAt(y-1)!==188)throw Error("Encoded message does not end in 0xBC.");var p=y-r-1,v=c.substr(0,p),x=c.substr(p,r),b=65280>>8*y-f&255;if((v.charCodeAt(0)&b)!==0)throw Error("Bits beyond keysize not zero as expected.");var A=n.generate(x,p),E="";for(d=0;d<p;d++)E+=String.fromCharCode(v.charCodeAt(d)^A.charCodeAt(d));E=String.fromCharCode(E.charCodeAt(0)&~b)+E.substr(1);var k=y-r-a-2;for(d=0;d<k;d++)if(E.charCodeAt(d)!==0)throw Error("Leftmost octets not zero as expected");if(E.charCodeAt(k)!==1)throw Error("Inconsistent PSS signature, 0x01 marker not found");var I=E.substr(-a),R=new un.util.ByteBuffer;R.fillWithByte(0,8),R.putBytes(l),R.putBytes(I),t.start(),t.update(R.getBytes());var M=t.digest().getBytes();return x===M},o}});var $a=de(function(u1,ed){var ne=me();Dr();qt();vi();tr();zu();Lr();an();Fa();bi();Pe();var h=ne.asn1,F=ed.exports=ne.pki=ne.pki||{},Be=F.oids,Ye={};Ye.CN=Be.commonName;Ye.commonName="CN";Ye.C=Be.countryName;Ye.countryName="C";Ye.L=Be.localityName;Ye.localityName="L";Ye.ST=Be.stateOrProvinceName;Ye.stateOrProvinceName="ST";Ye.O=Be.organizationName;Ye.organizationName="O";Ye.OU=Be.organizationalUnitName;Ye.organizationalUnitName="OU";Ye.E=Be.emailAddress;Ye.emailAddress="E";var Yu=ne.pki.rsa.publicKeyValidator,Um={name:"Certificate",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:h.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:h.Class.UNIVERSAL,type:h.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:h.Class.UNIVERSAL,type:h.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:h.Class.UNIVERSAL,type:h.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:h.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:h.Class.UNIVERSAL,type:h.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:h.Class.UNIVERSAL,type:h.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:h.Class.UNIVERSAL,type:h.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:h.Class.UNIVERSAL,type:h.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},Yu,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:h.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:h.Class.UNIVERSAL,type:h.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:h.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:h.Class.UNIVERSAL,type:h.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:h.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:h.Class.UNIVERSAL,type:h.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:h.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:h.Class.UNIVERSAL,type:h.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},Vm={name:"rsapss",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:h.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:h.Class.UNIVERSAL,type:h.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:h.Class.UNIVERSAL,type:h.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:h.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:h.Class.UNIVERSAL,type:h.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:h.Class.UNIVERSAL,type:h.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:h.Class.UNIVERSAL,type:h.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:h.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:h.Class.UNIVERSAL,type:h.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:h.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:h.Class.UNIVERSAL,type:h.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},Fm={name:"CertificationRequestInfo",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:h.Class.UNIVERSAL,type:h.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},Yu,{name:"CertificationRequestInfo.attributes",tagClass:h.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:h.Class.UNIVERSAL,type:h.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:h.Class.UNIVERSAL,type:h.Type.SET,constructed:!0}]}]}]},Mm={name:"CertificationRequest",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[Fm,{name:"CertificationRequest.signatureAlgorithm",tagClass:h.Class.UNIVERSAL,type:h.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:h.Class.UNIVERSAL,type:h.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:h.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:h.Class.UNIVERSAL,type:h.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};F.RDNAttributesAsArray=function(e,t){var n=[],r,i,a;for(var s=0;s<e.value.length;++s){r=e.value[s];for(var o=0;o<r.value.length;++o){if(a={},i=r.value[o],a.type=h.derToOid(i.value[0].value),a.value=i.value[1].value,a.valueTagClass=i.value[1].type,a.type in Be){if(a.name=Be[a.type],a.name in Ye)a.shortName=Ye[a.name]}if(t)t.update(a.type),t.update(a.value);n.push(a)}}return n};F.CRIAttributesAsArray=function(e){var t=[];for(var n=0;n<e.length;++n){var r=e[n],i=h.derToOid(r.value[0].value),a=r.value[1].value;for(var s=0;s<a.length;++s){var o={};if(o.type=i,o.value=a[s].value,o.valueTagClass=a[s].type,o.type in Be){if(o.name=Be[o.type],o.name in Ye)o.shortName=Ye[o.name]}if(o.type===Be.extensionRequest){o.extensions=[];for(var l=0;l<o.value.length;++l)o.extensions.push(F.certificateExtensionFromAsn1(o.value[l]))}t.push(o)}}return t};function Vr(e,t){if(typeof t==="string")t={shortName:t};var n=null,r;for(var i=0;n===null&&i<e.attributes.length;++i)if(r=e.attributes[i],t.type&&t.type===r.type)n=r;else if(t.name&&t.name===r.name)n=r;else if(t.shortName&&t.shortName===r.shortName)n=r;return n}var Ma=function(e,t,n){var r={};if(e!==Be["RSASSA-PSS"])return r;if(n)r={hash:{algorithmOid:Be.sha1},mgf:{algorithmOid:Be.mgf1,hash:{algorithmOid:Be.sha1}},saltLength:20};var i={},a=[];if(!h.validate(t,Vm,i,a)){var s=Error("Cannot read RSASSA-PSS parameter block.");throw s.errors=a,s}if(i.hashOid!==void 0)r.hash=r.hash||{},r.hash.algorithmOid=h.derToOid(i.hashOid);if(i.maskGenOid!==void 0)r.mgf=r.mgf||{},r.mgf.algorithmOid=h.derToOid(i.maskGenOid),r.mgf.hash=r.mgf.hash||{},r.mgf.hash.algorithmOid=h.derToOid(i.maskGenHashOid);if(i.saltLength!==void 0)r.saltLength=i.saltLength.charCodeAt(0);return r},Wa=function(e){switch(Be[e.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return ne.md.sha1.create();case"md5WithRSAEncryption":return ne.md.md5.create();case"sha256WithRSAEncryption":return ne.md.sha256.create();case"sha384WithRSAEncryption":return ne.md.sha384.create();case"sha512WithRSAEncryption":return ne.md.sha512.create();case"RSASSA-PSS":return ne.md.sha256.create();default:var t=Error("Could not compute "+e.type+" digest. Unknown signature OID.");throw t.signatureOid=e.signatureOid,t}},Ju=function(e){var t=e.certificate,n;switch(t.signatureOid){case Be.sha1WithRSAEncryption:case Be.sha1WithRSASignature:break;case Be["RSASSA-PSS"]:var r,i;if(r=Be[t.signatureParameters.mgf.hash.algorithmOid],r===void 0||ne.md[r]===void 0){var a=Error("Unsupported MGF hash function.");throw a.oid=t.signatureParameters.mgf.hash.algorithmOid,a.name=r,a}if(i=Be[t.signatureParameters.mgf.algorithmOid],i===void 0||ne.mgf[i]===void 0){var a=Error("Unsupported MGF function.");throw a.oid=t.signatureParameters.mgf.algorithmOid,a.name=i,a}if(i=ne.mgf[i].create(ne.md[r].create()),r=Be[t.signatureParameters.hash.algorithmOid],r===void 0||ne.md[r]===void 0){var a=Error("Unsupported RSASSA-PSS hash function.");throw a.oid=t.signatureParameters.hash.algorithmOid,a.name=r,a}n=ne.pss.create(ne.md[r].create(),i,t.signatureParameters.saltLength);break}return t.publicKey.verify(e.md.digest().getBytes(),e.signature,n)};F.certificateFromPem=function(e,t,n){var r=ne.pem.decode(e)[0];if(r.type!=="CERTIFICATE"&&r.type!=="X509 CERTIFICATE"&&r.type!=="TRUSTED CERTIFICATE"){var i=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw i.headerType=r.type,i}if(r.procType&&r.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var a=h.fromDer(r.body,n);return F.certificateFromAsn1(a,t)};F.certificateToPem=function(e,t){var n={type:"CERTIFICATE",body:h.toDer(F.certificateToAsn1(e)).getBytes()};return ne.pem.encode(n,{maxline:t})};F.publicKeyFromPem=function(e){var t=ne.pem.decode(e)[0];if(t.type!=="PUBLIC KEY"&&t.type!=="RSA PUBLIC KEY"){var n=Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw n.headerType=t.type,n}if(t.procType&&t.procType.type==="ENCRYPTED")throw Error("Could not convert public key from PEM; PEM is encrypted.");var r=h.fromDer(t.body);return F.publicKeyFromAsn1(r)};F.publicKeyToPem=function(e,t){var n={type:"PUBLIC KEY",body:h.toDer(F.publicKeyToAsn1(e)).getBytes()};return ne.pem.encode(n,{maxline:t})};F.publicKeyToRSAPublicKeyPem=function(e,t){var n={type:"RSA PUBLIC KEY",body:h.toDer(F.publicKeyToRSAPublicKey(e)).getBytes()};return ne.pem.encode(n,{maxline:t})};F.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||ne.md.sha1.create(),r=t.type||"RSAPublicKey",i;switch(r){case"RSAPublicKey":i=h.toDer(F.publicKeyToRSAPublicKey(e)).getBytes();break;case"SubjectPublicKeyInfo":i=h.toDer(F.publicKeyToAsn1(e)).getBytes();break;default:throw Error('Unknown fingerprint type "'+t.type+'".')}n.start(),n.update(i);var a=n.digest();if(t.encoding==="hex"){var s=a.toHex();if(t.delimiter)return s.match(/.{2}/g).join(t.delimiter);return s}else if(t.encoding==="binary")return a.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return a};F.certificationRequestFromPem=function(e,t,n){var r=ne.pem.decode(e)[0];if(r.type!=="CERTIFICATE REQUEST"){var i=Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw i.headerType=r.type,i}if(r.procType&&r.procType.type==="ENCRYPTED")throw Error("Could not convert certification request from PEM; PEM is encrypted.");var a=h.fromDer(r.body,n);return F.certificationRequestFromAsn1(a,t)};F.certificationRequestToPem=function(e,t){var n={type:"CERTIFICATE REQUEST",body:h.toDer(F.certificationRequestToAsn1(e)).getBytes()};return ne.pem.encode(n,{maxline:t})};F.createCertificate=function(){var e={};return e.version=2,e.serialNumber="00",e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.validity={},e.validity.notBefore=new Date,e.validity.notAfter=new Date,e.issuer={},e.issuer.getField=function(t){return Vr(e.issuer,t)},e.issuer.addField=function(t){Ut([t]),e.issuer.attributes.push(t)},e.issuer.attributes=[],e.issuer.hash=null,e.subject={},e.subject.getField=function(t){return Vr(e.subject,t)},e.subject.addField=function(t){Ut([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.extensions=[],e.publicKey=null,e.md=null,e.setSubject=function(t,n){if(Ut(t),e.subject.attributes=t,delete e.subject.uniqueId,n)e.subject.uniqueId=n;e.subject.hash=null},e.setIssuer=function(t,n){if(Ut(t),e.issuer.attributes=t,delete e.issuer.uniqueId,n)e.issuer.uniqueId=n;e.issuer.hash=null},e.setExtensions=function(t){for(var n=0;n<t.length;++n)Zu(t[n],{cert:e});e.extensions=t},e.getExtension=function(t){if(typeof t==="string")t={name:t};var n=null,r;for(var i=0;n===null&&i<e.extensions.length;++i)if(r=e.extensions[i],t.id&&r.id===t.id)n=r;else if(t.name&&r.name===t.name)n=r;return n},e.sign=function(t,n){e.md=n||ne.md.sha1.create();var r=Be[e.md.algorithm+"WithRSAEncryption"];if(!r){var i=Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw i.algorithm=e.md.algorithm,i}e.signatureOid=e.siginfo.algorithmOid=r,e.tbsCertificate=F.getTBSCertificate(e);var a=h.toDer(e.tbsCertificate);e.md.update(a.getBytes()),e.signature=t.sign(e.md)},e.verify=function(t){var n=!1;if(!e.issued(t)){var r=t.issuer,i=e.subject,a=Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw a.expectedIssuer=i.attributes,a.actualIssuer=r.attributes,a}var s=t.md;if(s===null){s=Wa({signatureOid:t.signatureOid,type:"certificate"});var o=t.tbsCertificate||F.getTBSCertificate(t),l=h.toDer(o);s.update(l.getBytes())}if(s!==null)n=Ju({certificate:e,md:s,signature:t.signature});return n},e.isIssuer=function(t){var n=!1,r=e.issuer,i=t.subject;if(r.hash&&i.hash)n=r.hash===i.hash;else if(r.attributes.length===i.attributes.length){n=!0;var a,s;for(var o=0;n&&o<r.attributes.length;++o)if(a=r.attributes[o],s=i.attributes[o],a.type!==s.type||a.value!==s.value)n=!1}return n},e.issued=function(t){return t.isIssuer(e)},e.generateSubjectKeyIdentifier=function(){return F.getPublicKeyFingerprint(e.publicKey,{type:"RSAPublicKey"})},e.verifySubjectKeyIdentifier=function(){var t=Be.subjectKeyIdentifier;for(var n=0;n<e.extensions.length;++n){var r=e.extensions[n];if(r.id===t){var i=e.generateSubjectKeyIdentifier().getBytes();return ne.util.hexToBytes(r.subjectKeyIdentifier)===i}}return!1},e};F.certificateFromAsn1=function(e,t){var n={},r=[];if(!h.validate(e,Um,n,r)){var i=Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw i.errors=r,i}var a=h.derToOid(n.publicKeyOid);if(a!==F.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var s=F.createCertificate();s.version=n.certVersion?n.certVersion.charCodeAt(0):0;var o=ne.util.createBuffer(n.certSerialNumber);s.serialNumber=o.toHex(),s.signatureOid=ne.asn1.derToOid(n.certSignatureOid),s.signatureParameters=Ma(s.signatureOid,n.certSignatureParams,!0),s.siginfo.algorithmOid=ne.asn1.derToOid(n.certinfoSignatureOid),s.siginfo.parameters=Ma(s.siginfo.algorithmOid,n.certinfoSignatureParams,!1),s.signature=n.certSignature;var l=[];if(n.certValidity1UTCTime!==void 0)l.push(h.utcTimeToDate(n.certValidity1UTCTime));if(n.certValidity2GeneralizedTime!==void 0)l.push(h.generalizedTimeToDate(n.certValidity2GeneralizedTime));if(n.certValidity3UTCTime!==void 0)l.push(h.utcTimeToDate(n.certValidity3UTCTime));if(n.certValidity4GeneralizedTime!==void 0)l.push(h.generalizedTimeToDate(n.certValidity4GeneralizedTime));if(l.length>2)throw Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(l.length<2)throw Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(s.validity.notBefore=l[0],s.validity.notAfter=l[1],s.tbsCertificate=n.tbsCertificate,t){s.md=Wa({signatureOid:s.signatureOid,type:"certificate"});var c=h.toDer(s.tbsCertificate);s.md.update(c.getBytes())}var u=ne.md.sha1.create(),d=h.toDer(n.certIssuer);if(u.update(d.getBytes()),s.issuer.getField=function(p){return Vr(s.issuer,p)},s.issuer.addField=function(p){Ut([p]),s.issuer.attributes.push(p)},s.issuer.attributes=F.RDNAttributesAsArray(n.certIssuer),n.certIssuerUniqueId)s.issuer.uniqueId=n.certIssuerUniqueId;s.issuer.hash=u.digest().toHex();var f=ne.md.sha1.create(),y=h.toDer(n.certSubject);if(f.update(y.getBytes()),s.subject.getField=function(p){return Vr(s.subject,p)},s.subject.addField=function(p){Ut([p]),s.subject.attributes.push(p)},s.subject.attributes=F.RDNAttributesAsArray(n.certSubject),n.certSubjectUniqueId)s.subject.uniqueId=n.certSubjectUniqueId;if(s.subject.hash=f.digest().toHex(),n.certExtensions)s.extensions=F.certificateExtensionsFromAsn1(n.certExtensions);else s.extensions=[];return s.publicKey=F.publicKeyFromAsn1(n.subjectPublicKeyInfo),s};F.certificateExtensionsFromAsn1=function(e){var t=[];for(var n=0;n<e.value.length;++n){var r=e.value[n];for(var i=0;i<r.value.length;++i)t.push(F.certificateExtensionFromAsn1(r.value[i]))}return t};F.certificateExtensionFromAsn1=function(e){var t={};if(t.id=h.derToOid(e.value[0].value),t.critical=!1,e.value[1].type===h.Type.BOOLEAN)t.critical=e.value[1].value.charCodeAt(0)!==0,t.value=e.value[2].value;else t.value=e.value[1].value;if(t.id in Be){if(t.name=Be[t.id],t.name==="keyUsage"){var n=h.fromDer(t.value),r=0,i=0;if(n.value.length>1)r=n.value.charCodeAt(1),i=n.value.length>2?n.value.charCodeAt(2):0;t.digitalSignature=(r&128)===128,t.nonRepudiation=(r&64)===64,t.keyEncipherment=(r&32)===32,t.dataEncipherment=(r&16)===16,t.keyAgreement=(r&8)===8,t.keyCertSign=(r&4)===4,t.cRLSign=(r&2)===2,t.encipherOnly=(r&1)===1,t.decipherOnly=(i&128)===128}else if(t.name==="basicConstraints"){var n=h.fromDer(t.value);if(n.value.length>0&&n.value[0].type===h.Type.BOOLEAN)t.cA=n.value[0].value.charCodeAt(0)!==0;else t.cA=!1;var a=null;if(n.value.length>0&&n.value[0].type===h.Type.INTEGER)a=n.value[0].value;else if(n.value.length>1)a=n.value[1].value;if(a!==null)t.pathLenConstraint=h.derToInteger(a)}else if(t.name==="extKeyUsage"){var n=h.fromDer(t.value);for(var s=0;s<n.value.length;++s){var o=h.derToOid(n.value[s].value);if(o in Be)t[Be[o]]=!0;else t[o]=!0}}else if(t.name==="nsCertType"){var n=h.fromDer(t.value),r=0;if(n.value.length>1)r=n.value.charCodeAt(1);t.client=(r&128)===128,t.server=(r&64)===64,t.email=(r&32)===32,t.objsign=(r&16)===16,t.reserved=(r&8)===8,t.sslCA=(r&4)===4,t.emailCA=(r&2)===2,t.objCA=(r&1)===1}else if(t.name==="subjectAltName"||t.name==="issuerAltName"){t.altNames=[];var l,n=h.fromDer(t.value);for(var c=0;c<n.value.length;++c){l=n.value[c];var u={type:l.type,value:l.value};switch(t.altNames.push(u),l.type){case 1:case 2:case 6:break;case 7:u.ip=ne.util.bytesToIP(l.value);break;case 8:u.oid=h.derToOid(l.value);break;default:}}}else if(t.name==="subjectKeyIdentifier"){var n=h.fromDer(t.value);t.subjectKeyIdentifier=ne.util.bytesToHex(n.value)}}return t};F.certificationRequestFromAsn1=function(e,t){var n={},r=[];if(!h.validate(e,Mm,n,r)){var i=Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw i.errors=r,i}var a=h.derToOid(n.publicKeyOid);if(a!==F.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var s=F.createCertificationRequest();if(s.version=n.csrVersion?n.csrVersion.charCodeAt(0):0,s.signatureOid=ne.asn1.derToOid(n.csrSignatureOid),s.signatureParameters=Ma(s.signatureOid,n.csrSignatureParams,!0),s.siginfo.algorithmOid=ne.asn1.derToOid(n.csrSignatureOid),s.siginfo.parameters=Ma(s.siginfo.algorithmOid,n.csrSignatureParams,!1),s.signature=n.csrSignature,s.certificationRequestInfo=n.certificationRequestInfo,t){s.md=Wa({signatureOid:s.signatureOid,type:"certification request"});var o=h.toDer(s.certificationRequestInfo);s.md.update(o.getBytes())}var l=ne.md.sha1.create();return s.subject.getField=function(c){return Vr(s.subject,c)},s.subject.addField=function(c){Ut([c]),s.subject.attributes.push(c)},s.subject.attributes=F.RDNAttributesAsArray(n.certificationRequestInfoSubject,l),s.subject.hash=l.digest().toHex(),s.publicKey=F.publicKeyFromAsn1(n.subjectPublicKeyInfo),s.getAttribute=function(c){return Vr(s,c)},s.addAttribute=function(c){Ut([c]),s.attributes.push(c)},s.attributes=F.CRIAttributesAsArray(n.certificationRequestInfoAttributes||[]),s};F.createCertificationRequest=function(){var e={};return e.version=0,e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.subject={},e.subject.getField=function(t){return Vr(e.subject,t)},e.subject.addField=function(t){Ut([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.publicKey=null,e.attributes=[],e.getAttribute=function(t){return Vr(e,t)},e.addAttribute=function(t){Ut([t]),e.attributes.push(t)},e.md=null,e.setSubject=function(t){Ut(t),e.subject.attributes=t,e.subject.hash=null},e.setAttributes=function(t){Ut(t),e.attributes=t},e.sign=function(t,n){e.md=n||ne.md.sha1.create();var r=Be[e.md.algorithm+"WithRSAEncryption"];if(!r){var i=Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw i.algorithm=e.md.algorithm,i}e.signatureOid=e.siginfo.algorithmOid=r,e.certificationRequestInfo=F.getCertificationRequestInfo(e);var a=h.toDer(e.certificationRequestInfo);e.md.update(a.getBytes()),e.signature=t.sign(e.md)},e.verify=function(){var t=!1,n=e.md;if(n===null){n=Wa({signatureOid:e.signatureOid,type:"certification request"});var r=e.certificationRequestInfo||F.getCertificationRequestInfo(e),i=h.toDer(r);n.update(i.getBytes())}if(n!==null)t=Ju({certificate:e,md:n,signature:e.signature});return t},e};function Nn(e){var t=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[]),n,r,i=e.attributes;for(var a=0;a<i.length;++a){n=i[a];var s=n.value,o=h.Type.PRINTABLESTRING;if("valueTagClass"in n){if(o=n.valueTagClass,o===h.Type.UTF8)s=ne.util.encodeUtf8(s)}r=h.create(h.Class.UNIVERSAL,h.Type.SET,!0,[h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(n.type).getBytes()),h.create(h.Class.UNIVERSAL,o,!1,s)])]),t.value.push(r)}return t}function Ut(e){var t;for(var n=0;n<e.length;++n){if(t=e[n],typeof t.name>"u"){if(t.type&&t.type in F.oids)t.name=F.oids[t.type];else if(t.shortName&&t.shortName in Ye)t.name=F.oids[Ye[t.shortName]]}if(typeof t.type>"u")if(t.name&&t.name in F.oids)t.type=F.oids[t.name];else{var r=Error("Attribute type not specified.");throw r.attribute=t,r}if(typeof t.shortName>"u"){if(t.name&&t.name in Ye)t.shortName=Ye[t.name]}if(t.type===Be.extensionRequest){if(t.valueConstructed=!0,t.valueTagClass=h.Type.SEQUENCE,!t.value&&t.extensions){t.value=[];for(var i=0;i<t.extensions.length;++i)t.value.push(F.certificateExtensionToAsn1(Zu(t.extensions[i])))}}if(typeof t.value>"u"){var r=Error("Attribute value not specified.");throw r.attribute=t,r}}}function Zu(e,t){if(t=t||{},typeof e.name>"u"){if(e.id&&e.id in F.oids)e.name=F.oids[e.id]}if(typeof e.id>"u")if(e.name&&e.name in F.oids)e.id=F.oids[e.name];else{var n=Error("Extension ID not specified.");throw n.extension=e,n}if(typeof e.value<"u")return e;if(e.name==="keyUsage"){var r=0,i=0,a=0;if(e.digitalSignature)i|=128,r=7;if(e.nonRepudiation)i|=64,r=6;if(e.keyEncipherment)i|=32,r=5;if(e.dataEncipherment)i|=16,r=4;if(e.keyAgreement)i|=8,r=3;if(e.keyCertSign)i|=4,r=2;if(e.cRLSign)i|=2,r=1;if(e.encipherOnly)i|=1,r=0;if(e.decipherOnly)a|=128,r=7;var s=String.fromCharCode(r);if(a!==0)s+=String.fromCharCode(i)+String.fromCharCode(a);else if(i!==0)s+=String.fromCharCode(i);e.value=h.create(h.Class.UNIVERSAL,h.Type.BITSTRING,!1,s)}else if(e.name==="basicConstraints"){if(e.value=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[]),e.cA)e.value.value.push(h.create(h.Class.UNIVERSAL,h.Type.BOOLEAN,!1,String.fromCharCode(255)));if("pathLenConstraint"in e)e.value.value.push(h.create(h.Class.UNIVERSAL,h.Type.INTEGER,!1,h.integerToDer(e.pathLenConstraint).getBytes()))}else if(e.name==="extKeyUsage"){e.value=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[]);var o=e.value.value;for(var l in e){if(e[l]!==!0)continue;if(l in Be)o.push(h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(Be[l]).getBytes()));else if(l.indexOf(".")!==-1)o.push(h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(l).getBytes()))}}else if(e.name==="nsCertType"){var r=0,i=0;if(e.client)i|=128,r=7;if(e.server)i|=64,r=6;if(e.email)i|=32,r=5;if(e.objsign)i|=16,r=4;if(e.reserved)i|=8,r=3;if(e.sslCA)i|=4,r=2;if(e.emailCA)i|=2,r=1;if(e.objCA)i|=1,r=0;var s=String.fromCharCode(r);if(i!==0)s+=String.fromCharCode(i);e.value=h.create(h.Class.UNIVERSAL,h.Type.BITSTRING,!1,s)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[]);var c;for(var u=0;u<e.altNames.length;++u){c=e.altNames[u];var s=c.value;if(c.type===7&&c.ip){if(s=ne.util.bytesFromIP(c.ip),s===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(c.type===8)if(c.oid)s=h.oidToDer(h.oidToDer(c.oid));else s=h.oidToDer(s);e.value.value.push(h.create(h.Class.CONTEXT_SPECIFIC,c.type,!1,s))}}else if(e.name==="nsComment"&&t.cert){if(!/^[\x00-\x7F]*$/.test(e.comment)||e.comment.length<1||e.comment.length>128)throw Error('Invalid "nsComment" content.');e.value=h.create(h.Class.UNIVERSAL,h.Type.IA5STRING,!1,e.comment)}else if(e.name==="subjectKeyIdentifier"&&t.cert){var d=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=d.toHex(),e.value=h.create(h.Class.UNIVERSAL,h.Type.OCTETSTRING,!1,d.getBytes())}else if(e.name==="authorityKeyIdentifier"&&t.cert){e.value=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[]);var o=e.value.value;if(e.keyIdentifier){var f=e.keyIdentifier===!0?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;o.push(h.create(h.Class.CONTEXT_SPECIFIC,0,!1,f))}if(e.authorityCertIssuer){var y=[h.create(h.Class.CONTEXT_SPECIFIC,4,!0,[Nn(e.authorityCertIssuer===!0?t.cert.issuer:e.authorityCertIssuer)])];o.push(h.create(h.Class.CONTEXT_SPECIFIC,1,!0,y))}if(e.serialNumber){var p=ne.util.hexToBytes(e.serialNumber===!0?t.cert.serialNumber:e.serialNumber);o.push(h.create(h.Class.CONTEXT_SPECIFIC,2,!1,p))}}else if(e.name==="cRLDistributionPoints"){e.value=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[]);var o=e.value.value,v=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[]),x=h.create(h.Class.CONTEXT_SPECIFIC,0,!0,[]),c;for(var u=0;u<e.altNames.length;++u){c=e.altNames[u];var s=c.value;if(c.type===7&&c.ip){if(s=ne.util.bytesFromIP(c.ip),s===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(c.type===8)if(c.oid)s=h.oidToDer(h.oidToDer(c.oid));else s=h.oidToDer(s);x.value.push(h.create(h.Class.CONTEXT_SPECIFIC,c.type,!1,s))}v.value.push(h.create(h.Class.CONTEXT_SPECIFIC,0,!0,[x])),o.push(v)}if(typeof e.value>"u"){var n=Error("Extension value not specified.");throw n.extension=e,n}return e}function ko(e,t){switch(e){case Be["RSASSA-PSS"]:var n=[];if(t.hash.algorithmOid!==void 0)n.push(h.create(h.Class.CONTEXT_SPECIFIC,0,!0,[h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(t.hash.algorithmOid).getBytes()),h.create(h.Class.UNIVERSAL,h.Type.NULL,!1,"")])]));if(t.mgf.algorithmOid!==void 0)n.push(h.create(h.Class.CONTEXT_SPECIFIC,1,!0,[h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(t.mgf.algorithmOid).getBytes()),h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(t.mgf.hash.algorithmOid).getBytes()),h.create(h.Class.UNIVERSAL,h.Type.NULL,!1,"")])])]));if(t.saltLength!==void 0)n.push(h.create(h.Class.CONTEXT_SPECIFIC,2,!0,[h.create(h.Class.UNIVERSAL,h.Type.INTEGER,!1,h.integerToDer(t.saltLength).getBytes())]));return h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,n);default:return h.create(h.Class.UNIVERSAL,h.Type.NULL,!1,"")}}function Wm(e){var t=h.create(h.Class.CONTEXT_SPECIFIC,0,!0,[]);if(e.attributes.length===0)return t;var n=e.attributes;for(var r=0;r<n.length;++r){var i=n[r],a=i.value,s=h.Type.UTF8;if("valueTagClass"in i)s=i.valueTagClass;if(s===h.Type.UTF8)a=ne.util.encodeUtf8(a);var o=!1;if("valueConstructed"in i)o=i.valueConstructed;var l=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(i.type).getBytes()),h.create(h.Class.UNIVERSAL,h.Type.SET,!0,[h.create(h.Class.UNIVERSAL,s,o,a)])]);t.value.push(l)}return t}var $m=new Date("1950-01-01T00:00:00Z"),Hm=new Date("2050-01-01T00:00:00Z");function Xu(e){if(e>=$m&&e<Hm)return h.create(h.Class.UNIVERSAL,h.Type.UTCTIME,!1,h.dateToUtcTime(e));else return h.create(h.Class.UNIVERSAL,h.Type.GENERALIZEDTIME,!1,h.dateToGeneralizedTime(e))}F.getTBSCertificate=function(e){var t=Xu(e.validity.notBefore),n=Xu(e.validity.notAfter),r=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.CONTEXT_SPECIFIC,0,!0,[h.create(h.Class.UNIVERSAL,h.Type.INTEGER,!1,h.integerToDer(e.version).getBytes())]),h.create(h.Class.UNIVERSAL,h.Type.INTEGER,!1,ne.util.hexToBytes(e.serialNumber)),h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(e.siginfo.algorithmOid).getBytes()),ko(e.siginfo.algorithmOid,e.siginfo.parameters)]),Nn(e.issuer),h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[t,n]),Nn(e.subject),F.publicKeyToAsn1(e.publicKey)]);if(e.issuer.uniqueId)r.value.push(h.create(h.Class.CONTEXT_SPECIFIC,1,!0,[h.create(h.Class.UNIVERSAL,h.Type.BITSTRING,!1,String.fromCharCode(0)+e.issuer.uniqueId)]));if(e.subject.uniqueId)r.value.push(h.create(h.Class.CONTEXT_SPECIFIC,2,!0,[h.create(h.Class.UNIVERSAL,h.Type.BITSTRING,!1,String.fromCharCode(0)+e.subject.uniqueId)]));if(e.extensions.length>0)r.value.push(F.certificateExtensionsToAsn1(e.extensions));return r};F.getCertificationRequestInfo=function(e){var t=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.UNIVERSAL,h.Type.INTEGER,!1,h.integerToDer(e.version).getBytes()),Nn(e.subject),F.publicKeyToAsn1(e.publicKey),Wm(e)]);return t};F.distinguishedNameToAsn1=function(e){return Nn(e)};F.certificateToAsn1=function(e){var t=e.tbsCertificate||F.getTBSCertificate(e);return h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[t,h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(e.signatureOid).getBytes()),ko(e.signatureOid,e.signatureParameters)]),h.create(h.Class.UNIVERSAL,h.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};F.certificateExtensionsToAsn1=function(e){var t=h.create(h.Class.CONTEXT_SPECIFIC,3,!0,[]),n=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[]);t.value.push(n);for(var r=0;r<e.length;++r)n.value.push(F.certificateExtensionToAsn1(e[r]));return t};F.certificateExtensionToAsn1=function(e){var t=h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[]);if(t.value.push(h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(e.id).getBytes())),e.critical)t.value.push(h.create(h.Class.UNIVERSAL,h.Type.BOOLEAN,!1,String.fromCharCode(255)));var n=e.value;if(typeof e.value!=="string")n=h.toDer(n).getBytes();return t.value.push(h.create(h.Class.UNIVERSAL,h.Type.OCTETSTRING,!1,n)),t};F.certificationRequestToAsn1=function(e){var t=e.certificationRequestInfo||F.getCertificationRequestInfo(e);return h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[t,h.create(h.Class.UNIVERSAL,h.Type.SEQUENCE,!0,[h.create(h.Class.UNIVERSAL,h.Type.OID,!1,h.oidToDer(e.signatureOid).getBytes()),ko(e.signatureOid,e.signatureParameters)]),h.create(h.Class.UNIVERSAL,h.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};F.createCaStore=function(e){var t={certs:{}};t.getIssuer=function(s){var o=n(s.issuer);return o},t.addCertificate=function(s){if(typeof s==="string")s=ne.pki.certificateFromPem(s);if(r(s.subject),!t.hasCertificate(s))if(s.subject.hash in t.certs){var o=t.certs[s.subject.hash];if(!ne.util.isArray(o))o=[o];o.push(s),t.certs[s.subject.hash]=o}else t.certs[s.subject.hash]=s},t.hasCertificate=function(s){if(typeof s==="string")s=ne.pki.certificateFromPem(s);var o=n(s.subject);if(!o)return!1;if(!ne.util.isArray(o))o=[o];var l=h.toDer(F.certificateToAsn1(s)).getBytes();for(var c=0;c<o.length;++c){var u=h.toDer(F.certificateToAsn1(o[c])).getBytes();if(l===u)return!0}return!1},t.listAllCertificates=function(){var s=[];for(var o in t.certs)if(t.certs.hasOwnProperty(o)){var l=t.certs[o];if(!ne.util.isArray(l))s.push(l);else for(var c=0;c<l.length;++c)s.push(l[c])}return s},t.removeCertificate=function(s){var o;if(typeof s==="string")s=ne.pki.certificateFromPem(s);if(r(s.subject),!t.hasCertificate(s))return null;var l=n(s.subject);if(!ne.util.isArray(l))return o=t.certs[s.subject.hash],delete t.certs[s.subject.hash],o;var c=h.toDer(F.certificateToAsn1(s)).getBytes();for(var u=0;u<l.length;++u){var d=h.toDer(F.certificateToAsn1(l[u])).getBytes();if(c===d)o=l[u],l.splice(u,1)}if(l.length===0)delete t.certs[s.subject.hash];return o};function n(s){return r(s),t.certs[s.hash]||null}function r(s){if(!s.hash){var o=ne.md.sha1.create();s.attributes=F.RDNAttributesAsArray(Nn(s),o),s.hash=o.digest().toHex()}}if(e)for(var i=0;i<e.length;++i){var a=e[i];t.addCertificate(a)}return t};F.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"};F.verifyCertificateChain=function(e,t,n){if(typeof n==="function")n={verify:n};n=n||{},t=t.slice(0);var r=t.slice(0),i=n.validityCheckDate;if(typeof i>"u")i=new Date;var a=!0,s=null,o=0;do{var l=t.shift(),c=null,u=!1;if(i){if(i<l.validity.notBefore||i>l.validity.notAfter)s={message:"Certificate is not valid yet or has expired.",error:F.certificateError.certificate_expired,notBefore:l.validity.notBefore,notAfter:l.validity.notAfter,now:i}}if(s===null){if(c=t[0]||e.getIssuer(l),c===null){if(l.isIssuer(l))u=!0,c=l}if(c){var d=c;if(!ne.util.isArray(d))d=[d];var f=!1;while(!f&&d.length>0){c=d.shift();try{f=c.verify(l)}catch(I){}}if(!f)s={message:"Certificate signature is invalid.",error:F.certificateError.bad_certificate}}if(s===null&&(!c||u)&&!e.hasCertificate(l))s={message:"Certificate is not trusted.",error:F.certificateError.unknown_ca}}if(s===null&&c&&!l.isIssuer(c))s={message:"Certificate issuer is invalid.",error:F.certificateError.bad_certificate};if(s===null){var y={keyUsage:!0,basicConstraints:!0};for(var p=0;s===null&&p<l.extensions.length;++p){var v=l.extensions[p];if(v.critical&&!(v.name in y))s={message:"Certificate has an unsupported critical extension.",error:F.certificateError.unsupported_certificate}}}if(s===null&&(!a||t.length===0&&(!c||u))){var x=l.getExtension("basicConstraints"),b=l.getExtension("keyUsage");if(b!==null){if(!b.keyCertSign||x===null)s={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:F.certificateError.bad_certificate}}if(s===null&&x===null)s={message:"Certificate is missing basicConstraints extension and cannot be used as a CA.",error:F.certificateError.bad_certificate};if(s===null&&x!==null&&!x.cA)s={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:F.certificateError.bad_certificate};if(s===null&&b!==null&&"pathLenConstraint"in x){var A=o-1;if(A>x.pathLenConstraint)s={message:"Certificate basicConstraints pathLenConstraint violated.",error:F.certificateError.bad_certificate}}}var E=s===null?!0:s.error,k=n.verify?n.verify(E,o,r):E;if(k===!0)s=null;else{if(E===!0)s={message:"The application rejected the certificate.",error:F.certificateError.bad_certificate};if(k||k===0){if(typeof k==="object"&&!ne.util.isArray(k)){if(k.message)s.message=k.message;if(k.error)s.error=k.error}else if(typeof k==="string")s.error=k}throw s}a=!1,++o}while(t.length>0);return!0}});var Ro=de(function(d1,rd){var He=me();qt();An();Lr();Ao();To();Dt();bi();Rn();Pe();$a();var{asn1:S,pki:Ce}=He,Ei=rd.exports=He.pkcs12=He.pkcs12||{},td={name:"ContentInfo",tagClass:S.Class.UNIVERSAL,type:S.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:S.Class.UNIVERSAL,type:S.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:S.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},Km={name:"PFX",tagClass:S.Class.UNIVERSAL,type:S.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:S.Class.UNIVERSAL,type:S.Type.INTEGER,constructed:!1,capture:"version"},td,{name:"PFX.macData",tagClass:S.Class.UNIVERSAL,type:S.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:S.Class.UNIVERSAL,type:S.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:S.Class.UNIVERSAL,type:S.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:S.Class.UNIVERSAL,type:S.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:!0,tagClass:S.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:S.Class.UNIVERSAL,type:S.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:S.Class.UNIVERSAL,type:S.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:S.Class.UNIVERSAL,type:S.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},qm={name:"SafeBag",tagClass:S.Class.UNIVERSAL,type:S.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:S.Class.UNIVERSAL,type:S.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:S.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:S.Class.UNIVERSAL,type:S.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},Gm={name:"Attribute",tagClass:S.Class.UNIVERSAL,type:S.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:S.Class.UNIVERSAL,type:S.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:S.Class.UNIVERSAL,type:S.Type.SET,constructed:!0,capture:"values"}]},jm={name:"CertBag",tagClass:S.Class.UNIVERSAL,type:S.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:S.Class.UNIVERSAL,type:S.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:S.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:S.Class.UNIVERSAL,type:S.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Ci(e,t,n,r){var i=[];for(var a=0;a<e.length;a++)for(var s=0;s<e[a].safeBags.length;s++){var o=e[a].safeBags[s];if(r!==void 0&&o.type!==r)continue;if(t===null){i.push(o);continue}if(o.attributes[t]!==void 0&&o.attributes[t].indexOf(n)>=0)i.push(o)}return i}Ei.pkcs12FromAsn1=function(e,t,n){if(typeof t==="string")n=t,t=!0;else if(t===void 0)t=!0;var r={},i=[];if(!S.validate(e,Km,r,i)){var a=Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw a.errors=a,a}var s={version:r.version.charCodeAt(0),safeContents:[],getBags:function(x){var b={},A;if("localKeyId"in x)A=x.localKeyId;else if("localKeyIdHex"in x)A=He.util.hexToBytes(x.localKeyIdHex);if(A===void 0&&!("friendlyName"in x)&&"bagType"in x)b[x.bagType]=Ci(s.safeContents,null,null,x.bagType);if(A!==void 0)b.localKeyId=Ci(s.safeContents,"localKeyId",A,x.bagType);if("friendlyName"in x)b.friendlyName=Ci(s.safeContents,"friendlyName",x.friendlyName,x.bagType);return b},getBagsByFriendlyName:function(x,b){return Ci(s.safeContents,"friendlyName",x,b)},getBagsByLocalKeyId:function(x,b){return Ci(s.safeContents,"localKeyId",x,b)}};if(r.version.charCodeAt(0)!==3){var a=Error("PKCS#12 PFX of version other than 3 not supported.");throw a.version=r.version.charCodeAt(0),a}if(S.derToOid(r.contentType)!==Ce.oids.data){var a=Error("Only PKCS#12 PFX in password integrity mode supported.");throw a.oid=S.derToOid(r.contentType),a}var o=r.content.value[0];if(o.tagClass!==S.Class.UNIVERSAL||o.type!==S.Type.OCTETSTRING)throw Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(o=Io(o),r.mac){var l=null,c=0,u=S.derToOid(r.macAlgorithm);switch(u){case Ce.oids.sha1:l=He.md.sha1.create(),c=20;break;case Ce.oids.sha256:l=He.md.sha256.create(),c=32;break;case Ce.oids.sha384:l=He.md.sha384.create(),c=48;break;case Ce.oids.sha512:l=He.md.sha512.create(),c=64;break;case Ce.oids.md5:l=He.md.md5.create(),c=16;break}if(l===null)throw Error("PKCS#12 uses unsupported MAC algorithm: "+u);var d=new He.util.ByteBuffer(r.macSalt),f="macIterations"in r?parseInt(He.util.bytesToHex(r.macIterations),16):1,y=Ei.generateKey(n,d,3,f,c,l),p=He.hmac.create();p.start(l,y),p.update(o.value);var v=p.getMac();if(v.getBytes()!==r.macDigest)throw Error("PKCS#12 MAC could not be verified. Invalid password?")}else if(Array.isArray(e.value)&&e.value.length>2)throw Error("Invalid PKCS#12. macData field present but MAC was not validated.");return zm(s,o.value,t,n),s};function Io(e){if(e.composed||e.constructed){var t=He.util.createBuffer();for(var n=0;n<e.value.length;++n)t.putBytes(e.value[n].value);e.composed=e.constructed=!1,e.value=t.getBytes()}return e}function zm(e,t,n,r){if(t=S.fromDer(t,n),t.tagClass!==S.Class.UNIVERSAL||t.type!==S.Type.SEQUENCE||t.constructed!==!0)throw Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var i=0;i<t.value.length;i++){var a=t.value[i],s={},o=[];if(!S.validate(a,td,s,o)){var l=Error("Cannot read ContentInfo.");throw l.errors=o,l}var c={encrypted:!1},u=null,d=s.content.value[0];switch(S.derToOid(s.contentType)){case Ce.oids.data:if(d.tagClass!==S.Class.UNIVERSAL||d.type!==S.Type.OCTETSTRING)throw Error("PKCS#12 SafeContents Data is not an OCTET STRING.");u=Io(d).value;break;case Ce.oids.encryptedData:u=Qm(d,r),c.encrypted=!0;break;default:var l=Error("Unsupported PKCS#12 contentType.");throw l.contentType=S.derToOid(s.contentType),l}c.safeBags=Xm(u,n,r),e.safeContents.push(c)}}function Qm(e,t){var n={},r=[];if(!S.validate(e,He.pkcs7.asn1.encryptedDataValidator,n,r)){var i=Error("Cannot read EncryptedContentInfo.");throw i.errors=r,i}var a=S.derToOid(n.contentType);if(a!==Ce.oids.data){var i=Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw i.oid=a,i}a=S.derToOid(n.encAlgorithm);var s=Ce.pbe.getCipher(a,n.encParameter,t),o=Io(n.encryptedContentAsn1),l=He.util.createBuffer(o.value);if(s.update(l),!s.finish())throw Error("Failed to decrypt PKCS#12 SafeContents.");return s.output.getBytes()}function Xm(e,t,n){if(!t&&e.length===0)return[];if(e=S.fromDer(e,t),e.tagClass!==S.Class.UNIVERSAL||e.type!==S.Type.SEQUENCE||e.constructed!==!0)throw Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");var r=[];for(var i=0;i<e.value.length;i++){var a=e.value[i],s={},o=[];if(!S.validate(a,qm,s,o)){var l=Error("Cannot read SafeBag.");throw l.errors=o,l}var c={type:S.derToOid(s.bagId),attributes:Ym(s.bagAttributes)};r.push(c);var u,d,f=s.bagValue.value[0];switch(c.type){case Ce.oids.pkcs8ShroudedKeyBag:if(f=Ce.decryptPrivateKeyInfo(f,n),f===null)throw Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case Ce.oids.keyBag:try{c.key=Ce.privateKeyFromAsn1(f)}catch(p){c.key=null,c.asn1=f}continue;case Ce.oids.certBag:u=jm,d=function(){if(S.derToOid(s.certId)!==Ce.oids.x509Certificate){var p=Error("Unsupported certificate type, only X.509 supported.");throw p.oid=S.derToOid(s.certId),p}var v=S.fromDer(s.cert,t);try{c.cert=Ce.certificateFromAsn1(v,!0)}catch(x){c.cert=null,c.asn1=v}};break;default:var l=Error("Unsupported PKCS#12 SafeBag type.");throw l.oid=c.type,l}if(u!==void 0&&!S.validate(f,u,s,o)){var l=Error("Cannot read PKCS#12 "+u.name);throw l.errors=o,l}d()}return r}function Ym(e){var t={};if(e!==void 0)for(var n=0;n<e.length;++n){var r={},i=[];if(!S.validate(e[n],Gm,r,i)){var a=Error("Cannot read PKCS#12 BagAttribute.");throw a.errors=i,a}var s=S.derToOid(r.oid);if(Ce.oids[s]===void 0)continue;t[Ce.oids[s]]=[];for(var o=0;o<r.values.length;++o)t[Ce.oids[s]].push(r.values[o].value)}return t}Ei.toPkcs12Asn1=function(e,t,n,r){if(r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||r.encAlgorithm||"aes128",!("useMac"in r))r.useMac=!0;if(!("localKeyId"in r))r.localKeyId=null;if(!("generateLocalKeyId"in r))r.generateLocalKeyId=!0;var i=r.localKeyId,a;if(i!==null)i=He.util.hexToBytes(i);else if(r.generateLocalKeyId)if(t){var s=He.util.isArray(t)?t[0]:t;if(typeof s==="string")s=Ce.certificateFromPem(s);var o=He.md.sha1.create();o.update(S.toDer(Ce.certificateToAsn1(s)).getBytes()),i=o.digest().getBytes()}else i=He.random.getBytes(20);var l=[];if(i!==null)l.push(S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.localKeyId).getBytes()),S.create(S.Class.UNIVERSAL,S.Type.SET,!0,[S.create(S.Class.UNIVERSAL,S.Type.OCTETSTRING,!1,i)])]));if("friendlyName"in r)l.push(S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.friendlyName).getBytes()),S.create(S.Class.UNIVERSAL,S.Type.SET,!0,[S.create(S.Class.UNIVERSAL,S.Type.BMPSTRING,!1,r.friendlyName)])]));if(l.length>0)a=S.create(S.Class.UNIVERSAL,S.Type.SET,!0,l);var c=[],u=[];if(t!==null)if(He.util.isArray(t))u=t;else u=[t];var d=[];for(var f=0;f<u.length;++f){if(t=u[f],typeof t==="string")t=Ce.certificateFromPem(t);var y=f===0?a:void 0,p=Ce.certificateToAsn1(t),v=S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.certBag).getBytes()),S.create(S.Class.CONTEXT_SPECIFIC,0,!0,[S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.x509Certificate).getBytes()),S.create(S.Class.CONTEXT_SPECIFIC,0,!0,[S.create(S.Class.UNIVERSAL,S.Type.OCTETSTRING,!1,S.toDer(p).getBytes())])])]),y]);d.push(v)}if(d.length>0){var x=S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,d),b=S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.data).getBytes()),S.create(S.Class.CONTEXT_SPECIFIC,0,!0,[S.create(S.Class.UNIVERSAL,S.Type.OCTETSTRING,!1,S.toDer(x).getBytes())])]);c.push(b)}var A=null;if(e!==null){var E=Ce.wrapRsaPrivateKey(Ce.privateKeyToAsn1(e));if(n===null)A=S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.keyBag).getBytes()),S.create(S.Class.CONTEXT_SPECIFIC,0,!0,[E]),a]);else A=S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.pkcs8ShroudedKeyBag).getBytes()),S.create(S.Class.CONTEXT_SPECIFIC,0,!0,[Ce.encryptPrivateKeyInfo(E,n,r)]),a]);var k=S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[A]),I=S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.data).getBytes()),S.create(S.Class.CONTEXT_SPECIFIC,0,!0,[S.create(S.Class.UNIVERSAL,S.Type.OCTETSTRING,!1,S.toDer(k).getBytes())])]);c.push(I)}var R=S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,c),M;if(r.useMac){var o=He.md.sha1.create(),ee=new He.util.ByteBuffer(He.random.getBytes(r.saltSize)),O=r.count,e=Ei.generateKey(n,ee,3,O,20),K=He.hmac.create();K.start(o,e),K.update(S.toDer(R).getBytes());var ie=K.getMac();M=S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.sha1).getBytes()),S.create(S.Class.UNIVERSAL,S.Type.NULL,!1,"")]),S.create(S.Class.UNIVERSAL,S.Type.OCTETSTRING,!1,ie.getBytes())]),S.create(S.Class.UNIVERSAL,S.Type.OCTETSTRING,!1,ee.getBytes()),S.create(S.Class.UNIVERSAL,S.Type.INTEGER,!1,S.integerToDer(O).getBytes())])}return S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.INTEGER,!1,S.integerToDer(3).getBytes()),S.create(S.Class.UNIVERSAL,S.Type.SEQUENCE,!0,[S.create(S.Class.UNIVERSAL,S.Type.OID,!1,S.oidToDer(Ce.oids.data).getBytes()),S.create(S.Class.CONTEXT_SPECIFIC,0,!0,[S.create(S.Class.UNIVERSAL,S.Type.OCTETSTRING,!1,S.toDer(R).getBytes())])]),M])};Ei.generateKey=He.pbe.generatePkcs12Key});var Po=de(function(f1,nd){var Fr=me();qt();Lr();To();an();Pa();Ro();Fa();bi();Pe();$a();var Bo=Fr.asn1,Dn=nd.exports=Fr.pki=Fr.pki||{};Dn.pemToDer=function(e){var t=Fr.pem.decode(e)[0];if(t.procType&&t.procType.type==="ENCRYPTED")throw Error("Could not convert PEM to DER; PEM is encrypted.");return Fr.util.createBuffer(t.body)};Dn.privateKeyFromPem=function(e){var t=Fr.pem.decode(e)[0];if(t.type!=="PRIVATE KEY"&&t.type!=="RSA PRIVATE KEY"){var n=Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw n.headerType=t.type,n}if(t.procType&&t.procType.type==="ENCRYPTED")throw Error("Could not convert private key from PEM; PEM is encrypted.");var r=Bo.fromDer(t.body);return Dn.privateKeyFromAsn1(r)};Dn.privateKeyToPem=function(e,t){var n={type:"RSA PRIVATE KEY",body:Bo.toDer(Dn.privateKeyToAsn1(e)).getBytes()};return Fr.pem.encode(n,{maxline:t})};Dn.privateKeyInfoToPem=function(e,t){var n={type:"PRIVATE KEY",body:Bo.toDer(e).getBytes()};return Fr.pem.encode(n,{maxline:t})}});var Vo=de(function(p1,dd){var L=me();qt();An();ka();an();Po();Dt();Rn();Pe();var qa=function(e,t,n,r){var i=L.util.createBuffer(),a=e.length>>1,s=a+(e.length&1),o=e.substr(0,s),l=e.substr(a,s),c=L.util.createBuffer(),u=L.hmac.create();n=t+n;var d=Math.ceil(r/16),f=Math.ceil(r/20);u.start("MD5",o);var y=L.util.createBuffer();c.putBytes(n);for(var p=0;p<d;++p)u.start(null,null),u.update(c.getBytes()),c.putBuffer(u.digest()),u.start(null,null),u.update(c.bytes()+n),y.putBuffer(u.digest());u.start("SHA1",l);var v=L.util.createBuffer();c.clear(),c.putBytes(n);for(var p=0;p<f;++p)u.start(null,null),u.update(c.getBytes()),c.putBuffer(u.digest()),u.start(null,null),u.update(c.bytes()+n),v.putBuffer(u.digest());return i.putBytes(L.util.xorBytes(y.getBytes(),v.getBytes(),r)),i},Jm=function(e,t,n){var r=L.hmac.create();r.start("SHA1",e);var i=L.util.createBuffer();return i.putInt32(t[0]),i.putInt32(t[1]),i.putByte(n.type),i.putByte(n.version.major),i.putByte(n.version.minor),i.putInt16(n.length),i.putBytes(n.fragment.bytes()),r.update(i.getBytes()),r.digest().getBytes()},Zm=function(e,t,n){var r=!1;try{var i=e.deflate(t.fragment.getBytes());t.fragment=L.util.createBuffer(i),t.length=i.length,r=!0}catch(a){}return r},ey=function(e,t,n){var r=!1;try{var i=e.inflate(t.fragment.getBytes());t.fragment=L.util.createBuffer(i),t.length=i.length,r=!0}catch(a){}return r},It=function(e,t){var n=0;switch(t){case 1:n=e.getByte();break;case 2:n=e.getInt16();break;case 3:n=e.getInt24();break;case 4:n=e.getInt32();break}return L.util.createBuffer(e.getBytes(n))},Vt=function(e,t,n){e.putInt(n.length(),t<<3),e.putBuffer(n)},m={};m.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};m.SupportedVersions=[m.Versions.TLS_1_1,m.Versions.TLS_1_0];m.Version=m.SupportedVersions[0];m.MaxFragment=15360;m.ConnectionEnd={server:0,client:1};m.PRFAlgorithm={tls_prf_sha256:0};m.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};m.CipherType={stream:0,block:1,aead:2};m.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};m.CompressionMethod={none:0,deflate:1};m.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};m.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20};m.Alert={};m.Alert.Level={warning:1,fatal:2};m.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_denied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100};m.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};m.CipherSuites={};m.getCipherSuite=function(e){var t=null;for(var n in m.CipherSuites){var r=m.CipherSuites[n];if(r.id[0]===e.charCodeAt(0)&&r.id[1]===e.charCodeAt(1)){t=r;break}}return t};m.handleUnexpected=function(e,t){var n=!e.open&&e.entity===m.ConnectionEnd.client;if(!n)e.error(e,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.unexpected_message}})};m.handleHelloRequest=function(e,t,n){if(!e.handshaking&&e.handshakes>0)m.queue(e,m.createAlert(e,{level:m.Alert.Level.warning,description:m.Alert.Description.no_renegotiation})),m.flush(e);e.process()};m.parseHelloMessage=function(e,t,n){var r=null,i=e.entity===m.ConnectionEnd.client;if(n<38)e.error(e,{message:i?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.illegal_parameter}});else{var a=t.fragment,s=a.length();if(r={version:{major:a.getByte(),minor:a.getByte()},random:L.util.createBuffer(a.getBytes(32)),session_id:It(a,1),extensions:[]},i)r.cipher_suite=a.getBytes(2),r.compression_method=a.getByte();else r.cipher_suites=It(a,2),r.compression_methods=It(a,1);if(s=n-(s-a.length()),s>0){var o=It(a,2);while(o.length()>0)r.extensions.push({type:[o.getByte(),o.getByte()],data:It(o,2)});if(!i)for(var l=0;l<r.extensions.length;++l){var c=r.extensions[l];if(c.type[0]===0&&c.type[1]===0){var u=It(c.data,2);while(u.length()>0){var d=u.getByte();if(d!==0)break;e.session.extensions.server_name.serverNameList.push(It(u,2).getBytes())}}}}if(e.session.version){if(r.version.major!==e.session.version.major||r.version.minor!==e.session.version.minor)return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.protocol_version}})}if(i)e.session.cipherSuite=m.getCipherSuite(r.cipher_suite);else{var f=L.util.createBuffer(r.cipher_suites.bytes());while(f.length()>0)if(e.session.cipherSuite=m.getCipherSuite(f.getBytes(2)),e.session.cipherSuite!==null)break}if(e.session.cipherSuite===null)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.handshake_failure},cipherSuite:L.util.bytesToHex(r.cipher_suite)});if(i)e.session.compressionMethod=r.compression_method;else e.session.compressionMethod=m.CompressionMethod.none}return r};m.createSecurityParameters=function(e,t){var n=e.entity===m.ConnectionEnd.client,r=t.random.bytes(),i=n?e.session.sp.client_random:r,a=n?r:m.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:m.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:i,server_random:a}};m.handleServerHello=function(e,t,n){var r=m.parseHelloMessage(e,t,n);if(e.fail)return;if(r.version.minor<=e.version.minor)e.version.minor=r.version.minor;else return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.protocol_version}});e.session.version=e.version;var i=r.session_id.bytes();if(i.length>0&&i===e.session.id)e.expect=sd,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes();else e.expect=ry,e.session.resuming=!1,m.createSecurityParameters(e,r);e.session.id=i,e.process()};m.handleClientHello=function(e,t,n){var r=m.parseHelloMessage(e,t,n);if(e.fail)return;var i=r.session_id.bytes(),a=null;if(e.sessionCache){if(a=e.sessionCache.getSession(i),a===null)i="";else if(a.version.major!==r.version.major||a.version.minor>r.version.minor)a=null,i=""}if(i.length===0)i=L.random.getBytes(32);if(e.session.id=i,e.session.clientHelloVersion=r.version,e.session.sp={},a)e.version=e.session.version=a.version,e.session.sp=a.sp;else{var s;for(var o=1;o<m.SupportedVersions.length;++o)if(s=m.SupportedVersions[o],s.minor<=r.version.minor)break;e.version={major:s.major,minor:s.minor},e.session.version=e.version}if(a!==null)e.expect=Oo,e.session.resuming=!0,e.session.sp.client_random=r.random.bytes();else e.expect=e.verifyClient!==!1?cy:Lo,e.session.resuming=!1,m.createSecurityParameters(e,r);if(e.open=!0,m.queue(e,m.createRecord(e,{type:m.ContentType.handshake,data:m.createServerHello(e)})),e.session.resuming)m.queue(e,m.createRecord(e,{type:m.ContentType.change_cipher_spec,data:m.createChangeCipherSpec()})),e.state.pending=m.createConnectionState(e),e.state.current.write=e.state.pending.write,m.queue(e,m.createRecord(e,{type:m.ContentType.handshake,data:m.createFinished(e)}));else if(m.queue(e,m.createRecord(e,{type:m.ContentType.handshake,data:m.createCertificate(e)})),!e.fail){if(m.queue(e,m.createRecord(e,{type:m.ContentType.handshake,data:m.createServerKeyExchange(e)})),e.verifyClient!==!1)m.queue(e,m.createRecord(e,{type:m.ContentType.handshake,data:m.createCertificateRequest(e)}));m.queue(e,m.createRecord(e,{type:m.ContentType.handshake,data:m.createServerHelloDone(e)}))}m.flush(e),e.process()};m.handleCertificate=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.illegal_parameter}});var r=t.fragment,i={certificate_list:It(r,3)},a,s,o=[];try{while(i.certificate_list.length()>0)a=It(i.certificate_list,3),s=L.asn1.fromDer(a),a=L.pki.certificateFromAsn1(s,!0),o.push(a)}catch(c){return e.error(e,{message:"Could not parse certificate list.",cause:c,send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.bad_certificate}})}var l=e.entity===m.ConnectionEnd.client;if((l||e.verifyClient===!0)&&o.length===0)e.error(e,{message:l?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.illegal_parameter}});else if(o.length===0)e.expect=l?id:Lo;else{if(l)e.session.serverCertificate=o[0];else e.session.clientCertificate=o[0];if(m.verifyCertificateChain(e,o))e.expect=l?id:Lo}e.process()};m.handleServerKeyExchange=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.unsupported_certificate}});e.expect=ny,e.process()};m.handleClientKeyExchange=function(e,t,n){if(n<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.unsupported_certificate}});var r=t.fragment,i={enc_pre_master_secret:It(r,2).getBytes()},a=null;if(e.getPrivateKey)try{a=e.getPrivateKey(e,e.session.serverCertificate),a=L.pki.privateKeyFromPem(a)}catch(l){e.error(e,{message:"Could not get private key.",cause:l,send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.internal_error}})}if(a===null)return e.error(e,{message:"No private key set.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.internal_error}});try{var s=e.session.sp;s.pre_master_secret=a.decrypt(i.enc_pre_master_secret);var o=e.session.clientHelloVersion;if(o.major!==s.pre_master_secret.charCodeAt(0)||o.minor!==s.pre_master_secret.charCodeAt(1))throw Error("TLS version rollback attack detected.")}catch(l){s.pre_master_secret=L.random.getBytes(48)}if(e.expect=Oo,e.session.clientCertificate!==null)e.expect=uy;e.process()};m.handleCertificateRequest=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.illegal_parameter}});var r=t.fragment,i={certificate_types:It(r,1),certificate_authorities:It(r,2)};e.session.certificateRequest=i,e.expect=iy,e.process()};m.handleCertificateVerify=function(e,t,n){if(n<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.illegal_parameter}});var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var a={signature:It(r,2).getBytes()},s=L.util.createBuffer();s.putBuffer(e.session.md5.digest()),s.putBuffer(e.session.sha1.digest()),s=s.getBytes();try{var o=e.session.clientCertificate;if(!o.publicKey.verify(s,a.signature,"NONE"))throw Error("CertificateVerify signature does not match.");e.session.md5.update(i),e.session.sha1.update(i)}catch(l){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.handshake_failure}})}e.expect=Oo,e.process()};m.handleServerHelloDone=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.record_overflow}});if(e.serverCertificate===null){var r={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.insufficient_security}},i=0,a=e.verify(e,r.alert.description,i,[]);if(a!==!0){if(a||a===0){if(typeof a==="object"&&!L.util.isArray(a)){if(a.message)r.message=a.message;if(a.alert)r.alert.description=a.alert}else if(typeof a==="number")r.alert.description=a}return e.error(e,r)}}if(e.session.certificateRequest!==null)t=m.createRecord(e,{type:m.ContentType.handshake,data:m.createCertificate(e)}),m.queue(e,t);t=m.createRecord(e,{type:m.ContentType.handshake,data:m.createClientKeyExchange(e)}),m.queue(e,t),e.expect=oy;var s=function(o,l){if(o.session.certificateRequest!==null&&o.session.clientCertificate!==null)m.queue(o,m.createRecord(o,{type:m.ContentType.handshake,data:m.createCertificateVerify(o,l)}));m.queue(o,m.createRecord(o,{type:m.ContentType.change_cipher_spec,data:m.createChangeCipherSpec()})),o.state.pending=m.createConnectionState(o),o.state.current.write=o.state.pending.write,m.queue(o,m.createRecord(o,{type:m.ContentType.handshake,data:m.createFinished(o)})),o.expect=sd,m.flush(o),o.process()};if(e.session.certificateRequest===null||e.session.clientCertificate===null)return s(e,null);m.getClientSignature(e,s)};m.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.illegal_parameter}});var n=e.entity===m.ConnectionEnd.client;if(e.session.resuming&&n||!e.session.resuming&&!n)e.state.pending=m.createConnectionState(e);if(e.state.current.read=e.state.pending.read,!e.session.resuming&&n||e.session.resuming&&!n)e.state.pending=null;e.expect=n?ay:dy,e.process()};m.handleFinished=function(e,t,n){var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var a=t.fragment.getBytes();r=L.util.createBuffer(),r.putBuffer(e.session.md5.digest()),r.putBuffer(e.session.sha1.digest());var s=e.entity===m.ConnectionEnd.client,o=s?"server finished":"client finished",l=e.session.sp,c=12,u=qa;if(r=u(l.master_secret,o,r.getBytes(),c),r.getBytes()!==a)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.decrypt_error}});if(e.session.md5.update(i),e.session.sha1.update(i),e.session.resuming&&s||!e.session.resuming&&!s)m.queue(e,m.createRecord(e,{type:m.ContentType.change_cipher_spec,data:m.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,m.queue(e,m.createRecord(e,{type:m.ContentType.handshake,data:m.createFinished(e)}));e.expect=s?sy:fy,e.handshaking=!1,++e.handshakes,e.peerCertificate=s?e.session.serverCertificate:e.session.clientCertificate,m.flush(e),e.isConnected=!0,e.connected(e),e.process()};m.handleAlert=function(e,t){var n=t.fragment,r={level:n.getByte(),description:n.getByte()},i;switch(r.description){case m.Alert.Description.close_notify:i="Connection closed.";break;case m.Alert.Description.unexpected_message:i="Unexpected message.";break;case m.Alert.Description.bad_record_mac:i="Bad record MAC.";break;case m.Alert.Description.decryption_failed:i="Decryption failed.";break;case m.Alert.Description.record_overflow:i="Record overflow.";break;case m.Alert.Description.decompression_failure:i="Decompression failed.";break;case m.Alert.Description.handshake_failure:i="Handshake failure.";break;case m.Alert.Description.bad_certificate:i="Bad certificate.";break;case m.Alert.Description.unsupported_certificate:i="Unsupported certificate.";break;case m.Alert.Description.certificate_revoked:i="Certificate revoked.";break;case m.Alert.Description.certificate_expired:i="Certificate expired.";break;case m.Alert.Description.certificate_unknown:i="Certificate unknown.";break;case m.Alert.Description.illegal_parameter:i="Illegal parameter.";break;case m.Alert.Description.unknown_ca:i="Unknown certificate authority.";break;case m.Alert.Description.access_denied:i="Access denied.";break;case m.Alert.Description.decode_error:i="Decode error.";break;case m.Alert.Description.decrypt_error:i="Decrypt error.";break;case m.Alert.Description.export_restriction:i="Export restriction.";break;case m.Alert.Description.protocol_version:i="Unsupported protocol version.";break;case m.Alert.Description.insufficient_security:i="Insufficient security.";break;case m.Alert.Description.internal_error:i="Internal error.";break;case m.Alert.Description.user_canceled:i="User canceled.";break;case m.Alert.Description.no_renegotiation:i="Renegotiation not supported.";break;default:i="Unknown error.";break}if(r.description===m.Alert.Description.close_notify)return e.close();e.error(e,{message:i,send:!1,origin:e.entity===m.ConnectionEnd.client?"server":"client",alert:r}),e.process()};m.handleHandshake=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt24();if(i>n.length())return e.fragmented=t,t.fragment=L.util.createBuffer(),n.read-=4,e.process();e.fragmented=null,n.read-=4;var a=n.bytes(i+4);if(n.read+=4,r in Ka[e.entity][e.expect]){if(e.entity===m.ConnectionEnd.server&&!e.open&&!e.fail)e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:L.md.md5.create(),sha1:L.md.sha1.create()};if(r!==m.HandshakeType.hello_request&&r!==m.HandshakeType.certificate_verify&&r!==m.HandshakeType.finished)e.session.md5.update(a),e.session.sha1.update(a);Ka[e.entity][e.expect][r](e,t,i)}else m.handleUnexpected(e,t)};m.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};m.handleHeartbeat=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt16(),a=n.getBytes(i);if(r===m.HeartbeatMessageType.heartbeat_request){if(e.handshaking||i>a.length)return e.process();m.queue(e,m.createRecord(e,{type:m.ContentType.heartbeat,data:m.createHeartbeat(m.HeartbeatMessageType.heartbeat_response,a)})),m.flush(e)}else if(r===m.HeartbeatMessageType.heartbeat_response){if(a!==e.expectedHeartbeatPayload)return e.process();if(e.heartbeatReceived)e.heartbeatReceived(e,L.util.createBuffer(a))}e.process()};var ty=0,ry=1,id=2,ny=3,iy=4,sd=5,ay=6,sy=7,oy=8,ly=0,cy=1,Lo=2,uy=3,Oo=4,dy=5,fy=6,{handleUnexpected:g,handleChangeCipherSpec:od,handleAlert:gt,handleHandshake:Ct,handleApplicationData:ld,handleHeartbeat:mt}=m,Uo=[];Uo[m.ConnectionEnd.client]=[[g,gt,Ct,g,mt],[g,gt,Ct,g,mt],[g,gt,Ct,g,mt],[g,gt,Ct,g,mt],[g,gt,Ct,g,mt],[od,gt,g,g,mt],[g,gt,Ct,g,mt],[g,gt,Ct,ld,mt],[g,gt,Ct,g,mt]];Uo[m.ConnectionEnd.server]=[[g,gt,Ct,g,mt],[g,gt,Ct,g,mt],[g,gt,Ct,g,mt],[g,gt,Ct,g,mt],[od,gt,g,g,mt],[g,gt,Ct,g,mt],[g,gt,Ct,ld,mt],[g,gt,Ct,g,mt]];var{handleHelloRequest:Mr,handleServerHello:py,handleCertificate:cd,handleServerKeyExchange:ad,handleCertificateRequest:No,handleServerHelloDone:Ha,handleFinished:ud}=m,Ka=[];Ka[m.ConnectionEnd.client]=[[g,g,py,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[Mr,g,g,g,g,g,g,g,g,g,g,cd,ad,No,Ha,g,g,g,g,g,g],[Mr,g,g,g,g,g,g,g,g,g,g,g,ad,No,Ha,g,g,g,g,g,g],[Mr,g,g,g,g,g,g,g,g,g,g,g,g,No,Ha,g,g,g,g,g,g],[Mr,g,g,g,g,g,g,g,g,g,g,g,g,g,Ha,g,g,g,g,g,g],[Mr,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[Mr,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,ud],[Mr,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[Mr,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g]];var{handleClientHello:hy,handleClientKeyExchange:gy,handleCertificateVerify:my}=m;Ka[m.ConnectionEnd.server]=[[g,hy,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,cd,g,g,g,g,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,gy,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,my,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,ud],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g],[g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g,g]];m.generateKeys=function(e,t){var n=qa,r=t.client_random+t.server_random;if(!e.session.resuming)t.master_secret=n(t.pre_master_secret,"master secret",r,48).bytes(),t.pre_master_secret=null;r=t.server_random+t.client_random;var i=2*t.mac_key_length+2*t.enc_key_length,a=e.version.major===m.Versions.TLS_1_0.major&&e.version.minor===m.Versions.TLS_1_0.minor;if(a)i+=2*t.fixed_iv_length;var s=n(t.master_secret,"key expansion",r,i),o={client_write_MAC_key:s.getBytes(t.mac_key_length),server_write_MAC_key:s.getBytes(t.mac_key_length),client_write_key:s.getBytes(t.enc_key_length),server_write_key:s.getBytes(t.enc_key_length)};if(a)o.client_write_IV=s.getBytes(t.fixed_iv_length),o.server_write_IV=s.getBytes(t.fixed_iv_length);return o};m.createConnectionState=function(e){var t=e.entity===m.ConnectionEnd.client,n=function(){var a={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(s){return!0},compressionState:null,compressFunction:function(s){return!0},updateSequenceNumber:function(){if(a.sequenceNumber[1]===4294967295)a.sequenceNumber[1]=0,++a.sequenceNumber[0];else++a.sequenceNumber[1]}};return a},r={read:n(),write:n()};if(r.read.update=function(a,s){if(!r.read.cipherFunction(s,r.read))a.error(a,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.bad_record_mac}});else if(!r.read.compressFunction(a,s,r.read))a.error(a,{message:"Could not decompress record.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.decompression_failure}});return!a.fail},r.write.update=function(a,s){if(!r.write.compressFunction(a,s,r.write))a.error(a,{message:"Could not compress record.",send:!1,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.internal_error}});else if(!r.write.cipherFunction(s,r.write))a.error(a,{message:"Could not encrypt record.",send:!1,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.internal_error}});return!a.fail},e.session){var i=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(i),i.keys=m.generateKeys(e,i),r.read.macKey=t?i.keys.server_write_MAC_key:i.keys.client_write_MAC_key,r.write.macKey=t?i.keys.client_write_MAC_key:i.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(r,e,i),i.compression_algorithm){case m.CompressionMethod.none:break;case m.CompressionMethod.deflate:r.read.compressFunction=ey,r.write.compressFunction=Zm;break;default:throw Error("Unsupported compression algorithm.")}}return r};m.createRandom=function(){var e=new Date,t=+e+e.getTimezoneOffset()*60000,n=L.util.createBuffer();return n.putInt32(t),n.putBytes(L.random.getBytes(28)),n};m.createRecord=function(e,t){if(!t.data)return null;var n={type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data};return n};m.createAlert=function(e,t){var n=L.util.createBuffer();return n.putByte(t.level),n.putByte(t.description),m.createRecord(e,{type:m.ContentType.alert,data:n})};m.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};var t=L.util.createBuffer();for(var n=0;n<e.cipherSuites.length;++n){var r=e.cipherSuites[n];t.putByte(r.id[0]),t.putByte(r.id[1])}var i=t.length(),a=L.util.createBuffer();a.putByte(m.CompressionMethod.none);var s=a.length(),o=L.util.createBuffer();if(e.virtualHost){var l=L.util.createBuffer();l.putByte(0),l.putByte(0);var c=L.util.createBuffer();c.putByte(0),Vt(c,2,L.util.createBuffer(e.virtualHost));var u=L.util.createBuffer();Vt(u,2,c),Vt(l,2,u),o.putBuffer(l)}var d=o.length();if(d>0)d+=2;var f=e.session.id,y=f.length+1+2+4+28+2+i+1+s+d,p=L.util.createBuffer();if(p.putByte(m.HandshakeType.client_hello),p.putInt24(y),p.putByte(e.version.major),p.putByte(e.version.minor),p.putBytes(e.session.sp.client_random),Vt(p,1,L.util.createBuffer(f)),Vt(p,2,t),Vt(p,1,a),d>0)Vt(p,2,o);return p};m.createServerHello=function(e){var t=e.session.id,n=t.length+1+2+4+28+2+1,r=L.util.createBuffer();return r.putByte(m.HandshakeType.server_hello),r.putInt24(n),r.putByte(e.version.major),r.putByte(e.version.minor),r.putBytes(e.session.sp.server_random),Vt(r,1,L.util.createBuffer(t)),r.putByte(e.session.cipherSuite.id[0]),r.putByte(e.session.cipherSuite.id[1]),r.putByte(e.session.compressionMethod),r};m.createCertificate=function(e){var t=e.entity===m.ConnectionEnd.client,n=null;if(e.getCertificate){var r;if(t)r=e.session.certificateRequest;else r=e.session.extensions.server_name.serverNameList;n=e.getCertificate(e,r)}var i=L.util.createBuffer();if(n!==null)try{if(!L.util.isArray(n))n=[n];var a=null;for(var s=0;s<n.length;++s){var o=L.pem.decode(n[s])[0];if(o.type!=="CERTIFICATE"&&o.type!=="X509 CERTIFICATE"&&o.type!=="TRUSTED CERTIFICATE"){var l=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw l.headerType=o.type,l}if(o.procType&&o.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var c=L.util.createBuffer(o.body);if(a===null)a=L.asn1.fromDer(c.bytes(),!1);var u=L.util.createBuffer();Vt(u,3,c),i.putBuffer(u)}if(n=L.pki.certificateFromAsn1(a),t)e.session.clientCertificate=n;else e.session.serverCertificate=n}catch(y){return e.error(e,{message:"Could not send certificate list.",cause:y,send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.bad_certificate}})}var d=3+i.length(),f=L.util.createBuffer();return f.putByte(m.HandshakeType.certificate),f.putInt24(d),Vt(f,3,i),f};m.createClientKeyExchange=function(e){var t=L.util.createBuffer();t.putByte(e.session.clientHelloVersion.major),t.putByte(e.session.clientHelloVersion.minor),t.putBytes(L.random.getBytes(46));var n=e.session.sp;n.pre_master_secret=t.getBytes();var r=e.session.serverCertificate.publicKey;t=r.encrypt(n.pre_master_secret);var i=t.length+2,a=L.util.createBuffer();return a.putByte(m.HandshakeType.client_key_exchange),a.putInt24(i),a.putInt16(t.length),a.putBytes(t),a};m.createServerKeyExchange=function(e){var t=0,n=L.util.createBuffer();if(t>0)n.putByte(m.HandshakeType.server_key_exchange),n.putInt24(t);return n};m.getClientSignature=function(e,t){var n=L.util.createBuffer();n.putBuffer(e.session.md5.digest()),n.putBuffer(e.session.sha1.digest()),n=n.getBytes(),e.getSignature=e.getSignature||function(r,i,a){var s=null;if(r.getPrivateKey)try{s=r.getPrivateKey(r,r.session.clientCertificate),s=L.pki.privateKeyFromPem(s)}catch(o){r.error(r,{message:"Could not get private key.",cause:o,send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.internal_error}})}if(s===null)r.error(r,{message:"No private key set.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.internal_error}});else i=s.sign(i,null);a(r,i)},e.getSignature(e,n,t)};m.createCertificateVerify=function(e,t){var n=t.length+2,r=L.util.createBuffer();return r.putByte(m.HandshakeType.certificate_verify),r.putInt24(n),r.putInt16(t.length),r.putBytes(t),r};m.createCertificateRequest=function(e){var t=L.util.createBuffer();t.putByte(1);var n=L.util.createBuffer();for(var r in e.caStore.certs){var i=e.caStore.certs[r],a=L.pki.distinguishedNameToAsn1(i.subject),s=L.asn1.toDer(a);n.putInt16(s.length()),n.putBuffer(s)}var o=1+t.length()+2+n.length(),l=L.util.createBuffer();return l.putByte(m.HandshakeType.certificate_request),l.putInt24(o),Vt(l,1,t),Vt(l,2,n),l};m.createServerHelloDone=function(e){var t=L.util.createBuffer();return t.putByte(m.HandshakeType.server_hello_done),t.putInt24(0),t};m.createChangeCipherSpec=function(){var e=L.util.createBuffer();return e.putByte(1),e};m.createFinished=function(e){var t=L.util.createBuffer();t.putBuffer(e.session.md5.digest()),t.putBuffer(e.session.sha1.digest());var n=e.entity===m.ConnectionEnd.client,r=e.session.sp,i=12,a=qa,s=n?"client finished":"server finished";t=a(r.master_secret,s,t.getBytes(),i);var o=L.util.createBuffer();return o.putByte(m.HandshakeType.finished),o.putInt24(t.length()),o.putBuffer(t),o};m.createHeartbeat=function(e,t,n){if(typeof n>"u")n=t.length;var r=L.util.createBuffer();r.putByte(e),r.putInt16(n),r.putBytes(t);var i=r.length(),a=Math.max(16,i-n-3);return r.putBytes(L.random.getBytes(a)),r};m.queue=function(e,t){if(!t)return;if(t.fragment.length()===0){if(t.type===m.ContentType.handshake||t.type===m.ContentType.alert||t.type===m.ContentType.change_cipher_spec)return}if(t.type===m.ContentType.handshake){var n=t.fragment.bytes();e.session.md5.update(n),e.session.sha1.update(n),n=null}var r;if(t.fragment.length()<=m.MaxFragment)r=[t];else{r=[];var i=t.fragment.bytes();while(i.length>m.MaxFragment)r.push(m.createRecord(e,{type:t.type,data:L.util.createBuffer(i.slice(0,m.MaxFragment))})),i=i.slice(m.MaxFragment);if(i.length>0)r.push(m.createRecord(e,{type:t.type,data:L.util.createBuffer(i)}))}for(var a=0;a<r.length&&!e.fail;++a){var s=r[a],o=e.state.current.write;if(o.update(e,s))e.records.push(s)}};m.flush=function(e){for(var t=0;t<e.records.length;++t){var n=e.records[t];e.tlsData.putByte(n.type),e.tlsData.putByte(n.version.major),e.tlsData.putByte(n.version.minor),e.tlsData.putInt16(n.fragment.length()),e.tlsData.putBuffer(e.records[t].fragment)}return e.records=[],e.tlsDataReady(e)};var Do=function(e){switch(e){case!0:return!0;case L.pki.certificateError.bad_certificate:return m.Alert.Description.bad_certificate;case L.pki.certificateError.unsupported_certificate:return m.Alert.Description.unsupported_certificate;case L.pki.certificateError.certificate_revoked:return m.Alert.Description.certificate_revoked;case L.pki.certificateError.certificate_expired:return m.Alert.Description.certificate_expired;case L.pki.certificateError.certificate_unknown:return m.Alert.Description.certificate_unknown;case L.pki.certificateError.unknown_ca:return m.Alert.Description.unknown_ca;default:return m.Alert.Description.bad_certificate}},yy=function(e){switch(e){case!0:return!0;case m.Alert.Description.bad_certificate:return L.pki.certificateError.bad_certificate;case m.Alert.Description.unsupported_certificate:return L.pki.certificateError.unsupported_certificate;case m.Alert.Description.certificate_revoked:return L.pki.certificateError.certificate_revoked;case m.Alert.Description.certificate_expired:return L.pki.certificateError.certificate_expired;case m.Alert.Description.certificate_unknown:return L.pki.certificateError.certificate_unknown;case m.Alert.Description.unknown_ca:return L.pki.certificateError.unknown_ca;default:return L.pki.certificateError.bad_certificate}};m.verifyCertificateChain=function(e,t){try{var n={};for(var r in e.verifyOptions)n[r]=e.verifyOptions[r];n.verify=function(a,s,o){var l=Do(a),c=e.verify(e,a,s,o);if(c!==!0){if(typeof c==="object"&&!L.util.isArray(c)){var u=Error("The application rejected the certificate.");if(u.send=!0,u.alert={level:m.Alert.Level.fatal,description:m.Alert.Description.bad_certificate},c.message)u.message=c.message;if(c.alert)u.alert.description=c.alert;throw u}if(c!==a)c=yy(c)}return c},L.pki.verifyCertificateChain(e.caStore,t,n)}catch(a){var i=a;if(typeof i!=="object"||L.util.isArray(i))i={send:!0,alert:{level:m.Alert.Level.fatal,description:Do(a)}};if(!("send"in i))i.send=!0;if(!("alert"in i))i.alert={level:m.Alert.Level.fatal,description:Do(i.error)};e.error(e,i)}return!e.fail};m.createSessionCache=function(e,t){var n=null;if(e&&e.getSession&&e.setSession&&e.order)n=e;else{n={},n.cache=e||{},n.capacity=Math.max(t||100,1),n.order=[];for(var r in e)if(n.order.length<=t)n.order.push(r);else delete e[r];n.getSession=function(i){var a=null,s=null;if(i)s=L.util.bytesToHex(i);else if(n.order.length>0)s=n.order[0];if(s!==null&&s in n.cache){a=n.cache[s],delete n.cache[s];for(var o in n.order)if(n.order[o]===s){n.order.splice(o,1);break}}return a},n.setSession=function(i,a){if(n.order.length===n.capacity){var s=n.order.shift();delete n.cache[s]}var s=L.util.bytesToHex(i);n.order.push(s),n.cache[s]=a}}return n};m.createConnection=function(e){var t=null;if(e.caStore)if(L.util.isArray(e.caStore))t=L.pki.createCaStore(e.caStore);else t=e.caStore;else t=L.pki.createCaStore();var n=e.cipherSuites||null;if(n===null){n=[];for(var r in m.CipherSuites)n.push(m.CipherSuites[r])}var i=e.server?m.ConnectionEnd.server:m.ConnectionEnd.client,a=e.sessionCache?m.createSessionCache(e.sessionCache):null,s={version:{major:m.Version.major,minor:m.Version.minor},entity:i,sessionId:e.sessionId,caStore:t,sessionCache:a,cipherSuites:n,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(u,d,f,y){return d},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:L.util.createBuffer(),tlsData:L.util.createBuffer(),data:L.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(u,d){if(d.origin=d.origin||(u.entity===m.ConnectionEnd.client?"client":"server"),d.send)m.queue(u,m.createAlert(u,d.alert)),m.flush(u);var f=d.fatal!==!1;if(f)u.fail=!0;if(e.error(u,d),f)u.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};s.reset=function(u){s.version={major:m.Version.major,minor:m.Version.minor},s.record=null,s.session=null,s.peerCertificate=null,s.state={pending:null,current:null},s.expect=s.entity===m.ConnectionEnd.client?ty:ly,s.fragmented=null,s.records=[],s.open=!1,s.handshakes=0,s.handshaking=!1,s.isConnected=!1,s.fail=!(u||typeof u>"u"),s.input.clear(),s.tlsData.clear(),s.data.clear(),s.state.current=m.createConnectionState(s)},s.reset();var o=function(u,d){var f=d.type-m.ContentType.change_cipher_spec,y=Uo[u.entity][u.expect];if(f in y)y[f](u,d);else m.handleUnexpected(u,d)},l=function(u){var d=0,f=u.input,y=f.length();if(y<5)d=5-y;else{u.record={type:f.getByte(),version:{major:f.getByte(),minor:f.getByte()},length:f.getInt16(),fragment:L.util.createBuffer(),ready:!1};var p=u.record.version.major===u.version.major;if(p&&u.session&&u.session.version)p=u.record.version.minor===u.version.minor;if(!p)u.error(u,{message:"Incompatible TLS version.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.protocol_version}})}return d},c=function(u){var d=0,f=u.input,y=f.length();if(y<u.record.length)d=u.record.length-y;else{u.record.fragment.putBytes(f.getBytes(u.record.length)),f.compact();var p=u.state.current.read;if(p.update(u,u.record)){if(u.fragmented!==null)if(u.fragmented.type===u.record.type)u.fragmented.fragment.putBuffer(u.record.fragment),u.record=u.fragmented;else u.error(u,{message:"Invalid fragmented record.",send:!0,alert:{level:m.Alert.Level.fatal,description:m.Alert.Description.unexpected_message}});u.record.ready=!0}}return d};return s.handshake=function(u){if(s.entity!==m.ConnectionEnd.client)s.error(s,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(s.handshaking)s.error(s,{message:"Handshake already in progress.",fatal:!1});else{if(s.fail&&!s.open&&s.handshakes===0)s.fail=!1;s.handshaking=!0,u=u||"";var d=null;if(u.length>0){if(s.sessionCache)d=s.sessionCache.getSession(u);if(d===null)u=""}if(u.length===0&&s.sessionCache){if(d=s.sessionCache.getSession(),d!==null)u=d.id}if(s.session={id:u,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:L.md.md5.create(),sha1:L.md.sha1.create()},d)s.version=d.version,s.session.sp=d.sp;s.session.sp.client_random=m.createRandom().getBytes(),s.open=!0,m.queue(s,m.createRecord(s,{type:m.ContentType.handshake,data:m.createClientHello(s)})),m.flush(s)}},s.process=function(u){var d=0;if(u)s.input.putBytes(u);if(!s.fail){if(s.record!==null&&s.record.ready&&s.record.fragment.isEmpty())s.record=null;if(s.record===null)d=l(s);if(!s.fail&&s.record!==null&&!s.record.ready)d=c(s);if(!s.fail&&s.record!==null&&s.record.ready)o(s,s.record)}return d},s.prepare=function(u){return m.queue(s,m.createRecord(s,{type:m.ContentType.application_data,data:L.util.createBuffer(u)})),m.flush(s)},s.prepareHeartbeatRequest=function(u,d){if(u instanceof L.util.ByteBuffer)u=u.bytes();if(typeof d>"u")d=u.length;return s.expectedHeartbeatPayload=u,m.queue(s,m.createRecord(s,{type:m.ContentType.heartbeat,data:m.createHeartbeat(m.HeartbeatMessageType.heartbeat_request,u,d)})),m.flush(s)},s.close=function(u){if(!s.fail&&s.sessionCache&&s.session){var d={id:s.session.id,version:s.session.version,sp:s.session.sp};d.sp.keys=null,s.sessionCache.setSession(d.id,d)}if(s.open){if(s.open=!1,s.input.clear(),s.isConnected||s.handshaking)s.isConnected=s.handshaking=!1,m.queue(s,m.createAlert(s,{level:m.Alert.Level.warning,description:m.Alert.Description.close_notify})),m.flush(s);s.closed(s)}s.reset(u)},s};dd.exports=L.tls=L.tls||{};for(wi in m)if(typeof m[wi]!=="function")L.tls[wi]=m[wi];var wi;L.tls.prf_tls1=qa;L.tls.hmac_sha1=Jm;L.tls.createSessionCache=m.createSessionCache;L.tls.createConnection=m.createConnection});var hd=de(function(h1,pd){var Wr=me();Dr();Vo();var Ft=pd.exports=Wr.tls;Ft.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=Ft.BulkCipherAlgorithm.aes,e.cipher_type=Ft.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Ft.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:fd};Ft.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=Ft.BulkCipherAlgorithm.aes,e.cipher_type=Ft.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Ft.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:fd};function fd(e,t,n){var r=t.entity===Wr.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:Wr.cipher.createDecipher("AES-CBC",r?n.keys.server_write_key:n.keys.client_write_key),iv:r?n.keys.server_write_IV:n.keys.client_write_IV},e.write.cipherState={init:!1,cipher:Wr.cipher.createCipher("AES-CBC",r?n.keys.client_write_key:n.keys.server_write_key),iv:r?n.keys.client_write_IV:n.keys.server_write_IV},e.read.cipherFunction=by,e.write.cipherFunction=vy,e.read.macLength=e.write.macLength=n.mac_length,e.read.macFunction=e.write.macFunction=Ft.hmac_sha1}function vy(e,t){var n=!1,r=t.macFunction(t.macKey,t.sequenceNumber,e);e.fragment.putBytes(r),t.updateSequenceNumber();var i;if(e.version.minor===Ft.Versions.TLS_1_0.minor)i=t.cipherState.init?null:t.cipherState.iv;else i=Wr.random.getBytesSync(16);t.cipherState.init=!0;var a=t.cipherState.cipher;if(a.start({iv:i}),e.version.minor>=Ft.Versions.TLS_1_1.minor)a.output.putBytes(i);if(a.update(e.fragment),a.finish(xy))e.fragment=a.output,e.length=e.fragment.length(),n=!0;return n}function xy(e,t,n){if(!n){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function Sy(e,t,n){var r=!0;if(n){var i=t.length(),a=t.last();for(var s=i-1-a;s<i-1;++s)r=r&&t.at(s)==a;if(r)t.truncate(a+1)}return r}function by(e,t){var n=!1,r;if(e.version.minor===Ft.Versions.TLS_1_0.minor)r=t.cipherState.init?null:t.cipherState.iv;else r=e.fragment.getBytes(16);t.cipherState.init=!0;var i=t.cipherState.cipher;i.start({iv:r}),i.update(e.fragment),n=i.finish(Sy);var a=t.macLength,s=Wr.random.getBytesSync(a),o=i.output.length();if(o>=a)e.fragment=i.output.getBytes(o-a),s=i.output.getBytes(a);else e.fragment=i.output.getBytes();e.fragment=Wr.util.createBuffer(e.fragment),e.length=e.fragment.length();var l=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),n=Cy(t.macKey,s,l)&&n,n}function Cy(e,t,n){var r=Wr.hmac.create();return r.start("SHA1",e),r.update(t),t=r.digest().getBytes(),r.start(null,null),r.update(n),n=r.digest().getBytes(),t===n}});var Wo=de(function(g1,vd){var qe=me();tr();Pe();var Ti=vd.exports=qe.sha512=qe.sha512||{};qe.md.sha512=qe.md.algorithms.sha512=Ti;var md=qe.sha384=qe.sha512.sha384=qe.sha512.sha384||{};md.create=function(){return Ti.create("SHA-384")};qe.md.sha384=qe.md.algorithms.sha384=md;qe.sha512.sha256=qe.sha512.sha256||{create:function(){return Ti.create("SHA-512/256")}};qe.md["sha512/256"]=qe.md.algorithms["sha512/256"]=qe.sha512.sha256;qe.sha512.sha224=qe.sha512.sha224||{create:function(){return Ti.create("SHA-512/224")}};qe.md["sha512/224"]=qe.md.algorithms["sha512/224"]=qe.sha512.sha224;Ti.create=function(e){if(!yd)Ey();if(typeof e>"u")e="SHA-512";if(!(e in dn))throw Error("Invalid SHA-512 algorithm: "+e);var t=dn[e],n=null,r=qe.util.createBuffer(),i=Array(80);for(var a=0;a<80;++a)i[a]=[,,];var s=64;switch(e){case"SHA-384":s=48;break;case"SHA-512/256":s=32;break;case"SHA-512/224":s=28;break}var o={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:s,messageLength:0,fullMessageLength:null,messageLengthSize:16};return o.start=function(){o.messageLength=0,o.fullMessageLength=o.messageLength128=[];var l=o.messageLengthSize/4;for(var c=0;c<l;++c)o.fullMessageLength.push(0);r=qe.util.createBuffer(),n=Array(t.length);for(var c=0;c<t.length;++c)n[c]=t[c].slice(0);return o},o.start(),o.update=function(l,c){if(c==="utf8")l=qe.util.encodeUtf8(l);var u=l.length;o.messageLength+=u,u=[u/4294967296>>>0,u>>>0];for(var d=o.fullMessageLength.length-1;d>=0;--d)o.fullMessageLength[d]+=u[1],u[1]=u[0]+(o.fullMessageLength[d]/4294967296>>>0),o.fullMessageLength[d]=o.fullMessageLength[d]>>>0,u[0]=u[1]/4294967296>>>0;if(r.putBytes(l),gd(n,i,r),r.read>2048||r.length()===0)r.compact();return o},o.digest=function(){var l=qe.util.createBuffer();l.putBytes(r.bytes());var c=o.fullMessageLength[o.fullMessageLength.length-1]+o.messageLengthSize,u=c&o.blockLength-1;l.putBytes(Fo.substr(0,o.blockLength-u));var d,f,y=o.fullMessageLength[0]*8;for(var p=0;p<o.fullMessageLength.length-1;++p)d=o.fullMessageLength[p+1]*8,f=d/4294967296>>>0,y+=f,l.putInt32(y>>>0),y=d>>>0;l.putInt32(y);var v=Array(n.length);for(var p=0;p<n.length;++p)v[p]=n[p].slice(0);gd(v,i,l);var x=qe.util.createBuffer(),b;if(e==="SHA-512")b=v.length;else if(e==="SHA-384")b=v.length-2;else b=v.length-4;for(var p=0;p<b;++p)if(x.putInt32(v[p][0]),p!==b-1||e!=="SHA-512/224")x.putInt32(v[p][1]);return x},o};var Fo=null,yd=!1,Mo=null,dn=null;function Ey(){Fo=String.fromCharCode(128),Fo+=qe.util.fillString(String.fromCharCode(0),128),Mo=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],dn={},dn["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],dn["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],dn["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],dn["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],yd=!0}function gd(e,t,n){var r,i,a,s,o,l,c,u,d,f,y,p,v,x,b,A,E,k,I,R,M,ee,O,K,ie,ve,we,rt,_e,Ve,V,te,Q,ue,ce,Z=n.length();while(Z>=128){for(_e=0;_e<16;++_e)t[_e][0]=n.getInt32()>>>0,t[_e][1]=n.getInt32()>>>0;for(;_e<80;++_e)te=t[_e-2],Ve=te[0],V=te[1],r=((Ve>>>19|V<<13)^(V>>>29|Ve<<3)^Ve>>>6)>>>0,i=((Ve<<13|V>>>19)^(V<<3|Ve>>>29)^(Ve<<26|V>>>6))>>>0,ue=t[_e-15],Ve=ue[0],V=ue[1],a=((Ve>>>1|V<<31)^(Ve>>>8|V<<24)^Ve>>>7)>>>0,s=((Ve<<31|V>>>1)^(Ve<<24|V>>>8)^(Ve<<25|V>>>7))>>>0,Q=t[_e-7],ce=t[_e-16],V=i+Q[1]+s+ce[1],t[_e][0]=r+Q[0]+a+ce[0]+(V/4294967296>>>0)>>>0,t[_e][1]=V>>>0;v=e[0][0],x=e[0][1],b=e[1][0],A=e[1][1],E=e[2][0],k=e[2][1],I=e[3][0],R=e[3][1],M=e[4][0],ee=e[4][1],O=e[5][0],K=e[5][1],ie=e[6][0],ve=e[6][1],we=e[7][0],rt=e[7][1];for(_e=0;_e<80;++_e)c=((M>>>14|ee<<18)^(M>>>18|ee<<14)^(ee>>>9|M<<23))>>>0,u=((M<<18|ee>>>14)^(M<<14|ee>>>18)^(ee<<23|M>>>9))>>>0,d=(ie^M&(O^ie))>>>0,f=(ve^ee&(K^ve))>>>0,o=((v>>>28|x<<4)^(x>>>2|v<<30)^(x>>>7|v<<25))>>>0,l=((v<<4|x>>>28)^(x<<30|v>>>2)^(x<<25|v>>>7))>>>0,y=(v&b|E&(v^b))>>>0,p=(x&A|k&(x^A))>>>0,V=rt+u+f+Mo[_e][1]+t[_e][1],r=we+c+d+Mo[_e][0]+t[_e][0]+(V/4294967296>>>0)>>>0,i=V>>>0,V=l+p,a=o+y+(V/4294967296>>>0)>>>0,s=V>>>0,we=ie,rt=ve,ie=O,ve=K,O=M,K=ee,V=R+i,M=I+r+(V/4294967296>>>0)>>>0,ee=V>>>0,I=E,R=k,E=b,k=A,b=v,A=x,V=i+s,v=r+a+(V/4294967296>>>0)>>>0,x=V>>>0;V=e[0][1]+x,e[0][0]=e[0][0]+v+(V/4294967296>>>0)>>>0,e[0][1]=V>>>0,V=e[1][1]+A,e[1][0]=e[1][0]+b+(V/4294967296>>>0)>>>0,e[1][1]=V>>>0,V=e[2][1]+k,e[2][0]=e[2][0]+E+(V/4294967296>>>0)>>>0,e[2][1]=V>>>0,V=e[3][1]+R,e[3][0]=e[3][0]+I+(V/4294967296>>>0)>>>0,e[3][1]=V>>>0,V=e[4][1]+ee,e[4][0]=e[4][0]+M+(V/4294967296>>>0)>>>0,e[4][1]=V>>>0,V=e[5][1]+K,e[5][0]=e[5][0]+O+(V/4294967296>>>0)>>>0,e[5][1]=V>>>0,V=e[6][1]+ve,e[6][0]=e[6][0]+ie+(V/4294967296>>>0)>>>0,e[6][1]=V>>>0,V=e[7][1]+rt,e[7][0]=e[7][0]+we+(V/4294967296>>>0)>>>0,e[7][1]=V>>>0,Z-=128}}});var xd=de(function(Ty){var wy=me();qt();var pt=wy.asn1;Ty.privateKeyValidator={name:"PrivateKeyInfo",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:pt.Class.UNIVERSAL,type:pt.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:pt.Class.UNIVERSAL,type:pt.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:pt.Class.UNIVERSAL,type:pt.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};Ty.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:pt.Class.UNIVERSAL,type:pt.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:pt.Class.UNIVERSAL,type:pt.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var Bd=de(function(y1,Rd){var yt=me();Si();Dt();Wo();Pe();var wd=xd(),{publicKeyValidator:ky,privateKeyValidator:Iy}=wd;if(typeof Ho>"u")Ho=yt.jsbn.BigInteger;var Ho,Ko=yt.util.ByteBuffer,At=typeof Buffer>"u"?Uint8Array:Buffer;yt.pki=yt.pki||{};Rd.exports=yt.pki.ed25519=yt.ed25519=yt.ed25519||{};var Ee=yt.ed25519;Ee.constants={};Ee.constants.PUBLIC_KEY_BYTE_LENGTH=32;Ee.constants.PRIVATE_KEY_BYTE_LENGTH=64;Ee.constants.SEED_BYTE_LENGTH=32;Ee.constants.SIGN_BYTE_LENGTH=64;Ee.constants.HASH_BYTE_LENGTH=64;Ee.generateKeyPair=function(e){e=e||{};var t=e.seed;if(t===void 0)t=yt.random.getBytesSync(Ee.constants.SEED_BYTE_LENGTH);else if(typeof t==="string"){if(t.length!==Ee.constants.SEED_BYTE_LENGTH)throw TypeError('"seed" must be '+Ee.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(t instanceof Uint8Array))throw TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');t=br({message:t,encoding:"binary"});var n=new At(Ee.constants.PUBLIC_KEY_BYTE_LENGTH),r=new At(Ee.constants.PRIVATE_KEY_BYTE_LENGTH);for(var i=0;i<32;++i)r[i]=t[i];return Ny(n,r),{publicKey:n,privateKey:r}};Ee.privateKeyFromAsn1=function(e){var t={},n=[],r=yt.asn1.validate(e,Iy,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var a=yt.asn1.derToOid(t.privateKeyOid),s=yt.oids.EdDSA25519;if(a!==s)throw Error('Invalid OID "'+a+'"; OID must be "'+s+'".');var o=t.privateKey,l=br({message:yt.asn1.fromDer(o).value,encoding:"binary"});return{privateKeyBytes:l}};Ee.publicKeyFromAsn1=function(e){var t={},n=[],r=yt.asn1.validate(e,ky,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var a=yt.asn1.derToOid(t.publicKeyOid),s=yt.oids.EdDSA25519;if(a!==s)throw Error('Invalid OID "'+a+'"; OID must be "'+s+'".');var o=t.ed25519PublicKey;if(o.length!==Ee.constants.PUBLIC_KEY_BYTE_LENGTH)throw Error("Key length is invalid.");return br({message:o,encoding:"binary"})};Ee.publicKeyFromPrivateKey=function(e){e=e||{};var t=br({message:e.privateKey,encoding:"binary"});if(t.length!==Ee.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+Ee.constants.PRIVATE_KEY_BYTE_LENGTH);var n=new At(Ee.constants.PUBLIC_KEY_BYTE_LENGTH);for(var r=0;r<n.length;++r)n[r]=t[32+r];return n};Ee.sign=function(e){e=e||{};var t=br(e),n=br({message:e.privateKey,encoding:"binary"});if(n.length===Ee.constants.SEED_BYTE_LENGTH){var r=Ee.generateKeyPair({seed:n});n=r.privateKey}else if(n.length!==Ee.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+Ee.constants.SEED_BYTE_LENGTH+" or "+Ee.constants.PRIVATE_KEY_BYTE_LENGTH);var i=new At(Ee.constants.SIGN_BYTE_LENGTH+t.length);Dy(i,t,t.length,n);var a=new At(Ee.constants.SIGN_BYTE_LENGTH);for(var s=0;s<a.length;++s)a[s]=i[s];return a};Ee.verify=function(e){e=e||{};var t=br(e);if(e.signature===void 0)throw TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var n=br({message:e.signature,encoding:"binary"});if(n.length!==Ee.constants.SIGN_BYTE_LENGTH)throw TypeError('"options.signature" must have a byte length of '+Ee.constants.SIGN_BYTE_LENGTH);var r=br({message:e.publicKey,encoding:"binary"});if(r.length!==Ee.constants.PUBLIC_KEY_BYTE_LENGTH)throw TypeError('"options.publicKey" must have a byte length of '+Ee.constants.PUBLIC_KEY_BYTE_LENGTH);var i=new At(Ee.constants.SIGN_BYTE_LENGTH+t.length),a=new At(Ee.constants.SIGN_BYTE_LENGTH+t.length),s;for(s=0;s<Ee.constants.SIGN_BYTE_LENGTH;++s)i[s]=n[s];for(s=0;s<t.length;++s)i[s+Ee.constants.SIGN_BYTE_LENGTH]=t[s];return Ly(a,i,i.length,r)>=0};function br(e){var t=e.message;if(t instanceof Uint8Array||t instanceof At)return t;var n=e.encoding;if(t===void 0)if(e.md)t=e.md.digest().getBytes(),n="binary";else throw TypeError('"options.message" or "options.md" not specified.');if(typeof t==="string"&&!n)throw TypeError('"options.encoding" must be "binary" or "utf8".');if(typeof t==="string"){if(typeof Buffer<"u")return Buffer.from(t,n);t=new Ko(t,n)}else if(!(t instanceof Ko))throw TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');var r=new At(t.length());for(var i=0;i<r.length;++i)r[i]=t.at(i);return r}var qo=se(),Ga=se([1]),Ry=se([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),By=se([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),Sd=se([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),bd=se([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),Ai=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),Py=se([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function _i(e,t){var n=yt.md.sha512.create(),r=new Ko(e);n.update(r.getBytes(t),"binary");var i=n.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(i,"binary");var a=new At(Ee.constants.HASH_BYTE_LENGTH);for(var s=0;s<64;++s)a[s]=i.charCodeAt(s);return a}function Ny(e,t){var n=[se(),se(),se(),se()],r,i=_i(t,32);i[0]&=248,i[31]&=127,i[31]|=64,Qo(n,i),zo(e,n);for(r=0;r<32;++r)t[r+32]=e[r];return 0}function Dy(e,t,n,r){var i,a,s=new Float64Array(64),o=[se(),se(),se(),se()],l=_i(r,32);l[0]&=248,l[31]&=127,l[31]|=64;var c=n+64;for(i=0;i<n;++i)e[64+i]=t[i];for(i=0;i<32;++i)e[32+i]=l[32+i];var u=_i(e.subarray(32),n+32);Go(u),Qo(o,u),zo(e,o);for(i=32;i<64;++i)e[i]=r[i];var d=_i(e,n+64);Go(d);for(i=32;i<64;++i)s[i]=0;for(i=0;i<32;++i)s[i]=u[i];for(i=0;i<32;++i)for(a=0;a<32;a++)s[i+a]+=d[i]*l[a];return Td(e.subarray(32),s),c}function Ly(e,t,n,r){var i,a,s=new At(32),o=[se(),se(),se(),se()],l=[se(),se(),se(),se()];if(a=-1,n<64)return-1;if(Uy(l,r))return-1;if(!Oy(t,32))return-1;for(i=0;i<n;++i)e[i]=t[i];for(i=0;i<32;++i)e[i+32]=r[i];var c=_i(e,n);if(Go(c),kd(o,l,c),Qo(l,t.subarray(32)),jo(o,l),zo(s,o),n-=64,Ad(t,0,s,0)){for(i=0;i<n;++i)e[i]=0;return-1}for(i=0;i<n;++i)e[i]=t[i+64];return a=n,a}function Oy(e,t){var n;for(n=31;n>=0;--n){if(e[t+n]<Ai[n])return!0;if(e[t+n]>Ai[n])return!1}return!1}function Td(e,t){var n,r,i,a;for(r=63;r>=32;--r){n=0;for(i=r-32,a=r-12;i<a;++i)t[i]+=n-16*t[r]*Ai[i-(r-32)],n=t[i]+128>>8,t[i]-=n*256;t[i]+=n,t[r]=0}n=0;for(i=0;i<32;++i)t[i]+=n-(t[31]>>4)*Ai[i],n=t[i]>>8,t[i]&=255;for(i=0;i<32;++i)t[i]-=n*Ai[i];for(r=0;r<32;++r)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function Go(e){var t=new Float64Array(64);for(var n=0;n<64;++n)t[n]=e[n],e[n]=0;Td(e,t)}function jo(e,t){var n=se(),r=se(),i=se(),a=se(),s=se(),o=se(),l=se(),c=se(),u=se();On(n,e[1],e[0]),On(u,t[1],t[0]),Fe(n,n,u),Ln(r,e[0],e[1]),Ln(u,t[0],t[1]),Fe(r,r,u),Fe(i,e[3],t[3]),Fe(i,i,By),Fe(a,e[2],t[2]),Ln(a,a,a),On(s,r,n),On(o,a,i),Ln(l,a,i),Ln(c,r,n),Fe(e[0],s,o),Fe(e[1],c,l),Fe(e[2],l,o),Fe(e[3],s,c)}function Cd(e,t,n){for(var r=0;r<4;++r)Id(e[r],t[r],n)}function zo(e,t){var n=se(),r=se(),i=se();Wy(i,t[2]),Fe(n,t[0],i),Fe(r,t[1],i),ja(e,r),e[31]^=_d(n)<<7}function ja(e,t){var n,r,i,a=se(),s=se();for(n=0;n<16;++n)s[n]=t[n];$o(s),$o(s),$o(s);for(r=0;r<2;++r){a[0]=s[0]-65517;for(n=1;n<15;++n)a[n]=s[n]-65535-(a[n-1]>>16&1),a[n-1]&=65535;a[15]=s[15]-32767-(a[14]>>16&1),i=a[15]>>16&1,a[14]&=65535,Id(s,a,1-i)}for(n=0;n<16;n++)e[2*n]=s[n]&255,e[2*n+1]=s[n]>>8}function Uy(e,t){var n=se(),r=se(),i=se(),a=se(),s=se(),o=se(),l=se();if($r(e[2],Ga),Vy(e[1],t),fn(i,e[1]),Fe(a,i,Ry),On(i,i,e[2]),Ln(a,e[2],a),fn(s,a),fn(o,s),Fe(l,o,s),Fe(n,l,i),Fe(n,n,a),Fy(n,n),Fe(n,n,i),Fe(n,n,a),Fe(n,n,a),Fe(e[0],n,a),fn(r,e[0]),Fe(r,r,a),Ed(r,i))Fe(e[0],e[0],Py);if(fn(r,e[0]),Fe(r,r,a),Ed(r,i))return-1;if(_d(e[0])===t[31]>>7)On(e[0],qo,e[0]);return Fe(e[3],e[0],e[1]),0}function Vy(e,t){var n;for(n=0;n<16;++n)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function Fy(e,t){var n=se(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=250;r>=0;--r)if(fn(n,n),r!==1)Fe(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function Ed(e,t){var n=new At(32),r=new At(32);return ja(n,e),ja(r,t),Ad(n,0,r,0)}function Ad(e,t,n,r){return My(e,t,n,r,32)}function My(e,t,n,r,i){var a,s=0;for(a=0;a<i;++a)s|=e[t+a]^n[r+a];return(1&s-1>>>8)-1}function _d(e){var t=new At(32);return ja(t,e),t[0]&1}function kd(e,t,n){var r,i;$r(e[0],qo),$r(e[1],Ga),$r(e[2],Ga),$r(e[3],qo);for(i=255;i>=0;--i)r=n[i/8|0]>>(i&7)&1,Cd(e,t,r),jo(t,e),jo(e,e),Cd(e,t,r)}function Qo(e,t){var n=[se(),se(),se(),se()];$r(n[0],Sd),$r(n[1],bd),$r(n[2],Ga),Fe(n[3],Sd,bd),kd(e,n,t)}function $r(e,t){var n;for(n=0;n<16;n++)e[n]=t[n]|0}function Wy(e,t){var n=se(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=253;r>=0;--r)if(fn(n,n),r!==2&&r!==4)Fe(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function $o(e){var t,n,r=1;for(t=0;t<16;++t)n=e[t]+r+65535,r=Math.floor(n/65536),e[t]=n-r*65536;e[0]+=r-1+37*(r-1)}function Id(e,t,n){var r,i=~(n-1);for(var a=0;a<16;++a)r=i&(e[a]^t[a]),e[a]^=r,t[a]^=r}function se(e){var t,n=new Float64Array(16);if(e)for(t=0;t<e.length;++t)n[t]=e[t];return n}function Ln(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]+n[r]}function On(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]-n[r]}function fn(e,t){Fe(e,t,t)}function Fe(e,t,n){var r,i,a=0,s=0,o=0,l=0,c=0,u=0,d=0,f=0,y=0,p=0,v=0,x=0,b=0,A=0,E=0,k=0,I=0,R=0,M=0,ee=0,O=0,K=0,ie=0,ve=0,we=0,rt=0,_e=0,Ve=0,V=0,te=0,Q=0,ue=n[0],ce=n[1],Z=n[2],Ie=n[3],We=n[4],ze=n[5],ae=n[6],he=n[7],De=n[8],Oe=n[9],at=n[10],st=n[11],Qe=n[12],ot=n[13],lt=n[14],Xe=n[15];r=t[0],a+=r*ue,s+=r*ce,o+=r*Z,l+=r*Ie,c+=r*We,u+=r*ze,d+=r*ae,f+=r*he,y+=r*De,p+=r*Oe,v+=r*at,x+=r*st,b+=r*Qe,A+=r*ot,E+=r*lt,k+=r*Xe,r=t[1],s+=r*ue,o+=r*ce,l+=r*Z,c+=r*Ie,u+=r*We,d+=r*ze,f+=r*ae,y+=r*he,p+=r*De,v+=r*Oe,x+=r*at,b+=r*st,A+=r*Qe,E+=r*ot,k+=r*lt,I+=r*Xe,r=t[2],o+=r*ue,l+=r*ce,c+=r*Z,u+=r*Ie,d+=r*We,f+=r*ze,y+=r*ae,p+=r*he,v+=r*De,x+=r*Oe,b+=r*at,A+=r*st,E+=r*Qe,k+=r*ot,I+=r*lt,R+=r*Xe,r=t[3],l+=r*ue,c+=r*ce,u+=r*Z,d+=r*Ie,f+=r*We,y+=r*ze,p+=r*ae,v+=r*he,x+=r*De,b+=r*Oe,A+=r*at,E+=r*st,k+=r*Qe,I+=r*ot,R+=r*lt,M+=r*Xe,r=t[4],c+=r*ue,u+=r*ce,d+=r*Z,f+=r*Ie,y+=r*We,p+=r*ze,v+=r*ae,x+=r*he,b+=r*De,A+=r*Oe,E+=r*at,k+=r*st,I+=r*Qe,R+=r*ot,M+=r*lt,ee+=r*Xe,r=t[5],u+=r*ue,d+=r*ce,f+=r*Z,y+=r*Ie,p+=r*We,v+=r*ze,x+=r*ae,b+=r*he,A+=r*De,E+=r*Oe,k+=r*at,I+=r*st,R+=r*Qe,M+=r*ot,ee+=r*lt,O+=r*Xe,r=t[6],d+=r*ue,f+=r*ce,y+=r*Z,p+=r*Ie,v+=r*We,x+=r*ze,b+=r*ae,A+=r*he,E+=r*De,k+=r*Oe,I+=r*at,R+=r*st,M+=r*Qe,ee+=r*ot,O+=r*lt,K+=r*Xe,r=t[7],f+=r*ue,y+=r*ce,p+=r*Z,v+=r*Ie,x+=r*We,b+=r*ze,A+=r*ae,E+=r*he,k+=r*De,I+=r*Oe,R+=r*at,M+=r*st,ee+=r*Qe,O+=r*ot,K+=r*lt,ie+=r*Xe,r=t[8],y+=r*ue,p+=r*ce,v+=r*Z,x+=r*Ie,b+=r*We,A+=r*ze,E+=r*ae,k+=r*he,I+=r*De,R+=r*Oe,M+=r*at,ee+=r*st,O+=r*Qe,K+=r*ot,ie+=r*lt,ve+=r*Xe,r=t[9],p+=r*ue,v+=r*ce,x+=r*Z,b+=r*Ie,A+=r*We,E+=r*ze,k+=r*ae,I+=r*he,R+=r*De,M+=r*Oe,ee+=r*at,O+=r*st,K+=r*Qe,ie+=r*ot,ve+=r*lt,we+=r*Xe,r=t[10],v+=r*ue,x+=r*ce,b+=r*Z,A+=r*Ie,E+=r*We,k+=r*ze,I+=r*ae,R+=r*he,M+=r*De,ee+=r*Oe,O+=r*at,K+=r*st,ie+=r*Qe,ve+=r*ot,we+=r*lt,rt+=r*Xe,r=t[11],x+=r*ue,b+=r*ce,A+=r*Z,E+=r*Ie,k+=r*We,I+=r*ze,R+=r*ae,M+=r*he,ee+=r*De,O+=r*Oe,K+=r*at,ie+=r*st,ve+=r*Qe,we+=r*ot,rt+=r*lt,_e+=r*Xe,r=t[12],b+=r*ue,A+=r*ce,E+=r*Z,k+=r*Ie,I+=r*We,R+=r*ze,M+=r*ae,ee+=r*he,O+=r*De,K+=r*Oe,ie+=r*at,ve+=r*st,we+=r*Qe,rt+=r*ot,_e+=r*lt,Ve+=r*Xe,r=t[13],A+=r*ue,E+=r*ce,k+=r*Z,I+=r*Ie,R+=r*We,M+=r*ze,ee+=r*ae,O+=r*he,K+=r*De,ie+=r*Oe,ve+=r*at,we+=r*st,rt+=r*Qe,_e+=r*ot,Ve+=r*lt,V+=r*Xe,r=t[14],E+=r*ue,k+=r*ce,I+=r*Z,R+=r*Ie,M+=r*We,ee+=r*ze,O+=r*ae,K+=r*he,ie+=r*De,ve+=r*Oe,we+=r*at,rt+=r*st,_e+=r*Qe,Ve+=r*ot,V+=r*lt,te+=r*Xe,r=t[15],k+=r*ue,I+=r*ce,R+=r*Z,M+=r*Ie,ee+=r*We,O+=r*ze,K+=r*ae,ie+=r*he,ve+=r*De,we+=r*Oe,rt+=r*at,_e+=r*st,Ve+=r*Qe,V+=r*ot,te+=r*lt,Q+=r*Xe,a+=38*I,s+=38*R,o+=38*M,l+=38*ee,c+=38*O,u+=38*K,d+=38*ie,f+=38*ve,y+=38*we,p+=38*rt,v+=38*_e,x+=38*Ve,b+=38*V,A+=38*te,E+=38*Q,i=1,r=a+i+65535,i=Math.floor(r/65536),a=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=y+i+65535,i=Math.floor(r/65536),y=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=x+i+65535,i=Math.floor(r/65536),x=r-i*65536,r=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,r=A+i+65535,i=Math.floor(r/65536),A=r-i*65536,r=E+i+65535,i=Math.floor(r/65536),E=r-i*65536,r=k+i+65535,i=Math.floor(r/65536),k=r-i*65536,a+=i-1+37*(i-1),i=1,r=a+i+65535,i=Math.floor(r/65536),a=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=y+i+65535,i=Math.floor(r/65536),y=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=x+i+65535,i=Math.floor(r/65536),x=r-i*65536,r=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,r=A+i+65535,i=Math.floor(r/65536),A=r-i*65536,r=E+i+65535,i=Math.floor(r/65536),E=r-i*65536,r=k+i+65535,i=Math.floor(r/65536),k=r-i*65536,a+=i-1+37*(i-1),e[0]=a,e[1]=s,e[2]=o,e[3]=l,e[4]=c,e[5]=u,e[6]=d,e[7]=f,e[8]=y,e[9]=p,e[10]=v,e[11]=x,e[12]=b,e[13]=A,e[14]=E,e[15]=k}});var Ld=de(function(v1,Dd){var Rt=me();Pe();Dt();Si();Dd.exports=Rt.kem=Rt.kem||{};var Pd=Rt.jsbn.BigInteger;Rt.kem.rsa={};Rt.kem.rsa.create=function(e,t){t=t||{};var n=t.prng||Rt.random,r={};return r.encrypt=function(i,a){var s=Math.ceil(i.n.bitLength()/8),o;do o=new Pd(Rt.util.bytesToHex(n.getBytesSync(s)),16).mod(i.n);while(o.compareTo(Pd.ONE)<=0);o=Rt.util.hexToBytes(o.toString(16));var l=s-o.length;if(l>0)o=Rt.util.fillString(String.fromCharCode(0),l)+o;var c=i.encrypt(o,"NONE"),u=e.generate(o,a);return{encapsulation:c,key:u}},r.decrypt=function(i,a,s){var o=i.decrypt(a,"NONE");return e.generate(o,s)},r};Rt.kem.kdf1=function(e,t){Nd(this,e,0,t||e.digestLength)};Rt.kem.kdf2=function(e,t){Nd(this,e,1,t||e.digestLength)};function Nd(e,t,n,r){e.generate=function(i,a){var s=new Rt.util.ByteBuffer,o=Math.ceil(a/r)+n,l=new Rt.util.ByteBuffer;for(var c=n;c<o;++c){l.putInt32(c),t.start(),t.update(i+l.getBytes());var u=t.digest();s.putBytes(u.getBytes(r))}return s.truncate(s.length()-a),s.getBytes()}}});var Ud=de(function(x1,Od){var Te=me();Pe();Od.exports=Te.log=Te.log||{};Te.log.levels=["none","error","warning","info","debug","verbose","max"];var Xa={},Xo=[],ki=null;Te.log.LEVEL_LOCKED=2;Te.log.NO_LEVEL_CHECK=4;Te.log.INTERPOLATE=8;for(Mt=0;Mt<Te.log.levels.length;++Mt)za=Te.log.levels[Mt],Xa[za]={index:Mt,name:za.toUpperCase()};var za,Mt;Te.log.logMessage=function(e){var t=Xa[e.level].index;for(var n=0;n<Xo.length;++n){var r=Xo[n];if(r.flags&Te.log.NO_LEVEL_CHECK)r.f(e);else{var i=Xa[r.level].index;if(t<=i)r.f(r,e)}}};Te.log.prepareStandard=function(e){if(!("standard"in e))e.standard=Xa[e.level].name+" ["+e.category+"] "+e.message};Te.log.prepareFull=function(e){if(!("full"in e)){var t=[e.message];t=t.concat([]),e.full=Te.util.format.apply(this,t)}};Te.log.prepareStandardFull=function(e){if(!("standardFull"in e))Te.log.prepareStandard(e),e.standardFull=e.standard};Qa=["error","warning","info","debug","verbose"];for(Mt=0;Mt<Qa.length;++Mt)(function(t){Te.log[t]=function(n,r){var i=Array.prototype.slice.call(arguments).slice(2),a={timestamp:new Date,level:t,category:n,message:r,arguments:i};Te.log.logMessage(a)}})(Qa[Mt]);var Qa,Mt;Te.log.makeLogger=function(e){var t={flags:0,f:e};return Te.log.setLevel(t,"none"),t};Te.log.setLevel=function(e,t){var n=!1;if(e&&!(e.flags&Te.log.LEVEL_LOCKED))for(var r=0;r<Te.log.levels.length;++r){var i=Te.log.levels[r];if(t==i){e.level=t,n=!0;break}}return n};Te.log.lock=function(e,t){if(typeof t>"u"||t)e.flags|=Te.log.LEVEL_LOCKED;else e.flags&=~Te.log.LEVEL_LOCKED};Te.log.addLogger=function(e){Xo.push(e)};if(typeof console<"u"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug)Yo={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},Vn=function(e,t){Te.log.prepareStandard(t);var n=Yo[t.level],r=[t.standard];r=r.concat(t.arguments.slice()),n.apply(console,r)},pn=Te.log.makeLogger(Vn);else Vn=function(t,n){Te.log.prepareStandardFull(n),console.log(n.standardFull)},pn=Te.log.makeLogger(Vn);Te.log.setLevel(pn,"debug"),Te.log.addLogger(pn),ki=pn}else console={log:function(){}};var pn,Yo,Vn;if(ki!==null&&typeof window<"u"&&window.location){if(Un=new URL(window.location.href).searchParams,Un.has("console.level"))Te.log.setLevel(ki,Un.get("console.level").slice(-1)[0]);if(Un.has("console.lock")){if(Jo=Un.get("console.lock").slice(-1)[0],Jo=="true")Te.log.lock(ki)}}var Un,Jo;Te.log.consoleLogger=ki});var Fd=de(function(S1,Vd){Vd.exports=tr();ka();Rn();uo();Wo()});var $d=de(function(b1,Wd){var W=me();Dr();qt();vi();Lr();an();Ao();Dt();Pe();$a();var w=W.asn1,Et=Wd.exports=W.pkcs7=W.pkcs7||{};Et.messageFromPem=function(e){var t=W.pem.decode(e)[0];if(t.type!=="PKCS7"){var n=Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw n.headerType=t.type,n}if(t.procType&&t.procType.type==="ENCRYPTED")throw Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var r=w.fromDer(t.body);return Et.messageFromAsn1(r)};Et.messageToPem=function(e,t){var n={type:"PKCS7",body:w.toDer(e.toAsn1()).getBytes()};return W.pem.encode(n,{maxline:t})};Et.messageFromAsn1=function(e){var t={},n=[];if(!w.validate(e,Et.asn1.contentInfoValidator,t,n)){var r=Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw r.errors=n,r}var i=w.derToOid(t.contentType),a;switch(i){case W.pki.oids.envelopedData:a=Et.createEnvelopedData();break;case W.pki.oids.encryptedData:a=Et.createEncryptedData();break;case W.pki.oids.signedData:a=Et.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return a.fromAsn1(t.content.value[0]),a};Et.createSignedData=function(){var e=null;return e={type:W.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(r){if(el(e,r,Et.asn1.signedDataValidator),e.certificates=[],e.crls=[],e.digestAlgorithmIdentifiers=[],e.contentInfo=null,e.signerInfos=[],e.rawCapture.certificates){var i=e.rawCapture.certificates.value;for(var a=0;a<i.length;++a)e.certificates.push(W.pki.certificateFromAsn1(i[a]))}},toAsn1:function(){if(!e.contentInfo)e.sign();var r=[];for(var i=0;i<e.certificates.length;++i)r.push(W.pki.certificateToAsn1(e.certificates[i]));var a=[],s=w.create(w.Class.CONTEXT_SPECIFIC,0,!0,[w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,w.integerToDer(e.version).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SET,!0,e.digestAlgorithmIdentifiers),e.contentInfo])]);if(r.length>0)s.value[0].value.push(w.create(w.Class.CONTEXT_SPECIFIC,0,!0,r));if(a.length>0)s.value[0].value.push(w.create(w.Class.CONTEXT_SPECIFIC,1,!0,a));return s.value[0].value.push(w.create(w.Class.UNIVERSAL,w.Type.SET,!0,e.signerInfos)),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(e.type).getBytes()),s])},addSigner:function(r){var{issuer:i,serialNumber:a}=r;if(r.certificate){var s=r.certificate;if(typeof s==="string")s=W.pki.certificateFromPem(s);i=s.issuer.attributes,a=s.serialNumber}var o=r.key;if(!o)throw Error("Could not add PKCS#7 signer; no private key specified.");if(typeof o==="string")o=W.pki.privateKeyFromPem(o);var l=r.digestAlgorithm||W.pki.oids.sha1;switch(l){case W.pki.oids.sha1:case W.pki.oids.sha256:case W.pki.oids.sha384:case W.pki.oids.sha512:case W.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+l)}var c=r.authenticatedAttributes||[];if(c.length>0){var u=!1,d=!1;for(var f=0;f<c.length;++f){var y=c[f];if(!u&&y.type===W.pki.oids.contentType){if(u=!0,d)break;continue}if(!d&&y.type===W.pki.oids.messageDigest){if(d=!0,u)break;continue}}if(!u||!d)throw Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}e.signers.push({key:o,version:1,issuer:i,serialNumber:a,digestAlgorithm:l,signatureAlgorithm:W.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:c,unauthenticatedAttributes:[]})},sign:function(r){if(r=r||{},typeof e.content!=="object"||e.contentInfo===null){if(e.contentInfo=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(W.pki.oids.data).getBytes())]),"content"in e){var i;if(e.content instanceof W.util.ByteBuffer)i=e.content.bytes();else if(typeof e.content==="string")i=W.util.encodeUtf8(e.content);if(r.detached)e.detachedContent=w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,i);else e.contentInfo.value.push(w.create(w.Class.CONTEXT_SPECIFIC,0,!0,[w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,i)]))}}if(e.signers.length===0)return;var a=t();n(a)},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(r){if(typeof r==="string")r=W.pki.certificateFromPem(r);e.certificates.push(r)},addCertificateRevokationList:function(r){throw Error("PKCS#7 CRL support not yet implemented.")}},e;function t(){var r={};for(var i=0;i<e.signers.length;++i){var a=e.signers[i],s=a.digestAlgorithm;if(!(s in r))r[s]=W.md[W.pki.oids[s]].create();if(a.authenticatedAttributes.length===0)a.md=r[s];else a.md=W.md[W.pki.oids[s]].create()}e.digestAlgorithmIdentifiers=[];for(var s in r)e.digestAlgorithmIdentifiers.push(w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(s).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.NULL,!1,"")]));return r}function n(r){var i;if(e.detachedContent)i=e.detachedContent;else i=e.contentInfo.value[1],i=i.value[0];if(!i)throw Error("Could not sign PKCS#7 message; there is no content to sign.");var a=w.derToOid(e.contentInfo.value[0].value),s=w.toDer(i);s.getByte(),w.getBerValueLength(s),s=s.getBytes();for(var o in r)r[o].start().update(s);var l=new Date;for(var c=0;c<e.signers.length;++c){var u=e.signers[c];if(u.authenticatedAttributes.length===0){if(a!==W.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{u.authenticatedAttributesAsn1=w.create(w.Class.CONTEXT_SPECIFIC,0,!0,[]);var d=w.create(w.Class.UNIVERSAL,w.Type.SET,!0,[]);for(var f=0;f<u.authenticatedAttributes.length;++f){var y=u.authenticatedAttributes[f];if(y.type===W.pki.oids.messageDigest)y.value=r[u.digestAlgorithm].digest();else if(y.type===W.pki.oids.signingTime){if(!y.value)y.value=l}d.value.push(Zo(y)),u.authenticatedAttributesAsn1.value.push(Zo(y))}s=w.toDer(d).getBytes(),u.md.start().update(s)}u.signature=u.key.sign(u.md,"RSASSA-PKCS1-V1_5")}e.signerInfos=jy(e.signers)}};Et.createEncryptedData=function(){var e=null;return e={type:W.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:W.pki.oids["aes256-CBC"]},fromAsn1:function(t){el(e,t,Et.asn1.encryptedDataValidator)},decrypt:function(t){if(t!==void 0)e.encryptedContent.key=t;Md(e)}},e};Et.createEnvelopedData=function(){var e=null;return e={type:W.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:W.pki.oids["aes256-CBC"]},fromAsn1:function(t){var n=el(e,t,Et.asn1.envelopedDataValidator);e.recipients=Ky(n.recipientInfos.value)},toAsn1:function(){return w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(e.type).getBytes()),w.create(w.Class.CONTEXT_SPECIFIC,0,!0,[w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,w.integerToDer(e.version).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SET,!0,qy(e.recipients)),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,zy(e.encryptedContent))])])])},findRecipient:function(t){var n=t.issuer.attributes;for(var r=0;r<e.recipients.length;++r){var i=e.recipients[r],a=i.issuer;if(i.serialNumber!==t.serialNumber)continue;if(a.length!==n.length)continue;var s=!0;for(var o=0;o<n.length;++o)if(a[o].type!==n[o].type||a[o].value!==n[o].value){s=!1;break}if(s)return i}return null},decrypt:function(t,n){if(e.encryptedContent.key===void 0&&t!==void 0&&n!==void 0)switch(t.encryptedContent.algorithm){case W.pki.oids.rsaEncryption:case W.pki.oids.desCBC:var r=n.decrypt(t.encryptedContent.content);e.encryptedContent.key=W.util.createBuffer(r);break;default:throw Error("Unsupported asymmetric cipher, OID "+t.encryptedContent.algorithm)}Md(e)},addRecipient:function(t){e.recipients.push({version:0,issuer:t.issuer.attributes,serialNumber:t.serialNumber,encryptedContent:{algorithm:W.pki.oids.rsaEncryption,key:t.publicKey}})},encrypt:function(t,n){if(e.encryptedContent.content===void 0){n=n||e.encryptedContent.algorithm,t=t||e.encryptedContent.key;var r,i,a;switch(n){case W.pki.oids["aes128-CBC"]:r=16,i=16,a=W.aes.createEncryptionCipher;break;case W.pki.oids["aes192-CBC"]:r=24,i=16,a=W.aes.createEncryptionCipher;break;case W.pki.oids["aes256-CBC"]:r=32,i=16,a=W.aes.createEncryptionCipher;break;case W.pki.oids["des-EDE3-CBC"]:r=24,i=8,a=W.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+n)}if(t===void 0)t=W.util.createBuffer(W.random.getBytes(r));else if(t.length()!=r)throw Error("Symmetric key has wrong length; got "+t.length()+" bytes, expected "+r+".");e.encryptedContent.algorithm=n,e.encryptedContent.key=t,e.encryptedContent.parameter=W.util.createBuffer(W.random.getBytes(i));var s=a(t);if(s.start(e.encryptedContent.parameter.copy()),s.update(e.content),!s.finish())throw Error("Symmetric encryption failed.");e.encryptedContent.content=s.output}for(var o=0;o<e.recipients.length;++o){var l=e.recipients[o];if(l.encryptedContent.content!==void 0)continue;switch(l.encryptedContent.algorithm){case W.pki.oids.rsaEncryption:l.encryptedContent.content=l.encryptedContent.key.encrypt(e.encryptedContent.key.data);break;default:throw Error("Unsupported asymmetric cipher, OID "+l.encryptedContent.algorithm)}}}},e};function $y(e){var t={},n=[];if(!w.validate(e,Et.asn1.recipientInfoValidator,t,n)){var r=Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw r.errors=n,r}return{version:t.version.charCodeAt(0),issuer:W.pki.RDNAttributesAsArray(t.issuer),serialNumber:W.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:w.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function Hy(e){return w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,w.integerToDer(e.version).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[W.pki.distinguishedNameToAsn1({attributes:e.issuer}),w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,W.util.hexToBytes(e.serialNumber))]),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(e.encryptedContent.algorithm).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.NULL,!1,"")]),w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function Ky(e){var t=[];for(var n=0;n<e.length;++n)t.push($y(e[n]));return t}function qy(e){var t=[];for(var n=0;n<e.length;++n)t.push(Hy(e[n]));return t}function Gy(e){var t=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,w.integerToDer(e.version).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[W.pki.distinguishedNameToAsn1({attributes:e.issuer}),w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,W.util.hexToBytes(e.serialNumber))]),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(e.digestAlgorithm).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.NULL,!1,"")])]);if(e.authenticatedAttributesAsn1)t.value.push(e.authenticatedAttributesAsn1);if(t.value.push(w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(e.signatureAlgorithm).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.NULL,!1,"")])),t.value.push(w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,e.signature)),e.unauthenticatedAttributes.length>0){var n=w.create(w.Class.CONTEXT_SPECIFIC,1,!0,[]);for(var r=0;r<e.unauthenticatedAttributes.length;++r){var i=e.unauthenticatedAttributes[r];n.values.push(Zo(i))}t.value.push(n)}return t}function jy(e){var t=[];for(var n=0;n<e.length;++n)t.push(Gy(e[n]));return t}function Zo(e){var t;if(e.type===W.pki.oids.contentType)t=w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(e.value).getBytes());else if(e.type===W.pki.oids.messageDigest)t=w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,e.value.bytes());else if(e.type===W.pki.oids.signingTime){var n=new Date("1950-01-01T00:00:00Z"),r=new Date("2050-01-01T00:00:00Z"),i=e.value;if(typeof i==="string"){var a=Date.parse(i);if(!isNaN(a))i=new Date(a);else if(i.length===13)i=w.utcTimeToDate(i);else i=w.generalizedTimeToDate(i)}if(i>=n&&i<r)t=w.create(w.Class.UNIVERSAL,w.Type.UTCTIME,!1,w.dateToUtcTime(i));else t=w.create(w.Class.UNIVERSAL,w.Type.GENERALIZEDTIME,!1,w.dateToGeneralizedTime(i))}return w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(e.type).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SET,!0,[t])])}function zy(e){return[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(W.pki.oids.data).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(e.algorithm).getBytes()),!e.parameter?void 0:w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,e.parameter.getBytes())]),w.create(w.Class.CONTEXT_SPECIFIC,0,!0,[w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,e.content.getBytes())])]}function el(e,t,n){var r={},i=[];if(!w.validate(t,n,r,i)){var a=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw a.errors=a,a}var s=w.derToOid(r.contentType);if(s!==W.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(r.encryptedContent){var o="";if(W.util.isArray(r.encryptedContent))for(var l=0;l<r.encryptedContent.length;++l){if(r.encryptedContent[l].type!==w.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");o+=r.encryptedContent[l].value}else o=r.encryptedContent;e.encryptedContent={algorithm:w.derToOid(r.encAlgorithm),parameter:W.util.createBuffer(r.encParameter.value),content:W.util.createBuffer(o)}}if(r.content){var o="";if(W.util.isArray(r.content))for(var l=0;l<r.content.length;++l){if(r.content[l].type!==w.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");o+=r.content[l].value}else o=r.content;e.content=W.util.createBuffer(o)}return e.version=r.version.charCodeAt(0),e.rawCapture=r,r}function Md(e){if(e.encryptedContent.key===void 0)throw Error("Symmetric key not available.");if(e.content===void 0){var t;switch(e.encryptedContent.algorithm){case W.pki.oids["aes128-CBC"]:case W.pki.oids["aes192-CBC"]:case W.pki.oids["aes256-CBC"]:t=W.aes.createDecryptionCipher(e.encryptedContent.key);break;case W.pki.oids.desCBC:case W.pki.oids["des-EDE3-CBC"]:t=W.des.createDecryptionCipher(e.encryptedContent.key);break;default:throw Error("Unsupported symmetric cipher, OID "+e.encryptedContent.algorithm)}if(t.start(e.encryptedContent.parameter),t.update(e.encryptedContent.content),!t.finish())throw Error("Symmetric decryption failed.");e.content=t.output}}});var Kd=de(function(C1,Hd){var it=me();Dr();An();ka();Rn();Pe();var Ja=Hd.exports=it.ssh=it.ssh||{};Ja.privateKeyToPutty=function(e,t,n){n=n||"",t=t||"";var r="ssh-rsa",i=t===""?"none":"aes256-cbc",a="PuTTY-User-Key-File-2: "+r+`\r
16
- `;a+="Encryption: "+i+`\r
17
- `,a+="Comment: "+n+`\r
18
- `;var s=it.util.createBuffer();Fn(s,r),cr(s,e.e),cr(s,e.n);var o=it.util.encode64(s.bytes(),64),l=Math.floor(o.length/66)+1;a+="Public-Lines: "+l+`\r
19
- `,a+=o;var c=it.util.createBuffer();cr(c,e.d),cr(c,e.p),cr(c,e.q),cr(c,e.qInv);var u;if(!t)u=it.util.encode64(c.bytes(),64);else{var d=c.length()+16-1;d-=d%16;var f=Ya(c.bytes());f.truncate(f.length()-d+c.length()),c.putBuffer(f);var y=it.util.createBuffer();y.putBuffer(Ya("\x00\x00\x00\x00",t)),y.putBuffer(Ya("\x00\x00\x00\x01",t));var p=it.aes.createEncryptionCipher(y.truncate(8),"CBC");p.start(it.util.createBuffer().fillWithByte(0,16)),p.update(c.copy()),p.finish();var v=p.output;v.truncate(16),u=it.util.encode64(v.bytes(),64)}l=Math.floor(u.length/66)+1,a+=`\r
20
- Private-Lines: `+l+`\r
21
- `,a+=u;var x=Ya("putty-private-key-file-mac-key",t),b=it.util.createBuffer();Fn(b,r),Fn(b,i),Fn(b,n),b.putInt32(s.length()),b.putBuffer(s),b.putInt32(c.length()),b.putBuffer(c);var A=it.hmac.create();return A.start("sha1",x),A.update(b.bytes()),a+=`\r
22
- Private-MAC: `+A.digest().toHex()+`\r
23
- `,a};Ja.publicKeyToOpenSSH=function(e,t){var n="ssh-rsa";t=t||"";var r=it.util.createBuffer();return Fn(r,n),cr(r,e.e),cr(r,e.n),n+" "+it.util.encode64(r.bytes())+" "+t};Ja.privateKeyToOpenSSH=function(e,t){if(!t)return it.pki.privateKeyToPem(e);return it.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:"aes128"})};Ja.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||it.md.md5.create(),r="ssh-rsa",i=it.util.createBuffer();Fn(i,r),cr(i,e.e),cr(i,e.n),n.start(),n.update(i.getBytes());var a=n.digest();if(t.encoding==="hex"){var s=a.toHex();if(t.delimiter)return s.match(/.{2}/g).join(t.delimiter);return s}else if(t.encoding==="binary")return a.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return a};function cr(e,t){var n=t.toString(16);if(n[0]>="8")n="00"+n;var r=it.util.hexToBytes(n);e.putInt32(r.length),e.putBytes(r)}function Fn(e,t){e.putInt32(t.length),e.putString(t)}function Ya(){var e=it.md.sha1.create(),t=arguments.length;for(var n=0;n<t;++n)e.update(arguments[n]);return e.digest()}});var tl=de(function(E1,qd){qd.exports=me();Dr();hd();qt();ba();vi();Bd();An();Ld();Ud();Fd();_o();Pa();an();So();Ro();$d();Po();Co();fo();Fa();Dt();go();Kd();Vo();Pe()});var Bf=de(function(TE,Rf){var{create:Qv,defineProperty:ls,getOwnPropertyDescriptor:Xv,getOwnPropertyNames:Yv,getPrototypeOf:Jv}=Object,Zv=Object.prototype.hasOwnProperty,ex=(e,t)=>{for(var n in t)ls(e,n,{get:t[n],enumerable:!0})},Tf=(e,t,n,r)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of Yv(t))if(!Zv.call(e,i)&&i!==n)ls(e,i,{get:()=>t[i],enumerable:!(r=Xv(t,i))||r.enumerable})}return e},Af=(e,t,n)=>(n=e!=null?Qv(Jv(e)):{},Tf(t||!e||!e.__esModule?ls(n,"default",{value:e,enumerable:!0}):n,e)),tx=(e)=>Tf(ls({},"__esModule",{value:!0}),e),_f={};ex(_f,{Socks5Server:()=>If,createServer:()=>ax,defaultConnectionHandler:()=>Al});Rf.exports=tx(_f);var rx=Af(li("net")),kf=((e)=>(e[e.connect=1]="connect",e[e.bind=2]="bind",e[e.udp=3]="udp",e))(kf||{}),Tl=((e)=>(e[e.REQUEST_GRANTED=0]="REQUEST_GRANTED",e[e.GENERAL_FAILURE=1]="GENERAL_FAILURE",e[e.CONNECTION_NOT_ALLOWED=2]="CONNECTION_NOT_ALLOWED",e[e.NETWORK_UNREACHABLE=3]="NETWORK_UNREACHABLE",e[e.HOST_UNREACHABLE=4]="HOST_UNREACHABLE",e[e.CONNECTION_REFUSED=5]="CONNECTION_REFUSED",e[e.TTL_EXPIRED=6]="TTL_EXPIRED",e[e.COMMAND_NOT_SUPPORTED=7]="COMMAND_NOT_SUPPORTED",e[e.ADDRESS_TYPE_NOT_SUPPORTED=8]="ADDRESS_TYPE_NOT_SUPPORTED",e))(Tl||{}),nx=class{constructor(e,t){this.errorHandler=()=>{},this.metadata={},this.socket=t,this.server=e,t.on("error",this.errorHandler),t.pause(),this.handleGreeting()}readBytes(e){return new Promise((t)=>{let n=Buffer.allocUnsafe(e),r=0,i=(a)=>{let s=Math.min(a.length,e-r);if(a.copy(n,r,0,s),r+=s,r<e)return;this.socket.removeListener("data",i),this.socket.push(a.subarray(s)),t(n),this.socket.pause()};this.socket.on("data",i),this.socket.resume()})}async handleGreeting(){if((await this.readBytes(1)).readUInt8()!==5)return this.socket.destroy();let t=(await this.readBytes(1)).readUInt8();if(t>128||t===0)return this.socket.destroy();let n=await this.readBytes(t),r=this.server.authHandler?2:0;if(!n.includes(r))return this.socket.write(Buffer.from([5,255])),this.socket.destroy();if(this.socket.write(Buffer.from([5,r])),this.server.authHandler)this.handleUserPassword();else this.handleConnectionRequest()}async handleUserPassword(){await this.readBytes(1);let e=(await this.readBytes(1)).readUint8(),t=(await this.readBytes(e)).toString(),n=(await this.readBytes(1)).readUint8(),r=(await this.readBytes(n)).toString();this.username=t,this.password=r;let i=!1,a=()=>{if(i)return;i=!0,this.socket.write(Buffer.from([1,0])),this.handleConnectionRequest()},s=()=>{if(i)return;i=!0,this.socket.write(Buffer.from([1,1])),this.socket.destroy()},o=await this.server.authHandler(this,a,s);if(o===!0)a();else if(o===!1)s()}async handleConnectionRequest(){await this.readBytes(1);let e=(await this.readBytes(1))[0],t=kf[e];if(!t)return this.socket.destroy();this.command=t,await this.readBytes(1);let n=(await this.readBytes(1)).readUInt8(),r="";switch(n){case 1:r=(await this.readBytes(4)).join(".");break;case 3:let c=(await this.readBytes(1)).readUInt8();r=(await this.readBytes(c)).toString();break;case 4:let u=await this.readBytes(16);for(let d=0;d<16;d++){if(d%2===0&&d>0)r+=":";r+=`${u[d]<16?"0":""}${u[d].toString(16)}`}break;default:this.socket.destroy();return}let i=(await this.readBytes(2)).readUInt16BE();if(!this.server.supportedCommands.has(t))return this.socket.write(Buffer.from([5,7])),this.socket.destroy();this.destAddress=r,this.destPort=i;let a=!1,s=()=>{if(a)return;a=!0,this.connect()};if(!this.server.rulesetValidator)return s();let o=()=>{if(a)return;a=!0,this.socket.write(Buffer.from([5,2,0,1,0,0,0,0,0,0])),this.socket.destroy()},l=await this.server.rulesetValidator(this,s,o);if(l===!0)s();else if(l===!1)o()}connect(){this.socket.removeListener("error",this.errorHandler),this.server.connectionHandler(this,(e)=>{if(Tl[e]===void 0)throw Error(`"${e}" is not a valid status.`);if(this.socket.write(Buffer.from([5,Tl[e],0,1,0,0,0,0,0,0])),e!=="REQUEST_GRANTED")this.socket.destroy()}),this.socket.resume()}},ix=Af(li("net"));function Al(e,t){if(e.command!=="connect")return t("COMMAND_NOT_SUPPORTED");e.socket.on("error",()=>{});let n=ix.default.createConnection({host:e.destAddress,port:e.destPort});n.setNoDelay();let r=!1;return n.on("error",(i)=>{if(!r)switch(i.code){case"EINVAL":case"ENOENT":case"ENOTFOUND":case"ETIMEDOUT":case"EADDRNOTAVAIL":case"EHOSTUNREACH":t("HOST_UNREACHABLE");break;case"ENETUNREACH":t("NETWORK_UNREACHABLE");break;case"ECONNREFUSED":t("CONNECTION_REFUSED");break;default:t("GENERAL_FAILURE")}}),n.on("ready",()=>{r=!0,t("REQUEST_GRANTED"),e.socket.pipe(n).pipe(e.socket)}),e.socket.on("close",()=>n.destroy()),n}var If=class{constructor(){this.supportedCommands=new Set(["connect"]),this.connectionHandler=Al,this.server=rx.default.createServer((e)=>{e.setNoDelay(),this._handleConnection(e)})}listen(...e){return this.server.listen(...e),this}close(e){return this.server.close(e),this}setAuthHandler(e){return this.authHandler=e,this}disableAuthHandler(){return this.authHandler=void 0,this}setRulesetValidator(e){return this.rulesetValidator=e,this}disableRulesetValidator(){return this.rulesetValidator=void 0,this}setConnectionHandler(e){return this.connectionHandler=e,this}useDefaultConnectionHandler(){return this.connectionHandler=Al,this}_handleConnection(e){return new nx(this,e),this}};function ax(e){let t=new If;if(e?.auth)t.setAuthHandler((n)=>n.username===e.auth.username&&n.password===e.auth.password);if(e?.port)t.listen(e.port,e.hostname);return t}});import{Agent as Hv,createServer as Kv}from"http";import{request as wl}from"http";import{request as Cf}from"https";import{connect as qv,isIP as Gv}from"net";import{URL as Ef}from"url";function C(e,t){if(!process.env.SRT_DEBUG)return;let n=t?.level||"info",r="[SandboxDebug]";switch(n){case"error":console.error(`${r} ${e}`);break;case"warn":console.warn(`${r} ${e}`);break;default:console.error(`${r} ${e}`)}}import{timingSafeEqual as t0}from"crypto";function ha(e,t){let n=Buffer.from(e),r=Buffer.from(t);if(n.length!==r.length)return!1;return t0(n,r)}import{homedir as ga}from"os";import*as ct from"path";import*as en from"fs";import*as Pc from"fs";function Qs(){if(process.platform!=="linux")return;try{let e=Pc.readFileSync("/proc/version",{encoding:"utf8"}),t=e.match(/WSL(\d+)/i);if(t&&t[1])return t[1];if(e.toLowerCase().includes("microsoft"))return"1";return}catch{return}}function Ne(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"unknown"}}var ci=[".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json"],r0=[".git",".vscode",".idea"];function ya(){return[...r0.filter((e)=>e!==".git"),".claude/commands",".claude/agents"]}function Xs(e){return e.toLowerCase()}function xt(e){return e.includes("*")||e.includes("?")||e.includes("[")||e.includes("]")}function ui(e){return e.includes("*")||e.includes("?")}function Nc(e){return Ne()==="windows"?ui(e):xt(e)}function Dc(e){if(/^\\\\\?\\unc\\/i.test(e))return"\\\\"+e.slice(8);if(e.startsWith("\\\\?\\"))return e.slice(4);return e}function di(e){let t=ct.win32.toNamespacedPath(e);return/^[\\/]{2}[?.][\\/]unc[\\/]/i.test(t)}function yr(e){return e.replace(/\/\*\*$/,"")||"/"}function ma(e,t){let n=ct.normalize(e),r=ct.normalize(t);if(r===n)return!1;if(n.startsWith("/tmp/")&&r==="/private"+n)return!1;if(n.startsWith("/var/")&&r==="/private"+n)return!1;if(n.startsWith("/private/tmp/")&&r===n)return!1;if(n.startsWith("/private/var/")&&r===n)return!1;if(r==="/")return!0;if(r.split("/").filter(Boolean).length<=1)return!0;if(n.startsWith(r+"/"))return!0;let a=n;if(n.startsWith("/tmp/"))a="/private"+n;else if(n.startsWith("/var/"))a="/private"+n;if(a!==n&&a.startsWith(r+"/"))return!0;let s=r.startsWith(n+"/"),o=a!==n&&r.startsWith(a+"/");if(r!==n&&!(a!==n&&r===a)&&!s&&!o)return!0;return!1}function n0(e){if(e==="~")return ga();if(e.startsWith("~/")||process.platform==="win32"&&e.startsWith("~\\"))return ga()+e.slice(1);return e}function i0(e){let t=ga(),n=/^[A-Za-z]:/.test(t)?t.slice(0,2):"",r=n?t.slice(2):t;return e.replace(/%USERPROFILE%/gi,t).replace(/%HOMEDRIVE%/gi,n).replace(/%HOMEPATH%/gi,r)}function nt(e){let t=process.cwd();if(Ne()==="windows"){if(e=Dc(i0(e)),/^[a-z]:/.test(e))e=e[0].toUpperCase()+e.slice(1);if(di(e)&&!ui(e))return ct.win32.normalize(e)}if(Ne()!=="windows"&&e.endsWith("/")&&e!=="/"&&!Nc(e))e=e.replace(/\/+$/,"")||"/";let n=n0(e);if(n!==e);else if(e.startsWith("./")||e.startsWith("../"))n=ct.resolve(t,e);else if(!ct.isAbsolute(e))n=ct.resolve(t,e);if(Nc(n)){let r=Ne()==="windows"?/[*?]/:/[*?[\]]/,i=n.split(r)[0];if(i&&i!=="/"){let a=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);try{let s=en.realpathSync(a);if(!ma(a,s)){let o=n.slice(a.length);return s+o}}catch{}}return n}try{let r=en.realpathSync(n);if(ma(n,r));else n=r}catch{}return n}function Cn(e){let t=e??ga();return["/dev/stdout","/dev/stderr","/dev/null","/dev/tty","/dev/dtracehelper","/dev/autofs_nowait","/tmp/claude","/private/tmp/claude",ct.join(t,".npm/_logs"),ct.join(t,".claude/debug")]}var a0=["NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","CURL_CA_BUNDLE","REQUESTS_CA_BUNDLE","PIP_CERT","GIT_SSL_CAINFO","AWS_CA_BUNDLE","CARGO_HTTP_CAINFO","DENO_CERT","CLOUDSDK_CORE_CUSTOM_CA_CERTS_FILE","NIX_SSL_CERT_FILE"];function En(e,t,n,r,i,a){let s=o0(a),o=s===mr?s:encodeURIComponent(s),l=r?`${o}:${r}@`:"",c=Ne()==="linux"?"127.0.0.1":"localhost",u=["SANDBOX_RUNTIME=1"];if(!i){let y=process.env.CLAUDE_CODE_TMPDIR||process.env.CLAUDE_TMPDIR||"/tmp/claude";u.push(`TMPDIR=${y}`)}if(n)for(let y of a0)u.push(`${y}=${n}`);if(!e&&!t)return u;let d=["localhost","127.0.0.1","::1","169.254.0.0/16","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"].join(",");if(u.push(`NO_PROXY=${d}`),u.push(`no_proxy=${d}`),e){if(u.push(`HTTP_PROXY=http://${l}${c}:${e}`),u.push(`HTTPS_PROXY=http://${l}${c}:${e}`),u.push(`http_proxy=http://${l}${c}:${e}`),u.push(`https_proxy=http://${l}${c}:${e}`),r)u.push("GIT_CONFIG_PARAMETERS='http.proxyAuthMethod=basic'")}let f=e?`http://${l}${c}:${e}`:`socks5h://${l}${c}:${t}`;if(u.push(`ALL_PROXY=${f}`),u.push(`all_proxy=${f}`),u.push(`GRPC_PROXY=${f}`),u.push(`grpc_proxy=${f}`),t){let p=Ne();if(p==="macos")u.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='nc -X 5 -x localhost:${t} %h %p'`);else if(p==="linux"&&e){let v=r?`,proxyauth=${s}:${r}`:"";u.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='socat - PROXY:${c}:%h:%p,proxyport=${e}${v}'`)}if(u.push(`FTP_PROXY=socks5h://${l}${c}:${t}`),u.push(`ftp_proxy=socks5h://${l}${c}:${t}`),u.push(`RSYNC_PROXY=${c}:${t}`),u.push(`DOCKER_HTTP_PROXY=http://${l}${c}:${e||t}`),u.push(`DOCKER_HTTPS_PROXY=http://${l}${c}:${e||t}`),e){if(u.push("CLOUDSDK_PROXY_TYPE=http"),u.push(`CLOUDSDK_PROXY_ADDRESS=${c}`),u.push(`CLOUDSDK_PROXY_PORT=${e}`),r)u.push(`CLOUDSDK_PROXY_USERNAME=${s}`),u.push(`CLOUDSDK_PROXY_PASSWORD=${r}`)}}return u}var s0=8;function fi(e){if(e.baseEnv?.GIT_CONFIG_COUNT==="0")return{};let t=Number.parseInt(e.baseEnv?.GIT_CONFIG_COUNT??"",10),n=Number.isFinite(t)&&t>=0?t:0,r=n,i={},a=(o,l)=>{i[`GIT_CONFIG_KEY_${r}`]=o,i[`GIT_CONFIG_VALUE_${r}`]=l,r++},s=[...new Set(e.safeDirs.filter((o)=>!!o).map((o)=>{let c=o.replace(/\\/g,"/").replace(/\/+$/,"");if(c===""||/^[A-Za-z]:$/.test(c))return`${c}/`;return c}))];if(s.length>s0)a("safe.directory","*");else for(let o of s)a("safe.directory",o),a("safe.directory",o.endsWith("/")?`${o}*`:`${o}/*`);if(e.schannelCa)a("http.schannelUseSSLCAInfo","true"),a("http.schannelCheckRevoke","false");if(r===n)return{};return i.GIT_CONFIG_COUNT=String(r),i}function va(e){let t={GIT_CONFIG_COUNT:process.env.GIT_CONFIG_COUNT};for(let n of e.unsetEnvVars??[])delete t[n];return Object.assign(t,e.setEnvVars??{}),fi({safeDirs:e.safeDirs,baseEnv:t})}function Nt(e){let t=e.slice(0,100);return Buffer.from(t).toString("base64")}function tn(e){return Buffer.from(e,"base64").toString("utf8")}var mr="srt";function o0(e){if(!e)return mr;let t=`${mr}.${e}`;return Buffer.byteLength(t)<=255?t:mr}function xa(e){if(!e||!e.startsWith(`${mr}.`))return;return e.slice(mr.length+1)||void 0}function pi(e){return"^"+e.replace(/[.^$+{}()|\\]/g,"\\$&").replace(/\[([^\]]*?)$/g,"\\[$1").replace(/\*\*\//g,"__GLOBSTAR_SLASH__").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/__GLOBSTAR_SLASH__/g,"(.*/)?").replace(/__GLOBSTAR__/g,".*")+"$"}function rn(e,t={}){let n=(l)=>process.platform==="win32"?l.replace(/\\/g,"/"):l,r=n(nt(e)),i=r.split(/[*?[\]]/)[0];if(!i||i==="/")return C(`[Sandbox] Glob pattern too broad, skipping: ${e}`),[];let a=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);if(!en.existsSync(a))return C(`[Sandbox] Base directory for glob does not exist: ${a}`),[];let s=new RegExp(pi(r),t.caseInsensitive?"i":""),o=[];try{let l=en.readdirSync(a,{recursive:!0,withFileTypes:!0});for(let c of l){let u=c.parentPath??c.path??a,d=ct.join(u,c.name);if(s.test(n(d)))o.push(d)}}catch(l){C(`[Sandbox] Error expanding glob pattern ${e}: ${l}`)}return o}var zd=zs(tl(),1);import{sign as Qy,X509Certificate as Xy}from"crypto";import{mkdtempSync as nl,readFileSync as il,writeFileSync as al}from"fs";import{rm as Yy}from"fs/promises";import{tmpdir as sl}from"os";import{join as Wn,dirname as rl}from"path";import{rootCertificates as Jy}from"tls";var{asn1:Je,pki:jt,md:Zy,random:ev,util:Qd}=zd.default,tv=jt.getTBSCertificate,rv=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,Za="/srt.crl";function ol(e){let t=e.getExtension("subjectKeyIdentifier");return t?.subjectKeyIdentifier?Qd.hexToBytes(t.subjectKeyIdentifier):e.generateSubjectKeyIdentifier().getBytes()}function ll(e,t){let n=jt.oids.sha256WithRSAEncryption;e.siginfo.algorithmOid=n,e.signatureOid=n,e.tbsCertificate=tv(e);let r=Je.toDer(e.tbsCertificate).getBytes();e.signature=Xd(r,t),e.md=Zy.sha256.create(),e.md.update(r)}function Xd(e,t){return Qy("sha256",Buffer.from(e,"binary"),t).toString("binary")}function cl(e){if(e.caCertPem&&e.caKeyPem){let t=Ri(e.caCertPem,e.caKeyPem);if(!t.ok)throw Error(`tlsTerminate: CA PEM pair: ${t.reason}`);return ul(e.caCertPem,e.caKeyPem,t.cert,t.key,{certPath:e.caCertPath??"",keyPath:e.caKeyPath??"",extraCaCertPaths:e.extraCaCertPaths})}if(e.caCertPath&&e.caKeyPath)return av(e.caCertPath,e.caKeyPath,e.extraCaCertPaths);if(e.caCertPath||e.caKeyPath)throw Error("tlsTerminate: caCertPath and caKeyPath must be provided together");return sv(e.extraCaCertPaths)}async function Yd(e){let t=new Set([rl(e.trustBundlePath)]);if(e.ephemeral){if(t.add(rl(e.certPath)),e.keyPath)t.add(rl(e.keyPath))}for(let n of t)try{await Yy(n,{recursive:!0,force:!0})}catch(r){C(`[mitm-ca] cleanup failed: ${r.message}`,{level:"warn"})}}function nv(e,t,n){let r=[t.trim(),...Jy],i=process.env.NODE_EXTRA_CA_CERTS;if(i)try{r.push(il(i,"utf8").trim())}catch{}for(let s of n??[]){let o;try{o=il(s,"utf8")}catch(c){let u=c.code??String(c);C(`[mitm-ca] extraCaCertPaths: cannot read ${s} (${u}); skipping`,{level:"warn"});continue}let l=o.match(rv);if(!l){C(`[mitm-ca] extraCaCertPaths: ${s} has no PEM CERTIFICATE block; skipping`,{level:"warn"});continue}r.push(...l)}let a=Wn(e,"trust-bundle.crt");return al(a,r.join(`
2
+ var dU=Object.create;var{getPrototypeOf:cU,defineProperty:c9,getOwnPropertyNames:nU}=Object;var iU=Object.prototype.hasOwnProperty;function oU($){return this[$]}var aU,sU,n9=($,J,X)=>{var Q=$!=null&&typeof $==="object";if(Q){var Y=J?aU??=new WeakMap:sU??=new WeakMap,G=Y.get($);if(G)return G}X=$!=null?dU(cU($)):{};let W=J||!$||!$.__esModule?c9(X,"default",{value:$,enumerable:!0}):X;for(let U of nU($))if(!iU.call(W,U))c9(W,U,{get:oU.bind($,U),enumerable:!0});if(Q)Y.set($,W);return W};var q$=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var rU=($)=>$;function tU($,J){this[$]=rU.bind(null,J)}var eU=($,J)=>{for(var X in J)c9($,X,{get:J[X],enumerable:!0,configurable:!0,set:tU.bind(J,X)})};var FX=import.meta.require;var F$=q$((LF,IG)=>{IG.exports={options:{usePureJavaScript:!1}}});var PG=q$((AF,wG)=>{var a9={};wG.exports=a9;var CG={};a9.encode=function($,J,X){if(typeof J!=="string")throw TypeError('"alphabet" must be a string.');if(X!==void 0&&typeof X!=="number")throw TypeError('"maxline" must be a number.');var Q="";if(!($ instanceof Uint8Array))Q=UM($,J);else{var Y=0,G=J.length,W=J.charAt(0),U=[0];for(Y=0;Y<$.length;++Y){for(var M=0,O=$[Y];M<U.length;++M)O+=U[M]<<8,U[M]=O%G,O=O/G|0;while(O>0)U.push(O%G),O=O/G|0}for(Y=0;$[Y]===0&&Y<$.length-1;++Y)Q+=W;for(Y=U.length-1;Y>=0;--Y)Q+=J[U[Y]]}if(X){var V=new RegExp(".{1,"+X+"}","g");Q=Q.match(V).join(`\r
3
+ `)}return Q};a9.decode=function($,J){if(typeof $!=="string")throw TypeError('"input" must be a string.');if(typeof J!=="string")throw TypeError('"alphabet" must be a string.');var X=CG[J];if(!X){X=CG[J]=[];for(var Q=0;Q<J.length;++Q)X[J.charCodeAt(Q)]=Q}$=$.replace(/\s/g,"");var Y=J.length,G=J.charAt(0),W=[0];for(var Q=0;Q<$.length;Q++){var U=X[$.charCodeAt(Q)];if(U===void 0)return;for(var M=0,O=U;M<W.length;++M)O+=W[M]*Y,W[M]=O&255,O>>=8;while(O>0)W.push(O&255),O>>=8}for(var V=0;$[V]===G&&V<$.length-1;++V)W.push(0);if(typeof Buffer<"u")return Buffer.from(W.reverse());return new Uint8Array(W.reverse())};function UM($,J){var X=0,Q=J.length,Y=J.charAt(0),G=[0];for(X=0;X<$.length();++X){for(var W=0,U=$.at(X);W<G.length;++W)U+=G[W]<<8,G[W]=U%Q,U=U/Q|0;while(U>0)G.push(U%Q),U=U/Q|0}var M="";for(X=0;$.at(X)===0&&X<$.length()-1;++X)M+=Y;for(X=G.length-1;X>=0;--X)M+=J[G[X]];return M}});var _$=q$((RF,kG)=>{var _G=F$(),xG=PG(),T=kG.exports=_G.util=_G.util||{};(function(){if(typeof process<"u"&&process.nextTick){if(T.nextTick=process.nextTick,typeof setImmediate==="function")T.setImmediate=setImmediate;else T.setImmediate=T.nextTick;return}if(typeof setImmediate==="function"){T.setImmediate=function(){return setImmediate.apply(void 0,arguments)},T.nextTick=function(U){return setImmediate(U)};return}if(T.setImmediate=function(U){setTimeout(U,0)},typeof window<"u"&&typeof window.postMessage==="function"){let U=function(M){if(M.source===window&&M.data===$){M.stopPropagation();var O=J.slice();J.length=0,O.forEach(function(V){V()})}};var W=U,$="forge.setImmediate",J=[];T.setImmediate=function(M){if(J.push(M),J.length===1)window.postMessage($,"*")},window.addEventListener("message",U,!0)}if(typeof MutationObserver<"u"){var X=Date.now(),Q=!0,Y=document.createElement("div"),J=[];new MutationObserver(function(){var M=J.slice();J.length=0,M.forEach(function(O){O()})}).observe(Y,{attributes:!0});var G=T.setImmediate;T.setImmediate=function(M){if(Date.now()-X>15)X=Date.now(),G(M);else if(J.push(M),J.length===1)Y.setAttribute("a",Q=!Q)}}T.nextTick=T.setImmediate})();T.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;T.globalScope=function(){if(T.isNodejs)return global;return typeof self>"u"?window:self}();T.isArray=Array.isArray||function($){return Object.prototype.toString.call($)==="[object Array]"};T.isArrayBuffer=function($){return typeof ArrayBuffer<"u"&&$ instanceof ArrayBuffer};T.isArrayBufferView=function($){return $&&T.isArrayBuffer($.buffer)&&$.byteLength!==void 0};function ZX($){if(!($===8||$===16||$===24||$===32))throw Error("Only 8, 16, 24, or 32 bits supported: "+$)}T.ByteBuffer=s9;function s9($){if(this.data="",this.read=0,typeof $==="string")this.data=$;else if(T.isArrayBuffer($)||T.isArrayBufferView($))if(typeof Buffer<"u"&&$ instanceof Buffer)this.data=$.toString("binary");else{var J=new Uint8Array($);try{this.data=String.fromCharCode.apply(null,J)}catch(Q){for(var X=0;X<J.length;++X)this.putByte(J[X])}}else if($ instanceof s9||typeof $==="object"&&typeof $.data==="string"&&typeof $.read==="number")this.data=$.data,this.read=$.read;this._constructedStringLength=0}T.ByteStringBuffer=s9;var MM=4096;T.ByteStringBuffer.prototype._optimizeConstructedString=function($){if(this._constructedStringLength+=$,this._constructedStringLength>MM)this.data.substr(0,1),this._constructedStringLength=0};T.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};T.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};T.ByteStringBuffer.prototype.putByte=function($){return this.putBytes(String.fromCharCode($))};T.ByteStringBuffer.prototype.fillWithByte=function($,J){$=String.fromCharCode($);var X=this.data;while(J>0){if(J&1)X+=$;if(J>>>=1,J>0)$+=$}return this.data=X,this._optimizeConstructedString(J),this};T.ByteStringBuffer.prototype.putBytes=function($){return this.data+=$,this._optimizeConstructedString($.length),this};T.ByteStringBuffer.prototype.putString=function($){return this.putBytes(T.encodeUtf8($))};T.ByteStringBuffer.prototype.putInt16=function($){return this.putBytes(String.fromCharCode($>>8&255)+String.fromCharCode($&255))};T.ByteStringBuffer.prototype.putInt24=function($){return this.putBytes(String.fromCharCode($>>16&255)+String.fromCharCode($>>8&255)+String.fromCharCode($&255))};T.ByteStringBuffer.prototype.putInt32=function($){return this.putBytes(String.fromCharCode($>>24&255)+String.fromCharCode($>>16&255)+String.fromCharCode($>>8&255)+String.fromCharCode($&255))};T.ByteStringBuffer.prototype.putInt16Le=function($){return this.putBytes(String.fromCharCode($&255)+String.fromCharCode($>>8&255))};T.ByteStringBuffer.prototype.putInt24Le=function($){return this.putBytes(String.fromCharCode($&255)+String.fromCharCode($>>8&255)+String.fromCharCode($>>16&255))};T.ByteStringBuffer.prototype.putInt32Le=function($){return this.putBytes(String.fromCharCode($&255)+String.fromCharCode($>>8&255)+String.fromCharCode($>>16&255)+String.fromCharCode($>>24&255))};T.ByteStringBuffer.prototype.putInt=function($,J){ZX(J);var X="";do J-=8,X+=String.fromCharCode($>>J&255);while(J>0);return this.putBytes(X)};T.ByteStringBuffer.prototype.putSignedInt=function($,J){if($<0)$+=2<<J-1;return this.putInt($,J)};T.ByteStringBuffer.prototype.putBuffer=function($){return this.putBytes($.getBytes())};T.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};T.ByteStringBuffer.prototype.getInt16=function(){var $=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,$};T.ByteStringBuffer.prototype.getInt24=function(){var $=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,$};T.ByteStringBuffer.prototype.getInt32=function(){var $=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,$};T.ByteStringBuffer.prototype.getInt16Le=function(){var $=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,$};T.ByteStringBuffer.prototype.getInt24Le=function(){var $=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,$};T.ByteStringBuffer.prototype.getInt32Le=function(){var $=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,$};T.ByteStringBuffer.prototype.getInt=function($){ZX($);var J=0;do J=(J<<8)+this.data.charCodeAt(this.read++),$-=8;while($>0);return J};T.ByteStringBuffer.prototype.getSignedInt=function($){var J=this.getInt($),X=2<<$-2;if(J>=X)J-=X<<1;return J};T.ByteStringBuffer.prototype.getBytes=function($){var J;if($)$=Math.min(this.length(),$),J=this.data.slice(this.read,this.read+$),this.read+=$;else if($===0)J="";else J=this.read===0?this.data:this.data.slice(this.read),this.clear();return J};T.ByteStringBuffer.prototype.bytes=function($){return typeof $>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+$)};T.ByteStringBuffer.prototype.at=function($){return this.data.charCodeAt(this.read+$)};T.ByteStringBuffer.prototype.setAt=function($,J){return this.data=this.data.substr(0,this.read+$)+String.fromCharCode(J)+this.data.substr(this.read+$+1),this};T.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};T.ByteStringBuffer.prototype.copy=function(){var $=T.createBuffer(this.data);return $.read=this.read,$};T.ByteStringBuffer.prototype.compact=function(){if(this.read>0)this.data=this.data.slice(this.read),this.read=0;return this};T.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};T.ByteStringBuffer.prototype.truncate=function($){var J=Math.max(0,this.length()-$);return this.data=this.data.substr(this.read,J),this.read=0,this};T.ByteStringBuffer.prototype.toHex=function(){var $="";for(var J=this.read;J<this.data.length;++J){var X=this.data.charCodeAt(J);if(X<16)$+="0";$+=X.toString(16)}return $};T.ByteStringBuffer.prototype.toString=function(){return T.decodeUtf8(this.bytes())};function OM($,J){J=J||{},this.read=J.readOffset||0,this.growSize=J.growSize||1024;var X=T.isArrayBuffer($),Q=T.isArrayBufferView($);if(X||Q){if(X)this.data=new DataView($);else this.data=new DataView($.buffer,$.byteOffset,$.byteLength);this.write="writeOffset"in J?J.writeOffset:this.data.byteLength;return}if(this.data=new DataView(new ArrayBuffer(0)),this.write=0,$!==null&&$!==void 0)this.putBytes($);if("writeOffset"in J)this.write=J.writeOffset}T.DataBuffer=OM;T.DataBuffer.prototype.length=function(){return this.write-this.read};T.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};T.DataBuffer.prototype.accommodate=function($,J){if(this.length()>=$)return this;J=Math.max(J||this.growSize,$);var X=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),Q=new Uint8Array(this.length()+J);return Q.set(X),this.data=new DataView(Q.buffer),this};T.DataBuffer.prototype.putByte=function($){return this.accommodate(1),this.data.setUint8(this.write++,$),this};T.DataBuffer.prototype.fillWithByte=function($,J){this.accommodate(J);for(var X=0;X<J;++X)this.data.setUint8($);return this};T.DataBuffer.prototype.putBytes=function($,J){if(T.isArrayBufferView($)){var X=new Uint8Array($.buffer,$.byteOffset,$.byteLength),Q=X.byteLength-X.byteOffset;this.accommodate(Q);var Y=new Uint8Array(this.data.buffer,this.write);return Y.set(X),this.write+=Q,this}if(T.isArrayBuffer($)){var X=new Uint8Array($);this.accommodate(X.byteLength);var Y=new Uint8Array(this.data.buffer);return Y.set(X,this.write),this.write+=X.byteLength,this}if($ instanceof T.DataBuffer||typeof $==="object"&&typeof $.read==="number"&&typeof $.write==="number"&&T.isArrayBufferView($.data)){var X=new Uint8Array($.data.byteLength,$.read,$.length());this.accommodate(X.byteLength);var Y=new Uint8Array($.data.byteLength,this.write);return Y.set(X),this.write+=X.byteLength,this}if($ instanceof T.ByteStringBuffer)$=$.data,J="binary";if(J=J||"binary",typeof $==="string"){var G;if(J==="hex")return this.accommodate(Math.ceil($.length/2)),G=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.hex.decode($,G,this.write),this;if(J==="base64")return this.accommodate(Math.ceil($.length/4)*3),G=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.base64.decode($,G,this.write),this;if(J==="utf8")$=T.encodeUtf8($),J="binary";if(J==="binary"||J==="raw")return this.accommodate($.length),G=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.raw.decode(G),this;if(J==="utf16")return this.accommodate($.length*2),G=new Uint16Array(this.data.buffer,this.write),this.write+=T.text.utf16.encode(G),this;throw Error("Invalid encoding: "+J)}throw Error("Invalid parameter: "+$)};T.DataBuffer.prototype.putBuffer=function($){return this.putBytes($),$.clear(),this};T.DataBuffer.prototype.putString=function($){return this.putBytes($,"utf16")};T.DataBuffer.prototype.putInt16=function($){return this.accommodate(2),this.data.setInt16(this.write,$),this.write+=2,this};T.DataBuffer.prototype.putInt24=function($){return this.accommodate(3),this.data.setInt16(this.write,$>>8&65535),this.data.setInt8(this.write,$>>16&255),this.write+=3,this};T.DataBuffer.prototype.putInt32=function($){return this.accommodate(4),this.data.setInt32(this.write,$),this.write+=4,this};T.DataBuffer.prototype.putInt16Le=function($){return this.accommodate(2),this.data.setInt16(this.write,$,!0),this.write+=2,this};T.DataBuffer.prototype.putInt24Le=function($){return this.accommodate(3),this.data.setInt8(this.write,$>>16&255),this.data.setInt16(this.write,$>>8&65535,!0),this.write+=3,this};T.DataBuffer.prototype.putInt32Le=function($){return this.accommodate(4),this.data.setInt32(this.write,$,!0),this.write+=4,this};T.DataBuffer.prototype.putInt=function($,J){ZX(J),this.accommodate(J/8);do J-=8,this.data.setInt8(this.write++,$>>J&255);while(J>0);return this};T.DataBuffer.prototype.putSignedInt=function($,J){if(ZX(J),this.accommodate(J/8),$<0)$+=2<<J-1;return this.putInt($,J)};T.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};T.DataBuffer.prototype.getInt16=function(){var $=this.data.getInt16(this.read);return this.read+=2,$};T.DataBuffer.prototype.getInt24=function(){var $=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,$};T.DataBuffer.prototype.getInt32=function(){var $=this.data.getInt32(this.read);return this.read+=4,$};T.DataBuffer.prototype.getInt16Le=function(){var $=this.data.getInt16(this.read,!0);return this.read+=2,$};T.DataBuffer.prototype.getInt24Le=function(){var $=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,$};T.DataBuffer.prototype.getInt32Le=function(){var $=this.data.getInt32(this.read,!0);return this.read+=4,$};T.DataBuffer.prototype.getInt=function($){ZX($);var J=0;do J=(J<<8)+this.data.getInt8(this.read++),$-=8;while($>0);return J};T.DataBuffer.prototype.getSignedInt=function($){var J=this.getInt($),X=2<<$-2;if(J>=X)J-=X<<1;return J};T.DataBuffer.prototype.getBytes=function($){var J;if($)$=Math.min(this.length(),$),J=this.data.slice(this.read,this.read+$),this.read+=$;else if($===0)J="";else J=this.read===0?this.data:this.data.slice(this.read),this.clear();return J};T.DataBuffer.prototype.bytes=function($){return typeof $>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+$)};T.DataBuffer.prototype.at=function($){return this.data.getUint8(this.read+$)};T.DataBuffer.prototype.setAt=function($,J){return this.data.setUint8($,J),this};T.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};T.DataBuffer.prototype.copy=function(){return new T.DataBuffer(this)};T.DataBuffer.prototype.compact=function(){if(this.read>0){var $=new Uint8Array(this.data.buffer,this.read),J=new Uint8Array($.byteLength);J.set($),this.data=new DataView(J),this.write-=this.read,this.read=0}return this};T.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};T.DataBuffer.prototype.truncate=function($){return this.write=Math.max(0,this.length()-$),this.read=Math.min(this.read,this.write),this};T.DataBuffer.prototype.toHex=function(){var $="";for(var J=this.read;J<this.data.byteLength;++J){var X=this.data.getUint8(J);if(X<16)$+="0";$+=X.toString(16)}return $};T.DataBuffer.prototype.toString=function($){var J=new Uint8Array(this.data,this.read,this.length());if($=$||"utf8",$==="binary"||$==="raw")return T.binary.raw.encode(J);if($==="hex")return T.binary.hex.encode(J);if($==="base64")return T.binary.base64.encode(J);if($==="utf8")return T.text.utf8.decode(J);if($==="utf16")return T.text.utf16.decode(J);throw Error("Invalid encoding: "+$)};T.createBuffer=function($,J){if(J=J||"raw",$!==void 0&&J==="utf8")$=T.encodeUtf8($);return new T.ByteBuffer($)};T.fillString=function($,J){var X="";while(J>0){if(J&1)X+=$;if(J>>>=1,J>0)$+=$}return X};T.xorBytes=function($,J,X){var Q="",Y="",G="",W=0,U=0;for(;X>0;--X,++W){if(Y=$.charCodeAt(W)^J.charCodeAt(W),U>=10)Q+=G,G="",U=0;G+=String.fromCharCode(Y),++U}return Q+=G,Q};T.hexToBytes=function($){var J="",X=0;if($.length&!0)X=1,J+=String.fromCharCode(parseInt($[0],16));for(;X<$.length;X+=2)J+=String.fromCharCode(parseInt($.substr(X,2),16));return J};T.bytesToHex=function($){return T.createBuffer($).toHex()};T.int32ToBytes=function($){return String.fromCharCode($>>24&255)+String.fromCharCode($>>16&255)+String.fromCharCode($>>8&255)+String.fromCharCode($&255)};var w0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",P0=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],vG="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";T.encode64=function($,J){var X="",Q="",Y,G,W,U=0;while(U<$.length){if(Y=$.charCodeAt(U++),G=$.charCodeAt(U++),W=$.charCodeAt(U++),X+=w0.charAt(Y>>2),X+=w0.charAt((Y&3)<<4|G>>4),isNaN(G))X+="==";else X+=w0.charAt((G&15)<<2|W>>6),X+=isNaN(W)?"=":w0.charAt(W&63);if(J&&X.length>J)Q+=X.substr(0,J)+`\r
4
+ `,X=X.substr(J)}return Q+=X,Q};T.decode64=function($){$=$.replace(/[^A-Za-z0-9\+\/\=]/g,"");var J="",X,Q,Y,G,W=0;while(W<$.length)if(X=P0[$.charCodeAt(W++)-43],Q=P0[$.charCodeAt(W++)-43],Y=P0[$.charCodeAt(W++)-43],G=P0[$.charCodeAt(W++)-43],J+=String.fromCharCode(X<<2|Q>>4),Y!==64){if(J+=String.fromCharCode((Q&15)<<4|Y>>2),G!==64)J+=String.fromCharCode((Y&3)<<6|G)}return J};T.encodeUtf8=function($){return unescape(encodeURIComponent($))};T.decodeUtf8=function($){return decodeURIComponent(escape($))};T.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:xG.encode,decode:xG.decode}};T.binary.raw.encode=function($){return String.fromCharCode.apply(null,$)};T.binary.raw.decode=function($,J,X){var Q=J;if(!Q)Q=new Uint8Array($.length);X=X||0;var Y=X;for(var G=0;G<$.length;++G)Q[Y++]=$.charCodeAt(G);return J?Y-X:Q};T.binary.hex.encode=T.bytesToHex;T.binary.hex.decode=function($,J,X){var Q=J;if(!Q)Q=new Uint8Array(Math.ceil($.length/2));X=X||0;var Y=0,G=X;if($.length&1)Y=1,Q[G++]=parseInt($[0],16);for(;Y<$.length;Y+=2)Q[G++]=parseInt($.substr(Y,2),16);return J?G-X:Q};T.binary.base64.encode=function($,J){var X="",Q="",Y,G,W,U=0;while(U<$.byteLength){if(Y=$[U++],G=$[U++],W=$[U++],X+=w0.charAt(Y>>2),X+=w0.charAt((Y&3)<<4|G>>4),isNaN(G))X+="==";else X+=w0.charAt((G&15)<<2|W>>6),X+=isNaN(W)?"=":w0.charAt(W&63);if(J&&X.length>J)Q+=X.substr(0,J)+`\r
5
+ `,X=X.substr(J)}return Q+=X,Q};T.binary.base64.decode=function($,J,X){var Q=J;if(!Q)Q=new Uint8Array(Math.ceil($.length/4)*3);$=$.replace(/[^A-Za-z0-9\+\/\=]/g,""),X=X||0;var Y,G,W,U,M=0,O=X;while(M<$.length)if(Y=P0[$.charCodeAt(M++)-43],G=P0[$.charCodeAt(M++)-43],W=P0[$.charCodeAt(M++)-43],U=P0[$.charCodeAt(M++)-43],Q[O++]=Y<<2|G>>4,W!==64){if(Q[O++]=(G&15)<<4|W>>2,U!==64)Q[O++]=(W&3)<<6|U}return J?O-X:Q.subarray(0,O)};T.binary.base58.encode=function($,J){return T.binary.baseN.encode($,vG,J)};T.binary.base58.decode=function($,J){return T.binary.baseN.decode($,vG,J)};T.text={utf8:{},utf16:{}};T.text.utf8.encode=function($,J,X){$=T.encodeUtf8($);var Q=J;if(!Q)Q=new Uint8Array($.length);X=X||0;var Y=X;for(var G=0;G<$.length;++G)Q[Y++]=$.charCodeAt(G);return J?Y-X:Q};T.text.utf8.decode=function($){return T.decodeUtf8(String.fromCharCode.apply(null,$))};T.text.utf16.encode=function($,J,X){var Q=J;if(!Q)Q=new Uint8Array($.length*2);var Y=new Uint16Array(Q.buffer);X=X||0;var G=X,W=X;for(var U=0;U<$.length;++U)Y[W++]=$.charCodeAt(U),G+=2;return J?G-X:Q};T.text.utf16.decode=function($){return String.fromCharCode.apply(null,new Uint16Array($.buffer))};T.deflate=function($,J,X){if(J=T.decode64($.deflate(T.encode64(J)).rval),X){var Q=2,Y=J.charCodeAt(1);if(Y&32)Q=6;J=J.substring(Q,J.length-4)}return J};T.inflate=function($,J,X){var Q=$.inflate(T.encode64(J)).rval;return Q===null?null:T.decode64(Q)};var r9=function($,J,X){if(!$)throw Error("WebStorage not available.");var Q;if(X===null)Q=$.removeItem(J);else X=T.encode64(JSON.stringify(X)),Q=$.setItem(J,X);if(typeof Q<"u"&&Q.rval!==!0){var Y=Error(Q.error.message);throw Y.id=Q.error.id,Y.name=Q.error.name,Y}},t9=function($,J){if(!$)throw Error("WebStorage not available.");var X=$.getItem(J);if($.init)if(X.rval===null){if(X.error){var Q=Error(X.error.message);throw Q.id=X.error.id,Q.name=X.error.name,Q}X=null}else X=X.rval;if(X!==null)X=JSON.parse(T.decode64(X));return X},VM=function($,J,X,Q){var Y=t9($,J);if(Y===null)Y={};Y[X]=Q,r9($,J,Y)},qM=function($,J,X){var Q=t9($,J);if(Q!==null)Q=X in Q?Q[X]:null;return Q},HM=function($,J,X){var Q=t9($,J);if(Q!==null&&X in Q){delete Q[X];var Y=!0;for(var G in Q){Y=!1;break}if(Y)Q=null;r9($,J,Q)}},KM=function($,J){r9($,J,null)},DY=function($,J,X){var Q=null;if(typeof X>"u")X=["web","flash"];var Y,G=!1,W=null;for(var U in X){Y=X[U];try{if(Y==="flash"||Y==="both"){if(J[0]===null)throw Error("Flash local storage not available.");Q=$.apply(this,J),G=Y==="flash"}if(Y==="web"||Y==="both")J[0]=localStorage,Q=$.apply(this,J),G=!0}catch(M){W=M}if(G)break}if(!G)throw W;return Q};T.setItem=function($,J,X,Q,Y){DY(VM,arguments,Y)};T.getItem=function($,J,X,Q){return DY(qM,arguments,Q)};T.removeItem=function($,J,X,Q){DY(HM,arguments,Q)};T.clearItems=function($,J,X){DY(KM,arguments,X)};T.isEmpty=function($){for(var J in $)if($.hasOwnProperty(J))return!1;return!0};T.format=function($){var J=/%./g,X,Q,Y=0,G=[],W=0;while(X=J.exec($)){if(Q=$.substring(W,J.lastIndex-2),Q.length>0)G.push(Q);W=J.lastIndex;var U=X[0][1];switch(U){case"s":case"o":if(Y<arguments.length)G.push(arguments[Y+++1]);else G.push("<?>");break;case"%":G.push("%");break;default:G.push("<%"+U+"?>")}}return G.push($.substring(W)),G.join("")};T.formatNumber=function($,J,X,Q){var Y=$,G=isNaN(J=Math.abs(J))?2:J,W=X===void 0?",":X,U=Q===void 0?".":Q,M=Y<0?"-":"",O=parseInt(Y=Math.abs(+Y||0).toFixed(G),10)+"",V=O.length>3?O.length%3:0;return M+(V?O.substr(0,V)+U:"")+O.substr(V).replace(/(\d{3})(?=\d)/g,"$1"+U)+(G?W+Math.abs(Y-O).toFixed(G).slice(2):"")};T.formatSize=function($){if($>=1073741824)$=T.formatNumber($/1073741824,2,".","")+" GiB";else if($>=1048576)$=T.formatNumber($/1048576,2,".","")+" MiB";else if($>=1024)$=T.formatNumber($/1024,0)+" KiB";else $=T.formatNumber($,0)+" bytes";return $};T.bytesFromIP=function($){if($.indexOf(".")!==-1)return T.bytesFromIPv4($);if($.indexOf(":")!==-1)return T.bytesFromIPv6($);return null};T.bytesFromIPv4=function($){if($=$.split("."),$.length!==4)return null;var J=T.createBuffer();for(var X=0;X<$.length;++X){var Q=parseInt($[X],10);if(isNaN(Q))return null;J.putByte(Q)}return J.getBytes()};T.bytesFromIPv6=function($){var J=0;$=$.split(":").filter(function(W){if(W.length===0)++J;return!0});var X=(8-$.length+J)*2,Q=T.createBuffer();for(var Y=0;Y<8;++Y){if(!$[Y]||$[Y].length===0){Q.fillWithByte(0,X),X=0;continue}var G=T.hexToBytes($[Y]);if(G.length<2)Q.putByte(0);Q.putBytes(G)}return Q.getBytes()};T.bytesToIP=function($){if($.length===4)return T.bytesToIPv4($);if($.length===16)return T.bytesToIPv6($);return null};T.bytesToIPv4=function($){if($.length!==4)return null;var J=[];for(var X=0;X<$.length;++X)J.push($.charCodeAt(X));return J.join(".")};T.bytesToIPv6=function($){if($.length!==16)return null;var J=[],X=[],Q=0;for(var Y=0;Y<$.length;Y+=2){var G=T.bytesToHex($[Y]+$[Y+1]);while(G[0]==="0"&&G!=="0")G=G.substr(1);if(G==="0"){var W=X[X.length-1],U=J.length;if(!W||U!==W.end+1)X.push({start:U,end:U});else if(W.end=U,W.end-W.start>X[Q].end-X[Q].start)Q=X.length-1}J.push(G)}if(X.length>0){var M=X[Q];if(M.end-M.start>0){if(J.splice(M.start,M.end-M.start+1,""),M.start===0)J.unshift("");if(M.end===7)J.push("")}}return J.join(":")};T.estimateCores=function($,J){if(typeof $==="function")J=$,$={};if($=$||{},"cores"in T&&!$.update)return J(null,T.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return T.cores=navigator.hardwareConcurrency,J(null,T.cores);if(typeof Worker>"u")return T.cores=1,J(null,T.cores);if(typeof Blob>"u")return T.cores=2,J(null,T.cores);var X=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(W){var U=Date.now(),M=U+4;while(Date.now()<M);self.postMessage({st:U,et:M})})}.toString(),")()"],{type:"application/javascript"}));Q([],5,16);function Q(W,U,M){if(U===0){var O=Math.floor(W.reduce(function(V,q){return V+q},0)/W.length);return T.cores=Math.max(1,O),URL.revokeObjectURL(X),J(null,T.cores)}Y(M,function(V,q){W.push(G(M,q)),Q(W,U-1,M)})}function Y(W,U){var M=[],O=[];for(var V=0;V<W;++V){var q=new Worker(X);q.addEventListener("message",function(H){if(O.push(H.data),O.length===W){for(var N=0;N<W;++N)M[N].terminate();U(null,O)}}),M.push(q)}for(var V=0;V<W;++V)M[V].postMessage(V)}function G(W,U){var M=[];for(var O=0;O<W;++O){var V=U[O],q=M[O]=[];for(var H=0;H<W;++H){if(O===H)continue;var N=U[H];if(V.st>N.st&&V.st<N.et||N.st>V.st&&N.st<V.et)q.push(H)}}return M.reduce(function(K,L){return Math.max(K,L.length)},0)}}});var ZY=q$((DF,fG)=>{var MJ=F$();_$();fG.exports=MJ.cipher=MJ.cipher||{};MJ.cipher.algorithms=MJ.cipher.algorithms||{};MJ.cipher.createCipher=function($,J){var X=$;if(typeof X==="string"){if(X=MJ.cipher.getAlgorithm(X),X)X=X()}if(!X)throw Error("Unsupported algorithm: "+$);return new MJ.cipher.BlockCipher({algorithm:X,key:J,decrypt:!1})};MJ.cipher.createDecipher=function($,J){var X=$;if(typeof X==="string"){if(X=MJ.cipher.getAlgorithm(X),X)X=X()}if(!X)throw Error("Unsupported algorithm: "+$);return new MJ.cipher.BlockCipher({algorithm:X,key:J,decrypt:!0})};MJ.cipher.registerAlgorithm=function($,J){$=$.toUpperCase(),MJ.cipher.algorithms[$]=J};MJ.cipher.getAlgorithm=function($){if($=$.toUpperCase(),$ in MJ.cipher.algorithms)return MJ.cipher.algorithms[$];return null};var e9=MJ.cipher.BlockCipher=function($){this.algorithm=$.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=$.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=$.decrypt,this.algorithm.initialize($)};e9.prototype.start=function($){$=$||{};var J={};for(var X in $)J[X]=$[X];J.decrypt=this._decrypt,this._finish=!1,this._input=MJ.util.createBuffer(),this.output=$.output||MJ.util.createBuffer(),this.mode.start(J)};e9.prototype.update=function($){if($)this._input.putBuffer($);while(!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish);this._input.compact()};e9.prototype.finish=function($){if($&&(this.mode.name==="ECB"||this.mode.name==="CBC"))this.mode.pad=function(X){return $(this.blockSize,X,!1)},this.mode.unpad=function(X){return $(this.blockSize,X,!0)};var J={};if(J.decrypt=this._decrypt,J.overflow=this._input.length()%this.blockSize,!this._decrypt&&this.mode.pad){if(!this.mode.pad(this._input,J))return!1}if(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad){if(!this.mode.unpad(this.output,J))return!1}if(this.mode.afterFinish){if(!this.mode.afterFinish(this.output,J))return!1}return!0}});var J8=q$((ZF,yG)=>{var OJ=F$();_$();OJ.cipher=OJ.cipher||{};var R$=yG.exports=OJ.cipher.modes=OJ.cipher.modes||{};R$.ecb=function($){$=$||{},this.name="ECB",this.cipher=$.cipher,this.blockSize=$.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints)};R$.ecb.prototype.start=function($){};R$.ecb.prototype.encrypt=function($,J,X){if($.length()<this.blockSize&&!(X&&$.length()>0))return!0;for(var Q=0;Q<this._ints;++Q)this._inBlock[Q]=$.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var Q=0;Q<this._ints;++Q)J.putInt32(this._outBlock[Q])};R$.ecb.prototype.decrypt=function($,J,X){if($.length()<this.blockSize&&!(X&&$.length()>0))return!0;for(var Q=0;Q<this._ints;++Q)this._inBlock[Q]=$.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var Q=0;Q<this._ints;++Q)J.putInt32(this._outBlock[Q])};R$.ecb.prototype.pad=function($,J){var X=$.length()===this.blockSize?this.blockSize:this.blockSize-$.length();return $.fillWithByte(X,X),!0};R$.ecb.prototype.unpad=function($,J){if(J.overflow>0)return!1;var X=$.length(),Q=$.at(X-1);if(Q>this.blockSize<<2)return!1;return $.truncate(Q),!0};R$.cbc=function($){$=$||{},this.name="CBC",this.cipher=$.cipher,this.blockSize=$.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints)};R$.cbc.prototype.start=function($){if($.iv===null){if(!this._prev)throw Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if(!("iv"in $))throw Error("Invalid IV parameter.");else this._iv=BY($.iv,this.blockSize),this._prev=this._iv.slice(0)};R$.cbc.prototype.encrypt=function($,J,X){if($.length()<this.blockSize&&!(X&&$.length()>0))return!0;for(var Q=0;Q<this._ints;++Q)this._inBlock[Q]=this._prev[Q]^$.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var Q=0;Q<this._ints;++Q)J.putInt32(this._outBlock[Q]);this._prev=this._outBlock};R$.cbc.prototype.decrypt=function($,J,X){if($.length()<this.blockSize&&!(X&&$.length()>0))return!0;for(var Q=0;Q<this._ints;++Q)this._inBlock[Q]=$.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var Q=0;Q<this._ints;++Q)J.putInt32(this._prev[Q]^this._outBlock[Q]);this._prev=this._inBlock.slice(0)};R$.cbc.prototype.pad=function($,J){var X=$.length()===this.blockSize?this.blockSize:this.blockSize-$.length();return $.fillWithByte(X,X),!0};R$.cbc.prototype.unpad=function($,J){if(J.overflow>0)return!1;var X=$.length(),Q=$.at(X-1);if(Q>this.blockSize<<2)return!1;return $.truncate(Q),!0};R$.cfb=function($){$=$||{},this.name="CFB",this.cipher=$.cipher,this.blockSize=$.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialBlock=Array(this._ints),this._partialOutput=OJ.util.createBuffer(),this._partialBytes=0};R$.cfb.prototype.start=function($){if(!("iv"in $))throw Error("Invalid IV parameter.");this._iv=BY($.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};R$.cfb.prototype.encrypt=function($,J,X){var Q=$.length();if(Q===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&Q>=this.blockSize){for(var Y=0;Y<this._ints;++Y)this._inBlock[Y]=$.getInt32()^this._outBlock[Y],J.putInt32(this._inBlock[Y]);return}var G=(this.blockSize-Q)%this.blockSize;if(G>0)G=this.blockSize-G;this._partialOutput.clear();for(var Y=0;Y<this._ints;++Y)this._partialBlock[Y]=$.getInt32()^this._outBlock[Y],this._partialOutput.putInt32(this._partialBlock[Y]);if(G>0)$.read-=this.blockSize;else for(var Y=0;Y<this._ints;++Y)this._inBlock[Y]=this._partialBlock[Y];if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(G>0&&!X)return J.putBytes(this._partialOutput.getBytes(G-this._partialBytes)),this._partialBytes=G,!0;J.putBytes(this._partialOutput.getBytes(Q-this._partialBytes)),this._partialBytes=0};R$.cfb.prototype.decrypt=function($,J,X){var Q=$.length();if(Q===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&Q>=this.blockSize){for(var Y=0;Y<this._ints;++Y)this._inBlock[Y]=$.getInt32(),J.putInt32(this._inBlock[Y]^this._outBlock[Y]);return}var G=(this.blockSize-Q)%this.blockSize;if(G>0)G=this.blockSize-G;this._partialOutput.clear();for(var Y=0;Y<this._ints;++Y)this._partialBlock[Y]=$.getInt32(),this._partialOutput.putInt32(this._partialBlock[Y]^this._outBlock[Y]);if(G>0)$.read-=this.blockSize;else for(var Y=0;Y<this._ints;++Y)this._inBlock[Y]=this._partialBlock[Y];if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(G>0&&!X)return J.putBytes(this._partialOutput.getBytes(G-this._partialBytes)),this._partialBytes=G,!0;J.putBytes(this._partialOutput.getBytes(Q-this._partialBytes)),this._partialBytes=0};R$.ofb=function($){$=$||{},this.name="OFB",this.cipher=$.cipher,this.blockSize=$.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=OJ.util.createBuffer(),this._partialBytes=0};R$.ofb.prototype.start=function($){if(!("iv"in $))throw Error("Invalid IV parameter.");this._iv=BY($.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};R$.ofb.prototype.encrypt=function($,J,X){var Q=$.length();if($.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&Q>=this.blockSize){for(var Y=0;Y<this._ints;++Y)J.putInt32($.getInt32()^this._outBlock[Y]),this._inBlock[Y]=this._outBlock[Y];return}var G=(this.blockSize-Q)%this.blockSize;if(G>0)G=this.blockSize-G;this._partialOutput.clear();for(var Y=0;Y<this._ints;++Y)this._partialOutput.putInt32($.getInt32()^this._outBlock[Y]);if(G>0)$.read-=this.blockSize;else for(var Y=0;Y<this._ints;++Y)this._inBlock[Y]=this._outBlock[Y];if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(G>0&&!X)return J.putBytes(this._partialOutput.getBytes(G-this._partialBytes)),this._partialBytes=G,!0;J.putBytes(this._partialOutput.getBytes(Q-this._partialBytes)),this._partialBytes=0};R$.ofb.prototype.decrypt=R$.ofb.prototype.encrypt;R$.ctr=function($){$=$||{},this.name="CTR",this.cipher=$.cipher,this.blockSize=$.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=OJ.util.createBuffer(),this._partialBytes=0};R$.ctr.prototype.start=function($){if(!("iv"in $))throw Error("Invalid IV parameter.");this._iv=BY($.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};R$.ctr.prototype.encrypt=function($,J,X){var Q=$.length();if(Q===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&Q>=this.blockSize)for(var Y=0;Y<this._ints;++Y)J.putInt32($.getInt32()^this._outBlock[Y]);else{var G=(this.blockSize-Q)%this.blockSize;if(G>0)G=this.blockSize-G;this._partialOutput.clear();for(var Y=0;Y<this._ints;++Y)this._partialOutput.putInt32($.getInt32()^this._outBlock[Y]);if(G>0)$.read-=this.blockSize;if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(G>0&&!X)return J.putBytes(this._partialOutput.getBytes(G-this._partialBytes)),this._partialBytes=G,!0;J.putBytes(this._partialOutput.getBytes(Q-this._partialBytes)),this._partialBytes=0}jY(this._inBlock)};R$.ctr.prototype.decrypt=R$.ctr.prototype.encrypt;R$.gcm=function($){$=$||{},this.name="GCM",this.cipher=$.cipher,this.blockSize=$.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints),this._partialOutput=OJ.util.createBuffer(),this._partialBytes=0,this._R=3774873600};R$.gcm.prototype.start=function($){if(!("iv"in $))throw Error("Invalid IV parameter.");var J=OJ.util.createBuffer($.iv);this._cipherLength=0;var X;if("additionalData"in $)X=OJ.util.createBuffer($.additionalData);else X=OJ.util.createBuffer();if("tagLength"in $)this._tagLength=$.tagLength;else this._tagLength=128;if(this._tag=null,$.decrypt){if(this._tag=OJ.util.createBuffer($.tag).getBytes(),this._tag.length!==this._tagLength/8)throw Error("Authentication tag does not match tag length.")}this._hashBlock=Array(this._ints),this.tag=null,this._hashSubkey=Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var Q=J.length();if(Q===12)this._j0=[J.getInt32(),J.getInt32(),J.getInt32(),1];else{this._j0=[0,0,0,0];while(J.length()>0)this._j0=this.ghash(this._hashSubkey,this._j0,[J.getInt32(),J.getInt32(),J.getInt32(),J.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat($8(Q*8)))}this._inBlock=this._j0.slice(0),jY(this._inBlock),this._partialBytes=0,X=OJ.util.createBuffer(X),this._aDataLength=$8(X.length()*8);var Y=X.length()%this.blockSize;if(Y)X.fillWithByte(0,this.blockSize-Y);this._s=[0,0,0,0];while(X.length()>0)this._s=this.ghash(this._hashSubkey,this._s,[X.getInt32(),X.getInt32(),X.getInt32(),X.getInt32()])};R$.gcm.prototype.encrypt=function($,J,X){var Q=$.length();if(Q===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&Q>=this.blockSize){for(var Y=0;Y<this._ints;++Y)J.putInt32(this._outBlock[Y]^=$.getInt32());this._cipherLength+=this.blockSize}else{var G=(this.blockSize-Q)%this.blockSize;if(G>0)G=this.blockSize-G;this._partialOutput.clear();for(var Y=0;Y<this._ints;++Y)this._partialOutput.putInt32($.getInt32()^this._outBlock[Y]);if(G<=0||X){if(X){var W=Q%this.blockSize;this._cipherLength+=W,this._partialOutput.truncate(this.blockSize-W)}else this._cipherLength+=this.blockSize;for(var Y=0;Y<this._ints;++Y)this._outBlock[Y]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(G>0&&!X)return $.read-=this.blockSize,J.putBytes(this._partialOutput.getBytes(G-this._partialBytes)),this._partialBytes=G,!0;J.putBytes(this._partialOutput.getBytes(Q-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),jY(this._inBlock)};R$.gcm.prototype.decrypt=function($,J,X){var Q=$.length();if(Q<this.blockSize&&!(X&&Q>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),jY(this._inBlock),this._hashBlock[0]=$.getInt32(),this._hashBlock[1]=$.getInt32(),this._hashBlock[2]=$.getInt32(),this._hashBlock[3]=$.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var Y=0;Y<this._ints;++Y)J.putInt32(this._outBlock[Y]^this._hashBlock[Y]);if(Q<this.blockSize)this._cipherLength+=Q%this.blockSize;else this._cipherLength+=this.blockSize};R$.gcm.prototype.afterFinish=function($,J){var X=!0;if(J.decrypt&&J.overflow)$.truncate(this.blockSize-J.overflow);this.tag=OJ.util.createBuffer();var Q=this._aDataLength.concat($8(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,Q);var Y=[];this.cipher.encrypt(this._j0,Y);for(var G=0;G<this._ints;++G)this.tag.putInt32(this._s[G]^Y[G]);if(this.tag.truncate(this.tag.length()%(this._tagLength/8)),J.decrypt&&this.tag.bytes()!==this._tag)X=!1;return X};R$.gcm.prototype.multiply=function($,J){var X=[0,0,0,0],Q=J.slice(0);for(var Y=0;Y<128;++Y){var G=$[Y/32|0]&1<<31-Y%32;if(G)X[0]^=Q[0],X[1]^=Q[1],X[2]^=Q[2],X[3]^=Q[3];this.pow(Q,Q)}return X};R$.gcm.prototype.pow=function($,J){var X=$[3]&1;for(var Q=3;Q>0;--Q)J[Q]=$[Q]>>>1|($[Q-1]&1)<<31;if(J[0]=$[0]>>>1,X)J[0]^=this._R};R$.gcm.prototype.tableMultiply=function($){var J=[0,0,0,0];for(var X=0;X<32;++X){var Q=X/8|0,Y=$[Q]>>>(7-X%8)*4&15,G=this._m[X][Y];J[0]^=G[0],J[1]^=G[1],J[2]^=G[2],J[3]^=G[3]}return J};R$.gcm.prototype.ghash=function($,J,X){return J[0]^=X[0],J[1]^=X[1],J[2]^=X[2],J[3]^=X[3],this.tableMultiply(J)};R$.gcm.prototype.generateHashTable=function($,J){var X=8/J,Q=4*X,Y=16*X,G=Array(Y);for(var W=0;W<Y;++W){var U=[0,0,0,0],M=W/Q|0,O=(Q-1-W%Q)*J;U[M]=1<<J-1<<O,G[W]=this.generateSubHashTable(this.multiply(U,$),J)}return G};R$.gcm.prototype.generateSubHashTable=function($,J){var X=1<<J,Q=X>>>1,Y=Array(X);Y[Q]=$.slice(0);var G=Q>>>1;while(G>0)this.pow(Y[2*G],Y[G]=[]),G>>=1;G=2;while(G<Q){for(var W=1;W<G;++W){var U=Y[G],M=Y[W];Y[G+W]=[U[0]^M[0],U[1]^M[1],U[2]^M[2],U[3]^M[3]]}G*=2}Y[0]=[0,0,0,0];for(G=Q+1;G<X;++G){var O=Y[G^Q];Y[G]=[$[0]^O[0],$[1]^O[1],$[2]^O[2],$[3]^O[3]]}return Y};function BY($,J){if(typeof $==="string")$=OJ.util.createBuffer($);if(OJ.util.isArray($)&&$.length>4){var X=$;$=OJ.util.createBuffer();for(var Q=0;Q<X.length;++Q)$.putByte(X[Q])}if($.length()<J)throw Error("Invalid IV length; got "+$.length()+" bytes and expected "+J+" bytes.");if(!OJ.util.isArray($)){var Y=[],G=J/4;for(var Q=0;Q<G;++Q)Y.push($.getInt32());$=Y}return $}function jY($){$[$.length-1]=$[$.length-1]+1&4294967295}function $8($){return[$/4294967296|0,$&4294967295]}});var _0=q$((BF,gG)=>{var m$=F$();ZY();J8();_$();gG.exports=m$.aes=m$.aes||{};m$.aes.startEncrypting=function($,J,X,Q){var Y=TY({key:$,output:X,decrypt:!1,mode:Q});return Y.start(J),Y};m$.aes.createEncryptionCipher=function($,J){return TY({key:$,output:null,decrypt:!1,mode:J})};m$.aes.startDecrypting=function($,J,X,Q){var Y=TY({key:$,output:X,decrypt:!0,mode:Q});return Y.start(J),Y};m$.aes.createDecryptionCipher=function($,J){return TY({key:$,output:null,decrypt:!0,mode:J})};m$.aes.Algorithm=function($,J){if(!Y8)hG();var X=this;X.name=$,X.mode=new J({blockSize:16,cipher:{encrypt:function(Q,Y){return X8(X._w,Q,Y,!1)},decrypt:function(Q,Y){return X8(X._w,Q,Y,!0)}}}),X._init=!1};m$.aes.Algorithm.prototype.initialize=function($){if(this._init)return;var J=$.key,X;if(typeof J==="string"&&(J.length===16||J.length===24||J.length===32))J=m$.util.createBuffer(J);else if(m$.util.isArray(J)&&(J.length===16||J.length===24||J.length===32)){X=J,J=m$.util.createBuffer();for(var Q=0;Q<X.length;++Q)J.putByte(X[Q])}if(!m$.util.isArray(J)){X=J,J=[];var Y=X.length();if(Y===16||Y===24||Y===32){Y=Y>>>2;for(var Q=0;Q<Y;++Q)J.push(X.getInt32())}}if(!m$.util.isArray(J)||!(J.length===4||J.length===6||J.length===8))throw Error("Invalid key parameter.");var G=this.mode.name,W=["CFB","OFB","CTR","GCM"].indexOf(G)!==-1;this._w=uG(J,$.decrypt&&!W),this._init=!0};m$.aes._expandKey=function($,J){if(!Y8)hG();return uG($,J)};m$.aes._updateBlock=X8;SQ("AES-ECB",m$.cipher.modes.ecb);SQ("AES-CBC",m$.cipher.modes.cbc);SQ("AES-CFB",m$.cipher.modes.cfb);SQ("AES-OFB",m$.cipher.modes.ofb);SQ("AES-CTR",m$.cipher.modes.ctr);SQ("AES-GCM",m$.cipher.modes.gcm);function SQ($,J){var X=function(){return new m$.aes.Algorithm($,J)};m$.cipher.registerAlgorithm($,X)}var Y8=!1,TQ=4,LJ,Q8,bG,XQ,mJ;function hG(){Y8=!0,bG=[0,1,2,4,8,16,32,64,128,27,54];var $=Array(256);for(var J=0;J<128;++J)$[J]=J<<1,$[J+128]=J+128<<1^283;LJ=Array(256),Q8=Array(256),XQ=[,,,,],mJ=[,,,,];for(var J=0;J<4;++J)XQ[J]=Array(256),mJ[J]=Array(256);var X=0,Q=0,Y,G,W,U,M,O,V;for(var J=0;J<256;++J){U=Q^Q<<1^Q<<2^Q<<3^Q<<4,U=U>>8^U&255^99,LJ[X]=U,Q8[U]=X,M=$[U],Y=$[X],G=$[Y],W=$[G],O=M<<24^U<<16^U<<8^(U^M),V=(Y^G^W)<<24^(X^W)<<16^(X^G^W)<<8^(X^Y^W);for(var q=0;q<4;++q)XQ[q][X]=O,mJ[q][U]=V,O=O<<24|O>>>8,V=V<<24|V>>>8;if(X===0)X=Q=1;else X=Y^$[$[$[Y^W]]],Q^=$[$[Q]]}}function uG($,J){var X=$.slice(0),Q,Y=1,G=X.length,W=G+6+1,U=TQ*W;for(var M=G;M<U;++M){if(Q=X[M-1],M%G===0)Q=LJ[Q>>>16&255]<<24^LJ[Q>>>8&255]<<16^LJ[Q&255]<<8^LJ[Q>>>24]^bG[Y]<<24,Y++;else if(G>6&&M%G===4)Q=LJ[Q>>>24]<<24^LJ[Q>>>16&255]<<16^LJ[Q>>>8&255]<<8^LJ[Q&255];X[M]=X[M-G]^Q}if(J){var O,V=mJ[0],q=mJ[1],H=mJ[2],N=mJ[3],K=X.slice(0);U=X.length;for(var M=0,L=U-TQ;M<U;M+=TQ,L-=TQ)if(M===0||M===U-TQ)K[M]=X[L],K[M+1]=X[L+3],K[M+2]=X[L+2],K[M+3]=X[L+1];else for(var A=0;A<TQ;++A)O=X[L+A],K[M+(3&-A)]=V[LJ[O>>>24]]^q[LJ[O>>>16&255]]^H[LJ[O>>>8&255]]^N[LJ[O&255]];X=K}return X}function X8($,J,X,Q){var Y=$.length/4-1,G,W,U,M,O;if(Q)G=mJ[0],W=mJ[1],U=mJ[2],M=mJ[3],O=Q8;else G=XQ[0],W=XQ[1],U=XQ[2],M=XQ[3],O=LJ;var V,q,H,N,K,L,A;V=J[0]^$[0],q=J[Q?3:1]^$[1],H=J[2]^$[2],N=J[Q?1:3]^$[3];var D=3;for(var S=1;S<Y;++S)K=G[V>>>24]^W[q>>>16&255]^U[H>>>8&255]^M[N&255]^$[++D],L=G[q>>>24]^W[H>>>16&255]^U[N>>>8&255]^M[V&255]^$[++D],A=G[H>>>24]^W[N>>>16&255]^U[V>>>8&255]^M[q&255]^$[++D],N=G[N>>>24]^W[V>>>16&255]^U[q>>>8&255]^M[H&255]^$[++D],V=K,q=L,H=A;X[0]=O[V>>>24]<<24^O[q>>>16&255]<<16^O[H>>>8&255]<<8^O[N&255]^$[++D],X[Q?3:1]=O[q>>>24]<<24^O[H>>>16&255]<<16^O[N>>>8&255]<<8^O[V&255]^$[++D],X[2]=O[H>>>24]<<24^O[N>>>16&255]<<16^O[V>>>8&255]<<8^O[q&255]^$[++D],X[Q?1:3]=O[N>>>24]<<24^O[V>>>16&255]<<16^O[q>>>8&255]<<8^O[H&255]^$[++D]}function TY($){$=$||{};var J=($.mode||"CBC").toUpperCase(),X="AES-"+J,Q;if($.decrypt)Q=m$.cipher.createDecipher(X,$.key);else Q=m$.cipher.createCipher(X,$.key);var Y=Q.start;return Q.start=function(G,W){var U=null;if(W instanceof m$.util.ByteBuffer)U=W,W={};W=W||{},W.output=U,W.iv=G,Y.call(Q,W)},Q}});var x0=q$((jF,mG)=>{var BX=F$();BX.pki=BX.pki||{};var G8=mG.exports=BX.pki.oids=BX.oids=BX.oids||{};function b($,J){G8[$]=J,G8[J]=$}function k$($,J){G8[$]=J}b("1.2.840.113549.1.1.1","rsaEncryption");b("1.2.840.113549.1.1.4","md5WithRSAEncryption");b("1.2.840.113549.1.1.5","sha1WithRSAEncryption");b("1.2.840.113549.1.1.7","RSAES-OAEP");b("1.2.840.113549.1.1.8","mgf1");b("1.2.840.113549.1.1.9","pSpecified");b("1.2.840.113549.1.1.10","RSASSA-PSS");b("1.2.840.113549.1.1.11","sha256WithRSAEncryption");b("1.2.840.113549.1.1.12","sha384WithRSAEncryption");b("1.2.840.113549.1.1.13","sha512WithRSAEncryption");b("1.3.101.112","EdDSA25519");b("1.2.840.10040.4.3","dsa-with-sha1");b("1.3.14.3.2.7","desCBC");b("1.3.14.3.2.26","sha1");b("1.3.14.3.2.29","sha1WithRSASignature");b("2.16.840.1.101.3.4.2.1","sha256");b("2.16.840.1.101.3.4.2.2","sha384");b("2.16.840.1.101.3.4.2.3","sha512");b("2.16.840.1.101.3.4.2.4","sha224");b("2.16.840.1.101.3.4.2.5","sha512-224");b("2.16.840.1.101.3.4.2.6","sha512-256");b("1.2.840.113549.2.2","md2");b("1.2.840.113549.2.5","md5");b("1.2.840.113549.1.7.1","data");b("1.2.840.113549.1.7.2","signedData");b("1.2.840.113549.1.7.3","envelopedData");b("1.2.840.113549.1.7.4","signedAndEnvelopedData");b("1.2.840.113549.1.7.5","digestedData");b("1.2.840.113549.1.7.6","encryptedData");b("1.2.840.113549.1.9.1","emailAddress");b("1.2.840.113549.1.9.2","unstructuredName");b("1.2.840.113549.1.9.3","contentType");b("1.2.840.113549.1.9.4","messageDigest");b("1.2.840.113549.1.9.5","signingTime");b("1.2.840.113549.1.9.6","counterSignature");b("1.2.840.113549.1.9.7","challengePassword");b("1.2.840.113549.1.9.8","unstructuredAddress");b("1.2.840.113549.1.9.14","extensionRequest");b("1.2.840.113549.1.9.20","friendlyName");b("1.2.840.113549.1.9.21","localKeyId");b("1.2.840.113549.1.9.22.1","x509Certificate");b("1.2.840.113549.1.12.10.1.1","keyBag");b("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");b("1.2.840.113549.1.12.10.1.3","certBag");b("1.2.840.113549.1.12.10.1.4","crlBag");b("1.2.840.113549.1.12.10.1.5","secretBag");b("1.2.840.113549.1.12.10.1.6","safeContentsBag");b("1.2.840.113549.1.5.13","pkcs5PBES2");b("1.2.840.113549.1.5.12","pkcs5PBKDF2");b("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");b("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");b("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");b("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");b("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");b("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");b("1.2.840.113549.2.7","hmacWithSHA1");b("1.2.840.113549.2.8","hmacWithSHA224");b("1.2.840.113549.2.9","hmacWithSHA256");b("1.2.840.113549.2.10","hmacWithSHA384");b("1.2.840.113549.2.11","hmacWithSHA512");b("1.2.840.113549.3.7","des-EDE3-CBC");b("2.16.840.1.101.3.4.1.2","aes128-CBC");b("2.16.840.1.101.3.4.1.22","aes192-CBC");b("2.16.840.1.101.3.4.1.42","aes256-CBC");b("2.5.4.3","commonName");b("2.5.4.4","surname");b("2.5.4.5","serialNumber");b("2.5.4.6","countryName");b("2.5.4.7","localityName");b("2.5.4.8","stateOrProvinceName");b("2.5.4.9","streetAddress");b("2.5.4.10","organizationName");b("2.5.4.11","organizationalUnitName");b("2.5.4.12","title");b("2.5.4.13","description");b("2.5.4.15","businessCategory");b("2.5.4.17","postalCode");b("2.5.4.42","givenName");b("2.5.4.65","pseudonym");b("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");b("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");b("2.16.840.1.113730.1.1","nsCertType");b("2.16.840.1.113730.1.13","nsComment");k$("2.5.29.1","authorityKeyIdentifier");k$("2.5.29.2","keyAttributes");k$("2.5.29.3","certificatePolicies");k$("2.5.29.4","keyUsageRestriction");k$("2.5.29.5","policyMapping");k$("2.5.29.6","subtreesConstraint");k$("2.5.29.7","subjectAltName");k$("2.5.29.8","issuerAltName");k$("2.5.29.9","subjectDirectoryAttributes");k$("2.5.29.10","basicConstraints");k$("2.5.29.11","nameConstraints");k$("2.5.29.12","policyConstraints");k$("2.5.29.13","basicConstraints");b("2.5.29.14","subjectKeyIdentifier");b("2.5.29.15","keyUsage");k$("2.5.29.16","privateKeyUsagePeriod");b("2.5.29.17","subjectAltName");b("2.5.29.18","issuerAltName");b("2.5.29.19","basicConstraints");k$("2.5.29.20","cRLNumber");k$("2.5.29.21","cRLReason");k$("2.5.29.22","expirationDate");k$("2.5.29.23","instructionCode");k$("2.5.29.24","invalidityDate");k$("2.5.29.25","cRLDistributionPoints");k$("2.5.29.26","issuingDistributionPoint");k$("2.5.29.27","deltaCRLIndicator");k$("2.5.29.28","issuingDistributionPoint");k$("2.5.29.29","certificateIssuer");k$("2.5.29.30","nameConstraints");b("2.5.29.31","cRLDistributionPoints");b("2.5.29.32","certificatePolicies");k$("2.5.29.33","policyMappings");k$("2.5.29.34","policyConstraints");b("2.5.29.35","authorityKeyIdentifier");k$("2.5.29.36","policyConstraints");b("2.5.29.37","extKeyUsage");k$("2.5.29.46","freshestCRL");k$("2.5.29.54","inhibitAnyPolicy");b("1.3.6.1.4.1.11129.2.4.2","timestampList");b("1.3.6.1.5.5.7.1.1","authorityInfoAccess");b("1.3.6.1.5.5.7.3.1","serverAuth");b("1.3.6.1.5.5.7.3.2","clientAuth");b("1.3.6.1.5.5.7.3.3","codeSigning");b("1.3.6.1.5.5.7.3.4","emailProtection");b("1.3.6.1.5.5.7.3.8","timeStamping")});var lJ=q$((TF,pG)=>{var p$=F$();_$();x0();var d=pG.exports=p$.asn1=p$.asn1||{};d.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};d.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};d.maxDepth=256;d.create=function($,J,X,Q,Y){if(p$.util.isArray(Q)){var G=[];for(var W=0;W<Q.length;++W)if(Q[W]!==void 0)G.push(Q[W]);Q=G}var U={tagClass:$,type:J,constructed:X,composed:X||p$.util.isArray(Q),value:Q};if(Y&&"bitStringContents"in Y)U.bitStringContents=Y.bitStringContents,U.original=d.copy(U);return U};d.copy=function($,J){var X;if(p$.util.isArray($)){X=[];for(var Q=0;Q<$.length;++Q)X.push(d.copy($[Q],J));return X}if(typeof $==="string")return $;if(X={tagClass:$.tagClass,type:$.type,constructed:$.constructed,composed:$.composed,value:d.copy($.value,J)},J&&!J.excludeBitStringContents)X.bitStringContents=$.bitStringContents;return X};d.equals=function($,J,X){if(p$.util.isArray($)){if(!p$.util.isArray(J))return!1;if($.length!==J.length)return!1;for(var Q=0;Q<$.length;++Q)if(!d.equals($[Q],J[Q]))return!1;return!0}if(typeof $!==typeof J)return!1;if(typeof $==="string")return $===J;var Y=$.tagClass===J.tagClass&&$.type===J.type&&$.constructed===J.constructed&&$.composed===J.composed&&d.equals($.value,J.value);if(X&&X.includeBitStringContents)Y=Y&&$.bitStringContents===J.bitStringContents;return Y};d.getBerValueLength=function($){var J=$.getByte();if(J===128)return;var X,Q=J&128;if(!Q)X=J;else X=$.getInt((J&127)<<3);return X};function jX($,J,X){if(X>J){var Q=Error("Too few bytes to parse DER.");throw Q.available=$.length(),Q.remaining=J,Q.requested=X,Q}}var zM=function($,J){var X=$.getByte();if(J--,X===128)return;var Q,Y=X&128;if(!Y)Q=X;else{var G=X&127;jX($,J,G),Q=$.getInt(G<<3)}if(Q<0)throw Error("Negative length: "+Q);return Q};d.fromDer=function($,J){if(J===void 0)J={strict:!0,parseAllBytes:!0,decodeBitStrings:!0};if(typeof J==="boolean")J={strict:J,parseAllBytes:!0,decodeBitStrings:!0};if(!("strict"in J))J.strict=!0;if(!("parseAllBytes"in J))J.parseAllBytes=!0;if(!("decodeBitStrings"in J))J.decodeBitStrings=!0;if(!("maxDepth"in J))J.maxDepth=d.maxDepth;if(typeof $==="string")$=p$.util.createBuffer($);var X=$.length(),Q=SY($,$.length(),0,J);if(J.parseAllBytes&&$.length()!==0){var Y=Error("Unparsed DER bytes remain after ASN.1 parsing.");throw Y.byteCount=X,Y.remaining=$.length(),Y}return Q};function SY($,J,X,Q){if(X>=Q.maxDepth)throw Error("ASN.1 parsing error: Max depth exceeded.");var Y;jX($,J,2);var G=$.getByte();J--;var W=G&192,U=G&31;Y=$.length();var M=zM($,J);if(J-=Y-$.length(),M!==void 0&&M>J){if(Q.strict){var O=Error("Too few bytes to read ASN.1 value.");throw O.available=$.length(),O.remaining=J,O.requested=M,O}M=J}var V,q,H=(G&32)===32;if(H)if(V=[],M===void 0)for(;;){if(jX($,J,2),$.bytes(2)===String.fromCharCode(0,0)){$.getBytes(2),J-=2;break}Y=$.length(),V.push(SY($,J,X+1,Q)),J-=Y-$.length()}else while(M>0)Y=$.length(),V.push(SY($,M,X+1,Q)),J-=Y-$.length(),M-=Y-$.length();if(V===void 0&&W===d.Class.UNIVERSAL&&U===d.Type.BITSTRING)q=$.bytes(M);if(V===void 0&&Q.decodeBitStrings&&W===d.Class.UNIVERSAL&&U===d.Type.BITSTRING&&M>1){var N=$.read,K=J,L=0;if(U===d.Type.BITSTRING)jX($,J,1),L=$.getByte(),J--;if(L===0)try{Y=$.length();var A={strict:!0,decodeBitStrings:!0},D=SY($,J,X+1,A),S=Y-$.length();if(J-=S,U==d.Type.BITSTRING)S++;var B=D.tagClass;if(S===M&&(B===d.Class.UNIVERSAL||B===d.Class.CONTEXT_SPECIFIC))V=[D]}catch(w){}if(V===void 0)$.read=N,J=K}if(V===void 0){if(M===void 0){if(Q.strict)throw Error("Non-constructed ASN.1 object of indefinite length.");M=J}if(U===d.Type.BMPSTRING){V="";for(;M>0;M-=2)jX($,J,2),V+=String.fromCharCode($.getInt16()),J-=2}else V=$.getBytes(M),J-=M}var C=q===void 0?null:{bitStringContents:q};return d.create(W,U,H,V,C)}d.toDer=function($){var J=p$.util.createBuffer(),X=$.tagClass|$.type,Q=p$.util.createBuffer(),Y=!1;if("bitStringContents"in $){if(Y=!0,$.original)Y=d.equals($,$.original)}if(Y)Q.putBytes($.bitStringContents);else if($.composed){if($.constructed)X|=32;else Q.putByte(0);for(var G=0;G<$.value.length;++G)if($.value[G]!==void 0)Q.putBuffer(d.toDer($.value[G]))}else if($.type===d.Type.BMPSTRING)for(var G=0;G<$.value.length;++G)Q.putInt16($.value.charCodeAt(G));else if($.type===d.Type.INTEGER&&$.value.length>1&&($.value.charCodeAt(0)===0&&($.value.charCodeAt(1)&128)===0||$.value.charCodeAt(0)===255&&($.value.charCodeAt(1)&128)===128))Q.putBytes($.value.substr(1));else Q.putBytes($.value);if(J.putByte(X),Q.length()<=127)J.putByte(Q.length()&127);else{var W=Q.length(),U="";do U+=String.fromCharCode(W&255),W=W>>>8;while(W>0);J.putByte(U.length|128);for(var G=U.length-1;G>=0;--G)J.putByte(U.charCodeAt(G))}return J.putBuffer(Q),J};d.oidToDer=function($){var J=$.split("."),X=p$.util.createBuffer();X.putByte(40*parseInt(J[0],10)+parseInt(J[1],10));var Q,Y,G,W;for(var U=2;U<J.length;++U){if(Q=!0,Y=[],G=parseInt(J[U],10),G>4294967295)throw Error("OID value too large; max is 32-bits.");do{if(W=G&127,G=G>>>7,!Q)W|=128;Y.push(W),Q=!1}while(G>0);for(var M=Y.length-1;M>=0;--M)X.putByte(Y[M])}return X};d.derToOid=function($){var J;if(typeof $==="string")$=p$.util.createBuffer($);var X=$.getByte();J=Math.floor(X/40)+"."+X%40;var Q=0;while($.length()>0){if(Q>70368744177663)throw Error("OID value too large; max is 53-bits.");if(X=$.getByte(),Q=Q*128,X&128)Q+=X&127;else J+="."+(Q+X),Q=0}return J};d.utcTimeToDate=function($){var J=new Date,X=parseInt($.substr(0,2),10);X=X>=50?1900+X:2000+X;var Q=parseInt($.substr(2,2),10)-1,Y=parseInt($.substr(4,2),10),G=parseInt($.substr(6,2),10),W=parseInt($.substr(8,2),10),U=0;if($.length>11){var M=$.charAt(10),O=10;if(M!=="+"&&M!=="-")U=parseInt($.substr(10,2),10),O+=2}if(J.setUTCFullYear(X,Q,Y),J.setUTCHours(G,W,U,0),O){if(M=$.charAt(O),M==="+"||M==="-"){var V=parseInt($.substr(O+1,2),10),q=parseInt($.substr(O+4,2),10),H=V*60+q;if(H*=60000,M==="+")J.setTime(+J-H);else J.setTime(+J+H)}}return J};d.generalizedTimeToDate=function($){var J=new Date,X=parseInt($.substr(0,4),10),Q=parseInt($.substr(4,2),10)-1,Y=parseInt($.substr(6,2),10),G=parseInt($.substr(8,2),10),W=parseInt($.substr(10,2),10),U=parseInt($.substr(12,2),10),M=0,O=0,V=!1;if($.charAt($.length-1)==="Z")V=!0;var q=$.length-5,H=$.charAt(q);if(H==="+"||H==="-"){var N=parseInt($.substr(q+1,2),10),K=parseInt($.substr(q+4,2),10);if(O=N*60+K,O*=60000,H==="+")O*=-1;V=!0}if($.charAt(14)===".")M=parseFloat($.substr(14),10)*1000;if(V)J.setUTCFullYear(X,Q,Y),J.setUTCHours(G,W,U,M),J.setTime(+J+O);else J.setFullYear(X,Q,Y),J.setHours(G,W,U,M);return J};d.dateToUtcTime=function($){if(typeof $==="string")return $;var J="",X=[];X.push((""+$.getUTCFullYear()).substr(2)),X.push(""+($.getUTCMonth()+1)),X.push(""+$.getUTCDate()),X.push(""+$.getUTCHours()),X.push(""+$.getUTCMinutes()),X.push(""+$.getUTCSeconds());for(var Q=0;Q<X.length;++Q){if(X[Q].length<2)J+="0";J+=X[Q]}return J+="Z",J};d.dateToGeneralizedTime=function($){if(typeof $==="string")return $;var J="",X=[];X.push(""+$.getUTCFullYear()),X.push(""+($.getUTCMonth()+1)),X.push(""+$.getUTCDate()),X.push(""+$.getUTCHours()),X.push(""+$.getUTCMinutes()),X.push(""+$.getUTCSeconds());for(var Q=0;Q<X.length;++Q){if(X[Q].length<2)J+="0";J+=X[Q]}return J+="Z",J};d.integerToDer=function($){var J=p$.util.createBuffer();if($>=-128&&$<128)return J.putSignedInt($,8);if($>=-32768&&$<32768)return J.putSignedInt($,16);if($>=-8388608&&$<8388608)return J.putSignedInt($,24);if($>=-2147483648&&$<2147483648)return J.putSignedInt($,32);var X=Error("Integer too large; max is 32-bits.");throw X.integer=$,X};d.derToInteger=function($){if(typeof $==="string")$=p$.util.createBuffer($);var J=$.length()*8;if(J>32)throw Error("Integer too large; max is 32-bits.");return $.getSignedInt(J)};d.validate=function($,J,X,Q){var Y=!1;if(($.tagClass===J.tagClass||typeof J.tagClass>"u")&&($.type===J.type||typeof J.type>"u")){if($.constructed===J.constructed||typeof J.constructed>"u"){if(Y=!0,J.value&&p$.util.isArray(J.value)){var G=0;for(var W=0;Y&&W<J.value.length;++W){var U=J.value[W];Y=!!U.optional;var M=$.value[G];if(!M){if(!U.optional){if(Y=!1,Q)Q.push("["+J.name+'] Missing required element. Expected tag class "'+U.tagClass+'", type "'+U.type+'"')}continue}var O=typeof U.tagClass<"u"&&typeof U.type<"u";if(O&&(M.tagClass!==U.tagClass||M.type!==U.type))if(U.optional){Y=!0;continue}else{if(Y=!1,Q)Q.push("["+J.name+"] Tag mismatch. Expected ("+U.tagClass+","+U.type+"), got ("+M.tagClass+","+M.type+")");break}var V=d.validate(M,U,X,Q);if(V)++G,Y=!0;else if(U.optional)Y=!0;else{Y=!1;break}}}if(Y&&X){if(J.capture)X[J.capture]=$.value;if(J.captureAsn1)X[J.captureAsn1]=$;if(J.captureBitStringContents&&"bitStringContents"in $)X[J.captureBitStringContents]=$.bitStringContents;if(J.captureBitStringValue&&"bitStringContents"in $){var q;if($.bitStringContents.length<2)X[J.captureBitStringValue]="";else{var H=$.bitStringContents.charCodeAt(0);if(H!==0)throw Error("captureBitStringValue only supported for zero unused bits");X[J.captureBitStringValue]=$.bitStringContents.slice(1)}}}}else if(Q)Q.push("["+J.name+'] Expected constructed "'+J.constructed+'", got "'+$.constructed+'"')}else if(Q){if($.tagClass!==J.tagClass)Q.push("["+J.name+'] Expected tag class "'+J.tagClass+'", got "'+$.tagClass+'"');if($.type!==J.type)Q.push("["+J.name+'] Expected type "'+J.type+'", got "'+$.type+'"')}return Y};var lG=/[^\\u0000-\\u00ff]/;d.prettyPrint=function($,J,X){var Q="";if(J=J||0,X=X||2,J>0)Q+=`
6
+ `;var Y="";for(var G=0;G<J*X;++G)Y+=" ";switch(Q+=Y+"Tag: ",$.tagClass){case d.Class.UNIVERSAL:Q+="Universal:";break;case d.Class.APPLICATION:Q+="Application:";break;case d.Class.CONTEXT_SPECIFIC:Q+="Context-Specific:";break;case d.Class.PRIVATE:Q+="Private:";break}if($.tagClass===d.Class.UNIVERSAL)switch(Q+=$.type,$.type){case d.Type.NONE:Q+=" (None)";break;case d.Type.BOOLEAN:Q+=" (Boolean)";break;case d.Type.INTEGER:Q+=" (Integer)";break;case d.Type.BITSTRING:Q+=" (Bit string)";break;case d.Type.OCTETSTRING:Q+=" (Octet string)";break;case d.Type.NULL:Q+=" (Null)";break;case d.Type.OID:Q+=" (Object Identifier)";break;case d.Type.ODESC:Q+=" (Object Descriptor)";break;case d.Type.EXTERNAL:Q+=" (External or Instance of)";break;case d.Type.REAL:Q+=" (Real)";break;case d.Type.ENUMERATED:Q+=" (Enumerated)";break;case d.Type.EMBEDDED:Q+=" (Embedded PDV)";break;case d.Type.UTF8:Q+=" (UTF8)";break;case d.Type.ROID:Q+=" (Relative Object Identifier)";break;case d.Type.SEQUENCE:Q+=" (Sequence)";break;case d.Type.SET:Q+=" (Set)";break;case d.Type.PRINTABLESTRING:Q+=" (Printable String)";break;case d.Type.IA5String:Q+=" (IA5String (ASCII))";break;case d.Type.UTCTIME:Q+=" (UTC time)";break;case d.Type.GENERALIZEDTIME:Q+=" (Generalized time)";break;case d.Type.BMPSTRING:Q+=" (BMP String)";break}else Q+=$.type;if(Q+=`
7
+ `,Q+=Y+"Constructed: "+$.constructed+`
8
+ `,$.composed){var W=0,U="";for(var G=0;G<$.value.length;++G)if($.value[G]!==void 0){if(W+=1,U+=d.prettyPrint($.value[G],J+1,X),G+1<$.value.length)U+=","}Q+=Y+"Sub values: "+W+U}else{if(Q+=Y+"Value: ",$.type===d.Type.OID){var M=d.derToOid($.value);if(Q+=M,p$.pki&&p$.pki.oids){if(M in p$.pki.oids)Q+=" ("+p$.pki.oids[M]+") "}}if($.type===d.Type.INTEGER)try{Q+=d.derToInteger($.value)}catch(V){Q+="0x"+p$.util.bytesToHex($.value)}else if($.type===d.Type.BITSTRING){if($.value.length>1)Q+="0x"+p$.util.bytesToHex($.value.slice(1));else Q+="(none)";if($.value.length>0){var O=$.value.charCodeAt(0);if(O==1)Q+=" (1 unused bit shown)";else if(O>1)Q+=" ("+O+" unused bits shown)"}}else if($.type===d.Type.OCTETSTRING){if(!lG.test($.value))Q+="("+$.value+") ";Q+="0x"+p$.util.bytesToHex($.value)}else if($.type===d.Type.UTF8)try{Q+=p$.util.decodeUtf8($.value)}catch(V){if(V.message==="URI malformed")Q+="0x"+p$.util.bytesToHex($.value)+" (malformed UTF8)";else throw V}else if($.type===d.Type.PRINTABLESTRING||$.type===d.Type.IA5String)Q+=$.value;else if(lG.test($.value))Q+="0x"+p$.util.bytesToHex($.value);else if($.value.length===0)Q+="[null]";else Q+=$.value}return Q}});var J0=q$((SF,dG)=>{var IY=F$();dG.exports=IY.md=IY.md||{};IY.md.algorithms=IY.md.algorithms||{}});var IQ=q$((IF,cG)=>{var L0=F$();J0();_$();var EM=cG.exports=L0.hmac=L0.hmac||{};EM.create=function(){var $=null,J=null,X=null,Q=null,Y={};return Y.start=function(G,W){if(G!==null)if(typeof G==="string")if(G=G.toLowerCase(),G in L0.md.algorithms)J=L0.md.algorithms[G].create();else throw Error('Unknown hash algorithm "'+G+'"');else J=G;if(W===null)W=$;else{if(typeof W==="string")W=L0.util.createBuffer(W);else if(L0.util.isArray(W)){var U=W;W=L0.util.createBuffer();for(var M=0;M<U.length;++M)W.putByte(U[M])}var O=W.length();if(O>J.blockLength)J.start(),J.update(W.bytes()),W=J.digest();X=L0.util.createBuffer(),Q=L0.util.createBuffer(),O=W.length();for(var M=0;M<O;++M){var U=W.at(M);X.putByte(54^U),Q.putByte(92^U)}if(O<J.blockLength){var U=J.blockLength-O;for(var M=0;M<U;++M)X.putByte(54),Q.putByte(92)}$=W,X=X.bytes(),Q=Q.bytes()}J.start(),J.update(X)},Y.update=function(G){J.update(G)},Y.getMac=function(){var G=J.digest().bytes();return J.start(),J.update(Q),J.update(G),J.digest()},Y.digest=Y.getMac,Y}});var wY=q$((CF,aG)=>{var Q0=F$();J0();_$();var iG=aG.exports=Q0.md5=Q0.md5||{};Q0.md.md5=Q0.md.algorithms.md5=iG;iG.create=function(){if(!oG)FM();var $=null,J=Q0.util.createBuffer(),X=Array(16),Q={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return Q.start=function(){Q.messageLength=0,Q.fullMessageLength=Q.messageLength64=[];var Y=Q.messageLengthSize/4;for(var G=0;G<Y;++G)Q.fullMessageLength.push(0);return J=Q0.util.createBuffer(),$={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},Q},Q.start(),Q.update=function(Y,G){if(G==="utf8")Y=Q0.util.encodeUtf8(Y);var W=Y.length;Q.messageLength+=W,W=[W/4294967296>>>0,W>>>0];for(var U=Q.fullMessageLength.length-1;U>=0;--U)Q.fullMessageLength[U]+=W[1],W[1]=W[0]+(Q.fullMessageLength[U]/4294967296>>>0),Q.fullMessageLength[U]=Q.fullMessageLength[U]>>>0,W[0]=W[1]/4294967296>>>0;if(J.putBytes(Y),nG($,X,J),J.read>2048||J.length()===0)J.compact();return Q},Q.digest=function(){var Y=Q0.util.createBuffer();Y.putBytes(J.bytes());var G=Q.fullMessageLength[Q.fullMessageLength.length-1]+Q.messageLengthSize,W=G&Q.blockLength-1;Y.putBytes(W8.substr(0,Q.blockLength-W));var U,M=0;for(var O=Q.fullMessageLength.length-1;O>=0;--O)U=Q.fullMessageLength[O]*8+M,M=U/4294967296>>>0,Y.putInt32Le(U>>>0);var V={h0:$.h0,h1:$.h1,h2:$.h2,h3:$.h3};nG(V,X,Y);var q=Q0.util.createBuffer();return q.putInt32Le(V.h0),q.putInt32Le(V.h1),q.putInt32Le(V.h2),q.putInt32Le(V.h3),q},Q};var W8=null,CY=null,TX=null,CQ=null,oG=!1;function FM(){W8=String.fromCharCode(128),W8+=Q0.util.fillString(String.fromCharCode(0),64),CY=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],TX=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],CQ=Array(64);for(var $=0;$<64;++$)CQ[$]=Math.floor(Math.abs(Math.sin($+1))*4294967296);oG=!0}function nG($,J,X){var Q,Y,G,W,U,M,O,V,q=X.length();while(q>=64){Y=$.h0,G=$.h1,W=$.h2,U=$.h3;for(V=0;V<16;++V)J[V]=X.getInt32Le(),M=U^G&(W^U),Q=Y+M+CQ[V]+J[V],O=TX[V],Y=U,U=W,W=G,G+=Q<<O|Q>>>32-O;for(;V<32;++V)M=W^U&(G^W),Q=Y+M+CQ[V]+J[CY[V]],O=TX[V],Y=U,U=W,W=G,G+=Q<<O|Q>>>32-O;for(;V<48;++V)M=G^W^U,Q=Y+M+CQ[V]+J[CY[V]],O=TX[V],Y=U,U=W,W=G,G+=Q<<O|Q>>>32-O;for(;V<64;++V)M=W^(G|~U),Q=Y+M+CQ[V]+J[CY[V]],O=TX[V],Y=U,U=W,W=G,G+=Q<<O|Q>>>32-O;$.h0=$.h0+Y|0,$.h1=$.h1+G|0,$.h2=$.h2+W|0,$.h3=$.h3+U|0,q-=64}}});var YQ=q$((wF,rG)=>{var _Y=F$();_$();var sG=rG.exports=_Y.pem=_Y.pem||{};sG.encode=function($,J){J=J||{};var X="-----BEGIN "+$.type+`-----\r
9
+ `,Q;if($.procType)Q={name:"Proc-Type",values:[String($.procType.version),$.procType.type]},X+=PY(Q);if($.contentDomain)Q={name:"Content-Domain",values:[$.contentDomain]},X+=PY(Q);if($.dekInfo){if(Q={name:"DEK-Info",values:[$.dekInfo.algorithm]},$.dekInfo.parameters)Q.values.push($.dekInfo.parameters);X+=PY(Q)}if($.headers)for(var Y=0;Y<$.headers.length;++Y)X+=PY($.headers[Y]);if($.procType)X+=`\r
10
+ `;return X+=_Y.util.encode64($.body,J.maxline||64)+`\r
11
+ `,X+="-----END "+$.type+`-----\r
12
+ `,X};sG.decode=function($){var J=[],X=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,Q=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,Y=/\r?\n/,G;while(!0){if(G=X.exec($),!G)break;var W=G[1];if(W==="NEW CERTIFICATE REQUEST")W="CERTIFICATE REQUEST";var U={type:W,procType:null,contentDomain:null,dekInfo:null,headers:[],body:_Y.util.decode64(G[3])};if(J.push(U),!G[2])continue;var M=G[2].split(Y),O=0;while(G&&O<M.length){var V=M[O].replace(/\s+$/,"");for(var q=O+1;q<M.length;++q){var H=M[q];if(!/\s/.test(H[0]))break;V+=H,O=q}if(G=V.match(Q),G){var N={name:G[1],values:[]},K=G[2].split(",");for(var L=0;L<K.length;++L)N.values.push(NM(K[L]));if(!U.procType){if(N.name!=="Proc-Type")throw Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');else if(N.values.length!==2)throw Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');U.procType={version:K[0],type:K[1]}}else if(!U.contentDomain&&N.name==="Content-Domain")U.contentDomain=K[0]||"";else if(!U.dekInfo&&N.name==="DEK-Info"){if(N.values.length===0)throw Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');U.dekInfo={algorithm:K[0],parameters:K[1]||null}}else U.headers.push(N)}++O}if(U.procType==="ENCRYPTED"&&!U.dekInfo)throw Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}if(J.length===0)throw Error("Invalid PEM formatted message.");return J};function PY($){var J=$.name+": ",X=[],Q=function(M,O){return" "+O};for(var Y=0;Y<$.values.length;++Y)X.push($.values[Y].replace(/^(\S+\r\n)/,Q));J+=X.join(",")+`\r
13
+ `;var G=0,W=-1;for(var Y=0;Y<J.length;++Y,++G)if(G>65&&W!==-1){var U=J[W];if(U===",")++W,J=J.substr(0,W)+`\r
14
+ `+J.substr(W);else J=J.substr(0,W)+`\r
15
+ `+U+J.substr(W+1);G=Y-W-1,W=-1,++Y}else if(J[Y]===" "||J[Y]==="\t"||J[Y]===",")W=Y;return J}function NM($){return $.replace(/^\s+/,"")}});var SX=q$((PF,eG)=>{var c$=F$();ZY();J8();_$();eG.exports=c$.des=c$.des||{};c$.des.startEncrypting=function($,J,X,Q){var Y=xY({key:$,output:X,decrypt:!1,mode:Q||(J===null?"ECB":"CBC")});return Y.start(J),Y};c$.des.createEncryptionCipher=function($,J){return xY({key:$,output:null,decrypt:!1,mode:J})};c$.des.startDecrypting=function($,J,X,Q){var Y=xY({key:$,output:X,decrypt:!0,mode:Q||(J===null?"ECB":"CBC")});return Y.start(J),Y};c$.des.createDecryptionCipher=function($,J){return xY({key:$,output:null,decrypt:!0,mode:J})};c$.des.Algorithm=function($,J){var X=this;X.name=$,X.mode=new J({blockSize:8,cipher:{encrypt:function(Q,Y){return tG(X._keys,Q,Y,!1)},decrypt:function(Q,Y){return tG(X._keys,Q,Y,!0)}}}),X._init=!1};c$.des.Algorithm.prototype.initialize=function($){if(this._init)return;var J=c$.util.createBuffer($.key);if(this.name.indexOf("3DES")===0){if(J.length()!==24)throw Error("Invalid Triple-DES key size: "+J.length()*8)}this._keys=SM(J),this._init=!0};X0("DES-ECB",c$.cipher.modes.ecb);X0("DES-CBC",c$.cipher.modes.cbc);X0("DES-CFB",c$.cipher.modes.cfb);X0("DES-OFB",c$.cipher.modes.ofb);X0("DES-CTR",c$.cipher.modes.ctr);X0("3DES-ECB",c$.cipher.modes.ecb);X0("3DES-CBC",c$.cipher.modes.cbc);X0("3DES-CFB",c$.cipher.modes.cfb);X0("3DES-OFB",c$.cipher.modes.ofb);X0("3DES-CTR",c$.cipher.modes.ctr);function X0($,J){var X=function(){return new c$.des.Algorithm($,J)};c$.cipher.registerAlgorithm($,X)}var LM=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],AM=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],RM=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],DM=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],ZM=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],BM=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],jM=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],TM=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function SM($){var J=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],X=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],Q=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],Y=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],G=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],W=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],U=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],M=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],O=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],V=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],q=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],H=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],N=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],K=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],L=$.length()>8?3:1,A=[],D=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],S=0,B;for(var C=0;C<L;C++){var w=$.getInt32(),P=$.getInt32();B=(w>>>4^P)&252645135,P^=B,w^=B<<4,B=(P>>>-16^w)&65535,w^=B,P^=B<<-16,B=(w>>>2^P)&858993459,P^=B,w^=B<<2,B=(P>>>-16^w)&65535,w^=B,P^=B<<-16,B=(w>>>1^P)&1431655765,P^=B,w^=B<<1,B=(P>>>8^w)&16711935,w^=B,P^=B<<8,B=(w>>>1^P)&1431655765,P^=B,w^=B<<1,B=w<<8|P>>>20&240,w=P<<24|P<<8&16711680|P>>>8&65280|P>>>24&240,P=B;for(var l=0;l<D.length;++l){if(D[l])w=w<<2|w>>>26,P=P<<2|P>>>26;else w=w<<1|w>>>27,P=P<<1|P>>>27;w&=-15,P&=-15;var $$=J[w>>>28]|X[w>>>24&15]|Q[w>>>20&15]|Y[w>>>16&15]|G[w>>>12&15]|W[w>>>8&15]|U[w>>>4&15],y=M[P>>>28]|O[P>>>24&15]|V[P>>>20&15]|q[P>>>16&15]|H[P>>>12&15]|N[P>>>8&15]|K[P>>>4&15];B=(y>>>16^$$)&65535,A[S++]=$$^B,A[S++]=y^B<<16}}return A}function tG($,J,X,Q){var Y=$.length===32?3:9,G;if(Y===3)G=Q?[30,-2,-2]:[0,32,2];else G=Q?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var W,U=J[0],M=J[1];W=(U>>>4^M)&252645135,M^=W,U^=W<<4,W=(U>>>16^M)&65535,M^=W,U^=W<<16,W=(M>>>2^U)&858993459,U^=W,M^=W<<2,W=(M>>>8^U)&16711935,U^=W,M^=W<<8,W=(U>>>1^M)&1431655765,M^=W,U^=W<<1,U=U<<1|U>>>31,M=M<<1|M>>>31;for(var O=0;O<Y;O+=3){var V=G[O+1],q=G[O+2];for(var H=G[O];H!=V;H+=q){var N=M^$[H],K=(M>>>4|M<<28)^$[H+1];W=U,U=M,M=W^(AM[N>>>24&63]|DM[N>>>16&63]|BM[N>>>8&63]|TM[N&63]|LM[K>>>24&63]|RM[K>>>16&63]|ZM[K>>>8&63]|jM[K&63])}W=U,U=M,M=W}U=U>>>1|U<<31,M=M>>>1|M<<31,W=(U>>>1^M)&1431655765,M^=W,U^=W<<1,W=(M>>>8^U)&16711935,U^=W,M^=W<<8,W=(M>>>2^U)&858993459,U^=W,M^=W<<2,W=(U>>>16^M)&65535,M^=W,U^=W<<16,W=(U>>>4^M)&252645135,M^=W,U^=W<<4,X[0]=U,X[1]=M}function xY($){$=$||{};var J=($.mode||"CBC").toUpperCase(),X="DES-"+J,Q;if($.decrypt)Q=c$.cipher.createDecipher(X,$.key);else Q=c$.cipher.createCipher(X,$.key);var Y=Q.start;return Q.start=function(G,W){var U=null;if(W instanceof c$.util.ByteBuffer)U=W,W={};W=W||{},W.output=U,W.iv=G,Y.call(Q,W)},Q}});var vY=q$((_F,$1)=>{var AJ=F$();IQ();J0();_$();var IM=AJ.pkcs5=AJ.pkcs5||{},A0;if(AJ.util.isNodejs&&!AJ.options.usePureJavaScript)A0=FX("crypto");$1.exports=AJ.pbkdf2=IM.pbkdf2=function($,J,X,Q,Y,G){if(typeof Y==="function")G=Y,Y=null;if(AJ.util.isNodejs&&!AJ.options.usePureJavaScript&&A0.pbkdf2&&(Y===null||typeof Y!=="object")&&(A0.pbkdf2Sync.length>4||(!Y||Y==="sha1"))){if(typeof Y!=="string")Y="sha1";if($=Buffer.from($,"binary"),J=Buffer.from(J,"binary"),!G){if(A0.pbkdf2Sync.length===4)return A0.pbkdf2Sync($,J,X,Q).toString("binary");return A0.pbkdf2Sync($,J,X,Q,Y).toString("binary")}if(A0.pbkdf2Sync.length===4)return A0.pbkdf2($,J,X,Q,function(B,C){if(B)return G(B);G(null,C.toString("binary"))});return A0.pbkdf2($,J,X,Q,Y,function(B,C){if(B)return G(B);G(null,C.toString("binary"))})}if(typeof Y>"u"||Y===null)Y="sha1";if(typeof Y==="string"){if(!(Y in AJ.md.algorithms))throw Error("Unknown hash algorithm: "+Y);Y=AJ.md[Y].create()}var W=Y.digestLength;if(Q>4294967295*W){var U=Error("Derived key is too long.");if(G)return G(U);throw U}var M=Math.ceil(Q/W),O=Q-(M-1)*W,V=AJ.hmac.create();V.start(Y,$);var q="",H,N,K;if(!G){for(var L=1;L<=M;++L){V.start(null,null),V.update(J),V.update(AJ.util.int32ToBytes(L)),H=K=V.digest().getBytes();for(var A=2;A<=X;++A)V.start(null,null),V.update(K),N=V.digest().getBytes(),H=AJ.util.xorBytes(H,N,W),K=N;q+=L<M?H:H.substr(0,O)}return q}var L=1,A;function D(){if(L>M)return G(null,q);V.start(null,null),V.update(J),V.update(AJ.util.int32ToBytes(L)),H=K=V.digest().getBytes(),A=2,S()}function S(){if(A<=X)return V.start(null,null),V.update(K),N=V.digest().getBytes(),H=AJ.util.xorBytes(H,N,W),K=N,++A,AJ.util.setImmediate(S);q+=L<M?H:H.substr(0,O),++L,D()}D()}});var M8=q$((xF,G1)=>{var Y0=F$();J0();_$();var Q1=G1.exports=Y0.sha256=Y0.sha256||{};Y0.md.sha256=Y0.md.algorithms.sha256=Q1;Q1.create=function(){if(!X1)CM();var $=null,J=Y0.util.createBuffer(),X=Array(64),Q={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return Q.start=function(){Q.messageLength=0,Q.fullMessageLength=Q.messageLength64=[];var Y=Q.messageLengthSize/4;for(var G=0;G<Y;++G)Q.fullMessageLength.push(0);return J=Y0.util.createBuffer(),$={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},Q},Q.start(),Q.update=function(Y,G){if(G==="utf8")Y=Y0.util.encodeUtf8(Y);var W=Y.length;Q.messageLength+=W,W=[W/4294967296>>>0,W>>>0];for(var U=Q.fullMessageLength.length-1;U>=0;--U)Q.fullMessageLength[U]+=W[1],W[1]=W[0]+(Q.fullMessageLength[U]/4294967296>>>0),Q.fullMessageLength[U]=Q.fullMessageLength[U]>>>0,W[0]=W[1]/4294967296>>>0;if(J.putBytes(Y),J1($,X,J),J.read>2048||J.length()===0)J.compact();return Q},Q.digest=function(){var Y=Y0.util.createBuffer();Y.putBytes(J.bytes());var G=Q.fullMessageLength[Q.fullMessageLength.length-1]+Q.messageLengthSize,W=G&Q.blockLength-1;Y.putBytes(U8.substr(0,Q.blockLength-W));var U,M,O=Q.fullMessageLength[0]*8;for(var V=0;V<Q.fullMessageLength.length-1;++V)U=Q.fullMessageLength[V+1]*8,M=U/4294967296>>>0,O+=M,Y.putInt32(O>>>0),O=U>>>0;Y.putInt32(O);var q={h0:$.h0,h1:$.h1,h2:$.h2,h3:$.h3,h4:$.h4,h5:$.h5,h6:$.h6,h7:$.h7};J1(q,X,Y);var H=Y0.util.createBuffer();return H.putInt32(q.h0),H.putInt32(q.h1),H.putInt32(q.h2),H.putInt32(q.h3),H.putInt32(q.h4),H.putInt32(q.h5),H.putInt32(q.h6),H.putInt32(q.h7),H},Q};var U8=null,X1=!1,Y1=null;function CM(){U8=String.fromCharCode(128),U8+=Y0.util.fillString(String.fromCharCode(0),64),Y1=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],X1=!0}function J1($,J,X){var Q,Y,G,W,U,M,O,V,q,H,N,K,L,A,D,S=X.length();while(S>=64){for(O=0;O<16;++O)J[O]=X.getInt32();for(;O<64;++O)Q=J[O-2],Q=(Q>>>17|Q<<15)^(Q>>>19|Q<<13)^Q>>>10,Y=J[O-15],Y=(Y>>>7|Y<<25)^(Y>>>18|Y<<14)^Y>>>3,J[O]=Q+J[O-7]+Y+J[O-16]|0;V=$.h0,q=$.h1,H=$.h2,N=$.h3,K=$.h4,L=$.h5,A=$.h6,D=$.h7;for(O=0;O<64;++O)W=(K>>>6|K<<26)^(K>>>11|K<<21)^(K>>>25|K<<7),U=A^K&(L^A),G=(V>>>2|V<<30)^(V>>>13|V<<19)^(V>>>22|V<<10),M=V&q|H&(V^q),Q=D+W+U+Y1[O]+J[O],Y=G+M,D=A,A=L,L=K,K=N+Q>>>0,N=H,H=q,q=V,V=Q+Y>>>0;$.h0=$.h0+V|0,$.h1=$.h1+q|0,$.h2=$.h2+H|0,$.h3=$.h3+N|0,$.h4=$.h4+K|0,$.h5=$.h5+L|0,$.h6=$.h6+A|0,$.h7=$.h7+D|0,S-=64}}});var O8=q$((vF,W1)=>{var G0=F$();_$();var kY=null;if(G0.util.isNodejs&&!G0.options.usePureJavaScript&&!process.versions["node-webkit"])kY=FX("crypto");var wM=W1.exports=G0.prng=G0.prng||{};wM.create=function($){var J={plugin:$,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},X=$.md,Q=Array(32);for(var Y=0;Y<32;++Y)Q[Y]=X.create();J.pools=Q,J.pool=0,J.generate=function(O,V){if(!V)return J.generateSync(O);var q=J.plugin.cipher,H=J.plugin.increment,N=J.plugin.formatKey,K=J.plugin.formatSeed,L=G0.util.createBuffer();J.key=null,A();function A(D){if(D)return V(D);if(L.length()>=O)return V(null,L.getBytes(O));if(J.generated>1048575)J.key=null;if(J.key===null)return G0.util.nextTick(function(){G(A)});var S=q(J.key,J.seed);J.generated+=S.length,L.putBytes(S),J.key=N(q(J.key,H(J.seed))),J.seed=K(q(J.key,J.seed)),G0.util.setImmediate(A)}},J.generateSync=function(O){var V=J.plugin.cipher,q=J.plugin.increment,H=J.plugin.formatKey,N=J.plugin.formatSeed;J.key=null;var K=G0.util.createBuffer();while(K.length()<O){if(J.generated>1048575)J.key=null;if(J.key===null)W();var L=V(J.key,J.seed);J.generated+=L.length,K.putBytes(L),J.key=H(V(J.key,q(J.seed))),J.seed=N(V(J.key,J.seed))}return K.getBytes(O)};function G(O){if(J.pools[0].messageLength>=32)return U(),O();var V=32-J.pools[0].messageLength<<5;J.seedFile(V,function(q,H){if(q)return O(q);J.collect(H),U(),O()})}function W(){if(J.pools[0].messageLength>=32)return U();var O=32-J.pools[0].messageLength<<5;J.collect(J.seedFileSync(O)),U()}function U(){J.reseeds=J.reseeds===4294967295?0:J.reseeds+1;var O=J.plugin.md.create();O.update(J.keyBytes);var V=1;for(var q=0;q<32;++q){if(J.reseeds%V===0)O.update(J.pools[q].digest().getBytes()),J.pools[q].start();V=V<<1}J.keyBytes=O.digest().getBytes(),O.start(),O.update(J.keyBytes);var H=O.digest().getBytes();J.key=J.plugin.formatKey(J.keyBytes),J.seed=J.plugin.formatSeed(H),J.generated=0}function M(O){var V=null,q=G0.util.globalScope,H=q.crypto||q.msCrypto;if(H&&H.getRandomValues)V=function(w){return H.getRandomValues(w)};var N=G0.util.createBuffer();if(V)while(N.length()<O){var K=Math.max(1,Math.min(O-N.length(),65536)/4),L=new Uint32Array(Math.floor(K));try{V(L);for(var A=0;A<L.length;++A)N.putInt32(L[A])}catch(w){if(!(typeof QuotaExceededError<"u"&&w instanceof QuotaExceededError))throw w}}if(N.length()<O){var D,S,B,C=Math.floor(Math.random()*65536);while(N.length()<O){S=16807*(C&65535),D=16807*(C>>16),S+=(D&32767)<<16,S+=D>>15,S=(S&2147483647)+(S>>31),C=S&4294967295;for(var A=0;A<3;++A)B=C>>>(A<<3),B^=Math.floor(Math.random()*256),N.putByte(B&255)}}return N.getBytes(O)}if(kY)J.seedFile=function(O,V){kY.randomBytes(O,function(q,H){if(q)return V(q);V(null,H.toString())})},J.seedFileSync=function(O){return kY.randomBytes(O).toString()};else J.seedFile=function(O,V){try{V(null,M(O))}catch(q){V(q)}},J.seedFileSync=M;return J.collect=function(O){var V=O.length;for(var q=0;q<V;++q)J.pools[J.pool].update(O.substr(q,1)),J.pool=J.pool===31?0:J.pool+1},J.collectInt=function(O,V){var q="";for(var H=0;H<V;H+=8)q+=String.fromCharCode(O>>H&255);J.collect(q)},J.registerWorker=function(O){if(O===self)J.seedFile=function(q,H){function N(K){var L=K.data;if(L.forge&&L.forge.prng)self.removeEventListener("message",N),H(L.forge.prng.err,L.forge.prng.bytes)}self.addEventListener("message",N),self.postMessage({forge:{prng:{needed:q}}})};else{var V=function(q){var H=q.data;if(H.forge&&H.forge.prng)J.seedFile(H.forge.prng.needed,function(N,K){O.postMessage({forge:{prng:{err:N,bytes:K}}})})};O.addEventListener("message",V)}},J}});var _J=q$((kF,V8)=>{var VJ=F$();_0();M8();O8();_$();(function(){if(VJ.random&&VJ.random.getBytes){V8.exports=VJ.random;return}(function($){var J={},X=[,,,,],Q=VJ.util.createBuffer();J.formatKey=function(q){var H=VJ.util.createBuffer(q);return q=[,,,,],q[0]=H.getInt32(),q[1]=H.getInt32(),q[2]=H.getInt32(),q[3]=H.getInt32(),VJ.aes._expandKey(q,!1)},J.formatSeed=function(q){var H=VJ.util.createBuffer(q);return q=[,,,,],q[0]=H.getInt32(),q[1]=H.getInt32(),q[2]=H.getInt32(),q[3]=H.getInt32(),q},J.cipher=function(q,H){return VJ.aes._updateBlock(q,H,X,!1),Q.putInt32(X[0]),Q.putInt32(X[1]),Q.putInt32(X[2]),Q.putInt32(X[3]),Q.getBytes()},J.increment=function(q){return++q[3],q},J.md=VJ.md.sha256;function Y(){var q=VJ.prng.create(J);return q.getBytes=function(H,N){return q.generate(H,N)},q.getBytesSync=function(H){return q.generate(H)},q}var G=Y(),W=null,U=VJ.util.globalScope,M=U.crypto||U.msCrypto;if(M&&M.getRandomValues)W=function(q){return M.getRandomValues(q)};if(VJ.options.usePureJavaScript||!VJ.util.isNodejs&&!W){if(typeof window>"u"||window.document===void 0);if(G.collectInt(+new Date,32),typeof navigator<"u"){var O="";for(var V in navigator)try{if(typeof navigator[V]=="string")O+=navigator[V]}catch(q){}G.collect(O),O=null}if($)$().mousemove(function(q){G.collectInt(q.clientX,16),G.collectInt(q.clientY,16)}),$().keypress(function(q){G.collectInt(q.charCode,8)})}if(!VJ.random)VJ.random=G;else for(var V in G)VJ.random[V]=G[V];VJ.random.createInstance=Y,V8.exports=VJ.random})(typeof jQuery<"u"?jQuery:null)})()});var H8=q$((fF,O1)=>{var ZJ=F$();_$();var q8=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],U1=[1,2,3,5],PM=function($,J){return $<<J&65535|($&65535)>>16-J},_M=function($,J){return($&65535)>>J|$<<16-J&65535};O1.exports=ZJ.rc2=ZJ.rc2||{};ZJ.rc2.expandKey=function($,J){if(typeof $==="string")$=ZJ.util.createBuffer($);J=J||128;var X=$,Q=$.length(),Y=J,G=Math.ceil(Y/8),W=255>>(Y&7),U;for(U=Q;U<128;U++)X.putByte(q8[X.at(U-1)+X.at(U-Q)&255]);X.setAt(128-G,q8[X.at(128-G)&W]);for(U=127-G;U>=0;U--)X.setAt(U,q8[X.at(U+1)^X.at(U+G)]);return X};var M1=function($,J,X){var Q=!1,Y=null,G=null,W=null,U,M,O,V,q=[];$=ZJ.rc2.expandKey($,J);for(O=0;O<64;O++)q.push($.getInt16Le());if(X)U=function(K){for(O=0;O<4;O++)K[O]+=q[V]+(K[(O+3)%4]&K[(O+2)%4])+(~K[(O+3)%4]&K[(O+1)%4]),K[O]=PM(K[O],U1[O]),V++},M=function(K){for(O=0;O<4;O++)K[O]+=q[K[(O+3)%4]&63]};else U=function(K){for(O=3;O>=0;O--)K[O]=_M(K[O],U1[O]),K[O]-=q[V]+(K[(O+3)%4]&K[(O+2)%4])+(~K[(O+3)%4]&K[(O+1)%4]),V--},M=function(K){for(O=3;O>=0;O--)K[O]-=q[K[(O+3)%4]&63]};var H=function(K){var L=[];for(O=0;O<4;O++){var A=Y.getInt16Le();if(W!==null)if(X)A^=W.getInt16Le();else W.putInt16Le(A);L.push(A&65535)}V=X?0:63;for(var D=0;D<K.length;D++)for(var S=0;S<K[D][0];S++)K[D][1](L);for(O=0;O<4;O++){if(W!==null)if(X)W.putInt16Le(L[O]);else L[O]^=W.getInt16Le();G.putInt16Le(L[O])}},N=null;return N={start:function(K,L){if(K){if(typeof K==="string")K=ZJ.util.createBuffer(K)}Q=!1,Y=ZJ.util.createBuffer(),G=L||new ZJ.util.createBuffer,W=K,N.output=G},update:function(K){if(!Q)Y.putBuffer(K);while(Y.length()>=8)H([[5,U],[1,M],[6,U],[1,M],[5,U]])},finish:function(K){var L=!0;if(X)if(K)L=K(8,Y,!X);else{var A=Y.length()===8?8:8-Y.length();Y.fillWithByte(A,A)}if(L)Q=!0,N.update();if(!X){if(L=Y.length()===0,L)if(K)L=K(8,G,!X);else{var D=G.length(),S=G.at(D-1);if(S>D)L=!1;else G.truncate(S)}}return L}},N};ZJ.rc2.startEncrypting=function($,J,X){var Q=ZJ.rc2.createEncryptionCipher($,128);return Q.start(J,X),Q};ZJ.rc2.createEncryptionCipher=function($,J){return M1($,J,!0)};ZJ.rc2.startDecrypting=function($,J,X){var Q=ZJ.rc2.createDecryptionCipher($,128);return Q.start(J,X),Q};ZJ.rc2.createDecryptionCipher=function($,J){return M1($,J,!1)}});var CX=q$((yF,N1)=>{var K8=F$();N1.exports=K8.jsbn=K8.jsbn||{};var R0,xM=244837814094590,V1=(xM&16777215)==15715070;function k($,J,X){if(this.data=[],$!=null)if(typeof $=="number")this.fromNumber($,J,X);else if(J==null&&typeof $!="string")this.fromString($,256);else this.fromString($,J)}K8.jsbn.BigInteger=k;function w$(){return new k(null)}function vM($,J,X,Q,Y,G){while(--G>=0){var W=J*this.data[$++]+X.data[Q]+Y;Y=Math.floor(W/67108864),X.data[Q++]=W&67108863}return Y}function kM($,J,X,Q,Y,G){var W=J&32767,U=J>>15;while(--G>=0){var M=this.data[$]&32767,O=this.data[$++]>>15,V=U*M+O*W;M=W*M+((V&32767)<<15)+X.data[Q]+(Y&1073741823),Y=(M>>>30)+(V>>>15)+U*O+(Y>>>30),X.data[Q++]=M&1073741823}return Y}function q1($,J,X,Q,Y,G){var W=J&16383,U=J>>14;while(--G>=0){var M=this.data[$]&16383,O=this.data[$++]>>14,V=U*M+O*W;M=W*M+((V&16383)<<14)+X.data[Q]+Y,Y=(M>>28)+(V>>14)+U*O,X.data[Q++]=M&268435455}return Y}if(typeof navigator>"u")k.prototype.am=q1,R0=28;else if(V1&&navigator.appName=="Microsoft Internet Explorer")k.prototype.am=kM,R0=30;else if(V1&&navigator.appName!="Netscape")k.prototype.am=vM,R0=26;else k.prototype.am=q1,R0=28;k.prototype.DB=R0;k.prototype.DM=(1<<R0)-1;k.prototype.DV=1<<R0;var z8=52;k.prototype.FV=Math.pow(2,z8);k.prototype.F1=z8-R0;k.prototype.F2=2*R0-z8;var fM="0123456789abcdefghijklmnopqrstuvwxyz",fY=[],wQ,xJ;wQ=48;for(xJ=0;xJ<=9;++xJ)fY[wQ++]=xJ;wQ=97;for(xJ=10;xJ<36;++xJ)fY[wQ++]=xJ;wQ=65;for(xJ=10;xJ<36;++xJ)fY[wQ++]=xJ;function H1($){return fM.charAt($)}function K1($,J){var X=fY[$.charCodeAt(J)];return X==null?-1:X}function yM($){for(var J=this.t-1;J>=0;--J)$.data[J]=this.data[J];$.t=this.t,$.s=this.s}function bM($){if(this.t=1,this.s=$<0?-1:0,$>0)this.data[0]=$;else if($<-1)this.data[0]=$+this.DV;else this.t=0}function v0($){var J=w$();return J.fromInt($),J}function hM($,J){var X;if(J==16)X=4;else if(J==8)X=3;else if(J==256)X=8;else if(J==2)X=1;else if(J==32)X=5;else if(J==4)X=2;else{this.fromRadix($,J);return}this.t=0,this.s=0;var Q=$.length,Y=!1,G=0;while(--Q>=0){var W=X==8?$[Q]&255:K1($,Q);if(W<0){if($.charAt(Q)=="-")Y=!0;continue}if(Y=!1,G==0)this.data[this.t++]=W;else if(G+X>this.DB)this.data[this.t-1]|=(W&(1<<this.DB-G)-1)<<G,this.data[this.t++]=W>>this.DB-G;else this.data[this.t-1]|=W<<G;if(G+=X,G>=this.DB)G-=this.DB}if(X==8&&($[0]&128)!=0){if(this.s=-1,G>0)this.data[this.t-1]|=(1<<this.DB-G)-1<<G}if(this.clamp(),Y)k.ZERO.subTo(this,this)}function uM(){var $=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==$)--this.t}function gM($){if(this.s<0)return"-"+this.negate().toString($);var J;if($==16)J=4;else if($==8)J=3;else if($==2)J=1;else if($==32)J=5;else if($==4)J=2;else return this.toRadix($);var X=(1<<J)-1,Q,Y=!1,G="",W=this.t,U=this.DB-W*this.DB%J;if(W-- >0){if(U<this.DB&&(Q=this.data[W]>>U)>0)Y=!0,G=H1(Q);while(W>=0){if(U<J)Q=(this.data[W]&(1<<U)-1)<<J-U,Q|=this.data[--W]>>(U+=this.DB-J);else if(Q=this.data[W]>>(U-=J)&X,U<=0)U+=this.DB,--W;if(Q>0)Y=!0;if(Y)G+=H1(Q)}}return Y?G:"0"}function mM(){var $=w$();return k.ZERO.subTo(this,$),$}function lM(){return this.s<0?this.negate():this}function pM($){var J=this.s-$.s;if(J!=0)return J;var X=this.t;if(J=X-$.t,J!=0)return this.s<0?-J:J;while(--X>=0)if((J=this.data[X]-$.data[X])!=0)return J;return 0}function yY($){var J=1,X;if((X=$>>>16)!=0)$=X,J+=16;if((X=$>>8)!=0)$=X,J+=8;if((X=$>>4)!=0)$=X,J+=4;if((X=$>>2)!=0)$=X,J+=2;if((X=$>>1)!=0)$=X,J+=1;return J}function dM(){if(this.t<=0)return 0;return this.DB*(this.t-1)+yY(this.data[this.t-1]^this.s&this.DM)}function cM($,J){var X;for(X=this.t-1;X>=0;--X)J.data[X+$]=this.data[X];for(X=$-1;X>=0;--X)J.data[X]=0;J.t=this.t+$,J.s=this.s}function nM($,J){for(var X=$;X<this.t;++X)J.data[X-$]=this.data[X];J.t=Math.max(this.t-$,0),J.s=this.s}function iM($,J){var X=$%this.DB,Q=this.DB-X,Y=(1<<Q)-1,G=Math.floor($/this.DB),W=this.s<<X&this.DM,U;for(U=this.t-1;U>=0;--U)J.data[U+G+1]=this.data[U]>>Q|W,W=(this.data[U]&Y)<<X;for(U=G-1;U>=0;--U)J.data[U]=0;J.data[G]=W,J.t=this.t+G+1,J.s=this.s,J.clamp()}function oM($,J){J.s=this.s;var X=Math.floor($/this.DB);if(X>=this.t){J.t=0;return}var Q=$%this.DB,Y=this.DB-Q,G=(1<<Q)-1;J.data[0]=this.data[X]>>Q;for(var W=X+1;W<this.t;++W)J.data[W-X-1]|=(this.data[W]&G)<<Y,J.data[W-X]=this.data[W]>>Q;if(Q>0)J.data[this.t-X-1]|=(this.s&G)<<Y;J.t=this.t-X,J.clamp()}function aM($,J){var X=0,Q=0,Y=Math.min($.t,this.t);while(X<Y)Q+=this.data[X]-$.data[X],J.data[X++]=Q&this.DM,Q>>=this.DB;if($.t<this.t){Q-=$.s;while(X<this.t)Q+=this.data[X],J.data[X++]=Q&this.DM,Q>>=this.DB;Q+=this.s}else{Q+=this.s;while(X<$.t)Q-=$.data[X],J.data[X++]=Q&this.DM,Q>>=this.DB;Q-=$.s}if(J.s=Q<0?-1:0,Q<-1)J.data[X++]=this.DV+Q;else if(Q>0)J.data[X++]=Q;J.t=X,J.clamp()}function sM($,J){var X=this.abs(),Q=$.abs(),Y=X.t;J.t=Y+Q.t;while(--Y>=0)J.data[Y]=0;for(Y=0;Y<Q.t;++Y)J.data[Y+X.t]=X.am(0,Q.data[Y],J,Y,0,X.t);if(J.s=0,J.clamp(),this.s!=$.s)k.ZERO.subTo(J,J)}function rM($){var J=this.abs(),X=$.t=2*J.t;while(--X>=0)$.data[X]=0;for(X=0;X<J.t-1;++X){var Q=J.am(X,J.data[X],$,2*X,0,1);if(($.data[X+J.t]+=J.am(X+1,2*J.data[X],$,2*X+1,Q,J.t-X-1))>=J.DV)$.data[X+J.t]-=J.DV,$.data[X+J.t+1]=1}if($.t>0)$.data[$.t-1]+=J.am(X,J.data[X],$,2*X,0,1);$.s=0,$.clamp()}function tM($,J,X){var Q=$.abs();if(Q.t<=0)return;var Y=this.abs();if(Y.t<Q.t){if(J!=null)J.fromInt(0);if(X!=null)this.copyTo(X);return}if(X==null)X=w$();var G=w$(),W=this.s,U=$.s,M=this.DB-yY(Q.data[Q.t-1]);if(M>0)Q.lShiftTo(M,G),Y.lShiftTo(M,X);else Q.copyTo(G),Y.copyTo(X);var O=G.t,V=G.data[O-1];if(V==0)return;var q=V*(1<<this.F1)+(O>1?G.data[O-2]>>this.F2:0),H=this.FV/q,N=(1<<this.F1)/q,K=1<<this.F2,L=X.t,A=L-O,D=J==null?w$():J;if(G.dlShiftTo(A,D),X.compareTo(D)>=0)X.data[X.t++]=1,X.subTo(D,X);k.ONE.dlShiftTo(O,D),D.subTo(G,G);while(G.t<O)G.data[G.t++]=0;while(--A>=0){var S=X.data[--L]==V?this.DM:Math.floor(X.data[L]*H+(X.data[L-1]+K)*N);if((X.data[L]+=G.am(0,S,X,A,0,O))<S){G.dlShiftTo(A,D),X.subTo(D,X);while(X.data[L]<--S)X.subTo(D,X)}}if(J!=null){if(X.drShiftTo(O,J),W!=U)k.ZERO.subTo(J,J)}if(X.t=O,X.clamp(),M>0)X.rShiftTo(M,X);if(W<0)k.ZERO.subTo(X,X)}function eM($){var J=w$();if(this.abs().divRemTo($,null,J),this.s<0&&J.compareTo(k.ZERO)>0)$.subTo(J,J);return J}function GQ($){this.m=$}function $O($){if($.s<0||$.compareTo(this.m)>=0)return $.mod(this.m);else return $}function JO($){return $}function QO($){$.divRemTo(this.m,null,$)}function XO($,J,X){$.multiplyTo(J,X),this.reduce(X)}function YO($,J){$.squareTo(J),this.reduce(J)}GQ.prototype.convert=$O;GQ.prototype.revert=JO;GQ.prototype.reduce=QO;GQ.prototype.mulTo=XO;GQ.prototype.sqrTo=YO;function GO(){if(this.t<1)return 0;var $=this.data[0];if(($&1)==0)return 0;var J=$&3;return J=J*(2-($&15)*J)&15,J=J*(2-($&255)*J)&255,J=J*(2-(($&65535)*J&65535))&65535,J=J*(2-$*J%this.DV)%this.DV,J>0?this.DV-J:-J}function WQ($){this.m=$,this.mp=$.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<$.DB-15)-1,this.mt2=2*$.t}function WO($){var J=w$();if($.abs().dlShiftTo(this.m.t,J),J.divRemTo(this.m,null,J),$.s<0&&J.compareTo(k.ZERO)>0)this.m.subTo(J,J);return J}function UO($){var J=w$();return $.copyTo(J),this.reduce(J),J}function MO($){while($.t<=this.mt2)$.data[$.t++]=0;for(var J=0;J<this.m.t;++J){var X=$.data[J]&32767,Q=X*this.mpl+((X*this.mph+($.data[J]>>15)*this.mpl&this.um)<<15)&$.DM;X=J+this.m.t,$.data[X]+=this.m.am(0,Q,$,J,0,this.m.t);while($.data[X]>=$.DV)$.data[X]-=$.DV,$.data[++X]++}if($.clamp(),$.drShiftTo(this.m.t,$),$.compareTo(this.m)>=0)$.subTo(this.m,$)}function OO($,J){$.squareTo(J),this.reduce(J)}function VO($,J,X){$.multiplyTo(J,X),this.reduce(X)}WQ.prototype.convert=WO;WQ.prototype.revert=UO;WQ.prototype.reduce=MO;WQ.prototype.mulTo=VO;WQ.prototype.sqrTo=OO;function qO(){return(this.t>0?this.data[0]&1:this.s)==0}function HO($,J){if($>4294967295||$<1)return k.ONE;var X=w$(),Q=w$(),Y=J.convert(this),G=yY($)-1;Y.copyTo(X);while(--G>=0)if(J.sqrTo(X,Q),($&1<<G)>0)J.mulTo(Q,Y,X);else{var W=X;X=Q,Q=W}return J.revert(X)}function KO($,J){var X;if($<256||J.isEven())X=new GQ(J);else X=new WQ(J);return this.exp($,X)}k.prototype.copyTo=yM;k.prototype.fromInt=bM;k.prototype.fromString=hM;k.prototype.clamp=uM;k.prototype.dlShiftTo=cM;k.prototype.drShiftTo=nM;k.prototype.lShiftTo=iM;k.prototype.rShiftTo=oM;k.prototype.subTo=aM;k.prototype.multiplyTo=sM;k.prototype.squareTo=rM;k.prototype.divRemTo=tM;k.prototype.invDigit=GO;k.prototype.isEven=qO;k.prototype.exp=HO;k.prototype.toString=gM;k.prototype.negate=mM;k.prototype.abs=lM;k.prototype.compareTo=pM;k.prototype.bitLength=dM;k.prototype.mod=eM;k.prototype.modPowInt=KO;k.ZERO=v0(0);k.ONE=v0(1);function zO(){var $=w$();return this.copyTo($),$}function EO(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this.data[0];else if(this.t==0)return 0;return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function FO(){return this.t==0?this.s:this.data[0]<<24>>24}function NO(){return this.t==0?this.s:this.data[0]<<16>>16}function LO($){return Math.floor(Math.LN2*this.DB/Math.log($))}function AO(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function RO($){if($==null)$=10;if(this.signum()==0||$<2||$>36)return"0";var J=this.chunkSize($),X=Math.pow($,J),Q=v0(X),Y=w$(),G=w$(),W="";this.divRemTo(Q,Y,G);while(Y.signum()>0)W=(X+G.intValue()).toString($).substr(1)+W,Y.divRemTo(Q,Y,G);return G.intValue().toString($)+W}function DO($,J){if(this.fromInt(0),J==null)J=10;var X=this.chunkSize(J),Q=Math.pow(J,X),Y=!1,G=0,W=0;for(var U=0;U<$.length;++U){var M=K1($,U);if(M<0){if($.charAt(U)=="-"&&this.signum()==0)Y=!0;continue}if(W=J*W+M,++G>=X)this.dMultiply(Q),this.dAddOffset(W,0),G=0,W=0}if(G>0)this.dMultiply(Math.pow(J,G)),this.dAddOffset(W,0);if(Y)k.ZERO.subTo(this,this)}function ZO($,J,X){if(typeof J=="number")if($<2)this.fromInt(1);else{if(this.fromNumber($,X),!this.testBit($-1))this.bitwiseTo(k.ONE.shiftLeft($-1),E8,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(J))if(this.dAddOffset(2,0),this.bitLength()>$)this.subTo(k.ONE.shiftLeft($-1),this)}else{var Q=[],Y=$&7;if(Q.length=($>>3)+1,J.nextBytes(Q),Y>0)Q[0]&=(1<<Y)-1;else Q[0]=0;this.fromString(Q,256)}}function BO(){var $=this.t,J=[];J[0]=this.s;var X=this.DB-$*this.DB%8,Q,Y=0;if($-- >0){if(X<this.DB&&(Q=this.data[$]>>X)!=(this.s&this.DM)>>X)J[Y++]=Q|this.s<<this.DB-X;while($>=0){if(X<8)Q=(this.data[$]&(1<<X)-1)<<8-X,Q|=this.data[--$]>>(X+=this.DB-8);else if(Q=this.data[$]>>(X-=8)&255,X<=0)X+=this.DB,--$;if((Q&128)!=0)Q|=-256;if(Y==0&&(this.s&128)!=(Q&128))++Y;if(Y>0||Q!=this.s)J[Y++]=Q}}return J}function jO($){return this.compareTo($)==0}function TO($){return this.compareTo($)<0?this:$}function SO($){return this.compareTo($)>0?this:$}function IO($,J,X){var Q,Y,G=Math.min($.t,this.t);for(Q=0;Q<G;++Q)X.data[Q]=J(this.data[Q],$.data[Q]);if($.t<this.t){Y=$.s&this.DM;for(Q=G;Q<this.t;++Q)X.data[Q]=J(this.data[Q],Y);X.t=this.t}else{Y=this.s&this.DM;for(Q=G;Q<$.t;++Q)X.data[Q]=J(Y,$.data[Q]);X.t=$.t}X.s=J(this.s,$.s),X.clamp()}function CO($,J){return $&J}function wO($){var J=w$();return this.bitwiseTo($,CO,J),J}function E8($,J){return $|J}function PO($){var J=w$();return this.bitwiseTo($,E8,J),J}function z1($,J){return $^J}function _O($){var J=w$();return this.bitwiseTo($,z1,J),J}function E1($,J){return $&~J}function xO($){var J=w$();return this.bitwiseTo($,E1,J),J}function vO(){var $=w$();for(var J=0;J<this.t;++J)$.data[J]=this.DM&~this.data[J];return $.t=this.t,$.s=~this.s,$}function kO($){var J=w$();if($<0)this.rShiftTo(-$,J);else this.lShiftTo($,J);return J}function fO($){var J=w$();if($<0)this.lShiftTo(-$,J);else this.rShiftTo($,J);return J}function yO($){if($==0)return-1;var J=0;if(($&65535)==0)$>>=16,J+=16;if(($&255)==0)$>>=8,J+=8;if(($&15)==0)$>>=4,J+=4;if(($&3)==0)$>>=2,J+=2;if(($&1)==0)++J;return J}function bO(){for(var $=0;$<this.t;++$)if(this.data[$]!=0)return $*this.DB+yO(this.data[$]);if(this.s<0)return this.t*this.DB;return-1}function hO($){var J=0;while($!=0)$&=$-1,++J;return J}function uO(){var $=0,J=this.s&this.DM;for(var X=0;X<this.t;++X)$+=hO(this.data[X]^J);return $}function gO($){var J=Math.floor($/this.DB);if(J>=this.t)return this.s!=0;return(this.data[J]&1<<$%this.DB)!=0}function mO($,J){var X=k.ONE.shiftLeft($);return this.bitwiseTo(X,J,X),X}function lO($){return this.changeBit($,E8)}function pO($){return this.changeBit($,E1)}function dO($){return this.changeBit($,z1)}function cO($,J){var X=0,Q=0,Y=Math.min($.t,this.t);while(X<Y)Q+=this.data[X]+$.data[X],J.data[X++]=Q&this.DM,Q>>=this.DB;if($.t<this.t){Q+=$.s;while(X<this.t)Q+=this.data[X],J.data[X++]=Q&this.DM,Q>>=this.DB;Q+=this.s}else{Q+=this.s;while(X<$.t)Q+=$.data[X],J.data[X++]=Q&this.DM,Q>>=this.DB;Q+=$.s}if(J.s=Q<0?-1:0,Q>0)J.data[X++]=Q;else if(Q<-1)J.data[X++]=this.DV+Q;J.t=X,J.clamp()}function nO($){var J=w$();return this.addTo($,J),J}function iO($){var J=w$();return this.subTo($,J),J}function oO($){var J=w$();return this.multiplyTo($,J),J}function aO(){var $=w$();return this.squareTo($),$}function sO($){var J=w$();return this.divRemTo($,J,null),J}function rO($){var J=w$();return this.divRemTo($,null,J),J}function tO($){var J=w$(),X=w$();return this.divRemTo($,J,X),[J,X]}function eO($){this.data[this.t]=this.am(0,$-1,this,0,0,this.t),++this.t,this.clamp()}function $V($,J){if($==0)return;while(this.t<=J)this.data[this.t++]=0;this.data[J]+=$;while(this.data[J]>=this.DV){if(this.data[J]-=this.DV,++J>=this.t)this.data[this.t++]=0;++this.data[J]}}function IX(){}function F1($){return $}function JV($,J,X){$.multiplyTo(J,X)}function QV($,J){$.squareTo(J)}IX.prototype.convert=F1;IX.prototype.revert=F1;IX.prototype.mulTo=JV;IX.prototype.sqrTo=QV;function XV($){return this.exp($,new IX)}function YV($,J,X){var Q=Math.min(this.t+$.t,J);X.s=0,X.t=Q;while(Q>0)X.data[--Q]=0;var Y;for(Y=X.t-this.t;Q<Y;++Q)X.data[Q+this.t]=this.am(0,$.data[Q],X,Q,0,this.t);for(Y=Math.min($.t,J);Q<Y;++Q)this.am(0,$.data[Q],X,Q,0,J-Q);X.clamp()}function GV($,J,X){--J;var Q=X.t=this.t+$.t-J;X.s=0;while(--Q>=0)X.data[Q]=0;for(Q=Math.max(J-this.t,0);Q<$.t;++Q)X.data[this.t+Q-J]=this.am(J-Q,$.data[Q],X,0,0,this.t+Q-J);X.clamp(),X.drShiftTo(1,X)}function PQ($){this.r2=w$(),this.q3=w$(),k.ONE.dlShiftTo(2*$.t,this.r2),this.mu=this.r2.divide($),this.m=$}function WV($){if($.s<0||$.t>2*this.m.t)return $.mod(this.m);else if($.compareTo(this.m)<0)return $;else{var J=w$();return $.copyTo(J),this.reduce(J),J}}function UV($){return $}function MV($){if($.drShiftTo(this.m.t-1,this.r2),$.t>this.m.t+1)$.t=this.m.t+1,$.clamp();this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while($.compareTo(this.r2)<0)$.dAddOffset(1,this.m.t+1);$.subTo(this.r2,$);while($.compareTo(this.m)>=0)$.subTo(this.m,$)}function OV($,J){$.squareTo(J),this.reduce(J)}function VV($,J,X){$.multiplyTo(J,X),this.reduce(X)}PQ.prototype.convert=WV;PQ.prototype.revert=UV;PQ.prototype.reduce=MV;PQ.prototype.mulTo=VV;PQ.prototype.sqrTo=OV;function qV($,J){var X=$.bitLength(),Q,Y=v0(1),G;if(X<=0)return Y;else if(X<18)Q=1;else if(X<48)Q=3;else if(X<144)Q=4;else if(X<768)Q=5;else Q=6;if(X<8)G=new GQ(J);else if(J.isEven())G=new PQ(J);else G=new WQ(J);var W=[],U=3,M=Q-1,O=(1<<Q)-1;if(W[1]=G.convert(this),Q>1){var V=w$();G.sqrTo(W[1],V);while(U<=O)W[U]=w$(),G.mulTo(V,W[U-2],W[U]),U+=2}var q=$.t-1,H,N=!0,K=w$(),L;X=yY($.data[q])-1;while(q>=0){if(X>=M)H=$.data[q]>>X-M&O;else if(H=($.data[q]&(1<<X+1)-1)<<M-X,q>0)H|=$.data[q-1]>>this.DB+X-M;U=Q;while((H&1)==0)H>>=1,--U;if((X-=U)<0)X+=this.DB,--q;if(N)W[H].copyTo(Y),N=!1;else{while(U>1)G.sqrTo(Y,K),G.sqrTo(K,Y),U-=2;if(U>0)G.sqrTo(Y,K);else L=Y,Y=K,K=L;G.mulTo(K,W[H],Y)}while(q>=0&&($.data[q]&1<<X)==0)if(G.sqrTo(Y,K),L=Y,Y=K,K=L,--X<0)X=this.DB-1,--q}return G.revert(Y)}function HV($){var J=this.s<0?this.negate():this.clone(),X=$.s<0?$.negate():$.clone();if(J.compareTo(X)<0){var Q=J;J=X,X=Q}var Y=J.getLowestSetBit(),G=X.getLowestSetBit();if(G<0)return J;if(Y<G)G=Y;if(G>0)J.rShiftTo(G,J),X.rShiftTo(G,X);while(J.signum()>0){if((Y=J.getLowestSetBit())>0)J.rShiftTo(Y,J);if((Y=X.getLowestSetBit())>0)X.rShiftTo(Y,X);if(J.compareTo(X)>=0)J.subTo(X,J),J.rShiftTo(1,J);else X.subTo(J,X),X.rShiftTo(1,X)}if(G>0)X.lShiftTo(G,X);return X}function KV($){if($<=0)return 0;var J=this.DV%$,X=this.s<0?$-1:0;if(this.t>0)if(J==0)X=this.data[0]%$;else for(var Q=this.t-1;Q>=0;--Q)X=(J*X+this.data[Q])%$;return X}function zV($){if(this.signum()==0)return k.ZERO;var J=$.isEven();if(this.isEven()&&J||$.signum()==0)return k.ZERO;var X=$.clone(),Q=this.clone(),Y=v0(1),G=v0(0),W=v0(0),U=v0(1);while(X.signum()!=0){while(X.isEven()){if(X.rShiftTo(1,X),J){if(!Y.isEven()||!G.isEven())Y.addTo(this,Y),G.subTo($,G);Y.rShiftTo(1,Y)}else if(!G.isEven())G.subTo($,G);G.rShiftTo(1,G)}while(Q.isEven()){if(Q.rShiftTo(1,Q),J){if(!W.isEven()||!U.isEven())W.addTo(this,W),U.subTo($,U);W.rShiftTo(1,W)}else if(!U.isEven())U.subTo($,U);U.rShiftTo(1,U)}if(X.compareTo(Q)>=0){if(X.subTo(Q,X),J)Y.subTo(W,Y);G.subTo(U,G)}else{if(Q.subTo(X,Q),J)W.subTo(Y,W);U.subTo(G,U)}}if(Q.compareTo(k.ONE)!=0)return k.ZERO;if(U.compareTo($)>=0)return U.subtract($);if(U.signum()<0)U.addTo($,U);else return U;if(U.signum()<0)return U.add($);else return U}var pJ=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],EV=67108864/pJ[pJ.length-1];function FV($){var J,X=this.abs();if(X.t==1&&X.data[0]<=pJ[pJ.length-1]){for(J=0;J<pJ.length;++J)if(X.data[0]==pJ[J])return!0;return!1}if(X.isEven())return!1;J=1;while(J<pJ.length){var Q=pJ[J],Y=J+1;while(Y<pJ.length&&Q<EV)Q*=pJ[Y++];Q=X.modInt(Q);while(J<Y)if(Q%pJ[J++]==0)return!1}return X.millerRabin($)}function NV($){var J=this.subtract(k.ONE),X=J.getLowestSetBit();if(X<=0)return!1;var Q=J.shiftRight(X),Y=LV(),G;for(var W=0;W<$;++W){do G=new k(this.bitLength(),Y);while(G.compareTo(k.ONE)<=0||G.compareTo(J)>=0);var U=G.modPow(Q,this);if(U.compareTo(k.ONE)!=0&&U.compareTo(J)!=0){var M=1;while(M++<X&&U.compareTo(J)!=0)if(U=U.modPowInt(2,this),U.compareTo(k.ONE)==0)return!1;if(U.compareTo(J)!=0)return!1}}return!0}function LV(){return{nextBytes:function($){for(var J=0;J<$.length;++J)$[J]=Math.floor(Math.random()*256)}}}k.prototype.chunkSize=LO;k.prototype.toRadix=RO;k.prototype.fromRadix=DO;k.prototype.fromNumber=ZO;k.prototype.bitwiseTo=IO;k.prototype.changeBit=mO;k.prototype.addTo=cO;k.prototype.dMultiply=eO;k.prototype.dAddOffset=$V;k.prototype.multiplyLowerTo=YV;k.prototype.multiplyUpperTo=GV;k.prototype.modInt=KV;k.prototype.millerRabin=NV;k.prototype.clone=zO;k.prototype.intValue=EO;k.prototype.byteValue=FO;k.prototype.shortValue=NO;k.prototype.signum=AO;k.prototype.toByteArray=BO;k.prototype.equals=jO;k.prototype.min=TO;k.prototype.max=SO;k.prototype.and=wO;k.prototype.or=PO;k.prototype.xor=_O;k.prototype.andNot=xO;k.prototype.not=vO;k.prototype.shiftLeft=kO;k.prototype.shiftRight=fO;k.prototype.getLowestSetBit=bO;k.prototype.bitCount=uO;k.prototype.testBit=gO;k.prototype.setBit=lO;k.prototype.clearBit=pO;k.prototype.flipBit=dO;k.prototype.add=nO;k.prototype.subtract=iO;k.prototype.multiply=oO;k.prototype.divide=sO;k.prototype.remainder=rO;k.prototype.divideAndRemainder=tO;k.prototype.modPow=qV;k.prototype.modInverse=zV;k.prototype.pow=XV;k.prototype.gcd=HV;k.prototype.isProbablePrime=FV;k.prototype.square=aO});var _Q=q$((bF,D1)=>{var W0=F$();J0();_$();var A1=D1.exports=W0.sha1=W0.sha1||{};W0.md.sha1=W0.md.algorithms.sha1=A1;A1.create=function(){if(!R1)AV();var $=null,J=W0.util.createBuffer(),X=Array(80),Q={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return Q.start=function(){Q.messageLength=0,Q.fullMessageLength=Q.messageLength64=[];var Y=Q.messageLengthSize/4;for(var G=0;G<Y;++G)Q.fullMessageLength.push(0);return J=W0.util.createBuffer(),$={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},Q},Q.start(),Q.update=function(Y,G){if(G==="utf8")Y=W0.util.encodeUtf8(Y);var W=Y.length;Q.messageLength+=W,W=[W/4294967296>>>0,W>>>0];for(var U=Q.fullMessageLength.length-1;U>=0;--U)Q.fullMessageLength[U]+=W[1],W[1]=W[0]+(Q.fullMessageLength[U]/4294967296>>>0),Q.fullMessageLength[U]=Q.fullMessageLength[U]>>>0,W[0]=W[1]/4294967296>>>0;if(J.putBytes(Y),L1($,X,J),J.read>2048||J.length()===0)J.compact();return Q},Q.digest=function(){var Y=W0.util.createBuffer();Y.putBytes(J.bytes());var G=Q.fullMessageLength[Q.fullMessageLength.length-1]+Q.messageLengthSize,W=G&Q.blockLength-1;Y.putBytes(F8.substr(0,Q.blockLength-W));var U,M,O=Q.fullMessageLength[0]*8;for(var V=0;V<Q.fullMessageLength.length-1;++V)U=Q.fullMessageLength[V+1]*8,M=U/4294967296>>>0,O+=M,Y.putInt32(O>>>0),O=U>>>0;Y.putInt32(O);var q={h0:$.h0,h1:$.h1,h2:$.h2,h3:$.h3,h4:$.h4};L1(q,X,Y);var H=W0.util.createBuffer();return H.putInt32(q.h0),H.putInt32(q.h1),H.putInt32(q.h2),H.putInt32(q.h3),H.putInt32(q.h4),H},Q};var F8=null,R1=!1;function AV(){F8=String.fromCharCode(128),F8+=W0.util.fillString(String.fromCharCode(0),64),R1=!0}function L1($,J,X){var Q,Y,G,W,U,M,O,V,q=X.length();while(q>=64){Y=$.h0,G=$.h1,W=$.h2,U=$.h3,M=$.h4;for(V=0;V<16;++V)Q=X.getInt32(),J[V]=Q,O=U^G&(W^U),Q=(Y<<5|Y>>>27)+O+M+1518500249+Q,M=U,U=W,W=(G<<30|G>>>2)>>>0,G=Y,Y=Q;for(;V<20;++V)Q=J[V-3]^J[V-8]^J[V-14]^J[V-16],Q=Q<<1|Q>>>31,J[V]=Q,O=U^G&(W^U),Q=(Y<<5|Y>>>27)+O+M+1518500249+Q,M=U,U=W,W=(G<<30|G>>>2)>>>0,G=Y,Y=Q;for(;V<32;++V)Q=J[V-3]^J[V-8]^J[V-14]^J[V-16],Q=Q<<1|Q>>>31,J[V]=Q,O=G^W^U,Q=(Y<<5|Y>>>27)+O+M+1859775393+Q,M=U,U=W,W=(G<<30|G>>>2)>>>0,G=Y,Y=Q;for(;V<40;++V)Q=J[V-6]^J[V-16]^J[V-28]^J[V-32],Q=Q<<2|Q>>>30,J[V]=Q,O=G^W^U,Q=(Y<<5|Y>>>27)+O+M+1859775393+Q,M=U,U=W,W=(G<<30|G>>>2)>>>0,G=Y,Y=Q;for(;V<60;++V)Q=J[V-6]^J[V-16]^J[V-28]^J[V-32],Q=Q<<2|Q>>>30,J[V]=Q,O=G&W|U&(G^W),Q=(Y<<5|Y>>>27)+O+M+2400959708+Q,M=U,U=W,W=(G<<30|G>>>2)>>>0,G=Y,Y=Q;for(;V<80;++V)Q=J[V-6]^J[V-16]^J[V-28]^J[V-32],Q=Q<<2|Q>>>30,J[V]=Q,O=G^W^U,Q=(Y<<5|Y>>>27)+O+M+3395469782+Q,M=U,U=W,W=(G<<30|G>>>2)>>>0,G=Y,Y=Q;$.h0=$.h0+Y|0,$.h1=$.h1+G|0,$.h2=$.h2+W|0,$.h3=$.h3+U|0,$.h4=$.h4+M|0,q-=64}}});var N8=q$((hF,B1)=>{var U0=F$();_$();_J();_Q();var Z1=B1.exports=U0.pkcs1=U0.pkcs1||{};Z1.encode_rsa_oaep=function($,J,X){var Q,Y,G,W;if(typeof X==="string")Q=X,Y=arguments[3]||void 0,G=arguments[4]||void 0;else if(X){if(Q=X.label||void 0,Y=X.seed||void 0,G=X.md||void 0,X.mgf1&&X.mgf1.md)W=X.mgf1.md}if(!G)G=U0.md.sha1.create();else G.start();if(!W)W=G;var U=Math.ceil($.n.bitLength()/8),M=U-2*G.digestLength-2;if(J.length>M){var O=Error("RSAES-OAEP input message length is too long.");throw O.length=J.length,O.maxLength=M,O}if(!Q)Q="";G.update(Q,"raw");var V=G.digest(),q="",H=M-J.length;for(var N=0;N<H;N++)q+="\x00";var K=V.getBytes()+q+"\x01"+J;if(!Y)Y=U0.random.getBytes(G.digestLength);else if(Y.length!==G.digestLength){var O=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw O.seedLength=Y.length,O.digestLength=G.digestLength,O}var L=bY(Y,U-G.digestLength-1,W),A=U0.util.xorBytes(K,L,K.length),D=bY(A,G.digestLength,W),S=U0.util.xorBytes(Y,D,Y.length);return"\x00"+S+A};Z1.decode_rsa_oaep=function($,J,X){var Q,Y,G;if(typeof X==="string")Q=X,Y=arguments[3]||void 0;else if(X){if(Q=X.label||void 0,Y=X.md||void 0,X.mgf1&&X.mgf1.md)G=X.mgf1.md}var W=Math.ceil($.n.bitLength()/8);if(J.length!==W){var A=Error("RSAES-OAEP encoded message length is invalid.");throw A.length=J.length,A.expectedLength=W,A}if(Y===void 0)Y=U0.md.sha1.create();else Y.start();if(!G)G=Y;if(W<2*Y.digestLength+2)throw Error("RSAES-OAEP key is too short for the hash function.");if(!Q)Q="";Y.update(Q,"raw");var U=Y.digest().getBytes(),M=J.charAt(0),O=J.substring(1,Y.digestLength+1),V=J.substring(1+Y.digestLength),q=bY(V,Y.digestLength,G),H=U0.util.xorBytes(O,q,O.length),N=bY(H,W-Y.digestLength-1,G),K=U0.util.xorBytes(V,N,V.length),L=K.substring(0,Y.digestLength),A=M!=="\x00";for(var D=0;D<Y.digestLength;++D)A|=U.charAt(D)!==L.charAt(D);var S=1,B=Y.digestLength;for(var C=Y.digestLength;C<K.length;C++){var w=K.charCodeAt(C),P=w&1^1,l=S?65534:0;A|=w&l,S=S&P,B+=S}if(A||K.charCodeAt(B)!==1)throw Error("Invalid RSAES-OAEP padding.");return K.substring(B+1)};function bY($,J,X){if(!X)X=U0.md.sha1.create();var Q="",Y=Math.ceil(J/X.digestLength);for(var G=0;G<Y;++G){var W=String.fromCharCode(G>>24&255,G>>16&255,G>>8&255,G&255);X.start(),X.update($+W),Q+=X.digest().getBytes()}return Q.substring(0,J)}});var A8=q$((uF,L8)=>{var k0=F$();_$();CX();_J();(function(){if(k0.prime){L8.exports=k0.prime;return}var $=L8.exports=k0.prime=k0.prime||{},J=k0.jsbn.BigInteger,X=[6,4,2,4,2,4,6,2],Q=new J(null);Q.fromInt(30);var Y=function(q,H){return q|H};$.generateProbablePrime=function(q,H,N){if(typeof H==="function")N=H,H={};H=H||{};var K=H.algorithm||"PRIMEINC";if(typeof K==="string")K={name:K};K.options=K.options||{};var L=H.prng||k0.random,A={nextBytes:function(D){var S=L.getBytesSync(D.length);for(var B=0;B<D.length;++B)D[B]=S.charCodeAt(B)}};if(K.name==="PRIMEINC")return G(q,A,K.options,N);throw Error("Invalid prime generation algorithm: "+K.name)};function G(q,H,N,K){if("workers"in N)return M(q,H,N,K);return W(q,H,N,K)}function W(q,H,N,K){var L=O(q,H),A=0,D=V(L.bitLength());if("millerRabinTests"in N)D=N.millerRabinTests;var S=10;if("maxBlockTime"in N)S=N.maxBlockTime;U(L,q,H,A,D,S,K)}function U(q,H,N,K,L,A,D){var S=+new Date;do{if(q.bitLength()>H)q=O(H,N);if(q.isProbablePrime(L))return D(null,q);q.dAddOffset(X[K++%8],0)}while(A<0||+new Date-S<A);k0.util.setImmediate(function(){U(q,H,N,K,L,A,D)})}function M(q,H,N,K){if(typeof Worker>"u")return W(q,H,N,K);var L=O(q,H),A=N.workers,D=N.workLoad||100,S=D*30/8,B=N.workerScript||"forge/prime.worker.js";if(A===-1)return k0.util.estimateCores(function(w,P){if(w)P=2;A=P-1,C()});C();function C(){A=Math.max(1,A);var w=[];for(var P=0;P<A;++P)w[P]=new Worker(B);var l=A;for(var P=0;P<A;++P)w[P].addEventListener("message",y);var $$=!1;function y(n){if($$)return;--l;var Y$=n.data;if(Y$.found){for(var L$=0;L$<w.length;++L$)w[L$].terminate();return $$=!0,K(null,new J(Y$.prime,16))}if(L.bitLength()>q)L=O(q,H);var j$=L.toString(16);n.target.postMessage({hex:j$,workLoad:D}),L.dAddOffset(S,0)}}}function O(q,H){var N=new J(q,H),K=q-1;if(!N.testBit(K))N.bitwiseTo(J.ONE.shiftLeft(K),Y,N);return N.dAddOffset(31-N.mod(Q).byteValue(),0),N}function V(q){if(q<=100)return 27;if(q<=150)return 18;if(q<=200)return 15;if(q<=250)return 12;if(q<=300)return 9;if(q<=350)return 8;if(q<=400)return 7;if(q<=500)return 6;if(q<=600)return 5;if(q<=800)return 4;if(q<=1250)return 3;return 2}})()});var wX=q$((gF,P1)=>{var Q$=F$();lJ();CX();x0();N8();A8();_J();_$();if(typeof I$>"u")I$=Q$.jsbn.BigInteger;var I$,R8=Q$.util.isNodejs?FX("crypto"):null,I=Q$.asn1,vJ=Q$.util;Q$.pki=Q$.pki||{};P1.exports=Q$.pki.rsa=Q$.rsa=Q$.rsa||{};var H$=Q$.pki,RV=[6,4,2,4,2,4,6,2],DV={name:"PrivateKeyInfo",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:I.Class.UNIVERSAL,type:I.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:I.Class.UNIVERSAL,type:I.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},ZV={name:"RSAPrivateKey",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},BV={name:"RSAPublicKey",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:I.Class.UNIVERSAL,type:I.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},jV=Q$.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:I.Class.UNIVERSAL,type:I.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:I.Class.UNIVERSAL,type:I.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},TV={name:"DigestInfo",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:I.Class.UNIVERSAL,type:I.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:I.Class.UNIVERSAL,type:I.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:I.Class.UNIVERSAL,type:I.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:I.Class.UNIVERSAL,type:I.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},SV=function($){var J;if($.algorithm in H$.oids)J=H$.oids[$.algorithm];else{var X=Error("Unknown message digest algorithm.");throw X.algorithm=$.algorithm,X}var Q=I.oidToDer(J).getBytes(),Y=I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[]),G=I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[]);G.value.push(I.create(I.Class.UNIVERSAL,I.Type.OID,!1,Q)),G.value.push(I.create(I.Class.UNIVERSAL,I.Type.NULL,!1,""));var W=I.create(I.Class.UNIVERSAL,I.Type.OCTETSTRING,!1,$.digest().getBytes());return Y.value.push(G),Y.value.push(W),I.toDer(Y).getBytes()},C1=function($,J,X){if(X)return $.modPow(J.e,J.n);if(!J.p||!J.q)return $.modPow(J.d,J.n);if(!J.dP)J.dP=J.d.mod(J.p.subtract(I$.ONE));if(!J.dQ)J.dQ=J.d.mod(J.q.subtract(I$.ONE));if(!J.qInv)J.qInv=J.q.modInverse(J.p);var Q;do Q=new I$(Q$.util.bytesToHex(Q$.random.getBytes(J.n.bitLength()/8)),16);while(Q.compareTo(J.n)>=0||!Q.gcd(J.n).equals(I$.ONE));$=$.multiply(Q.modPow(J.e,J.n)).mod(J.n);var Y=$.mod(J.p).modPow(J.dP,J.p),G=$.mod(J.q).modPow(J.dQ,J.q);while(Y.compareTo(G)<0)Y=Y.add(J.p);var W=Y.subtract(G).multiply(J.qInv).mod(J.p).multiply(J.q).add(G);return W=W.multiply(Q.modInverse(J.n)).mod(J.n),W};H$.rsa.encrypt=function($,J,X){var Q=X,Y,G=Math.ceil(J.n.bitLength()/8);if(X!==!1&&X!==!0)Q=X===2,Y=w1($,J,X);else Y=Q$.util.createBuffer(),Y.putBytes($);var W=new I$(Y.toHex(),16),U=C1(W,J,Q),M=U.toString(16),O=Q$.util.createBuffer(),V=G-Math.ceil(M.length/2);while(V>0)O.putByte(0),--V;return O.putBytes(Q$.util.hexToBytes(M)),O.getBytes()};H$.rsa.decrypt=function($,J,X,Q){var Y=Math.ceil(J.n.bitLength()/8);if($.length!==Y){var G=Error("Encrypted message length is invalid.");throw G.length=$.length,G.expected=Y,G}var W=new I$(Q$.util.createBuffer($).toHex(),16);if(W.compareTo(J.n)>=0)throw Error("Encrypted message is invalid.");var U=C1(W,J,X),M=U.toString(16),O=Q$.util.createBuffer(),V=Y-Math.ceil(M.length/2);while(V>0)O.putByte(0),--V;if(O.putBytes(Q$.util.hexToBytes(M)),Q!==!1)return hY(O.getBytes(),J,X);return O.getBytes()};H$.rsa.createKeyPairGenerationState=function($,J,X){if(typeof $==="string")$=parseInt($,10);$=$||2048,X=X||{};var Q=X.prng||Q$.random,Y={nextBytes:function(U){var M=Q.getBytesSync(U.length);for(var O=0;O<U.length;++O)U[O]=M.charCodeAt(O)}},G=X.algorithm||"PRIMEINC",W;if(G==="PRIMEINC")W={algorithm:G,state:0,bits:$,rng:Y,eInt:J||65537,e:new I$(null),p:null,q:null,qBits:$>>1,pBits:$-($>>1),pqState:0,num:null,keys:null},W.e.fromInt(W.eInt);else throw Error("Invalid key generation algorithm: "+G);return W};H$.rsa.stepKeyPairGenerationState=function($,J){if(!("algorithm"in $))$.algorithm="PRIMEINC";var X=new I$(null);X.fromInt(30);var Q=0,Y=function(q,H){return q|H},G=+new Date,W,U=0;while($.keys===null&&(J<=0||U<J)){if($.state===0){var M=$.p===null?$.pBits:$.qBits,O=M-1;if($.pqState===0){if($.num=new I$(M,$.rng),!$.num.testBit(O))$.num.bitwiseTo(I$.ONE.shiftLeft(O),Y,$.num);$.num.dAddOffset(31-$.num.mod(X).byteValue(),0),Q=0,++$.pqState}else if($.pqState===1)if($.num.bitLength()>M)$.pqState=0;else if($.num.isProbablePrime(CV($.num.bitLength())))++$.pqState;else $.num.dAddOffset(RV[Q++%8],0);else if($.pqState===2)$.pqState=$.num.subtract(I$.ONE).gcd($.e).compareTo(I$.ONE)===0?3:0;else if($.pqState===3){if($.pqState=0,$.p===null)$.p=$.num;else $.q=$.num;if($.p!==null&&$.q!==null)++$.state;$.num=null}}else if($.state===1){if($.p.compareTo($.q)<0)$.num=$.p,$.p=$.q,$.q=$.num;++$.state}else if($.state===2)$.p1=$.p.subtract(I$.ONE),$.q1=$.q.subtract(I$.ONE),$.phi=$.p1.multiply($.q1),++$.state;else if($.state===3)if($.phi.gcd($.e).compareTo(I$.ONE)===0)++$.state;else $.p=null,$.q=null,$.state=0;else if($.state===4)if($.n=$.p.multiply($.q),$.n.bitLength()===$.bits)++$.state;else $.q=null,$.state=0;else if($.state===5){var V=$.e.modInverse($.phi);$.keys={privateKey:H$.rsa.setPrivateKey($.n,$.e,V,$.p,$.q,V.mod($.p1),V.mod($.q1),$.q.modInverse($.p)),publicKey:H$.rsa.setPublicKey($.n,$.e)}}W=+new Date,U+=W-G,G=W}return $.keys!==null};H$.rsa.generateKeyPair=function($,J,X,Q){if(arguments.length===1){if(typeof $==="object")X=$,$=void 0;else if(typeof $==="function")Q=$,$=void 0}else if(arguments.length===2)if(typeof $==="number"){if(typeof J==="function")Q=J,J=void 0;else if(typeof J!=="number")X=J,J=void 0}else X=$,Q=J,$=void 0,J=void 0;else if(arguments.length===3)if(typeof J==="number"){if(typeof X==="function")Q=X,X=void 0}else Q=X,X=J,J=void 0;if(X=X||{},$===void 0)$=X.bits||2048;if(J===void 0)J=X.e||65537;if(!Q$.options.usePureJavaScript&&!X.prng&&$>=256&&$<=16384&&(J===65537||J===3)){if(Q){if(j1("generateKeyPair"))return R8.generateKeyPair("rsa",{modulusLength:$,publicExponent:J,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(U,M,O){if(U)return Q(U);Q(null,{privateKey:H$.privateKeyFromPem(O),publicKey:H$.publicKeyFromPem(M)})});if(T1("generateKey")&&T1("exportKey"))return vJ.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:$,publicExponent:I1(J),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(U){return vJ.globalScope.crypto.subtle.exportKey("pkcs8",U.privateKey)}).then(void 0,function(U){Q(U)}).then(function(U){if(U){var M=H$.privateKeyFromAsn1(I.fromDer(Q$.util.createBuffer(U)));Q(null,{privateKey:M,publicKey:H$.setRsaPublicKey(M.n,M.e)})}});if(S1("generateKey")&&S1("exportKey")){var Y=vJ.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:$,publicExponent:I1(J),hash:{name:"SHA-256"}},!0,["sign","verify"]);Y.oncomplete=function(U){var M=U.target.result,O=vJ.globalScope.msCrypto.subtle.exportKey("pkcs8",M.privateKey);O.oncomplete=function(V){var q=V.target.result,H=H$.privateKeyFromAsn1(I.fromDer(Q$.util.createBuffer(q)));Q(null,{privateKey:H,publicKey:H$.setRsaPublicKey(H.n,H.e)})},O.onerror=function(V){Q(V)}},Y.onerror=function(U){Q(U)};return}}else if(j1("generateKeyPairSync")){var G=R8.generateKeyPairSync("rsa",{modulusLength:$,publicExponent:J,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:H$.privateKeyFromPem(G.privateKey),publicKey:H$.publicKeyFromPem(G.publicKey)}}}var W=H$.rsa.createKeyPairGenerationState($,J,X);if(!Q)return H$.rsa.stepKeyPairGenerationState(W,0),W.keys;IV(W,X,Q)};H$.setRsaPublicKey=H$.rsa.setPublicKey=function($,J){var X={n:$,e:J};return X.encrypt=function(Q,Y,G){if(typeof Y==="string")Y=Y.toUpperCase();else if(Y===void 0)Y="RSAES-PKCS1-V1_5";if(Y==="RSAES-PKCS1-V1_5")Y={encode:function(U,M,O){return w1(U,M,2).getBytes()}};else if(Y==="RSA-OAEP"||Y==="RSAES-OAEP")Y={encode:function(U,M){return Q$.pkcs1.encode_rsa_oaep(M,U,G)}};else if(["RAW","NONE","NULL",null].indexOf(Y)!==-1)Y={encode:function(U){return U}};else if(typeof Y==="string")throw Error('Unsupported encryption scheme: "'+Y+'".');var W=Y.encode(Q,X,!0);return H$.rsa.encrypt(W,X,!0)},X.verify=function(Q,Y,G,W){if(typeof G==="string")G=G.toUpperCase();else if(G===void 0)G="RSASSA-PKCS1-V1_5";if(W===void 0)W={_parseAllDigestBytes:!0,_skipPaddingChecks:!1};if(!("_parseAllDigestBytes"in W))W._parseAllDigestBytes=!0;if(!("_skipPaddingChecks"in W))W._skipPaddingChecks=!1;if(G==="RSASSA-PKCS1-V1_5")G={verify:function(M,O){O=hY(O,X,!0,void 0,W);var V=I.fromDer(O,{parseAllBytes:W._parseAllDigestBytes}),q={},H=[];if(!I.validate(V,TV,q,H)||V.value.length!==2){var N=Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw N.errors=H,N}var K=I.derToOid(q.algorithmIdentifier);if(!(K===Q$.oids.md2||K===Q$.oids.md5||K===Q$.oids.sha1||K===Q$.oids.sha224||K===Q$.oids.sha256||K===Q$.oids.sha384||K===Q$.oids.sha512||K===Q$.oids["sha512-224"]||K===Q$.oids["sha512-256"])){var N=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw N.oid=K,N}if(K===Q$.oids.md2||K===Q$.oids.md5){if(!("parameters"in q))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}return M===q.digest}};else if(G==="NONE"||G==="NULL"||G===null)G={verify:function(M,O){return O=hY(O,X,!0,void 0,W),M===O}};var U=H$.rsa.decrypt(Y,X,!0,!1);return G.verify(Q,U,X.n.bitLength())},X};H$.setRsaPrivateKey=H$.rsa.setPrivateKey=function($,J,X,Q,Y,G,W,U){var M={n:$,e:J,d:X,p:Q,q:Y,dP:G,dQ:W,qInv:U};return M.decrypt=function(O,V,q){if(typeof V==="string")V=V.toUpperCase();else if(V===void 0)V="RSAES-PKCS1-V1_5";var H=H$.rsa.decrypt(O,M,!1,!1);if(V==="RSAES-PKCS1-V1_5")V={decode:hY};else if(V==="RSA-OAEP"||V==="RSAES-OAEP")V={decode:function(N,K){return Q$.pkcs1.decode_rsa_oaep(K,N,q)}};else if(["RAW","NONE","NULL",null].indexOf(V)!==-1)V={decode:function(N){return N}};else throw Error('Unsupported encryption scheme: "'+V+'".');return V.decode(H,M,!1)},M.sign=function(O,V){var q=!1;if(typeof V==="string")V=V.toUpperCase();if(V===void 0||V==="RSASSA-PKCS1-V1_5")V={encode:SV},q=1;else if(V==="NONE"||V==="NULL"||V===null)V={encode:function(){return O}},q=1;var H=V.encode(O,M.n.bitLength());return H$.rsa.encrypt(H,M,q)},M};H$.wrapRsaPrivateKey=function($){return I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,I.integerToDer(0).getBytes()),I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.OID,!1,I.oidToDer(H$.oids.rsaEncryption).getBytes()),I.create(I.Class.UNIVERSAL,I.Type.NULL,!1,"")]),I.create(I.Class.UNIVERSAL,I.Type.OCTETSTRING,!1,I.toDer($).getBytes())])};H$.privateKeyFromAsn1=function($){var J={},X=[];if(I.validate($,DV,J,X))$=I.fromDer(Q$.util.createBuffer(J.privateKey));if(J={},X=[],!I.validate($,ZV,J,X)){var Q=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw Q.errors=X,Q}var Y,G,W,U,M,O,V,q;return Y=Q$.util.createBuffer(J.privateKeyModulus).toHex(),G=Q$.util.createBuffer(J.privateKeyPublicExponent).toHex(),W=Q$.util.createBuffer(J.privateKeyPrivateExponent).toHex(),U=Q$.util.createBuffer(J.privateKeyPrime1).toHex(),M=Q$.util.createBuffer(J.privateKeyPrime2).toHex(),O=Q$.util.createBuffer(J.privateKeyExponent1).toHex(),V=Q$.util.createBuffer(J.privateKeyExponent2).toHex(),q=Q$.util.createBuffer(J.privateKeyCoefficient).toHex(),H$.setRsaPrivateKey(new I$(Y,16),new I$(G,16),new I$(W,16),new I$(U,16),new I$(M,16),new I$(O,16),new I$(V,16),new I$(q,16))};H$.privateKeyToAsn1=H$.privateKeyToRSAPrivateKey=function($){return I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,I.integerToDer(0).getBytes()),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.n)),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.e)),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.d)),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.p)),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.q)),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.dP)),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.dQ)),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.qInv))])};H$.publicKeyFromAsn1=function($){var J={},X=[];if(I.validate($,jV,J,X)){var Q=I.derToOid(J.publicKeyOid);if(Q!==H$.oids.rsaEncryption){var Y=Error("Cannot read public key. Unknown OID.");throw Y.oid=Q,Y}$=J.rsaPublicKey}if(X=[],!I.validate($,BV,J,X)){var Y=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw Y.errors=X,Y}var G=Q$.util.createBuffer(J.publicKeyModulus).toHex(),W=Q$.util.createBuffer(J.publicKeyExponent).toHex();return H$.setRsaPublicKey(new I$(G,16),new I$(W,16))};H$.publicKeyToAsn1=H$.publicKeyToSubjectPublicKeyInfo=function($){return I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.OID,!1,I.oidToDer(H$.oids.rsaEncryption).getBytes()),I.create(I.Class.UNIVERSAL,I.Type.NULL,!1,"")]),I.create(I.Class.UNIVERSAL,I.Type.BITSTRING,!1,[H$.publicKeyToRSAPublicKey($)])])};H$.publicKeyToRSAPublicKey=function($){return I.create(I.Class.UNIVERSAL,I.Type.SEQUENCE,!0,[I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.n)),I.create(I.Class.UNIVERSAL,I.Type.INTEGER,!1,M0($.e))])};function w1($,J,X){var Q=Q$.util.createBuffer(),Y=Math.ceil(J.n.bitLength()/8);if($.length>Y-11){var G=Error("Message is too long for PKCS#1 v1.5 padding.");throw G.length=$.length,G.max=Y-11,G}Q.putByte(0),Q.putByte(X);var W=Y-3-$.length,U;if(X===0||X===1){U=X===0?0:255;for(var M=0;M<W;++M)Q.putByte(U)}else while(W>0){var O=0,V=Q$.random.getBytes(W);for(var M=0;M<W;++M)if(U=V.charCodeAt(M),U===0)++O;else Q.putByte(U);W=O}return Q.putByte(0),Q.putBytes($),Q}function hY($,J,X,Q,Y){var G=Math.ceil(J.n.bitLength()/8),W=Q$.util.createBuffer($),U=W.getByte(),M=W.getByte();if(U!==0||X&&M!==0&&M!==1||!X&&M!==2||X&&M===0&&typeof Q>"u")throw Error("Encryption block is invalid.");var O=0;if(M===0){O=G-3-Q;for(var V=0;V<O;++V)if(W.getByte()!==0)throw Error("Encryption block is invalid.")}else if(M===1){O=0;while(W.length()>1){if(W.getByte()!==255){--W.read;break}++O}if(O<8&&!(Y?Y._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}else if(M===2){O=0;while(W.length()>1){if(W.getByte()===0){--W.read;break}++O}if(O<8&&!(Y?Y._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}var q=W.getByte();if(q!==0||O!==G-3-W.length())throw Error("Encryption block is invalid.");return W.getBytes()}function IV($,J,X){if(typeof J==="function")X=J,J={};J=J||{};var Q={algorithm:{name:J.algorithm||"PRIMEINC",options:{workers:J.workers||2,workLoad:J.workLoad||100,workerScript:J.workerScript}}};if("prng"in J)Q.prng=J.prng;Y();function Y(){G($.pBits,function(U,M){if(U)return X(U);if($.p=M,$.q!==null)return W(U,$.q);G($.qBits,W)})}function G(U,M){Q$.prime.generateProbablePrime(U,Q,M)}function W(U,M){if(U)return X(U);if($.q=M,$.p.compareTo($.q)<0){var O=$.p;$.p=$.q,$.q=O}if($.p.subtract(I$.ONE).gcd($.e).compareTo(I$.ONE)!==0){$.p=null,Y();return}if($.q.subtract(I$.ONE).gcd($.e).compareTo(I$.ONE)!==0){$.q=null,G($.qBits,W);return}if($.p1=$.p.subtract(I$.ONE),$.q1=$.q.subtract(I$.ONE),$.phi=$.p1.multiply($.q1),$.phi.gcd($.e).compareTo(I$.ONE)!==0){$.p=$.q=null,Y();return}if($.n=$.p.multiply($.q),$.n.bitLength()!==$.bits){$.q=null,G($.qBits,W);return}var V=$.e.modInverse($.phi);$.keys={privateKey:H$.rsa.setPrivateKey($.n,$.e,V,$.p,$.q,V.mod($.p1),V.mod($.q1),$.q.modInverse($.p)),publicKey:H$.rsa.setPublicKey($.n,$.e)},X(null,$.keys)}}function M0($){var J=$.toString(16);if(J[0]>="8")J="00"+J;var X=Q$.util.hexToBytes(J);if(X.length>1&&(X.charCodeAt(0)===0&&(X.charCodeAt(1)&128)===0||X.charCodeAt(0)===255&&(X.charCodeAt(1)&128)===128))return X.substr(1);return X}function CV($){if($<=100)return 27;if($<=150)return 18;if($<=200)return 15;if($<=250)return 12;if($<=300)return 9;if($<=350)return 8;if($<=400)return 7;if($<=500)return 6;if($<=600)return 5;if($<=800)return 4;if($<=1250)return 3;return 2}function j1($){return Q$.util.isNodejs&&typeof R8[$]==="function"}function T1($){return typeof vJ.globalScope<"u"&&typeof vJ.globalScope.crypto==="object"&&typeof vJ.globalScope.crypto.subtle==="object"&&typeof vJ.globalScope.crypto.subtle[$]==="function"}function S1($){return typeof vJ.globalScope<"u"&&typeof vJ.globalScope.msCrypto==="object"&&typeof vJ.globalScope.msCrypto.subtle==="object"&&typeof vJ.globalScope.msCrypto.subtle[$]==="function"}function I1($){var J=Q$.util.hexToBytes($.toString(16)),X=new Uint8Array(J.length);for(var Q=0;Q<J.length;++Q)X[Q]=J.charCodeAt(Q);return X}});var Z8=q$((mF,k1)=>{var o=F$();_0();lJ();SX();J0();x0();vY();YQ();_J();H8();wX();_$();if(typeof D8>"u")D8=o.jsbn.BigInteger;var D8,x=o.asn1,E$=o.pki=o.pki||{};k1.exports=E$.pbe=o.pbe=o.pbe||{};var UQ=E$.oids,wV={name:"EncryptedPrivateKeyInfo",tagClass:x.Class.UNIVERSAL,type:x.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:x.Class.UNIVERSAL,type:x.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:x.Class.UNIVERSAL,type:x.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:x.Class.UNIVERSAL,type:x.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:x.Class.UNIVERSAL,type:x.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},PV={name:"PBES2Algorithms",tagClass:x.Class.UNIVERSAL,type:x.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:x.Class.UNIVERSAL,type:x.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:x.Class.UNIVERSAL,type:x.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:x.Class.UNIVERSAL,type:x.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:x.Class.UNIVERSAL,type:x.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:x.Class.UNIVERSAL,type:x.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:x.Class.UNIVERSAL,type:x.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:x.Class.UNIVERSAL,type:x.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:x.Class.UNIVERSAL,type:x.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:x.Class.UNIVERSAL,type:x.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:x.Class.UNIVERSAL,type:x.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:x.Class.UNIVERSAL,type:x.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},_V={name:"pkcs-12PbeParams",tagClass:x.Class.UNIVERSAL,type:x.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:x.Class.UNIVERSAL,type:x.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:x.Class.UNIVERSAL,type:x.Type.INTEGER,constructed:!1,capture:"iterations"}]};E$.encryptPrivateKeyInfo=function($,J,X){X=X||{},X.saltSize=X.saltSize||8,X.count=X.count||2048,X.algorithm=X.algorithm||"aes128",X.prfAlgorithm=X.prfAlgorithm||"sha1";var Q=o.random.getBytesSync(X.saltSize),Y=X.count,G=x.integerToDer(Y),W,U,M;if(X.algorithm.indexOf("aes")===0||X.algorithm==="des"){var O,V,q;switch(X.algorithm){case"aes128":W=16,O=16,V=UQ["aes128-CBC"],q=o.aes.createEncryptionCipher;break;case"aes192":W=24,O=16,V=UQ["aes192-CBC"],q=o.aes.createEncryptionCipher;break;case"aes256":W=32,O=16,V=UQ["aes256-CBC"],q=o.aes.createEncryptionCipher;break;case"des":W=8,O=8,V=UQ.desCBC,q=o.des.createEncryptionCipher;break;default:var H=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw H.algorithm=X.algorithm,H}var N="hmacWith"+X.prfAlgorithm.toUpperCase(),K=v1(N),L=o.pkcs5.pbkdf2(J,Q,Y,W,K),A=o.random.getBytesSync(O),D=q(L);D.start(A),D.update(x.toDer($)),D.finish(),M=D.output.getBytes();var S=xV(Q,G,W,N);U=x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(UQ.pkcs5PBES2).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(UQ.pkcs5PBKDF2).getBytes()),S]),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(V).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,A)])])])}else if(X.algorithm==="3des"){W=24;var B=new o.util.ByteBuffer(Q),L=E$.pbe.generatePkcs12Key(J,B,1,Y,W),A=E$.pbe.generatePkcs12Key(J,B,2,Y,W),D=o.des.createEncryptionCipher(L);D.start(A),D.update(x.toDer($)),D.finish(),M=D.output.getBytes(),U=x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(UQ["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,Q),x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,G.getBytes())])])}else{var H=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw H.algorithm=X.algorithm,H}var C=x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[U,x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,M)]);return C};E$.decryptPrivateKeyInfo=function($,J){var X=null,Q={},Y=[];if(!x.validate($,wV,Q,Y)){var G=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw G.errors=Y,G}var W=x.derToOid(Q.encryptionOid),U=E$.pbe.getCipher(W,Q.encryptionParams,J),M=o.util.createBuffer(Q.encryptedData);if(U.update(M),U.finish())X=x.fromDer(U.output);return X};E$.encryptedPrivateKeyToPem=function($,J){var X={type:"ENCRYPTED PRIVATE KEY",body:x.toDer($).getBytes()};return o.pem.encode(X,{maxline:J})};E$.encryptedPrivateKeyFromPem=function($){var J=o.pem.decode($)[0];if(J.type!=="ENCRYPTED PRIVATE KEY"){var X=Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw X.headerType=J.type,X}if(J.procType&&J.procType.type==="ENCRYPTED")throw Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return x.fromDer(J.body)};E$.encryptRsaPrivateKey=function($,J,X){if(X=X||{},!X.legacy){var Q=E$.wrapRsaPrivateKey(E$.privateKeyToAsn1($));return Q=E$.encryptPrivateKeyInfo(Q,J,X),E$.encryptedPrivateKeyToPem(Q)}var Y,G,W,U;switch(X.algorithm){case"aes128":Y="AES-128-CBC",W=16,G=o.random.getBytesSync(16),U=o.aes.createEncryptionCipher;break;case"aes192":Y="AES-192-CBC",W=24,G=o.random.getBytesSync(16),U=o.aes.createEncryptionCipher;break;case"aes256":Y="AES-256-CBC",W=32,G=o.random.getBytesSync(16),U=o.aes.createEncryptionCipher;break;case"3des":Y="DES-EDE3-CBC",W=24,G=o.random.getBytesSync(8),U=o.des.createEncryptionCipher;break;case"des":Y="DES-CBC",W=8,G=o.random.getBytesSync(8),U=o.des.createEncryptionCipher;break;default:var M=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+X.algorithm+'".');throw M.algorithm=X.algorithm,M}var O=o.pbe.opensslDeriveBytes(J,G.substr(0,8),W),V=U(O);V.start(G),V.update(x.toDer(E$.privateKeyToAsn1($))),V.finish();var q={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:Y,parameters:o.util.bytesToHex(G).toUpperCase()},body:V.output.getBytes()};return o.pem.encode(q)};E$.decryptRsaPrivateKey=function($,J){var X=null,Q=o.pem.decode($)[0];if(Q.type!=="ENCRYPTED PRIVATE KEY"&&Q.type!=="PRIVATE KEY"&&Q.type!=="RSA PRIVATE KEY"){var Y=Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw Y.headerType=Y,Y}if(Q.procType&&Q.procType.type==="ENCRYPTED"){var G,W;switch(Q.dekInfo.algorithm){case"DES-CBC":G=8,W=o.des.createDecryptionCipher;break;case"DES-EDE3-CBC":G=24,W=o.des.createDecryptionCipher;break;case"AES-128-CBC":G=16,W=o.aes.createDecryptionCipher;break;case"AES-192-CBC":G=24,W=o.aes.createDecryptionCipher;break;case"AES-256-CBC":G=32,W=o.aes.createDecryptionCipher;break;case"RC2-40-CBC":G=5,W=function(q){return o.rc2.createDecryptionCipher(q,40)};break;case"RC2-64-CBC":G=8,W=function(q){return o.rc2.createDecryptionCipher(q,64)};break;case"RC2-128-CBC":G=16,W=function(q){return o.rc2.createDecryptionCipher(q,128)};break;default:var Y=Error('Could not decrypt private key; unsupported encryption algorithm "'+Q.dekInfo.algorithm+'".');throw Y.algorithm=Q.dekInfo.algorithm,Y}var U=o.util.hexToBytes(Q.dekInfo.parameters),M=o.pbe.opensslDeriveBytes(J,U.substr(0,8),G),O=W(M);if(O.start(U),O.update(o.util.createBuffer(Q.body)),O.finish())X=O.output.getBytes();else return X}else X=Q.body;if(Q.type==="ENCRYPTED PRIVATE KEY")X=E$.decryptPrivateKeyInfo(x.fromDer(X),J);else X=x.fromDer(X);if(X!==null)X=E$.privateKeyFromAsn1(X);return X};E$.pbe.generatePkcs12Key=function($,J,X,Q,Y,G){var W,U;if(typeof G>"u"||G===null){if(!("sha1"in o.md))throw Error('"sha1" hash algorithm unavailable.');G=o.md.sha1.create()}var{digestLength:M,blockLength:O}=G,V=new o.util.ByteBuffer,q=new o.util.ByteBuffer;if($!==null&&$!==void 0){for(U=0;U<$.length;U++)q.putInt16($.charCodeAt(U));q.putInt16(0)}var H=q.length(),N=J.length(),K=new o.util.ByteBuffer;K.fillWithByte(X,O);var L=O*Math.ceil(N/O),A=new o.util.ByteBuffer;for(U=0;U<L;U++)A.putByte(J.at(U%N));var D=O*Math.ceil(H/O),S=new o.util.ByteBuffer;for(U=0;U<D;U++)S.putByte(q.at(U%H));var B=A;B.putBuffer(S);var C=Math.ceil(Y/M);for(var w=1;w<=C;w++){var P=new o.util.ByteBuffer;P.putBytes(K.bytes()),P.putBytes(B.bytes());for(var l=0;l<Q;l++)G.start(),G.update(P.getBytes()),P=G.digest();var $$=new o.util.ByteBuffer;for(U=0;U<O;U++)$$.putByte(P.at(U%M));var y=Math.ceil(N/O)+Math.ceil(H/O),n=new o.util.ByteBuffer;for(W=0;W<y;W++){var Y$=new o.util.ByteBuffer(B.getBytes(O)),L$=511;for(U=$$.length()-1;U>=0;U--)L$=L$>>8,L$+=$$.at(U)+Y$.at(U),Y$.setAt(U,L$&255);n.putBuffer(Y$)}B=n,V.putBuffer(P)}return V.truncate(V.length()-Y),V};E$.pbe.getCipher=function($,J,X){switch($){case E$.oids.pkcs5PBES2:return E$.pbe.getCipherForPBES2($,J,X);case E$.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case E$.oids["pbewithSHAAnd40BitRC2-CBC"]:return E$.pbe.getCipherForPKCS12PBE($,J,X);default:var Q=Error("Cannot read encrypted PBE data block. Unsupported OID.");throw Q.oid=$,Q.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],Q}};E$.pbe.getCipherForPBES2=function($,J,X){var Q={},Y=[];if(!x.validate(J,PV,Q,Y)){var G=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw G.errors=Y,G}if($=x.derToOid(Q.kdfOid),$!==E$.oids.pkcs5PBKDF2){var G=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw G.oid=$,G.supportedOids=["pkcs5PBKDF2"],G}if($=x.derToOid(Q.encOid),$!==E$.oids["aes128-CBC"]&&$!==E$.oids["aes192-CBC"]&&$!==E$.oids["aes256-CBC"]&&$!==E$.oids["des-EDE3-CBC"]&&$!==E$.oids.desCBC){var G=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw G.oid=$,G.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],G}var W=Q.kdfSalt,U=o.util.createBuffer(Q.kdfIterationCount);U=U.getInt(U.length()<<3);var M,O;switch(E$.oids[$]){case"aes128-CBC":M=16,O=o.aes.createDecryptionCipher;break;case"aes192-CBC":M=24,O=o.aes.createDecryptionCipher;break;case"aes256-CBC":M=32,O=o.aes.createDecryptionCipher;break;case"des-EDE3-CBC":M=24,O=o.des.createDecryptionCipher;break;case"desCBC":M=8,O=o.des.createDecryptionCipher;break}var V=x1(Q.prfOid),q=o.pkcs5.pbkdf2(X,W,U,M,V),H=Q.encIv,N=O(q);return N.start(H),N};E$.pbe.getCipherForPKCS12PBE=function($,J,X){var Q={},Y=[];if(!x.validate(J,_V,Q,Y)){var G=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw G.errors=Y,G}var W=o.util.createBuffer(Q.salt),U=o.util.createBuffer(Q.iterations);U=U.getInt(U.length()<<3);var M,O,V;switch($){case E$.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:M=24,O=8,V=o.des.startDecrypting;break;case E$.oids["pbewithSHAAnd40BitRC2-CBC"]:M=5,O=8,V=function(L,A){var D=o.rc2.createDecryptionCipher(L,40);return D.start(A,null),D};break;default:var G=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw G.oid=$,G}var q=x1(Q.prfOid),H=E$.pbe.generatePkcs12Key(X,W,1,U,M,q);q.start();var N=E$.pbe.generatePkcs12Key(X,W,2,U,O,q);return V(H,N)};E$.pbe.opensslDeriveBytes=function($,J,X,Q){if(typeof Q>"u"||Q===null){if(!("md5"in o.md))throw Error('"md5" hash algorithm unavailable.');Q=o.md.md5.create()}if(J===null)J="";var Y=[_1(Q,$+J)];for(var G=16,W=1;G<X;++W,G+=16)Y.push(_1(Q,Y[W-1]+$+J));return Y.join("").substr(0,X)};function _1($,J){return $.start().update(J).digest().getBytes()}function x1($){var J;if(!$)J="hmacWithSHA1";else if(J=E$.oids[x.derToOid($)],!J){var X=Error("Unsupported PRF OID.");throw X.oid=$,X.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],X}return v1(J)}function v1($){var J=o.md;switch($){case"hmacWithSHA224":J=o.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":$=$.substr(8).toLowerCase();break;default:var X=Error("Unsupported PRF algorithm.");throw X.algorithm=$,X.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],X}if(!J||!($ in J))throw Error("Unknown hash algorithm: "+$);return J[$].create()}function xV($,J,X,Q){var Y=x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,$),x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,J.getBytes())]);if(Q!=="hmacWithSHA1")Y.value.push(x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,o.util.hexToBytes(X.toString(16))),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(E$.oids[Q]).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.NULL,!1,"")]));return Y}});var B8=q$((lF,b1)=>{var xQ=F$();lJ();_$();var i=xQ.asn1,vQ=b1.exports=xQ.pkcs7asn1=xQ.pkcs7asn1||{};xQ.pkcs7=xQ.pkcs7||{};xQ.pkcs7.asn1=vQ;var f1={name:"ContentInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};vQ.contentInfoValidator=f1;var y1={name:"EncryptedContentInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};vQ.envelopedDataValidator={name:"EnvelopedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(y1)};vQ.encryptedDataValidator={name:"EncryptedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"}].concat(y1)};var vV={name:"SignerInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};vQ.signedDataValidator={name:"SignedData",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},f1,{name:"SignedData.Certificates",tagClass:i.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:i.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:i.Class.UNIVERSAL,type:i.Type.SET,capture:"signerInfos",optional:!0,value:[vV]}]};vQ.recipientInfoValidator={name:"RecipientInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:i.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var j8=q$((pF,h1)=>{var MQ=F$();_$();MQ.mgf=MQ.mgf||{};var kV=h1.exports=MQ.mgf.mgf1=MQ.mgf1=MQ.mgf1||{};kV.create=function($){var J={generate:function(X,Q){var Y=new MQ.util.ByteBuffer,G=Math.ceil(Q/$.digestLength);for(var W=0;W<G;W++){var U=new MQ.util.ByteBuffer;U.putInt32(W),$.start(),$.update(X+U.getBytes()),Y.putBuffer($.digest())}return Y.truncate(Y.length()-Q),Y.getBytes()}};return J}});var g1=q$((dF,u1)=>{var uY=F$();j8();u1.exports=uY.mgf=uY.mgf||{};uY.mgf.mgf1=uY.mgf1});var gY=q$((cF,m1)=>{var OQ=F$();_J();_$();var fV=m1.exports=OQ.pss=OQ.pss||{};fV.create=function($){if(arguments.length===3)$={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]};var{md:J,mgf:X}=$,Q=J.digestLength,Y=$.salt||null;if(typeof Y==="string")Y=OQ.util.createBuffer(Y);var G;if("saltLength"in $)G=$.saltLength;else if(Y!==null)G=Y.length();else throw Error("Salt length not specified or specific salt not given.");if(Y!==null&&Y.length()!==G)throw Error("Given salt length does not match length of given salt.");var W=$.prng||OQ.random,U={};return U.encode=function(M,O){var V,q=O-1,H=Math.ceil(q/8),N=M.digest().getBytes();if(H<Q+G+2)throw Error("Message is too long to encrypt.");var K;if(Y===null)K=W.getBytesSync(G);else K=Y.bytes();var L=new OQ.util.ByteBuffer;L.fillWithByte(0,8),L.putBytes(N),L.putBytes(K),J.start(),J.update(L.getBytes());var A=J.digest().getBytes(),D=new OQ.util.ByteBuffer;D.fillWithByte(0,H-G-Q-2),D.putByte(1),D.putBytes(K);var S=D.getBytes(),B=H-Q-1,C=X.generate(A,B),w="";for(V=0;V<B;V++)w+=String.fromCharCode(S.charCodeAt(V)^C.charCodeAt(V));var P=65280>>8*H-q&255;return w=String.fromCharCode(w.charCodeAt(0)&~P)+w.substr(1),w+A+String.fromCharCode(188)},U.verify=function(M,O,V){var q,H=V-1,N=Math.ceil(H/8);if(O=O.substr(-N),N<Q+G+2)throw Error("Inconsistent parameters to PSS signature verification.");if(O.charCodeAt(N-1)!==188)throw Error("Encoded message does not end in 0xBC.");var K=N-Q-1,L=O.substr(0,K),A=O.substr(K,Q),D=65280>>8*N-H&255;if((L.charCodeAt(0)&D)!==0)throw Error("Bits beyond keysize not zero as expected.");var S=X.generate(A,K),B="";for(q=0;q<K;q++)B+=String.fromCharCode(L.charCodeAt(q)^S.charCodeAt(q));B=String.fromCharCode(B.charCodeAt(0)&~D)+B.substr(1);var C=N-Q-G-2;for(q=0;q<C;q++)if(B.charCodeAt(q)!==0)throw Error("Leftmost octets not zero as expected");if(B.charCodeAt(C)!==1)throw Error("Inconsistent PSS signature, 0x01 marker not found");var w=B.substr(-G),P=new OQ.util.ByteBuffer;P.fillWithByte(0,8),P.putBytes(M),P.putBytes(w),J.start(),J.update(P.getBytes());var l=J.digest().getBytes();return A===l},U}});var pY=q$((nF,n1)=>{var X$=F$();_0();lJ();SX();J0();g1();x0();YQ();gY();wX();_$();var z=X$.asn1,g=n1.exports=X$.pki=X$.pki||{},P$=g.oids,s$={};s$.CN=P$.commonName;s$.commonName="CN";s$.C=P$.countryName;s$.countryName="C";s$.L=P$.localityName;s$.localityName="L";s$.ST=P$.stateOrProvinceName;s$.stateOrProvinceName="ST";s$.O=P$.organizationName;s$.organizationName="O";s$.OU=P$.organizationalUnitName;s$.organizationalUnitName="OU";s$.E=P$.emailAddress;s$.emailAddress="E";var p1=X$.pki.rsa.publicKeyValidator,yV={name:"Certificate",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:z.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:z.Class.UNIVERSAL,type:z.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:z.Class.UNIVERSAL,type:z.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:z.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:z.Class.UNIVERSAL,type:z.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:z.Class.UNIVERSAL,type:z.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:z.Class.UNIVERSAL,type:z.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:z.Class.UNIVERSAL,type:z.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},p1,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:z.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:z.Class.UNIVERSAL,type:z.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:z.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:z.Class.UNIVERSAL,type:z.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:z.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:z.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:z.Class.UNIVERSAL,type:z.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},bV={name:"rsapss",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:z.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:z.Class.UNIVERSAL,type:z.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:z.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:z.Class.UNIVERSAL,type:z.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:z.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:z.Class.UNIVERSAL,type:z.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:z.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:z.Class.UNIVERSAL,type:z.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},hV={name:"CertificationRequestInfo",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:z.Class.UNIVERSAL,type:z.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},p1,{name:"CertificationRequestInfo.attributes",tagClass:z.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:z.Class.UNIVERSAL,type:z.Type.SET,constructed:!0}]}]}]},uV={name:"CertificationRequest",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[hV,{name:"CertificationRequest.signatureAlgorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:z.Class.UNIVERSAL,type:z.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:z.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:z.Class.UNIVERSAL,type:z.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};g.RDNAttributesAsArray=function($,J){var X=[],Q,Y,G;for(var W=0;W<$.value.length;++W){Q=$.value[W];for(var U=0;U<Q.value.length;++U){if(G={},Y=Q.value[U],G.type=z.derToOid(Y.value[0].value),G.value=Y.value[1].value,G.valueTagClass=Y.value[1].type,G.type in P$){if(G.name=P$[G.type],G.name in s$)G.shortName=s$[G.name]}if(J)J.update(G.type),J.update(G.value);X.push(G)}}return X};g.CRIAttributesAsArray=function($){var J=[];for(var X=0;X<$.length;++X){var Q=$[X],Y=z.derToOid(Q.value[0].value),G=Q.value[1].value;for(var W=0;W<G.length;++W){var U={};if(U.type=Y,U.value=G[W].value,U.valueTagClass=G[W].type,U.type in P$){if(U.name=P$[U.type],U.name in s$)U.shortName=s$[U.name]}if(U.type===P$.extensionRequest){U.extensions=[];for(var M=0;M<U.value.length;++M)U.extensions.push(g.certificateExtensionFromAsn1(U.value[M]))}J.push(U)}}return J};function f0($,J){if(typeof J==="string")J={shortName:J};var X=null,Q;for(var Y=0;X===null&&Y<$.attributes.length;++Y)if(Q=$.attributes[Y],J.type&&J.type===Q.type)X=Q;else if(J.name&&J.name===Q.name)X=Q;else if(J.shortName&&J.shortName===Q.shortName)X=Q;return X}var mY=function($,J,X){var Q={};if($!==P$["RSASSA-PSS"])return Q;if(X)Q={hash:{algorithmOid:P$.sha1},mgf:{algorithmOid:P$.mgf1,hash:{algorithmOid:P$.sha1}},saltLength:20};var Y={},G=[];if(!z.validate(J,bV,Y,G)){var W=Error("Cannot read RSASSA-PSS parameter block.");throw W.errors=G,W}if(Y.hashOid!==void 0)Q.hash=Q.hash||{},Q.hash.algorithmOid=z.derToOid(Y.hashOid);if(Y.maskGenOid!==void 0)Q.mgf=Q.mgf||{},Q.mgf.algorithmOid=z.derToOid(Y.maskGenOid),Q.mgf.hash=Q.mgf.hash||{},Q.mgf.hash.algorithmOid=z.derToOid(Y.maskGenHashOid);if(Y.saltLength!==void 0)Q.saltLength=Y.saltLength.charCodeAt(0);return Q},lY=function($){switch(P$[$.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return X$.md.sha1.create();case"md5WithRSAEncryption":return X$.md.md5.create();case"sha256WithRSAEncryption":return X$.md.sha256.create();case"sha384WithRSAEncryption":return X$.md.sha384.create();case"sha512WithRSAEncryption":return X$.md.sha512.create();case"RSASSA-PSS":return X$.md.sha256.create();default:var J=Error("Could not compute "+$.type+" digest. Unknown signature OID.");throw J.signatureOid=$.signatureOid,J}},d1=function($){var J=$.certificate,X;switch(J.signatureOid){case P$.sha1WithRSAEncryption:case P$.sha1WithRSASignature:break;case P$["RSASSA-PSS"]:var Q,Y;if(Q=P$[J.signatureParameters.mgf.hash.algorithmOid],Q===void 0||X$.md[Q]===void 0){var G=Error("Unsupported MGF hash function.");throw G.oid=J.signatureParameters.mgf.hash.algorithmOid,G.name=Q,G}if(Y=P$[J.signatureParameters.mgf.algorithmOid],Y===void 0||X$.mgf[Y]===void 0){var G=Error("Unsupported MGF function.");throw G.oid=J.signatureParameters.mgf.algorithmOid,G.name=Y,G}if(Y=X$.mgf[Y].create(X$.md[Q].create()),Q=P$[J.signatureParameters.hash.algorithmOid],Q===void 0||X$.md[Q]===void 0){var G=Error("Unsupported RSASSA-PSS hash function.");throw G.oid=J.signatureParameters.hash.algorithmOid,G.name=Q,G}X=X$.pss.create(X$.md[Q].create(),Y,J.signatureParameters.saltLength);break}return J.publicKey.verify($.md.digest().getBytes(),$.signature,X)};g.certificateFromPem=function($,J,X){var Q=X$.pem.decode($)[0];if(Q.type!=="CERTIFICATE"&&Q.type!=="X509 CERTIFICATE"&&Q.type!=="TRUSTED CERTIFICATE"){var Y=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw Y.headerType=Q.type,Y}if(Q.procType&&Q.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var G=z.fromDer(Q.body,X);return g.certificateFromAsn1(G,J)};g.certificateToPem=function($,J){var X={type:"CERTIFICATE",body:z.toDer(g.certificateToAsn1($)).getBytes()};return X$.pem.encode(X,{maxline:J})};g.publicKeyFromPem=function($){var J=X$.pem.decode($)[0];if(J.type!=="PUBLIC KEY"&&J.type!=="RSA PUBLIC KEY"){var X=Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw X.headerType=J.type,X}if(J.procType&&J.procType.type==="ENCRYPTED")throw Error("Could not convert public key from PEM; PEM is encrypted.");var Q=z.fromDer(J.body);return g.publicKeyFromAsn1(Q)};g.publicKeyToPem=function($,J){var X={type:"PUBLIC KEY",body:z.toDer(g.publicKeyToAsn1($)).getBytes()};return X$.pem.encode(X,{maxline:J})};g.publicKeyToRSAPublicKeyPem=function($,J){var X={type:"RSA PUBLIC KEY",body:z.toDer(g.publicKeyToRSAPublicKey($)).getBytes()};return X$.pem.encode(X,{maxline:J})};g.getPublicKeyFingerprint=function($,J){J=J||{};var X=J.md||X$.md.sha1.create(),Q=J.type||"RSAPublicKey",Y;switch(Q){case"RSAPublicKey":Y=z.toDer(g.publicKeyToRSAPublicKey($)).getBytes();break;case"SubjectPublicKeyInfo":Y=z.toDer(g.publicKeyToAsn1($)).getBytes();break;default:throw Error('Unknown fingerprint type "'+J.type+'".')}X.start(),X.update(Y);var G=X.digest();if(J.encoding==="hex"){var W=G.toHex();if(J.delimiter)return W.match(/.{2}/g).join(J.delimiter);return W}else if(J.encoding==="binary")return G.getBytes();else if(J.encoding)throw Error('Unknown encoding "'+J.encoding+'".');return G};g.certificationRequestFromPem=function($,J,X){var Q=X$.pem.decode($)[0];if(Q.type!=="CERTIFICATE REQUEST"){var Y=Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw Y.headerType=Q.type,Y}if(Q.procType&&Q.procType.type==="ENCRYPTED")throw Error("Could not convert certification request from PEM; PEM is encrypted.");var G=z.fromDer(Q.body,X);return g.certificationRequestFromAsn1(G,J)};g.certificationRequestToPem=function($,J){var X={type:"CERTIFICATE REQUEST",body:z.toDer(g.certificationRequestToAsn1($)).getBytes()};return X$.pem.encode(X,{maxline:J})};g.createCertificate=function(){var $={};return $.version=2,$.serialNumber="00",$.signatureOid=null,$.signature=null,$.siginfo={},$.siginfo.algorithmOid=null,$.validity={},$.validity.notBefore=new Date,$.validity.notAfter=new Date,$.issuer={},$.issuer.getField=function(J){return f0($.issuer,J)},$.issuer.addField=function(J){kJ([J]),$.issuer.attributes.push(J)},$.issuer.attributes=[],$.issuer.hash=null,$.subject={},$.subject.getField=function(J){return f0($.subject,J)},$.subject.addField=function(J){kJ([J]),$.subject.attributes.push(J)},$.subject.attributes=[],$.subject.hash=null,$.extensions=[],$.publicKey=null,$.md=null,$.setSubject=function(J,X){if(kJ(J),$.subject.attributes=J,delete $.subject.uniqueId,X)$.subject.uniqueId=X;$.subject.hash=null},$.setIssuer=function(J,X){if(kJ(J),$.issuer.attributes=J,delete $.issuer.uniqueId,X)$.issuer.uniqueId=X;$.issuer.hash=null},$.setExtensions=function(J){for(var X=0;X<J.length;++X)c1(J[X],{cert:$});$.extensions=J},$.getExtension=function(J){if(typeof J==="string")J={name:J};var X=null,Q;for(var Y=0;X===null&&Y<$.extensions.length;++Y)if(Q=$.extensions[Y],J.id&&Q.id===J.id)X=Q;else if(J.name&&Q.name===J.name)X=Q;return X},$.sign=function(J,X){$.md=X||X$.md.sha1.create();var Q=P$[$.md.algorithm+"WithRSAEncryption"];if(!Q){var Y=Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw Y.algorithm=$.md.algorithm,Y}$.signatureOid=$.siginfo.algorithmOid=Q,$.tbsCertificate=g.getTBSCertificate($);var G=z.toDer($.tbsCertificate);$.md.update(G.getBytes()),$.signature=J.sign($.md)},$.verify=function(J){var X=!1;if(!$.issued(J)){var Q=J.issuer,Y=$.subject,G=Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw G.expectedIssuer=Y.attributes,G.actualIssuer=Q.attributes,G}var W=J.md;if(W===null){W=lY({signatureOid:J.signatureOid,type:"certificate"});var U=J.tbsCertificate||g.getTBSCertificate(J),M=z.toDer(U);W.update(M.getBytes())}if(W!==null)X=d1({certificate:$,md:W,signature:J.signature});return X},$.isIssuer=function(J){var X=!1,Q=$.issuer,Y=J.subject;if(Q.hash&&Y.hash)X=Q.hash===Y.hash;else if(Q.attributes.length===Y.attributes.length){X=!0;var G,W;for(var U=0;X&&U<Q.attributes.length;++U)if(G=Q.attributes[U],W=Y.attributes[U],G.type!==W.type||G.value!==W.value)X=!1}return X},$.issued=function(J){return J.isIssuer($)},$.generateSubjectKeyIdentifier=function(){return g.getPublicKeyFingerprint($.publicKey,{type:"RSAPublicKey"})},$.verifySubjectKeyIdentifier=function(){var J=P$.subjectKeyIdentifier;for(var X=0;X<$.extensions.length;++X){var Q=$.extensions[X];if(Q.id===J){var Y=$.generateSubjectKeyIdentifier().getBytes();return X$.util.hexToBytes(Q.subjectKeyIdentifier)===Y}}return!1},$};g.certificateFromAsn1=function($,J){var X={},Q=[];if(!z.validate($,yV,X,Q)){var Y=Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw Y.errors=Q,Y}var G=z.derToOid(X.publicKeyOid);if(G!==g.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var W=g.createCertificate();W.version=X.certVersion?X.certVersion.charCodeAt(0):0;var U=X$.util.createBuffer(X.certSerialNumber);W.serialNumber=U.toHex(),W.signatureOid=X$.asn1.derToOid(X.certSignatureOid),W.signatureParameters=mY(W.signatureOid,X.certSignatureParams,!0),W.siginfo.algorithmOid=X$.asn1.derToOid(X.certinfoSignatureOid),W.siginfo.parameters=mY(W.siginfo.algorithmOid,X.certinfoSignatureParams,!1),W.signature=X.certSignature;var M=[];if(X.certValidity1UTCTime!==void 0)M.push(z.utcTimeToDate(X.certValidity1UTCTime));if(X.certValidity2GeneralizedTime!==void 0)M.push(z.generalizedTimeToDate(X.certValidity2GeneralizedTime));if(X.certValidity3UTCTime!==void 0)M.push(z.utcTimeToDate(X.certValidity3UTCTime));if(X.certValidity4GeneralizedTime!==void 0)M.push(z.generalizedTimeToDate(X.certValidity4GeneralizedTime));if(M.length>2)throw Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(M.length<2)throw Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(W.validity.notBefore=M[0],W.validity.notAfter=M[1],W.tbsCertificate=X.tbsCertificate,J){W.md=lY({signatureOid:W.signatureOid,type:"certificate"});var O=z.toDer(W.tbsCertificate);W.md.update(O.getBytes())}var V=X$.md.sha1.create(),q=z.toDer(X.certIssuer);if(V.update(q.getBytes()),W.issuer.getField=function(K){return f0(W.issuer,K)},W.issuer.addField=function(K){kJ([K]),W.issuer.attributes.push(K)},W.issuer.attributes=g.RDNAttributesAsArray(X.certIssuer),X.certIssuerUniqueId)W.issuer.uniqueId=X.certIssuerUniqueId;W.issuer.hash=V.digest().toHex();var H=X$.md.sha1.create(),N=z.toDer(X.certSubject);if(H.update(N.getBytes()),W.subject.getField=function(K){return f0(W.subject,K)},W.subject.addField=function(K){kJ([K]),W.subject.attributes.push(K)},W.subject.attributes=g.RDNAttributesAsArray(X.certSubject),X.certSubjectUniqueId)W.subject.uniqueId=X.certSubjectUniqueId;if(W.subject.hash=H.digest().toHex(),X.certExtensions)W.extensions=g.certificateExtensionsFromAsn1(X.certExtensions);else W.extensions=[];return W.publicKey=g.publicKeyFromAsn1(X.subjectPublicKeyInfo),W};g.certificateExtensionsFromAsn1=function($){var J=[];for(var X=0;X<$.value.length;++X){var Q=$.value[X];for(var Y=0;Y<Q.value.length;++Y)J.push(g.certificateExtensionFromAsn1(Q.value[Y]))}return J};g.certificateExtensionFromAsn1=function($){var J={};if(J.id=z.derToOid($.value[0].value),J.critical=!1,$.value[1].type===z.Type.BOOLEAN)J.critical=$.value[1].value.charCodeAt(0)!==0,J.value=$.value[2].value;else J.value=$.value[1].value;if(J.id in P$){if(J.name=P$[J.id],J.name==="keyUsage"){var X=z.fromDer(J.value),Q=0,Y=0;if(X.value.length>1)Q=X.value.charCodeAt(1),Y=X.value.length>2?X.value.charCodeAt(2):0;J.digitalSignature=(Q&128)===128,J.nonRepudiation=(Q&64)===64,J.keyEncipherment=(Q&32)===32,J.dataEncipherment=(Q&16)===16,J.keyAgreement=(Q&8)===8,J.keyCertSign=(Q&4)===4,J.cRLSign=(Q&2)===2,J.encipherOnly=(Q&1)===1,J.decipherOnly=(Y&128)===128}else if(J.name==="basicConstraints"){var X=z.fromDer(J.value);if(X.value.length>0&&X.value[0].type===z.Type.BOOLEAN)J.cA=X.value[0].value.charCodeAt(0)!==0;else J.cA=!1;var G=null;if(X.value.length>0&&X.value[0].type===z.Type.INTEGER)G=X.value[0].value;else if(X.value.length>1)G=X.value[1].value;if(G!==null)J.pathLenConstraint=z.derToInteger(G)}else if(J.name==="extKeyUsage"){var X=z.fromDer(J.value);for(var W=0;W<X.value.length;++W){var U=z.derToOid(X.value[W].value);if(U in P$)J[P$[U]]=!0;else J[U]=!0}}else if(J.name==="nsCertType"){var X=z.fromDer(J.value),Q=0;if(X.value.length>1)Q=X.value.charCodeAt(1);J.client=(Q&128)===128,J.server=(Q&64)===64,J.email=(Q&32)===32,J.objsign=(Q&16)===16,J.reserved=(Q&8)===8,J.sslCA=(Q&4)===4,J.emailCA=(Q&2)===2,J.objCA=(Q&1)===1}else if(J.name==="subjectAltName"||J.name==="issuerAltName"){J.altNames=[];var M,X=z.fromDer(J.value);for(var O=0;O<X.value.length;++O){M=X.value[O];var V={type:M.type,value:M.value};switch(J.altNames.push(V),M.type){case 1:case 2:case 6:break;case 7:V.ip=X$.util.bytesToIP(M.value);break;case 8:V.oid=z.derToOid(M.value);break;default:}}}else if(J.name==="subjectKeyIdentifier"){var X=z.fromDer(J.value);J.subjectKeyIdentifier=X$.util.bytesToHex(X.value)}}return J};g.certificationRequestFromAsn1=function($,J){var X={},Q=[];if(!z.validate($,uV,X,Q)){var Y=Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw Y.errors=Q,Y}var G=z.derToOid(X.publicKeyOid);if(G!==g.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var W=g.createCertificationRequest();if(W.version=X.csrVersion?X.csrVersion.charCodeAt(0):0,W.signatureOid=X$.asn1.derToOid(X.csrSignatureOid),W.signatureParameters=mY(W.signatureOid,X.csrSignatureParams,!0),W.siginfo.algorithmOid=X$.asn1.derToOid(X.csrSignatureOid),W.siginfo.parameters=mY(W.siginfo.algorithmOid,X.csrSignatureParams,!1),W.signature=X.csrSignature,W.certificationRequestInfo=X.certificationRequestInfo,J){W.md=lY({signatureOid:W.signatureOid,type:"certification request"});var U=z.toDer(W.certificationRequestInfo);W.md.update(U.getBytes())}var M=X$.md.sha1.create();return W.subject.getField=function(O){return f0(W.subject,O)},W.subject.addField=function(O){kJ([O]),W.subject.attributes.push(O)},W.subject.attributes=g.RDNAttributesAsArray(X.certificationRequestInfoSubject,M),W.subject.hash=M.digest().toHex(),W.publicKey=g.publicKeyFromAsn1(X.subjectPublicKeyInfo),W.getAttribute=function(O){return f0(W,O)},W.addAttribute=function(O){kJ([O]),W.attributes.push(O)},W.attributes=g.CRIAttributesAsArray(X.certificationRequestInfoAttributes||[]),W};g.createCertificationRequest=function(){var $={};return $.version=0,$.signatureOid=null,$.signature=null,$.siginfo={},$.siginfo.algorithmOid=null,$.subject={},$.subject.getField=function(J){return f0($.subject,J)},$.subject.addField=function(J){kJ([J]),$.subject.attributes.push(J)},$.subject.attributes=[],$.subject.hash=null,$.publicKey=null,$.attributes=[],$.getAttribute=function(J){return f0($,J)},$.addAttribute=function(J){kJ([J]),$.attributes.push(J)},$.md=null,$.setSubject=function(J){kJ(J),$.subject.attributes=J,$.subject.hash=null},$.setAttributes=function(J){kJ(J),$.attributes=J},$.sign=function(J,X){$.md=X||X$.md.sha1.create();var Q=P$[$.md.algorithm+"WithRSAEncryption"];if(!Q){var Y=Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw Y.algorithm=$.md.algorithm,Y}$.signatureOid=$.siginfo.algorithmOid=Q,$.certificationRequestInfo=g.getCertificationRequestInfo($);var G=z.toDer($.certificationRequestInfo);$.md.update(G.getBytes()),$.signature=J.sign($.md)},$.verify=function(){var J=!1,X=$.md;if(X===null){X=lY({signatureOid:$.signatureOid,type:"certification request"});var Q=$.certificationRequestInfo||g.getCertificationRequestInfo($),Y=z.toDer(Q);X.update(Y.getBytes())}if(X!==null)J=d1({certificate:$,md:X,signature:$.signature});return J},$};function kQ($){var J=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[]),X,Q,Y=$.attributes;for(var G=0;G<Y.length;++G){X=Y[G];var W=X.value,U=z.Type.PRINTABLESTRING;if("valueTagClass"in X){if(U=X.valueTagClass,U===z.Type.UTF8)W=X$.util.encodeUtf8(W)}Q=z.create(z.Class.UNIVERSAL,z.Type.SET,!0,[z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(X.type).getBytes()),z.create(z.Class.UNIVERSAL,U,!1,W)])]),J.value.push(Q)}return J}function kJ($){var J;for(var X=0;X<$.length;++X){if(J=$[X],typeof J.name>"u"){if(J.type&&J.type in g.oids)J.name=g.oids[J.type];else if(J.shortName&&J.shortName in s$)J.name=g.oids[s$[J.shortName]]}if(typeof J.type>"u")if(J.name&&J.name in g.oids)J.type=g.oids[J.name];else{var Q=Error("Attribute type not specified.");throw Q.attribute=J,Q}if(typeof J.shortName>"u"){if(J.name&&J.name in s$)J.shortName=s$[J.name]}if(J.type===P$.extensionRequest){if(J.valueConstructed=!0,J.valueTagClass=z.Type.SEQUENCE,!J.value&&J.extensions){J.value=[];for(var Y=0;Y<J.extensions.length;++Y)J.value.push(g.certificateExtensionToAsn1(c1(J.extensions[Y])))}}if(typeof J.value>"u"){var Q=Error("Attribute value not specified.");throw Q.attribute=J,Q}}}function c1($,J){if(J=J||{},typeof $.name>"u"){if($.id&&$.id in g.oids)$.name=g.oids[$.id]}if(typeof $.id>"u")if($.name&&$.name in g.oids)$.id=g.oids[$.name];else{var X=Error("Extension ID not specified.");throw X.extension=$,X}if(typeof $.value<"u")return $;if($.name==="keyUsage"){var Q=0,Y=0,G=0;if($.digitalSignature)Y|=128,Q=7;if($.nonRepudiation)Y|=64,Q=6;if($.keyEncipherment)Y|=32,Q=5;if($.dataEncipherment)Y|=16,Q=4;if($.keyAgreement)Y|=8,Q=3;if($.keyCertSign)Y|=4,Q=2;if($.cRLSign)Y|=2,Q=1;if($.encipherOnly)Y|=1,Q=0;if($.decipherOnly)G|=128,Q=7;var W=String.fromCharCode(Q);if(G!==0)W+=String.fromCharCode(Y)+String.fromCharCode(G);else if(Y!==0)W+=String.fromCharCode(Y);$.value=z.create(z.Class.UNIVERSAL,z.Type.BITSTRING,!1,W)}else if($.name==="basicConstraints"){if($.value=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[]),$.cA)$.value.value.push(z.create(z.Class.UNIVERSAL,z.Type.BOOLEAN,!1,String.fromCharCode(255)));if("pathLenConstraint"in $)$.value.value.push(z.create(z.Class.UNIVERSAL,z.Type.INTEGER,!1,z.integerToDer($.pathLenConstraint).getBytes()))}else if($.name==="extKeyUsage"){$.value=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[]);var U=$.value.value;for(var M in $){if($[M]!==!0)continue;if(M in P$)U.push(z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(P$[M]).getBytes()));else if(M.indexOf(".")!==-1)U.push(z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(M).getBytes()))}}else if($.name==="nsCertType"){var Q=0,Y=0;if($.client)Y|=128,Q=7;if($.server)Y|=64,Q=6;if($.email)Y|=32,Q=5;if($.objsign)Y|=16,Q=4;if($.reserved)Y|=8,Q=3;if($.sslCA)Y|=4,Q=2;if($.emailCA)Y|=2,Q=1;if($.objCA)Y|=1,Q=0;var W=String.fromCharCode(Q);if(Y!==0)W+=String.fromCharCode(Y);$.value=z.create(z.Class.UNIVERSAL,z.Type.BITSTRING,!1,W)}else if($.name==="subjectAltName"||$.name==="issuerAltName"){$.value=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[]);var O;for(var V=0;V<$.altNames.length;++V){O=$.altNames[V];var W=O.value;if(O.type===7&&O.ip){if(W=X$.util.bytesFromIP(O.ip),W===null){var X=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw X.extension=$,X}}else if(O.type===8)if(O.oid)W=z.oidToDer(z.oidToDer(O.oid));else W=z.oidToDer(W);$.value.value.push(z.create(z.Class.CONTEXT_SPECIFIC,O.type,!1,W))}}else if($.name==="nsComment"&&J.cert){if(!/^[\x00-\x7F]*$/.test($.comment)||$.comment.length<1||$.comment.length>128)throw Error('Invalid "nsComment" content.');$.value=z.create(z.Class.UNIVERSAL,z.Type.IA5STRING,!1,$.comment)}else if($.name==="subjectKeyIdentifier"&&J.cert){var q=J.cert.generateSubjectKeyIdentifier();$.subjectKeyIdentifier=q.toHex(),$.value=z.create(z.Class.UNIVERSAL,z.Type.OCTETSTRING,!1,q.getBytes())}else if($.name==="authorityKeyIdentifier"&&J.cert){$.value=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[]);var U=$.value.value;if($.keyIdentifier){var H=$.keyIdentifier===!0?J.cert.generateSubjectKeyIdentifier().getBytes():$.keyIdentifier;U.push(z.create(z.Class.CONTEXT_SPECIFIC,0,!1,H))}if($.authorityCertIssuer){var N=[z.create(z.Class.CONTEXT_SPECIFIC,4,!0,[kQ($.authorityCertIssuer===!0?J.cert.issuer:$.authorityCertIssuer)])];U.push(z.create(z.Class.CONTEXT_SPECIFIC,1,!0,N))}if($.serialNumber){var K=X$.util.hexToBytes($.serialNumber===!0?J.cert.serialNumber:$.serialNumber);U.push(z.create(z.Class.CONTEXT_SPECIFIC,2,!1,K))}}else if($.name==="cRLDistributionPoints"){$.value=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[]);var U=$.value.value,L=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[]),A=z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[]),O;for(var V=0;V<$.altNames.length;++V){O=$.altNames[V];var W=O.value;if(O.type===7&&O.ip){if(W=X$.util.bytesFromIP(O.ip),W===null){var X=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw X.extension=$,X}}else if(O.type===8)if(O.oid)W=z.oidToDer(z.oidToDer(O.oid));else W=z.oidToDer(W);A.value.push(z.create(z.Class.CONTEXT_SPECIFIC,O.type,!1,W))}L.value.push(z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[A])),U.push(L)}if(typeof $.value>"u"){var X=Error("Extension value not specified.");throw X.extension=$,X}return $}function T8($,J){switch($){case P$["RSASSA-PSS"]:var X=[];if(J.hash.algorithmOid!==void 0)X.push(z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(J.hash.algorithmOid).getBytes()),z.create(z.Class.UNIVERSAL,z.Type.NULL,!1,"")])]));if(J.mgf.algorithmOid!==void 0)X.push(z.create(z.Class.CONTEXT_SPECIFIC,1,!0,[z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(J.mgf.algorithmOid).getBytes()),z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(J.mgf.hash.algorithmOid).getBytes()),z.create(z.Class.UNIVERSAL,z.Type.NULL,!1,"")])])]));if(J.saltLength!==void 0)X.push(z.create(z.Class.CONTEXT_SPECIFIC,2,!0,[z.create(z.Class.UNIVERSAL,z.Type.INTEGER,!1,z.integerToDer(J.saltLength).getBytes())]));return z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,X);default:return z.create(z.Class.UNIVERSAL,z.Type.NULL,!1,"")}}function gV($){var J=z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[]);if($.attributes.length===0)return J;var X=$.attributes;for(var Q=0;Q<X.length;++Q){var Y=X[Q],G=Y.value,W=z.Type.UTF8;if("valueTagClass"in Y)W=Y.valueTagClass;if(W===z.Type.UTF8)G=X$.util.encodeUtf8(G);var U=!1;if("valueConstructed"in Y)U=Y.valueConstructed;var M=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer(Y.type).getBytes()),z.create(z.Class.UNIVERSAL,z.Type.SET,!0,[z.create(z.Class.UNIVERSAL,W,U,G)])]);J.value.push(M)}return J}var mV=new Date("1950-01-01T00:00:00Z"),lV=new Date("2050-01-01T00:00:00Z");function l1($){if($>=mV&&$<lV)return z.create(z.Class.UNIVERSAL,z.Type.UTCTIME,!1,z.dateToUtcTime($));else return z.create(z.Class.UNIVERSAL,z.Type.GENERALIZEDTIME,!1,z.dateToGeneralizedTime($))}g.getTBSCertificate=function($){var J=l1($.validity.notBefore),X=l1($.validity.notAfter),Q=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.CONTEXT_SPECIFIC,0,!0,[z.create(z.Class.UNIVERSAL,z.Type.INTEGER,!1,z.integerToDer($.version).getBytes())]),z.create(z.Class.UNIVERSAL,z.Type.INTEGER,!1,X$.util.hexToBytes($.serialNumber)),z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer($.siginfo.algorithmOid).getBytes()),T8($.siginfo.algorithmOid,$.siginfo.parameters)]),kQ($.issuer),z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[J,X]),kQ($.subject),g.publicKeyToAsn1($.publicKey)]);if($.issuer.uniqueId)Q.value.push(z.create(z.Class.CONTEXT_SPECIFIC,1,!0,[z.create(z.Class.UNIVERSAL,z.Type.BITSTRING,!1,String.fromCharCode(0)+$.issuer.uniqueId)]));if($.subject.uniqueId)Q.value.push(z.create(z.Class.CONTEXT_SPECIFIC,2,!0,[z.create(z.Class.UNIVERSAL,z.Type.BITSTRING,!1,String.fromCharCode(0)+$.subject.uniqueId)]));if($.extensions.length>0)Q.value.push(g.certificateExtensionsToAsn1($.extensions));return Q};g.getCertificationRequestInfo=function($){var J=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.INTEGER,!1,z.integerToDer($.version).getBytes()),kQ($.subject),g.publicKeyToAsn1($.publicKey),gV($)]);return J};g.distinguishedNameToAsn1=function($){return kQ($)};g.certificateToAsn1=function($){var J=$.tbsCertificate||g.getTBSCertificate($);return z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[J,z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer($.signatureOid).getBytes()),T8($.signatureOid,$.signatureParameters)]),z.create(z.Class.UNIVERSAL,z.Type.BITSTRING,!1,String.fromCharCode(0)+$.signature)])};g.certificateExtensionsToAsn1=function($){var J=z.create(z.Class.CONTEXT_SPECIFIC,3,!0,[]),X=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[]);J.value.push(X);for(var Q=0;Q<$.length;++Q)X.value.push(g.certificateExtensionToAsn1($[Q]));return J};g.certificateExtensionToAsn1=function($){var J=z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[]);if(J.value.push(z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer($.id).getBytes())),$.critical)J.value.push(z.create(z.Class.UNIVERSAL,z.Type.BOOLEAN,!1,String.fromCharCode(255)));var X=$.value;if(typeof $.value!=="string")X=z.toDer(X).getBytes();return J.value.push(z.create(z.Class.UNIVERSAL,z.Type.OCTETSTRING,!1,X)),J};g.certificationRequestToAsn1=function($){var J=$.certificationRequestInfo||g.getCertificationRequestInfo($);return z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[J,z.create(z.Class.UNIVERSAL,z.Type.SEQUENCE,!0,[z.create(z.Class.UNIVERSAL,z.Type.OID,!1,z.oidToDer($.signatureOid).getBytes()),T8($.signatureOid,$.signatureParameters)]),z.create(z.Class.UNIVERSAL,z.Type.BITSTRING,!1,String.fromCharCode(0)+$.signature)])};g.createCaStore=function($){var J={certs:{}};J.getIssuer=function(W){var U=X(W.issuer);return U},J.addCertificate=function(W){if(typeof W==="string")W=X$.pki.certificateFromPem(W);if(Q(W.subject),!J.hasCertificate(W))if(W.subject.hash in J.certs){var U=J.certs[W.subject.hash];if(!X$.util.isArray(U))U=[U];U.push(W),J.certs[W.subject.hash]=U}else J.certs[W.subject.hash]=W},J.hasCertificate=function(W){if(typeof W==="string")W=X$.pki.certificateFromPem(W);var U=X(W.subject);if(!U)return!1;if(!X$.util.isArray(U))U=[U];var M=z.toDer(g.certificateToAsn1(W)).getBytes();for(var O=0;O<U.length;++O){var V=z.toDer(g.certificateToAsn1(U[O])).getBytes();if(M===V)return!0}return!1},J.listAllCertificates=function(){var W=[];for(var U in J.certs)if(J.certs.hasOwnProperty(U)){var M=J.certs[U];if(!X$.util.isArray(M))W.push(M);else for(var O=0;O<M.length;++O)W.push(M[O])}return W},J.removeCertificate=function(W){var U;if(typeof W==="string")W=X$.pki.certificateFromPem(W);if(Q(W.subject),!J.hasCertificate(W))return null;var M=X(W.subject);if(!X$.util.isArray(M))return U=J.certs[W.subject.hash],delete J.certs[W.subject.hash],U;var O=z.toDer(g.certificateToAsn1(W)).getBytes();for(var V=0;V<M.length;++V){var q=z.toDer(g.certificateToAsn1(M[V])).getBytes();if(O===q)U=M[V],M.splice(V,1)}if(M.length===0)delete J.certs[W.subject.hash];return U};function X(W){return Q(W),J.certs[W.hash]||null}function Q(W){if(!W.hash){var U=X$.md.sha1.create();W.attributes=g.RDNAttributesAsArray(kQ(W),U),W.hash=U.digest().toHex()}}if($)for(var Y=0;Y<$.length;++Y){var G=$[Y];J.addCertificate(G)}return J};g.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"};g.verifyCertificateChain=function($,J,X){if(typeof X==="function")X={verify:X};X=X||{},J=J.slice(0);var Q=J.slice(0),Y=X.validityCheckDate;if(typeof Y>"u")Y=new Date;var G=!0,W=null,U=0;do{var M=J.shift(),O=null,V=!1;if(Y){if(Y<M.validity.notBefore||Y>M.validity.notAfter)W={message:"Certificate is not valid yet or has expired.",error:g.certificateError.certificate_expired,notBefore:M.validity.notBefore,notAfter:M.validity.notAfter,now:Y}}if(W===null){if(O=J[0]||$.getIssuer(M),O===null){if(M.isIssuer(M))V=!0,O=M}if(O){var q=O;if(!X$.util.isArray(q))q=[q];var H=!1;while(!H&&q.length>0){O=q.shift();try{H=O.verify(M)}catch(w){}}if(!H)W={message:"Certificate signature is invalid.",error:g.certificateError.bad_certificate}}if(W===null&&(!O||V)&&!$.hasCertificate(M))W={message:"Certificate is not trusted.",error:g.certificateError.unknown_ca}}if(W===null&&O&&!M.isIssuer(O))W={message:"Certificate issuer is invalid.",error:g.certificateError.bad_certificate};if(W===null){var N={keyUsage:!0,basicConstraints:!0};for(var K=0;W===null&&K<M.extensions.length;++K){var L=M.extensions[K];if(L.critical&&!(L.name in N))W={message:"Certificate has an unsupported critical extension.",error:g.certificateError.unsupported_certificate}}}if(W===null&&(!G||J.length===0&&(!O||V))){var A=M.getExtension("basicConstraints"),D=M.getExtension("keyUsage");if(D!==null){if(!D.keyCertSign||A===null)W={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:g.certificateError.bad_certificate}}if(W===null&&A===null)W={message:"Certificate is missing basicConstraints extension and cannot be used as a CA.",error:g.certificateError.bad_certificate};if(W===null&&A!==null&&!A.cA)W={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:g.certificateError.bad_certificate};if(W===null&&D!==null&&"pathLenConstraint"in A){var S=U-1;if(S>A.pathLenConstraint)W={message:"Certificate basicConstraints pathLenConstraint violated.",error:g.certificateError.bad_certificate}}}var B=W===null?!0:W.error,C=X.verify?X.verify(B,U,Q):B;if(C===!0)W=null;else{if(B===!0)W={message:"The application rejected the certificate.",error:g.certificateError.bad_certificate};if(C||C===0){if(typeof C==="object"&&!X$.util.isArray(C)){if(C.message)W.message=C.message;if(C.error)W.error=C.error}else if(typeof C==="string")W.error=C}throw W}G=!1,++U}while(J.length>0);return!0}});var I8=q$((iF,o1)=>{var l$=F$();lJ();IQ();x0();B8();Z8();_J();wX();_Q();_$();pY();var{asn1:R,pki:D$}=l$,_X=o1.exports=l$.pkcs12=l$.pkcs12||{},i1={name:"ContentInfo",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:R.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},pV={name:"PFX",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:R.Class.UNIVERSAL,type:R.Type.INTEGER,constructed:!1,capture:"version"},i1,{name:"PFX.macData",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:!0,tagClass:R.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:R.Class.UNIVERSAL,type:R.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:R.Class.UNIVERSAL,type:R.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:R.Class.UNIVERSAL,type:R.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},dV={name:"SafeBag",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:R.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:R.Class.UNIVERSAL,type:R.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},cV={name:"Attribute",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:R.Class.UNIVERSAL,type:R.Type.SET,constructed:!0,capture:"values"}]},nV={name:"CertBag",tagClass:R.Class.UNIVERSAL,type:R.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:R.Class.UNIVERSAL,type:R.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:R.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:R.Class.UNIVERSAL,type:R.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function PX($,J,X,Q){var Y=[];for(var G=0;G<$.length;G++)for(var W=0;W<$[G].safeBags.length;W++){var U=$[G].safeBags[W];if(Q!==void 0&&U.type!==Q)continue;if(J===null){Y.push(U);continue}if(U.attributes[J]!==void 0&&U.attributes[J].indexOf(X)>=0)Y.push(U)}return Y}_X.pkcs12FromAsn1=function($,J,X){if(typeof J==="string")X=J,J=!0;else if(J===void 0)J=!0;var Q={},Y=[];if(!R.validate($,pV,Q,Y)){var G=Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw G.errors=G,G}var W={version:Q.version.charCodeAt(0),safeContents:[],getBags:function(A){var D={},S;if("localKeyId"in A)S=A.localKeyId;else if("localKeyIdHex"in A)S=l$.util.hexToBytes(A.localKeyIdHex);if(S===void 0&&!("friendlyName"in A)&&"bagType"in A)D[A.bagType]=PX(W.safeContents,null,null,A.bagType);if(S!==void 0)D.localKeyId=PX(W.safeContents,"localKeyId",S,A.bagType);if("friendlyName"in A)D.friendlyName=PX(W.safeContents,"friendlyName",A.friendlyName,A.bagType);return D},getBagsByFriendlyName:function(A,D){return PX(W.safeContents,"friendlyName",A,D)},getBagsByLocalKeyId:function(A,D){return PX(W.safeContents,"localKeyId",A,D)}};if(Q.version.charCodeAt(0)!==3){var G=Error("PKCS#12 PFX of version other than 3 not supported.");throw G.version=Q.version.charCodeAt(0),G}if(R.derToOid(Q.contentType)!==D$.oids.data){var G=Error("Only PKCS#12 PFX in password integrity mode supported.");throw G.oid=R.derToOid(Q.contentType),G}var U=Q.content.value[0];if(U.tagClass!==R.Class.UNIVERSAL||U.type!==R.Type.OCTETSTRING)throw Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(U=S8(U),Q.mac){var M=null,O=0,V=R.derToOid(Q.macAlgorithm);switch(V){case D$.oids.sha1:M=l$.md.sha1.create(),O=20;break;case D$.oids.sha256:M=l$.md.sha256.create(),O=32;break;case D$.oids.sha384:M=l$.md.sha384.create(),O=48;break;case D$.oids.sha512:M=l$.md.sha512.create(),O=64;break;case D$.oids.md5:M=l$.md.md5.create(),O=16;break}if(M===null)throw Error("PKCS#12 uses unsupported MAC algorithm: "+V);var q=new l$.util.ByteBuffer(Q.macSalt),H="macIterations"in Q?parseInt(l$.util.bytesToHex(Q.macIterations),16):1,N=_X.generateKey(X,q,3,H,O,M),K=l$.hmac.create();K.start(M,N),K.update(U.value);var L=K.getMac();if(L.getBytes()!==Q.macDigest)throw Error("PKCS#12 MAC could not be verified. Invalid password?")}else if(Array.isArray($.value)&&$.value.length>2)throw Error("Invalid PKCS#12. macData field present but MAC was not validated.");return iV(W,U.value,J,X),W};function S8($){if($.composed||$.constructed){var J=l$.util.createBuffer();for(var X=0;X<$.value.length;++X)J.putBytes($.value[X].value);$.composed=$.constructed=!1,$.value=J.getBytes()}return $}function iV($,J,X,Q){if(J=R.fromDer(J,X),J.tagClass!==R.Class.UNIVERSAL||J.type!==R.Type.SEQUENCE||J.constructed!==!0)throw Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var Y=0;Y<J.value.length;Y++){var G=J.value[Y],W={},U=[];if(!R.validate(G,i1,W,U)){var M=Error("Cannot read ContentInfo.");throw M.errors=U,M}var O={encrypted:!1},V=null,q=W.content.value[0];switch(R.derToOid(W.contentType)){case D$.oids.data:if(q.tagClass!==R.Class.UNIVERSAL||q.type!==R.Type.OCTETSTRING)throw Error("PKCS#12 SafeContents Data is not an OCTET STRING.");V=S8(q).value;break;case D$.oids.encryptedData:V=oV(q,Q),O.encrypted=!0;break;default:var M=Error("Unsupported PKCS#12 contentType.");throw M.contentType=R.derToOid(W.contentType),M}O.safeBags=aV(V,X,Q),$.safeContents.push(O)}}function oV($,J){var X={},Q=[];if(!R.validate($,l$.pkcs7.asn1.encryptedDataValidator,X,Q)){var Y=Error("Cannot read EncryptedContentInfo.");throw Y.errors=Q,Y}var G=R.derToOid(X.contentType);if(G!==D$.oids.data){var Y=Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw Y.oid=G,Y}G=R.derToOid(X.encAlgorithm);var W=D$.pbe.getCipher(G,X.encParameter,J),U=S8(X.encryptedContentAsn1),M=l$.util.createBuffer(U.value);if(W.update(M),!W.finish())throw Error("Failed to decrypt PKCS#12 SafeContents.");return W.output.getBytes()}function aV($,J,X){if(!J&&$.length===0)return[];if($=R.fromDer($,J),$.tagClass!==R.Class.UNIVERSAL||$.type!==R.Type.SEQUENCE||$.constructed!==!0)throw Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");var Q=[];for(var Y=0;Y<$.value.length;Y++){var G=$.value[Y],W={},U=[];if(!R.validate(G,dV,W,U)){var M=Error("Cannot read SafeBag.");throw M.errors=U,M}var O={type:R.derToOid(W.bagId),attributes:sV(W.bagAttributes)};Q.push(O);var V,q,H=W.bagValue.value[0];switch(O.type){case D$.oids.pkcs8ShroudedKeyBag:if(H=D$.decryptPrivateKeyInfo(H,X),H===null)throw Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case D$.oids.keyBag:try{O.key=D$.privateKeyFromAsn1(H)}catch(K){O.key=null,O.asn1=H}continue;case D$.oids.certBag:V=nV,q=function(){if(R.derToOid(W.certId)!==D$.oids.x509Certificate){var K=Error("Unsupported certificate type, only X.509 supported.");throw K.oid=R.derToOid(W.certId),K}var L=R.fromDer(W.cert,J);try{O.cert=D$.certificateFromAsn1(L,!0)}catch(A){O.cert=null,O.asn1=L}};break;default:var M=Error("Unsupported PKCS#12 SafeBag type.");throw M.oid=O.type,M}if(V!==void 0&&!R.validate(H,V,W,U)){var M=Error("Cannot read PKCS#12 "+V.name);throw M.errors=U,M}q()}return Q}function sV($){var J={};if($!==void 0)for(var X=0;X<$.length;++X){var Q={},Y=[];if(!R.validate($[X],cV,Q,Y)){var G=Error("Cannot read PKCS#12 BagAttribute.");throw G.errors=Y,G}var W=R.derToOid(Q.oid);if(D$.oids[W]===void 0)continue;J[D$.oids[W]]=[];for(var U=0;U<Q.values.length;++U)J[D$.oids[W]].push(Q.values[U].value)}return J}_X.toPkcs12Asn1=function($,J,X,Q){if(Q=Q||{},Q.saltSize=Q.saltSize||8,Q.count=Q.count||2048,Q.algorithm=Q.algorithm||Q.encAlgorithm||"aes128",!("useMac"in Q))Q.useMac=!0;if(!("localKeyId"in Q))Q.localKeyId=null;if(!("generateLocalKeyId"in Q))Q.generateLocalKeyId=!0;var Y=Q.localKeyId,G;if(Y!==null)Y=l$.util.hexToBytes(Y);else if(Q.generateLocalKeyId)if(J){var W=l$.util.isArray(J)?J[0]:J;if(typeof W==="string")W=D$.certificateFromPem(W);var U=l$.md.sha1.create();U.update(R.toDer(D$.certificateToAsn1(W)).getBytes()),Y=U.digest().getBytes()}else Y=l$.random.getBytes(20);var M=[];if(Y!==null)M.push(R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.localKeyId).getBytes()),R.create(R.Class.UNIVERSAL,R.Type.SET,!0,[R.create(R.Class.UNIVERSAL,R.Type.OCTETSTRING,!1,Y)])]));if("friendlyName"in Q)M.push(R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.friendlyName).getBytes()),R.create(R.Class.UNIVERSAL,R.Type.SET,!0,[R.create(R.Class.UNIVERSAL,R.Type.BMPSTRING,!1,Q.friendlyName)])]));if(M.length>0)G=R.create(R.Class.UNIVERSAL,R.Type.SET,!0,M);var O=[],V=[];if(J!==null)if(l$.util.isArray(J))V=J;else V=[J];var q=[];for(var H=0;H<V.length;++H){if(J=V[H],typeof J==="string")J=D$.certificateFromPem(J);var N=H===0?G:void 0,K=D$.certificateToAsn1(J),L=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.certBag).getBytes()),R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.x509Certificate).getBytes()),R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[R.create(R.Class.UNIVERSAL,R.Type.OCTETSTRING,!1,R.toDer(K).getBytes())])])]),N]);q.push(L)}if(q.length>0){var A=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,q),D=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.data).getBytes()),R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[R.create(R.Class.UNIVERSAL,R.Type.OCTETSTRING,!1,R.toDer(A).getBytes())])]);O.push(D)}var S=null;if($!==null){var B=D$.wrapRsaPrivateKey(D$.privateKeyToAsn1($));if(X===null)S=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.keyBag).getBytes()),R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[B]),G]);else S=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.pkcs8ShroudedKeyBag).getBytes()),R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[D$.encryptPrivateKeyInfo(B,X,Q)]),G]);var C=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[S]),w=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.data).getBytes()),R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[R.create(R.Class.UNIVERSAL,R.Type.OCTETSTRING,!1,R.toDer(C).getBytes())])]);O.push(w)}var P=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,O),l;if(Q.useMac){var U=l$.md.sha1.create(),$$=new l$.util.ByteBuffer(l$.random.getBytes(Q.saltSize)),y=Q.count,$=_X.generateKey(X,$$,3,y,20),n=l$.hmac.create();n.start(U,$),n.update(R.toDer(P).getBytes());var Y$=n.getMac();l=R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.sha1).getBytes()),R.create(R.Class.UNIVERSAL,R.Type.NULL,!1,"")]),R.create(R.Class.UNIVERSAL,R.Type.OCTETSTRING,!1,Y$.getBytes())]),R.create(R.Class.UNIVERSAL,R.Type.OCTETSTRING,!1,$$.getBytes()),R.create(R.Class.UNIVERSAL,R.Type.INTEGER,!1,R.integerToDer(y).getBytes())])}return R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.INTEGER,!1,R.integerToDer(3).getBytes()),R.create(R.Class.UNIVERSAL,R.Type.SEQUENCE,!0,[R.create(R.Class.UNIVERSAL,R.Type.OID,!1,R.oidToDer(D$.oids.data).getBytes()),R.create(R.Class.CONTEXT_SPECIFIC,0,!0,[R.create(R.Class.UNIVERSAL,R.Type.OCTETSTRING,!1,R.toDer(P).getBytes())])]),l])};_X.generateKey=l$.pbe.generatePkcs12Key});var w8=q$((oF,a1)=>{var y0=F$();lJ();x0();Z8();YQ();vY();I8();gY();wX();_$();pY();var C8=y0.asn1,fQ=a1.exports=y0.pki=y0.pki||{};fQ.pemToDer=function($){var J=y0.pem.decode($)[0];if(J.procType&&J.procType.type==="ENCRYPTED")throw Error("Could not convert PEM to DER; PEM is encrypted.");return y0.util.createBuffer(J.body)};fQ.privateKeyFromPem=function($){var J=y0.pem.decode($)[0];if(J.type!=="PRIVATE KEY"&&J.type!=="RSA PRIVATE KEY"){var X=Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw X.headerType=J.type,X}if(J.procType&&J.procType.type==="ENCRYPTED")throw Error("Could not convert private key from PEM; PEM is encrypted.");var Q=C8.fromDer(J.body);return fQ.privateKeyFromAsn1(Q)};fQ.privateKeyToPem=function($,J){var X={type:"RSA PRIVATE KEY",body:C8.toDer(fQ.privateKeyToAsn1($)).getBytes()};return y0.pem.encode(X,{maxline:J})};fQ.privateKeyInfoToPem=function($,J){var X={type:"PRIVATE KEY",body:C8.toDer($).getBytes()};return y0.pem.encode(X,{maxline:J})}});var f8=q$((aF,XW)=>{var f=F$();lJ();IQ();wY();YQ();w8();_J();_Q();_$();var nY=function($,J,X,Q){var Y=f.util.createBuffer(),G=$.length>>1,W=G+($.length&1),U=$.substr(0,W),M=$.substr(G,W),O=f.util.createBuffer(),V=f.hmac.create();X=J+X;var q=Math.ceil(Q/16),H=Math.ceil(Q/20);V.start("MD5",U);var N=f.util.createBuffer();O.putBytes(X);for(var K=0;K<q;++K)V.start(null,null),V.update(O.getBytes()),O.putBuffer(V.digest()),V.start(null,null),V.update(O.bytes()+X),N.putBuffer(V.digest());V.start("SHA1",M);var L=f.util.createBuffer();O.clear(),O.putBytes(X);for(var K=0;K<H;++K)V.start(null,null),V.update(O.getBytes()),O.putBuffer(V.digest()),V.start(null,null),V.update(O.bytes()+X),L.putBuffer(V.digest());return Y.putBytes(f.util.xorBytes(N.getBytes(),L.getBytes(),Q)),Y},rV=function($,J,X){var Q=f.hmac.create();Q.start("SHA1",$);var Y=f.util.createBuffer();return Y.putInt32(J[0]),Y.putInt32(J[1]),Y.putByte(X.type),Y.putByte(X.version.major),Y.putByte(X.version.minor),Y.putInt16(X.length),Y.putBytes(X.fragment.bytes()),Q.update(Y.getBytes()),Q.digest().getBytes()},tV=function($,J,X){var Q=!1;try{var Y=$.deflate(J.fragment.getBytes());J.fragment=f.util.createBuffer(Y),J.length=Y.length,Q=!0}catch(G){}return Q},eV=function($,J,X){var Q=!1;try{var Y=$.inflate(J.fragment.getBytes());J.fragment=f.util.createBuffer(Y),J.length=Y.length,Q=!0}catch(G){}return Q},IJ=function($,J){var X=0;switch(J){case 1:X=$.getByte();break;case 2:X=$.getInt16();break;case 3:X=$.getInt24();break;case 4:X=$.getInt32();break}return f.util.createBuffer($.getBytes(X))},fJ=function($,J,X){$.putInt(X.length(),J<<3),$.putBuffer(X)},F={};F.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};F.SupportedVersions=[F.Versions.TLS_1_1,F.Versions.TLS_1_0];F.Version=F.SupportedVersions[0];F.MaxFragment=15360;F.ConnectionEnd={server:0,client:1};F.PRFAlgorithm={tls_prf_sha256:0};F.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};F.CipherType={stream:0,block:1,aead:2};F.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};F.CompressionMethod={none:0,deflate:1};F.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};F.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20};F.Alert={};F.Alert.Level={warning:1,fatal:2};F.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_denied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100};F.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};F.CipherSuites={};F.getCipherSuite=function($){var J=null;for(var X in F.CipherSuites){var Q=F.CipherSuites[X];if(Q.id[0]===$.charCodeAt(0)&&Q.id[1]===$.charCodeAt(1)){J=Q;break}}return J};F.handleUnexpected=function($,J){var X=!$.open&&$.entity===F.ConnectionEnd.client;if(!X)$.error($,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.unexpected_message}})};F.handleHelloRequest=function($,J,X){if(!$.handshaking&&$.handshakes>0)F.queue($,F.createAlert($,{level:F.Alert.Level.warning,description:F.Alert.Description.no_renegotiation})),F.flush($);$.process()};F.parseHelloMessage=function($,J,X){var Q=null,Y=$.entity===F.ConnectionEnd.client;if(X<38)$.error($,{message:Y?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.illegal_parameter}});else{var G=J.fragment,W=G.length();if(Q={version:{major:G.getByte(),minor:G.getByte()},random:f.util.createBuffer(G.getBytes(32)),session_id:IJ(G,1),extensions:[]},Y)Q.cipher_suite=G.getBytes(2),Q.compression_method=G.getByte();else Q.cipher_suites=IJ(G,2),Q.compression_methods=IJ(G,1);if(W=X-(W-G.length()),W>0){var U=IJ(G,2);while(U.length()>0)Q.extensions.push({type:[U.getByte(),U.getByte()],data:IJ(U,2)});if(!Y)for(var M=0;M<Q.extensions.length;++M){var O=Q.extensions[M];if(O.type[0]===0&&O.type[1]===0){var V=IJ(O.data,2);while(V.length()>0){var q=V.getByte();if(q!==0)break;$.session.extensions.server_name.serverNameList.push(IJ(V,2).getBytes())}}}}if($.session.version){if(Q.version.major!==$.session.version.major||Q.version.minor!==$.session.version.minor)return $.error($,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.protocol_version}})}if(Y)$.session.cipherSuite=F.getCipherSuite(Q.cipher_suite);else{var H=f.util.createBuffer(Q.cipher_suites.bytes());while(H.length()>0)if($.session.cipherSuite=F.getCipherSuite(H.getBytes(2)),$.session.cipherSuite!==null)break}if($.session.cipherSuite===null)return $.error($,{message:"No cipher suites in common.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.handshake_failure},cipherSuite:f.util.bytesToHex(Q.cipher_suite)});if(Y)$.session.compressionMethod=Q.compression_method;else $.session.compressionMethod=F.CompressionMethod.none}return Q};F.createSecurityParameters=function($,J){var X=$.entity===F.ConnectionEnd.client,Q=J.random.bytes(),Y=X?$.session.sp.client_random:Q,G=X?Q:F.createRandom().getBytes();$.session.sp={entity:$.entity,prf_algorithm:F.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:$.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:Y,server_random:G}};F.handleServerHello=function($,J,X){var Q=F.parseHelloMessage($,J,X);if($.fail)return;if(Q.version.minor<=$.version.minor)$.version.minor=Q.version.minor;else return $.error($,{message:"Incompatible TLS version.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.protocol_version}});$.session.version=$.version;var Y=Q.session_id.bytes();if(Y.length>0&&Y===$.session.id)$.expect=t1,$.session.resuming=!0,$.session.sp.server_random=Q.random.bytes();else $.expect=Jq,$.session.resuming=!1,F.createSecurityParameters($,Q);$.session.id=Y,$.process()};F.handleClientHello=function($,J,X){var Q=F.parseHelloMessage($,J,X);if($.fail)return;var Y=Q.session_id.bytes(),G=null;if($.sessionCache){if(G=$.sessionCache.getSession(Y),G===null)Y="";else if(G.version.major!==Q.version.major||G.version.minor>Q.version.minor)G=null,Y=""}if(Y.length===0)Y=f.random.getBytes(32);if($.session.id=Y,$.session.clientHelloVersion=Q.version,$.session.sp={},G)$.version=$.session.version=G.version,$.session.sp=G.sp;else{var W;for(var U=1;U<F.SupportedVersions.length;++U)if(W=F.SupportedVersions[U],W.minor<=Q.version.minor)break;$.version={major:W.major,minor:W.minor},$.session.version=$.version}if(G!==null)$.expect=v8,$.session.resuming=!0,$.session.sp.client_random=Q.random.bytes();else $.expect=$.verifyClient!==!1?Mq:x8,$.session.resuming=!1,F.createSecurityParameters($,Q);if($.open=!0,F.queue($,F.createRecord($,{type:F.ContentType.handshake,data:F.createServerHello($)})),$.session.resuming)F.queue($,F.createRecord($,{type:F.ContentType.change_cipher_spec,data:F.createChangeCipherSpec()})),$.state.pending=F.createConnectionState($),$.state.current.write=$.state.pending.write,F.queue($,F.createRecord($,{type:F.ContentType.handshake,data:F.createFinished($)}));else if(F.queue($,F.createRecord($,{type:F.ContentType.handshake,data:F.createCertificate($)})),!$.fail){if(F.queue($,F.createRecord($,{type:F.ContentType.handshake,data:F.createServerKeyExchange($)})),$.verifyClient!==!1)F.queue($,F.createRecord($,{type:F.ContentType.handshake,data:F.createCertificateRequest($)}));F.queue($,F.createRecord($,{type:F.ContentType.handshake,data:F.createServerHelloDone($)}))}F.flush($),$.process()};F.handleCertificate=function($,J,X){if(X<3)return $.error($,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.illegal_parameter}});var Q=J.fragment,Y={certificate_list:IJ(Q,3)},G,W,U=[];try{while(Y.certificate_list.length()>0)G=IJ(Y.certificate_list,3),W=f.asn1.fromDer(G),G=f.pki.certificateFromAsn1(W,!0),U.push(G)}catch(O){return $.error($,{message:"Could not parse certificate list.",cause:O,send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.bad_certificate}})}var M=$.entity===F.ConnectionEnd.client;if((M||$.verifyClient===!0)&&U.length===0)$.error($,{message:M?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.illegal_parameter}});else if(U.length===0)$.expect=M?s1:x8;else{if(M)$.session.serverCertificate=U[0];else $.session.clientCertificate=U[0];if(F.verifyCertificateChain($,U))$.expect=M?s1:x8}$.process()};F.handleServerKeyExchange=function($,J,X){if(X>0)return $.error($,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.unsupported_certificate}});$.expect=Qq,$.process()};F.handleClientKeyExchange=function($,J,X){if(X<48)return $.error($,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.unsupported_certificate}});var Q=J.fragment,Y={enc_pre_master_secret:IJ(Q,2).getBytes()},G=null;if($.getPrivateKey)try{G=$.getPrivateKey($,$.session.serverCertificate),G=f.pki.privateKeyFromPem(G)}catch(M){$.error($,{message:"Could not get private key.",cause:M,send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.internal_error}})}if(G===null)return $.error($,{message:"No private key set.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.internal_error}});try{var W=$.session.sp;W.pre_master_secret=G.decrypt(Y.enc_pre_master_secret);var U=$.session.clientHelloVersion;if(U.major!==W.pre_master_secret.charCodeAt(0)||U.minor!==W.pre_master_secret.charCodeAt(1))throw Error("TLS version rollback attack detected.")}catch(M){W.pre_master_secret=f.random.getBytes(48)}if($.expect=v8,$.session.clientCertificate!==null)$.expect=Oq;$.process()};F.handleCertificateRequest=function($,J,X){if(X<3)return $.error($,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.illegal_parameter}});var Q=J.fragment,Y={certificate_types:IJ(Q,1),certificate_authorities:IJ(Q,2)};$.session.certificateRequest=Y,$.expect=Xq,$.process()};F.handleCertificateVerify=function($,J,X){if(X<2)return $.error($,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.illegal_parameter}});var Q=J.fragment;Q.read-=4;var Y=Q.bytes();Q.read+=4;var G={signature:IJ(Q,2).getBytes()},W=f.util.createBuffer();W.putBuffer($.session.md5.digest()),W.putBuffer($.session.sha1.digest()),W=W.getBytes();try{var U=$.session.clientCertificate;if(!U.publicKey.verify(W,G.signature,"NONE"))throw Error("CertificateVerify signature does not match.");$.session.md5.update(Y),$.session.sha1.update(Y)}catch(M){return $.error($,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.handshake_failure}})}$.expect=v8,$.process()};F.handleServerHelloDone=function($,J,X){if(X>0)return $.error($,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.record_overflow}});if($.serverCertificate===null){var Q={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.insufficient_security}},Y=0,G=$.verify($,Q.alert.description,Y,[]);if(G!==!0){if(G||G===0){if(typeof G==="object"&&!f.util.isArray(G)){if(G.message)Q.message=G.message;if(G.alert)Q.alert.description=G.alert}else if(typeof G==="number")Q.alert.description=G}return $.error($,Q)}}if($.session.certificateRequest!==null)J=F.createRecord($,{type:F.ContentType.handshake,data:F.createCertificate($)}),F.queue($,J);J=F.createRecord($,{type:F.ContentType.handshake,data:F.createClientKeyExchange($)}),F.queue($,J),$.expect=Wq;var W=function(U,M){if(U.session.certificateRequest!==null&&U.session.clientCertificate!==null)F.queue(U,F.createRecord(U,{type:F.ContentType.handshake,data:F.createCertificateVerify(U,M)}));F.queue(U,F.createRecord(U,{type:F.ContentType.change_cipher_spec,data:F.createChangeCipherSpec()})),U.state.pending=F.createConnectionState(U),U.state.current.write=U.state.pending.write,F.queue(U,F.createRecord(U,{type:F.ContentType.handshake,data:F.createFinished(U)})),U.expect=t1,F.flush(U),U.process()};if($.session.certificateRequest===null||$.session.clientCertificate===null)return W($,null);F.getClientSignature($,W)};F.handleChangeCipherSpec=function($,J){if(J.fragment.getByte()!==1)return $.error($,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.illegal_parameter}});var X=$.entity===F.ConnectionEnd.client;if($.session.resuming&&X||!$.session.resuming&&!X)$.state.pending=F.createConnectionState($);if($.state.current.read=$.state.pending.read,!$.session.resuming&&X||$.session.resuming&&!X)$.state.pending=null;$.expect=X?Yq:Vq,$.process()};F.handleFinished=function($,J,X){var Q=J.fragment;Q.read-=4;var Y=Q.bytes();Q.read+=4;var G=J.fragment.getBytes();Q=f.util.createBuffer(),Q.putBuffer($.session.md5.digest()),Q.putBuffer($.session.sha1.digest());var W=$.entity===F.ConnectionEnd.client,U=W?"server finished":"client finished",M=$.session.sp,O=12,V=nY;if(Q=V(M.master_secret,U,Q.getBytes(),O),Q.getBytes()!==G)return $.error($,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.decrypt_error}});if($.session.md5.update(Y),$.session.sha1.update(Y),$.session.resuming&&W||!$.session.resuming&&!W)F.queue($,F.createRecord($,{type:F.ContentType.change_cipher_spec,data:F.createChangeCipherSpec()})),$.state.current.write=$.state.pending.write,$.state.pending=null,F.queue($,F.createRecord($,{type:F.ContentType.handshake,data:F.createFinished($)}));$.expect=W?Gq:qq,$.handshaking=!1,++$.handshakes,$.peerCertificate=W?$.session.serverCertificate:$.session.clientCertificate,F.flush($),$.isConnected=!0,$.connected($),$.process()};F.handleAlert=function($,J){var X=J.fragment,Q={level:X.getByte(),description:X.getByte()},Y;switch(Q.description){case F.Alert.Description.close_notify:Y="Connection closed.";break;case F.Alert.Description.unexpected_message:Y="Unexpected message.";break;case F.Alert.Description.bad_record_mac:Y="Bad record MAC.";break;case F.Alert.Description.decryption_failed:Y="Decryption failed.";break;case F.Alert.Description.record_overflow:Y="Record overflow.";break;case F.Alert.Description.decompression_failure:Y="Decompression failed.";break;case F.Alert.Description.handshake_failure:Y="Handshake failure.";break;case F.Alert.Description.bad_certificate:Y="Bad certificate.";break;case F.Alert.Description.unsupported_certificate:Y="Unsupported certificate.";break;case F.Alert.Description.certificate_revoked:Y="Certificate revoked.";break;case F.Alert.Description.certificate_expired:Y="Certificate expired.";break;case F.Alert.Description.certificate_unknown:Y="Certificate unknown.";break;case F.Alert.Description.illegal_parameter:Y="Illegal parameter.";break;case F.Alert.Description.unknown_ca:Y="Unknown certificate authority.";break;case F.Alert.Description.access_denied:Y="Access denied.";break;case F.Alert.Description.decode_error:Y="Decode error.";break;case F.Alert.Description.decrypt_error:Y="Decrypt error.";break;case F.Alert.Description.export_restriction:Y="Export restriction.";break;case F.Alert.Description.protocol_version:Y="Unsupported protocol version.";break;case F.Alert.Description.insufficient_security:Y="Insufficient security.";break;case F.Alert.Description.internal_error:Y="Internal error.";break;case F.Alert.Description.user_canceled:Y="User canceled.";break;case F.Alert.Description.no_renegotiation:Y="Renegotiation not supported.";break;default:Y="Unknown error.";break}if(Q.description===F.Alert.Description.close_notify)return $.close();$.error($,{message:Y,send:!1,origin:$.entity===F.ConnectionEnd.client?"server":"client",alert:Q}),$.process()};F.handleHandshake=function($,J){var X=J.fragment,Q=X.getByte(),Y=X.getInt24();if(Y>X.length())return $.fragmented=J,J.fragment=f.util.createBuffer(),X.read-=4,$.process();$.fragmented=null,X.read-=4;var G=X.bytes(Y+4);if(X.read+=4,Q in cY[$.entity][$.expect]){if($.entity===F.ConnectionEnd.server&&!$.open&&!$.fail)$.handshaking=!0,$.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:f.md.md5.create(),sha1:f.md.sha1.create()};if(Q!==F.HandshakeType.hello_request&&Q!==F.HandshakeType.certificate_verify&&Q!==F.HandshakeType.finished)$.session.md5.update(G),$.session.sha1.update(G);cY[$.entity][$.expect][Q]($,J,Y)}else F.handleUnexpected($,J)};F.handleApplicationData=function($,J){$.data.putBuffer(J.fragment),$.dataReady($),$.process()};F.handleHeartbeat=function($,J){var X=J.fragment,Q=X.getByte(),Y=X.getInt16(),G=X.getBytes(Y);if(Q===F.HeartbeatMessageType.heartbeat_request){if($.handshaking||Y>G.length)return $.process();F.queue($,F.createRecord($,{type:F.ContentType.heartbeat,data:F.createHeartbeat(F.HeartbeatMessageType.heartbeat_response,G)})),F.flush($)}else if(Q===F.HeartbeatMessageType.heartbeat_response){if(G!==$.expectedHeartbeatPayload)return $.process();if($.heartbeatReceived)$.heartbeatReceived($,f.util.createBuffer(G))}$.process()};var $q=0,Jq=1,s1=2,Qq=3,Xq=4,t1=5,Yq=6,Gq=7,Wq=8,Uq=0,Mq=1,x8=2,Oq=3,v8=4,Vq=5,qq=6,E=F.handleUnexpected,e1=F.handleChangeCipherSpec,HJ=F.handleAlert,RJ=F.handleHandshake,$W=F.handleApplicationData,KJ=F.handleHeartbeat,k8=[];k8[F.ConnectionEnd.client]=[[E,HJ,RJ,E,KJ],[E,HJ,RJ,E,KJ],[E,HJ,RJ,E,KJ],[E,HJ,RJ,E,KJ],[E,HJ,RJ,E,KJ],[e1,HJ,E,E,KJ],[E,HJ,RJ,E,KJ],[E,HJ,RJ,$W,KJ],[E,HJ,RJ,E,KJ]];k8[F.ConnectionEnd.server]=[[E,HJ,RJ,E,KJ],[E,HJ,RJ,E,KJ],[E,HJ,RJ,E,KJ],[E,HJ,RJ,E,KJ],[e1,HJ,E,E,KJ],[E,HJ,RJ,E,KJ],[E,HJ,RJ,$W,KJ],[E,HJ,RJ,E,KJ]];var{handleHelloRequest:b0,handleServerHello:Hq,handleCertificate:JW,handleServerKeyExchange:r1,handleCertificateRequest:P8,handleServerHelloDone:dY,handleFinished:QW}=F,cY=[];cY[F.ConnectionEnd.client]=[[E,E,Hq,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E],[b0,E,E,E,E,E,E,E,E,E,E,JW,r1,P8,dY,E,E,E,E,E,E],[b0,E,E,E,E,E,E,E,E,E,E,E,r1,P8,dY,E,E,E,E,E,E],[b0,E,E,E,E,E,E,E,E,E,E,E,E,P8,dY,E,E,E,E,E,E],[b0,E,E,E,E,E,E,E,E,E,E,E,E,E,dY,E,E,E,E,E,E],[b0,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E],[b0,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,QW],[b0,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E],[b0,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E]];var{handleClientHello:Kq,handleClientKeyExchange:zq,handleCertificateVerify:Eq}=F;cY[F.ConnectionEnd.server]=[[E,Kq,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E],[E,E,E,E,E,E,E,E,E,E,E,JW,E,E,E,E,E,E,E,E,E],[E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,zq,E,E,E,E],[E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,Eq,E,E,E,E,E],[E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E],[E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,QW],[E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E],[E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E]];F.generateKeys=function($,J){var X=nY,Q=J.client_random+J.server_random;if(!$.session.resuming)J.master_secret=X(J.pre_master_secret,"master secret",Q,48).bytes(),J.pre_master_secret=null;Q=J.server_random+J.client_random;var Y=2*J.mac_key_length+2*J.enc_key_length,G=$.version.major===F.Versions.TLS_1_0.major&&$.version.minor===F.Versions.TLS_1_0.minor;if(G)Y+=2*J.fixed_iv_length;var W=X(J.master_secret,"key expansion",Q,Y),U={client_write_MAC_key:W.getBytes(J.mac_key_length),server_write_MAC_key:W.getBytes(J.mac_key_length),client_write_key:W.getBytes(J.enc_key_length),server_write_key:W.getBytes(J.enc_key_length)};if(G)U.client_write_IV=W.getBytes(J.fixed_iv_length),U.server_write_IV=W.getBytes(J.fixed_iv_length);return U};F.createConnectionState=function($){var J=$.entity===F.ConnectionEnd.client,X=function(){var G={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(W){return!0},compressionState:null,compressFunction:function(W){return!0},updateSequenceNumber:function(){if(G.sequenceNumber[1]===4294967295)G.sequenceNumber[1]=0,++G.sequenceNumber[0];else++G.sequenceNumber[1]}};return G},Q={read:X(),write:X()};if(Q.read.update=function(G,W){if(!Q.read.cipherFunction(W,Q.read))G.error(G,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.bad_record_mac}});else if(!Q.read.compressFunction(G,W,Q.read))G.error(G,{message:"Could not decompress record.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.decompression_failure}});return!G.fail},Q.write.update=function(G,W){if(!Q.write.compressFunction(G,W,Q.write))G.error(G,{message:"Could not compress record.",send:!1,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.internal_error}});else if(!Q.write.cipherFunction(W,Q.write))G.error(G,{message:"Could not encrypt record.",send:!1,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.internal_error}});return!G.fail},$.session){var Y=$.session.sp;switch($.session.cipherSuite.initSecurityParameters(Y),Y.keys=F.generateKeys($,Y),Q.read.macKey=J?Y.keys.server_write_MAC_key:Y.keys.client_write_MAC_key,Q.write.macKey=J?Y.keys.client_write_MAC_key:Y.keys.server_write_MAC_key,$.session.cipherSuite.initConnectionState(Q,$,Y),Y.compression_algorithm){case F.CompressionMethod.none:break;case F.CompressionMethod.deflate:Q.read.compressFunction=eV,Q.write.compressFunction=tV;break;default:throw Error("Unsupported compression algorithm.")}}return Q};F.createRandom=function(){var $=new Date,J=+$+$.getTimezoneOffset()*60000,X=f.util.createBuffer();return X.putInt32(J),X.putBytes(f.random.getBytes(28)),X};F.createRecord=function($,J){if(!J.data)return null;var X={type:J.type,version:{major:$.version.major,minor:$.version.minor},length:J.data.length(),fragment:J.data};return X};F.createAlert=function($,J){var X=f.util.createBuffer();return X.putByte(J.level),X.putByte(J.description),F.createRecord($,{type:F.ContentType.alert,data:X})};F.createClientHello=function($){$.session.clientHelloVersion={major:$.version.major,minor:$.version.minor};var J=f.util.createBuffer();for(var X=0;X<$.cipherSuites.length;++X){var Q=$.cipherSuites[X];J.putByte(Q.id[0]),J.putByte(Q.id[1])}var Y=J.length(),G=f.util.createBuffer();G.putByte(F.CompressionMethod.none);var W=G.length(),U=f.util.createBuffer();if($.virtualHost){var M=f.util.createBuffer();M.putByte(0),M.putByte(0);var O=f.util.createBuffer();O.putByte(0),fJ(O,2,f.util.createBuffer($.virtualHost));var V=f.util.createBuffer();fJ(V,2,O),fJ(M,2,V),U.putBuffer(M)}var q=U.length();if(q>0)q+=2;var H=$.session.id,N=H.length+1+2+4+28+2+Y+1+W+q,K=f.util.createBuffer();if(K.putByte(F.HandshakeType.client_hello),K.putInt24(N),K.putByte($.version.major),K.putByte($.version.minor),K.putBytes($.session.sp.client_random),fJ(K,1,f.util.createBuffer(H)),fJ(K,2,J),fJ(K,1,G),q>0)fJ(K,2,U);return K};F.createServerHello=function($){var J=$.session.id,X=J.length+1+2+4+28+2+1,Q=f.util.createBuffer();return Q.putByte(F.HandshakeType.server_hello),Q.putInt24(X),Q.putByte($.version.major),Q.putByte($.version.minor),Q.putBytes($.session.sp.server_random),fJ(Q,1,f.util.createBuffer(J)),Q.putByte($.session.cipherSuite.id[0]),Q.putByte($.session.cipherSuite.id[1]),Q.putByte($.session.compressionMethod),Q};F.createCertificate=function($){var J=$.entity===F.ConnectionEnd.client,X=null;if($.getCertificate){var Q;if(J)Q=$.session.certificateRequest;else Q=$.session.extensions.server_name.serverNameList;X=$.getCertificate($,Q)}var Y=f.util.createBuffer();if(X!==null)try{if(!f.util.isArray(X))X=[X];var G=null;for(var W=0;W<X.length;++W){var U=f.pem.decode(X[W])[0];if(U.type!=="CERTIFICATE"&&U.type!=="X509 CERTIFICATE"&&U.type!=="TRUSTED CERTIFICATE"){var M=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw M.headerType=U.type,M}if(U.procType&&U.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var O=f.util.createBuffer(U.body);if(G===null)G=f.asn1.fromDer(O.bytes(),!1);var V=f.util.createBuffer();fJ(V,3,O),Y.putBuffer(V)}if(X=f.pki.certificateFromAsn1(G),J)$.session.clientCertificate=X;else $.session.serverCertificate=X}catch(N){return $.error($,{message:"Could not send certificate list.",cause:N,send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.bad_certificate}})}var q=3+Y.length(),H=f.util.createBuffer();return H.putByte(F.HandshakeType.certificate),H.putInt24(q),fJ(H,3,Y),H};F.createClientKeyExchange=function($){var J=f.util.createBuffer();J.putByte($.session.clientHelloVersion.major),J.putByte($.session.clientHelloVersion.minor),J.putBytes(f.random.getBytes(46));var X=$.session.sp;X.pre_master_secret=J.getBytes();var Q=$.session.serverCertificate.publicKey;J=Q.encrypt(X.pre_master_secret);var Y=J.length+2,G=f.util.createBuffer();return G.putByte(F.HandshakeType.client_key_exchange),G.putInt24(Y),G.putInt16(J.length),G.putBytes(J),G};F.createServerKeyExchange=function($){var J=0,X=f.util.createBuffer();if(J>0)X.putByte(F.HandshakeType.server_key_exchange),X.putInt24(J);return X};F.getClientSignature=function($,J){var X=f.util.createBuffer();X.putBuffer($.session.md5.digest()),X.putBuffer($.session.sha1.digest()),X=X.getBytes(),$.getSignature=$.getSignature||function(Q,Y,G){var W=null;if(Q.getPrivateKey)try{W=Q.getPrivateKey(Q,Q.session.clientCertificate),W=f.pki.privateKeyFromPem(W)}catch(U){Q.error(Q,{message:"Could not get private key.",cause:U,send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.internal_error}})}if(W===null)Q.error(Q,{message:"No private key set.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.internal_error}});else Y=W.sign(Y,null);G(Q,Y)},$.getSignature($,X,J)};F.createCertificateVerify=function($,J){var X=J.length+2,Q=f.util.createBuffer();return Q.putByte(F.HandshakeType.certificate_verify),Q.putInt24(X),Q.putInt16(J.length),Q.putBytes(J),Q};F.createCertificateRequest=function($){var J=f.util.createBuffer();J.putByte(1);var X=f.util.createBuffer();for(var Q in $.caStore.certs){var Y=$.caStore.certs[Q],G=f.pki.distinguishedNameToAsn1(Y.subject),W=f.asn1.toDer(G);X.putInt16(W.length()),X.putBuffer(W)}var U=1+J.length()+2+X.length(),M=f.util.createBuffer();return M.putByte(F.HandshakeType.certificate_request),M.putInt24(U),fJ(M,1,J),fJ(M,2,X),M};F.createServerHelloDone=function($){var J=f.util.createBuffer();return J.putByte(F.HandshakeType.server_hello_done),J.putInt24(0),J};F.createChangeCipherSpec=function(){var $=f.util.createBuffer();return $.putByte(1),$};F.createFinished=function($){var J=f.util.createBuffer();J.putBuffer($.session.md5.digest()),J.putBuffer($.session.sha1.digest());var X=$.entity===F.ConnectionEnd.client,Q=$.session.sp,Y=12,G=nY,W=X?"client finished":"server finished";J=G(Q.master_secret,W,J.getBytes(),Y);var U=f.util.createBuffer();return U.putByte(F.HandshakeType.finished),U.putInt24(J.length()),U.putBuffer(J),U};F.createHeartbeat=function($,J,X){if(typeof X>"u")X=J.length;var Q=f.util.createBuffer();Q.putByte($),Q.putInt16(X),Q.putBytes(J);var Y=Q.length(),G=Math.max(16,Y-X-3);return Q.putBytes(f.random.getBytes(G)),Q};F.queue=function($,J){if(!J)return;if(J.fragment.length()===0){if(J.type===F.ContentType.handshake||J.type===F.ContentType.alert||J.type===F.ContentType.change_cipher_spec)return}if(J.type===F.ContentType.handshake){var X=J.fragment.bytes();$.session.md5.update(X),$.session.sha1.update(X),X=null}var Q;if(J.fragment.length()<=F.MaxFragment)Q=[J];else{Q=[];var Y=J.fragment.bytes();while(Y.length>F.MaxFragment)Q.push(F.createRecord($,{type:J.type,data:f.util.createBuffer(Y.slice(0,F.MaxFragment))})),Y=Y.slice(F.MaxFragment);if(Y.length>0)Q.push(F.createRecord($,{type:J.type,data:f.util.createBuffer(Y)}))}for(var G=0;G<Q.length&&!$.fail;++G){var W=Q[G],U=$.state.current.write;if(U.update($,W))$.records.push(W)}};F.flush=function($){for(var J=0;J<$.records.length;++J){var X=$.records[J];$.tlsData.putByte(X.type),$.tlsData.putByte(X.version.major),$.tlsData.putByte(X.version.minor),$.tlsData.putInt16(X.fragment.length()),$.tlsData.putBuffer($.records[J].fragment)}return $.records=[],$.tlsDataReady($)};var _8=function($){switch($){case!0:return!0;case f.pki.certificateError.bad_certificate:return F.Alert.Description.bad_certificate;case f.pki.certificateError.unsupported_certificate:return F.Alert.Description.unsupported_certificate;case f.pki.certificateError.certificate_revoked:return F.Alert.Description.certificate_revoked;case f.pki.certificateError.certificate_expired:return F.Alert.Description.certificate_expired;case f.pki.certificateError.certificate_unknown:return F.Alert.Description.certificate_unknown;case f.pki.certificateError.unknown_ca:return F.Alert.Description.unknown_ca;default:return F.Alert.Description.bad_certificate}},Fq=function($){switch($){case!0:return!0;case F.Alert.Description.bad_certificate:return f.pki.certificateError.bad_certificate;case F.Alert.Description.unsupported_certificate:return f.pki.certificateError.unsupported_certificate;case F.Alert.Description.certificate_revoked:return f.pki.certificateError.certificate_revoked;case F.Alert.Description.certificate_expired:return f.pki.certificateError.certificate_expired;case F.Alert.Description.certificate_unknown:return f.pki.certificateError.certificate_unknown;case F.Alert.Description.unknown_ca:return f.pki.certificateError.unknown_ca;default:return f.pki.certificateError.bad_certificate}};F.verifyCertificateChain=function($,J){try{var X={};for(var Q in $.verifyOptions)X[Q]=$.verifyOptions[Q];X.verify=function(G,W,U){var M=_8(G),O=$.verify($,G,W,U);if(O!==!0){if(typeof O==="object"&&!f.util.isArray(O)){var V=Error("The application rejected the certificate.");if(V.send=!0,V.alert={level:F.Alert.Level.fatal,description:F.Alert.Description.bad_certificate},O.message)V.message=O.message;if(O.alert)V.alert.description=O.alert;throw V}if(O!==G)O=Fq(O)}return O},f.pki.verifyCertificateChain($.caStore,J,X)}catch(G){var Y=G;if(typeof Y!=="object"||f.util.isArray(Y))Y={send:!0,alert:{level:F.Alert.Level.fatal,description:_8(G)}};if(!("send"in Y))Y.send=!0;if(!("alert"in Y))Y.alert={level:F.Alert.Level.fatal,description:_8(Y.error)};$.error($,Y)}return!$.fail};F.createSessionCache=function($,J){var X=null;if($&&$.getSession&&$.setSession&&$.order)X=$;else{X={},X.cache=$||{},X.capacity=Math.max(J||100,1),X.order=[];for(var Q in $)if(X.order.length<=J)X.order.push(Q);else delete $[Q];X.getSession=function(Y){var G=null,W=null;if(Y)W=f.util.bytesToHex(Y);else if(X.order.length>0)W=X.order[0];if(W!==null&&W in X.cache){G=X.cache[W],delete X.cache[W];for(var U in X.order)if(X.order[U]===W){X.order.splice(U,1);break}}return G},X.setSession=function(Y,G){if(X.order.length===X.capacity){var W=X.order.shift();delete X.cache[W]}var W=f.util.bytesToHex(Y);X.order.push(W),X.cache[W]=G}}return X};F.createConnection=function($){var J=null;if($.caStore)if(f.util.isArray($.caStore))J=f.pki.createCaStore($.caStore);else J=$.caStore;else J=f.pki.createCaStore();var X=$.cipherSuites||null;if(X===null){X=[];for(var Q in F.CipherSuites)X.push(F.CipherSuites[Q])}var Y=$.server?F.ConnectionEnd.server:F.ConnectionEnd.client,G=$.sessionCache?F.createSessionCache($.sessionCache):null,W={version:{major:F.Version.major,minor:F.Version.minor},entity:Y,sessionId:$.sessionId,caStore:J,sessionCache:G,cipherSuites:X,connected:$.connected,virtualHost:$.virtualHost||null,verifyClient:$.verifyClient||!1,verify:$.verify||function(V,q,H,N){return q},verifyOptions:$.verifyOptions||{},getCertificate:$.getCertificate||null,getPrivateKey:$.getPrivateKey||null,getSignature:$.getSignature||null,input:f.util.createBuffer(),tlsData:f.util.createBuffer(),data:f.util.createBuffer(),tlsDataReady:$.tlsDataReady,dataReady:$.dataReady,heartbeatReceived:$.heartbeatReceived,closed:$.closed,error:function(V,q){if(q.origin=q.origin||(V.entity===F.ConnectionEnd.client?"client":"server"),q.send)F.queue(V,F.createAlert(V,q.alert)),F.flush(V);var H=q.fatal!==!1;if(H)V.fail=!0;if($.error(V,q),H)V.close(!1)},deflate:$.deflate||null,inflate:$.inflate||null};W.reset=function(V){W.version={major:F.Version.major,minor:F.Version.minor},W.record=null,W.session=null,W.peerCertificate=null,W.state={pending:null,current:null},W.expect=W.entity===F.ConnectionEnd.client?$q:Uq,W.fragmented=null,W.records=[],W.open=!1,W.handshakes=0,W.handshaking=!1,W.isConnected=!1,W.fail=!(V||typeof V>"u"),W.input.clear(),W.tlsData.clear(),W.data.clear(),W.state.current=F.createConnectionState(W)},W.reset();var U=function(V,q){var H=q.type-F.ContentType.change_cipher_spec,N=k8[V.entity][V.expect];if(H in N)N[H](V,q);else F.handleUnexpected(V,q)},M=function(V){var q=0,H=V.input,N=H.length();if(N<5)q=5-N;else{V.record={type:H.getByte(),version:{major:H.getByte(),minor:H.getByte()},length:H.getInt16(),fragment:f.util.createBuffer(),ready:!1};var K=V.record.version.major===V.version.major;if(K&&V.session&&V.session.version)K=V.record.version.minor===V.version.minor;if(!K)V.error(V,{message:"Incompatible TLS version.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.protocol_version}})}return q},O=function(V){var q=0,H=V.input,N=H.length();if(N<V.record.length)q=V.record.length-N;else{V.record.fragment.putBytes(H.getBytes(V.record.length)),H.compact();var K=V.state.current.read;if(K.update(V,V.record)){if(V.fragmented!==null)if(V.fragmented.type===V.record.type)V.fragmented.fragment.putBuffer(V.record.fragment),V.record=V.fragmented;else V.error(V,{message:"Invalid fragmented record.",send:!0,alert:{level:F.Alert.Level.fatal,description:F.Alert.Description.unexpected_message}});V.record.ready=!0}}return q};return W.handshake=function(V){if(W.entity!==F.ConnectionEnd.client)W.error(W,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(W.handshaking)W.error(W,{message:"Handshake already in progress.",fatal:!1});else{if(W.fail&&!W.open&&W.handshakes===0)W.fail=!1;W.handshaking=!0,V=V||"";var q=null;if(V.length>0){if(W.sessionCache)q=W.sessionCache.getSession(V);if(q===null)V=""}if(V.length===0&&W.sessionCache){if(q=W.sessionCache.getSession(),q!==null)V=q.id}if(W.session={id:V,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:f.md.md5.create(),sha1:f.md.sha1.create()},q)W.version=q.version,W.session.sp=q.sp;W.session.sp.client_random=F.createRandom().getBytes(),W.open=!0,F.queue(W,F.createRecord(W,{type:F.ContentType.handshake,data:F.createClientHello(W)})),F.flush(W)}},W.process=function(V){var q=0;if(V)W.input.putBytes(V);if(!W.fail){if(W.record!==null&&W.record.ready&&W.record.fragment.isEmpty())W.record=null;if(W.record===null)q=M(W);if(!W.fail&&W.record!==null&&!W.record.ready)q=O(W);if(!W.fail&&W.record!==null&&W.record.ready)U(W,W.record)}return q},W.prepare=function(V){return F.queue(W,F.createRecord(W,{type:F.ContentType.application_data,data:f.util.createBuffer(V)})),F.flush(W)},W.prepareHeartbeatRequest=function(V,q){if(V instanceof f.util.ByteBuffer)V=V.bytes();if(typeof q>"u")q=V.length;return W.expectedHeartbeatPayload=V,F.queue(W,F.createRecord(W,{type:F.ContentType.heartbeat,data:F.createHeartbeat(F.HeartbeatMessageType.heartbeat_request,V,q)})),F.flush(W)},W.close=function(V){if(!W.fail&&W.sessionCache&&W.session){var q={id:W.session.id,version:W.session.version,sp:W.session.sp};q.sp.keys=null,W.sessionCache.setSession(q.id,q)}if(W.open){if(W.open=!1,W.input.clear(),W.isConnected||W.handshaking)W.isConnected=W.handshaking=!1,F.queue(W,F.createAlert(W,{level:F.Alert.Level.warning,description:F.Alert.Description.close_notify})),F.flush(W);W.closed(W)}W.reset(V)},W};XW.exports=f.tls=f.tls||{};for(xX in F)if(typeof F[xX]!=="function")f.tls[xX]=F[xX];var xX;f.tls.prf_tls1=nY;f.tls.hmac_sha1=rV;f.tls.createSessionCache=F.createSessionCache;f.tls.createConnection=F.createConnection});var WW=q$((sF,GW)=>{var h0=F$();_0();f8();var yJ=GW.exports=h0.tls;yJ.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function($){$.bulk_cipher_algorithm=yJ.BulkCipherAlgorithm.aes,$.cipher_type=yJ.CipherType.block,$.enc_key_length=16,$.block_length=16,$.fixed_iv_length=16,$.record_iv_length=16,$.mac_algorithm=yJ.MACAlgorithm.hmac_sha1,$.mac_length=20,$.mac_key_length=20},initConnectionState:YW};yJ.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function($){$.bulk_cipher_algorithm=yJ.BulkCipherAlgorithm.aes,$.cipher_type=yJ.CipherType.block,$.enc_key_length=32,$.block_length=16,$.fixed_iv_length=16,$.record_iv_length=16,$.mac_algorithm=yJ.MACAlgorithm.hmac_sha1,$.mac_length=20,$.mac_key_length=20},initConnectionState:YW};function YW($,J,X){var Q=J.entity===h0.tls.ConnectionEnd.client;$.read.cipherState={init:!1,cipher:h0.cipher.createDecipher("AES-CBC",Q?X.keys.server_write_key:X.keys.client_write_key),iv:Q?X.keys.server_write_IV:X.keys.client_write_IV},$.write.cipherState={init:!1,cipher:h0.cipher.createCipher("AES-CBC",Q?X.keys.client_write_key:X.keys.server_write_key),iv:Q?X.keys.client_write_IV:X.keys.server_write_IV},$.read.cipherFunction=Rq,$.write.cipherFunction=Nq,$.read.macLength=$.write.macLength=X.mac_length,$.read.macFunction=$.write.macFunction=yJ.hmac_sha1}function Nq($,J){var X=!1,Q=J.macFunction(J.macKey,J.sequenceNumber,$);$.fragment.putBytes(Q),J.updateSequenceNumber();var Y;if($.version.minor===yJ.Versions.TLS_1_0.minor)Y=J.cipherState.init?null:J.cipherState.iv;else Y=h0.random.getBytesSync(16);J.cipherState.init=!0;var G=J.cipherState.cipher;if(G.start({iv:Y}),$.version.minor>=yJ.Versions.TLS_1_1.minor)G.output.putBytes(Y);if(G.update($.fragment),G.finish(Lq))$.fragment=G.output,$.length=$.fragment.length(),X=!0;return X}function Lq($,J,X){if(!X){var Q=$-J.length()%$;J.fillWithByte(Q-1,Q)}return!0}function Aq($,J,X){var Q=!0;if(X){var Y=J.length(),G=J.last();for(var W=Y-1-G;W<Y-1;++W)Q=Q&&J.at(W)==G;if(Q)J.truncate(G+1)}return Q}function Rq($,J){var X=!1,Q;if($.version.minor===yJ.Versions.TLS_1_0.minor)Q=J.cipherState.init?null:J.cipherState.iv;else Q=$.fragment.getBytes(16);J.cipherState.init=!0;var Y=J.cipherState.cipher;Y.start({iv:Q}),Y.update($.fragment),X=Y.finish(Aq);var G=J.macLength,W=h0.random.getBytesSync(G),U=Y.output.length();if(U>=G)$.fragment=Y.output.getBytes(U-G),W=Y.output.getBytes(G);else $.fragment=Y.output.getBytes();$.fragment=h0.util.createBuffer($.fragment),$.length=$.fragment.length();var M=J.macFunction(J.macKey,J.sequenceNumber,$);return J.updateSequenceNumber(),X=Dq(J.macKey,W,M)&&X,X}function Dq($,J,X){var Q=h0.hmac.create();return Q.start("SHA1",$),Q.update(J),J=Q.digest().getBytes(),Q.start(null,null),Q.update(X),X=Q.digest().getBytes(),J===X}});var h8=q$((rF,VW)=>{var d$=F$();J0();_$();var vX=VW.exports=d$.sha512=d$.sha512||{};d$.md.sha512=d$.md.algorithms.sha512=vX;var MW=d$.sha384=d$.sha512.sha384=d$.sha512.sha384||{};MW.create=function(){return vX.create("SHA-384")};d$.md.sha384=d$.md.algorithms.sha384=MW;d$.sha512.sha256=d$.sha512.sha256||{create:function(){return vX.create("SHA-512/256")}};d$.md["sha512/256"]=d$.md.algorithms["sha512/256"]=d$.sha512.sha256;d$.sha512.sha224=d$.sha512.sha224||{create:function(){return vX.create("SHA-512/224")}};d$.md["sha512/224"]=d$.md.algorithms["sha512/224"]=d$.sha512.sha224;vX.create=function($){if(!OW)Zq();if(typeof $>"u")$="SHA-512";if(!($ in VQ))throw Error("Invalid SHA-512 algorithm: "+$);var J=VQ[$],X=null,Q=d$.util.createBuffer(),Y=Array(80);for(var G=0;G<80;++G)Y[G]=[,,];var W=64;switch($){case"SHA-384":W=48;break;case"SHA-512/256":W=32;break;case"SHA-512/224":W=28;break}var U={algorithm:$.replace("-","").toLowerCase(),blockLength:128,digestLength:W,messageLength:0,fullMessageLength:null,messageLengthSize:16};return U.start=function(){U.messageLength=0,U.fullMessageLength=U.messageLength128=[];var M=U.messageLengthSize/4;for(var O=0;O<M;++O)U.fullMessageLength.push(0);Q=d$.util.createBuffer(),X=Array(J.length);for(var O=0;O<J.length;++O)X[O]=J[O].slice(0);return U},U.start(),U.update=function(M,O){if(O==="utf8")M=d$.util.encodeUtf8(M);var V=M.length;U.messageLength+=V,V=[V/4294967296>>>0,V>>>0];for(var q=U.fullMessageLength.length-1;q>=0;--q)U.fullMessageLength[q]+=V[1],V[1]=V[0]+(U.fullMessageLength[q]/4294967296>>>0),U.fullMessageLength[q]=U.fullMessageLength[q]>>>0,V[0]=V[1]/4294967296>>>0;if(Q.putBytes(M),UW(X,Y,Q),Q.read>2048||Q.length()===0)Q.compact();return U},U.digest=function(){var M=d$.util.createBuffer();M.putBytes(Q.bytes());var O=U.fullMessageLength[U.fullMessageLength.length-1]+U.messageLengthSize,V=O&U.blockLength-1;M.putBytes(y8.substr(0,U.blockLength-V));var q,H,N=U.fullMessageLength[0]*8;for(var K=0;K<U.fullMessageLength.length-1;++K)q=U.fullMessageLength[K+1]*8,H=q/4294967296>>>0,N+=H,M.putInt32(N>>>0),N=q>>>0;M.putInt32(N);var L=Array(X.length);for(var K=0;K<X.length;++K)L[K]=X[K].slice(0);UW(L,Y,M);var A=d$.util.createBuffer(),D;if($==="SHA-512")D=L.length;else if($==="SHA-384")D=L.length-2;else D=L.length-4;for(var K=0;K<D;++K)if(A.putInt32(L[K][0]),K!==D-1||$!=="SHA-512/224")A.putInt32(L[K][1]);return A},U};var y8=null,OW=!1,b8=null,VQ=null;function Zq(){y8=String.fromCharCode(128),y8+=d$.util.fillString(String.fromCharCode(0),128),b8=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],VQ={},VQ["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],VQ["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],VQ["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],VQ["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],OW=!0}function UW($,J,X){var Q,Y,G,W,U,M,O,V,q,H,N,K,L,A,D,S,B,C,w,P,l,$$,y,n,Y$,L$,j$,$J,S$,b$,u,J$,a,V$,O$,e=X.length();while(e>=128){for(S$=0;S$<16;++S$)J[S$][0]=X.getInt32()>>>0,J[S$][1]=X.getInt32()>>>0;for(;S$<80;++S$)J$=J[S$-2],b$=J$[0],u=J$[1],Q=((b$>>>19|u<<13)^(u>>>29|b$<<3)^b$>>>6)>>>0,Y=((b$<<13|u>>>19)^(u<<3|b$>>>29)^(b$<<26|u>>>6))>>>0,V$=J[S$-15],b$=V$[0],u=V$[1],G=((b$>>>1|u<<31)^(b$>>>8|u<<24)^b$>>>7)>>>0,W=((b$<<31|u>>>1)^(b$<<24|u>>>8)^(b$<<25|u>>>7))>>>0,a=J[S$-7],O$=J[S$-16],u=Y+a[1]+W+O$[1],J[S$][0]=Q+a[0]+G+O$[0]+(u/4294967296>>>0)>>>0,J[S$][1]=u>>>0;L=$[0][0],A=$[0][1],D=$[1][0],S=$[1][1],B=$[2][0],C=$[2][1],w=$[3][0],P=$[3][1],l=$[4][0],$$=$[4][1],y=$[5][0],n=$[5][1],Y$=$[6][0],L$=$[6][1],j$=$[7][0],$J=$[7][1];for(S$=0;S$<80;++S$)O=((l>>>14|$$<<18)^(l>>>18|$$<<14)^($$>>>9|l<<23))>>>0,V=((l<<18|$$>>>14)^(l<<14|$$>>>18)^($$<<23|l>>>9))>>>0,q=(Y$^l&(y^Y$))>>>0,H=(L$^$$&(n^L$))>>>0,U=((L>>>28|A<<4)^(A>>>2|L<<30)^(A>>>7|L<<25))>>>0,M=((L<<4|A>>>28)^(A<<30|L>>>2)^(A<<25|L>>>7))>>>0,N=(L&D|B&(L^D))>>>0,K=(A&S|C&(A^S))>>>0,u=$J+V+H+b8[S$][1]+J[S$][1],Q=j$+O+q+b8[S$][0]+J[S$][0]+(u/4294967296>>>0)>>>0,Y=u>>>0,u=M+K,G=U+N+(u/4294967296>>>0)>>>0,W=u>>>0,j$=Y$,$J=L$,Y$=y,L$=n,y=l,n=$$,u=P+Y,l=w+Q+(u/4294967296>>>0)>>>0,$$=u>>>0,w=B,P=C,B=D,C=S,D=L,S=A,u=Y+W,L=Q+G+(u/4294967296>>>0)>>>0,A=u>>>0;u=$[0][1]+A,$[0][0]=$[0][0]+L+(u/4294967296>>>0)>>>0,$[0][1]=u>>>0,u=$[1][1]+S,$[1][0]=$[1][0]+D+(u/4294967296>>>0)>>>0,$[1][1]=u>>>0,u=$[2][1]+C,$[2][0]=$[2][0]+B+(u/4294967296>>>0)>>>0,$[2][1]=u>>>0,u=$[3][1]+P,$[3][0]=$[3][0]+w+(u/4294967296>>>0)>>>0,$[3][1]=u>>>0,u=$[4][1]+$$,$[4][0]=$[4][0]+l+(u/4294967296>>>0)>>>0,$[4][1]=u>>>0,u=$[5][1]+n,$[5][0]=$[5][0]+y+(u/4294967296>>>0)>>>0,$[5][1]=u>>>0,u=$[6][1]+L$,$[6][0]=$[6][0]+Y$+(u/4294967296>>>0)>>>0,$[6][1]=u>>>0,u=$[7][1]+$J,$[7][0]=$[7][0]+j$+(u/4294967296>>>0)>>>0,$[7][1]=u>>>0,e-=128}}});var qW=q$((jq)=>{var Bq=F$();lJ();var qJ=Bq.asn1;jq.privateKeyValidator={name:"PrivateKeyInfo",tagClass:qJ.Class.UNIVERSAL,type:qJ.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:qJ.Class.UNIVERSAL,type:qJ.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:qJ.Class.UNIVERSAL,type:qJ.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:qJ.Class.UNIVERSAL,type:qJ.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:qJ.Class.UNIVERSAL,type:qJ.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};jq.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:qJ.Class.UNIVERSAL,type:qJ.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:qJ.Class.UNIVERSAL,type:qJ.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:qJ.Class.UNIVERSAL,type:qJ.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:qJ.Class.UNIVERSAL,type:qJ.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var BW=q$((eF,ZW)=>{var zJ=F$();CX();_J();h8();_$();var FW=qW(),Iq=FW.publicKeyValidator,Cq=FW.privateKeyValidator;if(typeof g8>"u")g8=zJ.jsbn.BigInteger;var g8,m8=zJ.util.ByteBuffer,BJ=typeof Buffer>"u"?Uint8Array:Buffer;zJ.pki=zJ.pki||{};ZW.exports=zJ.pki.ed25519=zJ.ed25519=zJ.ed25519||{};var Z$=zJ.ed25519;Z$.constants={};Z$.constants.PUBLIC_KEY_BYTE_LENGTH=32;Z$.constants.PRIVATE_KEY_BYTE_LENGTH=64;Z$.constants.SEED_BYTE_LENGTH=32;Z$.constants.SIGN_BYTE_LENGTH=64;Z$.constants.HASH_BYTE_LENGTH=64;Z$.generateKeyPair=function($){$=$||{};var J=$.seed;if(J===void 0)J=zJ.random.getBytesSync(Z$.constants.SEED_BYTE_LENGTH);else if(typeof J==="string"){if(J.length!==Z$.constants.SEED_BYTE_LENGTH)throw TypeError('"seed" must be '+Z$.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(J instanceof Uint8Array))throw TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');J=D0({message:J,encoding:"binary"});var X=new BJ(Z$.constants.PUBLIC_KEY_BYTE_LENGTH),Q=new BJ(Z$.constants.PRIVATE_KEY_BYTE_LENGTH);for(var Y=0;Y<32;++Y)Q[Y]=J[Y];return xq(X,Q),{publicKey:X,privateKey:Q}};Z$.privateKeyFromAsn1=function($){var J={},X=[],Q=zJ.asn1.validate($,Cq,J,X);if(!Q){var Y=Error("Invalid Key.");throw Y.errors=X,Y}var G=zJ.asn1.derToOid(J.privateKeyOid),W=zJ.oids.EdDSA25519;if(G!==W)throw Error('Invalid OID "'+G+'"; OID must be "'+W+'".');var U=J.privateKey,M=D0({message:zJ.asn1.fromDer(U).value,encoding:"binary"});return{privateKeyBytes:M}};Z$.publicKeyFromAsn1=function($){var J={},X=[],Q=zJ.asn1.validate($,Iq,J,X);if(!Q){var Y=Error("Invalid Key.");throw Y.errors=X,Y}var G=zJ.asn1.derToOid(J.publicKeyOid),W=zJ.oids.EdDSA25519;if(G!==W)throw Error('Invalid OID "'+G+'"; OID must be "'+W+'".');var U=J.ed25519PublicKey;if(U.length!==Z$.constants.PUBLIC_KEY_BYTE_LENGTH)throw Error("Key length is invalid.");return D0({message:U,encoding:"binary"})};Z$.publicKeyFromPrivateKey=function($){$=$||{};var J=D0({message:$.privateKey,encoding:"binary"});if(J.length!==Z$.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+Z$.constants.PRIVATE_KEY_BYTE_LENGTH);var X=new BJ(Z$.constants.PUBLIC_KEY_BYTE_LENGTH);for(var Q=0;Q<X.length;++Q)X[Q]=J[32+Q];return X};Z$.sign=function($){$=$||{};var J=D0($),X=D0({message:$.privateKey,encoding:"binary"});if(X.length===Z$.constants.SEED_BYTE_LENGTH){var Q=Z$.generateKeyPair({seed:X});X=Q.privateKey}else if(X.length!==Z$.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+Z$.constants.SEED_BYTE_LENGTH+" or "+Z$.constants.PRIVATE_KEY_BYTE_LENGTH);var Y=new BJ(Z$.constants.SIGN_BYTE_LENGTH+J.length);vq(Y,J,J.length,X);var G=new BJ(Z$.constants.SIGN_BYTE_LENGTH);for(var W=0;W<G.length;++W)G[W]=Y[W];return G};Z$.verify=function($){$=$||{};var J=D0($);if($.signature===void 0)throw TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var X=D0({message:$.signature,encoding:"binary"});if(X.length!==Z$.constants.SIGN_BYTE_LENGTH)throw TypeError('"options.signature" must have a byte length of '+Z$.constants.SIGN_BYTE_LENGTH);var Q=D0({message:$.publicKey,encoding:"binary"});if(Q.length!==Z$.constants.PUBLIC_KEY_BYTE_LENGTH)throw TypeError('"options.publicKey" must have a byte length of '+Z$.constants.PUBLIC_KEY_BYTE_LENGTH);var Y=new BJ(Z$.constants.SIGN_BYTE_LENGTH+J.length),G=new BJ(Z$.constants.SIGN_BYTE_LENGTH+J.length),W;for(W=0;W<Z$.constants.SIGN_BYTE_LENGTH;++W)Y[W]=X[W];for(W=0;W<J.length;++W)Y[W+Z$.constants.SIGN_BYTE_LENGTH]=J[W];return kq(G,Y,Y.length,Q)>=0};function D0($){var J=$.message;if(J instanceof Uint8Array||J instanceof BJ)return J;var X=$.encoding;if(J===void 0)if($.md)J=$.md.digest().getBytes(),X="binary";else throw TypeError('"options.message" or "options.md" not specified.');if(typeof J==="string"&&!X)throw TypeError('"options.encoding" must be "binary" or "utf8".');if(typeof J==="string"){if(typeof Buffer<"u")return Buffer.from(J,X);J=new m8(J,X)}else if(!(J instanceof m8))throw TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');var Q=new BJ(J.length());for(var Y=0;Y<Q.length;++Y)Q[Y]=J.at(Y);return Q}var l8=U$(),iY=U$([1]),wq=U$([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),Pq=U$([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),HW=U$([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),KW=U$([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),kX=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),_q=U$([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function fX($,J){var X=zJ.md.sha512.create(),Q=new m8($);X.update(Q.getBytes(J),"binary");var Y=X.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(Y,"binary");var G=new BJ(Z$.constants.HASH_BYTE_LENGTH);for(var W=0;W<64;++W)G[W]=Y.charCodeAt(W);return G}function xq($,J){var X=[U$(),U$(),U$(),U$()],Q,Y=fX(J,32);Y[0]&=248,Y[31]&=127,Y[31]|=64,n8(X,Y),c8($,X);for(Q=0;Q<32;++Q)J[Q+32]=$[Q];return 0}function vq($,J,X,Q){var Y,G,W=new Float64Array(64),U=[U$(),U$(),U$(),U$()],M=fX(Q,32);M[0]&=248,M[31]&=127,M[31]|=64;var O=X+64;for(Y=0;Y<X;++Y)$[64+Y]=J[Y];for(Y=0;Y<32;++Y)$[32+Y]=M[32+Y];var V=fX($.subarray(32),X+32);p8(V),n8(U,V),c8($,U);for(Y=32;Y<64;++Y)$[Y]=Q[Y];var q=fX($,X+64);p8(q);for(Y=32;Y<64;++Y)W[Y]=0;for(Y=0;Y<32;++Y)W[Y]=V[Y];for(Y=0;Y<32;++Y)for(G=0;G<32;G++)W[Y+G]+=q[Y]*M[G];return NW($.subarray(32),W),O}function kq($,J,X,Q){var Y,G,W=new BJ(32),U=[U$(),U$(),U$(),U$()],M=[U$(),U$(),U$(),U$()];if(G=-1,X<64)return-1;if(yq(M,Q))return-1;if(!fq(J,32))return-1;for(Y=0;Y<X;++Y)$[Y]=J[Y];for(Y=0;Y<32;++Y)$[Y+32]=Q[Y];var O=fX($,X);if(p8(O),RW(U,M,O),n8(M,J.subarray(32)),d8(U,M),c8(W,U),X-=64,LW(J,0,W,0)){for(Y=0;Y<X;++Y)$[Y]=0;return-1}for(Y=0;Y<X;++Y)$[Y]=J[Y+64];return G=X,G}function fq($,J){var X;for(X=31;X>=0;--X){if($[J+X]<kX[X])return!0;if($[J+X]>kX[X])return!1}return!1}function NW($,J){var X,Q,Y,G;for(Q=63;Q>=32;--Q){X=0;for(Y=Q-32,G=Q-12;Y<G;++Y)J[Y]+=X-16*J[Q]*kX[Y-(Q-32)],X=J[Y]+128>>8,J[Y]-=X*256;J[Y]+=X,J[Q]=0}X=0;for(Y=0;Y<32;++Y)J[Y]+=X-(J[31]>>4)*kX[Y],X=J[Y]>>8,J[Y]&=255;for(Y=0;Y<32;++Y)J[Y]-=X*kX[Y];for(Q=0;Q<32;++Q)J[Q+1]+=J[Q]>>8,$[Q]=J[Q]&255}function p8($){var J=new Float64Array(64);for(var X=0;X<64;++X)J[X]=$[X],$[X]=0;NW($,J)}function d8($,J){var X=U$(),Q=U$(),Y=U$(),G=U$(),W=U$(),U=U$(),M=U$(),O=U$(),V=U$();bQ(X,$[1],$[0]),bQ(V,J[1],J[0]),h$(X,X,V),yQ(Q,$[0],$[1]),yQ(V,J[0],J[1]),h$(Q,Q,V),h$(Y,$[3],J[3]),h$(Y,Y,Pq),h$(G,$[2],J[2]),yQ(G,G,G),bQ(W,Q,X),bQ(U,G,Y),yQ(M,G,Y),yQ(O,Q,X),h$($[0],W,U),h$($[1],O,M),h$($[2],M,U),h$($[3],W,O)}function zW($,J,X){for(var Q=0;Q<4;++Q)DW($[Q],J[Q],X)}function c8($,J){var X=U$(),Q=U$(),Y=U$();gq(Y,J[2]),h$(X,J[0],Y),h$(Q,J[1],Y),oY($,Q),$[31]^=AW(X)<<7}function oY($,J){var X,Q,Y,G=U$(),W=U$();for(X=0;X<16;++X)W[X]=J[X];u8(W),u8(W),u8(W);for(Q=0;Q<2;++Q){G[0]=W[0]-65517;for(X=1;X<15;++X)G[X]=W[X]-65535-(G[X-1]>>16&1),G[X-1]&=65535;G[15]=W[15]-32767-(G[14]>>16&1),Y=G[15]>>16&1,G[14]&=65535,DW(W,G,1-Y)}for(X=0;X<16;X++)$[2*X]=W[X]&255,$[2*X+1]=W[X]>>8}function yq($,J){var X=U$(),Q=U$(),Y=U$(),G=U$(),W=U$(),U=U$(),M=U$();if(u0($[2],iY),bq($[1],J),qQ(Y,$[1]),h$(G,Y,wq),bQ(Y,Y,$[2]),yQ(G,$[2],G),qQ(W,G),qQ(U,W),h$(M,U,W),h$(X,M,Y),h$(X,X,G),hq(X,X),h$(X,X,Y),h$(X,X,G),h$(X,X,G),h$($[0],X,G),qQ(Q,$[0]),h$(Q,Q,G),EW(Q,Y))h$($[0],$[0],_q);if(qQ(Q,$[0]),h$(Q,Q,G),EW(Q,Y))return-1;if(AW($[0])===J[31]>>7)bQ($[0],l8,$[0]);return h$($[3],$[0],$[1]),0}function bq($,J){var X;for(X=0;X<16;++X)$[X]=J[2*X]+(J[2*X+1]<<8);$[15]&=32767}function hq($,J){var X=U$(),Q;for(Q=0;Q<16;++Q)X[Q]=J[Q];for(Q=250;Q>=0;--Q)if(qQ(X,X),Q!==1)h$(X,X,J);for(Q=0;Q<16;++Q)$[Q]=X[Q]}function EW($,J){var X=new BJ(32),Q=new BJ(32);return oY(X,$),oY(Q,J),LW(X,0,Q,0)}function LW($,J,X,Q){return uq($,J,X,Q,32)}function uq($,J,X,Q,Y){var G,W=0;for(G=0;G<Y;++G)W|=$[J+G]^X[Q+G];return(1&W-1>>>8)-1}function AW($){var J=new BJ(32);return oY(J,$),J[0]&1}function RW($,J,X){var Q,Y;u0($[0],l8),u0($[1],iY),u0($[2],iY),u0($[3],l8);for(Y=255;Y>=0;--Y)Q=X[Y/8|0]>>(Y&7)&1,zW($,J,Q),d8(J,$),d8($,$),zW($,J,Q)}function n8($,J){var X=[U$(),U$(),U$(),U$()];u0(X[0],HW),u0(X[1],KW),u0(X[2],iY),h$(X[3],HW,KW),RW($,X,J)}function u0($,J){var X;for(X=0;X<16;X++)$[X]=J[X]|0}function gq($,J){var X=U$(),Q;for(Q=0;Q<16;++Q)X[Q]=J[Q];for(Q=253;Q>=0;--Q)if(qQ(X,X),Q!==2&&Q!==4)h$(X,X,J);for(Q=0;Q<16;++Q)$[Q]=X[Q]}function u8($){var J,X,Q=1;for(J=0;J<16;++J)X=$[J]+Q+65535,Q=Math.floor(X/65536),$[J]=X-Q*65536;$[0]+=Q-1+37*(Q-1)}function DW($,J,X){var Q,Y=~(X-1);for(var G=0;G<16;++G)Q=Y&($[G]^J[G]),$[G]^=Q,J[G]^=Q}function U$($){var J,X=new Float64Array(16);if($)for(J=0;J<$.length;++J)X[J]=$[J];return X}function yQ($,J,X){for(var Q=0;Q<16;++Q)$[Q]=J[Q]+X[Q]}function bQ($,J,X){for(var Q=0;Q<16;++Q)$[Q]=J[Q]-X[Q]}function qQ($,J){h$($,J,J)}function h$($,J,X){var Q,Y,G=0,W=0,U=0,M=0,O=0,V=0,q=0,H=0,N=0,K=0,L=0,A=0,D=0,S=0,B=0,C=0,w=0,P=0,l=0,$$=0,y=0,n=0,Y$=0,L$=0,j$=0,$J=0,S$=0,b$=0,u=0,J$=0,a=0,V$=X[0],O$=X[1],e=X[2],C$=X[3],g$=X[4],i$=X[5],W$=X[6],z$=X[7],v$=X[8],f$=X[9],XJ=X[10],YJ=X[11],o$=X[12],GJ=X[13],WJ=X[14],a$=X[15];Q=J[0],G+=Q*V$,W+=Q*O$,U+=Q*e,M+=Q*C$,O+=Q*g$,V+=Q*i$,q+=Q*W$,H+=Q*z$,N+=Q*v$,K+=Q*f$,L+=Q*XJ,A+=Q*YJ,D+=Q*o$,S+=Q*GJ,B+=Q*WJ,C+=Q*a$,Q=J[1],W+=Q*V$,U+=Q*O$,M+=Q*e,O+=Q*C$,V+=Q*g$,q+=Q*i$,H+=Q*W$,N+=Q*z$,K+=Q*v$,L+=Q*f$,A+=Q*XJ,D+=Q*YJ,S+=Q*o$,B+=Q*GJ,C+=Q*WJ,w+=Q*a$,Q=J[2],U+=Q*V$,M+=Q*O$,O+=Q*e,V+=Q*C$,q+=Q*g$,H+=Q*i$,N+=Q*W$,K+=Q*z$,L+=Q*v$,A+=Q*f$,D+=Q*XJ,S+=Q*YJ,B+=Q*o$,C+=Q*GJ,w+=Q*WJ,P+=Q*a$,Q=J[3],M+=Q*V$,O+=Q*O$,V+=Q*e,q+=Q*C$,H+=Q*g$,N+=Q*i$,K+=Q*W$,L+=Q*z$,A+=Q*v$,D+=Q*f$,S+=Q*XJ,B+=Q*YJ,C+=Q*o$,w+=Q*GJ,P+=Q*WJ,l+=Q*a$,Q=J[4],O+=Q*V$,V+=Q*O$,q+=Q*e,H+=Q*C$,N+=Q*g$,K+=Q*i$,L+=Q*W$,A+=Q*z$,D+=Q*v$,S+=Q*f$,B+=Q*XJ,C+=Q*YJ,w+=Q*o$,P+=Q*GJ,l+=Q*WJ,$$+=Q*a$,Q=J[5],V+=Q*V$,q+=Q*O$,H+=Q*e,N+=Q*C$,K+=Q*g$,L+=Q*i$,A+=Q*W$,D+=Q*z$,S+=Q*v$,B+=Q*f$,C+=Q*XJ,w+=Q*YJ,P+=Q*o$,l+=Q*GJ,$$+=Q*WJ,y+=Q*a$,Q=J[6],q+=Q*V$,H+=Q*O$,N+=Q*e,K+=Q*C$,L+=Q*g$,A+=Q*i$,D+=Q*W$,S+=Q*z$,B+=Q*v$,C+=Q*f$,w+=Q*XJ,P+=Q*YJ,l+=Q*o$,$$+=Q*GJ,y+=Q*WJ,n+=Q*a$,Q=J[7],H+=Q*V$,N+=Q*O$,K+=Q*e,L+=Q*C$,A+=Q*g$,D+=Q*i$,S+=Q*W$,B+=Q*z$,C+=Q*v$,w+=Q*f$,P+=Q*XJ,l+=Q*YJ,$$+=Q*o$,y+=Q*GJ,n+=Q*WJ,Y$+=Q*a$,Q=J[8],N+=Q*V$,K+=Q*O$,L+=Q*e,A+=Q*C$,D+=Q*g$,S+=Q*i$,B+=Q*W$,C+=Q*z$,w+=Q*v$,P+=Q*f$,l+=Q*XJ,$$+=Q*YJ,y+=Q*o$,n+=Q*GJ,Y$+=Q*WJ,L$+=Q*a$,Q=J[9],K+=Q*V$,L+=Q*O$,A+=Q*e,D+=Q*C$,S+=Q*g$,B+=Q*i$,C+=Q*W$,w+=Q*z$,P+=Q*v$,l+=Q*f$,$$+=Q*XJ,y+=Q*YJ,n+=Q*o$,Y$+=Q*GJ,L$+=Q*WJ,j$+=Q*a$,Q=J[10],L+=Q*V$,A+=Q*O$,D+=Q*e,S+=Q*C$,B+=Q*g$,C+=Q*i$,w+=Q*W$,P+=Q*z$,l+=Q*v$,$$+=Q*f$,y+=Q*XJ,n+=Q*YJ,Y$+=Q*o$,L$+=Q*GJ,j$+=Q*WJ,$J+=Q*a$,Q=J[11],A+=Q*V$,D+=Q*O$,S+=Q*e,B+=Q*C$,C+=Q*g$,w+=Q*i$,P+=Q*W$,l+=Q*z$,$$+=Q*v$,y+=Q*f$,n+=Q*XJ,Y$+=Q*YJ,L$+=Q*o$,j$+=Q*GJ,$J+=Q*WJ,S$+=Q*a$,Q=J[12],D+=Q*V$,S+=Q*O$,B+=Q*e,C+=Q*C$,w+=Q*g$,P+=Q*i$,l+=Q*W$,$$+=Q*z$,y+=Q*v$,n+=Q*f$,Y$+=Q*XJ,L$+=Q*YJ,j$+=Q*o$,$J+=Q*GJ,S$+=Q*WJ,b$+=Q*a$,Q=J[13],S+=Q*V$,B+=Q*O$,C+=Q*e,w+=Q*C$,P+=Q*g$,l+=Q*i$,$$+=Q*W$,y+=Q*z$,n+=Q*v$,Y$+=Q*f$,L$+=Q*XJ,j$+=Q*YJ,$J+=Q*o$,S$+=Q*GJ,b$+=Q*WJ,u+=Q*a$,Q=J[14],B+=Q*V$,C+=Q*O$,w+=Q*e,P+=Q*C$,l+=Q*g$,$$+=Q*i$,y+=Q*W$,n+=Q*z$,Y$+=Q*v$,L$+=Q*f$,j$+=Q*XJ,$J+=Q*YJ,S$+=Q*o$,b$+=Q*GJ,u+=Q*WJ,J$+=Q*a$,Q=J[15],C+=Q*V$,w+=Q*O$,P+=Q*e,l+=Q*C$,$$+=Q*g$,y+=Q*i$,n+=Q*W$,Y$+=Q*z$,L$+=Q*v$,j$+=Q*f$,$J+=Q*XJ,S$+=Q*YJ,b$+=Q*o$,u+=Q*GJ,J$+=Q*WJ,a+=Q*a$,G+=38*w,W+=38*P,U+=38*l,M+=38*$$,O+=38*y,V+=38*n,q+=38*Y$,H+=38*L$,N+=38*j$,K+=38*$J,L+=38*S$,A+=38*b$,D+=38*u,S+=38*J$,B+=38*a,Y=1,Q=G+Y+65535,Y=Math.floor(Q/65536),G=Q-Y*65536,Q=W+Y+65535,Y=Math.floor(Q/65536),W=Q-Y*65536,Q=U+Y+65535,Y=Math.floor(Q/65536),U=Q-Y*65536,Q=M+Y+65535,Y=Math.floor(Q/65536),M=Q-Y*65536,Q=O+Y+65535,Y=Math.floor(Q/65536),O=Q-Y*65536,Q=V+Y+65535,Y=Math.floor(Q/65536),V=Q-Y*65536,Q=q+Y+65535,Y=Math.floor(Q/65536),q=Q-Y*65536,Q=H+Y+65535,Y=Math.floor(Q/65536),H=Q-Y*65536,Q=N+Y+65535,Y=Math.floor(Q/65536),N=Q-Y*65536,Q=K+Y+65535,Y=Math.floor(Q/65536),K=Q-Y*65536,Q=L+Y+65535,Y=Math.floor(Q/65536),L=Q-Y*65536,Q=A+Y+65535,Y=Math.floor(Q/65536),A=Q-Y*65536,Q=D+Y+65535,Y=Math.floor(Q/65536),D=Q-Y*65536,Q=S+Y+65535,Y=Math.floor(Q/65536),S=Q-Y*65536,Q=B+Y+65535,Y=Math.floor(Q/65536),B=Q-Y*65536,Q=C+Y+65535,Y=Math.floor(Q/65536),C=Q-Y*65536,G+=Y-1+37*(Y-1),Y=1,Q=G+Y+65535,Y=Math.floor(Q/65536),G=Q-Y*65536,Q=W+Y+65535,Y=Math.floor(Q/65536),W=Q-Y*65536,Q=U+Y+65535,Y=Math.floor(Q/65536),U=Q-Y*65536,Q=M+Y+65535,Y=Math.floor(Q/65536),M=Q-Y*65536,Q=O+Y+65535,Y=Math.floor(Q/65536),O=Q-Y*65536,Q=V+Y+65535,Y=Math.floor(Q/65536),V=Q-Y*65536,Q=q+Y+65535,Y=Math.floor(Q/65536),q=Q-Y*65536,Q=H+Y+65535,Y=Math.floor(Q/65536),H=Q-Y*65536,Q=N+Y+65535,Y=Math.floor(Q/65536),N=Q-Y*65536,Q=K+Y+65535,Y=Math.floor(Q/65536),K=Q-Y*65536,Q=L+Y+65535,Y=Math.floor(Q/65536),L=Q-Y*65536,Q=A+Y+65535,Y=Math.floor(Q/65536),A=Q-Y*65536,Q=D+Y+65535,Y=Math.floor(Q/65536),D=Q-Y*65536,Q=S+Y+65535,Y=Math.floor(Q/65536),S=Q-Y*65536,Q=B+Y+65535,Y=Math.floor(Q/65536),B=Q-Y*65536,Q=C+Y+65535,Y=Math.floor(Q/65536),C=Q-Y*65536,G+=Y-1+37*(Y-1),$[0]=G,$[1]=W,$[2]=U,$[3]=M,$[4]=O,$[5]=V,$[6]=q,$[7]=H,$[8]=N,$[9]=K,$[10]=L,$[11]=A,$[12]=D,$[13]=S,$[14]=B,$[15]=C}});var IW=q$(($N,SW)=>{var CJ=F$();_$();_J();CX();SW.exports=CJ.kem=CJ.kem||{};var jW=CJ.jsbn.BigInteger;CJ.kem.rsa={};CJ.kem.rsa.create=function($,J){J=J||{};var X=J.prng||CJ.random,Q={};return Q.encrypt=function(Y,G){var W=Math.ceil(Y.n.bitLength()/8),U;do U=new jW(CJ.util.bytesToHex(X.getBytesSync(W)),16).mod(Y.n);while(U.compareTo(jW.ONE)<=0);U=CJ.util.hexToBytes(U.toString(16));var M=W-U.length;if(M>0)U=CJ.util.fillString(String.fromCharCode(0),M)+U;var O=Y.encrypt(U,"NONE"),V=$.generate(U,G);return{encapsulation:O,key:V}},Q.decrypt=function(Y,G,W){var U=Y.decrypt(G,"NONE");return $.generate(U,W)},Q};CJ.kem.kdf1=function($,J){TW(this,$,0,J||$.digestLength)};CJ.kem.kdf2=function($,J){TW(this,$,1,J||$.digestLength)};function TW($,J,X,Q){$.generate=function(Y,G){var W=new CJ.util.ByteBuffer,U=Math.ceil(G/Q)+X,M=new CJ.util.ByteBuffer;for(var O=X;O<U;++O){M.putInt32(O),J.start(),J.update(Y+M.getBytes());var V=J.digest();W.putBytes(V.getBytes(Q))}return W.truncate(W.length()-G),W.getBytes()}}});var wW=q$((JN,CW)=>{var T$=F$();_$();CW.exports=T$.log=T$.log||{};T$.log.levels=["none","error","warning","info","debug","verbose","max"];var rY={},i8=[],yX=null;T$.log.LEVEL_LOCKED=2;T$.log.NO_LEVEL_CHECK=4;T$.log.INTERPOLATE=8;for(bJ=0;bJ<T$.log.levels.length;++bJ)aY=T$.log.levels[bJ],rY[aY]={index:bJ,name:aY.toUpperCase()};var aY,bJ;T$.log.logMessage=function($){var J=rY[$.level].index;for(var X=0;X<i8.length;++X){var Q=i8[X];if(Q.flags&T$.log.NO_LEVEL_CHECK)Q.f($);else{var Y=rY[Q.level].index;if(J<=Y)Q.f(Q,$)}}};T$.log.prepareStandard=function($){if(!("standard"in $))$.standard=rY[$.level].name+" ["+$.category+"] "+$.message};T$.log.prepareFull=function($){if(!("full"in $)){var J=[$.message];J=J.concat([]),$.full=T$.util.format.apply(this,J)}};T$.log.prepareStandardFull=function($){if(!("standardFull"in $))T$.log.prepareStandard($),$.standardFull=$.standard};sY=["error","warning","info","debug","verbose"];for(bJ=0;bJ<sY.length;++bJ)(function(J){T$.log[J]=function(X,Q){var Y=Array.prototype.slice.call(arguments).slice(2),G={timestamp:new Date,level:J,category:X,message:Q,arguments:Y};T$.log.logMessage(G)}})(sY[bJ]);var sY,bJ;T$.log.makeLogger=function($){var J={flags:0,f:$};return T$.log.setLevel(J,"none"),J};T$.log.setLevel=function($,J){var X=!1;if($&&!($.flags&T$.log.LEVEL_LOCKED))for(var Q=0;Q<T$.log.levels.length;++Q){var Y=T$.log.levels[Q];if(J==Y){$.level=J,X=!0;break}}return X};T$.log.lock=function($,J){if(typeof J>"u"||J)$.flags|=T$.log.LEVEL_LOCKED;else $.flags&=~T$.log.LEVEL_LOCKED};T$.log.addLogger=function($){i8.push($)};if(typeof console<"u"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug)o8={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},uQ=function($,J){T$.log.prepareStandard(J);var X=o8[J.level],Q=[J.standard];Q=Q.concat(J.arguments.slice()),X.apply(console,Q)},HQ=T$.log.makeLogger(uQ);else uQ=function(J,X){T$.log.prepareStandardFull(X),console.log(X.standardFull)},HQ=T$.log.makeLogger(uQ);T$.log.setLevel(HQ,"debug"),T$.log.addLogger(HQ),yX=HQ}else console={log:function(){}};var HQ,o8,uQ;if(yX!==null&&typeof window<"u"&&window.location){if(hQ=new URL(window.location.href).searchParams,hQ.has("console.level"))T$.log.setLevel(yX,hQ.get("console.level").slice(-1)[0]);if(hQ.has("console.lock")){if(a8=hQ.get("console.lock").slice(-1)[0],a8=="true")T$.log.lock(yX)}}var hQ,a8;T$.log.consoleLogger=yX});var _W=q$((QN,PW)=>{PW.exports=J0();wY();_Q();M8();h8()});var kW=q$((XN,vW)=>{var p=F$();_0();lJ();SX();x0();YQ();B8();_J();_$();pY();var j=p.asn1,DJ=vW.exports=p.pkcs7=p.pkcs7||{};DJ.messageFromPem=function($){var J=p.pem.decode($)[0];if(J.type!=="PKCS7"){var X=Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw X.headerType=J.type,X}if(J.procType&&J.procType.type==="ENCRYPTED")throw Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var Q=j.fromDer(J.body);return DJ.messageFromAsn1(Q)};DJ.messageToPem=function($,J){var X={type:"PKCS7",body:j.toDer($.toAsn1()).getBytes()};return p.pem.encode(X,{maxline:J})};DJ.messageFromAsn1=function($){var J={},X=[];if(!j.validate($,DJ.asn1.contentInfoValidator,J,X)){var Q=Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw Q.errors=X,Q}var Y=j.derToOid(J.contentType),G;switch(Y){case p.pki.oids.envelopedData:G=DJ.createEnvelopedData();break;case p.pki.oids.encryptedData:G=DJ.createEncryptedData();break;case p.pki.oids.signedData:G=DJ.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+Y+" is not (yet) supported.")}return G.fromAsn1(J.content.value[0]),G};DJ.createSignedData=function(){var $=null;return $={type:p.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(Q){if(r8($,Q,DJ.asn1.signedDataValidator),$.certificates=[],$.crls=[],$.digestAlgorithmIdentifiers=[],$.contentInfo=null,$.signerInfos=[],$.rawCapture.certificates){var Y=$.rawCapture.certificates.value;for(var G=0;G<Y.length;++G)$.certificates.push(p.pki.certificateFromAsn1(Y[G]))}},toAsn1:function(){if(!$.contentInfo)$.sign();var Q=[];for(var Y=0;Y<$.certificates.length;++Y)Q.push(p.pki.certificateToAsn1($.certificates[Y]));var G=[],W=j.create(j.Class.CONTEXT_SPECIFIC,0,!0,[j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.INTEGER,!1,j.integerToDer($.version).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.SET,!0,$.digestAlgorithmIdentifiers),$.contentInfo])]);if(Q.length>0)W.value[0].value.push(j.create(j.Class.CONTEXT_SPECIFIC,0,!0,Q));if(G.length>0)W.value[0].value.push(j.create(j.Class.CONTEXT_SPECIFIC,1,!0,G));return W.value[0].value.push(j.create(j.Class.UNIVERSAL,j.Type.SET,!0,$.signerInfos)),j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer($.type).getBytes()),W])},addSigner:function(Q){var{issuer:Y,serialNumber:G}=Q;if(Q.certificate){var W=Q.certificate;if(typeof W==="string")W=p.pki.certificateFromPem(W);Y=W.issuer.attributes,G=W.serialNumber}var U=Q.key;if(!U)throw Error("Could not add PKCS#7 signer; no private key specified.");if(typeof U==="string")U=p.pki.privateKeyFromPem(U);var M=Q.digestAlgorithm||p.pki.oids.sha1;switch(M){case p.pki.oids.sha1:case p.pki.oids.sha256:case p.pki.oids.sha384:case p.pki.oids.sha512:case p.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+M)}var O=Q.authenticatedAttributes||[];if(O.length>0){var V=!1,q=!1;for(var H=0;H<O.length;++H){var N=O[H];if(!V&&N.type===p.pki.oids.contentType){if(V=!0,q)break;continue}if(!q&&N.type===p.pki.oids.messageDigest){if(q=!0,V)break;continue}}if(!V||!q)throw Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}$.signers.push({key:U,version:1,issuer:Y,serialNumber:G,digestAlgorithm:M,signatureAlgorithm:p.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:O,unauthenticatedAttributes:[]})},sign:function(Q){if(Q=Q||{},typeof $.content!=="object"||$.contentInfo===null){if($.contentInfo=j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer(p.pki.oids.data).getBytes())]),"content"in $){var Y;if($.content instanceof p.util.ByteBuffer)Y=$.content.bytes();else if(typeof $.content==="string")Y=p.util.encodeUtf8($.content);if(Q.detached)$.detachedContent=j.create(j.Class.UNIVERSAL,j.Type.OCTETSTRING,!1,Y);else $.contentInfo.value.push(j.create(j.Class.CONTEXT_SPECIFIC,0,!0,[j.create(j.Class.UNIVERSAL,j.Type.OCTETSTRING,!1,Y)]))}}if($.signers.length===0)return;var G=J();X(G)},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(Q){if(typeof Q==="string")Q=p.pki.certificateFromPem(Q);$.certificates.push(Q)},addCertificateRevokationList:function(Q){throw Error("PKCS#7 CRL support not yet implemented.")}},$;function J(){var Q={};for(var Y=0;Y<$.signers.length;++Y){var G=$.signers[Y],W=G.digestAlgorithm;if(!(W in Q))Q[W]=p.md[p.pki.oids[W]].create();if(G.authenticatedAttributes.length===0)G.md=Q[W];else G.md=p.md[p.pki.oids[W]].create()}$.digestAlgorithmIdentifiers=[];for(var W in Q)$.digestAlgorithmIdentifiers.push(j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer(W).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.NULL,!1,"")]));return Q}function X(Q){var Y;if($.detachedContent)Y=$.detachedContent;else Y=$.contentInfo.value[1],Y=Y.value[0];if(!Y)throw Error("Could not sign PKCS#7 message; there is no content to sign.");var G=j.derToOid($.contentInfo.value[0].value),W=j.toDer(Y);W.getByte(),j.getBerValueLength(W),W=W.getBytes();for(var U in Q)Q[U].start().update(W);var M=new Date;for(var O=0;O<$.signers.length;++O){var V=$.signers[O];if(V.authenticatedAttributes.length===0){if(G!==p.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{V.authenticatedAttributesAsn1=j.create(j.Class.CONTEXT_SPECIFIC,0,!0,[]);var q=j.create(j.Class.UNIVERSAL,j.Type.SET,!0,[]);for(var H=0;H<V.authenticatedAttributes.length;++H){var N=V.authenticatedAttributes[H];if(N.type===p.pki.oids.messageDigest)N.value=Q[V.digestAlgorithm].digest();else if(N.type===p.pki.oids.signingTime){if(!N.value)N.value=M}q.value.push(s8(N)),V.authenticatedAttributesAsn1.value.push(s8(N))}W=j.toDer(q).getBytes(),V.md.start().update(W)}V.signature=V.key.sign(V.md,"RSASSA-PKCS1-V1_5")}$.signerInfos=nq($.signers)}};DJ.createEncryptedData=function(){var $=null;return $={type:p.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:p.pki.oids["aes256-CBC"]},fromAsn1:function(J){r8($,J,DJ.asn1.encryptedDataValidator)},decrypt:function(J){if(J!==void 0)$.encryptedContent.key=J;xW($)}},$};DJ.createEnvelopedData=function(){var $=null;return $={type:p.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:p.pki.oids["aes256-CBC"]},fromAsn1:function(J){var X=r8($,J,DJ.asn1.envelopedDataValidator);$.recipients=pq(X.recipientInfos.value)},toAsn1:function(){return j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer($.type).getBytes()),j.create(j.Class.CONTEXT_SPECIFIC,0,!0,[j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.INTEGER,!1,j.integerToDer($.version).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.SET,!0,dq($.recipients)),j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,iq($.encryptedContent))])])])},findRecipient:function(J){var X=J.issuer.attributes;for(var Q=0;Q<$.recipients.length;++Q){var Y=$.recipients[Q],G=Y.issuer;if(Y.serialNumber!==J.serialNumber)continue;if(G.length!==X.length)continue;var W=!0;for(var U=0;U<X.length;++U)if(G[U].type!==X[U].type||G[U].value!==X[U].value){W=!1;break}if(W)return Y}return null},decrypt:function(J,X){if($.encryptedContent.key===void 0&&J!==void 0&&X!==void 0)switch(J.encryptedContent.algorithm){case p.pki.oids.rsaEncryption:case p.pki.oids.desCBC:var Q=X.decrypt(J.encryptedContent.content);$.encryptedContent.key=p.util.createBuffer(Q);break;default:throw Error("Unsupported asymmetric cipher, OID "+J.encryptedContent.algorithm)}xW($)},addRecipient:function(J){$.recipients.push({version:0,issuer:J.issuer.attributes,serialNumber:J.serialNumber,encryptedContent:{algorithm:p.pki.oids.rsaEncryption,key:J.publicKey}})},encrypt:function(J,X){if($.encryptedContent.content===void 0){X=X||$.encryptedContent.algorithm,J=J||$.encryptedContent.key;var Q,Y,G;switch(X){case p.pki.oids["aes128-CBC"]:Q=16,Y=16,G=p.aes.createEncryptionCipher;break;case p.pki.oids["aes192-CBC"]:Q=24,Y=16,G=p.aes.createEncryptionCipher;break;case p.pki.oids["aes256-CBC"]:Q=32,Y=16,G=p.aes.createEncryptionCipher;break;case p.pki.oids["des-EDE3-CBC"]:Q=24,Y=8,G=p.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+X)}if(J===void 0)J=p.util.createBuffer(p.random.getBytes(Q));else if(J.length()!=Q)throw Error("Symmetric key has wrong length; got "+J.length()+" bytes, expected "+Q+".");$.encryptedContent.algorithm=X,$.encryptedContent.key=J,$.encryptedContent.parameter=p.util.createBuffer(p.random.getBytes(Y));var W=G(J);if(W.start($.encryptedContent.parameter.copy()),W.update($.content),!W.finish())throw Error("Symmetric encryption failed.");$.encryptedContent.content=W.output}for(var U=0;U<$.recipients.length;++U){var M=$.recipients[U];if(M.encryptedContent.content!==void 0)continue;switch(M.encryptedContent.algorithm){case p.pki.oids.rsaEncryption:M.encryptedContent.content=M.encryptedContent.key.encrypt($.encryptedContent.key.data);break;default:throw Error("Unsupported asymmetric cipher, OID "+M.encryptedContent.algorithm)}}}},$};function mq($){var J={},X=[];if(!j.validate($,DJ.asn1.recipientInfoValidator,J,X)){var Q=Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw Q.errors=X,Q}return{version:J.version.charCodeAt(0),issuer:p.pki.RDNAttributesAsArray(J.issuer),serialNumber:p.util.createBuffer(J.serial).toHex(),encryptedContent:{algorithm:j.derToOid(J.encAlgorithm),parameter:J.encParameter?J.encParameter.value:void 0,content:J.encKey}}}function lq($){return j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.INTEGER,!1,j.integerToDer($.version).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[p.pki.distinguishedNameToAsn1({attributes:$.issuer}),j.create(j.Class.UNIVERSAL,j.Type.INTEGER,!1,p.util.hexToBytes($.serialNumber))]),j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer($.encryptedContent.algorithm).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.NULL,!1,"")]),j.create(j.Class.UNIVERSAL,j.Type.OCTETSTRING,!1,$.encryptedContent.content)])}function pq($){var J=[];for(var X=0;X<$.length;++X)J.push(mq($[X]));return J}function dq($){var J=[];for(var X=0;X<$.length;++X)J.push(lq($[X]));return J}function cq($){var J=j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.INTEGER,!1,j.integerToDer($.version).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[p.pki.distinguishedNameToAsn1({attributes:$.issuer}),j.create(j.Class.UNIVERSAL,j.Type.INTEGER,!1,p.util.hexToBytes($.serialNumber))]),j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer($.digestAlgorithm).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.NULL,!1,"")])]);if($.authenticatedAttributesAsn1)J.value.push($.authenticatedAttributesAsn1);if(J.value.push(j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer($.signatureAlgorithm).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.NULL,!1,"")])),J.value.push(j.create(j.Class.UNIVERSAL,j.Type.OCTETSTRING,!1,$.signature)),$.unauthenticatedAttributes.length>0){var X=j.create(j.Class.CONTEXT_SPECIFIC,1,!0,[]);for(var Q=0;Q<$.unauthenticatedAttributes.length;++Q){var Y=$.unauthenticatedAttributes[Q];X.values.push(s8(Y))}J.value.push(X)}return J}function nq($){var J=[];for(var X=0;X<$.length;++X)J.push(cq($[X]));return J}function s8($){var J;if($.type===p.pki.oids.contentType)J=j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer($.value).getBytes());else if($.type===p.pki.oids.messageDigest)J=j.create(j.Class.UNIVERSAL,j.Type.OCTETSTRING,!1,$.value.bytes());else if($.type===p.pki.oids.signingTime){var X=new Date("1950-01-01T00:00:00Z"),Q=new Date("2050-01-01T00:00:00Z"),Y=$.value;if(typeof Y==="string"){var G=Date.parse(Y);if(!isNaN(G))Y=new Date(G);else if(Y.length===13)Y=j.utcTimeToDate(Y);else Y=j.generalizedTimeToDate(Y)}if(Y>=X&&Y<Q)J=j.create(j.Class.UNIVERSAL,j.Type.UTCTIME,!1,j.dateToUtcTime(Y));else J=j.create(j.Class.UNIVERSAL,j.Type.GENERALIZEDTIME,!1,j.dateToGeneralizedTime(Y))}return j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer($.type).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.SET,!0,[J])])}function iq($){return[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer(p.pki.oids.data).getBytes()),j.create(j.Class.UNIVERSAL,j.Type.SEQUENCE,!0,[j.create(j.Class.UNIVERSAL,j.Type.OID,!1,j.oidToDer($.algorithm).getBytes()),!$.parameter?void 0:j.create(j.Class.UNIVERSAL,j.Type.OCTETSTRING,!1,$.parameter.getBytes())]),j.create(j.Class.CONTEXT_SPECIFIC,0,!0,[j.create(j.Class.UNIVERSAL,j.Type.OCTETSTRING,!1,$.content.getBytes())])]}function r8($,J,X){var Q={},Y=[];if(!j.validate(J,X,Q,Y)){var G=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw G.errors=G,G}var W=j.derToOid(Q.contentType);if(W!==p.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(Q.encryptedContent){var U="";if(p.util.isArray(Q.encryptedContent))for(var M=0;M<Q.encryptedContent.length;++M){if(Q.encryptedContent[M].type!==j.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");U+=Q.encryptedContent[M].value}else U=Q.encryptedContent;$.encryptedContent={algorithm:j.derToOid(Q.encAlgorithm),parameter:p.util.createBuffer(Q.encParameter.value),content:p.util.createBuffer(U)}}if(Q.content){var U="";if(p.util.isArray(Q.content))for(var M=0;M<Q.content.length;++M){if(Q.content[M].type!==j.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");U+=Q.content[M].value}else U=Q.content;$.content=p.util.createBuffer(U)}return $.version=Q.version.charCodeAt(0),$.rawCapture=Q,Q}function xW($){if($.encryptedContent.key===void 0)throw Error("Symmetric key not available.");if($.content===void 0){var J;switch($.encryptedContent.algorithm){case p.pki.oids["aes128-CBC"]:case p.pki.oids["aes192-CBC"]:case p.pki.oids["aes256-CBC"]:J=p.aes.createDecryptionCipher($.encryptedContent.key);break;case p.pki.oids.desCBC:case p.pki.oids["des-EDE3-CBC"]:J=p.des.createDecryptionCipher($.encryptedContent.key);break;default:throw Error("Unsupported symmetric cipher, OID "+$.encryptedContent.algorithm)}if(J.start($.encryptedContent.parameter),J.update($.encryptedContent.content),!J.finish())throw Error("Symmetric decryption failed.");$.content=J.output}}});var yW=q$((YN,fW)=>{var QJ=F$();_0();IQ();wY();_Q();_$();var eY=fW.exports=QJ.ssh=QJ.ssh||{};eY.privateKeyToPutty=function($,J,X){X=X||"",J=J||"";var Q="ssh-rsa",Y=J===""?"none":"aes256-cbc",G="PuTTY-User-Key-File-2: "+Q+`\r
16
+ `;G+="Encryption: "+Y+`\r
17
+ `,G+="Comment: "+X+`\r
18
+ `;var W=QJ.util.createBuffer();gQ(W,Q),O0(W,$.e),O0(W,$.n);var U=QJ.util.encode64(W.bytes(),64),M=Math.floor(U.length/66)+1;G+="Public-Lines: "+M+`\r
19
+ `,G+=U;var O=QJ.util.createBuffer();O0(O,$.d),O0(O,$.p),O0(O,$.q),O0(O,$.qInv);var V;if(!J)V=QJ.util.encode64(O.bytes(),64);else{var q=O.length()+16-1;q-=q%16;var H=tY(O.bytes());H.truncate(H.length()-q+O.length()),O.putBuffer(H);var N=QJ.util.createBuffer();N.putBuffer(tY("\x00\x00\x00\x00",J)),N.putBuffer(tY("\x00\x00\x00\x01",J));var K=QJ.aes.createEncryptionCipher(N.truncate(8),"CBC");K.start(QJ.util.createBuffer().fillWithByte(0,16)),K.update(O.copy()),K.finish();var L=K.output;L.truncate(16),V=QJ.util.encode64(L.bytes(),64)}M=Math.floor(V.length/66)+1,G+=`\r
20
+ Private-Lines: `+M+`\r
21
+ `,G+=V;var A=tY("putty-private-key-file-mac-key",J),D=QJ.util.createBuffer();gQ(D,Q),gQ(D,Y),gQ(D,X),D.putInt32(W.length()),D.putBuffer(W),D.putInt32(O.length()),D.putBuffer(O);var S=QJ.hmac.create();return S.start("sha1",A),S.update(D.bytes()),G+=`\r
22
+ Private-MAC: `+S.digest().toHex()+`\r
23
+ `,G};eY.publicKeyToOpenSSH=function($,J){var X="ssh-rsa";J=J||"";var Q=QJ.util.createBuffer();return gQ(Q,X),O0(Q,$.e),O0(Q,$.n),X+" "+QJ.util.encode64(Q.bytes())+" "+J};eY.privateKeyToOpenSSH=function($,J){if(!J)return QJ.pki.privateKeyToPem($);return QJ.pki.encryptRsaPrivateKey($,J,{legacy:!0,algorithm:"aes128"})};eY.getPublicKeyFingerprint=function($,J){J=J||{};var X=J.md||QJ.md.md5.create(),Q="ssh-rsa",Y=QJ.util.createBuffer();gQ(Y,Q),O0(Y,$.e),O0(Y,$.n),X.start(),X.update(Y.getBytes());var G=X.digest();if(J.encoding==="hex"){var W=G.toHex();if(J.delimiter)return W.match(/.{2}/g).join(J.delimiter);return W}else if(J.encoding==="binary")return G.getBytes();else if(J.encoding)throw Error('Unknown encoding "'+J.encoding+'".');return G};function O0($,J){var X=J.toString(16);if(X[0]>="8")X="00"+X;var Q=QJ.util.hexToBytes(X);$.putInt32(Q.length),$.putBytes(Q)}function gQ($,J){$.putInt32(J.length),$.putString(J)}function tY(){var $=QJ.md.sha1.create(),J=arguments.length;for(var X=0;X<J;++X)$.update(arguments[X]);return $.digest()}});var t8=q$((GN,bW)=>{bW.exports=F$();_0();WW();lJ();ZY();SX();BW();IQ();IW();wW();_W();j8();vY();YQ();N8();I8();kW();w8();A8();O8();gY();_J();H8();yW();f8();_$()});var Z4=q$((UL,D4)=>{var{create:o6,defineProperty:O9,getOwnPropertyDescriptor:a6,getOwnPropertyNames:s6,getPrototypeOf:r6}=Object,t6=Object.prototype.hasOwnProperty,e6=($,J)=>{for(var X in J)O9($,X,{get:J[X],enumerable:!0})},F4=($,J,X,Q)=>{if(J&&typeof J==="object"||typeof J==="function"){for(let Y of s6(J))if(!t6.call($,Y)&&Y!==X)O9($,Y,{get:()=>J[Y],enumerable:!(Q=a6(J,Y))||Q.enumerable})}return $},N4=($,J,X)=>(X=$!=null?o6(r6($)):{},F4(J||!$||!$.__esModule?O9(X,"default",{value:$,enumerable:!0}):X,$)),$H=($)=>F4(O9({},"__esModule",{value:!0}),$),L4={};e6(L4,{Socks5Server:()=>R4,createServer:()=>YH,defaultConnectionHandler:()=>B7});D4.exports=$H(L4);var JH=N4(FX("net")),A4=(($)=>{return $[$.connect=1]="connect",$[$.bind=2]="bind",$[$.udp=3]="udp",$})(A4||{}),Z7=(($)=>{return $[$.REQUEST_GRANTED=0]="REQUEST_GRANTED",$[$.GENERAL_FAILURE=1]="GENERAL_FAILURE",$[$.CONNECTION_NOT_ALLOWED=2]="CONNECTION_NOT_ALLOWED",$[$.NETWORK_UNREACHABLE=3]="NETWORK_UNREACHABLE",$[$.HOST_UNREACHABLE=4]="HOST_UNREACHABLE",$[$.CONNECTION_REFUSED=5]="CONNECTION_REFUSED",$[$.TTL_EXPIRED=6]="TTL_EXPIRED",$[$.COMMAND_NOT_SUPPORTED=7]="COMMAND_NOT_SUPPORTED",$[$.ADDRESS_TYPE_NOT_SUPPORTED=8]="ADDRESS_TYPE_NOT_SUPPORTED",$})(Z7||{}),QH=class{constructor($,J){this.errorHandler=()=>{},this.metadata={},this.socket=J,this.server=$,J.on("error",this.errorHandler),J.pause(),this.handleGreeting()}readBytes($){return new Promise((J)=>{let X=Buffer.allocUnsafe($),Q=0,Y=(G)=>{let W=Math.min(G.length,$-Q);if(G.copy(X,Q,0,W),Q+=W,Q<$)return;this.socket.removeListener("data",Y),this.socket.push(G.subarray(W)),J(X),this.socket.pause()};this.socket.on("data",Y),this.socket.resume()})}async handleGreeting(){if((await this.readBytes(1)).readUInt8()!==5)return this.socket.destroy();let J=(await this.readBytes(1)).readUInt8();if(J>128||J===0)return this.socket.destroy();let X=await this.readBytes(J),Q=this.server.authHandler?2:0;if(!X.includes(Q))return this.socket.write(Buffer.from([5,255])),this.socket.destroy();if(this.socket.write(Buffer.from([5,Q])),this.server.authHandler)this.handleUserPassword();else this.handleConnectionRequest()}async handleUserPassword(){await this.readBytes(1);let $=(await this.readBytes(1)).readUint8(),J=(await this.readBytes($)).toString(),X=(await this.readBytes(1)).readUint8(),Q=(await this.readBytes(X)).toString();this.username=J,this.password=Q;let Y=!1,G=()=>{if(Y)return;Y=!0,this.socket.write(Buffer.from([1,0])),this.handleConnectionRequest()},W=()=>{if(Y)return;Y=!0,this.socket.write(Buffer.from([1,1])),this.socket.destroy()},U=await this.server.authHandler(this,G,W);if(U===!0)G();else if(U===!1)W()}async handleConnectionRequest(){await this.readBytes(1);let $=(await this.readBytes(1))[0],J=A4[$];if(!J)return this.socket.destroy();this.command=J,await this.readBytes(1);let X=(await this.readBytes(1)).readUInt8(),Q="";switch(X){case 1:Q=(await this.readBytes(4)).join(".");break;case 3:let O=(await this.readBytes(1)).readUInt8();Q=(await this.readBytes(O)).toString();break;case 4:let V=await this.readBytes(16);for(let q=0;q<16;q++){if(q%2===0&&q>0)Q+=":";Q+=`${V[q]<16?"0":""}${V[q].toString(16)}`}break;default:this.socket.destroy();return}let Y=(await this.readBytes(2)).readUInt16BE();if(!this.server.supportedCommands.has(J))return this.socket.write(Buffer.from([5,7])),this.socket.destroy();this.destAddress=Q,this.destPort=Y;let G=!1,W=()=>{if(G)return;G=!0,this.connect()};if(!this.server.rulesetValidator)return W();let U=()=>{if(G)return;G=!0,this.socket.write(Buffer.from([5,2,0,1,0,0,0,0,0,0])),this.socket.destroy()},M=await this.server.rulesetValidator(this,W,U);if(M===!0)W();else if(M===!1)U()}connect(){this.socket.removeListener("error",this.errorHandler),this.server.connectionHandler(this,($)=>{if(Z7[$]===void 0)throw Error(`"${$}" is not a valid status.`);if(this.socket.write(Buffer.from([5,Z7[$],0,1,0,0,0,0,0,0])),$!=="REQUEST_GRANTED")this.socket.destroy()}),this.socket.resume()}},XH=N4(FX("net"));function B7($,J){if($.command!=="connect")return J("COMMAND_NOT_SUPPORTED");$.socket.on("error",()=>{});let X=XH.default.createConnection({host:$.destAddress,port:$.destPort});X.setNoDelay();let Q=!1;return X.on("error",(Y)=>{if(!Q)switch(Y.code){case"EINVAL":case"ENOENT":case"ENOTFOUND":case"ETIMEDOUT":case"EADDRNOTAVAIL":case"EHOSTUNREACH":J("HOST_UNREACHABLE");break;case"ENETUNREACH":J("NETWORK_UNREACHABLE");break;case"ECONNREFUSED":J("CONNECTION_REFUSED");break;default:J("GENERAL_FAILURE")}}),X.on("ready",()=>{Q=!0,J("REQUEST_GRANTED"),$.socket.pipe(X).pipe($.socket)}),$.socket.on("close",()=>X.destroy()),X}var R4=class{constructor(){this.supportedCommands=new Set(["connect"]),this.connectionHandler=B7,this.server=JH.default.createServer(($)=>{$.setNoDelay(),this._handleConnection($)})}listen(...$){return this.server.listen(...$),this}close($){return this.server.close($),this}setAuthHandler($){return this.authHandler=$,this}disableAuthHandler(){return this.authHandler=void 0,this}setRulesetValidator($){return this.rulesetValidator=$,this}disableRulesetValidator(){return this.rulesetValidator=void 0,this}setConnectionHandler($){return this.connectionHandler=$,this}useDefaultConnectionHandler(){return this.connectionHandler=B7,this}_handleConnection($){return new QH(this,$),this}};function YH($){let J=new R4;if($?.auth)J.setAuthHandler((X)=>{return X.username===$.auth.username&&X.password===$.auth.password});if($?.port)J.listen($.port,$.hostname);return J}});import{Agent as l6,createServer as p6}from"http";import{request as D7}from"http";import{request as K4}from"https";import{connect as d6,isIP as c6}from"net";import{URL as z4}from"url";function Z($,J){if(!process.env.SRT_DEBUG)return;let X=J?.level||"info",Q="[SandboxDebug]";switch(X){case"error":console.error(`${Q} ${$}`);break;case"warn":console.warn(`${Q} ${$}`);break;default:console.error(`${Q} ${$}`)}}import{timingSafeEqual as $M}from"crypto";function EY($,J){let X=Buffer.from($),Q=Buffer.from(J);if(X.length!==Q.length)return!1;return $M(X,Q)}import{homedir as FY}from"os";import*as UJ from"path";import*as $Q from"fs";import*as jG from"fs";function i9(){if(process.platform!=="linux")return;try{let $=jG.readFileSync("/proc/version",{encoding:"utf8"}),J=$.match(/WSL(\d+)/i);if(J&&J[1])return J[1];if($.toLowerCase().includes("microsoft"))return"1";return}catch{return}}function x$(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"unknown"}}var NX=[".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json"],JM=[".git",".vscode",".idea"];function LY(){return[...JM.filter(($)=>$!==".git"),".claude/commands",".claude/agents"]}function o9($){return $.toLowerCase()}function NJ($){return $.includes("*")||$.includes("?")||$.includes("[")||$.includes("]")}function LX($){return $.includes("*")||$.includes("?")}function TG($){return x$()==="windows"?LX($):NJ($)}function SG($){if(/^\\\\\?\\unc\\/i.test($))return"\\\\"+$.slice(8);if($.startsWith("\\\\?\\"))return $.slice(4);return $}function AX($){let J=UJ.win32.toNamespacedPath($);return/^[\\/]{2}[?.][\\/]unc[\\/]/i.test(J)}function N0($){return $.replace(/\/\*\*$/,"")||"/"}function NY($,J){let X=UJ.normalize($),Q=UJ.normalize(J);if(Q===X)return!1;if(X.startsWith("/tmp/")&&Q==="/private"+X)return!1;if(X.startsWith("/var/")&&Q==="/private"+X)return!1;if(X.startsWith("/private/tmp/")&&Q===X)return!1;if(X.startsWith("/private/var/")&&Q===X)return!1;if(Q==="/")return!0;if(Q.split("/").filter(Boolean).length<=1)return!0;if(X.startsWith(Q+"/"))return!0;let G=X;if(X.startsWith("/tmp/"))G="/private"+X;else if(X.startsWith("/var/"))G="/private"+X;if(G!==X&&G.startsWith(Q+"/"))return!0;let W=Q.startsWith(X+"/"),U=G!==X&&Q.startsWith(G+"/");if(Q!==X&&!(G!==X&&Q===G)&&!W&&!U)return!0;return!1}function QM($){if($==="~")return FY();if($.startsWith("~/")||process.platform==="win32"&&$.startsWith("~\\"))return FY()+$.slice(1);return $}function XM($){let J=FY(),X=/^[A-Za-z]:/.test(J)?J.slice(0,2):"",Q=X?J.slice(2):J;return $.replace(/%USERPROFILE%/gi,J).replace(/%HOMEDRIVE%/gi,X).replace(/%HOMEPATH%/gi,Q)}function JJ($){let J=process.cwd();if(x$()==="windows"){if($=SG(XM($)),/^[a-z]:/.test($))$=$[0].toUpperCase()+$.slice(1);if(AX($)&&!LX($))return UJ.win32.normalize($)}if(x$()!=="windows"&&$.endsWith("/")&&$!=="/"&&!TG($))$=$.replace(/\/+$/,"")||"/";let X=QM($);if(X!==$);else if($.startsWith("./")||$.startsWith("../"))X=UJ.resolve(J,$);else if(!UJ.isAbsolute($))X=UJ.resolve(J,$);if(TG(X)){let Q=x$()==="windows"?/[*?]/:/[*?[\]]/,Y=X.split(Q)[0];if(Y&&Y!=="/"){let G=Y.endsWith("/")?Y.slice(0,-1):UJ.dirname(Y);try{let W=$Q.realpathSync(G);if(!NY(G,W)){let U=X.slice(G.length);return W+U}}catch{}}return X}try{let Q=$Q.realpathSync(X);if(NY(X,Q));else X=Q}catch{}return X}function BQ($){let J=$??FY();return["/dev/stdout","/dev/stderr","/dev/null","/dev/tty","/dev/dtracehelper","/dev/autofs_nowait","/tmp/claude","/private/tmp/claude",UJ.join(J,".npm/_logs"),UJ.join(J,".claude/debug")]}var YM=["NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","CURL_CA_BUNDLE","REQUESTS_CA_BUNDLE","PIP_CERT","GIT_SSL_CAINFO","AWS_CA_BUNDLE","CARGO_HTTP_CAINFO","DENO_CERT","CLOUDSDK_CORE_CUSTOM_CA_CERTS_FILE","NIX_SSL_CERT_FILE"];function jQ($,J,X,Q,Y,G){let W=WM(G),U=W===F0?W:encodeURIComponent(W),M=Q?`${U}:${Q}@`:"",O=x$()==="linux"?"127.0.0.1":"localhost",V=["SANDBOX_RUNTIME=1"];if(!Y){let N=process.env.CLAUDE_CODE_TMPDIR||process.env.CLAUDE_TMPDIR||"/tmp/claude";V.push(`TMPDIR=${N}`)}if(X)for(let N of YM)V.push(`${N}=${X}`);if(!$&&!J)return V;let q=["localhost","127.0.0.1","::1","169.254.0.0/16","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"].join(",");if(V.push(`NO_PROXY=${q}`),V.push(`no_proxy=${q}`),$){if(V.push(`HTTP_PROXY=http://${M}${O}:${$}`),V.push(`HTTPS_PROXY=http://${M}${O}:${$}`),V.push(`http_proxy=http://${M}${O}:${$}`),V.push(`https_proxy=http://${M}${O}:${$}`),Q)V.push("GIT_CONFIG_PARAMETERS='http.proxyAuthMethod=basic'")}let H=$?`http://${M}${O}:${$}`:`socks5h://${M}${O}:${J}`;if(V.push(`ALL_PROXY=${H}`),V.push(`all_proxy=${H}`),V.push(`GRPC_PROXY=${H}`),V.push(`grpc_proxy=${H}`),J){let K=x$();if(K==="macos")V.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='nc -X 5 -x localhost:${J} %h %p'`);else if(K==="linux"&&$){let L=Q?`,proxyauth=${W}:${Q}`:"";V.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='socat - PROXY:${O}:%h:%p,proxyport=${$}${L}'`)}if(V.push(`FTP_PROXY=socks5h://${M}${O}:${J}`),V.push(`ftp_proxy=socks5h://${M}${O}:${J}`),V.push(`RSYNC_PROXY=${O}:${J}`),V.push(`DOCKER_HTTP_PROXY=http://${M}${O}:${$||J}`),V.push(`DOCKER_HTTPS_PROXY=http://${M}${O}:${$||J}`),$){if(V.push("CLOUDSDK_PROXY_TYPE=http"),V.push(`CLOUDSDK_PROXY_ADDRESS=${O}`),V.push(`CLOUDSDK_PROXY_PORT=${$}`),Q)V.push(`CLOUDSDK_PROXY_USERNAME=${W}`),V.push(`CLOUDSDK_PROXY_PASSWORD=${Q}`)}}return V}var GM=8;function RX($){if($.baseEnv?.GIT_CONFIG_COUNT==="0")return{};let J=Number.parseInt($.baseEnv?.GIT_CONFIG_COUNT??"",10),X=Number.isFinite(J)&&J>=0?J:0,Q=X,Y={},G=(U,M)=>{Y[`GIT_CONFIG_KEY_${Q}`]=U,Y[`GIT_CONFIG_VALUE_${Q}`]=M,Q++},W=[...new Set($.safeDirs.filter((U)=>!!U).map((U)=>{let O=U.replace(/\\/g,"/").replace(/\/+$/,"");if(O===""||/^[A-Za-z]:$/.test(O))return`${O}/`;return O}))];if(W.length>GM)G("safe.directory","*");else for(let U of W)G("safe.directory",U),G("safe.directory",U.endsWith("/")?`${U}*`:`${U}/*`);if($.schannelCa)G("http.schannelUseSSLCAInfo","true"),G("http.schannelCheckRevoke","false");if(Q===X)return{};return Y.GIT_CONFIG_COUNT=String(Q),Y}function AY($){let J={GIT_CONFIG_COUNT:process.env.GIT_CONFIG_COUNT};for(let X of $.unsetEnvVars??[])delete J[X];return Object.assign(J,$.setEnvVars??{}),RX({safeDirs:$.safeDirs,baseEnv:J})}function PJ($){let J=$.slice(0,100);return Buffer.from(J).toString("base64")}function JQ($){return Buffer.from($,"base64").toString("utf8")}var F0="srt";function WM($){if(!$)return F0;let J=`${F0}.${$}`;return Buffer.byteLength(J)<=255?J:F0}function RY($){if(!$||!$.startsWith(`${F0}.`))return;return $.slice(F0.length+1)||void 0}function DX($){return"^"+$.replace(/[.^$+{}()|\\]/g,"\\$&").replace(/\[([^\]]*?)$/g,"\\[$1").replace(/\*\*\//g,"__GLOBSTAR_SLASH__").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/__GLOBSTAR_SLASH__/g,"(.*/)?").replace(/__GLOBSTAR__/g,".*")+"$"}function QQ($,J={}){let X=(M)=>process.platform==="win32"?M.replace(/\\/g,"/"):M,Q=X(JJ($)),Y=Q.split(/[*?[\]]/)[0];if(!Y||Y==="/")return Z(`[Sandbox] Glob pattern too broad, skipping: ${$}`),[];let G=Y.endsWith("/")?Y.slice(0,-1):UJ.dirname(Y);if(!$Q.existsSync(G))return Z(`[Sandbox] Base directory for glob does not exist: ${G}`),[];let W=new RegExp(DX(Q),J.caseInsensitive?"i":""),U=[];try{let M=$Q.readdirSync(G,{recursive:!0,withFileTypes:!0});for(let O of M){let V=O.parentPath??O.path??G,q=UJ.join(V,O.name);if(W.test(X(q)))U.push(q)}}catch(M){Z(`[Sandbox] Error expanding glob pattern ${$}: ${M}`)}return U}var gW=n9(t8(),1);import{sign as oq,X509Certificate as aq}from"crypto";import{mkdtempSync as $7,readFileSync as J7,writeFileSync as Q7}from"fs";import{rm as sq}from"fs/promises";import{tmpdir as X7}from"os";import{join as lQ,dirname as e8}from"path";import{rootCertificates as rq}from"tls";var{asn1:r$,pki:dJ,md:tq,random:eq,util:mW}=gW.default,$6=dJ.getTBSCertificate,J6=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,$9="/srt.crl";function Y7($){let J=$.getExtension("subjectKeyIdentifier");return J?.subjectKeyIdentifier?mW.hexToBytes(J.subjectKeyIdentifier):$.generateSubjectKeyIdentifier().getBytes()}function G7($,J){let X=dJ.oids.sha256WithRSAEncryption;$.siginfo.algorithmOid=X,$.signatureOid=X,$.tbsCertificate=$6($);let Q=r$.toDer($.tbsCertificate).getBytes();$.signature=lW(Q,J),$.md=tq.sha256.create(),$.md.update(Q)}function lW($,J){return oq("sha256",Buffer.from($,"binary"),J).toString("binary")}function W7($){if($.caCertPem&&$.caKeyPem){let J=hX($.caCertPem,$.caKeyPem);if(!J.ok)throw Error(`tlsTerminate: CA PEM pair: ${J.reason}`);return U7($.caCertPem,$.caKeyPem,J.cert,J.key,{certPath:$.caCertPath??"",keyPath:$.caKeyPath??"",extraCaCertPaths:$.extraCaCertPaths})}if($.caCertPath&&$.caKeyPath)return Y6($.caCertPath,$.caKeyPath,$.extraCaCertPaths);if($.caCertPath||$.caKeyPath)throw Error("tlsTerminate: caCertPath and caKeyPath must be provided together");return G6($.extraCaCertPaths)}async function pW($){let J=new Set([e8($.trustBundlePath)]);if($.ephemeral){if(J.add(e8($.certPath)),$.keyPath)J.add(e8($.keyPath))}for(let X of J)try{await sq(X,{recursive:!0,force:!0})}catch(Q){Z(`[mitm-ca] cleanup failed: ${Q.message}`,{level:"warn"})}}function Q6($,J,X){let Q=[J.trim(),...rq],Y=process.env.NODE_EXTRA_CA_CERTS;if(Y)try{Q.push(J7(Y,"utf8").trim())}catch{}for(let W of X??[]){let U;try{U=J7(W,"utf8")}catch(O){let V=O.code??String(O);Z(`[mitm-ca] extraCaCertPaths: cannot read ${W} (${V}); skipping`,{level:"warn"});continue}let M=U.match(J6);if(!M){Z(`[mitm-ca] extraCaCertPaths: ${W} has no PEM CERTIFICATE block; skipping`,{level:"warn"});continue}Q.push(...M)}let G=lQ($,"trust-bundle.crt");return Q7(G,Q.join(`
24
24
  `)+`
25
- `,{mode:420}),a}function iv(e,t){let n=jt.oids.sha256WithRSAEncryption,r=()=>Mn([Je.create(Wt.UNIVERSAL,ur.OID,!1,Je.oidToDer(n).getBytes()),Je.create(Wt.UNIVERSAL,ur.NULL,!1,"")]),i=(f,y)=>Mn([Je.create(Wt.UNIVERSAL,ur.OID,!1,Je.oidToDer(f).getBytes()),Je.create(Wt.UNIVERSAL,ur.OCTETSTRING,!1,Je.toDer(y).getBytes())]),a=Je.create(Wt.CONTEXT_SPECIFIC,0,!0,[Mn([i(jt.oids.authorityKeyIdentifier,Mn([Je.create(Wt.CONTEXT_SPECIFIC,0,!1,ol(e))])),i("2.5.29.20",Je.create(Wt.UNIVERSAL,ur.INTEGER,!1,"\x01"))])]),s=new Date,o=e.validity.notAfter,l=o>s?o:Ii(1),c=Mn([Je.create(Wt.UNIVERSAL,ur.INTEGER,!1,"\x01"),r(),jt.distinguishedNameToAsn1(e.subject),Gd(s),Gd(l),a]),u=Xd(Je.toDer(c).getBytes(),t),d=Mn([c,r(),Je.create(Wt.UNIVERSAL,ur.BITSTRING,!1,"\x00"+u)]);return Buffer.from(Je.toDer(d).getBytes(),"binary")}var{Class:Wt,Type:ur}=Je;function Mn(e){return Je.create(Wt.UNIVERSAL,ur.SEQUENCE,!0,e)}function Gd(e){return e.getUTCFullYear()<2050?Je.create(Wt.UNIVERSAL,ur.UTCTIME,!1,Je.dateToUtcTime(e)):Je.create(Wt.UNIVERSAL,ur.GENERALIZEDTIME,!1,Je.dateToGeneralizedTime(e))}function av(e,t,n){let r=jd(e,"CERTIFICATE","tlsTerminate.caCertPath"),i=jd(t,"PRIVATE KEY","tlsTerminate.caKeyPath"),a=Ri(r,i);if(!a.ok)throw Error(`tlsTerminate: CA at ${e}: ${a.reason}`);return C(`[mitm-ca] loaded CA from ${e}`),ul(r,i,a.cert,a.key,{certPath:e,keyPath:t,extraCaCertPaths:n})}function ul(e,t,n,r,i){let a=nl(Wn(sl(),"srt-ca-"));return{certPath:i.certPath,keyPath:i.keyPath,trustBundlePath:nv(a,e,i.extraCaCertPaths),certPem:e,keyPem:t,cert:n,key:r,leafCerts:new Map,secureContexts:new Map,crlDer:iv(n,t),ephemeral:i.ephemeral??!1}}function es(e={}){let t=jt.rsa.generateKeyPair(2048),n=jt.createCertificate();n.publicKey=t.publicKey,n.serialNumber=dl(),n.validity.notBefore=Ii(-1),n.validity.notAfter=Ii(e.validityDays??825);let r=[{name:"commonName",value:e.cn??"sandbox-runtime ephemeral CA"},{name:"organizationName",value:"sandbox-runtime"}];n.setSubject(r),n.setIssuer(r),n.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",critical:!0,keyCertSign:!0,cRLSign:!0,digitalSignature:!0},{name:"subjectKeyIdentifier"}]);let i=jt.privateKeyToPem(t.privateKey);return ll(n,i),{certPem:jt.certificateToPem(n),keyPem:i,cert:n,key:t.privateKey}}function $n(e){return new Xy(e).fingerprint.replace(/:/g,"").toUpperCase()}function Ri(e,t){let n,r;try{n=jt.certificateFromPem(e),r=jt.privateKeyFromPem(t)}catch(s){return{ok:!1,reason:`parse: ${s.message}`}}if(!("n"in r)||!("d"in r))return{ok:!1,reason:"key is not RSA"};if(n.validity.notBefore.getTime()>Date.now())return{ok:!1,reason:`notBefore ${n.validity.notBefore.toISOString()} is in the future (clock skew?)`};let i=n.publicKey;if(!("n"in i)||i.n.compareTo(r.n))return{ok:!1,reason:"key does not match certificate public key"};let a;try{a=$n(e)}catch(s){return{ok:!1,reason:`thumbprint: ${s.message}`}}return{ok:!0,thumbprint:a,notAfter:n.validity.notAfter,cert:n,key:r}}function sv(e){let{certPem:t,keyPem:n,cert:r,key:i}=es(),a=nl(Wn(sl(),"srt-ca-")),s=Wn(a,"ca.crt"),o=Wn(nl(Wn(sl(),"srt-ca-key-")),"ca.key");return al(s,t,{mode:420}),al(o,n,{mode:384}),C(`[mitm-ca] generated ephemeral CA at ${s}`),ul(t,n,r,i,{certPath:s,keyPath:o,extraCaCertPaths:e,ephemeral:!0})}function jd(e,t,n){let r;try{r=il(e,"utf8")}catch(i){let a=i.code??String(i);throw Error(`${n}: cannot read ${e} (${a})`)}if(!new RegExp(`-----BEGIN [A-Z ]*${t}-----`).test(r))throw Error(`${n}: ${e} is not a PEM ${t}`);return r}function dl(){let e=ev.getBytesSync(16),t=Qd.bytesToHex(e);return(parseInt(t[0],16)&7).toString(16)+t.slice(1)}function Ii(e){let t=new Date;return t.setDate(t.getDate()+e),t}import{PassThrough as ov,Readable as Jd}from"stream";var fl=new Set(["GET","HEAD","OPTIONS"]),tf="denied by sandbox policy";function Zd(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}async function ts(e,t,n,r,i,a){let s=t.method??"GET",o,l=t,c=Boolean(t.headers["content-length"]||t.headers["transfer-encoding"]),u=fl.has(s);if(!u||c){let y=new ov;y.on("error",()=>{}),t.pipe(y);let p=Jd.toWeb(y),[v,x]=p.tee();o=v,l=Jd.fromWeb(x);let b=l;b.on("error",()=>{}),t.on("error",(A)=>{y.end(),b.destroy(A)})}let d;try{if(o&&!(o instanceof ReadableStream))throw TypeError("Unexpected request body stream");let y=o&&!u?{body:o,duplex:"half"}:{};d=new Request(r,{method:s,headers:lv(t),signal:i,...y})}catch(y){let p=`malformed request: ${y.message}`;if(a?.(s,r,p),ef(n,{action:"deny",reason:p}),o?.cancel().catch(()=>{}),l.destroy(),l!==t)Zd(t,n);return null}let f;try{f=await e(d)}catch(y){f={action:"deny",reason:`sandbox policy check failed: ${y.message}`}}if(o&&!d.bodyUsed)o.cancel().catch(()=>{});if(f.action==="allow")return C(`[request-filter] allow ${s} ${r}`),l;if(a?.(s,r,f.reason??tf),ef(n,f),l.destroy(),l!==t)Zd(t,n);return null}function ef(e,t){Bi(e,t.reason??tf)}function Bi(e,t){if(C(`[request-filter] deny: ${t}`),e.headersSent){e.destroy();return}e.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-sandbox-runtime"}),e.end(t+`
26
- `)}function lv(e){let t=new Headers;for(let[n,r]of Object.entries(e.headers)){if(r===void 0)continue;if(Array.isArray(r))for(let i of r)t.append(n,i);else t.append(n,r)}return t}import{createServer as Rv,request as Bv}from"https";import{connect as Pv,isIP as Cl}from"net";import{unlink as Nv}from"fs";import{tmpdir as Dv}from"os";import{join as Lv}from"path";import{Transform as cv}from"stream";function uv(e){return e.every((t)=>t.sentinel.length===t.realValue.length)}function rs(e,t,n,r){if(e===void 0)return;let i=t.headers["content-length"]!==void 0||t.headers["transfer-encoding"]!==void 0;if(fl.has(t.method??"GET")&&!i)return;let a=e(r);if(!a?.length)return;if(t.headers["content-encoding"]!==void 0){C(`[body-substitution] ${r}: request body has Content-Encoding "${String(t.headers["content-encoding"])}"; masked-credential `+"substitution skipped \u2014 a sentinel in this body reaches the "+"upstream as the fake value",{level:"warn"});return}if(!uv(a))delete n["content-length"];return dv(a)}function dv(e){let t=Math.max(...e.map((r)=>r.sentinel.length)),n;return new cv({transform(r,i,a){let s=Buffer.isBuffer(r)?r:Buffer.from(r,i),o=n?.length?Buffer.concat([n,s]):s,{out:l,tail:c}=fv(o,e,t);n=c,a(null,l)},flush(r){r(null,n?.length?n:void 0)}})}function fv(e,t,n){let r=[],i=0;for(;;){let s=-1,o;for(let l of t){let c=e.indexOf(l.sentinel,i);if(c!==-1&&(s===-1||c<s))s=c,o=l}if(o===void 0)break;r.push(e.subarray(i,s),o.realValue),i=s+o.sentinel.length}let a=Math.max(i,e.length-(n-1));return r.push(e.subarray(i,a)),{out:Buffer.concat(r),tail:Buffer.from(e.subarray(a))}}var rf=zs(tl(),1);import{isIP as pv}from"net";import{createSecureContext as hv}from"tls";var{pki:ns}=rf.default;function pl(e,t){let n=e.leafCerts.get(t);if(n)return n;let r=ns.rsa.generateKeyPair(2048),i=ns.createCertificate();i.publicKey=r.publicKey,i.serialNumber=dl();let a=Ii(-1);i.validity.notBefore=a,i.validity.notAfter=mv(e.cert,a),i.setSubject([{name:"commonName",value:t}]),i.setIssuer(e.cert.subject.attributes),i.setExtensions([{name:"basicConstraints",cA:!1,critical:!0},{name:"keyUsage",critical:!0,digitalSignature:!0,keyEncipherment:!0},{name:"extKeyUsage",serverAuth:!0},{name:"subjectAltName",altNames:[gv(t)]},{name:"subjectKeyIdentifier"},{name:"authorityKeyIdentifier",keyIdentifier:ol(e.cert)},...e.crlUrl?[{name:"cRLDistributionPoints",altNames:[{type:6,value:e.crlUrl}]}]:[]]),ll(i,e.keyPem);let s={certPem:ns.certificateToPem(i)+e.certPem,keyPem:ns.privateKeyToPem(r.privateKey)};return e.leafCerts.set(t,s),C(`[mitm-leaf] minted RSA leaf for ${t}`),s}function nf(e,t){let n=e.secureContexts.get(t);if(n)return n;let{certPem:r,keyPem:i}=pl(e,t),a=hv({cert:r,key:i});return e.secureContexts.set(t,a),a}function gv(e){return pv(e)!==0?{type:7,ip:e}:{type:2,value:e}}function mv(e,t){let n=e.validity.notAfter,r=new Date(t);return r.setDate(r.getDate()+99),n<r?new Date(n):r}import{BlockList as af,connect as sf,isIP as hn}from"net";import{connect as yv}from"tls";import{URL as hl}from"url";var of=30000,vv=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade"]);function gl(e){let t=e?.http??process.env.HTTP_PROXY??process.env.http_proxy??void 0,n=e?.https??process.env.HTTPS_PROXY??process.env.https_proxy??t,r=e?.noProxy??process.env.NO_PROXY??process.env.no_proxy??"";if(!t&&!n)return;let i=(o)=>{if(!o)return;let c=/^[a-z][a-z0-9+.-]*:\/\//i.test(o)?o:`http://${o}`;try{let u=new hl(c);if(u.protocol!=="http:"&&u.protocol!=="https:"||!u.hostname)throw Error("unsupported scheme or empty host");return u}catch{C(`Invalid parent proxy URL, ignoring: ${bv(o)}`,{level:"error"});return}},a=i(t),s=i(n);if(!a&&!s)return;return{httpUrl:a,httpsUrl:s,noProxy:xv(r)}}function xv(e){let t={all:!1,suffixes:[],cidr:new af};for(let n of e.split(",")){if(n=n.trim(),!n)continue;if(n==="*"){t.all=!0;continue}let r=n.indexOf("/");if(r!==-1){let o=n.slice(0,r),l=n.slice(r+1),c=hn(o);if(c&&l!==""&&/^\d+$/.test(l)){let u=Number(l),d=c===6?128:32;if(u>=0&&u<=d){try{t.cidr.addSubnet(o,u,c===6?"ipv6":"ipv4")}catch{}continue}}continue}let i=n.toLowerCase(),a=/^\[([^\]]+)\](?::\d+)?$/.exec(i);if(a)i=a[1];if(i.startsWith("*."))i=i.slice(1);let s=hn(i);if(!s){let o=i.lastIndexOf(":");if(o!==-1&&/^\d+$/.test(i.slice(o+1)))i=i.slice(0,o)}else try{t.cidr.addAddress(i,s===6?"ipv6":"ipv4");continue}catch{}t.suffixes.push(i)}return t}function Pi(e,t){let n=zt(t.toLowerCase().replace(/\.$/,""));if(n==="localhost")return!0;let r=hn(n);if(r){if(Sv.check(n,r===6?"ipv6":"ipv4"))return!0}if(e.noProxy.all)return!0;if(r){if(e.noProxy.cidr.check(n,r===6?"ipv6":"ipv4"))return!0}for(let i of e.noProxy.suffixes)if(i.startsWith(".")){if(n===i.slice(1)||n.endsWith(i))return!0}else if(n===i||n.endsWith("."+i))return!0;return!1}var Sv=(()=>{let e=new af;return e.addSubnet("127.0.0.0",8,"ipv4"),e.addAddress("::1","ipv6"),e.addSubnet("::ffff:127.0.0.0",104,"ipv6"),e})();function Ni(e,t){if(t.isHttps)return e.httpsUrl??e.httpUrl;return e.httpUrl}function ml(e){let{destHost:t,destPort:n}=e,r=zt(t);if(!Hn(r))return Promise.reject(Error(`Invalid destination host for CONNECT: ${JSON.stringify(t)}`));if(!Number.isInteger(n)||n<1||n>65535)return Promise.reject(Error(`Invalid destination port: ${n}`));let i=hn(r)===6?`[${r}]:${n}`:`${r}:${n}`;return new Promise((a,s)=>{let o=e.dial(),l=!1,c=(d)=>{if(l)return;l=!0,o.destroy(),s(d)},u=()=>c(Error("Proxy closed during CONNECT handshake"));o.setTimeout(e.timeoutMs??of,()=>c(Error("CONNECT handshake timed out"))),o.once("error",c),o.once("close",u),o.once(e.readyEvent,()=>{o.write(`CONNECT ${i} HTTP/1.1\r
27
- Host: ${i}\r
28
- `+(e.authHeader?`Proxy-Authorization: ${e.authHeader}\r
25
+ `,{mode:420}),G}function X6($,J){let X=dJ.oids.sha256WithRSAEncryption,Q=()=>mQ([r$.create(hJ.UNIVERSAL,V0.OID,!1,r$.oidToDer(X).getBytes()),r$.create(hJ.UNIVERSAL,V0.NULL,!1,"")]),Y=(H,N)=>mQ([r$.create(hJ.UNIVERSAL,V0.OID,!1,r$.oidToDer(H).getBytes()),r$.create(hJ.UNIVERSAL,V0.OCTETSTRING,!1,r$.toDer(N).getBytes())]),G=r$.create(hJ.CONTEXT_SPECIFIC,0,!0,[mQ([Y(dJ.oids.authorityKeyIdentifier,mQ([r$.create(hJ.CONTEXT_SPECIFIC,0,!1,Y7($))])),Y("2.5.29.20",r$.create(hJ.UNIVERSAL,V0.INTEGER,!1,"\x01"))])]),W=new Date,U=$.validity.notAfter,M=U>W?U:bX(1),O=mQ([r$.create(hJ.UNIVERSAL,V0.INTEGER,!1,"\x01"),Q(),dJ.distinguishedNameToAsn1($.subject),hW(W),hW(M),G]),V=lW(r$.toDer(O).getBytes(),J),q=mQ([O,Q(),r$.create(hJ.UNIVERSAL,V0.BITSTRING,!1,"\x00"+V)]);return Buffer.from(r$.toDer(q).getBytes(),"binary")}var{Class:hJ,Type:V0}=r$;function mQ($){return r$.create(hJ.UNIVERSAL,V0.SEQUENCE,!0,$)}function hW($){return $.getUTCFullYear()<2050?r$.create(hJ.UNIVERSAL,V0.UTCTIME,!1,r$.dateToUtcTime($)):r$.create(hJ.UNIVERSAL,V0.GENERALIZEDTIME,!1,r$.dateToGeneralizedTime($))}function Y6($,J,X){let Q=uW($,"CERTIFICATE","tlsTerminate.caCertPath"),Y=uW(J,"PRIVATE KEY","tlsTerminate.caKeyPath"),G=hX(Q,Y);if(!G.ok)throw Error(`tlsTerminate: CA at ${$}: ${G.reason}`);return Z(`[mitm-ca] loaded CA from ${$}`),U7(Q,Y,G.cert,G.key,{certPath:$,keyPath:J,extraCaCertPaths:X})}function U7($,J,X,Q,Y){let G=$7(lQ(X7(),"srt-ca-"));return{certPath:Y.certPath,keyPath:Y.keyPath,trustBundlePath:Q6(G,$,Y.extraCaCertPaths),certPem:$,keyPem:J,cert:X,key:Q,leafCerts:new Map,secureContexts:new Map,crlDer:X6(X,J),ephemeral:Y.ephemeral??!1}}function J9($={}){let J=dJ.rsa.generateKeyPair(2048),X=dJ.createCertificate();X.publicKey=J.publicKey,X.serialNumber=M7(),X.validity.notBefore=bX(-1),X.validity.notAfter=bX($.validityDays??825);let Q=[{name:"commonName",value:$.cn??"sandbox-runtime ephemeral CA"},{name:"organizationName",value:"sandbox-runtime"}];X.setSubject(Q),X.setIssuer(Q),X.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",critical:!0,keyCertSign:!0,cRLSign:!0,digitalSignature:!0},{name:"subjectKeyIdentifier"}]);let Y=dJ.privateKeyToPem(J.privateKey);return G7(X,Y),{certPem:dJ.certificateToPem(X),keyPem:Y,cert:X,key:J.privateKey}}function pQ($){return new aq($).fingerprint.replace(/:/g,"").toUpperCase()}function hX($,J){let X,Q;try{X=dJ.certificateFromPem($),Q=dJ.privateKeyFromPem(J)}catch(W){return{ok:!1,reason:`parse: ${W.message}`}}if(!("n"in Q)||!("d"in Q))return{ok:!1,reason:"key is not RSA"};if(X.validity.notBefore.getTime()>Date.now())return{ok:!1,reason:`notBefore ${X.validity.notBefore.toISOString()} is in the future (clock skew?)`};let Y=X.publicKey;if(!("n"in Y)||Y.n.compareTo(Q.n))return{ok:!1,reason:"key does not match certificate public key"};let G;try{G=pQ($)}catch(W){return{ok:!1,reason:`thumbprint: ${W.message}`}}return{ok:!0,thumbprint:G,notAfter:X.validity.notAfter,cert:X,key:Q}}function G6($){let{certPem:J,keyPem:X,cert:Q,key:Y}=J9(),G=$7(lQ(X7(),"srt-ca-")),W=lQ(G,"ca.crt"),U=lQ($7(lQ(X7(),"srt-ca-key-")),"ca.key");return Q7(W,J,{mode:420}),Q7(U,X,{mode:384}),Z(`[mitm-ca] generated ephemeral CA at ${W}`),U7(J,X,Q,Y,{certPath:W,keyPath:U,extraCaCertPaths:$,ephemeral:!0})}function uW($,J,X){let Q;try{Q=J7($,"utf8")}catch(Y){let G=Y.code??String(Y);throw Error(`${X}: cannot read ${$} (${G})`)}if(!new RegExp(`-----BEGIN [A-Z ]*${J}-----`).test(Q))throw Error(`${X}: ${$} is not a PEM ${J}`);return Q}function M7(){let $=eq.getBytesSync(16),J=mW.bytesToHex($);return(parseInt(J[0],16)&7).toString(16)+J.slice(1)}function bX($){let J=new Date;return J.setDate(J.getDate()+$),J}import{PassThrough as W6,Readable as dW}from"stream";var O7=new Set(["GET","HEAD","OPTIONS"]),iW="denied by sandbox policy";function cW($,J){if(J.writableFinished||J.destroyed){$.destroy();return}J.once("finish",()=>$.destroy()),J.once("close",()=>$.destroy())}async function Q9($,J,X,Q,Y,G){let W=J.method??"GET",U,M=J,O=Boolean(J.headers["content-length"]||J.headers["transfer-encoding"]),V=O7.has(W);if(!V||O){let N=new W6;N.on("error",()=>{}),J.pipe(N);let K=dW.toWeb(N),[L,A]=K.tee();U=L,M=dW.fromWeb(A);let D=M;D.on("error",()=>{}),J.on("error",(S)=>{N.end(),D.destroy(S)})}let q;try{if(U&&!(U instanceof ReadableStream))throw TypeError("Unexpected request body stream");let N=U&&!V?{body:U,duplex:"half"}:{};q=new Request(Q,{method:W,headers:U6(J),signal:Y,...N})}catch(N){let K=`malformed request: ${N.message}`;if(G?.(W,Q,K),nW(X,{action:"deny",reason:K}),U?.cancel().catch(()=>{}),M.destroy(),M!==J)cW(J,X);return null}let H;try{H=await $(q)}catch(N){H={action:"deny",reason:`sandbox policy check failed: ${N.message}`}}if(U&&!q.bodyUsed)U.cancel().catch(()=>{});if(H.action==="allow")return Z(`[request-filter] allow ${W} ${Q}`),M;if(G?.(W,Q,H.reason??iW),nW(X,H),M.destroy(),M!==J)cW(J,X);return null}function nW($,J){uX($,J.reason??iW)}function uX($,J){if(Z(`[request-filter] deny: ${J}`),$.headersSent){$.destroy();return}$.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-sandbox-runtime"}),$.end(J+`
26
+ `)}function U6($){let J=new Headers;for(let[X,Q]of Object.entries($.headers)){if(Q===void 0)continue;if(Array.isArray(Q))for(let Y of Q)J.append(X,Y);else J.append(X,Q)}return J}import{createServer as w6,request as P6}from"https";import{connect as _6,isIP as A7}from"net";import{unlink as x6}from"fs";import{tmpdir as v6}from"os";import{join as k6}from"path";import{Transform as M6}from"stream";function O6($){return $.every((J)=>J.sentinel.length===J.realValue.length)}function X9($,J,X,Q){if($===void 0)return;let Y=J.headers["content-length"]!==void 0||J.headers["transfer-encoding"]!==void 0;if(O7.has(J.method??"GET")&&!Y)return;let G=$(Q);if(!G?.length)return;if(J.headers["content-encoding"]!==void 0){Z(`[body-substitution] ${Q}: request body has Content-Encoding "${String(J.headers["content-encoding"])}"; masked-credential `+"substitution skipped \u2014 a sentinel in this body reaches the "+"upstream as the fake value",{level:"warn"});return}if(!O6(G))delete X["content-length"];return V6(G)}function V6($){let J=Math.max(...$.map((Q)=>Q.sentinel.length)),X;return new M6({transform(Q,Y,G){let W=Buffer.isBuffer(Q)?Q:Buffer.from(Q,Y),U=X?.length?Buffer.concat([X,W]):W,{out:M,tail:O}=q6(U,$,J);X=O,G(null,M)},flush(Q){Q(null,X?.length?X:void 0)}})}function q6($,J,X){let Q=[],Y=0;for(;;){let W=-1,U;for(let M of J){let O=$.indexOf(M.sentinel,Y);if(O!==-1&&(W===-1||O<W))W=O,U=M}if(U===void 0)break;Q.push($.subarray(Y,W),U.realValue),Y=W+U.sentinel.length}let G=Math.max(Y,$.length-(X-1));return Q.push($.subarray(Y,G)),{out:Buffer.concat(Q),tail:Buffer.from($.subarray(G))}}var oW=n9(t8(),1);import{isIP as H6}from"net";import{createSecureContext as K6}from"tls";var{pki:Y9}=oW.default;function V7($,J){let X=$.leafCerts.get(J);if(X)return X;let Q=Y9.rsa.generateKeyPair(2048),Y=Y9.createCertificate();Y.publicKey=Q.publicKey,Y.serialNumber=M7();let G=bX(-1);Y.validity.notBefore=G,Y.validity.notAfter=E6($.cert,G),Y.setSubject([{name:"commonName",value:J}]),Y.setIssuer($.cert.subject.attributes),Y.setExtensions([{name:"basicConstraints",cA:!1,critical:!0},{name:"keyUsage",critical:!0,digitalSignature:!0,keyEncipherment:!0},{name:"extKeyUsage",serverAuth:!0},{name:"subjectAltName",altNames:[z6(J)]},{name:"subjectKeyIdentifier"},{name:"authorityKeyIdentifier",keyIdentifier:Y7($.cert)},...$.crlUrl?[{name:"cRLDistributionPoints",altNames:[{type:6,value:$.crlUrl}]}]:[]]),G7(Y,$.keyPem);let W={certPem:Y9.certificateToPem(Y)+$.certPem,keyPem:Y9.privateKeyToPem(Q.privateKey)};return $.leafCerts.set(J,W),Z(`[mitm-leaf] minted RSA leaf for ${J}`),W}function aW($,J){let X=$.secureContexts.get(J);if(X)return X;let{certPem:Q,keyPem:Y}=V7($,J),G=K6({cert:Q,key:Y});return $.secureContexts.set(J,G),G}function z6($){return H6($)!==0?{type:7,ip:$}:{type:2,value:$}}function E6($,J){let X=$.validity.notAfter,Q=new Date(J);return Q.setDate(Q.getDate()+99),X<Q?new Date(X):Q}import{BlockList as sW,connect as rW,isIP as KQ}from"net";import{connect as F6}from"tls";import{URL as q7}from"url";var tW=30000,N6=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade"]);function H7($){let J=$?.http??process.env.HTTP_PROXY??process.env.http_proxy??void 0,X=$?.https??process.env.HTTPS_PROXY??process.env.https_proxy??J,Q=$?.noProxy??process.env.NO_PROXY??process.env.no_proxy??"";if(!J&&!X)return;let Y=(U)=>{if(!U)return;let O=/^[a-z][a-z0-9+.-]*:\/\//i.test(U)?U:`http://${U}`;try{let V=new q7(O);if(V.protocol!=="http:"&&V.protocol!=="https:"||!V.hostname)throw Error("unsupported scheme or empty host");return V}catch{Z(`Invalid parent proxy URL, ignoring: ${R6(U)}`,{level:"error"});return}},G=Y(J),W=Y(X);if(!G&&!W)return;return{httpUrl:G,httpsUrl:W,noProxy:L6(Q)}}function L6($){let J={all:!1,suffixes:[],cidr:new sW};for(let X of $.split(",")){if(X=X.trim(),!X)continue;if(X==="*"){J.all=!0;continue}let Q=X.indexOf("/");if(Q!==-1){let U=X.slice(0,Q),M=X.slice(Q+1),O=KQ(U);if(O&&M!==""&&/^\d+$/.test(M)){let V=Number(M),q=O===6?128:32;if(V>=0&&V<=q){try{J.cidr.addSubnet(U,V,O===6?"ipv6":"ipv4")}catch{}continue}}continue}let Y=X.toLowerCase(),G=/^\[([^\]]+)\](?::\d+)?$/.exec(Y);if(G)Y=G[1];if(Y.startsWith("*."))Y=Y.slice(1);let W=KQ(Y);if(!W){let U=Y.lastIndexOf(":");if(U!==-1&&/^\d+$/.test(Y.slice(U+1)))Y=Y.slice(0,U)}else try{J.cidr.addAddress(Y,W===6?"ipv6":"ipv4");continue}catch{}J.suffixes.push(Y)}return J}function gX($,J){let X=cJ(J.toLowerCase().replace(/\.$/,""));if(X==="localhost")return!0;let Q=KQ(X);if(Q){if(A6.check(X,Q===6?"ipv6":"ipv4"))return!0}if($.noProxy.all)return!0;if(Q){if($.noProxy.cidr.check(X,Q===6?"ipv6":"ipv4"))return!0}for(let Y of $.noProxy.suffixes)if(Y.startsWith(".")){if(X===Y.slice(1)||X.endsWith(Y))return!0}else if(X===Y||X.endsWith("."+Y))return!0;return!1}var A6=(()=>{let $=new sW;return $.addSubnet("127.0.0.0",8,"ipv4"),$.addAddress("::1","ipv6"),$.addSubnet("::ffff:127.0.0.0",104,"ipv6"),$})();function mX($,J){if(J.isHttps)return $.httpsUrl??$.httpUrl;return $.httpUrl}function K7($){let{destHost:J,destPort:X}=$,Q=cJ(J);if(!dQ(Q))return Promise.reject(Error(`Invalid destination host for CONNECT: ${JSON.stringify(J)}`));if(!Number.isInteger(X)||X<1||X>65535)return Promise.reject(Error(`Invalid destination port: ${X}`));let Y=KQ(Q)===6?`[${Q}]:${X}`:`${Q}:${X}`;return new Promise((G,W)=>{let U=$.dial(),M=!1,O=(q)=>{if(M)return;M=!0,U.destroy(),W(q)},V=()=>O(Error("Proxy closed during CONNECT handshake"));U.setTimeout($.timeoutMs??tW,()=>O(Error("CONNECT handshake timed out"))),U.once("error",O),U.once("close",V),U.once($.readyEvent,()=>{U.write(`CONNECT ${Y} HTTP/1.1\r
27
+ Host: ${Y}\r
28
+ `+($.authHeader?`Proxy-Authorization: ${$.authHeader}\r
29
29
  `:"")+`\r
30
- `);let d="",f=(y)=>{d+=y.toString("latin1");let p=d.indexOf(`\r
30
+ `);let q="",H=(N)=>{q+=N.toString("latin1");let K=q.indexOf(`\r
31
31
  \r
32
- `);if(p===-1){if(d.length>16384)c(Error("CONNECT response header too large"));return}o.pause(),o.removeListener("data",f);let v=d.slice(0,d.indexOf(`\r
33
- `));if(!/^HTTP\/1\.[01] 2\d\d(?:\s|$)/.test(v))return c(Error(`Proxy refused CONNECT: ${v.trim()}`));let x=d.slice(p+4);if(x.length)o.unshift(Buffer.from(x,"latin1"));l=!0,o.setTimeout(0),o.removeListener("error",c),o.removeListener("close",u),a(o)};o.on("data",f)})})}function is(e,t,n){let r=zt(e.hostname),i=Number(e.port)||(e.protocol==="https:"?443:80),a=e.protocol==="https:";return ml({destHost:t,destPort:n,authHeader:yl(e),readyEvent:a?"secureConnect":"connect",dial:()=>a?yv({host:r,port:i,...hn(r)?{}:{servername:r}}):sf(i,r)})}function yl(e){if(!e.username&&!e.password)return;try{let t=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;return`Basic ${Buffer.from(t).toString("base64")}`}catch{let t=`${e.username}:${e.password}`;return`Basic ${Buffer.from(t).toString("base64")}`}}function Hr(e){let t=new Set,n=e.connection;if(n)for(let i of String(n).split(","))t.add(i.trim().toLowerCase());let r={};for(let[i,a]of Object.entries(e)){let s=i.toLowerCase();if(!vv.has(s)&&!t.has(s))r[i]=a}return r}function zt(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function vl(e){if(!e)return"-";if(!e.username&&!e.password)return e.href;let t=new hl(e.href);return t.username="***",t.password="***",t.href}function bv(e){return e.replace(/\/\/[^@/]*@/,"//***:***@")}function Hn(e){if(!e||e.length>255)return!1;let t=zt(e);if(t.includes("%"))return!1;if(hn(t))return!0;return/^[A-Za-z0-9._-]+$/.test(t)}function _t(e){try{let t=zt(e),n=hn(t)===6?`[${t}]`:t,r=new hl(`http://${n}/`).hostname;return zt(r).replace(/\.$/,"")}catch{return}}function as(e,t,n=of){return new Promise((r,i)=>{let a=sf(t,e),s=!1,o=(l)=>{if(s)return;if(s=!0,a.setTimeout(0),l)a.destroy(),i(l);else r(a)};a.setTimeout(n,()=>o(Error("connect timed out"))),a.once("connect",()=>o()),a.once("error",o),a.once("close",()=>o(Error("socket closed before connect")))})}import{createHash as Cv,createHmac as df}from"crypto";var Di="AWS4-HMAC-SHA256",Ev="AWS4-ECDSA-P256-SHA256",os="UNSIGNED-PAYLOAD";function ff(e,t){let n=Kn(e.authorization);if(n!==void 0&&n.startsWith(Ev)){let o=lf(n);if(o!==void 0)return{kind:"sigv4a",accessKeyId:o}}else if(n!==void 0&&n.startsWith(Di)){let o=lf(n);if(o!==void 0)return{kind:Kn(e["x-amz-content-sha256"])?.startsWith("STREAMING-")?"streaming":"header-sigv4",accessKeyId:o}}let r=t.indexOf("?");if(r===-1)return null;let i=new URLSearchParams(t.slice(r+1));if(i.get("X-Amz-Algorithm")!==Di)return null;if(!i.has("X-Amz-Signature"))return null;let a=i.get("X-Amz-Credential");if(!a)return null;let s=a.split("/")[0];return s?{kind:"presigned",accessKeyId:s}:null}function lf(e){return/Credential=([^/,\s]+)\//.exec(e)?.[1]}function pf(e){if(!e.startsWith(Di))return null;let t=/Credential=([^,\s]+)/.exec(e)?.[1],n=/SignedHeaders=([^,\s]+)/.exec(e)?.[1],r=/Signature=([0-9a-fA-F]+)/.exec(e)?.[1];if(!t||!n||!r)return null;let i=t.split("/");if(i.length!==5||i[4]!=="aws4_request")return null;let[a,s,o,l]=i;if(!a||!s||!o||!l)return null;return{accessKeyId:a,date:s,region:o,service:l,signedHeaders:n.split(";").map((c)=>c.toLowerCase()),signature:r}}function xl(e){return encodeURIComponent(e).replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function wv(e,t){if(e==="")return"/";if(t==="s3")return e;let n=[];for(let a of e.split("/")){if(a===""||a===".")continue;if(a==="..")n.pop();else n.push(a)}let r=n.length>0&&e.endsWith("/")?"/":"",i=`/${n.join("/")}${r}`;return xl(i).replace(/%2F/gi,"/")}function Tv(e){if(e==="")return"";let t=[];for(let n of e.split("&")){if(n==="")continue;let r=n.indexOf("="),i=r===-1?n:n.slice(0,r),a=r===-1?"":n.slice(r+1);t.push([xl(cf(i)),xl(cf(a))])}return t.sort(([n,r],[i,a])=>n<i?-1:n>i?1:r<a?-1:r>a?1:0),t.map(([n,r])=>`${n}=${r}`).join("&")}function cf(e){try{return decodeURIComponent(e)}catch{return e}}function uf(e){return e.trim().replace(/[ \t]+/g," ")}function Av(e){let t=e.requestTarget.indexOf("?"),n=t===-1?e.requestTarget:e.requestTarget.slice(0,t),r=t===-1?"":e.requestTarget.slice(t+1),i=[...e.signedHeaders].map((s)=>s.toLowerCase()).sort(),a=[];for(let s of i){let o=s==="host"?e.hostHeader:e.headers[s];if(o===void 0)throw Error(`signed header "${s}" is missing from the request`);let l=Array.isArray(o)?o.map(uf).join(","):uf(String(o));a.push(`${s}:${l}`)}return[e.method.toUpperCase(),wv(n,e.scope.service),Tv(r),a.join(`
32
+ `);if(K===-1){if(q.length>16384)O(Error("CONNECT response header too large"));return}U.pause(),U.removeListener("data",H);let L=q.slice(0,q.indexOf(`\r
33
+ `));if(!/^HTTP\/1\.[01] 2\d\d(?:\s|$)/.test(L))return O(Error(`Proxy refused CONNECT: ${L.trim()}`));let A=q.slice(K+4);if(A.length)U.unshift(Buffer.from(A,"latin1"));M=!0,U.setTimeout(0),U.removeListener("error",O),U.removeListener("close",V),G(U)};U.on("data",H)})})}function G9($,J,X){let Q=cJ($.hostname),Y=Number($.port)||($.protocol==="https:"?443:80),G=$.protocol==="https:";return K7({destHost:J,destPort:X,authHeader:z7($),readyEvent:G?"secureConnect":"connect",dial:()=>G?F6({host:Q,port:Y,...KQ(Q)?{}:{servername:Q}}):rW(Y,Q)})}function z7($){if(!$.username&&!$.password)return;try{let J=`${decodeURIComponent($.username)}:${decodeURIComponent($.password)}`;return`Basic ${Buffer.from(J).toString("base64")}`}catch{let J=`${$.username}:${$.password}`;return`Basic ${Buffer.from(J).toString("base64")}`}}function g0($){let J=new Set,X=$.connection;if(X)for(let Y of String(X).split(","))J.add(Y.trim().toLowerCase());let Q={};for(let[Y,G]of Object.entries($)){let W=Y.toLowerCase();if(!N6.has(W)&&!J.has(W))Q[Y]=G}return Q}function cJ($){return $.startsWith("[")&&$.endsWith("]")?$.slice(1,-1):$}function E7($){if(!$)return"-";if(!$.username&&!$.password)return $.href;let J=new q7($.href);return J.username="***",J.password="***",J.href}function R6($){return $.replace(/\/\/[^@/]*@/,"//***:***@")}function dQ($){if(!$||$.length>255)return!1;let J=cJ($);if(J.includes("%"))return!1;if(KQ(J))return!0;return/^[A-Za-z0-9._-]+$/.test(J)}function jJ($){try{let J=cJ($),X=KQ(J)===6?`[${J}]`:J,Q=new q7(`http://${X}/`).hostname;return cJ(Q).replace(/\.$/,"")}catch{return}}function W9($,J,X=tW){return new Promise((Q,Y)=>{let G=rW(J,$),W=!1,U=(M)=>{if(W)return;if(W=!0,G.setTimeout(0),M)G.destroy(),Y(M);else Q(G)};G.setTimeout(X,()=>U(Error("connect timed out"))),G.once("connect",()=>U()),G.once("error",U),G.once("close",()=>U(Error("socket closed before connect")))})}import{createHash as D6,createHmac as Q4}from"crypto";var lX="AWS4-HMAC-SHA256",Z6="AWS4-ECDSA-P256-SHA256",M9="UNSIGNED-PAYLOAD";function X4($,J){let X=cQ($.authorization);if(X!==void 0&&X.startsWith(Z6)){let U=eW(X);if(U!==void 0)return{kind:"sigv4a",accessKeyId:U}}else if(X!==void 0&&X.startsWith(lX)){let U=eW(X);if(U!==void 0)return{kind:cQ($["x-amz-content-sha256"])?.startsWith("STREAMING-")?"streaming":"header-sigv4",accessKeyId:U}}let Q=J.indexOf("?");if(Q===-1)return null;let Y=new URLSearchParams(J.slice(Q+1));if(Y.get("X-Amz-Algorithm")!==lX)return null;if(!Y.has("X-Amz-Signature"))return null;let G=Y.get("X-Amz-Credential");if(!G)return null;let W=G.split("/")[0];return W?{kind:"presigned",accessKeyId:W}:null}function eW($){return/Credential=([^/,\s]+)\//.exec($)?.[1]}function Y4($){if(!$.startsWith(lX))return null;let J=/Credential=([^,\s]+)/.exec($)?.[1],X=/SignedHeaders=([^,\s]+)/.exec($)?.[1],Q=/Signature=([0-9a-fA-F]+)/.exec($)?.[1];if(!J||!X||!Q)return null;let Y=J.split("/");if(Y.length!==5||Y[4]!=="aws4_request")return null;let[G,W,U,M]=Y;if(!G||!W||!U||!M)return null;return{accessKeyId:G,date:W,region:U,service:M,signedHeaders:X.split(";").map((O)=>O.toLowerCase()),signature:Q}}function F7($){return encodeURIComponent($).replace(/[!'()*]/g,(J)=>"%"+J.charCodeAt(0).toString(16).toUpperCase())}function B6($,J){if($==="")return"/";if(J==="s3")return $;let X=[];for(let G of $.split("/")){if(G===""||G===".")continue;if(G==="..")X.pop();else X.push(G)}let Q=X.length>0&&$.endsWith("/")?"/":"",Y=`/${X.join("/")}${Q}`;return F7(Y).replace(/%2F/gi,"/")}function j6($){if($==="")return"";let J=[];for(let X of $.split("&")){if(X==="")continue;let Q=X.indexOf("="),Y=Q===-1?X:X.slice(0,Q),G=Q===-1?"":X.slice(Q+1);J.push([F7($4(Y)),F7($4(G))])}return J.sort(([X,Q],[Y,G])=>X<Y?-1:X>Y?1:Q<G?-1:Q>G?1:0),J.map(([X,Q])=>`${X}=${Q}`).join("&")}function $4($){try{return decodeURIComponent($)}catch{return $}}function J4($){return $.trim().replace(/[ \t]+/g," ")}function T6($){let J=$.requestTarget.indexOf("?"),X=J===-1?$.requestTarget:$.requestTarget.slice(0,J),Q=J===-1?"":$.requestTarget.slice(J+1),Y=[...$.signedHeaders].map((W)=>W.toLowerCase()).sort(),G=[];for(let W of Y){let U=W==="host"?$.hostHeader:$.headers[W];if(U===void 0)throw Error(`signed header "${W}" is missing from the request`);let M=Array.isArray(U)?U.map(J4).join(","):J4(String(U));G.push(`${W}:${M}`)}return[$.method.toUpperCase(),B6(X,$.scope.service),j6(Q),G.join(`
34
34
  `)+`
35
- `,i.join(";"),e.payloadHash].join(`
36
- `)}function _v(e,t,n){return[Di,t,`${n.date}/${n.region}/${n.service}/aws4_request`,Sl(e)].join(`
37
- `)}function kv(e,t){let n=ss(`AWS4${e}`,t.date),r=ss(n,t.region),i=ss(r,t.service);return ss(i,"aws4_request")}function hf(e){let t=Av(e),n=_v(t,e.amzDate,e.scope),r=df("sha256",kv(e.secretAccessKey,e.scope)).update(n,"utf8").digest("hex"),i=[...e.signedHeaders].map((s)=>s.toLowerCase()).sort(),a=`${e.scope.date}/${e.scope.region}/${e.scope.service}/aws4_request`;return{authorization:`${Di} Credential=${e.accessKeyId}/${a}, SignedHeaders=${i.join(";")}, Signature=${r}`,signature:r,canonicalRequest:t,stringToSign:n}}function Sl(e){return Cv("sha256").update(e).digest("hex")}function ss(e,t){return df("sha256",e).update(t,"utf8").digest()}function Kn(e){return Array.isArray(e)?e[0]:e}var gf="reason-egress-target",mf="reason-egress-token";class bl{entries=new Map;refs=new Map;lease=null;register(e,t,n,r){if(!e||!t||n.length===0)return;if(this.entries.set(e,{placeholder:e,token:t,hosts:[...n],url:r}),this.lease&&!this.lease.has(e))this.lease.add(e),this.refs.set(e,(this.refs.get(e)??0)+1)}beginLease(){this.lease=new Set}endLease(){let e=[...this.lease??[]];return this.lease=null,e}release(e){for(let t of e){let n=(this.refs.get(t)??1)-1;if(n>0){this.refs.set(t,n);continue}this.refs.delete(t),this.entries.delete(t)}e.length=0}clear(){this.entries.clear(),this.refs.clear()}forwardFor(e,t){for(let n of this.entries.values()){if(!n.hosts.includes(t))continue;for(let r of Object.values(e))if((Array.isArray(r)?r:r===void 0?[]:[r]).some((a)=>a.includes(n.placeholder)||Iv(a,n.placeholder)))return{url:new URL(n.url),token:n.token}}return}}function Iv(e,t){let n=/^\s*basic\s+([A-Za-z0-9+/=_-]+)\s*$/i.exec(e);return n?Buffer.from(n[1],"base64").toString("utf8").includes(t):!1}var xf=67108864;class El extends Error{}function yf(e){return e.length>=3&&e[0]===22&&e[1]===3&&e[2]<=3}function Sf(e,t){if(t.length>=3)return Promise.resolve({isTLS:yf(t),head:t});return new Promise((n)=>{let r=t,i=()=>{e.removeListener("data",a),e.removeListener("close",i),n({isTLS:yf(r),head:r})},a=(s)=>{if(e.pause(),r=r.length?Buffer.concat([r,s]):s,r.length>=3)return i();e.resume()};e.on("data",a),e.once("close",i)})}function Ov(e,t){let n=()=>{let r;while((r=e.read())!==null)if(!t.write(r)){t.once("drain",n);return}e.once("readable",n)};n(),e.once("end",()=>t.end())}function bf(e,t,n,r,i,a,s,o,l=xf,c){let u=pl(e,s.hostname),d=Rv({ALPNProtocols:["http/1.1"],cert:u.certPem,key:u.keyPem,SNICallback:(p,v)=>{try{v(null,nf(e,p||s.hostname))}catch(x){v(x)}}});d.on("request",(p,v)=>{p.on("error",(x)=>{C(`[tls-terminate] client request error: ${x.message}`,{level:"error"})}),v.on("error",(x)=>{C(`[tls-terminate] client response error: ${x.message}`,{level:"error"})}),Uv(t,n,r,p,v,s,o,l,c)}),d.on("clientError",(p,v)=>{C(`[tls-terminate] client connection error for ${s.hostname}: ${p.message}`,{level:"error"}),v.destroy()}),d.on("tlsClientError",(p,v)=>{C(`[tls-terminate] client TLS error for ${s.hostname}: ${p.message}`,{level:"error"}),v.destroy()}),d.on("upgrade",(p,v)=>{C("[tls-terminate] upgrade request refused",{level:"warn"}),v.destroy()});let f=$v(),y=()=>{d.close(),Nv(f,()=>{})};d.on("error",(p)=>{C(`[tls-terminate] inner server listen failed: ${p.message}`,{level:"error"}),i.destroy(),y()}),d.listen(f,()=>{let p=Pv({path:f});p.on("error",(v)=>{C(`[tls-terminate] inner loopback failed: ${v.message}`,{level:"error"}),i.destroy(),y()}),p.once("connect",()=>{if(a.length)p.write(a);Ov(i,p),p.pipe(i)}),i.on("error",()=>p.destroy()),i.once("close",()=>{p.destroy(),y()}),p.once("close",()=>i.destroy())}),d.unref()}function vf(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}function Uv(...e){Vv(...e).catch((t)=>{C(`[tls-terminate] forwardUpstream failed: ${t.message}`,{level:"error"})})}async function Vv(e,t,n,r,i,a,s,o=xf,l){let c=Mv(r.url),u=r;if(e){let E=new AbortController;i.once("close",()=>E.abort());let k=a.port===443?a.hostname:`${a.hostname}:${a.port}`,I=await ts(e,r,i,`https://${k}${c}`,E.signal,a.onFilterRequestDeny);if(I===null)return;if(u=I,r.destroyed&&!r.readableEnded||i.destroyed||r.socket.destroyed||u.destroyed){u.destroy();return}}let d=Hr(r.headers);delete d.host;let f=l?.(d,a.hostname),y=s?.(r.method??"GET",c,d,a.hostname);t?.(d,a.hostname);let p=rs(n,r,d,a.hostname),v;if(y?.action==="deny"){if(Bi(i,y.reason),u.destroy(),u!==r)vf(r,i);return}if(y?.action==="resign"){let E=y.payloadHash;if(E===void 0){let R=p?u.pipe(p):u;if(p)u.on("error",(M)=>p.destroy(M));try{v=await Fv(R,o)}catch(M){if(M instanceof El){Bi(i,`AWS SigV4 request uses a masked credential and signs a literal body hash, so the proxy must buffer the body to re-sign it, but the body exceeds the ${o}-byte buffering limit; denied. Sign the payload as UNSIGNED-PAYLOAD to stream it without buffering, or use an unmasked credential to have the request forwarded untouched.`),R.resume();return}C(`[tls-terminate] failed to buffer body for SigV4 re-sign: ${M.message}`,{level:"error"}),i.destroy();return}E=Sl(v),d["content-length"]=String(v.length)}let k=Cl(a.hostname)===6?`[${a.hostname}]`:a.hostname,I=a.port===443?k:`${k}:${a.port}`;try{y.apply(d,I,E)}catch(R){if(Bi(i,`AWS SigV4 re-signing failed: ${R.message}`),u.destroy(),u!==r)vf(r,i);return}}if(Boolean(r.headers["content-length"]||r.headers["transfer-encoding"])&&v===void 0&&d["content-length"]===void 0&&d["transfer-encoding"]===void 0)d["transfer-encoding"]="chunked";if(f){let E=Cl(a.hostname)===6?`[${a.hostname}]`:a.hostname;d[gf]=`https://${a.port===443?E:`${E}:${a.port}`}${c}`,d[mf]=f.token}let b=f?f.url.hostname:a.hostname,A=Bv({host:b,port:f?Number(f.url.port||443):a.port,path:f?`${f.url.pathname}${f.url.search}`:c,method:r.method,headers:d,...Cl(b)?{}:{servername:b},...a.upstreamCA?{ca:a.upstreamCA}:{},agent:!1},(E)=>{E.on("error",(k)=>{C(`[tls-terminate] upstream response error: ${k.message}`,{level:"error"}),i.destroy()}),i.writeHead(E.statusCode??502,Hr(E.headers)),E.pipe(i)});if(A.on("error",(E)=>{if(C(`[tls-terminate] upstream ${a.hostname}:${a.port} failed: ${E.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>A.destroy()),v!==void 0)A.end(v);else if(p)p.on("error",(E)=>A.destroy(E)),u.on("error",(E)=>p.destroy(E)),i.on("close",()=>p.destroy()),u.pipe(p).pipe(A);else u.on("error",(E)=>A.destroy(E)),u.pipe(A)}function Fv(e,t){return new Promise((n,r)=>{let i=[],a=0,s=(o)=>{if(a+=o.length,a>t){i.length=0,e.removeListener("data",s),r(new El(`request body exceeds ${t} bytes`));return}i.push(o)};e.on("data",s),e.once("end",()=>n(Buffer.concat(i))),e.once("error",r)})}function Mv(e){let t=e??"/";if(t.startsWith("/"))return t;try{let n=new URL(t);return`${n.pathname}${n.search}`||"/"}catch{return t}}var Wv=0;function $v(){return Lv(Dv(),`srt-tt-${process.pid}-${(Wv++).toString(36)}.sock`)}function jv(e,t){if(!t)return{ok:!0};let n=/^basic\s+([a-z0-9+/=]+)\s*$/i.exec(e??"");if(!n)return{ok:!1};let r=Buffer.from(n[1],"base64").toString("utf8"),i=r.indexOf(":");if(i<=0||!ha(r.slice(i+1),t))return{ok:!1};return{ok:!0,encodedCommand:xa(r.slice(0,i))}}function wf(e){let t=Kv();t.on("clientError",(r,i)=>{if(C(`Client connection error: ${r.message}`,{level:"error"}),i.on("error",()=>{}),r.code!=="ECONNRESET"&&i.writable){let a=r.code==="HPE_HEADER_OVERFLOW"?"431 Request Header Fields Too Large":"400 Bad Request";i.end(`HTTP/1.1 ${a}\r
35
+ `,Y.join(";"),$.payloadHash].join(`
36
+ `)}function S6($,J,X){return[lX,J,`${X.date}/${X.region}/${X.service}/aws4_request`,N7($)].join(`
37
+ `)}function I6($,J){let X=U9(`AWS4${$}`,J.date),Q=U9(X,J.region),Y=U9(Q,J.service);return U9(Y,"aws4_request")}function G4($){let J=T6($),X=S6(J,$.amzDate,$.scope),Q=Q4("sha256",I6($.secretAccessKey,$.scope)).update(X,"utf8").digest("hex"),Y=[...$.signedHeaders].map((W)=>W.toLowerCase()).sort(),G=`${$.scope.date}/${$.scope.region}/${$.scope.service}/aws4_request`;return{authorization:`${lX} Credential=${$.accessKeyId}/${G}, SignedHeaders=${Y.join(";")}, Signature=${Q}`,signature:Q,canonicalRequest:J,stringToSign:X}}function N7($){return D6("sha256").update($).digest("hex")}function U9($,J){return Q4("sha256",$).update(J,"utf8").digest()}function cQ($){return Array.isArray($)?$[0]:$}var W4="reason-egress-target",U4="reason-egress-token";class L7{entries=new Map;refs=new Map;lease=null;register($,J,X,Q){if(!$||!J||X.length===0)return;if(this.entries.set($,{placeholder:$,token:J,hosts:[...X],url:Q}),this.lease&&!this.lease.has($))this.lease.add($),this.refs.set($,(this.refs.get($)??0)+1)}beginLease(){this.lease=new Set}endLease(){let $=[...this.lease??[]];return this.lease=null,$}release($){for(let J of $){let X=(this.refs.get(J)??1)-1;if(X>0){this.refs.set(J,X);continue}this.refs.delete(J),this.entries.delete(J)}$.length=0}clear(){this.entries.clear(),this.refs.clear()}forwardFor($,J){for(let X of this.entries.values()){if(!X.hosts.includes(J))continue;for(let Q of Object.values($))if((Array.isArray(Q)?Q:Q===void 0?[]:[Q]).some((G)=>G.includes(X.placeholder)||C6(G,X.placeholder)))return{url:new URL(X.url),token:X.token}}return}}function C6($,J){let X=/^\s*basic\s+([A-Za-z0-9+/=_-]+)\s*$/i.exec($);return X?Buffer.from(X[1],"base64").toString("utf8").includes(J):!1}var V4=67108864;class R7 extends Error{}function M4($){return $.length>=3&&$[0]===22&&$[1]===3&&$[2]<=3}function q4($,J){if(J.length>=3)return Promise.resolve({isTLS:M4(J),head:J});return new Promise((X)=>{let Q=J,Y=()=>{$.removeListener("data",G),$.removeListener("close",Y),X({isTLS:M4(Q),head:Q})},G=(W)=>{if($.pause(),Q=Q.length?Buffer.concat([Q,W]):W,Q.length>=3)return Y();$.resume()};$.on("data",G),$.once("close",Y)})}function f6($,J){let X=()=>{let Q;while((Q=$.read())!==null)if(!J.write(Q)){J.once("drain",X);return}$.once("readable",X)};X(),$.once("end",()=>J.end())}function H4($,J,X,Q,Y,G,W,U,M=V4,O){let V=V7($,W.hostname),q=w6({ALPNProtocols:["http/1.1"],cert:V.certPem,key:V.keyPem,SNICallback:(K,L)=>{try{L(null,aW($,K||W.hostname))}catch(A){L(A)}}});q.on("request",(K,L)=>{K.on("error",(A)=>{Z(`[tls-terminate] client request error: ${A.message}`,{level:"error"})}),L.on("error",(A)=>{Z(`[tls-terminate] client response error: ${A.message}`,{level:"error"})}),y6(J,X,Q,K,L,W,U,M,O)}),q.on("clientError",(K,L)=>{Z(`[tls-terminate] client connection error for ${W.hostname}: ${K.message}`,{level:"error"}),L.destroy()}),q.on("tlsClientError",(K,L)=>{Z(`[tls-terminate] client TLS error for ${W.hostname}: ${K.message}`,{level:"error"}),L.destroy()}),q.on("upgrade",(K,L)=>{Z("[tls-terminate] upgrade request refused",{level:"warn"}),L.destroy()});let H=m6(),N=()=>{q.close(),x6(H,()=>{})};q.on("error",(K)=>{Z(`[tls-terminate] inner server listen failed: ${K.message}`,{level:"error"}),Y.destroy(),N()}),q.listen(H,()=>{let K=_6({path:H});K.on("error",(L)=>{Z(`[tls-terminate] inner loopback failed: ${L.message}`,{level:"error"}),Y.destroy(),N()}),K.once("connect",()=>{if(G.length)K.write(G);f6(Y,K),K.pipe(Y)}),Y.on("error",()=>K.destroy()),Y.once("close",()=>{K.destroy(),N()}),K.once("close",()=>Y.destroy())}),q.unref()}function O4($,J){if(J.writableFinished||J.destroyed){$.destroy();return}J.once("finish",()=>$.destroy()),J.once("close",()=>$.destroy())}function y6(...$){b6(...$).catch((J)=>{Z(`[tls-terminate] forwardUpstream failed: ${J.message}`,{level:"error"})})}async function b6($,J,X,Q,Y,G,W,U=V4,M){let O=u6(Q.url),V=Q;if($){let B=new AbortController;Y.once("close",()=>B.abort());let C=G.port===443?G.hostname:`${G.hostname}:${G.port}`,w=await Q9($,Q,Y,`https://${C}${O}`,B.signal,G.onFilterRequestDeny);if(w===null)return;if(V=w,Q.destroyed&&!Q.readableEnded||Y.destroyed||Q.socket.destroyed||V.destroyed){V.destroy();return}}let q=g0(Q.headers);delete q.host;let H=M?.(q,G.hostname),N=W?.(Q.method??"GET",O,q,G.hostname);J?.(q,G.hostname);let K=X9(X,Q,q,G.hostname),L;if(N?.action==="deny"){if(uX(Y,N.reason),V.destroy(),V!==Q)O4(Q,Y);return}if(N?.action==="resign"){let B=N.payloadHash;if(B===void 0){let P=K?V.pipe(K):V;if(K)V.on("error",(l)=>K.destroy(l));try{L=await h6(P,U)}catch(l){if(l instanceof R7){uX(Y,`AWS SigV4 request uses a masked credential and signs a literal body hash, so the proxy must buffer the body to re-sign it, but the body exceeds the ${U}-byte buffering limit; denied. Sign the payload as UNSIGNED-PAYLOAD to stream it without buffering, or use an unmasked credential to have the request forwarded untouched.`),P.resume();return}Z(`[tls-terminate] failed to buffer body for SigV4 re-sign: ${l.message}`,{level:"error"}),Y.destroy();return}B=N7(L),q["content-length"]=String(L.length)}let C=A7(G.hostname)===6?`[${G.hostname}]`:G.hostname,w=G.port===443?C:`${C}:${G.port}`;try{N.apply(q,w,B)}catch(P){if(uX(Y,`AWS SigV4 re-signing failed: ${P.message}`),V.destroy(),V!==Q)O4(Q,Y);return}}if(Boolean(Q.headers["content-length"]||Q.headers["transfer-encoding"])&&L===void 0&&q["content-length"]===void 0&&q["transfer-encoding"]===void 0)q["transfer-encoding"]="chunked";if(H){let B=A7(G.hostname)===6?`[${G.hostname}]`:G.hostname;q[W4]=`https://${G.port===443?B:`${B}:${G.port}`}${O}`,q[U4]=H.token}let D=H?H.url.hostname:G.hostname,S=P6({host:D,port:H?Number(H.url.port||443):G.port,path:H?`${H.url.pathname}${H.url.search}`:O,method:Q.method,headers:q,...A7(D)?{}:{servername:D},...G.upstreamCA?{ca:G.upstreamCA}:{},agent:!1},(B)=>{B.on("error",(C)=>{Z(`[tls-terminate] upstream response error: ${C.message}`,{level:"error"}),Y.destroy()}),Y.writeHead(B.statusCode??502,g0(B.headers)),B.pipe(Y)});if(S.on("error",(B)=>{if(Z(`[tls-terminate] upstream ${G.hostname}:${G.port} failed: ${B.message}`,{level:"error"}),!Y.headersSent)Y.writeHead(502,{"Content-Type":"text/plain"}),Y.end("Bad Gateway");else Y.destroy()}),Y.on("close",()=>S.destroy()),L!==void 0)S.end(L);else if(K)K.on("error",(B)=>S.destroy(B)),V.on("error",(B)=>K.destroy(B)),Y.on("close",()=>K.destroy()),V.pipe(K).pipe(S);else V.on("error",(B)=>S.destroy(B)),V.pipe(S)}function h6($,J){return new Promise((X,Q)=>{let Y=[],G=0,W=(U)=>{if(G+=U.length,G>J){Y.length=0,$.removeListener("data",W),Q(new R7(`request body exceeds ${J} bytes`));return}Y.push(U)};$.on("data",W),$.once("end",()=>X(Buffer.concat(Y))),$.once("error",Q)})}function u6($){let J=$??"/";if(J.startsWith("/"))return J;try{let X=new URL(J);return`${X.pathname}${X.search}`||"/"}catch{return J}}var g6=0;function m6(){return k6(v6(),`srt-tt-${process.pid}-${(g6++).toString(36)}.sock`)}function n6($,J){if(!J)return{ok:!0};let X=/^basic\s+([a-z0-9+/=]+)\s*$/i.exec($??"");if(!X)return{ok:!1};let Q=Buffer.from(X[1],"base64").toString("utf8"),Y=Q.indexOf(":");if(Y<=0||!EY(Q.slice(Y+1),J))return{ok:!1};return{ok:!0,encodedCommand:RY(Q.slice(0,Y))}}function E4($){let J=p6();J.on("clientError",(Q,Y)=>{if(Z(`Client connection error: ${Q.message}`,{level:"error"}),Y.on("error",()=>{}),Q.code!=="ECONNRESET"&&Y.writable){let G=Q.code==="HPE_HEADER_OVERFLOW"?"431 Request Header Fields Too Large":"400 Bad Request";Y.end(`HTTP/1.1 ${G}\r
38
38
  \r
39
- `,()=>i.destroy()),setTimeout(()=>i.destroy(),1000).unref?.();return}i.destroy()});let n=(r)=>jv(r,e.proxyAuthToken);return t.on("connect",async(r,i,a)=>{i.on("error",(b)=>{C(`Client socket error: ${b.message}`,{level:"error"}),i.destroy()});let s=!1;i.once("close",()=>{s=!0});let o=()=>{s=!0,i.destroy()},l=65536,c=0,u=!1,d=[],f=(b)=>{if(!u)return;if(c+=b.length,c>l){C("CONNECT client exceeded pre-establishment capture cap; destroying",{level:"error"}),o();return}d.push(b)};if(!e.mitmCA)u=!0,i.on("data",f);if(i.readableEnded)o();else i.once("end",o);let y=()=>{if(u=!1,d.length)a=Buffer.concat([a,...d]),d.length=0},p=()=>{i.removeListener("end",o),y()},v=(b)=>{if(s||i.destroyed||i.readableEnded||!i.writable){C("CONNECT client gone before status write; dropping verdict and destroying socket"),i.destroy();return}p(),i.end(b)};if(s||i.destroyed)return;let x=!1;try{let b=n(r.headers["proxy-authorization"]);if(!b.ok){v(`HTTP/1.1 407 Proxy Authentication Required\r
39
+ `,()=>Y.destroy()),setTimeout(()=>Y.destroy(),1000).unref?.();return}Y.destroy()});let X=(Q)=>n6(Q,$.proxyAuthToken);return J.on("connect",async(Q,Y,G)=>{Y.on("error",(D)=>{Z(`Client socket error: ${D.message}`,{level:"error"}),Y.destroy()});let W=!1;Y.once("close",()=>{W=!0});let U=()=>{W=!0,Y.destroy()},M=65536,O=0,V=!1,q=[],H=(D)=>{if(!V)return;if(O+=D.length,O>M){Z("CONNECT client exceeded pre-establishment capture cap; destroying",{level:"error"}),U();return}q.push(D)};if(!$.mitmCA)V=!0,Y.on("data",H);if(Y.readableEnded)U();else Y.once("end",U);let N=()=>{if(V=!1,q.length)G=Buffer.concat([G,...q]),q.length=0},K=()=>{Y.removeListener("end",U),N()},L=(D)=>{if(W||Y.destroyed||Y.readableEnded||!Y.writable){Z("CONNECT client gone before status write; dropping verdict and destroying socket"),Y.destroy();return}K(),Y.end(D)};if(W||Y.destroyed)return;let A=!1;try{let D=X(Q.headers["proxy-authorization"]);if(!D.ok){L(`HTTP/1.1 407 Proxy Authentication Required\r
40
40
  Proxy-Authenticate: Basic realm="srt"\r
41
41
  \r
42
- `);return}let A=zv(r.url);if(!A){C(`Invalid CONNECT request: ${r.url}`,{level:"error"}),v(`HTTP/1.1 400 Bad Request\r
42
+ `);return}let S=i6(Q.url);if(!S){Z(`Invalid CONNECT request: ${Q.url}`,{level:"error"}),L(`HTTP/1.1 400 Bad Request\r
43
43
  \r
44
- `);return}let{hostname:E,port:k}=A;if(!await e.filter(k,E,i,b.encodedCommand)){C(`Connection blocked to ${E}:${k}`,{level:"error"}),v(`HTTP/1.1 403 Forbidden\r
44
+ `);return}let{hostname:B,port:C}=S;if(!await $.filter(C,B,Y,D.encodedCommand)){Z(`Connection blocked to ${B}:${C}`,{level:"error"}),L(`HTTP/1.1 403 Forbidden\r
45
45
  Content-Type: text/plain\r
46
46
  X-Proxy-Error: blocked-by-allowlist\r
47
47
  \r
48
- Connection blocked by network allowlist`);return}if(s||i.destroyed){i.destroy();return}let R=_t(E)??E;if(e.mitmCA&&(e.shouldTerminateTLS?.(R,k)??!0)){i.write(`HTTP/1.1 200 Connection Established\r
48
+ Connection blocked by network allowlist`);return}if(W||Y.destroyed){Y.destroy();return}let P=jJ(B)??B;if($.mitmCA&&($.shouldTerminateTLS?.(P,C)??!0)){Y.write(`HTTP/1.1 200 Connection Established\r
49
49
  \r
50
- `),x=!0;let K=await Sf(i,a);if(s||i.destroyed){i.destroy();return}if(K.isTLS){p(),bf(e.mitmCA,e.filterRequest,e.mutateHeaders,e.getBodySubstitutions,i,K.head,{hostname:R,port:k,upstreamCA:e.tlsTerminateUpstreamCA,onFilterRequestDeny:e.onFilterRequestDenied?(ie,ve,we)=>e.onFilterRequestDenied({method:ie,url:ve,reason:we,encodedCommand:b.encodedCommand}):void 0},e.planSigv4,e.maxSigv4ResignBodyBytes,e.getBrokerForward);return}C(`[tls-terminate] non-TLS bytes on CONNECT ${R}:${k}; opaque-tunnelling`),a=K.head}else if(e.mitmCA)C(`[tls-terminate] policy exempts ${R}:${k}; opaque-tunnelling`);let M=e.getMitmSocketPath?.(R),ee=!M&&e.parentProxy&&!Pi(e.parentProxy,R)?Ni(e.parentProxy,{isHttps:!0}):void 0,O;try{if(M)C(`Routing CONNECT ${R}:${k} through MITM proxy at ${M}`),O=await ml({dial:()=>qv({path:M}),readyEvent:"connect",destHost:R,destPort:k});else if(ee)O=await is(ee,R,k);else O=await as(R,k)}catch(K){if(C(`CONNECT tunnel failed: ${K.message}`,{level:"error"}),x)i.destroy();else v(`HTTP/1.1 502 Bad Gateway\r
50
+ `),A=!0;let n=await q4(Y,G);if(W||Y.destroyed){Y.destroy();return}if(n.isTLS){K(),H4($.mitmCA,$.filterRequest,$.mutateHeaders,$.getBodySubstitutions,Y,n.head,{hostname:P,port:C,upstreamCA:$.tlsTerminateUpstreamCA,onFilterRequestDeny:$.onFilterRequestDenied?(Y$,L$,j$)=>$.onFilterRequestDenied({method:Y$,url:L$,reason:j$,encodedCommand:D.encodedCommand}):void 0},$.planSigv4,$.maxSigv4ResignBodyBytes,$.getBrokerForward);return}Z(`[tls-terminate] non-TLS bytes on CONNECT ${P}:${C}; opaque-tunnelling`),G=n.head}else if($.mitmCA)Z(`[tls-terminate] policy exempts ${P}:${C}; opaque-tunnelling`);let l=$.getMitmSocketPath?.(P),$$=!l&&$.parentProxy&&!gX($.parentProxy,P)?mX($.parentProxy,{isHttps:!0}):void 0,y;try{if(l)Z(`Routing CONNECT ${P}:${C} through MITM proxy at ${l}`),y=await K7({dial:()=>d6({path:l}),readyEvent:"connect",destHost:P,destPort:C});else if($$)y=await G9($$,P,C);else y=await W9(P,C)}catch(n){if(Z(`CONNECT tunnel failed: ${n.message}`,{level:"error"}),A)Y.destroy();else L(`HTTP/1.1 502 Bad Gateway\r
51
51
  \r
52
- `);return}if(s||i.destroyed){O.on("error",()=>{}),O.destroy(),i.destroy();return}if(!x)i.write(`HTTP/1.1 200 Connection Established\r
52
+ `);return}if(W||Y.destroyed){y.on("error",()=>{}),y.destroy(),Y.destroy();return}if(!A)Y.write(`HTTP/1.1 200 Connection Established\r
53
53
  \r
54
- `);if(p(),i.allowHalfOpen=!0,a.length)O.write(a);O.pipe(i),i.pipe(O),O.on("error",(K)=>{C(`CONNECT tunnel failed: ${K.message}`,{level:"error"}),i.destroy()}),i.on("close",()=>O.destroy()),O.on("close",()=>i.destroy())}catch(b){if(C(`Error handling CONNECT: ${b}`,{level:"error"}),x)i.destroy();else v(`HTTP/1.1 500 Internal Server Error\r
54
+ `);if(K(),Y.allowHalfOpen=!0,G.length)y.write(G);y.pipe(Y),Y.pipe(y),y.on("error",(n)=>{Z(`CONNECT tunnel failed: ${n.message}`,{level:"error"}),Y.destroy()}),Y.on("close",()=>y.destroy()),y.on("close",()=>Y.destroy())}catch(D){if(Z(`Error handling CONNECT: ${D}`,{level:"error"}),A)Y.destroy();else L(`HTTP/1.1 500 Internal Server Error\r
55
55
  \r
56
- `)}}),t.on("request",async(r,i)=>{r.on("error",(a)=>{C(`Client request error: ${a.message}`,{level:"error"})}),i.on("error",(a)=>{C(`Client response error: ${a.message}`,{level:"error"}),i.socket?.destroy()});try{if(e.mitmCA&&r.method==="GET"&&new Ef(r.url??"","http://x").pathname===Za){i.writeHead(200,{"Content-Type":"application/pkix-crl","Content-Length":e.mitmCA.crlDer.length}),i.end(e.mitmCA.crlDer);return}let a=n(r.headers["proxy-authorization"]);if(!a.ok){i.writeHead(407,{"Proxy-Authenticate":'Basic realm="srt"'}),i.end();return}let s=new Ef(r.url),o=zt(s.hostname),l=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80;if(!await e.filter(l,o,r.socket,a.encodedCommand)){if(C(`HTTP request blocked to ${o}:${l}`,{level:"error"}),r.socket.destroyed||i.destroyed){i.destroy();return}i.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-allowlist"}),i.end("Connection blocked by network allowlist");return}if(r.socket.destroyed)return;let u=_t(o)??o,d=(Gv(u)===6?`[${u}]`:u)+(s.port?`:${s.port}`:""),f={...Hr(r.headers),host:d};e.mutateHeadersPlaintext?.(f,u);let y=rs(e.getBodySubstitutionsPlaintext,r,f,u),p=e.getMitmSocketPath?.(u),v=!p&&e.parentProxy&&!Pi(e.parentProxy,u)?Ni(e.parentProxy,{isHttps:s.protocol==="https:"}):void 0,x=`${s.protocol}//${d}${s.pathname}${s.search}`,b=r;if(e.filterRequest){let k=new AbortController;i.once("close",()=>k.abort());let I=await ts(e.filterRequest,r,i,x,k.signal,e.onFilterRequestDenied?(R,M,ee)=>e.onFilterRequestDenied({method:R,url:M,reason:ee,encodedCommand:a.encodedCommand}):void 0);if(I===null)return;if(b=I,r.destroyed&&!r.readableEnded||i.destroyed||r.socket.destroyed||b.destroyed){b.destroy();return}}if(Boolean(r.headers["content-length"]||r.headers["transfer-encoding"])&&f["content-length"]===void 0&&f["transfer-encoding"]===void 0)f["transfer-encoding"]="chunked";let E;if(p){C(`Routing HTTP ${r.method} ${u}:${l} through MITM proxy at ${p}`);let k=new Hv({socketPath:p});E=wl({agent:k,path:x,method:r.method,headers:f},(I)=>{I.on("error",(R)=>{C(`Upstream response error: ${R.message}`,{level:"error"}),i.destroy()}),i.writeHead(I.statusCode,Hr(I.headers)),I.pipe(i)})}else if(v){let k=zt(v.hostname),I=Number(v.port)||(v.protocol==="https:"?443:80),R=yl(v);E=(v.protocol==="https:"?Cf:wl)({hostname:k,port:I,path:x,method:r.method,headers:R?{...f,"proxy-authorization":R}:f},(ee)=>{ee.on("error",(O)=>{C(`Upstream response error: ${O.message}`,{level:"error"}),i.destroy()}),i.writeHead(ee.statusCode,Hr(ee.headers)),ee.pipe(i)})}else E=(s.protocol==="https:"?Cf:wl)({hostname:u,port:l,path:s.pathname+s.search,method:r.method,headers:f},(I)=>{I.on("error",(R)=>{C(`Upstream response error: ${R.message}`,{level:"error"}),i.destroy()}),i.writeHead(I.statusCode,Hr(I.headers)),I.pipe(i)});if(E.on("error",(k)=>{if(C(`Proxy request failed: ${k.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>E.destroy()),y)y.on("error",(k)=>E.destroy(k)),b.on("error",(k)=>y.destroy(k)),i.on("close",()=>y.destroy()),b.pipe(y).pipe(E);else b.on("error",(k)=>E.destroy(k)),b.pipe(E)}catch(a){if(C(`Error handling HTTP request: ${a}`,{level:"error"}),!i.headersSent)i.writeHead(500,{"Content-Type":"text/plain"}),i.end("Internal Server Error");else i.destroy()}}),t}function zv(e){let t=/^\[([^\]]+)\]:(\d+)$/.exec(e)??/^([^:]+):(\d+)$/.exec(e);if(!t)return;let n=Number(t[2]);if(!Number.isInteger(n)||n<1||n>65535)return;return{hostname:t[1],port:n}}var Pf=zs(Bf(),1);function sx(e,t,n){if(!n||t===void 0)return!1;return e!==void 0&&(e===mr||e.startsWith(`${mr}.`))&&ha(t,n)}function Nf(e){let t=Pf.createServer();if(e.proxyAuthToken)t.setAuthHandler((r,i,a)=>{if(sx(r.username,r.password,e.proxyAuthToken))i();else C("SOCKS auth rejected",{level:"error"}),a()});t.setRulesetValidator(async(r)=>{try{let{destAddress:i,destPort:a}=r;if(!Hn(i))return C(`Rejecting malformed SOCKS host: ${JSON.stringify(i)}`,{level:"error"}),!1;if(C(`Connection request to ${i}:${a}`),!await e.filter(a,i,xa(r.username)))return C(`Connection blocked to ${i}:${a}`,{level:"error"}),!1;return C(`Connection allowed to ${i}:${a}`),!0}catch(i){return C(`Error validating connection: ${i}`,{level:"error"}),!1}}),t.setConnectionHandler((r,i)=>{let a=_t(r.destAddress)??r.destAddress,s=r.destPort,o=!1,l;r.socket.once("close",()=>{o=!0,l?.destroy()}),r.socket.on("error",()=>l?.destroy());let c=e.parentProxy&&!Pi(e.parentProxy,a)?Ni(e.parentProxy,{isHttps:!0}):void 0;(c?is(c,a,s):as(a,s)).then((d)=>{if(l=d,d.on("error",()=>r.socket.destroy()),o){d.destroy();return}i("REQUEST_GRANTED"),d.pipe(r.socket),r.socket.pipe(d),d.on("close",()=>r.socket.destroy())}).catch((d)=>{if(C(`SOCKS connect to ${a}:${s} failed: ${d.message}`,{level:"error"}),!o)try{i("HOST_UNREACHABLE")}catch{}})});let n=new Set;return{handleConnection(r){if(r.setNoDelay(),n.add(r),r.once("close",()=>n.delete(r)),!e.proxyAuthToken){t._handleConnection(r);return}cx(r,(i)=>{if(i){t._handleConnection(r);return}ux(r,e).catch(()=>r.destroy())})},async close(){for(let r of n)r.destroy();n.clear()}}}var ox=0,lx=2;function cx(e,t){let n=Buffer.alloc(0),r=(i)=>{if(n=Buffer.concat([n,i]),n.length<2)return;if(n[0]!==5){e.off("data",r),e.destroy();return}let a=n[1];if(n.length<2+a)return;e.off("data",r),e.pause();let o=n.subarray(2,2+a).includes(lx),l=o?n:n.subarray(2+a);if(l.length>0)e.unshift(l);t(o)};e.on("data",r),e.once("error",()=>e.off("data",r))}async function ux(e,t){e.write(Buffer.from([5,ox]));let n=await dx(e);if(n===void 0){e.destroy();return}let{host:r,port:i}=n;if(!Hn(r)){e.end(_l(2));return}let a=t.probeUnauthenticated?await t.probeUnauthenticated(i,r):{};if(C(`SOCKS unauthenticated client refused for ${r}:${i}`+(a.deniedReason!==void 0?" (denied by policy)":"")),i!==22){e.end(_l(2));return}let s=a.deniedReason??"This proxy requires authentication, and this client did not offer an authentication method, so the connection was refused.";e.write(_l(0)),e.write(Buffer.from(`SSH-2.0-policy_refusal\r
57
- `)),e.end(fx(s))}function _l(e){return Buffer.from([5,e,0,1,0,0,0,0,0,0])}function dx(e){return new Promise((t)=>{let n=Buffer.alloc(0),r=(s)=>{e.off("data",a),clearTimeout(i),t(s)},i=setTimeout(()=>r(void 0),5000),a=(s)=>{if(n=Buffer.concat([n,s]),n.length<4)return;if(n[0]!==5||n[1]!==1){r(void 0);return}let o=n[3];if(o===1){if(n.length<10)return;let l=Array.from(n.subarray(4,8)).join(".");r({host:l,port:n.readUInt16BE(8)})}else if(o===3){if(n.length<5)return;let l=n[4];if(n.length<5+l+2)return;r({host:n.subarray(5,5+l).toString("utf8"),port:n.readUInt16BE(5+l)})}else if(o===4){if(n.length<22)return;let l=[];for(let c=0;c<16;c+=2)l.push(n.readUInt16BE(4+c).toString(16));r({host:l.join(":"),port:n.readUInt16BE(20)})}else r(void 0)};e.on("data",a),e.resume(),e.once("error",()=>r(void 0)),e.once("close",()=>r(void 0))})}function fx(e){let t=e.replace(/[\x00-\x1f\x7f-\x9f]+/g," ").slice(0,1000),n=Buffer.from(t,"utf8"),r=Buffer.alloc(0),i=Buffer.concat([Buffer.from([1]),cs(1),cs(n.length),n,cs(r.length),r]),a=8-(5+i.length)%8;if(a<4)a+=8;return Buffer.concat([cs(1+i.length+a),Buffer.from([a]),i,Buffer.alloc(a)])}function cs(e){let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t}import{createServer as px,connect as Df}from"net";import{join as hx}from"path";import{tmpdir as gx}from"os";import{unlink as Lf}from"fs/promises";function us(e,t,n,r){return new Promise((i,a)=>{let[s,o]=n??[0,0],l=s,c=()=>{while(r.has(l)&&l<=o)l++;if(l>o){a(Error(`No free port in range ${s}-${o} (excluding ${[...r].join(",")})`));return}let u=()=>{e.removeListener("error",d),i()},d=(f)=>{if(e.removeListener("listening",u),n&&f?.code==="EADDRINUSE"&&l<o){l++,c();return}a(f??Error("listen error"))};e.once("error",d),e.once("listening",u),t(n?l:0)};c()})}var mx=new Set([4,5]),yx=1e4,vx=0;function xx(){return hx(gx(),`srt-mux-${process.pid}-${(vx++).toString(36)}.sock`)}function Of(e){let t=e.firstByteTimeoutMs??yx,n=Ne()==="windows",r,i,a=new Set;function s(l){if(r===void 0&&i===void 0){C("mux: HTTP dispatch before backend bound; dropping",{level:"error"}),l.destroy();return}let c=r?Df(r):Df(i,"127.0.0.1");c.on("error",(u)=>{let d=u.code??"ERR";if(C(`mux: HTTP backend dial failed: ${u.message}`,{level:"error"}),!l.destroyed)l.end(`HTTP/1.1 502 Bad Gateway\r
56
+ `)}}),J.on("request",async(Q,Y)=>{Q.on("error",(G)=>{Z(`Client request error: ${G.message}`,{level:"error"})}),Y.on("error",(G)=>{Z(`Client response error: ${G.message}`,{level:"error"}),Y.socket?.destroy()});try{if($.mitmCA&&Q.method==="GET"&&new z4(Q.url??"","http://x").pathname===$9){Y.writeHead(200,{"Content-Type":"application/pkix-crl","Content-Length":$.mitmCA.crlDer.length}),Y.end($.mitmCA.crlDer);return}let G=X(Q.headers["proxy-authorization"]);if(!G.ok){Y.writeHead(407,{"Proxy-Authenticate":'Basic realm="srt"'}),Y.end();return}let W=new z4(Q.url),U=cJ(W.hostname),M=W.port?parseInt(W.port,10):W.protocol==="https:"?443:80;if(!await $.filter(M,U,Q.socket,G.encodedCommand)){if(Z(`HTTP request blocked to ${U}:${M}`,{level:"error"}),Q.socket.destroyed||Y.destroyed){Y.destroy();return}Y.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-allowlist"}),Y.end("Connection blocked by network allowlist");return}if(Q.socket.destroyed)return;let V=jJ(U)??U,q=(c6(V)===6?`[${V}]`:V)+(W.port?`:${W.port}`:""),H={...g0(Q.headers),host:q};$.mutateHeadersPlaintext?.(H,V);let N=X9($.getBodySubstitutionsPlaintext,Q,H,V),K=$.getMitmSocketPath?.(V),L=!K&&$.parentProxy&&!gX($.parentProxy,V)?mX($.parentProxy,{isHttps:W.protocol==="https:"}):void 0,A=`${W.protocol}//${q}${W.pathname}${W.search}`,D=Q;if($.filterRequest){let C=new AbortController;Y.once("close",()=>C.abort());let w=await Q9($.filterRequest,Q,Y,A,C.signal,$.onFilterRequestDenied?(P,l,$$)=>$.onFilterRequestDenied({method:P,url:l,reason:$$,encodedCommand:G.encodedCommand}):void 0);if(w===null)return;if(D=w,Q.destroyed&&!Q.readableEnded||Y.destroyed||Q.socket.destroyed||D.destroyed){D.destroy();return}}if(Boolean(Q.headers["content-length"]||Q.headers["transfer-encoding"])&&H["content-length"]===void 0&&H["transfer-encoding"]===void 0)H["transfer-encoding"]="chunked";let B;if(K){Z(`Routing HTTP ${Q.method} ${V}:${M} through MITM proxy at ${K}`);let C=new l6({socketPath:K});B=D7({agent:C,path:A,method:Q.method,headers:H},(w)=>{w.on("error",(P)=>{Z(`Upstream response error: ${P.message}`,{level:"error"}),Y.destroy()}),Y.writeHead(w.statusCode,g0(w.headers)),w.pipe(Y)})}else if(L){let C=cJ(L.hostname),w=Number(L.port)||(L.protocol==="https:"?443:80),P=z7(L);B=(L.protocol==="https:"?K4:D7)({hostname:C,port:w,path:A,method:Q.method,headers:P?{...H,"proxy-authorization":P}:H},($$)=>{$$.on("error",(y)=>{Z(`Upstream response error: ${y.message}`,{level:"error"}),Y.destroy()}),Y.writeHead($$.statusCode,g0($$.headers)),$$.pipe(Y)})}else B=(W.protocol==="https:"?K4:D7)({hostname:V,port:M,path:W.pathname+W.search,method:Q.method,headers:H},(w)=>{w.on("error",(P)=>{Z(`Upstream response error: ${P.message}`,{level:"error"}),Y.destroy()}),Y.writeHead(w.statusCode,g0(w.headers)),w.pipe(Y)});if(B.on("error",(C)=>{if(Z(`Proxy request failed: ${C.message}`,{level:"error"}),!Y.headersSent)Y.writeHead(502,{"Content-Type":"text/plain"}),Y.end("Bad Gateway");else Y.destroy()}),Y.on("close",()=>B.destroy()),N)N.on("error",(C)=>B.destroy(C)),D.on("error",(C)=>N.destroy(C)),Y.on("close",()=>N.destroy()),D.pipe(N).pipe(B);else D.on("error",(C)=>B.destroy(C)),D.pipe(B)}catch(G){if(Z(`Error handling HTTP request: ${G}`,{level:"error"}),!Y.headersSent)Y.writeHead(500,{"Content-Type":"text/plain"}),Y.end("Internal Server Error");else Y.destroy()}}),J}function i6($){let J=/^\[([^\]]+)\]:(\d+)$/.exec($)??/^([^:]+):(\d+)$/.exec($);if(!J)return;let X=Number(J[2]);if(!Number.isInteger(X)||X<1||X>65535)return;return{hostname:J[1],port:X}}var B4=n9(Z4(),1);function GH($,J,X){if(!X||J===void 0)return!1;return $!==void 0&&($===F0||$.startsWith(`${F0}.`))&&EY(J,X)}function j4($){let J=B4.createServer();if($.proxyAuthToken)J.setAuthHandler((Q,Y,G)=>{if(GH(Q.username,Q.password,$.proxyAuthToken))Y();else Z("SOCKS auth rejected",{level:"error"}),G()});J.setRulesetValidator(async(Q)=>{try{let{destAddress:Y,destPort:G}=Q;if(!dQ(Y))return Z(`Rejecting malformed SOCKS host: ${JSON.stringify(Y)}`,{level:"error"}),!1;if(Z(`Connection request to ${Y}:${G}`),!await $.filter(G,Y,RY(Q.username)))return Z(`Connection blocked to ${Y}:${G}`,{level:"error"}),!1;return Z(`Connection allowed to ${Y}:${G}`),!0}catch(Y){return Z(`Error validating connection: ${Y}`,{level:"error"}),!1}}),J.setConnectionHandler((Q,Y)=>{let G=jJ(Q.destAddress)??Q.destAddress,W=Q.destPort,U=!1,M;Q.socket.once("close",()=>{U=!0,M?.destroy()}),Q.socket.on("error",()=>M?.destroy());let O=$.parentProxy&&!gX($.parentProxy,G)?mX($.parentProxy,{isHttps:!0}):void 0;(O?G9(O,G,W):W9(G,W)).then((q)=>{if(M=q,q.on("error",()=>Q.socket.destroy()),U){q.destroy();return}Y("REQUEST_GRANTED"),q.pipe(Q.socket),Q.socket.pipe(q),q.on("close",()=>Q.socket.destroy())}).catch((q)=>{if(Z(`SOCKS connect to ${G}:${W} failed: ${q.message}`,{level:"error"}),!U)try{Y("HOST_UNREACHABLE")}catch{}})});let X=new Set;return{handleConnection(Q){if(Q.setNoDelay(),X.add(Q),Q.once("close",()=>X.delete(Q)),!$.proxyAuthToken){J._handleConnection(Q);return}MH(Q,(Y)=>{if(Y){J._handleConnection(Q);return}OH(Q,$).catch(()=>Q.destroy())})},async close(){for(let Q of X)Q.destroy();X.clear()}}}var WH=0,UH=2;function MH($,J){let X=Buffer.alloc(0),Q=(Y)=>{if(X=Buffer.concat([X,Y]),X.length<2)return;if(X[0]!==5){$.off("data",Q),$.destroy();return}let G=X[1];if(X.length<2+G)return;$.off("data",Q),$.pause();let U=X.subarray(2,2+G).includes(UH),M=U?X:X.subarray(2+G);if(M.length>0)$.unshift(M);J(U)};$.on("data",Q),$.once("error",()=>$.off("data",Q))}async function OH($,J){$.write(Buffer.from([5,WH]));let X=await VH($);if(X===void 0){$.destroy();return}let{host:Q,port:Y}=X;if(!dQ(Q)){$.end(j7(2));return}let G=J.probeUnauthenticated?await J.probeUnauthenticated(Y,Q):{};if(Z(`SOCKS unauthenticated client refused for ${Q}:${Y}`+(G.deniedReason!==void 0?" (denied by policy)":"")),Y!==22){$.end(j7(2));return}let W=G.deniedReason??"This proxy requires authentication, and this client did not offer an authentication method, so the connection was refused.";$.write(j7(0)),$.write(Buffer.from(`SSH-2.0-policy_refusal\r
57
+ `)),$.end(qH(W))}function j7($){return Buffer.from([5,$,0,1,0,0,0,0,0,0])}function VH($){return new Promise((J)=>{let X=Buffer.alloc(0),Q=(W)=>{$.off("data",G),clearTimeout(Y),J(W)},Y=setTimeout(()=>Q(void 0),5000),G=(W)=>{if(X=Buffer.concat([X,W]),X.length<4)return;if(X[0]!==5||X[1]!==1){Q(void 0);return}let U=X[3];if(U===1){if(X.length<10)return;let M=Array.from(X.subarray(4,8)).join(".");Q({host:M,port:X.readUInt16BE(8)})}else if(U===3){if(X.length<5)return;let M=X[4];if(X.length<5+M+2)return;Q({host:X.subarray(5,5+M).toString("utf8"),port:X.readUInt16BE(5+M)})}else if(U===4){if(X.length<22)return;let M=[];for(let O=0;O<16;O+=2)M.push(X.readUInt16BE(4+O).toString(16));Q({host:M.join(":"),port:X.readUInt16BE(20)})}else Q(void 0)};$.on("data",G),$.resume(),$.once("error",()=>Q(void 0)),$.once("close",()=>Q(void 0))})}function qH($){let J=$.replace(/[\x00-\x1f\x7f-\x9f]+/g," ").slice(0,1000),X=Buffer.from(J,"utf8"),Q=Buffer.alloc(0),Y=Buffer.concat([Buffer.from([1]),V9(1),V9(X.length),X,V9(Q.length),Q]),G=8-(5+Y.length)%8;if(G<4)G+=8;return Buffer.concat([V9(1+Y.length+G),Buffer.from([G]),Y,Buffer.alloc(G)])}function V9($){let J=Buffer.alloc(4);return J.writeUInt32BE($,0),J}import{createServer as HH,connect as T4}from"net";import{join as KH}from"path";import{tmpdir as zH}from"os";import{unlink as S4}from"fs/promises";function q9($,J,X,Q){return new Promise((Y,G)=>{let[W,U]=X??[0,0],M=W,O=()=>{while(Q.has(M)&&M<=U)M++;if(M>U){G(Error(`No free port in range ${W}-${U} (excluding ${[...Q].join(",")})`));return}let V=()=>{$.removeListener("error",q),Y()},q=(H)=>{if($.removeListener("listening",V),X&&H?.code==="EADDRINUSE"&&M<U){M++,O();return}G(H??Error("listen error"))};$.once("error",q),$.once("listening",V),J(X?M:0)};O()})}var EH=new Set([4,5]),FH=1e4,NH=0;function LH(){return KH(zH(),`srt-mux-${process.pid}-${(NH++).toString(36)}.sock`)}function I4($){let J=$.firstByteTimeoutMs??FH,X=x$()==="windows",Q,Y,G=new Set;function W(M){if(Q===void 0&&Y===void 0){Z("mux: HTTP dispatch before backend bound; dropping",{level:"error"}),M.destroy();return}let O=Q?T4(Q):T4(Y,"127.0.0.1");O.on("error",(V)=>{let q=V.code??"ERR";if(Z(`mux: HTTP backend dial failed: ${V.message}`,{level:"error"}),!M.destroyed)M.end(`HTTP/1.1 502 Bad Gateway\r
58
58
  Connection: close\r
59
59
  \r
60
- mux backend dial failed (${d})
61
- `)}),l.on("error",()=>c.destroy()),l.once("close",()=>c.destroy()),c.once("close",()=>l.destroy()),l.pipe(c),c.pipe(l)}let o=px((l)=>{a.add(l),l.once("close",()=>a.delete(l)),l.on("error",(u)=>C(`mux: client socket error: ${u.message}`));let c=setTimeout(()=>{C("mux: first-byte timeout; destroying connection"),l.destroy()},t);if(typeof c.unref==="function")c.unref();l.once("readable",()=>{clearTimeout(c);let u=l.read(1);if(!u||u.length===0){l.destroy();return}if(l.unshift(u),mx.has(u[0]))e.handleSocksConnection(l);else s(l)})});return{server:o,getPort(){let l=o.address();return l&&typeof l==="object"?l.port:void 0},async listenHttpBackend(){if(!n){let c=xx();await Lf(c).catch(()=>{}),await new Promise((u,d)=>{e.httpServer.once("error",d),e.httpServer.listen(c,()=>{e.httpServer.removeListener("error",d),u()})}),r=c,C(`mux: HTTP backend listening on ${c}`);return}await us(e.httpServer,(c)=>e.httpServer.listen(c,"127.0.0.1"),e.httpBackendPortRange,new Set);let l=e.httpServer.address();return i=l&&typeof l==="object"?l.port:void 0,C(`mux: HTTP backend listening on 127.0.0.1:${i}`),i},async close(){for(let l of a)l.destroy();if(a.clear(),await new Promise((l)=>o.close(()=>l())),await new Promise((l)=>e.httpServer.close(()=>l())),r)await Lf(r).catch(()=>{}),r=void 0;i=void 0},unref(){o.unref(),e.httpServer.unref()}}}import{randomBytes as Sx,randomUUID as bx}from"crypto";var qn="fake_value_",Uf="abcdefghijklmnopqrstuvwxyz0123456789_-";function Cx(e){let t=qn+bx(),n=Buffer.byteLength(e)-t.length;if(n<=0)return t;let r=t;for(let i of Sx(n))r+=Uf[i%Uf.length];return r}class kl{byName=new Map;bySentinel=new Map;allSentinelsPrefixed=!0;refs=new Map;lease=null;register(e,t,n,r){return this.registerWithSentinel(e,Cx(t),t,n,r)}registerWithSentinel(e,t,n,r,i){let a=this.byName.get(e);if(a!==void 0&&a.realValue===n)return a.injectHosts=r,a.injectHeaders=i,this.lease?.add(a),a.sentinel;if(this.bySentinel.has(t))throw Error("credential sentinel collision");if(!t.startsWith(qn))this.allSentinelsPrefixed=!1;let s={name:e,sentinel:t,realValue:n,injectHosts:r,injectHeaders:i};return this.byName.set(e,s),this.bySentinel.set(t,s),this.lease?.add(s),t}beginLease(){this.lease=new Set}endLease(){let e=[...this.lease??[]];this.lease=null;for(let t of e)this.refs.set(t,(this.refs.get(t)??0)+1);return{entries:e}}release(e){let t=[];for(let n of e.entries){let r=(this.refs.get(n)??1)-1;if(r>0){this.refs.set(n,r);continue}if(this.refs.delete(n),this.bySentinel.get(n.sentinel)===n)this.bySentinel.delete(n.sentinel);if(this.byName.get(n.name)===n)this.byName.delete(n.name);t.push(n.sentinel)}if(e.entries.length=0,t.length>0&&!this.allSentinelsPrefixed)this.allSentinelsPrefixed=[...this.bySentinel.keys()].every((n)=>n.startsWith(qn));return t}lookupReal(e){return this.bySentinel.get(e)?.realValue}namesInjectableAt(e,t){let n=[];for(let r of this.byName.values())if(r.injectHosts.some((i)=>t(e,i)))n.push(r.name);return n}sentinelsForHost(e,t){let n=[];for(let r of this.bySentinel.values()){if(!r.injectHosts.some((i)=>t(e,i)))continue;if(r.injectHeaders!==void 0)continue;n.push({sentinel:Buffer.from(r.sentinel),realValue:Buffer.from(r.realValue)})}return n}*entries(){for(let e of this.bySentinel.values())yield[e.sentinel,e.realValue]}get size(){return this.bySentinel.size}clear(){this.byName.clear(),this.bySentinel.clear(),this.refs.clear(),this.lease=null,this.allSentinelsPrefixed=!0}substituteInHeaders(e,t,n){if(this.bySentinel.size===0)return;for(let[r,i]of Object.entries(e)){if(i===void 0)continue;if(Array.isArray(i))for(let a=0;a<i.length;a++)i[a]=this.substituteInHeaderValue(r,i[a],t,n);else e[r]=this.substituteInHeaderValue(r,i,t,n)}}substituteInHeaderValue(e,t,n,r){let i=e.toLowerCase(),a=this.substituteInString(t,n,r,i);if(i!=="authorization")return a;let s=/^(\s*basic\s+)([a-z0-9+/]+={0,2})(\s*)$/i.exec(a);if(s===null)return a;let o=s[2],l=Buffer.from(o,"base64");if(o.length%4!==0||l.toString("base64")!==o)return a;let c=l.toString("utf8");if(!Buffer.from(c,"utf8").equals(l))return a;let u=this.substituteInString(c,n,r,i);if(u===c)return a;return`${s[1]}${Buffer.from(u,"utf8").toString("base64")}${s[3]}`}substituteInString(e,t,n,r){if(this.allSentinelsPrefixed&&!e.includes(qn))return e;let i=e;for(let a of this.bySentinel.values()){if(!i.includes(a.sentinel))continue;if(!a.injectHosts.some((s)=>n(t,s)))continue;if(a.injectHeaders!==void 0&&!a.injectHeaders.includes(r))continue;i=i.split(a.sentinel).join(a.realValue)}return i}}import{randomUUID as Rx}from"crypto";import*as Qt from"fs";import{tmpdir as Bx}from"os";import{join as Wf}from"path";function Ex(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let i=e[r];if(n){n=!1;continue}if(i==="\\")n=!0;else if(i==="]")return r+1}return e.length}function wx(e){switch(e){case"s":return{kind:"whitespace"};case"S":return{kind:"non-whitespace"};case"d":return{kind:"digit"};case"D":return{kind:"non-digit"};case"w":return{kind:"word"};case"W":return{kind:"non-word"};default:return{kind:"unknown"}}}function Vf(e,t){if(e===null||t===null)return!0;if(e.kind==="literal"&&t.kind==="literal")return e.value===t.value;if(e.kind==="whitespace"&&t.kind==="non-whitespace"||e.kind==="non-whitespace"&&t.kind==="whitespace"||e.kind==="digit"&&t.kind==="non-digit"||e.kind==="non-digit"&&t.kind==="digit"||e.kind==="word"&&t.kind==="non-word"||e.kind==="non-word"&&t.kind==="word")return!1;return!0}function Tx(e,t){if(e[t+1]!=="?")return{next:t+1,capturing:!0};if(e[t+2]==="<"){let r=e[t+3];if(r==="="||r==="!")return{next:t+4,capturing:!1};let i=e.indexOf(">",t+3);return{next:i===-1?t+3:i+1,capturing:!0}}return{next:t+3,capturing:!1}}function Ax(e,t){let n=e[t];if(n==="*"||n==="+")return{next:e[t+1]==="?"?t+2:t+1,unbounded:!0};if(n==="?")return{next:e[t+1]==="?"?t+2:t+1,unbounded:!1};if(n!=="{")return null;let r=t+1,i=r;while(/[0-9]/.test(e[r]??""))r++;if(r===i)return null;let a=Number(e.slice(i,r)),s=a,o=!1;if(e[r]===","){r++;let l=r;while(/[0-9]/.test(e[r]??""))r++;if(r===l)o=!0,s=void 0;else s=Number(e.slice(l,r))}if(e[r]!=="}")return null;if(!Number.isFinite(a)||a>4096||s!==void 0&&(!Number.isFinite(s)||s>4096))return{next:r+1,unbounded:o,error:"finite repetitions must be at most 4096"};if(r++,e[r]==="?")r++;return{next:r,unbounded:o}}function _x(e){let t=[{previousAtom:null,lastAtom:null,atomCount:0,simpleClass:null,containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1}],n=0,r=()=>t[t.length-1],i=(a)=>{let s=r();if(s.lastAtom?.hasUnboundedQuantifier&&a.hasUnboundedQuantifier&&s.lastAtom.repeatClass!==null&&a.repeatClass!==null&&Vf(s.lastAtom.repeatClass,a.repeatClass))s.error="adjacent unbounded repetition with overlapping input is not supported";if(s.previousAtom=s.lastAtom,s.lastAtom=a,s.atomCount===0)s.simpleClass=a.repeatClass;else s.simpleClass=null;if(s.atomCount++,a.kind==="group")s.containsQuantifier||=a.containsQuantifier,s.containsAlternation||=a.containsAlternation;s.hasUnboundedQuantifier||=a.hasUnboundedQuantifier};for(let a=0;a<e.length;){if(r().error!==void 0)return{groupCount:n,error:r().error};let s=e[a];if(s==="\\"){let l=e[a+1];if(l!==void 0&&/[1-9]/.test(l)||l==="k"&&e[a+2]==="<")return{groupCount:n,error:"backreferences are not supported by the safe extractor"};let c=l==="b"||l==="B";if(i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:wx(l)}),a+=l===void 0?1:2,c)r().previousAtom=null,r().lastAtom=null;continue}if(s==="["){i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:{kind:"unknown"}}),a=Ex(e,a);continue}if(s==="("){let l=Tx(e,a);if(l.capturing)n++;t.push({previousAtom:null,lastAtom:null,atomCount:0,simpleClass:null,containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1}),a=l.next;continue}if(s===")"){if(t.length>1){let l=t.pop();if(l.error!==void 0)return{groupCount:n,error:l.error};i({kind:"group",containsQuantifier:l.containsQuantifier,containsAlternation:l.containsAlternation,hasUnboundedQuantifier:l.hasUnboundedQuantifier,repeatClass:l.atomCount===1&&!l.containsAlternation?l.simpleClass:null})}a++;continue}if(s==="|"){r().containsAlternation=!0,r().previousAtom=null,r().lastAtom=null,a++;continue}let o=Ax(e,a);if(o!==null){if(o.error)return{groupCount:n,error:o.error};let l=r(),c=l.lastAtom;if(o.unbounded&&c?.kind==="group"&&(c.containsQuantifier||c.containsAlternation))return{groupCount:n,error:"nested unbounded repetition or unbounded alternation is not supported"};if(o.unbounded&&l.previousAtom?.hasUnboundedQuantifier&&c!==null&&l.previousAtom.repeatClass!==null&&c.repeatClass!==null&&Vf(l.previousAtom.repeatClass,c.repeatClass))return{groupCount:n,error:"adjacent unbounded repetition with overlapping input is not supported"};if(l.containsQuantifier=!0,c!==null)l.lastAtom={...c,containsQuantifier:!0,hasUnboundedQuantifier:c.hasUnboundedQuantifier||o.unbounded};l.hasUnboundedQuantifier||=o.unbounded,a=o.next;continue}if(s!=="^"&&s!=="$")i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:s==="."?{kind:"any"}:{kind:"literal",value:s}});else r().previousAtom=null,r().lastAtom=null;a++}return{groupCount:n,error:r().error}}function Il(e){if(e.length>2048)throw Error("Credential extract pattern exceeds the 2048-character limit");let t;try{t=new RegExp(e)}catch{throw Error("Credential extract pattern is not a valid regular expression")}let n=_x(e);if(n.error!==void 0)throw Error(`Credential extract pattern rejected: ${n.error}`);return{regex:t,groupCount:n.groupCount}}function kx(e,t=""){Il(e);try{return new RegExp(e,t)}catch{throw Error("Credential extract pattern is not supported by this runtime")}}function ds(e,t,n,r={}){if(e.length>1048576)throw Error("Credential extraction input exceeds the 1048576-character limit");let i=kx(t,"gd"),a=new Map,s=new Map,o=[],l=0;for(let d of e.matchAll(i)){if(l++,l>4096)throw Error("Credential extraction exceeds the 4096-match limit");let f=d[1];if(f===void 0)throw Error(`Credential extraction matched at offset ${d.index} without a group-1 capture; group 1 must capture the credential value on every match.`);if(f.length===0)continue;let y=a.get(f);if(y===void 0)a.set(f,y=a.size);let[p,v]=d.indices[1],x=n(f,y);if(!s.has(f))s.set(f,x);o.push({start:p,end:v,sentinel:x})}if(a.size===0)return null;if(r.maskDuplicates){let d=[...a.keys()].sort((f,y)=>y.length-f.length);for(let f of d){let y=s.get(f);if(y===f)continue;for(let p=e.indexOf(f);p!==-1;p=e.indexOf(f,p+1)){let v=p+f.length;if(o.some((x)=>p<x.end&&x.start<v))continue;o.push({start:p,end:v,sentinel:y})}}o.sort((f,y)=>f.start-y.start)}let c="",u=0;for(let d of o)c+=e.slice(u,d.start)+d.sentinel,u=d.end;return{fakeContent:c+e.slice(u),captures:[...a.keys()]}}var Ff="(eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)";function Rl(e){try{return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{return}}function fs(e){let t=e.split(".");if(t.length!==3)return!1;let n=Rl(t[0]);if(typeof n!=="object"||n===null||!("alg"in n))return!1;return Rl(t[1])!==void 0}var Ix=9999999999,Mf="c3J0LWZha2U";function Bl(e){return Buffer.from(e,"utf8").toString("base64url")}function ps(e){let t=Bl(JSON.stringify({alg:"HS256",typ:"JWT"})),n=Bl(JSON.stringify({sub:qn+e,exp:Ix}));return`${t}.${n}.${Mf}`}function hs(e,t,n){let[r,i]=e.split("."),a=Rl(i??"");if(typeof a!=="object"||a===null||Array.isArray(a))return null;let s=a,o=[];for(let c of t){let u=s[c];if(typeof u==="string")o.push([c,u])}if(o.length===0)return null;let l=new Map;for(let[c,u]of o){let d=n(c,u);s[c]=d,l.set(c,d)}return{fakeToken:`${r}.${Bl(JSON.stringify(s))}.${Mf}`,claimSentinels:l}}var Px="file:";class Pl{dir;byKey=new Map;write(e,t){if(this.dir===void 0)this.dir=Qt.mkdtempSync(Wf(Bx(),"srt-credmask-"));let n=this.byKey.get(e);if(n===void 0)n=Wf(this.dir,`${this.byKey.size}.fake`),this.byKey.set(e,n);return Qt.rmSync(n,{force:!0}),Qt.writeFileSync(n,t,{mode:384}),n}dispose(){if(this.dir!==void 0)try{Qt.rmSync(this.dir,{recursive:!0,force:!0})}catch(e){C(`MaskedFileStore cleanup failed: ${e}`,{level:"error"})}this.dir=void 0,this.byKey.clear()}get dirPath(){return this.dir}}function $f(e,t,n,r){let i=[],a=[];for(let s of e){if(s.mode!=="mask")continue;let o=nt(s.path),l;try{if(Qt.statSync(o).isDirectory()){C(`[credential-mask] Skipping masked file entry that resolves to a directory: ${s.path} \u2014 use mode "deny" for directories.`,{level:"warn"});continue}let p=Qt.readFileSync(o);if(l=p.toString("utf8"),Buffer.byteLength(l,"utf8")!==p.length){C(`[credential-mask] Skipping masked file with non-UTF-8 content (binary credential files are not supported in mask mode): ${s.path}`,{level:"warn"});continue}}catch(y){C(`[credential-mask] Skipping masked file (unreadable on host): ${s.path} \u2014 ${y.message}`);continue}let c=s.injectHosts??t,u=Px+o,d;if(s.extract===void 0&&s.decode===void 0)d=n.register(u,l,c);else{let y=s.extract??Ff,p=0,v=ds(l,y,(x,b)=>{if(s.decode==="jwt"&&!fs(x))return x;let A=`${u}#${b}`;if(s.decode==="jwt"&&s.maskClaims?.length){let E=hs(x,s.maskClaims,(I,R)=>n.register(`${u}#jwt${b}.${I}`,R,c));if(E===null)return C(`[credential-mask] ${s.path}: verified JWT candidate has none of maskClaims ${JSON.stringify(s.maskClaims)} as `+"string claims \u2014 left unmasked."),x;let k=s.maskClaims.filter((I)=>!E.claimSentinels.has(I));if(k.length>0)C(`[credential-mask] ${s.path}: maskClaims ${JSON.stringify(k)} absent or non-string in a `+"verified JWT \u2014 skipped.");return p++,n.registerWithSentinel(A,E.fakeToken,x,c)}return p++,s.decode==="jwt"?n.registerWithSentinel(A,ps(Rx()),x,c):n.register(A,x,c)},{maskDuplicates:s.maskDuplicates??!1});if(v===null||p===0){let x=s.decode==="jwt"?s.maskClaims?.length?`decode "jwt" with pattern "${y}" that matched no verified JWT with maskable claims (maskClaims: ${JSON.stringify(s.maskClaims)})`:`decode "jwt" with pattern "${y}" that matched no verified JWT`:`extract pattern "${y}" that matched nothing`,b=s.onExtractNoMatch??"warn";if(b==="error")throw Error(`credentials.files entry "${s.path}": ${x} (onExtractNoMatch: "error"). Fix the config, change to "warn"/"deny", or remove the entry.`);if(b==="deny"){C(`[credential-mask] ${s.path} has ${x} \u2014 degrading to `+'mode "deny".',{level:"warn"}),a.push(o);continue}let A=`[sandbox-runtime] WARNING: credentials.files entry "${s.path}" has ${x} in the file. The file is left UNPROTECTED (readable as-is inside the sandbox). Fix the config, set onExtractNoMatch to "deny" or "error", or remove the entry.`;console.warn(A),C(A,{level:"warn"});continue}d=v.fakeContent}let f=r.write(u,d);i.push({realPath:o,fakePath:f})}return{binds:i,degradeToDenyPaths:a}}import{randomUUID as Nx}from"crypto";var gs="env:";function Hf(e,t,n,r=process.env){let i={},a=[];for(let s of e){if(s.mode!=="mask")continue;let o=r[s.name];if(o===void 0)continue;let l=s.injectHosts??t;if(s.decode==="jwt"){if(!fs(o)){let u=`[sandbox-runtime] WARNING: credentials.envVars entry "${s.name}" has decode "jwt" but its value did not verify as a JWT. The variable is left UNPROTECTED (real value visible as-is inside the sandbox). Fix the config or remove the entry.`;console.warn(u),C(u,{level:"warn"});continue}if(s.maskClaims?.length){let u=hs(o,s.maskClaims,(f,y)=>n.register(`${gs}${s.name}#${f}`,y,l,s.injectHeaders));if(u===null){let f=`[sandbox-runtime] WARNING: credentials.envVars entry "${s.name}" has maskClaims ${JSON.stringify(s.maskClaims)} but none is present as a string claim in its JWT value. The variable is left UNPROTECTED (real value visible as-is inside the sandbox). Fix the config or remove the entry.`;console.warn(f),C(f,{level:"warn"});continue}let d=s.maskClaims.filter((f)=>!u.claimSentinels.has(f));if(d.length>0)C(`[credential-mask] env var "${s.name}": maskClaims ${JSON.stringify(d)} absent or non-string in the `+"JWT \u2014 skipped.");i[s.name]=n.registerWithSentinel(`${gs}${s.name}`,u.fakeToken,o,l,s.injectHeaders);continue}i[s.name]=n.registerWithSentinel(`${gs}${s.name}`,ps(Nx()),o,l,s.injectHeaders);continue}if(s.extract===void 0){i[s.name]=n.register(s.name,o,l,s.injectHeaders);continue}let c=ds(o,s.extract,(u,d)=>n.register(`${gs}${s.name}#${d}`,u,l,s.injectHeaders));if(c===null){let u=s.onExtractNoMatch??"warn";if(u==="error")throw Error(`credentials.envVars entry "${s.name}": extract pattern "${s.extract}" matched nothing (onExtractNoMatch: "error"). Fix the regex, change to "warn"/"deny", or remove the entry.`);if(u==="deny"){C(`[credential-mask] extract pattern /${s.extract}/ matched nothing in the value of ${s.name} \u2014 unsetting the variable.`,{level:"warn"}),a.push(s.name);continue}let d=`[sandbox-runtime] WARNING: credentials.envVars entry "${s.name}" has extract pattern "${s.extract}" that matched nothing in the variable's value. The variable is left UNPROTECTED (visible as-is inside the sandbox). Fix the regex, set onExtractNoMatch to "deny" or "error", or remove the entry.`;console.warn(d),C(d,{level:"warn"});continue}i[s.name]=c.fakeContent}return{setEnvVars:i,degradeToUnsetNames:a}}var Kf="AWS_ACCESS_KEY_ID",qf="AWS_SECRET_ACCESS_KEY",Gf="AWS_SESSION_TOKEN";class Nl{bySentinel=new Map;register(e){this.bySentinel.set(e.accessKeyIdSentinel,e)}lookup(e){return this.bySentinel.get(e)}get size(){return this.bySentinel.size}forget(e){for(let t of e)this.bySentinel.delete(t)}clear(){this.bySentinel.clear()}}function jf(e,t,n,r,i,a=process.env){let s=[...t??[]],o=new Set(s.flatMap((d)=>[d.accessKeyIdVar,d.secretAccessKeyVar,...d.sessionTokenVar?[d.sessionTokenVar]:[]]));if(![Kf,qf,Gf].some((d)=>o.has(d)))s.push({accessKeyIdVar:Kf,secretAccessKeyVar:qf,sessionTokenVar:Gf});let c=(d)=>e.find((f)=>f.name===d&&f.mode==="mask"&&f.extract===void 0&&f.decode===void 0),u=(d)=>c(d)!==void 0?r[d]:void 0;for(let d of s){let f=u(d.accessKeyIdVar),y=u(d.secretAccessKeyVar)!==void 0,p=a[d.accessKeyIdVar],v=a[d.secretAccessKeyVar];if(f===void 0||!y||p===void 0||v===void 0){if(y&&f===void 0){let E=`[sandbox-runtime] WARNING: "${d.secretAccessKeyVar}" is masked but "${d.accessKeyIdVar}" is not, so no AWS credential pair was registered. SigV4 requests will be signed with the masked placeholder secret and the proxy cannot `+"detect or re-sign them \u2014 they will fail upstream. Mask both "+"variables (whole-value) to enable re-signing.";console.warn(E),C(E,{level:"warn"})}continue}let x=c(d.accessKeyIdVar),A=(d.sessionTokenVar!==void 0?u(d.sessionTokenVar):void 0)!==void 0&&d.sessionTokenVar!==void 0?a[d.sessionTokenVar]:void 0;i.register({accessKeyIdSentinel:f,realAccessKeyId:p,realSecretAccessKey:v,...A!==void 0?{realSessionToken:A}:{},injectHosts:x.injectHosts??n}),C(`[credential-aws] registered SigV4 pair for ${d.accessKeyIdVar}/${d.secretAccessKeyVar}`+(A!==void 0?" (+session token)":""))}}function Dx(e){return{streaming:e?.streaming??"deny",presigned:e?.presigned??"deny",sigv4a:e?.sigv4a??"deny"}}function zf(e,t,n){let r=Dx(t);return(i,a,s,o)=>{if(e.size===0)return;let l=ff(s,a);if(l===null)return;let c=e.lookup(l.accessKeyId);if(c===void 0)return;if(!c.injectHosts.some((p)=>n(o,p)))return;if(l.kind!=="header-sigv4"){if(r[l.kind]==="passthrough"){C(`[credential-aws] ${l.kind} request with masked credential passed through un-resigned per credentials.sigv4.${l.kind} (its signature covers the placeholder secret and will fail upstream)`);return}return{action:"deny",reason:`AWS SigV4 ${l.kind} request uses a masked credential but cannot be re-signed by the sandbox proxy; denied by policy. Set credentials.sigv4.${l.kind} to "passthrough" to forward it unmodified (it will fail upstream: the signature covers the masked placeholder).`}}let u=pf(Kn(s.authorization));if(u===null)return{action:"deny",reason:"AWS SigV4 request uses a masked credential but its Authorization header is malformed; the proxy cannot re-sign it."};let d=Kn(s["x-amz-date"]);if(d===void 0)return{action:"deny",reason:"AWS SigV4 request uses a masked credential but carries no x-amz-date header; the proxy cannot re-sign it."};let f=[...u.signedHeaders];for(let p of f){if(p==="host")continue;if(p==="x-amz-security-token"&&c.realSessionToken!==void 0)continue;if(s[p]===void 0)return{action:"deny",reason:`AWS SigV4 request uses a masked credential but signed header "${p}" is missing; the proxy cannot re-sign it.`}}if(c.realSessionToken!==void 0&&!f.includes("x-amz-security-token"))f.push("x-amz-security-token");let y=Kn(s["x-amz-content-sha256"]);return{action:"resign",payloadHash:y===os?os:void 0,apply(p,v,x){if(c.realSessionToken!==void 0)p["x-amz-security-token"]=c.realSessionToken;if(p["x-amz-content-sha256"]!==void 0&&y!==os)p["x-amz-content-sha256"]=x;let{authorization:b}=hf({method:i,requestTarget:a,headers:p,hostHeader:v,signedHeaders:f,payloadHash:x,amzDate:d,scope:{date:u.date,region:u.region,service:u.service},accessKeyId:c.realAccessKeyId,secretAccessKey:c.realSecretAccessKey});p.authorization=b}}}}import{spawnSync as Lx}from"child_process";import*as Gn from"fs";function Cr(e){if(typeof globalThis.Bun<"u")return globalThis.Bun.which(e);let t=process.env.PATH;if(process.platform==="linux"&&t){let r=(i)=>{try{if(!Gn.statSync(i).isFile())return!1;return Gn.accessSync(i,Gn.constants.X_OK),!0}catch{return!1}};if(e.includes("/"))return r(e)?e.trim():null;for(let i of t.split(":")){let a=`${i||"."}/${e}`;if(r(a))return a.trim()}return null}let n=Lx("which",[e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000});if(n.status===0&&n.stdout)return n.stdout.trim();return null}import*as zr from"fs";import{randomBytes as XS}from"crypto";function kt(e){return e.map((t)=>{if(t==="")return"''";if(/^[A-Za-z0-9_./:@+,-][A-Za-z0-9_./:=@+,-]*$/.test(t))return t;return"'"+t.replace(/'/g,`'"'"'`)+"'"}).join(" ")}import{randomBytes as sS}from"crypto";import*as Y from"fs";import{spawn as pp}from"child_process";import{tmpdir as bs}from"os";import Ue,{join as hp}from"path";import{spawn as Ox}from"child_process";import{text as Qf}from"stream/consumers";var Ux={ms:1e4};class ms extends Error{constructor(e){super(`ripgrep timed out after ${e} ms`);this.name="RipgrepTimeoutError"}}async function Dl(e,t,n,r={command:"rg"}){let{command:i,args:a=[],argv0:s}=r,o=Ox(i,[...a,...e,t],{argv0:s,env:{PATH:process.env.PATH??"/usr/bin:/bin"},signal:n,windowsHide:!0}),l=Ux.ms,c=!1,u=setTimeout(()=>{c=!0,o.kill("SIGKILL")},l),d,f,y;try{[d,f,y]=await Promise.all([Qf(o.stdout),Qf(o.stderr),new Promise((p,v)=>{o.on("close",p),o.on("error",v)})])}finally{clearTimeout(u)}if(c)throw new ms(l);if(y===0)return d.trim().split(`
62
- `).filter(Boolean);if(y===1)return[];throw Error(`ripgrep failed with exit code ${y}: ${f}`)}import{join as dr,dirname as Vx}from"path";import{fileURLToPath as Fx}from"url";import*as ys from"fs";import{homedir as Mx}from"os";var Ll=new Map,Ol=null;function Wx(){if(Ol)return Ol;let e=[],t=Mx();return e.push(dr("/usr","lib","node_modules","@anthropic-ai","sandbox-runtime"),dr("/usr","local","lib","node_modules","@anthropic-ai","sandbox-runtime"),dr("/opt","homebrew","lib","node_modules","@anthropic-ai","sandbox-runtime"),dr(t,".npm","lib","node_modules","@anthropic-ai","sandbox-runtime"),dr(t,".npm-global","lib","node_modules","@anthropic-ai","sandbox-runtime")),Ol=e,e}function Xf(){let e=process.arch;switch(e){case"x64":case"x86_64":return"x64";case"arm64":case"aarch64":return"arm64";case"ia32":case"x86":return C("[SeccompFilter] 32-bit x86 (ia32) is not currently supported due to missing socketcall() syscall blocking. The current seccomp filter only blocks socket(AF_UNIX, ...), but on 32-bit x86, socketcall() can be used to bypass this.",{level:"error"}),null;default:return C(`[SeccompFilter] Unsupported architecture: ${e}. Only x64 and arm64 are supported.`),null}}function $x(e){let t=Xf();if(!t)return[];let n=Vx(Fx(import.meta.url)),r=dr("vendor","seccomp",t,e);return[dr(n,r),dr(n,"..","..",r),dr(n,"..",r)]}function Ul(e){let t=e??"";if(Ll.has(t))return Ll.get(t);let n=Hx(e);return Ll.set(t,n),n}function Hx(e){if(e){if(ys.existsSync(e))return C(`[SeccompFilter] Using apply-seccomp binary from explicit path: ${e}`),e;C(`[SeccompFilter] Explicit path provided but file not found: ${e}`)}let t=Xf();if(!t)return C(`[SeccompFilter] Cannot find apply-seccomp binary: unsupported architecture ${process.arch}`),null;C(`[SeccompFilter] Looking for apply-seccomp binary for architecture: ${t}`);for(let n of $x("apply-seccomp"))if(ys.existsSync(n))return C(`[SeccompFilter] Found apply-seccomp binary: ${n} (${t})`),n;for(let n of Wx()){let r=dr(n,"vendor","seccomp",t,"apply-seccomp");if(ys.existsSync(r))return C(`[SeccompFilter] Found apply-seccomp binary in global install: ${r} (${t})`),r}return C(`[SeccompFilter] apply-seccomp binary not found in any expected location (${t})`),null}import{spawnSync as Kx}from"child_process";import{createHash as qx}from"crypto";import*as X from"fs";import Xt from"path";class Oi extends Error{}var Gx={dir:"/run/srt-stubs",uid:0,lockWaitMs:2000,flockPath:"/usr/bin/flock"},jn=Gx,jx,Zf;var vs=X.constants.O_CLOEXEC??524288,Vl={kind:"masked"},Yf={kind:"real"},Li={kind:"unregistered"},zx=new Set(["ENOENT","EACCES"]),Qx=new Set(["ENOENT","ENOTDIR","EROFS"]),fr=null,gn=null,Xx=0;function Ui(e){return e?.code}function Ml(e){return qx("sha256").update(e).digest("hex")}function Wl(){if(process.platform!=="linux")return"off";let{dir:e,uid:t,flockPath:n}=jn;if(process.geteuid?.()!==t)return"off";try{X.accessSync(n,X.constants.X_OK)}catch(i){return zx.has(Ui(i)??"")?"off":"error"}try{X.mkdirSync(e,{mode:448}),X.chmodSync(e,448)}catch(i){let a=Ui(i)??"";if(a!=="EEXIST")return Qx.has(a)?"off":"error"}let r;try{r=X.lstatSync(e)}catch{return"error"}if(!r.isDirectory()||r.uid!==t||(r.mode&511)!==448)return C(`[Sandbox Linux] ${e} is not a 0700 directory owned by uid ${t}; mask stubs are not shared`,{level:"warn"}),"off";return e}function ep(e,t){try{return X.openSync(Xt.join(e,t),X.constants.O_RDONLY|X.constants.O_CREAT|X.constants.O_NOFOLLOW|vs,384)}catch{return null}}function tp(e,t){try{return Kx(jn.flockPath,[...t,"3"],{stdio:["ignore","ignore","ignore",e],timeout:jn.lockWaitMs+5000}).status===0}catch{return!1}}function Jf(e,t,n){let r=ep(e,t);if(r===null)return null;let i=(jn.lockWaitMs/1000).toFixed(3);if(tp(r,[n,"-w",i]))return r;return X.closeSync(r),null}function rp(e){try{X.closeSync(e)}catch{}}function np(){let e=Wl();if(e==="off")return!1;if(e==="error")throw new Oi(`srt: cannot read the mask stub registry ${jn.dir}; refusing to start the sandbox`);if(fr===null)fr=Jf(e,"lock","-s");if(fr!==null&&gn===null)gn=Jf(e,"claims","-x");if(fr===null||gn===null)throw new Oi(`srt: mask stub registry ${e} is busy (no ${fr===null?"shared":"claims"} lock within ${jn.lockWaitMs} ms); refusing to start the sandbox rather than risk a mask another call removes`);return!0}function xs(){if(gn===null)return;rp(gn),gn=null}function Yx(){if(fr===null)return;rp(fr),fr=null}function ip(){let e=Wl();if(e==="off")return null;if(e==="error"||fr===null||gn===null)throw new Oi("srt: mask stub claimed without holding the registry; refusing to start the sandbox");return e}function Vi(e){try{return X.lstatSync(e,{bigint:!0})}catch(t){return Ui(t)==="ENOENT"?"absent":"unknown"}}function ap(e){try{let t=JSON.parse(X.readFileSync(e,"utf8")),{v:n,type:r,uid:i,dev:a,ino:s,ctimeNs:o,path:l}=t,c=(u)=>typeof u==="string"&&/^\d+$/.test(u);if(n!==1||r!=="f"&&r!=="d"||typeof i!=="number"||!c(a)||!c(s)||!c(o)||typeof l!=="string"||!l.startsWith("/"))return null;return{type:r,uid:i,dev:BigInt(a),ino:BigInt(s),ctimeNs:BigInt(o),dest:l}}catch{return null}}function sp(e,t){return Xt.join(e,`${Ml(t)}.stub`)}function Jx(e,t){let n=Ml(t.dest),r=Xt.join(e,`${n}.stub.${process.pid}-${++Xx}`),i=JSON.stringify({v:1,type:t.type,uid:t.uid,dev:String(t.dev),ino:String(t.ino),ctimeNs:String(t.ctimeNs),path:t.dest});X.writeFileSync(r,i+`
63
- `,{flag:"wx",mode:384}),X.renameSync(r,Xt.join(e,`${n}.stub`))}function op(e,t){return(t.type==="f"?e.isFile()&&e.size===BigInt(0):e.isDirectory())&&e.uid===BigInt(t.uid)&&e.dev===t.dev&&e.ino===t.ino&&e.ctimeNs===t.ctimeNs}function $l(e){let t=Xt.dirname(e),n;try{n=X.openSync(t,X.constants.O_RDONLY|X.constants.O_DIRECTORY|X.constants.O_NOFOLLOW|vs)}catch{return null}try{if(X.readlinkSync(`/proc/self/fd/${n}`)===t)return n}catch{}return X.closeSync(n),null}function lp(e,t,n){return{type:e,uid:Number(t.uid),dev:t.dev,ino:t.ino,ctimeNs:t.ctimeNs,dest:n}}function Zx(e){let t=$l(e);if(t===null)return null;try{let n;try{n=X.openSync(`/proc/self/fd/${t}/${Xt.basename(e)}`,X.constants.O_RDONLY|X.constants.O_CREAT|X.constants.O_EXCL|X.constants.O_NOFOLLOW|vs,292)}catch(r){return Ui(r)==="EEXIST"?"exists":null}try{return Zf?.(e),lp("f",X.fstatSync(n,{bigint:!0}),e)}finally{X.closeSync(n)}}finally{X.closeSync(t)}}function eS(e,t){let n=$l(e);if(n===null)return null;try{let r=`/proc/self/fd/${n}/${Xt.basename(e)}`;try{X.mkdirSync(r,{mode:493})}catch(a){return Ui(a)==="EEXIST"?"exists":null}Zf?.(e);let i;try{i=X.openSync(r,X.constants.O_RDONLY|X.constants.O_DIRECTORY|X.constants.O_NOFOLLOW|vs)}catch{return null}try{let a=X.fstatSync(i,{bigint:!0});if(!a.isDirectory()||a.uid!==BigInt(process.geteuid?.()??-1)||a.nlink>BigInt(2)||X.readdirSync(`/proc/self/fd/${i}`).length!==0)return null;if(t)X.fchownSync(i,t.uid,t.gid);return lp("d",X.fstatSync(i,{bigint:!0}),e)}catch{return null}finally{X.closeSync(i)}}finally{X.closeSync(n)}}function tS(e){let t=$l(e.dest);if(t===null)return;try{let n=`/proc/self/fd/${t}/${Xt.basename(e.dest)}`,r=Vi(n);if(typeof r==="object"&&op(r,e)){if(e.type==="d")X.rmdirSync(n);else X.unlinkSync(n);C(`[Sandbox Linux] Removed shared mask stub: ${e.dest}`)}}catch{}finally{X.closeSync(t)}}function rS(e){try{X.unlinkSync(e)}catch{}}function Fl(e,t,n,r){let i=ap(sp(e,t));return i!==null&&i.type===r&&i.dest===t&&op(n,i)}function cp(e,t,n){let r=ip();if(r===null)return Li;if(jx?.(e)==="unregistered")return Li;let i=Vi(e);if(i==="unknown")return Li;if(i!=="absent")return Fl(r,e,i,t)?Vl:Yf;let a=n();if(a==="exists"){let s=Vi(e);return typeof s==="object"&&Fl(r,e,s,t)?Vl:Yf}if(a===null)return Li;try{Jx(r,a)}catch(s){C(`[Sandbox Linux] mask stub marker not written for ${e}: ${s}`,{level:"warn"})}return Vl}function nS(e){return cp(e,"f",()=>Zx(e))}function iS(e,t){return cp(e,"d",()=>eS(e,t))}function up(e,t){let n=ip();if(n===null)return null;let r=(a)=>t.some((s)=>a.startsWith(s+"/")),i=[];for(let a=Xt.dirname(e);r(a);a=Xt.dirname(a))i.unshift(a);for(let a of i){let s=Vi(a);if(typeof s==="object"&&Fl(n,a,s,"d"))return a}return null}function dp(e,t){try{return e()}catch(n){if(n instanceof Oi)throw n;return C(`[Sandbox Linux] mask stub not recorded for ${t}: ${n}`,{level:"warn"}),Li}}function Hl(e){return dp(()=>nS(e),e)}function fp(e,t){return dp(()=>iS(e,t),e)}function aS(e){let t;try{t=X.readdirSync(e)}catch{return}let n=[],r=[];for(let a of t){let s=/^([0-9a-f]{64})\.stub(\..*)?$/.exec(a);if(s===null)continue;let o=Xt.join(e,a);if(r.push(o),s[2]===void 0){let l=ap(o);if(l!==null&&Ml(l.dest)===s[1])n.push(l)}}let i=(a)=>a.dest.split("/").length;n.sort((a,s)=>a.type===s.type?i(s)-i(a):a.type==="f"?-1:1);for(let a of n)tS(a);for(let a of r)rS(a)}function Kl(e,t){let n=Wl(),r=fr!==null;if(xs(),Yx(),n==="off"){for(let a of e)t(a);return[]}if(n==="error")return[...e];if(!r&&e.length===0)return[];let i=ep(n,"lock");if(i===null)return[...e];try{if(!tp(i,["-x","-n"]))return[...e];for(let a of e)if(Vi(sp(n,a))==="absent")t(a);return aS(n),[]}catch(a){return C(`[Sandbox Linux] mask stub sweep failed: ${a}`,{level:"warn"}),[...e]}finally{X.closeSync(i)}}var zl=3;function oS(e){let t=e.uid===void 0?e.bwrapCommand:[e.setprivPath??"/usr/bin/setpriv",`--reuid=${e.uid}`,`--regid=${e.gid??e.uid}`,"--clear-groups","--inh-caps=-all","--ambient-caps=-all","--bounding-set=-all",...e.bwrapCommand],n=e.unsetEnvVars??[],r=Object.entries(e.setEnvVars??{});if(n.length===0&&r.length===0)return t;return["/usr/bin/env",...n.flatMap((i)=>["-u",i]),...r.map(([i,a])=>`${i}=${a}`),...t]}function ql(e,t){let n=e.split(Ue.sep),r="";for(let i of n){if(!i)continue;let a=r+Ue.sep+i;try{if(Y.lstatSync(a).isSymbolicLink()){if(t.some((l)=>a.startsWith(l+"/")||a===l))return a}}catch{break}r=a}return null}var lS=40;function gp(e){let t=e;for(let n=0;n<lS;n++){try{return Y.realpathSync(t)}catch{}let r=t,i=[],a=null;while(a===null){let l=Ue.dirname(r);if(l===r)return null;i.unshift(Ue.basename(r)),r=l;try{a=Y.realpathSync(r)}catch{}}let s=Ue.join(a,i[0]),o=null;try{o=Y.readlinkSync(s)}catch{}if(o===null)return Ue.join(a,...i);t=Ue.join(Ue.resolve(Ue.dirname(s),o),...i.slice(1))}return null}function cS(e){let t=e.split(Ue.sep),n="";for(let r of t){if(!r)continue;let i=n+Ue.sep+r;try{let a=Y.statSync(i);if(a.isFile()||a.isSymbolicLink())return!0}catch{break}n=i}return!1}function uS(e){let t=e.split(Ue.sep),n="";for(let r of t){if(!r)continue;let i=n+Ue.sep+r;if(!Y.existsSync(i))return i;n=i}return e}async function dS(e={command:"rg"},t=zl,n=!1,r){let i=process.cwd(),a=new AbortController,s=r??a.signal,o=ya(),l=[...ci.map((p)=>Ue.resolve(i,p)),...o.map((p)=>Ue.resolve(i,p))],c=Ue.resolve(i,".git"),u=!1;try{u=Y.statSync(c).isDirectory()}catch{}if(u){if(l.push(Ue.resolve(i,".git/hooks")),!n)l.push(Ue.resolve(i,".git/config"))}let d=[];for(let p of ci)d.push("--iglob",p);for(let p of o)d.push("--iglob",`**/${p}/**`);if(d.push("--iglob","**/.git/hooks/**"),!n)d.push("--iglob","**/.git/config");let f=["--files","--hidden","--no-ignore","--max-depth",String(t),...d,"-g","!**/node_modules/**"],y;try{y=await Dl(f,i,s,e)}catch(p){if(p instanceof ms)throw Error(`mandatory deny scan failed: ${p}`);C(`[Sandbox] ripgrep scan failed, retrying once: ${p}`);try{y=await Dl(f,i,s,e)}catch(v){throw Error(`mandatory deny scan failed: ${v}`)}}for(let p of y){let v=Ue.resolve(i,p),x=!1;for(let b of[...o,".git"]){let A=Xs(b),E=v.split(Ue.sep),k=E.findIndex((I)=>Xs(I)===A);if(k!==-1){if(b===".git"){let I=E.slice(0,k+1).join(Ue.sep);if(p.includes(".git/hooks"))l.push(Ue.join(I,"hooks"));else if(p.includes(".git/config"))l.push(Ue.join(I,"config"))}else l.push(E.slice(0,k+1).join(Ue.sep));x=!0;break}}if(!x)l.push(v)}return[...new Set(l)]}var Fi;function fS(){if(process.getuid?.()!==0||process.env.ARA_SRT_FILE_MASK!=="empty")return"/dev/null";if(Fi)try{let n=Y.lstatSync(Fi);if(n.isFile()&&n.size===0&&n.uid===0&&(n.mode&146)===0)return Fi}catch{}let e=Y.mkdtempSync(Ue.join(bs(),"claude-empty-file-"));Cs.add(e),Y.chmodSync(e,493);let t=Ue.join(e,"empty");return Y.writeFileSync(t,"",{flag:"wx",mode:292}),Y.chmodSync(t,292),Fi=t,t}var Mi=new Set,Cs=new Set;function mp(e,t){return e===t?fS():"/dev/null"}var pS="ARA_SRT_MASKED_PATHS",hS=16384;function gS(e,t,n=hS){let r=[],i=0;for(let a of new Set(e)){if(a.includes(`
64
- `))continue;if(a!==t&&!a.startsWith(t==="/"?"/":t+"/"))continue;let s=a.split("'").length-1,o=Buffer.byteLength(a)+4*s+(r.length>0?1:0);if(i+o>n)break;r.push(a),i+=o}return r.length>0?r.join(`
65
- `):void 0}function mS(e){try{let t=Y.lstatSync(e);return t.isFile()&&t.size===0}catch{return!1}}var Er=0,yp=!1;function Ss(){if(yp)return;process.on("exit",()=>{Es({force:!0})}),yp=!0}function Es(e){if(!e?.force){if(Er>0)Er--;if(Er>0){C(`[Sandbox Linux] Deferring mount point cleanup \u2014 ${Er} sandbox(es) still active`);return}}else Er=0;let t=[],n=[];for(let a of Mi)try{let s=Y.statSync(a);if(s.isFile()&&s.size===0)t.push(a);else if(s.isDirectory())n.push(a)}catch{}let r=(a)=>a.split("/").length;n.sort((a,s)=>r(s)-r(a));let i=Kl([...t,...n],(a)=>{try{let s=Y.statSync(a);if(s.isFile()&&s.size===0)Y.unlinkSync(a),C(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${a}`);else if(s.isDirectory()){if(Y.readdirSync(a).length!==0)return;Y.rmdirSync(a),C(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${a}`)}}catch{}});Mi.clear();for(let a of i)Mi.add(a);for(let a of Cs)try{Y.rmSync(a,{recursive:!0,force:!0})}catch{}Cs.clear(),Fi=void 0}function vp(e){try{return Y.accessSync(e,Y.constants.X_OK),!0}catch{return!1}}function Sp(e){let{seccompConfig:t,bwrapPath:n,socatPath:r}=e??{},i=[],a=[];if(n){if(!vp(n))i.push(`bubblewrap (bwrap) not executable at ${n}`)}else if(Cr("bwrap")===null)i.push("bubblewrap (bwrap) not installed");if(r){if(!vp(r))i.push(`socat not executable at ${r}`)}else if(Cr("socat")===null)i.push("socat not installed");if(!t?.argv0&&Ul(t?.applyPath)===null)a.push("seccomp not available - unix socket access not restricted");return{warnings:a,errors:i}}async function bp(e,t,n,r,i){let a=n??"socat",s=sS(8).toString("hex"),o=hp(bs(),`claude-http-${s}.sock`),l=hp(bs(),`claude-socks-${s}.sock`),c=[`UNIX-LISTEN:${o},fork,reuseaddr`,`TCP:localhost:${e},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];C(`Starting HTTP bridge: ${a} ${c.join(" ")}`);let u=pp(a,c,{stdio:"ignore"});if(u.on("error",(p)=>{C(`HTTP bridge process error: ${p}`,{level:"error"})}),u.on("exit",(p,v)=>{C(`HTTP bridge process exited with code ${p}, signal ${v}`,{level:p===0?"info":"error"})}),!u.pid)throw Error("Failed to start HTTP bridge process");let d,f;if(t===e)d=u,f=o;else{f=l;let p=[`UNIX-LISTEN:${l},fork,reuseaddr`,`TCP:localhost:${t},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];if(C(`Starting SOCKS bridge: ${a} ${p.join(" ")}`),d=pp(a,p,{stdio:"ignore"}),d.on("error",(v)=>{C(`SOCKS bridge process error: ${v}`,{level:"error"})}),d.on("exit",(v,x)=>{C(`SOCKS bridge process exited with code ${v}, signal ${x}`,{level:v===0?"info":"error"})}),!d.pid){if(u.pid)try{process.kill(u.pid,"SIGTERM")}catch{}throw Error("Failed to start SOCKS bridge process")}}let y=200;for(let p=0;p<y;p++){if(!u.pid||u.killed||!d.pid||d.killed)throw Error("Linux bridge process died unexpectedly");try{if(Y.existsSync(o)&&Y.existsSync(f)){if(r!==void 0){let v=i??r;for(let x of new Set([o,f]))Y.chownSync(x,r,v),Y.chmodSync(x,384)}C(`Linux bridges ready after ${p+1} attempts`);break}}catch(v){C(`Error checking sockets (attempt ${p+1}): ${v}`,{level:"error"})}if(p===y-1){if(u.pid)try{process.kill(u.pid,"SIGTERM")}catch{}if(d.pid)try{process.kill(d.pid,"SIGTERM")}catch{}throw Error(`Failed to create bridge sockets after ${y} attempts`)}await new Promise((v)=>setTimeout(v,5))}return{httpSocketPath:o,socksSocketPath:f,httpBridgeProcess:u,socksBridgeProcess:d,httpProxyPort:e,socksProxyPort:t}}function yS(e,t){if(t){if(!e)throw Error("seccompConfig.argv0 requires seccompConfig.applyPath");return`ARGV0=${kt([t])} ${kt([e])} `}let n=Ul(e);return n?`${kt([n])} `:void 0}function jl(e,t,n){if(n===void 0)return[e,"-c",t];return[e,"-c",`${Cp(n)}; exec "$0" "$@"`,e,"-c",t]}function Cp(e){if(!Number.isSafeInteger(e)||e<3||e>9)throw Error("bad_start_fd");return`printf . >&${e}; exec ${e}>&-`}function vS(e,t,n,r,i,a,s,o){let l=i||"bash",c=kt([a??"socat"]),u=s===void 0?"":` ${s}>&-`,d=["srt_payload_pid=",`${c} TCP4-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr ${kt([`UNIX-CONNECT:${e}`])} >/dev/null 2>&1${u} &`,"srt_http_proxy_pid=$!",`${c} TCP4-LISTEN:1080,bind=127.0.0.1,fork,reuseaddr ${kt([`UNIX-CONNECT:${t}`])} >/dev/null 2>&1${u} &`,"srt_socks_proxy_pid=$!","srt_cleanup_command() {"," srt_status=$?"," trap - EXIT INT TERM",' if [ -n "$srt_payload_pid" ]; then',' kill -KILL "$srt_payload_pid" 2>/dev/null',' wait "$srt_payload_pid" 2>/dev/null'," fi",' kill -KILL "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null',' wait "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null',' exit "$srt_status"',"}","trap srt_cleanup_command EXIT","trap 'exit 143' TERM","trap 'exit 130' INT",...[3128,1080].map((p)=>`{ true <>/dev/tcp/127.0.0.1/${p}; } 2>/dev/null || { ${c} -u OPEN:/dev/null TCP4:127.0.0.1:${p},connect-timeout=0.1,retry=480,interval=0.005 >/dev/null 2>&1${u} & wait "$!"; } || { printf '%s\\n' 'Sandbox proxy listener readiness failed' >&2; exit 1; }`),`kill -0 "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null || { printf '%s\\n' 'Sandbox proxy listener exited before command' >&2; exit 1; }`],f=r===void 0&&s!==void 0?`{ ${Cp(s)}; trap '' INT QUIT; exec ${o?n:kt([l,"-c",n])}; }`:(r??"")+kt(jl(l,n,s));return[...d,`${f} <&0 &`,"srt_payload_pid=$!",'wait "$srt_payload_pid"',"srt_payload_status=$?","srt_payload_pid=",'exit "$srt_payload_status"'].join(`
66
- `)}function Gl(e){try{if(Y.lstatSync(e).isSymbolicLink())return Y.realpathSync(e)}catch{}return e}function xp(e,t,n,r){let i=t==="/"?"/":t+"/";e.push("--tmpfs",t);for(let a of n)if(a.startsWith(i)||a===t)e.push("--bind",a,a),C(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${a}`);for(let a of r)if(a.startsWith(i)||a===t){if(!Y.existsSync(a)){C(`[Sandbox Linux] Skipping non-existent read allow path: ${a}`);continue}if(n.some((s)=>(s.startsWith(i)||s===t)&&(a===s||a.startsWith(s+"/"))))continue;e.push("--ro-bind",a,a),C(`[Sandbox Linux] Re-allowed read access within denied region: ${a}`)}}async function xS(e,t,n,r,i={command:"rg"},a=zl,s=!1,o,l,c=[]){let u=[],d=[],f=[],y=new Set,p=new Map,v=new Map;if(t){u.push("--ro-bind","/","/");for(let V of t.allowOnly||[]){let te=nt(V).replace(/\/+$/,"")||"/";if(C(`[Sandbox Linux] Processing write path: ${V} -> ${te}`),te.startsWith("/dev/")){C(`[Sandbox Linux] Skipping /dev path: ${te}`);continue}if(!Y.existsSync(te)){C(`[Sandbox Linux] Skipping non-existent write path: ${te}`);continue}try{let Q=Y.realpathSync(te),ue=te.replace(/\/+$/,"");if(Q!==ue&&ma(te,Q)){C(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${V} -> ${Q}`);continue}}catch{C(`[Sandbox Linux] Skipping write path that could not be resolved: ${te}`);continue}u.push("--bind",te,te),d.push(te)}let O,K=()=>{if(O!==void 0)return O;let V=[];for(let Q of d){V.push(Q);try{let ue=Y.realpathSync(Q);if(ue!==Q)V.push(ue)}catch{}}let te=[];if(e){let Q=[],ue=new Set(["proc","dev","sys"]);for(let ce of e.denyOnly||[])if(nt(ce)==="/")try{for(let Z of Y.readdirSync("/"))if(!ue.has(Z))Q.push("/"+Z)}catch{}else Q.push(ce);if(Y.existsSync("/etc/ssh/ssh_config.d"))Q.push("/etc/ssh/ssh_config.d");for(let ce of Q){let Z=nt(ce),Ie=!1;try{Ie=Y.statSync(Z).isDirectory()}catch{continue}if(!Ie)continue;te.push(Z);try{let We=Y.realpathSync(Z);if(We!==Z)te.push(We)}catch{}}}return O={allowedWritePathsBothForms:V,prospectiveReadDenyTmpfsDirsBothForms:te},O},ie=(V)=>d.some((te)=>V.startsWith(te+"/")||V===te),ve=[...t.denyWithinAllow||[],...await dS(i,a,s,o)];np();let we=new Set;for(let V of ve){let te=nt(V);if(te.startsWith("/dev/"))continue;let Q=gp(te);if(Q===null||Q.startsWith("/dev/"))continue;if(ql(Q,d))continue;let ue=!1;try{ue=Y.statSync(Q).isDirectory()}catch{continue}if(!ue)continue;if(ie(Q)){let ce=p.get(Q);if(ce===void 0)ce=new Set,p.set(Q,ce);ce.add(te)}}let rt=new Map,_e=(V)=>{let te=rt.get(V);if(te!==void 0)return te;let{allowedWritePathsBothForms:Q,prospectiveReadDenyTmpfsDirsBothForms:ue}=K(),ce=Q.some((Z)=>Z.startsWith(V+"/"))||ue.some((Z)=>Z===V||Z.startsWith(V+"/"))||ue.some((Z)=>[V,...p.get(V)??[]].some((Ie)=>Ie===Z||Ie.startsWith(Z+"/")));return rt.set(V,ce),ce},Ve=[...p.keys()];for(let V of ve){let te=nt(V);if(te.startsWith("/dev/"))continue;let Q=gp(te);if(Q===null){let Z=ql(te,d);if(Z&&!we.has(Z))we.add(Z),f.push("--ro-bind","/dev/null",Z),v.set(Z,te);C(`[Sandbox Linux] Deny path could not be resolved through symlinks, failing closed: ${te}`);continue}if(Q!==te)C(`[Sandbox Linux] Resolved symlinked deny path: ${te} -> ${Q}`);if(Q.startsWith("/dev/"))continue;if(we.has(Q))continue;we.add(Q);let ue=ql(Q,d);if(ue){if(!we.has(ue))we.add(ue),f.push("--ro-bind","/dev/null",ue),v.set(ue,te);C(`[Sandbox Linux] Mounted /dev/null at symlink ${ue} to prevent symlink replacement attack`);continue}if(!Y.existsSync(Q)){if(cS(Q)){C(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${Q}`);continue}let Z=Ue.dirname(Q);while(Z!=="/"&&!Y.existsSync(Z))Z=Ue.dirname(Z);let Ie=ie(Z)||ie(Q),We=Ve.filter((ae)=>Z===ae||Z.startsWith(ae+"/")),ze=We.length>0&&!We.some(_e);if(Ie&&!ze){let ae=uS(Q),he=up(ae,d)??ae;if(he!==Q){if(!y.has(he)){let De=fp(he,l),Oe=Y.mkdtempSync(Ue.join(bs(),"claude-empty-"));if(Y.chmodSync(Oe,365),Cs.add(Oe),f.push("--ro-bind",Oe,he),v.set(he,te),y.add(he),De.kind==="unregistered")Mi.add(he);Ss(),C(`[Sandbox Linux] Mounted empty dir at ${he} to block creation of ${Q}`)}}else{let De=Hl(he),Oe=mp(Q,te);if(De.kind==="masked")f.push("--ro-bind",Oe,he),v.set(he,te),Ss(),C(`[Sandbox Linux] Masked shared stub at ${he} with ${Oe} to block creation of ${Q}`);else if(De.kind==="real")f.push("--ro-bind",he,he),v.set(he,te);else f.push("--ro-bind",Oe,he),v.set(he,te),Mi.add(he),Ss(),C(`[Sandbox Linux] Mounted ${Oe} at ${he} to block creation of ${Q}`)}}else if(ze)C(`[Sandbox Linux] Skipping non-existent deny path inside a read-only denied directory (already uncreatable): ${Q}`);else C(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${Q}`);continue}if(ie(Q)){if((mS(Q)?Hl(Q):void 0)?.kind==="masked")f.push("--ro-bind",mp(Q,te),Q),Ss();else f.push("--ro-bind",Q,Q);v.set(Q,te)}else C(`[Sandbox Linux] Skipping deny path not within allowed paths: ${Q}`)}}else u.push("--bind","/","/");let x=[],b=(e?.allowWithinDeny||[]).map((O)=>nt(O)),A=new Map,E=[],k=new Set(["proc","dev","sys"]);for(let O of e?.denyOnly||[])if(nt(O)==="/"){for(let K of Y.readdirSync("/"))if(!k.has(K))x.push("/"+K)}else x.push(O);if(e&&Y.existsSync("/etc/ssh/ssh_config.d"))x.push("/etc/ssh/ssh_config.d");let I=x.map((O)=>nt(O)).sort((O,K)=>O.split("/").length-K.split("/").length);for(let O of I){if(!Y.existsSync(O)){C(`[Sandbox Linux] Skipping non-existent read deny path: ${O}`);continue}if(Y.statSync(O).isDirectory())E.push(O),xp(u,O,d,b);else{if(b.includes(O)){C(`[Sandbox Linux] Skipping read deny for re-allowed path: ${O}`);continue}let ie=Gl(O);u.push("--ro-bind","/dev/null",ie),A.set(ie,"/dev/null"),A.set(O,"/dev/null")}}for(let{realPath:O,fakePath:K}of n??[]){let ie=Gl(O);u.push("--ro-bind",K,ie),A.set(ie,K),A.set(O,K)}let R=(O)=>E.some((K)=>{if(!(O===K||O.startsWith(K+"/")))return!1;return!d.some((we)=>(we===K||we.startsWith(K+"/"))&&(O===we||O.startsWith(we+"/")))}),M=[...y].filter((O)=>{let K=v.get(O)??O;return!A.has(O)&&!R(O)&&!R(K)&&!d.some((ie)=>ie===O||ie.startsWith(O+"/"))}),ee=[];for(let O=0;O<f.length;O+=3){let K=f[O+2],ie=v.get(K)??K;if(A.has(K))continue;if(R(K)||R(ie)){C(`[Sandbox Linux] Skipping denyWrite bind already hidden by denyRead tmpfs: ${K}`);continue}if(M.some((ve)=>K.startsWith(ve+"/"))){C(`[Sandbox Linux] Skipping denyWrite bind under an empty-directory mask: ${K}`);continue}if(u.push(f[O],f[O+1],K),ee.push(K),f[O+1]!==K)c.push(K);if(ie!==K)ee.push(ie)}for(let O of E)if(ee.some((K)=>O.startsWith(K+"/")))C(`[Sandbox Linux] Re-applying denyRead tmpfs re-exposed by denyWrite bind: ${O}`),xp(u,O,d,b);for(let[O,K]of A)if(ee.some((ie)=>O.startsWith(ie+"/"))){if(Gl(O)!==O)continue;C(`[Sandbox Linux] Re-applying file mask re-exposed by denyWrite bind: ${O}`),u.push("--ro-bind",K,O)}if(r!==void 0)u.push("--ro-bind",r,r);return u}async function Ep(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpSocketPath:i,socksSocketPath:a,httpProxyPort:s,socksProxyPort:o,proxyAuthToken:l,caCertPath:c,readConfig:u,writeConfig:d,unsetEnvVars:f,setEnvVars:y,maskedFileBinds:p,maskedFileStoreDir:v,enableWeakerNestedSandbox:x,runAsUid:b,runAsGid:A,runAsHostUid:E,runAsHostGid:k,runAsHostHome:I,runAsHostUser:R,setprivPath:M,allowAllUnixSockets:ee,binShell:O,ripgrepConfig:K={command:"rg"},mandatoryDenySearchDepth:ie=zl,allowGitConfig:ve=!1,gitSafeDirectories:we,seccompConfig:rt,bwrapPath:_e,socatPath:Ve,observeSocketPath:V,startFd:te,argvCommand:Q,abortSignal:ue}=e,ce=u&&u.denyOnly.length>0||p!==void 0&&p.length>0,Z=d!==void 0,Ie=f!==void 0&&f.length>0||y!==void 0&&Object.keys(y).length>0,We=(we?.length??0)>0;if(!r&&!ce&&!Z&&!Ie&&!We)return t;Er++;let ze=[],ae=["--new-session","--die-with-parent"],he=[],De;try{if(!ee)if(De=yS(rt?.applyPath,rt?.argv0),!De)throw Error("seccomp_unavailable: the policy requires the unix-socket filter (allowAllUnixSockets is false) but apply-seccomp is not installed beside srt (vendor/seccomp/<arch>/apply-seccomp; build it with `bun run build:seccomp` in packages/sandbox-runtime)");else C("[Sandbox Linux] Applying seccomp filter for Unix socket blocking");else C("[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled");if(V&&De)if(Y.existsSync(V))he.push("--bind",V,V),ae.push("--setenv","SRT_OBSERVE_SOCK",V),ae.push("--setenv","SRT_ENCODED_CMD",Nt(n??t));else C("[Sandbox Linux] observe socket missing \u2014 supervisor not running; "+"continuing without violation monitoring");if(Ie){for(let Ht of f??[])ae.push("--unsetenv",Ht);for(let[Ht,Zr]of Object.entries(y??{}))ae.push("--setenv",Ht,Zr)}if(we&&we.length>0){let Ht=va({safeDirs:we,unsetEnvVars:f,setEnvVars:y});for(let[Zr,pa]of Object.entries(Ht))ae.push("--setenv",Zr,pa)}if(r){if(ae.push("--unshare-net"),i&&a){if(!Y.existsSync(i))throw Error(`Linux HTTP bridge socket does not exist: ${i}. The bridge process may have died. Try reinitializing the sandbox.`);if(!Y.existsSync(a))throw Error(`Linux SOCKS bridge socket does not exist: ${a}. The bridge process may have died. Try reinitializing the sandbox.`);if(he.push("--bind",i,i),a!==i)he.push("--bind",a,a);let Ht=En(3128,1080,c,l,d===void 0,Nt(n??t));if(ae.push(...Ht.flatMap((Zr)=>{let pa=Zr.indexOf("="),jh=Zr.slice(0,pa),zh=Zr.slice(pa+1);return["--setenv",jh,zh]})),s!==void 0)ae.push("--setenv","CLAUDE_CODE_HOST_HTTP_PROXY_PORT",String(s));if(o!==void 0)ae.push("--setenv","CLAUDE_CODE_HOST_SOCKS_PROXY_PORT",String(o))}}let Oe=await xS(u,d,p,v,K,ie,ve,ue,E===void 0?void 0:{uid:E,gid:k??E},ze);xs(),ae.push(...Oe);let at=gS(ze,process.cwd());if(at!==void 0)ae.push("--setenv",pS,at);if(ae.push(...he),ae.push("--dev","/dev"),ae.push("--unshare-pid"),!x){if(ae.push("--unshare-user","--cap-drop","ALL","--proc","/proc"),!De)ae.push("--ro-bind","/dev/null","/proc/sysrq-trigger")}else ae.push("--unshare-user","--bind","/proc","/proc");if(b!==void 0)ae.push("--uid",String(b)),ae.push("--gid",String(A??b));if(E!==void 0){if(I)ae.push("--setenv","HOME",I);if(R)ae.push("--setenv","USER",R),ae.push("--setenv","LOGNAME",R)}let st=O||"bash",Qe=Cr(st);if(!Qe)throw Error(`Shell '${st}' not found in PATH`);if(ae.push("--",Qe,"-c"),r&&i&&a){let Ht=vS(i,a,t,De,Qe,Ve,te,Q);ae.push(Ht)}else if(De){let Ht=De+kt(jl(Qe,t,te));ae.push(Ht)}else ae.push(te===void 0?t:`exec ${kt(jl(Qe,t,te))}`);let ot=[_e??"bwrap",...ae],lt=kt(oS({bwrapCommand:ot,uid:E,gid:k,setprivPath:M,unsetEnvVars:f,setEnvVars:y})),Xe=[];if(r)Xe.push("network");if(ce||Z)Xe.push("filesystem");if(Ie)Xe.push("env");if(De)Xe.push("seccomp(unix-block)");return C(`[Sandbox Linux] Wrapped command with bwrap (${Xe.join(", ")} restrictions)`),lt}catch(Oe){if(Er>0)Er--;if(xs(),Er===0)Kl([],()=>{});throw Oe}}import{spawn as SS}from"child_process";import*as wr from"path";class ws{violations=[];totalCount=0;maxSize=100;listeners=new Set;addViolation(e){if(this.violations.push({...e,line:Ql(e.line).replace(/[<>]/g,"")}),this.totalCount++,this.violations.length>this.maxSize)this.violations=this.violations.slice(-this.maxSize);this.notifyListeners()}getViolations(e){if(e===void 0)return[...this.violations];return this.violations.slice(-e)}getCount(){return this.violations.length}getTotalCount(){return this.totalCount}getViolationsForCommand(e){let t=Nt(e);return this.violations.filter((n)=>n.encodedCommand===t)}clear(){this.violations=[],this.notifyListeners()}subscribe(e){return this.listeners.add(e),e(this.getViolations()),()=>{this.listeners.delete(e)}}notifyListeners(){let e=this.getViolations();this.listeners.forEach((t)=>t(e))}}function zn(e,t,n){if(!n)return!1;if((n["*"]??[]).some((i)=>e.includes(i)))return!0;if(t===void 0)return!1;for(let[i,a]of Object.entries(n))if(i!=="*"&&t.includes(i)&&a.some((s)=>e.includes(s)))return!0;return!1}function Ql(e){return e.replace(/[\x00-\x1f\x7f-\x9f]+/g," ").trim()}function bS(e=!1){let t=process.cwd(),n=[];for(let r of ci)n.push(wr.resolve(t,r)),n.push(`**/${r}`);for(let r of ya())n.push(wr.resolve(t,r)),n.push(`**/${r}/**`);if(n.push(wr.resolve(t,".git/hooks")),n.push("**/.git/hooks/**"),!e)n.push(wr.resolve(t,".git/config")),n.push("**/.git/config");return[...new Set(n)]}var wp=`_${Math.random().toString(36).slice(2,11)}_SBX`;function CS(e){return`CMD64_${Nt(e)}_END_${wp}`}function Qn(e){return xt(e)?`(regex ${Yt(pi(e))})`:`(subpath ${Yt(e)})`}function Zl(e){return pi(e).slice(0,-1)+"(/.*)?$"}function mn(e){return xt(e)?`(regex ${Yt(Zl(e))})`:`(subpath ${Yt(e)})`}function Tp(e){return e.replace(/\[[^\]]*\]|[*?]+/g,"x")}function Yl(e,t){let n=[...new Set(t)];if(n.length===0)return e;let r=n.map((i)=>`(require-not ${i})`).join(" ");return`(require-all ${e} ${r})`}function Xl(e){let t=nt(e);return{path:t,glob:xt(t)}}function Ap(e,t){return e.test(t.glob?Tp(t.path):t.path)}function Ts(e,t){let n=e.glob?Tp(e.path):e.path;return n.startsWith(t==="/"?"/":t+"/")&&n!==t}function ES(e,t){return{denies:(e.denyOnly||[]).map(Xl),allows:(e.allowWithinDeny||[]).map(Xl),writeRoots:(t||[]).map(Xl)}}function wS(e){let t=[],n=!1,r=e.allows.filter((i)=>!i.glob).map((i)=>i.path);for(let i of e.denies){if(!i.glob){if(r.some((o)=>i.path.startsWith(o+"/")))t.push(mn(i.path));continue}let a=new RegExp(Zl(i.path));if(a.test("/"))n=!0;let s=e.allows.filter((o)=>Ap(a,o)).map((o)=>Qn(o.path));t.push(Yl(mn(i.path),s))}return{filters:t,coversRoot:n}}function _p(e){let t=e.split(/[*?[\]]/)[0];if(!t||t==="/")return"/";return t.endsWith("/")?t.slice(0,-1):wr.dirname(t)}function TS(e,t){let{denies:n,allows:r,writeRoots:i}=e;if(i.length===0)return[];let a=i.filter((d)=>d.glob).map((d)=>new RegExp(pi(d.path))),s=i.filter((d)=>!d.glob).map((d)=>d.path),o=(d)=>s.some((f)=>Ts({path:d,glob:!1},f))||a.some((f)=>f.test(d)),l=(d)=>[...r,...i].filter((f)=>Ts(f,d)).map((f)=>Qn(f.path)),c=new Set,u=(d)=>{for(let f of d)if(o(f))c.add(`(literal ${Yt(f)})`)};for(let d of n)if(d.glob){let f=_p(d.path);if(!(a.length>0||s.some((x)=>f===x||Ts({path:f,glob:!1},x)||Ts({path:x,glob:!1},f))))continue;let p=new RegExp(Zl(d.path)),v=[...r,...i].filter((x)=>Ap(p,x)).map((x)=>Qn(x.path));if(c.add(Yl(mn(d.path),v)),f!=="/")u([f,...Jl(f)])}else{if(!o(d.path))continue;c.add(Yl(mn(d.path),l(d.path))),u(Jl(d.path))}return Kr("deny",["file-write-unlink"],c,t)}function Kr(e,t,n,r){if(n.size===0)return[];return[`(${e} ${t.join(" ")}`,...[...n].map((i)=>` ${i}`),` (with message "${r}"))`]}function Jl(e){let t=[],n=wr.dirname(e);while(n!=="/"&&n!=="."){t.push(n);let r=wr.dirname(n);if(r===n)break;n=r}return t}function kp(e,t){let n=new Set;for(let r of e){let i=nt(r);n.add(mn(i));let a;if(xt(i)){if(a=_p(i),a==="/")continue;n.add(`(literal ${Yt(a)})`)}else a=i;for(let s of Jl(a))n.add(`(literal ${Yt(s)})`)}return Kr("deny",["file-write-unlink","file-write-create"],n,t)}function AS(e,t){if(!e)return["(allow file-read*)"];let n=[];n.push("(allow file-read*)");let r=e.denies.some((l)=>l.path==="/"),i=new Set(e.denies.map((l)=>mn(l.path)));n.push(...Kr("deny",["file-read*"],i,t));let a=new Set(e.allows.map((l)=>Qn(l.path)));n.push(...Kr("allow",["file-read*"],a,t));let s=wS(e);if(n.push(...Kr("deny",["file-read*"],new Set(s.filters),t)),r||s.coversRoot)n.push('(allow file-read* (literal "/"))');if(e.denies.length>0)n.push("(allow file-read-metadata"," (vnode-type DIRECTORY))");n.push(...kp(e.denies.map((l)=>l.path),t));let o=new Set(e.writeRoots.map((l)=>Qn(l.path)));return n.push(...Kr("allow",["file-write-unlink","file-write-create"],o,t)),n}function _S(e,t,n=!1){if(!e)return["(allow file-write*)"];let r=[],i=new Set;for(let o of e.allowOnly||[])i.add(Qn(nt(o)));r.push(...Kr("allow",["file-write*"],i,t));let a=[...e.denyWithinAllow||[],...bS(n)],s=new Set;for(let o of a)s.add(mn(nt(o)));return r.push(...Kr("deny",["file-write*"],s,t)),r.push(...kp(a,t)),r}function kS({readConfig:e,writeConfig:t,httpProxyPort:n,socksProxyPort:r,needsNetworkRestriction:i,allowUnixSockets:a,allowAllUnixSockets:s,allowLocalBinding:o,allowMachLookup:l,allowPty:c,allowGitConfig:u=!1,enableWeakerNetworkIsolation:d=!1,allowAppleEvents:f=!1,logTag:y}){let p=["(version 1)",`(deny default (with message "${y}"))`,"",`; LogTag: ${y}`,"","; Essential permissions - based on Chrome sandbox policy","; Process permissions","(allow process-exec)","(allow process-fork)","(allow process-info* (target same-sandbox))","(allow signal (target same-sandbox))","(allow mach-priv-task-port (target same-sandbox))","","; User preferences","(allow user-preference-read)","","; Mach IPC - specific services only (no wildcard)","(allow mach-lookup",' (global-name "com.apple.audio.systemsoundserver")',' (global-name "com.apple.distributed_notifications@Uv3")',' (global-name "com.apple.FontObjectsServer")',' (global-name "com.apple.fonts")',' (global-name "com.apple.logd")',' (global-name "com.apple.lsd.mapdb")',' (global-name "com.apple.PowerManagement.control")',' (global-name "com.apple.system.logger")',' (global-name "com.apple.system.notification_center")',' (global-name "com.apple.system.opendirectoryd.libinfo")',' (global-name "com.apple.system.opendirectoryd.membership")',' (global-name "com.apple.bsd.dirhelper")',' (global-name "com.apple.securityd.xpc")',' (global-name "com.apple.coreservices.launchservicesd")',")","",...d?["; trustd.agent - needed for Go TLS certificate verification (weaker network isolation)",'(allow mach-lookup (global-name "com.apple.trustd.agent"))']:[],...f?["; Apple Events - opt-in; needed for open/osascript to talk to other apps (appleeventsd)","(allow appleevent-send)",'(allow mach-lookup (global-name "com.apple.coreservices.appleevents"))',"; Launch Services open requests need the lsopen operation plus, on","; macOS 14/15, coreservicesd and the quarantine resolver - without","; these open fails with -10822 kLSServerCommunicationErr or -54","(allow lsopen)",'(allow mach-lookup (global-name "com.apple.CoreServices.coreservicesd"))','(allow mach-lookup (global-name "com.apple.coreservices.quarantine-resolver"))']:[],...l&&l.length>0?["; User-specified XPC/Mach services",...l.map((x)=>x.endsWith("*")?`(allow mach-lookup (global-name-prefix ${Yt(x.slice(0,-1))}))`:`(allow mach-lookup (global-name ${Yt(x)}))`)]:[],"","; POSIX IPC - shared memory","(allow ipc-posix-shm)","","; POSIX IPC - semaphores for Python multiprocessing","(allow ipc-posix-sem)","","; IOKit - specific operations only","(allow iokit-open",' (iokit-registry-entry-class "IOSurfaceRootUserClient")',' (iokit-registry-entry-class "RootDomainUserClient")',' (iokit-user-client-class "IOSurfaceSendRight")',")","","; IOKit properties","(allow iokit-get-properties)","","; Specific safe system-sockets, doesn't allow network access","(allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))","","; sysctl - specific sysctls only","(allow sysctl-read",' (sysctl-name "hw.activecpu")',' (sysctl-name "hw.busfrequency_compat")',' (sysctl-name "hw.byteorder")',' (sysctl-name "hw.cacheconfig")',' (sysctl-name "hw.cachelinesize_compat")',' (sysctl-name "hw.cpufamily")',' (sysctl-name "hw.cpufrequency")',' (sysctl-name "hw.cpufrequency_compat")',' (sysctl-name "hw.cputype")',' (sysctl-name "hw.l1dcachesize_compat")',' (sysctl-name "hw.l1icachesize_compat")',' (sysctl-name "hw.l2cachesize_compat")',' (sysctl-name "hw.l3cachesize_compat")',' (sysctl-name "hw.logicalcpu")',' (sysctl-name "hw.logicalcpu_max")',' (sysctl-name "hw.machine")',' (sysctl-name "hw.memsize")',' (sysctl-name "hw.ncpu")',' (sysctl-name "hw.nperflevels")',' (sysctl-name "hw.packages")',' (sysctl-name "hw.pagesize_compat")',' (sysctl-name "hw.pagesize")',' (sysctl-name "hw.physicalcpu")',' (sysctl-name "hw.physicalcpu_max")',' (sysctl-name "hw.tbfrequency_compat")',' (sysctl-name "hw.vectorunit")',' (sysctl-name "kern.argmax")',' (sysctl-name "kern.bootargs")',' (sysctl-name "kern.hostname")',' (sysctl-name "kern.maxfiles")',' (sysctl-name "kern.maxfilesperproc")',' (sysctl-name "kern.maxproc")',' (sysctl-name "kern.ngroups")',' (sysctl-name "kern.osproductversion")',' (sysctl-name "kern.osrelease")',' (sysctl-name "kern.ostype")',' (sysctl-name "kern.osvariant_status")',' (sysctl-name "kern.osversion")',' (sysctl-name "kern.secure_kernel")',' (sysctl-name "kern.tcsm_available")',' (sysctl-name "kern.tcsm_enable")',' (sysctl-name "kern.usrstack64")',' (sysctl-name "kern.version")',' (sysctl-name "kern.willshutdown")',' (sysctl-name "machdep.cpu.brand_string")',' (sysctl-name "machdep.ptrauth_enabled")',' (sysctl-name "security.mac.lockdown_mode_state")',' (sysctl-name "sysctl.proc_cputype")',' (sysctl-name "vm.loadavg")',' (sysctl-name-prefix "hw.optional.arm")',' (sysctl-name-prefix "hw.optional.arm.")',' (sysctl-name-prefix "hw.optional.armv8_")',' (sysctl-name-prefix "hw.perflevel")',' (sysctl-name-prefix "kern.proc.all")',' (sysctl-name-prefix "kern.proc.pgrp.")',' (sysctl-name-prefix "kern.proc.pid.")',' (sysctl-name-prefix "machdep.cpu.")',' (sysctl-name-prefix "net.routetable.")',")","","; V8 thread calculations","(allow sysctl-write",' (sysctl-name "kern.tcsm_enable")',")","","; Distributed notifications","(allow distributed-notification-post)","","; Specific mach-lookup permissions for security operations",'(allow mach-lookup (global-name "com.apple.SecurityServer"))',"","; File I/O on device files",'(allow file-ioctl (literal "/dev/null"))','(allow file-ioctl (literal "/dev/zero"))','(allow file-ioctl (literal "/dev/random"))','(allow file-ioctl (literal "/dev/urandom"))','(allow file-ioctl (literal "/dev/dtracehelper"))','(allow file-ioctl (literal "/dev/tty"))',"","(allow file-ioctl file-read-data file-write-data"," (require-all",' (literal "/dev/null")'," (vnode-type CHARACTER-DEVICE)"," )",")",""];if(p.push("; Network"),!i)p.push("(allow network*)");else{if(o)p.push('(allow network-bind (local ip "*:*"))'),p.push('(allow network-inbound (local ip "*:*"))'),p.push('(allow network-outbound (remote ip "localhost:*"))');if(s)p.push("(allow system-socket (socket-domain AF_UNIX))"),p.push('(allow network-bind (local unix-socket (path-regex #"^/")))'),p.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))');else if(a&&a.length>0){p.push("(allow system-socket (socket-domain AF_UNIX))");for(let x of a){let b=nt(x);p.push(`(allow network-bind (local unix-socket (subpath ${Yt(b)})))`),p.push(`(allow network-outbound (remote unix-socket (subpath ${Yt(b)})))`)}}if(n!==void 0)p.push(`(allow network-bind (local ip "localhost:${n}"))`),p.push(`(allow network-inbound (local ip "localhost:${n}"))`),p.push(`(allow network-outbound (remote ip "localhost:${n}"))`);if(r!==void 0&&r!==n)p.push(`(allow network-bind (local ip "localhost:${r}"))`),p.push(`(allow network-inbound (local ip "localhost:${r}"))`),p.push(`(allow network-outbound (remote ip "localhost:${r}"))`)}p.push("");let v=e?ES(e,t?.allowOnly):void 0;if(p.push("; File read"),p.push(...AS(v,y)),p.push(""),p.push("; File write"),p.push(..._S(t,y,u)),v){let x=TS(v,y);if(x.length>0)p.push(""),p.push("; File read: keep read-denied paths inside write roots in place"),p.push(...x)}if(c)p.push(""),p.push("; Pseudo-terminal (pty) support"),p.push("(allow pseudo-tty)"),p.push("(allow file-ioctl"),p.push(' (literal "/dev/ptmx")'),p.push(' (regex #"^/dev/ttys")'),p.push(")"),p.push("(allow file-read* file-write*"),p.push(' (literal "/dev/ptmx")'),p.push(' (regex #"^/dev/ttys")'),p.push(")");return p.join(`
67
- `)}function Yt(e){return JSON.stringify(e)}function Ip(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpProxyPort:i,socksProxyPort:a,proxyAuthToken:s,caCertPath:o,allowUnixSockets:l,allowAllUnixSockets:c,allowLocalBinding:u,allowMachLookup:d,readConfig:f,writeConfig:y,unsetEnvVars:p,setEnvVars:v,maskedFileBinds:x,allowPty:b,allowGitConfig:A=!1,gitSafeDirectories:E,enableWeakerNetworkIsolation:k=!1,allowAppleEvents:I=!1,binShell:R}=e,M=f;if(x&&x.length>0)C("[Sandbox macOS] file mask degrades to deny on macOS until the interposer lands"),M={denyOnly:[...f?.denyOnly??[],...x.map((ce)=>ce.realPath)],allowWithinDeny:f?.allowWithinDeny};let ee=M&&M.denyOnly.length>0,O=y!==void 0,K=p!==void 0&&p.length>0||v!==void 0&&Object.keys(v).length>0,ie=(E?.length??0)>0;if(!r&&!ee&&!O&&!K&&!ie)return t;let ve=n??t,we=CS(ve),rt=kS({readConfig:M,writeConfig:y,httpProxyPort:i,socksProxyPort:a,needsNetworkRestriction:r,allowUnixSockets:l,allowAllUnixSockets:c,allowLocalBinding:u,allowMachLookup:d,allowPty:b,allowGitConfig:A,enableWeakerNetworkIsolation:k,allowAppleEvents:I,logTag:we}),_e=En(i,a,o,s,y===void 0,Nt(ve));if(u&&r){let Ie=(p??[]).includes("JAVA_TOOL_OPTIONS")?"":process.env.JAVA_TOOL_OPTIONS??"",We=Ie.includes("-Djava.net.preferIPv4Stack=true")?Ie:[Ie,"-Djava.net.preferIPv4Stack=true"].filter(Boolean).join(" ");_e.push(`JAVA_TOOL_OPTIONS=${We}`)}if(E&&E.length>0){let ce=va({safeDirs:E,unsetEnvVars:p,setEnvVars:v});for(let[Z,Ie]of Object.entries(ce))_e.push(`${Z}=${Ie}`)}let Ve=R||"bash",V=Cr(Ve);if(!V)throw Error(`Shell '${Ve}' not found in PATH`);let te=(p??[]).flatMap((ce)=>["-u",ce]),Q=Object.entries(v??{}).map(([ce,Z])=>`${ce}=${Z}`),ue=kt(["env",...te,...Q,..._e,"/usr/bin/sandbox-exec","-p",rt,V,"-c",t]);return C(`[Sandbox macOS] Applied restrictions - network: ${!!(i||a)}, read: ${M?"allowAllExcept"in M?"allowAllExcept":"denyAllExcept":"none"}, write: ${y?"allowAllExcept"in y?"allowAllExcept":"denyAllExcept":"none"}`),ue}function Rp(e,t,n=(r)=>r){let r=/CMD64_(.+?)_END/,i=/Sandbox:\s+(.+)$/,a=SS("log",["stream","--predicate",`(eventMessage ENDSWITH "${wp}")`,"--style","compact"]);return a.stdout?.on("data",(s)=>{let o=s.toString().split(`
68
- `),l=o.find((p)=>p.includes("Sandbox:")&&p.includes("deny")),c=o.find((p)=>p.startsWith("CMD64_"));if(!l)return;let u=l.match(i);if(!u?.[1])return;let d=u[1],f,y;if(c){if(y=c.match(r)?.[1],y)try{f=n(tn(y))}catch{}}if(d.includes("mDNSResponder")||d.includes("mach-lookup com.apple.diagnosticd")||d.includes("mach-lookup com.apple.analyticsd"))return;if(zn(d,f,t))return;e({line:d,command:f,encodedCommand:y,timestamp:new Date})}),a.stderr?.on("data",(s)=>{C(`[Sandbox Monitor] Log stream stderr: ${s.toString()}`)}),a.on("error",(s)=>{C(`[Sandbox Monitor] Failed to start log stream: ${s.message}`)}),a.on("exit",(s)=>{C(`[Sandbox Monitor] Log stream exited with code: ${s}`)}),()=>{C("[Sandbox Monitor] Stopping log monitor"),a.kill("SIGTERM")}}import{randomBytes as IS}from"crypto";import{chmodSync as Bp,chownSync as RS,mkdtempSync as BS,rmSync as PS}from"fs";import{createServer as NS}from"net";import{tmpdir as DS}from"os";import{join as Pp,posix as LS}from"path";import{createInterface as OS}from"readline";function Np(e,t){let{allowWritePaths:n,denyWritePaths:r,ignoreViolations:i,resolveCommandText:a=(E)=>E,consumerUid:s,consumerGid:o}=t,l=BS(Pp(DS(),"srt-obs-")),c=Pp(l,`s${IS(4).toString("hex")}.sock`),u=(E,k)=>E===k||E.startsWith(k.endsWith("/")?k:k+"/"),d=(E)=>{let k=LS.normalize(E);if(r.some((I)=>u(k,I)))return!0;return!n.some((I)=>u(k,I))},f=(E,k)=>{if(E.observe_init_error){C(`[Sandbox Linux Monitor] observe filter not installed: ${E.observe_init_error}`);return}if(typeof E.path!=="string")return;if(!E.path.startsWith("/"))return;if(!d(E.path))return;let I;if(k)try{I=a(tn(k))}catch{}if(zn(E.path,I,i))return;let R={line:`deny ${E.syscall??"syscall"} ${E.path}`,command:I,encodedCommand:k,timestamp:new Date};e(R)},y,p=new Promise((E)=>{y=E}),v=c,x=NS((E)=>{let k,I=OS({input:E});I.on("line",(R)=>{if(!R)return;let M;try{M=JSON.parse(R)}catch{return}if(M.encodedCommand&&k===void 0)k=M.encodedCommand;f(M,k??M.encodedCommand)}),E.on("error",()=>I.close()),E.on("close",()=>I.close())});x.on("error",(E)=>{C(`[Sandbox Linux Monitor] listen failed: ${E.message} - violation monitoring disabled`,{level:"warn"}),v=void 0,y()}),x.listen(c,()=>{if(s!==void 0)Bp(l,457),RS(c,s,o??s),Bp(c,384);y()});let b=new Set;return x.on("connection",(E)=>{b.add(E),E.on("close",()=>b.delete(E))}),{get observeSocketPath(){return v},ready:p,stop:()=>{C("[Sandbox Linux Monitor] stopping");for(let E of b)E.destroy();x.close();try{PS(l,{recursive:!0,force:!0})}catch{}}}}import*as tt from"fs";import*as Op from"net";import*as et from"path";import{spawn as US,spawnSync as VS}from"child_process";import{once as FS}from"events";import{fileURLToPath as MS}from"url";class xe extends Error{code;subcommand;constructor(e,t,n){super(t);this.name="WindowsSandboxError",this.code=e,this.subcommand=n}}var As=[60080,60089],Dp=["-NoProfile","-Command"];function _s(e){let t=process.env.SystemRoot??"C:\\Windows",n={exe:et.win32.join(t,"System32","cmd.exe"),args:["/d","/s","/c"]};if(e===void 0||e===null)return n;if(typeof e==="object"){if(!et.win32.isAbsolute(e.exe))throw new xe("bin_shell_invalid",`binShell.exe must be an absolute path (got ${JSON.stringify(e.exe)})`);if(!Array.isArray(e.args))throw new xe("bin_shell_invalid",`binShell.args must be an array (got ${JSON.stringify(e.args)})`);return e}let r=et.win32.basename(e),i=r.toLowerCase(),a=et.win32.isAbsolute(e);if(!a&&e!==r)throw new xe("bin_shell_invalid",`binShell string must be a bare token or an absolute path (got ${JSON.stringify(e)})`);switch(i){case"bash":case"bash.exe":case"sh":case"sh.exe":if(!a)throw new xe("bin_shell_invalid",`binShell bash path must be absolute (got ${JSON.stringify(e)}); pass the resolved Git Bash install path`);return{exe:e,args:["-c"]};case"pwsh":case"pwsh.exe":return{exe:a?e:"pwsh.exe",args:Dp};case"powershell":case"powershell.exe":return{exe:a?e:et.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),args:Dp};case"cmd":case"cmd.exe":return a?{exe:e,args:n.args}:n;default:throw new xe("bin_shell_invalid",`unrecognised binShell ${JSON.stringify(e)}: expected 'cmd' | 'powershell' | 'pwsh' or an absolute path to bash.exe/sh.exe/pwsh.exe/powershell.exe`)}}function Up(){let e=et.dirname(MS(import.meta.url));return et.resolve(e,"..","..")}var Vp={x64:"x64",arm64:"arm64"},WS=et.join(Up(),"vendor","srt-win",Vp[process.arch]??process.arch,"srt-win.exe");function $S(){let e=Up(),t=Vp[process.arch],n=[];if(t)n.push(et.join(e,"vendor","srt-win",t,"srt-win.exe"));n.push(et.join(e,"vendor","srt-win-src","target","release","srt-win.exe"));for(let r of n)if(tt.existsSync(r))return r;throw new xe("srt_win_not_found",`srt-win.exe not found. Set windows.srtWin.path or build with \`cargo build --release --manifest-path vendor/srt-win-src/Cargo.toml\`. Looked in: ${n.join(", ")}`)}var Fp="--srt-win";function Bt(e){if(e?.path===void 0)throw new xe("srt_win_not_found","no srt-win path configured; set windows.srtWin.path (e.g. to the exported VENDORED_SRT_WIN_EXE constant for the packaged binary)");if(!tt.existsSync(e.path))throw new xe("srt_win_not_found",`windows.srtWin.path is set to '${e.path}' but the file does not exist`);return{exe:e.path,prependArgs:[Fp]}}function qr(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Bt(),i=VS(n,[...r,...e],{encoding:"utf8",windowsHide:!0,timeout:t.timeoutMs??15000,...t.stdin!==void 0?{input:t.stdin}:{}});if(i.error){if(i.error.code==="ETIMEDOUT")throw new xe("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${t.timeoutMs??15000}ms`+(i.signal?` (killed by ${i.signal})`:""),e[0]);throw new xe("spawn_failed",`srt-win ${e[0]}: spawn failed: ${i.error.message}`,e[0])}return{status:i.status,signal:i.signal,stdout:(i.stdout??"").trim(),stderr:(i.stderr??"").trim()}}function tc(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Bt(),i=t.timeoutMs??15000;return new Promise((a,s)=>{let o=US(n,[...r,...e],{windowsHide:!0}),l=!1,c=i>0?setTimeout(()=>{l=!0,o.kill()},i):void 0,u="",d="";o.stdout?.setEncoding("utf8").on("data",(f)=>u+=f),o.stderr?.setEncoding("utf8").on("data",(f)=>d+=f),o.stdin?.on("error",()=>{}).end(t.stdin),o.once("error",(f)=>{clearTimeout(c),s(new xe("spawn_failed",`srt-win ${e[0]}: spawn failed: ${f.message}`,e[0]))}),o.once("close",(f,y)=>{if(clearTimeout(c),l){s(new xe("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${i}ms`+(y?` (killed by ${y})`:""),e[0]));return}a({status:f,signal:y,stdout:u.trim(),stderr:d.trim()})})})}function Mp(e,t){if(t.status!==0)throw new xe("srt_win_nonzero",`srt-win ${e.join(" ")} exited ${t.status}: ${t.stderr||t.stdout}`,e[0]);try{return JSON.parse(t.stdout)}catch(n){throw new xe("srt_win_bad_json",`srt-win ${e.join(" ")}: unparseable JSON output ${JSON.stringify(t.stdout)}: ${n.message}`,e[0])}}function rc(e,t){return Mp(e,qr(e,t))}async function nc(e,t){return Mp(e,await tc(e,t))}function Wp(e,t){let n=qr(e,t),r;try{r=JSON.parse(n.stdout)}catch(i){throw new xe("srt_win_bad_json",`srt-win ${e.join(" ")}: unparseable JSON output ${JSON.stringify(n.stdout)}: ${i.message}`,e[0])}return{ok:n.status===0,json:r,stderr:n.stderr}}function $p(e){let t=["wfp","status"];if(e)t.push("--sublayer-guid",e);return t}function ks(e){return{state:e.state,filters:e.filters,...e.port_range&&{portRange:e.port_range},...e.user_sid&&{userSid:e.user_sid},...e.hint&&{hint:e.hint}}}function Is(e){return{provisioned:e.user.exists,...e.user.sid&&{sid:e.user.sid},groupExists:e.user.group_exists,...e.user.group_sid&&{groupSid:e.user.group_sid},inBuiltinUsers:e.user.in_builtin_users,inSandboxGroup:e.user.in_sandbox_group,hiddenFromLogon:e.user.hidden_from_logon,credPresent:e.cred_present,...typeof e.marker_version==="number"&&{markerVersion:e.marker_version},realUserSid:e.real_user_sid,...e.ca_cert_thumb&&{caCertThumb:e.ca_cert_thumb},...e.ca_cert_pem&&{caCertPem:e.ca_cert_pem}}}function Hp(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=rc(t,{srtWin:e.srtWin});return{user:Is(n.user),wfp:ks(n.wfp)}}async function Kp(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=await nc(t,{srtWin:e.srtWin});return{user:Is(n.user),wfp:ks(n.wfp)}}function qp(e={}){return ks(rc($p(e.sublayerGuid),{srtWin:e.srtWin}))}async function Gp(e={}){return ks(await nc($p(e.sublayerGuid),{srtWin:e.srtWin}))}async function ic(e={}){let t=e.target,n;if(!t){let[r,i]=e.proxyPortRange??As;for(let a=0;a<5;a++){let s=Op.createServer();s.listen(0,"127.0.0.1"),await FS(s,"listening");let o=s.address().port;if(o<r||o>i){n=s,t=`127.0.0.1:${o}`;break}s.close()}if(!t)throw new xe("wfp_verify_bind_failed",`verifyWindowsWfpEgress: could not bind a loopback listener outside the WFP permit range [${r},${i}] in 5 attempts`)}try{let r=qr(["wfp","verify","--target",t],{timeoutMs:30000,srtWin:e.srtWin});C(`[Sandbox Windows] wfp verify exit=${r.status}: ${r.stderr||r.stdout}`);let i;try{i=JSON.parse(r.stdout)}catch{throw new xe("wfp_verify_unparseable","WFP egress fence could not be verified \u2014 `srt-win wfp "+`verify\` exited ${r.status}`+(r.signal?` (signal ${r.signal})`:"")+` with unparseable output ${JSON.stringify(r.stdout)} (stderr: ${JSON.stringify(r.stderr)})`)}if(r.status===3)throw new xe("wfp_fence_inactive","WFP egress fence is not active \u2014 direct outbound from the "+`sandbox user to ${i.target} succeeded. Re-run \`srt-win install\` (one UAC prompt). (${r.stderr})`);if(r.status!==0)throw new xe("wfp_verify_inconclusive","WFP egress fence could not be verified \u2014 probe to "+`${i.target} was '${i.egress_probe}' (exit ${r.status}). The fence may be absent. Re-run \`srt-win install\`. (${r.stderr})`);return{target:i.target,stderr:r.stderr}}finally{n?.close()}}function ac(e={}){return Is(rc(["user","status"],{srtWin:e.srtWin}))}async function Wi(e={}){return Is(await nc(["user","status"],{srtWin:e.srtWin}))}function sc(e,t={}){let n=e??ac(t);if(!n.caCertThumb||!n.caCertPem)return null;return{pem:n.caCertPem,thumb:n.caCertThumb}}function HS(e,t={}){let n=qr(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});zp(e,n)}async function jp(e,t={}){let n=await tc(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});zp(e,n)}function zp(e,t){if(C(`[Sandbox Windows] user trust-ca exit=${t.status}: ${t.stderr||t.stdout}`),t.status!==0)throw new xe("trust_ca_failed",`srt-win user trust-ca '${e}' failed (exit ${t.status}): ${t.stderr||t.stdout}`)}function Qp(){let e=process.env.ProgramData;if(!e)throw Error("ProgramData is not set");return et.win32.join(e,"sandbox-runtime")}async function oc(e={}){let t=e.status??await Wi({srtWin:e.srtWin});if(!t.provisioned||!t.credPresent)throw Error(`ensurePersistentWindowsCa: sandbox user is not provisioned (user=${t.provisioned}, cred=${t.credPresent}). Run \`npx sandbox-runtime windows-install\` first.`);let n=e.dir?void 0:Qp();if(n&&!tt.existsSync(n))throw Error(`ensurePersistentWindowsCa: state directory ${n} does not exist. Run \`npx sandbox-runtime windows-install\` first.`);let r=e.dir??et.win32.join(n,"ca"),i=et.join(r,"ca.json"),a=et.join(r,"cert.pem"),s=et.join(r,"key.pem"),o=(e.regenerateWithinDays??30)*24*60*60*1000,l=(x,b)=>{let A=`${x}.tmp.${process.pid}`;tt.writeFileSync(A,b),tt.renameSync(A,x)},c=async(x,b,A,E)=>{l(a,x),l(s,b);let k=E||t.caCertThumb!==A;if(k){let I=et.join(r,`.trust.${process.pid}.${Date.now()}.pem`);tt.writeFileSync(I,x);try{await jp(I,{srtWin:e.srtWin})}finally{tt.rmSync(I,{force:!0})}}return C(`[Sandbox Windows] persistent CA ${E?"generated":"reused"} (thumb=${A}${k&&!E?", trust reconciled":""})`),{certPem:x,keyPem:b,certPath:a,keyPath:s,thumbprint:A,generated:E,trusted:k}},u=()=>{let x;try{x=JSON.parse(tt.readFileSync(i,"utf8"))}catch(A){C(`[Sandbox Windows] persistent CA ca.json unreadable (${A.message})`,{level:"warn"});return}if(typeof x.certPem!=="string"||typeof x.keyPem!=="string")return;let b=Ri(x.certPem,x.keyPem);if(!b.ok){C(`[Sandbox Windows] persistent CA invalid (${b.reason})`,{level:"warn"});return}return{certPem:x.certPem,keyPem:x.keyPem,thumbprint:b.thumbprint,notAfter:b.notAfter}};if(!e.force){let x=u();if(x&&x.notAfter.getTime()-Date.now()>o)return await c(x.certPem,x.keyPem,x.thumbprint,!1);if(x)C(`[Sandbox Windows] persistent CA expiring ${x.notAfter.toISOString()}; regenerating`,{level:"warn"})}tt.mkdirSync(r,{recursive:!0});try{let x=Date.now()-300000;for(let b of tt.readdirSync(r)){if(!b.includes(".tmp.")&&!b.startsWith(".trust."))continue;let A=et.join(r,b);if(tt.statSync(A).mtimeMs<x)tt.rmSync(A,{force:!0})}}catch{}let d=es({cn:"sandbox-runtime persistent CA"});l(i,JSON.stringify({certPem:d.certPem,keyPem:d.keyPem}));let f=u(),{certPem:y,keyPem:p,thumbprint:v}=f??{certPem:d.certPem,keyPem:d.keyPem,thumbprint:$n(d.certPem)};return await c(y,p,v,!0)}function lc(e){return e.timeoutMs??120000}function Xp(e){let t=["install"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);if(e.proxyPortRange)t.push("--proxy-port-range",`${e.proxyPortRange[0]}-${e.proxyPortRange[1]}`);if(e.sandboxUser)t.push("--sandbox-user",e.sandboxUser);if(e.force)t.push("--force");return t}function Yp(e){if(e instanceof xe&&e.code==="srt_win_timeout")throw new xe("install_timeout","srt-win install timed out \u2014 the UAC prompt may still be open. "+`Re-run when ready to grant elevation. (${e.message})`);throw e}function Jp(e){if(C(`[Sandbox Windows] install exit=${e.status}: ${e.stderr||e.stdout}`),e.status===0||e.status===10)return;let t=e.stderr||e.stdout;switch(e.status){case 12:throw new xe("install_wfp_failed",`srt-win install: WFP filter install failed: ${t}`);case 14:throw new xe("install_user_failed",`srt-win install: sandbox user provisioning failed: ${t}`);case 13:throw new xe("install_config_conflict",`srt-win install: filters already exist under this sublayer with a different port range or sandbox-user name. Pass {force: true} to replace, or pick a different sublayerGuid. Output: ${t}`);case 17:throw new xe("install_ambient_failed",`srt-win install: ambient write-deny stamping failed (stock world-writable system dirs could not be deny-stamped for the sandbox user): ${t}`);default:throw new xe("install_failed",`srt-win install failed (exit ${e.status}): ${t}`)}}function KS(e={}){let t=e.srtWin??Bt(),n;try{n=qr(Xp(e),{timeoutMs:lc(e),srtWin:t})}catch(i){Yp(i)}Jp(n);let r=Hp({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}async function qS(e={}){let t=e.srtWin??Bt(),n;try{n=await tc(Xp(e),{timeoutMs:lc(e),srtWin:t})}catch(i){Yp(i)}Jp(n);let r=await Kp({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}function GS(e={}){let t=["uninstall"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);if(e.keepUser)t.push("--keep-user");let n=qr(t,{timeoutMs:lc(e),srtWin:e.srtWin});if(C(`[Sandbox Windows] uninstall exit=${n.status}: ${n.stderr||n.stdout}`),n.status===10)return{cancelled:!0};if(n.status!==0)throw new xe("uninstall_failed",`srt-win uninstall failed (exit ${n.status}): ${n.stderr||n.stdout}`);return{}}function Rs(e,t){let n=new Set;for(let r of e){let i=nt(r),a=ui(i);if(di(i)&&!a){n.add(i);continue}let s=a?rn(i,{caseInsensitive:!0}):[i];for(let o of s){if(!tt.statSync(o,{throwIfNoEntry:!1})){if(t?.mode==="deny"&&!a)n.add(/[\\/]$/.test(r)&&!/[\\/]$/.test(o)?o+"\\":o);continue}n.add(o)}}return[...n]}function jS(e){for(let t of e.split(/\r?\n/)){let n=t.trim();if(!n.startsWith("{")||!n.includes('"code"'))continue;try{let r=JSON.parse(n);if(r.code==="mapped_drive_cwd")return Object.assign(new xe("mapped_drive_cwd",r.message??"mapped/network-drive working directory","exec"),{drive:r.drive})}catch{}}return}function cc(e){let t=e.holderPid??process.pid,n=JSON.stringify({denyRead:e.denyRead,denyWrite:e.denyWrite}),r=qr(["acl","stamp","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid],{timeoutMs:60000,stdin:n,srtWin:e.srtWin});if(C(`[Sandbox Windows] acl stamp exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new xe("acl_stamp_failed",`srt-win acl stamp exited ${r.status} `+(r.status===2?"(partial \u2014 some inputs skipped)":"(failed)")+`: ${r.stderr||r.stdout}`)}function Bs(e){let t=e.holderPid??process.pid;try{let n=Wp(["acl","restore","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:e.srtWin});if(!n.ok)C(`[Sandbox Windows] acl restore exited non-zero (per-path outcomes preserved): ${n.stderr}`,{level:"error"});return Array.isArray(n.json)?n.json:[...n.json.paths??[],...n.json.parents??[]]}catch(n){C(`[Sandbox Windows] acl restore: ${n.message}`,{level:"error"});return}}function uc(e){let t=e.holderPid??process.pid,n=JSON.stringify({read:e.read,write:e.write}),r=qr(["acl","grant","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid],{timeoutMs:60000,stdin:n,srtWin:e.srtWin});if(C(`[Sandbox Windows] acl grant exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new xe("acl_grant_failed",`srt-win acl grant exited ${r.status}: ${r.stderr||r.stdout}`)}function Ps(e){let t=e.holderPid??process.pid;try{let n=Wp(["acl","revoke","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:e.srtWin});if(!n.ok)C(`[Sandbox Windows] acl revoke exited non-zero: ${n.stderr}`,{level:"error"});return n.json}catch(n){C(`[Sandbox Windows] acl revoke: ${n.message}`,{level:"error"});return}}function Zp(e){let{exe:t,prependArgs:n}=e.srtWin??Bt(),r=zS(En(e.httpProxyPort,e.socksProxyPort,e.caCertPath?.replace(/\\/g,"/"),e.proxyAuthToken,void 0,Nt(e.commandId??e.command)));delete r.TMPDIR,delete r.NO_PROXY,delete r.no_proxy;let i=fi({safeDirs:[e.cwd??process.cwd(),...e.allowWrite??[],...e.gitSafeDirectories??[]],schannelCa:e.caCertPath!==void 0,baseEnv:e.setEnvVars}),a=[t,...n,"exec"];if(e.quiet!==!1)a.push("--quiet");for(let u of e.denyRead??[])a.push("--deny-read",u);for(let u of e.denyWrite??[])a.push("--deny-write",u);let s={PATH:process.env.PATH,PATHEXT:process.env.PATHEXT,...e.setEnvVars??{},...r,...i};for(let[u,d]of Object.entries(s))if(d!==void 0)a.push("--env",`${u}=${d}`);a.push("--");let o=e.binShell??_s(void 0);a.push(o.exe,...o.args,e.command);let l=a.reduce((u,d)=>u+d.length+3,0);if(l>30000)throw new xe("argv_too_long",`Windows sandbox argv is ~${l} chars (CreateProcessW limit is 32 767).`);let c={...process.env,...r};return{argv:a,env:c}}function zS(e){let t={};for(let n of e){let r=n.indexOf("=");if(r===-1)continue;t[n.slice(0,r)]=n.slice(r+1)}return t}function ec(e){let t=e?` --sublayer-guid ${e}`:"";return`Windows sandbox needs a one-time install (one UAC prompt):
60
+ mux backend dial failed (${q})
61
+ `)}),M.on("error",()=>O.destroy()),M.once("close",()=>O.destroy()),O.once("close",()=>M.destroy()),M.pipe(O),O.pipe(M)}let U=HH((M)=>{G.add(M),M.once("close",()=>G.delete(M)),M.on("error",(V)=>Z(`mux: client socket error: ${V.message}`));let O=setTimeout(()=>{Z("mux: first-byte timeout; destroying connection"),M.destroy()},J);if(typeof O.unref==="function")O.unref();M.once("readable",()=>{clearTimeout(O);let V=M.read(1);if(!V||V.length===0){M.destroy();return}if(M.unshift(V),EH.has(V[0]))$.handleSocksConnection(M);else W(M)})});return{server:U,getPort(){let M=U.address();return M&&typeof M==="object"?M.port:void 0},async listenHttpBackend(){if(!X){let O=LH();await S4(O).catch(()=>{}),await new Promise((V,q)=>{$.httpServer.once("error",q),$.httpServer.listen(O,()=>{$.httpServer.removeListener("error",q),V()})}),Q=O,Z(`mux: HTTP backend listening on ${O}`);return}await q9($.httpServer,(O)=>$.httpServer.listen(O,"127.0.0.1"),$.httpBackendPortRange,new Set);let M=$.httpServer.address();return Y=M&&typeof M==="object"?M.port:void 0,Z(`mux: HTTP backend listening on 127.0.0.1:${Y}`),Y},async close(){for(let M of G)M.destroy();if(G.clear(),await new Promise((M)=>U.close(()=>M())),await new Promise((M)=>$.httpServer.close(()=>M())),Q)await S4(Q).catch(()=>{}),Q=void 0;Y=void 0},unref(){U.unref(),$.httpServer.unref()}}}import{randomBytes as AH,randomUUID as RH}from"crypto";var nQ="fake_value_",C4="abcdefghijklmnopqrstuvwxyz0123456789_-";function DH($){let J=nQ+RH(),X=Buffer.byteLength($)-J.length;if(X<=0)return J;let Q=J;for(let Y of AH(X))Q+=C4[Y%C4.length];return Q}class T7{byName=new Map;bySentinel=new Map;allSentinelsPrefixed=!0;refs=new Map;lease=null;register($,J,X,Q){return this.registerWithSentinel($,DH(J),J,X,Q)}registerWithSentinel($,J,X,Q,Y){let G=this.byName.get($);if(G!==void 0&&G.realValue===X)return G.injectHosts=Q,G.injectHeaders=Y,this.lease?.add(G),G.sentinel;if(this.bySentinel.has(J))throw Error("credential sentinel collision");if(!J.startsWith(nQ))this.allSentinelsPrefixed=!1;let W={name:$,sentinel:J,realValue:X,injectHosts:Q,injectHeaders:Y};return this.byName.set($,W),this.bySentinel.set(J,W),this.lease?.add(W),J}beginLease(){this.lease=new Set}endLease(){let $=[...this.lease??[]];this.lease=null;for(let J of $)this.refs.set(J,(this.refs.get(J)??0)+1);return{entries:$}}release($){let J=[];for(let X of $.entries){let Q=(this.refs.get(X)??1)-1;if(Q>0){this.refs.set(X,Q);continue}if(this.refs.delete(X),this.bySentinel.get(X.sentinel)===X)this.bySentinel.delete(X.sentinel);if(this.byName.get(X.name)===X)this.byName.delete(X.name);J.push(X.sentinel)}if($.entries.length=0,J.length>0&&!this.allSentinelsPrefixed)this.allSentinelsPrefixed=[...this.bySentinel.keys()].every((X)=>X.startsWith(nQ));return J}lookupReal($){return this.bySentinel.get($)?.realValue}namesInjectableAt($,J){let X=[];for(let Q of this.byName.values())if(Q.injectHosts.some((Y)=>J($,Y)))X.push(Q.name);return X}sentinelsForHost($,J){let X=[];for(let Q of this.bySentinel.values()){if(!Q.injectHosts.some((Y)=>J($,Y)))continue;if(Q.injectHeaders!==void 0)continue;X.push({sentinel:Buffer.from(Q.sentinel),realValue:Buffer.from(Q.realValue)})}return X}*entries(){for(let $ of this.bySentinel.values())yield[$.sentinel,$.realValue]}get size(){return this.bySentinel.size}clear(){this.byName.clear(),this.bySentinel.clear(),this.refs.clear(),this.lease=null,this.allSentinelsPrefixed=!0}substituteInHeaders($,J,X){if(this.bySentinel.size===0)return;for(let[Q,Y]of Object.entries($)){if(Y===void 0)continue;if(Array.isArray(Y))for(let G=0;G<Y.length;G++)Y[G]=this.substituteInHeaderValue(Q,Y[G],J,X);else $[Q]=this.substituteInHeaderValue(Q,Y,J,X)}}substituteInHeaderValue($,J,X,Q){let Y=$.toLowerCase(),G=this.substituteInString(J,X,Q,Y);if(Y!=="authorization")return G;let W=/^(\s*basic\s+)([a-z0-9+/]+={0,2})(\s*)$/i.exec(G);if(W===null)return G;let U=W[2],M=Buffer.from(U,"base64");if(U.length%4!==0||M.toString("base64")!==U)return G;let O=M.toString("utf8");if(!Buffer.from(O,"utf8").equals(M))return G;let V=this.substituteInString(O,X,Q,Y);if(V===O)return G;return`${W[1]}${Buffer.from(V,"utf8").toString("base64")}${W[3]}`}substituteInString($,J,X,Q){if(this.allSentinelsPrefixed&&!$.includes(nQ))return $;let Y=$;for(let G of this.bySentinel.values()){if(!Y.includes(G.sentinel))continue;if(!G.injectHosts.some((W)=>X(J,W)))continue;if(G.injectHeaders!==void 0&&!G.injectHeaders.includes(Q))continue;Y=Y.split(G.sentinel).join(G.realValue)}return Y}}import{randomUUID as wH}from"crypto";import*as nJ from"fs";import{tmpdir as PH}from"os";import{join as x4}from"path";function ZH($,J){let X=!1;for(let Q=J+1;Q<$.length;Q++){let Y=$[Q];if(X){X=!1;continue}if(Y==="\\")X=!0;else if(Y==="]")return Q+1}return $.length}function BH($){switch($){case"s":return{kind:"whitespace"};case"S":return{kind:"non-whitespace"};case"d":return{kind:"digit"};case"D":return{kind:"non-digit"};case"w":return{kind:"word"};case"W":return{kind:"non-word"};default:return{kind:"unknown"}}}function w4($,J){if($===null||J===null)return!0;if($.kind==="literal"&&J.kind==="literal")return $.value===J.value;if($.kind==="whitespace"&&J.kind==="non-whitespace"||$.kind==="non-whitespace"&&J.kind==="whitespace"||$.kind==="digit"&&J.kind==="non-digit"||$.kind==="non-digit"&&J.kind==="digit"||$.kind==="word"&&J.kind==="non-word"||$.kind==="non-word"&&J.kind==="word")return!1;return!0}function jH($,J){if($[J+1]!=="?")return{next:J+1,capturing:!0};if($[J+2]==="<"){let Q=$[J+3];if(Q==="="||Q==="!")return{next:J+4,capturing:!1};let Y=$.indexOf(">",J+3);return{next:Y===-1?J+3:Y+1,capturing:!0}}return{next:J+3,capturing:!1}}function TH($,J){let X=$[J];if(X==="*"||X==="+")return{next:$[J+1]==="?"?J+2:J+1,unbounded:!0};if(X==="?")return{next:$[J+1]==="?"?J+2:J+1,unbounded:!1};if(X!=="{")return null;let Q=J+1,Y=Q;while(/[0-9]/.test($[Q]??""))Q++;if(Q===Y)return null;let G=Number($.slice(Y,Q)),W=G,U=!1;if($[Q]===","){Q++;let M=Q;while(/[0-9]/.test($[Q]??""))Q++;if(Q===M)U=!0,W=void 0;else W=Number($.slice(M,Q))}if($[Q]!=="}")return null;if(!Number.isFinite(G)||G>4096||W!==void 0&&(!Number.isFinite(W)||W>4096))return{next:Q+1,unbounded:U,error:"finite repetitions must be at most 4096"};if(Q++,$[Q]==="?")Q++;return{next:Q,unbounded:U}}function SH($){let J=[{previousAtom:null,lastAtom:null,atomCount:0,simpleClass:null,containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1}],X=0,Q=()=>J[J.length-1],Y=(G)=>{let W=Q();if(W.lastAtom?.hasUnboundedQuantifier&&G.hasUnboundedQuantifier&&W.lastAtom.repeatClass!==null&&G.repeatClass!==null&&w4(W.lastAtom.repeatClass,G.repeatClass))W.error="adjacent unbounded repetition with overlapping input is not supported";if(W.previousAtom=W.lastAtom,W.lastAtom=G,W.atomCount===0)W.simpleClass=G.repeatClass;else W.simpleClass=null;if(W.atomCount++,G.kind==="group")W.containsQuantifier||=G.containsQuantifier,W.containsAlternation||=G.containsAlternation;W.hasUnboundedQuantifier||=G.hasUnboundedQuantifier};for(let G=0;G<$.length;){if(Q().error!==void 0)return{groupCount:X,error:Q().error};let W=$[G];if(W==="\\"){let M=$[G+1];if(M!==void 0&&/[1-9]/.test(M)||M==="k"&&$[G+2]==="<")return{groupCount:X,error:"backreferences are not supported by the safe extractor"};let O=M==="b"||M==="B";if(Y({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:BH(M)}),G+=M===void 0?1:2,O)Q().previousAtom=null,Q().lastAtom=null;continue}if(W==="["){Y({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:{kind:"unknown"}}),G=ZH($,G);continue}if(W==="("){let M=jH($,G);if(M.capturing)X++;J.push({previousAtom:null,lastAtom:null,atomCount:0,simpleClass:null,containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1}),G=M.next;continue}if(W===")"){if(J.length>1){let M=J.pop();if(M.error!==void 0)return{groupCount:X,error:M.error};Y({kind:"group",containsQuantifier:M.containsQuantifier,containsAlternation:M.containsAlternation,hasUnboundedQuantifier:M.hasUnboundedQuantifier,repeatClass:M.atomCount===1&&!M.containsAlternation?M.simpleClass:null})}G++;continue}if(W==="|"){Q().containsAlternation=!0,Q().previousAtom=null,Q().lastAtom=null,G++;continue}let U=TH($,G);if(U!==null){if(U.error)return{groupCount:X,error:U.error};let M=Q(),O=M.lastAtom;if(U.unbounded&&O?.kind==="group"&&(O.containsQuantifier||O.containsAlternation))return{groupCount:X,error:"nested unbounded repetition or unbounded alternation is not supported"};if(U.unbounded&&M.previousAtom?.hasUnboundedQuantifier&&O!==null&&M.previousAtom.repeatClass!==null&&O.repeatClass!==null&&w4(M.previousAtom.repeatClass,O.repeatClass))return{groupCount:X,error:"adjacent unbounded repetition with overlapping input is not supported"};if(M.containsQuantifier=!0,O!==null)M.lastAtom={...O,containsQuantifier:!0,hasUnboundedQuantifier:O.hasUnboundedQuantifier||U.unbounded};M.hasUnboundedQuantifier||=U.unbounded,G=U.next;continue}if(W!=="^"&&W!=="$")Y({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:W==="."?{kind:"any"}:{kind:"literal",value:W}});else Q().previousAtom=null,Q().lastAtom=null;G++}return{groupCount:X,error:Q().error}}function S7($){if($.length>2048)throw Error("Credential extract pattern exceeds the 2048-character limit");let J;try{J=new RegExp($)}catch{throw Error("Credential extract pattern is not a valid regular expression")}let X=SH($);if(X.error!==void 0)throw Error(`Credential extract pattern rejected: ${X.error}`);return{regex:J,groupCount:X.groupCount}}function IH($,J=""){S7($);try{return new RegExp($,J)}catch{throw Error("Credential extract pattern is not supported by this runtime")}}function H9($,J,X,Q={}){if($.length>1048576)throw Error("Credential extraction input exceeds the 1048576-character limit");let Y=IH(J,"gd"),G=new Map,W=new Map,U=[],M=0;for(let q of $.matchAll(Y)){if(M++,M>4096)throw Error("Credential extraction exceeds the 4096-match limit");let H=q[1];if(H===void 0)throw Error(`Credential extraction matched at offset ${q.index} without a group-1 capture; group 1 must capture the credential value on every match.`);if(H.length===0)continue;let N=G.get(H);if(N===void 0)G.set(H,N=G.size);let[K,L]=q.indices[1],A=X(H,N);if(!W.has(H))W.set(H,A);U.push({start:K,end:L,sentinel:A})}if(G.size===0)return null;if(Q.maskDuplicates){let q=[...G.keys()].sort((H,N)=>N.length-H.length);for(let H of q){let N=W.get(H);if(N===H)continue;for(let K=$.indexOf(H);K!==-1;K=$.indexOf(H,K+1)){let L=K+H.length;if(U.some((A)=>K<A.end&&A.start<L))continue;U.push({start:K,end:L,sentinel:N})}}U.sort((H,N)=>H.start-N.start)}let O="",V=0;for(let q of U)O+=$.slice(V,q.start)+q.sentinel,V=q.end;return{fakeContent:O+$.slice(V),captures:[...G.keys()]}}var P4="(eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)";function I7($){try{return JSON.parse(Buffer.from($,"base64url").toString("utf8"))}catch{return}}function K9($){let J=$.split(".");if(J.length!==3)return!1;let X=I7(J[0]);if(typeof X!=="object"||X===null||!("alg"in X))return!1;return I7(J[1])!==void 0}var CH=9999999999,_4="c3J0LWZha2U";function C7($){return Buffer.from($,"utf8").toString("base64url")}function z9($){let J=C7(JSON.stringify({alg:"HS256",typ:"JWT"})),X=C7(JSON.stringify({sub:nQ+$,exp:CH}));return`${J}.${X}.${_4}`}function E9($,J,X){let[Q,Y]=$.split("."),G=I7(Y??"");if(typeof G!=="object"||G===null||Array.isArray(G))return null;let W=G,U=[];for(let O of J){let V=W[O];if(typeof V==="string")U.push([O,V])}if(U.length===0)return null;let M=new Map;for(let[O,V]of U){let q=X(O,V);W[O]=q,M.set(O,q)}return{fakeToken:`${Q}.${C7(JSON.stringify(W))}.${_4}`,claimSentinels:M}}var _H="file:";class w7{dir;byKey=new Map;write($,J){if(this.dir===void 0)this.dir=nJ.mkdtempSync(x4(PH(),"srt-credmask-"));let X=this.byKey.get($);if(X===void 0)X=x4(this.dir,`${this.byKey.size}.fake`),this.byKey.set($,X);return nJ.rmSync(X,{force:!0}),nJ.writeFileSync(X,J,{mode:384}),X}dispose(){if(this.dir!==void 0)try{nJ.rmSync(this.dir,{recursive:!0,force:!0})}catch($){Z(`MaskedFileStore cleanup failed: ${$}`,{level:"error"})}this.dir=void 0,this.byKey.clear()}get dirPath(){return this.dir}}function v4($,J,X,Q){let Y=[],G=[];for(let W of $){if(W.mode!=="mask")continue;let U=JJ(W.path),M;try{if(nJ.statSync(U).isDirectory()){Z(`[credential-mask] Skipping masked file entry that resolves to a directory: ${W.path} \u2014 use mode "deny" for directories.`,{level:"warn"});continue}let K=nJ.readFileSync(U);if(M=K.toString("utf8"),Buffer.byteLength(M,"utf8")!==K.length){Z(`[credential-mask] Skipping masked file with non-UTF-8 content (binary credential files are not supported in mask mode): ${W.path}`,{level:"warn"});continue}}catch(N){Z(`[credential-mask] Skipping masked file (unreadable on host): ${W.path} \u2014 ${N.message}`);continue}let O=W.injectHosts??J,V=_H+U,q;if(W.extract===void 0&&W.decode===void 0)q=X.register(V,M,O);else{let N=W.extract??P4,K=0,L=H9(M,N,(A,D)=>{if(W.decode==="jwt"&&!K9(A))return A;let S=`${V}#${D}`;if(W.decode==="jwt"&&W.maskClaims?.length){let B=E9(A,W.maskClaims,(w,P)=>X.register(`${V}#jwt${D}.${w}`,P,O));if(B===null)return Z(`[credential-mask] ${W.path}: verified JWT candidate has none of maskClaims ${JSON.stringify(W.maskClaims)} as `+"string claims \u2014 left unmasked."),A;let C=W.maskClaims.filter((w)=>!B.claimSentinels.has(w));if(C.length>0)Z(`[credential-mask] ${W.path}: maskClaims ${JSON.stringify(C)} absent or non-string in a `+"verified JWT \u2014 skipped.");return K++,X.registerWithSentinel(S,B.fakeToken,A,O)}return K++,W.decode==="jwt"?X.registerWithSentinel(S,z9(wH()),A,O):X.register(S,A,O)},{maskDuplicates:W.maskDuplicates??!1});if(L===null||K===0){let A=W.decode==="jwt"?W.maskClaims?.length?`decode "jwt" with pattern "${N}" that matched no verified JWT with maskable claims (maskClaims: ${JSON.stringify(W.maskClaims)})`:`decode "jwt" with pattern "${N}" that matched no verified JWT`:`extract pattern "${N}" that matched nothing`,D=W.onExtractNoMatch??"warn";if(D==="error")throw Error(`credentials.files entry "${W.path}": ${A} (onExtractNoMatch: "error"). Fix the config, change to "warn"/"deny", or remove the entry.`);if(D==="deny"){Z(`[credential-mask] ${W.path} has ${A} \u2014 degrading to `+'mode "deny".',{level:"warn"}),G.push(U);continue}let S=`[sandbox-runtime] WARNING: credentials.files entry "${W.path}" has ${A} in the file. The file is left UNPROTECTED (readable as-is inside the sandbox). Fix the config, set onExtractNoMatch to "deny" or "error", or remove the entry.`;console.warn(S),Z(S,{level:"warn"});continue}q=L.fakeContent}let H=Q.write(V,q);Y.push({realPath:U,fakePath:H})}return{binds:Y,degradeToDenyPaths:G}}import{randomUUID as xH}from"crypto";var F9="env:";function k4($,J,X,Q=process.env){let Y={},G=[];for(let W of $){if(W.mode!=="mask")continue;let U=Q[W.name];if(U===void 0)continue;let M=W.injectHosts??J;if(W.decode==="jwt"){if(!K9(U)){let V=`[sandbox-runtime] WARNING: credentials.envVars entry "${W.name}" has decode "jwt" but its value did not verify as a JWT. The variable is left UNPROTECTED (real value visible as-is inside the sandbox). Fix the config or remove the entry.`;console.warn(V),Z(V,{level:"warn"});continue}if(W.maskClaims?.length){let V=E9(U,W.maskClaims,(H,N)=>X.register(`${F9}${W.name}#${H}`,N,M,W.injectHeaders));if(V===null){let H=`[sandbox-runtime] WARNING: credentials.envVars entry "${W.name}" has maskClaims ${JSON.stringify(W.maskClaims)} but none is present as a string claim in its JWT value. The variable is left UNPROTECTED (real value visible as-is inside the sandbox). Fix the config or remove the entry.`;console.warn(H),Z(H,{level:"warn"});continue}let q=W.maskClaims.filter((H)=>!V.claimSentinels.has(H));if(q.length>0)Z(`[credential-mask] env var "${W.name}": maskClaims ${JSON.stringify(q)} absent or non-string in the `+"JWT \u2014 skipped.");Y[W.name]=X.registerWithSentinel(`${F9}${W.name}`,V.fakeToken,U,M,W.injectHeaders);continue}Y[W.name]=X.registerWithSentinel(`${F9}${W.name}`,z9(xH()),U,M,W.injectHeaders);continue}if(W.extract===void 0){Y[W.name]=X.register(W.name,U,M,W.injectHeaders);continue}let O=H9(U,W.extract,(V,q)=>X.register(`${F9}${W.name}#${q}`,V,M,W.injectHeaders));if(O===null){let V=W.onExtractNoMatch??"warn";if(V==="error")throw Error(`credentials.envVars entry "${W.name}": extract pattern "${W.extract}" matched nothing (onExtractNoMatch: "error"). Fix the regex, change to "warn"/"deny", or remove the entry.`);if(V==="deny"){Z(`[credential-mask] extract pattern /${W.extract}/ matched nothing in the value of ${W.name} \u2014 unsetting the variable.`,{level:"warn"}),G.push(W.name);continue}let q=`[sandbox-runtime] WARNING: credentials.envVars entry "${W.name}" has extract pattern "${W.extract}" that matched nothing in the variable's value. The variable is left UNPROTECTED (visible as-is inside the sandbox). Fix the regex, set onExtractNoMatch to "deny" or "error", or remove the entry.`;console.warn(q),Z(q,{level:"warn"});continue}Y[W.name]=O.fakeContent}return{setEnvVars:Y,degradeToUnsetNames:G}}var f4="AWS_ACCESS_KEY_ID",y4="AWS_SECRET_ACCESS_KEY",b4="AWS_SESSION_TOKEN";class P7{bySentinel=new Map;register($){this.bySentinel.set($.accessKeyIdSentinel,$)}lookup($){return this.bySentinel.get($)}get size(){return this.bySentinel.size}forget($){for(let J of $)this.bySentinel.delete(J)}clear(){this.bySentinel.clear()}}function h4($,J,X,Q,Y,G=process.env){let W=[...J??[]],U=new Set(W.flatMap((q)=>[q.accessKeyIdVar,q.secretAccessKeyVar,...q.sessionTokenVar?[q.sessionTokenVar]:[]]));if(![f4,y4,b4].some((q)=>U.has(q)))W.push({accessKeyIdVar:f4,secretAccessKeyVar:y4,sessionTokenVar:b4});let O=(q)=>$.find((H)=>H.name===q&&H.mode==="mask"&&H.extract===void 0&&H.decode===void 0),V=(q)=>O(q)!==void 0?Q[q]:void 0;for(let q of W){let H=V(q.accessKeyIdVar),N=V(q.secretAccessKeyVar)!==void 0,K=G[q.accessKeyIdVar],L=G[q.secretAccessKeyVar];if(H===void 0||!N||K===void 0||L===void 0){if(N&&H===void 0){let B=`[sandbox-runtime] WARNING: "${q.secretAccessKeyVar}" is masked but "${q.accessKeyIdVar}" is not, so no AWS credential pair was registered. SigV4 requests will be signed with the masked placeholder secret and the proxy cannot `+"detect or re-sign them \u2014 they will fail upstream. Mask both "+"variables (whole-value) to enable re-signing.";console.warn(B),Z(B,{level:"warn"})}continue}let A=O(q.accessKeyIdVar),S=(q.sessionTokenVar!==void 0?V(q.sessionTokenVar):void 0)!==void 0&&q.sessionTokenVar!==void 0?G[q.sessionTokenVar]:void 0;Y.register({accessKeyIdSentinel:H,realAccessKeyId:K,realSecretAccessKey:L,...S!==void 0?{realSessionToken:S}:{},injectHosts:A.injectHosts??X}),Z(`[credential-aws] registered SigV4 pair for ${q.accessKeyIdVar}/${q.secretAccessKeyVar}`+(S!==void 0?" (+session token)":""))}}function vH($){return{streaming:$?.streaming??"deny",presigned:$?.presigned??"deny",sigv4a:$?.sigv4a??"deny"}}function u4($,J,X){let Q=vH(J);return(Y,G,W,U)=>{if($.size===0)return;let M=X4(W,G);if(M===null)return;let O=$.lookup(M.accessKeyId);if(O===void 0)return;if(!O.injectHosts.some((K)=>X(U,K)))return;if(M.kind!=="header-sigv4"){if(Q[M.kind]==="passthrough"){Z(`[credential-aws] ${M.kind} request with masked credential passed through un-resigned per credentials.sigv4.${M.kind} (its signature covers the placeholder secret and will fail upstream)`);return}return{action:"deny",reason:`AWS SigV4 ${M.kind} request uses a masked credential but cannot be re-signed by the sandbox proxy; denied by policy. Set credentials.sigv4.${M.kind} to "passthrough" to forward it unmodified (it will fail upstream: the signature covers the masked placeholder).`}}let V=Y4(cQ(W.authorization));if(V===null)return{action:"deny",reason:"AWS SigV4 request uses a masked credential but its Authorization header is malformed; the proxy cannot re-sign it."};let q=cQ(W["x-amz-date"]);if(q===void 0)return{action:"deny",reason:"AWS SigV4 request uses a masked credential but carries no x-amz-date header; the proxy cannot re-sign it."};let H=[...V.signedHeaders];for(let K of H){if(K==="host")continue;if(K==="x-amz-security-token"&&O.realSessionToken!==void 0)continue;if(W[K]===void 0)return{action:"deny",reason:`AWS SigV4 request uses a masked credential but signed header "${K}" is missing; the proxy cannot re-sign it.`}}if(O.realSessionToken!==void 0&&!H.includes("x-amz-security-token"))H.push("x-amz-security-token");let N=cQ(W["x-amz-content-sha256"]);return{action:"resign",payloadHash:N===M9?M9:void 0,apply(K,L,A){if(O.realSessionToken!==void 0)K["x-amz-security-token"]=O.realSessionToken;if(K["x-amz-content-sha256"]!==void 0&&N!==M9)K["x-amz-content-sha256"]=A;let{authorization:D}=G4({method:Y,requestTarget:G,headers:K,hostHeader:L,signedHeaders:H,payloadHash:A,amzDate:q,scope:{date:V.date,region:V.region,service:V.service},accessKeyId:O.realAccessKeyId,secretAccessKey:O.realSecretAccessKey});K.authorization=D}}}}import{spawnSync as kH}from"child_process";import*as iQ from"fs";function Z0($){if(typeof globalThis.Bun<"u")return globalThis.Bun.which($);let J=process.env.PATH;if(process.platform==="linux"&&J){let Q=(Y)=>{try{if(!iQ.statSync(Y).isFile())return!1;return iQ.accessSync(Y,iQ.constants.X_OK),!0}catch{return!1}};if($.includes("/"))return Q($)?$.trim():null;for(let Y of J.split(":")){let G=`${Y||"."}/${$}`;if(Q(G))return G.trim()}return null}let X=kH("which",[$],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000});if(X.status===0&&X.stdout)return X.stdout.trim();return null}import*as c0 from"fs";import{randomBytes as aK}from"crypto";function TJ($){return $.map((J)=>{if(J==="")return"''";if(/^[A-Za-z0-9_./:@+,-][A-Za-z0-9_./:=@+,-]*$/.test(J))return J;return"'"+J.replace(/'/g,`'"'"'`)+"'"}).join(" ")}import{randomBytes as GK}from"crypto";import*as r from"fs";import{spawn as Y5}from"child_process";import{tmpdir as Z9}from"os";import y$,{join as G5}from"path";import{spawn as fH}from"child_process";import{text as g4}from"stream/consumers";var yH={ms:1e4};class N9 extends Error{constructor($){super(`ripgrep timed out after ${$} ms`);this.name="RipgrepTimeoutError"}}async function _7($,J,X,Q={command:"rg"}){let{command:Y,args:G=[],argv0:W}=Q,U=fH(Y,[...G,...$,J],{argv0:W,env:{PATH:process.env.PATH??"/usr/bin:/bin"},signal:X,windowsHide:!0}),M=yH.ms,O=!1,V=setTimeout(()=>{O=!0,U.kill("SIGKILL")},M),q,H,N;try{[q,H,N]=await Promise.all([g4(U.stdout),g4(U.stderr),new Promise((K,L)=>{U.on("close",K),U.on("error",L)})])}finally{clearTimeout(V)}if(O)throw new N9(M);if(N===0)return q.trim().split(`
62
+ `).filter(Boolean);if(N===1)return[];throw Error(`ripgrep failed with exit code ${N}: ${H}`)}import{join as q0,dirname as bH}from"path";import{fileURLToPath as hH}from"url";import*as L9 from"fs";import{homedir as uH}from"os";var x7=new Map,v7=null;function gH(){if(v7)return v7;let $=[],J=uH();return $.push(q0("/usr","lib","node_modules","@anthropic-ai","sandbox-runtime"),q0("/usr","local","lib","node_modules","@anthropic-ai","sandbox-runtime"),q0("/opt","homebrew","lib","node_modules","@anthropic-ai","sandbox-runtime"),q0(J,".npm","lib","node_modules","@anthropic-ai","sandbox-runtime"),q0(J,".npm-global","lib","node_modules","@anthropic-ai","sandbox-runtime")),v7=$,$}function m4(){let $=process.arch;switch($){case"x64":case"x86_64":return"x64";case"arm64":case"aarch64":return"arm64";case"ia32":case"x86":return Z("[SeccompFilter] 32-bit x86 (ia32) is not currently supported due to missing socketcall() syscall blocking. The current seccomp filter only blocks socket(AF_UNIX, ...), but on 32-bit x86, socketcall() can be used to bypass this.",{level:"error"}),null;default:return Z(`[SeccompFilter] Unsupported architecture: ${$}. Only x64 and arm64 are supported.`),null}}function mH($){let J=m4();if(!J)return[];let X=bH(hH(import.meta.url)),Q=q0("vendor","seccomp",J,$);return[q0(X,Q),q0(X,"..","..",Q),q0(X,"..",Q)]}function k7($){let J=$??"";if(x7.has(J))return x7.get(J);let X=lH($);return x7.set(J,X),X}function lH($){if($){if(L9.existsSync($))return Z(`[SeccompFilter] Using apply-seccomp binary from explicit path: ${$}`),$;Z(`[SeccompFilter] Explicit path provided but file not found: ${$}`)}let J=m4();if(!J)return Z(`[SeccompFilter] Cannot find apply-seccomp binary: unsupported architecture ${process.arch}`),null;Z(`[SeccompFilter] Looking for apply-seccomp binary for architecture: ${J}`);for(let X of mH("apply-seccomp"))if(L9.existsSync(X))return Z(`[SeccompFilter] Found apply-seccomp binary: ${X} (${J})`),X;for(let X of gH()){let Q=q0(X,"vendor","seccomp",J,"apply-seccomp");if(L9.existsSync(Q))return Z(`[SeccompFilter] Found apply-seccomp binary in global install: ${Q} (${J})`),Q}return Z(`[SeccompFilter] apply-seccomp binary not found in any expected location (${J})`),null}import{spawnSync as pH}from"child_process";import{createHash as dH}from"crypto";import*as s from"fs";import iJ from"path";class dX extends Error{}var cH={dir:"/run/srt-stubs",uid:0,lockWaitMs:2000,flockPath:"/usr/bin/flock"},oQ=cH,nH,d4;var A9=s.constants.O_CLOEXEC??524288,f7={kind:"masked"},l4={kind:"real"},pX={kind:"unregistered"},iH=new Set(["ENOENT","EACCES"]),oH=new Set(["ENOENT","ENOTDIR","EROFS"]),H0=null,zQ=null,aH=0;function cX($){return $?.code}function b7($){return dH("sha256").update($).digest("hex")}function h7(){if(process.platform!=="linux")return"off";let{dir:$,uid:J,flockPath:X}=oQ;if(process.geteuid?.()!==J)return"off";try{s.accessSync(X,s.constants.X_OK)}catch(Y){return iH.has(cX(Y)??"")?"off":"error"}try{s.mkdirSync($,{mode:448}),s.chmodSync($,448)}catch(Y){let G=cX(Y)??"";if(G!=="EEXIST")return oH.has(G)?"off":"error"}let Q;try{Q=s.lstatSync($)}catch{return"error"}if(!Q.isDirectory()||Q.uid!==J||(Q.mode&511)!==448)return Z(`[Sandbox Linux] ${$} is not a 0700 directory owned by uid ${J}; mask stubs are not shared`,{level:"warn"}),"off";return $}function c4($,J){try{return s.openSync(iJ.join($,J),s.constants.O_RDONLY|s.constants.O_CREAT|s.constants.O_NOFOLLOW|A9,384)}catch{return null}}function n4($,J){try{return pH(oQ.flockPath,[...J,"3"],{stdio:["ignore","ignore","ignore",$],timeout:oQ.lockWaitMs+5000}).status===0}catch{return!1}}function p4($,J,X){let Q=c4($,J);if(Q===null)return null;let Y=(oQ.lockWaitMs/1000).toFixed(3);if(n4(Q,[X,"-w",Y]))return Q;return s.closeSync(Q),null}function i4($){try{s.closeSync($)}catch{}}function o4(){let $=h7();if($==="off")return!1;if($==="error")throw new dX(`srt: cannot read the mask stub registry ${oQ.dir}; refusing to start the sandbox`);if(H0===null)H0=p4($,"lock","-s");if(H0!==null&&zQ===null)zQ=p4($,"claims","-x");if(H0===null||zQ===null)throw new dX(`srt: mask stub registry ${$} is busy (no ${H0===null?"shared":"claims"} lock within ${oQ.lockWaitMs} ms); refusing to start the sandbox rather than risk a mask another call removes`);return!0}function R9(){if(zQ===null)return;i4(zQ),zQ=null}function sH(){if(H0===null)return;i4(H0),H0=null}function a4(){let $=h7();if($==="off")return null;if($==="error"||H0===null||zQ===null)throw new dX("srt: mask stub claimed without holding the registry; refusing to start the sandbox");return $}function nX($){try{return s.lstatSync($,{bigint:!0})}catch(J){return cX(J)==="ENOENT"?"absent":"unknown"}}function s4($){try{let J=JSON.parse(s.readFileSync($,"utf8")),{v:X,type:Q,uid:Y,dev:G,ino:W,ctimeNs:U,path:M}=J,O=(V)=>typeof V==="string"&&/^\d+$/.test(V);if(X!==1||Q!=="f"&&Q!=="d"||typeof Y!=="number"||!O(G)||!O(W)||!O(U)||typeof M!=="string"||!M.startsWith("/"))return null;return{type:Q,uid:Y,dev:BigInt(G),ino:BigInt(W),ctimeNs:BigInt(U),dest:M}}catch{return null}}function r4($,J){return iJ.join($,`${b7(J)}.stub`)}function rH($,J){let X=b7(J.dest),Q=iJ.join($,`${X}.stub.${process.pid}-${++aH}`),Y=JSON.stringify({v:1,type:J.type,uid:J.uid,dev:String(J.dev),ino:String(J.ino),ctimeNs:String(J.ctimeNs),path:J.dest});s.writeFileSync(Q,Y+`
63
+ `,{flag:"wx",mode:384}),s.renameSync(Q,iJ.join($,`${X}.stub`))}function t4($,J){return(J.type==="f"?$.isFile()&&$.size===BigInt(0):$.isDirectory())&&$.uid===BigInt(J.uid)&&$.dev===J.dev&&$.ino===J.ino&&$.ctimeNs===J.ctimeNs}function u7($){let J=iJ.dirname($),X;try{X=s.openSync(J,s.constants.O_RDONLY|s.constants.O_DIRECTORY|s.constants.O_NOFOLLOW|A9)}catch{return null}try{if(s.readlinkSync(`/proc/self/fd/${X}`)===J)return X}catch{}return s.closeSync(X),null}function e4($,J,X){return{type:$,uid:Number(J.uid),dev:J.dev,ino:J.ino,ctimeNs:J.ctimeNs,dest:X}}function tH($){let J=u7($);if(J===null)return null;try{let X;try{X=s.openSync(`/proc/self/fd/${J}/${iJ.basename($)}`,s.constants.O_RDONLY|s.constants.O_CREAT|s.constants.O_EXCL|s.constants.O_NOFOLLOW|A9,292)}catch(Q){return cX(Q)==="EEXIST"?"exists":null}try{return d4?.($),e4("f",s.fstatSync(X,{bigint:!0}),$)}finally{s.closeSync(X)}}finally{s.closeSync(J)}}function eH($,J){let X=u7($);if(X===null)return null;try{let Q=`/proc/self/fd/${X}/${iJ.basename($)}`;try{s.mkdirSync(Q,{mode:493})}catch(G){return cX(G)==="EEXIST"?"exists":null}d4?.($);let Y;try{Y=s.openSync(Q,s.constants.O_RDONLY|s.constants.O_DIRECTORY|s.constants.O_NOFOLLOW|A9)}catch{return null}try{let G=s.fstatSync(Y,{bigint:!0});if(!G.isDirectory()||G.uid!==BigInt(process.geteuid?.()??-1)||G.nlink>BigInt(2)||s.readdirSync(`/proc/self/fd/${Y}`).length!==0)return null;if(J)s.fchownSync(Y,J.uid,J.gid);return e4("d",s.fstatSync(Y,{bigint:!0}),$)}catch{return null}finally{s.closeSync(Y)}}finally{s.closeSync(X)}}function $K($){let J=u7($.dest);if(J===null)return;try{let X=`/proc/self/fd/${J}/${iJ.basename($.dest)}`,Q=nX(X);if(typeof Q==="object"&&t4(Q,$)){if($.type==="d")s.rmdirSync(X);else s.unlinkSync(X);Z(`[Sandbox Linux] Removed shared mask stub: ${$.dest}`)}}catch{}finally{s.closeSync(J)}}function JK($){try{s.unlinkSync($)}catch{}}function y7($,J,X,Q){let Y=s4(r4($,J));return Y!==null&&Y.type===Q&&Y.dest===J&&t4(X,Y)}function $5($,J,X){let Q=a4();if(Q===null)return pX;if(nH?.($)==="unregistered")return pX;let Y=nX($);if(Y==="unknown")return pX;if(Y!=="absent")return y7(Q,$,Y,J)?f7:l4;let G=X();if(G==="exists"){let W=nX($);return typeof W==="object"&&y7(Q,$,W,J)?f7:l4}if(G===null)return pX;try{rH(Q,G)}catch(W){Z(`[Sandbox Linux] mask stub marker not written for ${$}: ${W}`,{level:"warn"})}return f7}function QK($){return $5($,"f",()=>tH($))}function XK($,J){return $5($,"d",()=>eH($,J))}function J5($,J){let X=a4();if(X===null)return null;let Q=(G)=>J.some((W)=>G.startsWith(W+"/")),Y=[];for(let G=iJ.dirname($);Q(G);G=iJ.dirname(G))Y.unshift(G);for(let G of Y){let W=nX(G);if(typeof W==="object"&&y7(X,G,W,"d"))return G}return null}function Q5($,J){try{return $()}catch(X){if(X instanceof dX)throw X;return Z(`[Sandbox Linux] mask stub not recorded for ${J}: ${X}`,{level:"warn"}),pX}}function g7($){return Q5(()=>QK($),$)}function X5($,J){return Q5(()=>XK($,J),$)}function YK($){let J;try{J=s.readdirSync($)}catch{return}let X=[],Q=[];for(let G of J){let W=/^([0-9a-f]{64})\.stub(\..*)?$/.exec(G);if(W===null)continue;let U=iJ.join($,G);if(Q.push(U),W[2]===void 0){let M=s4(U);if(M!==null&&b7(M.dest)===W[1])X.push(M)}}let Y=(G)=>G.dest.split("/").length;X.sort((G,W)=>G.type===W.type?Y(W)-Y(G):G.type==="f"?-1:1);for(let G of X)$K(G);for(let G of Q)JK(G)}function m7($,J){let X=h7(),Q=H0!==null;if(R9(),sH(),X==="off"){for(let G of $)J(G);return[]}if(X==="error")return[...$];if(!Q&&$.length===0)return[];let Y=c4(X,"lock");if(Y===null)return[...$];try{if(!n4(Y,["-x","-n"]))return[...$];for(let G of $)if(nX(r4(X,G))==="absent")J(G);return YK(X),[]}catch(G){return Z(`[Sandbox Linux] mask stub sweep failed: ${G}`,{level:"warn"}),[...$]}finally{s.closeSync(Y)}}var c7=3;function WK($){let J=$.uid===void 0?$.bwrapCommand:[$.setprivPath??"/usr/bin/setpriv",`--reuid=${$.uid}`,`--regid=${$.gid??$.uid}`,"--clear-groups","--inh-caps=-all","--ambient-caps=-all","--bounding-set=-all",...$.bwrapCommand],X=$.unsetEnvVars??[],Q=Object.entries($.setEnvVars??{});if(X.length===0&&Q.length===0)return J;return["/usr/bin/env",...X.flatMap((Y)=>["-u",Y]),...Q.map(([Y,G])=>`${Y}=${G}`),...J]}function l7($,J){let X=$.split(y$.sep),Q="";for(let Y of X){if(!Y)continue;let G=Q+y$.sep+Y;try{if(r.lstatSync(G).isSymbolicLink()){if(J.some((M)=>G.startsWith(M+"/")||G===M))return G}}catch{break}Q=G}return null}var UK=40;function W5($){let J=$;for(let X=0;X<UK;X++){try{return r.realpathSync(J)}catch{}let Q=J,Y=[],G=null;while(G===null){let M=y$.dirname(Q);if(M===Q)return null;Y.unshift(y$.basename(Q)),Q=M;try{G=r.realpathSync(Q)}catch{}}let W=y$.join(G,Y[0]),U=null;try{U=r.readlinkSync(W)}catch{}if(U===null)return y$.join(G,...Y);J=y$.join(y$.resolve(y$.dirname(W),U),...Y.slice(1))}return null}function MK($){let J=$.split(y$.sep),X="";for(let Q of J){if(!Q)continue;let Y=X+y$.sep+Q;try{let G=r.statSync(Y);if(G.isFile()||G.isSymbolicLink())return!0}catch{break}X=Y}return!1}function OK($){let J=$.split(y$.sep),X="";for(let Q of J){if(!Q)continue;let Y=X+y$.sep+Q;if(!r.existsSync(Y))return Y;X=Y}return $}async function VK($={command:"rg"},J=c7,X=!1,Q){let Y=process.cwd(),G=new AbortController,W=Q??G.signal,U=LY(),M=[...NX.map((K)=>y$.resolve(Y,K)),...U.map((K)=>y$.resolve(Y,K))],O=y$.resolve(Y,".git"),V=!1;try{V=r.statSync(O).isDirectory()}catch{}if(V){if(M.push(y$.resolve(Y,".git/hooks")),!X)M.push(y$.resolve(Y,".git/config"))}let q=[];for(let K of NX)q.push("--iglob",K);for(let K of U)q.push("--iglob",`**/${K}/**`);if(q.push("--iglob","**/.git/hooks/**"),!X)q.push("--iglob","**/.git/config");let H=["--files","--hidden","--no-ignore","--max-depth",String(J),...q,"-g","!**/node_modules/**"],N;try{N=await _7(H,Y,W,$)}catch(K){if(K instanceof N9)throw Error(`mandatory deny scan failed: ${K}`);Z(`[Sandbox] ripgrep scan failed, retrying once: ${K}`);try{N=await _7(H,Y,W,$)}catch(L){throw Error(`mandatory deny scan failed: ${L}`)}}for(let K of N){let L=y$.resolve(Y,K),A=!1;for(let D of[...U,".git"]){let S=o9(D),B=L.split(y$.sep),C=B.findIndex((w)=>o9(w)===S);if(C!==-1){if(D===".git"){let w=B.slice(0,C+1).join(y$.sep);if(K.includes(".git/hooks"))M.push(y$.join(w,"hooks"));else if(K.includes(".git/config"))M.push(y$.join(w,"config"))}else M.push(B.slice(0,C+1).join(y$.sep));A=!0;break}}if(!A)M.push(L)}return[...new Set(M)]}var iX;function qK(){if(process.getuid?.()!==0||process.env.ARA_SRT_FILE_MASK!=="empty")return"/dev/null";if(iX)try{let X=r.lstatSync(iX);if(X.isFile()&&X.size===0&&X.uid===0&&(X.mode&146)===0)return iX}catch{}let $=r.mkdtempSync(y$.join(Z9(),"claude-empty-file-"));B9.add($),r.chmodSync($,493);let J=y$.join($,"empty");return r.writeFileSync(J,"",{flag:"wx",mode:292}),r.chmodSync(J,292),iX=J,J}var oX=new Set,B9=new Set;function U5($,J){return $===J?qK():"/dev/null"}var HK="ARA_SRT_MASKED_PATHS",KK=16384;function zK($,J,X=KK){let Q=[],Y=0;for(let G of new Set($)){if(G.includes(`
64
+ `))continue;if(G!==J&&!G.startsWith(J==="/"?"/":J+"/"))continue;let W=G.split("'").length-1,U=Buffer.byteLength(G)+4*W+(Q.length>0?1:0);if(Y+U>X)break;Q.push(G),Y+=U}return Q.length>0?Q.join(`
65
+ `):void 0}function EK($){try{let J=r.lstatSync($);return J.isFile()&&J.size===0}catch{return!1}}var B0=0,M5=!1;function D9(){if(M5)return;process.on("exit",()=>{j9({force:!0})}),M5=!0}function j9($){if(!$?.force){if(B0>0)B0--;if(B0>0){Z(`[Sandbox Linux] Deferring mount point cleanup \u2014 ${B0} sandbox(es) still active`);return}}else B0=0;let J=[],X=[];for(let G of oX)try{let W=r.statSync(G);if(W.isFile()&&W.size===0)J.push(G);else if(W.isDirectory())X.push(G)}catch{}let Q=(G)=>G.split("/").length;X.sort((G,W)=>Q(W)-Q(G));let Y=m7([...J,...X],(G)=>{try{let W=r.statSync(G);if(W.isFile()&&W.size===0)r.unlinkSync(G),Z(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${G}`);else if(W.isDirectory()){if(r.readdirSync(G).length!==0)return;r.rmdirSync(G),Z(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${G}`)}}catch{}});oX.clear();for(let G of Y)oX.add(G);for(let G of B9)try{r.rmSync(G,{recursive:!0,force:!0})}catch{}B9.clear(),iX=void 0}function O5($){try{return r.accessSync($,r.constants.X_OK),!0}catch{return!1}}function q5($){let{seccompConfig:J,bwrapPath:X,socatPath:Q}=$??{},Y=[],G=[];if(X){if(!O5(X))Y.push(`bubblewrap (bwrap) not executable at ${X}`)}else if(Z0("bwrap")===null)Y.push("bubblewrap (bwrap) not installed");if(Q){if(!O5(Q))Y.push(`socat not executable at ${Q}`)}else if(Z0("socat")===null)Y.push("socat not installed");if(!J?.argv0&&k7(J?.applyPath)===null)G.push("seccomp not available - unix socket access not restricted");return{warnings:G,errors:Y}}async function H5($,J,X,Q,Y){let G=X??"socat",W=GK(8).toString("hex"),U=G5(Z9(),`claude-http-${W}.sock`),M=G5(Z9(),`claude-socks-${W}.sock`),O=[`UNIX-LISTEN:${U},fork,reuseaddr`,`TCP:localhost:${$},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];Z(`Starting HTTP bridge: ${G} ${O.join(" ")}`);let V=Y5(G,O,{stdio:"ignore"});if(V.on("error",(K)=>{Z(`HTTP bridge process error: ${K}`,{level:"error"})}),V.on("exit",(K,L)=>{Z(`HTTP bridge process exited with code ${K}, signal ${L}`,{level:K===0?"info":"error"})}),!V.pid)throw Error("Failed to start HTTP bridge process");let q,H;if(J===$)q=V,H=U;else{H=M;let K=[`UNIX-LISTEN:${M},fork,reuseaddr`,`TCP:localhost:${J},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];if(Z(`Starting SOCKS bridge: ${G} ${K.join(" ")}`),q=Y5(G,K,{stdio:"ignore"}),q.on("error",(L)=>{Z(`SOCKS bridge process error: ${L}`,{level:"error"})}),q.on("exit",(L,A)=>{Z(`SOCKS bridge process exited with code ${L}, signal ${A}`,{level:L===0?"info":"error"})}),!q.pid){if(V.pid)try{process.kill(V.pid,"SIGTERM")}catch{}throw Error("Failed to start SOCKS bridge process")}}let N=200;for(let K=0;K<N;K++){if(!V.pid||V.killed||!q.pid||q.killed)throw Error("Linux bridge process died unexpectedly");try{if(r.existsSync(U)&&r.existsSync(H)){if(Q!==void 0){let L=Y??Q;for(let A of new Set([U,H]))r.chownSync(A,Q,L),r.chmodSync(A,384)}Z(`Linux bridges ready after ${K+1} attempts`);break}}catch(L){Z(`Error checking sockets (attempt ${K+1}): ${L}`,{level:"error"})}if(K===N-1){if(V.pid)try{process.kill(V.pid,"SIGTERM")}catch{}if(q.pid)try{process.kill(q.pid,"SIGTERM")}catch{}throw Error(`Failed to create bridge sockets after ${N} attempts`)}await new Promise((L)=>setTimeout(L,5))}return{httpSocketPath:U,socksSocketPath:H,httpBridgeProcess:V,socksBridgeProcess:q,httpProxyPort:$,socksProxyPort:J}}function FK($,J){if(J){if(!$)throw Error("seccompConfig.argv0 requires seccompConfig.applyPath");return`ARGV0=${TJ([J])} ${TJ([$])} `}let X=k7($);return X?`${TJ([X])} `:void 0}function d7($,J,X){if(X===void 0)return[$,"-c",J];return[$,"-c",`${K5(X)}; exec "$0" "$@"`,$,"-c",J]}function K5($){if(!Number.isSafeInteger($)||$<3||$>9)throw Error("bad_start_fd");return`printf . >&${$}; exec ${$}>&-`}function NK($,J,X,Q,Y,G,W,U){let M=Y||"bash",O=TJ([G??"socat"]),V=W===void 0?"":` ${W}>&-`,q=["srt_payload_pid=",`${O} TCP4-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr ${TJ([`UNIX-CONNECT:${$}`])} >/dev/null 2>&1${V} &`,"srt_http_proxy_pid=$!",`${O} TCP4-LISTEN:1080,bind=127.0.0.1,fork,reuseaddr ${TJ([`UNIX-CONNECT:${J}`])} >/dev/null 2>&1${V} &`,"srt_socks_proxy_pid=$!","srt_cleanup_command() {"," srt_status=$?"," trap - EXIT INT TERM",' if [ -n "$srt_payload_pid" ]; then',' kill -KILL "$srt_payload_pid" 2>/dev/null',' wait "$srt_payload_pid" 2>/dev/null'," fi",' kill -KILL "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null',' wait "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null',' exit "$srt_status"',"}","trap srt_cleanup_command EXIT","trap 'exit 143' TERM","trap 'exit 130' INT",...[3128,1080].map((K)=>`{ true <>/dev/tcp/127.0.0.1/${K}; } 2>/dev/null || { ${O} -u OPEN:/dev/null TCP4:127.0.0.1:${K},connect-timeout=0.1,retry=480,interval=0.005 >/dev/null 2>&1${V} & wait "$!"; } || { printf '%s\\n' 'Sandbox proxy listener readiness failed' >&2; exit 1; }`),`kill -0 "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null || { printf '%s\\n' 'Sandbox proxy listener exited before command' >&2; exit 1; }`],H=Q===void 0&&W!==void 0?`{ ${K5(W)}; trap '' INT QUIT; exec ${U?X:TJ([M,"-c",X])}; }`:(Q??"")+TJ(d7(M,X,W));return[...q,`${H} <&0 &`,"srt_payload_pid=$!",'wait "$srt_payload_pid"',"srt_payload_status=$?","srt_payload_pid=",'exit "$srt_payload_status"'].join(`
66
+ `)}function p7($){try{if(r.lstatSync($).isSymbolicLink())return r.realpathSync($)}catch{}return $}function V5($,J,X,Q){let Y=J==="/"?"/":J+"/";$.push("--tmpfs",J);for(let G of X)if(G.startsWith(Y)||G===J)$.push("--bind",G,G),Z(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${G}`);for(let G of Q)if(G.startsWith(Y)||G===J){if(!r.existsSync(G)){Z(`[Sandbox Linux] Skipping non-existent read allow path: ${G}`);continue}if(X.some((W)=>(W.startsWith(Y)||W===J)&&(G===W||G.startsWith(W+"/"))))continue;$.push("--ro-bind",G,G),Z(`[Sandbox Linux] Re-allowed read access within denied region: ${G}`)}}async function LK($,J,X,Q,Y={command:"rg"},G=c7,W=!1,U,M,O=[]){let V=[],q=[],H=[],N=new Set,K=new Map,L=new Map;if(J){V.push("--ro-bind","/","/");for(let u of J.allowOnly||[]){let J$=JJ(u).replace(/\/+$/,"")||"/";if(Z(`[Sandbox Linux] Processing write path: ${u} -> ${J$}`),J$.startsWith("/dev/")){Z(`[Sandbox Linux] Skipping /dev path: ${J$}`);continue}if(!r.existsSync(J$)){Z(`[Sandbox Linux] Skipping non-existent write path: ${J$}`);continue}try{let a=r.realpathSync(J$),V$=J$.replace(/\/+$/,"");if(a!==V$&&NY(J$,a)){Z(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${u} -> ${a}`);continue}}catch{Z(`[Sandbox Linux] Skipping write path that could not be resolved: ${J$}`);continue}V.push("--bind",J$,J$),q.push(J$)}let y,n=()=>{if(y!==void 0)return y;let u=[];for(let a of q){u.push(a);try{let V$=r.realpathSync(a);if(V$!==a)u.push(V$)}catch{}}let J$=[];if($){let a=[],V$=new Set(["proc","dev","sys"]);for(let O$ of $.denyOnly||[])if(JJ(O$)==="/")try{for(let e of r.readdirSync("/"))if(!V$.has(e))a.push("/"+e)}catch{}else a.push(O$);if(r.existsSync("/etc/ssh/ssh_config.d"))a.push("/etc/ssh/ssh_config.d");for(let O$ of a){let e=JJ(O$),C$=!1;try{C$=r.statSync(e).isDirectory()}catch{continue}if(!C$)continue;J$.push(e);try{let g$=r.realpathSync(e);if(g$!==e)J$.push(g$)}catch{}}}return y={allowedWritePathsBothForms:u,prospectiveReadDenyTmpfsDirsBothForms:J$},y},Y$=(u)=>q.some((J$)=>u.startsWith(J$+"/")||u===J$),L$=[...J.denyWithinAllow||[],...await VK(Y,G,W,U)];o4();let j$=new Set;for(let u of L$){let J$=JJ(u);if(J$.startsWith("/dev/"))continue;let a=W5(J$);if(a===null||a.startsWith("/dev/"))continue;if(l7(a,q))continue;let V$=!1;try{V$=r.statSync(a).isDirectory()}catch{continue}if(!V$)continue;if(Y$(a)){let O$=K.get(a);if(O$===void 0)O$=new Set,K.set(a,O$);O$.add(J$)}}let $J=new Map,S$=(u)=>{let J$=$J.get(u);if(J$!==void 0)return J$;let{allowedWritePathsBothForms:a,prospectiveReadDenyTmpfsDirsBothForms:V$}=n(),O$=a.some((e)=>e.startsWith(u+"/"))||V$.some((e)=>e===u||e.startsWith(u+"/"))||V$.some((e)=>[u,...K.get(u)??[]].some((C$)=>C$===e||C$.startsWith(e+"/")));return $J.set(u,O$),O$},b$=[...K.keys()];for(let u of L$){let J$=JJ(u);if(J$.startsWith("/dev/"))continue;let a=W5(J$);if(a===null){let e=l7(J$,q);if(e&&!j$.has(e))j$.add(e),H.push("--ro-bind","/dev/null",e),L.set(e,J$);Z(`[Sandbox Linux] Deny path could not be resolved through symlinks, failing closed: ${J$}`);continue}if(a!==J$)Z(`[Sandbox Linux] Resolved symlinked deny path: ${J$} -> ${a}`);if(a.startsWith("/dev/"))continue;if(j$.has(a))continue;j$.add(a);let V$=l7(a,q);if(V$){if(!j$.has(V$))j$.add(V$),H.push("--ro-bind","/dev/null",V$),L.set(V$,J$);Z(`[Sandbox Linux] Mounted /dev/null at symlink ${V$} to prevent symlink replacement attack`);continue}if(!r.existsSync(a)){if(MK(a)){Z(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${a}`);continue}let e=y$.dirname(a);while(e!=="/"&&!r.existsSync(e))e=y$.dirname(e);let C$=Y$(e)||Y$(a),g$=b$.filter((W$)=>e===W$||e.startsWith(W$+"/")),i$=g$.length>0&&!g$.some(S$);if(C$&&!i$){let W$=OK(a),z$=J5(W$,q)??W$;if(z$!==a){if(!N.has(z$)){let v$=X5(z$,M),f$=r.mkdtempSync(y$.join(Z9(),"claude-empty-"));if(r.chmodSync(f$,365),B9.add(f$),H.push("--ro-bind",f$,z$),L.set(z$,J$),N.add(z$),v$.kind==="unregistered")oX.add(z$);D9(),Z(`[Sandbox Linux] Mounted empty dir at ${z$} to block creation of ${a}`)}}else{let v$=g7(z$),f$=U5(a,J$);if(v$.kind==="masked")H.push("--ro-bind",f$,z$),L.set(z$,J$),D9(),Z(`[Sandbox Linux] Masked shared stub at ${z$} with ${f$} to block creation of ${a}`);else if(v$.kind==="real")H.push("--ro-bind",z$,z$),L.set(z$,J$);else H.push("--ro-bind",f$,z$),L.set(z$,J$),oX.add(z$),D9(),Z(`[Sandbox Linux] Mounted ${f$} at ${z$} to block creation of ${a}`)}}else if(i$)Z(`[Sandbox Linux] Skipping non-existent deny path inside a read-only denied directory (already uncreatable): ${a}`);else Z(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${a}`);continue}if(Y$(a)){if((EK(a)?g7(a):void 0)?.kind==="masked")H.push("--ro-bind",U5(a,J$),a),D9();else H.push("--ro-bind",a,a);L.set(a,J$)}else Z(`[Sandbox Linux] Skipping deny path not within allowed paths: ${a}`)}}else V.push("--bind","/","/");let A=[],D=($?.allowWithinDeny||[]).map((y)=>JJ(y)),S=new Map,B=[],C=new Set(["proc","dev","sys"]);for(let y of $?.denyOnly||[])if(JJ(y)==="/"){for(let n of r.readdirSync("/"))if(!C.has(n))A.push("/"+n)}else A.push(y);if($&&r.existsSync("/etc/ssh/ssh_config.d"))A.push("/etc/ssh/ssh_config.d");let w=A.map((y)=>JJ(y)).sort((y,n)=>y.split("/").length-n.split("/").length);for(let y of w){if(!r.existsSync(y)){Z(`[Sandbox Linux] Skipping non-existent read deny path: ${y}`);continue}if(r.statSync(y).isDirectory())B.push(y),V5(V,y,q,D);else{if(D.includes(y)){Z(`[Sandbox Linux] Skipping read deny for re-allowed path: ${y}`);continue}let Y$=p7(y);V.push("--ro-bind","/dev/null",Y$),S.set(Y$,"/dev/null"),S.set(y,"/dev/null")}}for(let{realPath:y,fakePath:n}of X??[]){let Y$=p7(y);V.push("--ro-bind",n,Y$),S.set(Y$,n),S.set(y,n)}let P=(y)=>B.some((n)=>{if(!(y===n||y.startsWith(n+"/")))return!1;return!q.some((j$)=>(j$===n||j$.startsWith(n+"/"))&&(y===j$||y.startsWith(j$+"/")))}),l=[...N].filter((y)=>{let n=L.get(y)??y;return!S.has(y)&&!P(y)&&!P(n)&&!q.some((Y$)=>Y$===y||Y$.startsWith(y+"/"))}),$$=[];for(let y=0;y<H.length;y+=3){let n=H[y+2],Y$=L.get(n)??n;if(S.has(n))continue;if(P(n)||P(Y$)){Z(`[Sandbox Linux] Skipping denyWrite bind already hidden by denyRead tmpfs: ${n}`);continue}if(l.some((L$)=>n.startsWith(L$+"/"))){Z(`[Sandbox Linux] Skipping denyWrite bind under an empty-directory mask: ${n}`);continue}if(V.push(H[y],H[y+1],n),$$.push(n),H[y+1]!==n)O.push(n);if(Y$!==n)$$.push(Y$)}for(let y of B)if($$.some((n)=>y.startsWith(n+"/")))Z(`[Sandbox Linux] Re-applying denyRead tmpfs re-exposed by denyWrite bind: ${y}`),V5(V,y,q,D);for(let[y,n]of S)if($$.some((Y$)=>y.startsWith(Y$+"/"))){if(p7(y)!==y)continue;Z(`[Sandbox Linux] Re-applying file mask re-exposed by denyWrite bind: ${y}`),V.push("--ro-bind",n,y)}if(Q!==void 0)V.push("--ro-bind",Q,Q);return V}async function z5($){let{command:J,commandId:X,needsNetworkRestriction:Q,httpSocketPath:Y,socksSocketPath:G,httpProxyPort:W,socksProxyPort:U,proxyAuthToken:M,caCertPath:O,readConfig:V,writeConfig:q,unsetEnvVars:H,setEnvVars:N,maskedFileBinds:K,maskedFileStoreDir:L,enableWeakerNestedSandbox:A,runAsUid:D,runAsGid:S,runAsHostUid:B,runAsHostGid:C,runAsHostHome:w,runAsHostUser:P,setprivPath:l,allowAllUnixSockets:$$,binShell:y,ripgrepConfig:n={command:"rg"},mandatoryDenySearchDepth:Y$=c7,allowGitConfig:L$=!1,gitSafeDirectories:j$,seccompConfig:$J,bwrapPath:S$,socatPath:b$,observeSocketPath:u,startFd:J$,argvCommand:a,abortSignal:V$}=$,O$=V&&V.denyOnly.length>0||K!==void 0&&K.length>0,e=q!==void 0,C$=H!==void 0&&H.length>0||N!==void 0&&Object.keys(N).length>0,g$=(j$?.length??0)>0;if(!Q&&!O$&&!e&&!C$&&!g$)return J;B0++;let i$=[],W$=["--new-session","--die-with-parent"],z$=[],v$;try{if(!$$)if(v$=FK($J?.applyPath,$J?.argv0),!v$)throw Error("seccomp_unavailable: the policy requires the unix-socket filter (allowAllUnixSockets is false) but apply-seccomp is not installed beside srt (vendor/seccomp/<arch>/apply-seccomp; build it with `bun run build:seccomp` in packages/sandbox-runtime)");else Z("[Sandbox Linux] Applying seccomp filter for Unix socket blocking");else Z("[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled");if(u&&v$)if(r.existsSync(u))z$.push("--bind",u,u),W$.push("--setenv","SRT_OBSERVE_SOCK",u),W$.push("--setenv","SRT_ENCODED_CMD",PJ(X??J));else Z("[Sandbox Linux] observe socket missing \u2014 supervisor not running; "+"continuing without violation monitoring");if(C$){for(let gJ of H??[])W$.push("--unsetenv",gJ);for(let[gJ,e0]of Object.entries(N??{}))W$.push("--setenv",gJ,e0)}if(j$&&j$.length>0){let gJ=AY({safeDirs:j$,unsetEnvVars:H,setEnvVars:N});for(let[e0,zY]of Object.entries(gJ))W$.push("--setenv",e0,zY)}if(Q){if(W$.push("--unshare-net"),Y&&G){if(!r.existsSync(Y))throw Error(`Linux HTTP bridge socket does not exist: ${Y}. The bridge process may have died. Try reinitializing the sandbox.`);if(!r.existsSync(G))throw Error(`Linux SOCKS bridge socket does not exist: ${G}. The bridge process may have died. Try reinitializing the sandbox.`);if(z$.push("--bind",Y,Y),G!==Y)z$.push("--bind",G,G);let gJ=jQ(3128,1080,O,M,q===void 0,PJ(X??J));if(W$.push(...gJ.flatMap((e0)=>{let zY=e0.indexOf("="),lU=e0.slice(0,zY),pU=e0.slice(zY+1);return["--setenv",lU,pU]})),W!==void 0)W$.push("--setenv","CLAUDE_CODE_HOST_HTTP_PROXY_PORT",String(W));if(U!==void 0)W$.push("--setenv","CLAUDE_CODE_HOST_SOCKS_PROXY_PORT",String(U))}}let f$=await LK(V,q,K,L,n,Y$,L$,V$,B===void 0?void 0:{uid:B,gid:C??B},i$);R9(),W$.push(...f$);let XJ=zK(i$,process.cwd());if(XJ!==void 0)W$.push("--setenv",HK,XJ);if(W$.push(...z$),W$.push("--dev","/dev"),W$.push("--unshare-pid"),!A){if(W$.push("--unshare-user","--cap-drop","ALL","--proc","/proc"),!v$)W$.push("--ro-bind","/dev/null","/proc/sysrq-trigger")}else W$.push("--unshare-user","--bind","/proc","/proc");if(D!==void 0)W$.push("--uid",String(D)),W$.push("--gid",String(S??D));if(B!==void 0){if(w)W$.push("--setenv","HOME",w);if(P)W$.push("--setenv","USER",P),W$.push("--setenv","LOGNAME",P)}let YJ=y||"bash",o$=Z0(YJ);if(!o$)throw Error(`Shell '${YJ}' not found in PATH`);if(W$.push("--",o$,"-c"),Q&&Y&&G){let gJ=NK(Y,G,J,v$,o$,b$,J$,a);W$.push(gJ)}else if(v$){let gJ=v$+TJ(d7(o$,J,J$));W$.push(gJ)}else W$.push(J$===void 0?J:`exec ${TJ(d7(o$,J,J$))}`);let GJ=[S$??"bwrap",...W$],WJ=TJ(WK({bwrapCommand:GJ,uid:B,gid:C,setprivPath:l,unsetEnvVars:H,setEnvVars:N})),a$=[];if(Q)a$.push("network");if(O$||e)a$.push("filesystem");if(C$)a$.push("env");if(v$)a$.push("seccomp(unix-block)");return Z(`[Sandbox Linux] Wrapped command with bwrap (${a$.join(", ")} restrictions)`),WJ}catch(f$){if(B0>0)B0--;if(R9(),B0===0)m7([],()=>{});throw f$}}import{spawn as AK}from"child_process";import*as j0 from"path";class T9{violations=[];totalCount=0;maxSize=100;listeners=new Set;addViolation($){if(this.violations.push({...$,line:n7($.line).replace(/[<>]/g,"")}),this.totalCount++,this.violations.length>this.maxSize)this.violations=this.violations.slice(-this.maxSize);this.notifyListeners()}getViolations($){if($===void 0)return[...this.violations];return this.violations.slice(-$)}getCount(){return this.violations.length}getTotalCount(){return this.totalCount}getViolationsForCommand($){let J=PJ($);return this.violations.filter((X)=>X.encodedCommand===J)}clear(){this.violations=[],this.notifyListeners()}subscribe($){return this.listeners.add($),$(this.getViolations()),()=>{this.listeners.delete($)}}notifyListeners(){let $=this.getViolations();this.listeners.forEach((J)=>J($))}}function aQ($,J,X){if(!X)return!1;if((X["*"]??[]).some((Y)=>$.includes(Y)))return!0;if(J===void 0)return!1;for(let[Y,G]of Object.entries(X))if(Y!=="*"&&J.includes(Y)&&G.some((W)=>$.includes(W)))return!0;return!1}function n7($){return $.replace(/[\x00-\x1f\x7f-\x9f]+/g," ").trim()}function RK($=!1){let J=process.cwd(),X=[];for(let Q of NX)X.push(j0.resolve(J,Q)),X.push(`**/${Q}`);for(let Q of LY())X.push(j0.resolve(J,Q)),X.push(`**/${Q}/**`);if(X.push(j0.resolve(J,".git/hooks")),X.push("**/.git/hooks/**"),!$)X.push(j0.resolve(J,".git/config")),X.push("**/.git/config");return[...new Set(X)]}var E5=`_${Math.random().toString(36).slice(2,11)}_SBX`;function DK($){return`CMD64_${PJ($)}_END_${E5}`}function sQ($){return NJ($)?`(regex ${oJ(DX($))})`:`(subpath ${oJ($)})`}function s7($){return DX($).slice(0,-1)+"(/.*)?$"}function EQ($){return NJ($)?`(regex ${oJ(s7($))})`:`(subpath ${oJ($)})`}function F5($){return $.replace(/\[[^\]]*\]|[*?]+/g,"x")}function o7($,J){let X=[...new Set(J)];if(X.length===0)return $;let Q=X.map((Y)=>`(require-not ${Y})`).join(" ");return`(require-all ${$} ${Q})`}function i7($){let J=JJ($);return{path:J,glob:NJ(J)}}function N5($,J){return $.test(J.glob?F5(J.path):J.path)}function S9($,J){let X=$.glob?F5($.path):$.path;return X.startsWith(J==="/"?"/":J+"/")&&X!==J}function ZK($,J){return{denies:($.denyOnly||[]).map(i7),allows:($.allowWithinDeny||[]).map(i7),writeRoots:(J||[]).map(i7)}}function BK($){let J=[],X=!1,Q=$.allows.filter((Y)=>!Y.glob).map((Y)=>Y.path);for(let Y of $.denies){if(!Y.glob){if(Q.some((U)=>Y.path.startsWith(U+"/")))J.push(EQ(Y.path));continue}let G=new RegExp(s7(Y.path));if(G.test("/"))X=!0;let W=$.allows.filter((U)=>N5(G,U)).map((U)=>sQ(U.path));J.push(o7(EQ(Y.path),W))}return{filters:J,coversRoot:X}}function L5($){let J=$.split(/[*?[\]]/)[0];if(!J||J==="/")return"/";return J.endsWith("/")?J.slice(0,-1):j0.dirname(J)}function jK($,J){let{denies:X,allows:Q,writeRoots:Y}=$;if(Y.length===0)return[];let G=Y.filter((q)=>q.glob).map((q)=>new RegExp(DX(q.path))),W=Y.filter((q)=>!q.glob).map((q)=>q.path),U=(q)=>W.some((H)=>S9({path:q,glob:!1},H))||G.some((H)=>H.test(q)),M=(q)=>[...Q,...Y].filter((H)=>S9(H,q)).map((H)=>sQ(H.path)),O=new Set,V=(q)=>{for(let H of q)if(U(H))O.add(`(literal ${oJ(H)})`)};for(let q of X)if(q.glob){let H=L5(q.path);if(!(G.length>0||W.some((A)=>H===A||S9({path:H,glob:!1},A)||S9({path:A,glob:!1},H))))continue;let K=new RegExp(s7(q.path)),L=[...Q,...Y].filter((A)=>N5(K,A)).map((A)=>sQ(A.path));if(O.add(o7(EQ(q.path),L)),H!=="/")V([H,...a7(H)])}else{if(!U(q.path))continue;O.add(o7(EQ(q.path),M(q.path))),V(a7(q.path))}return m0("deny",["file-write-unlink"],O,J)}function m0($,J,X,Q){if(X.size===0)return[];return[`(${$} ${J.join(" ")}`,...[...X].map((Y)=>` ${Y}`),` (with message "${Q}"))`]}function a7($){let J=[],X=j0.dirname($);while(X!=="/"&&X!=="."){J.push(X);let Q=j0.dirname(X);if(Q===X)break;X=Q}return J}function A5($,J){let X=new Set;for(let Q of $){let Y=JJ(Q);X.add(EQ(Y));let G;if(NJ(Y)){if(G=L5(Y),G==="/")continue;X.add(`(literal ${oJ(G)})`)}else G=Y;for(let W of a7(G))X.add(`(literal ${oJ(W)})`)}return m0("deny",["file-write-unlink","file-write-create"],X,J)}function TK($,J){if(!$)return["(allow file-read*)"];let X=[];X.push("(allow file-read*)");let Q=$.denies.some((M)=>M.path==="/"),Y=new Set($.denies.map((M)=>EQ(M.path)));X.push(...m0("deny",["file-read*"],Y,J));let G=new Set($.allows.map((M)=>sQ(M.path)));X.push(...m0("allow",["file-read*"],G,J));let W=BK($);if(X.push(...m0("deny",["file-read*"],new Set(W.filters),J)),Q||W.coversRoot)X.push('(allow file-read* (literal "/"))');if($.denies.length>0)X.push("(allow file-read-metadata"," (vnode-type DIRECTORY))");X.push(...A5($.denies.map((M)=>M.path),J));let U=new Set($.writeRoots.map((M)=>sQ(M.path)));return X.push(...m0("allow",["file-write-unlink","file-write-create"],U,J)),X}function SK($,J,X=!1){if(!$)return["(allow file-write*)"];let Q=[],Y=new Set;for(let U of $.allowOnly||[])Y.add(sQ(JJ(U)));Q.push(...m0("allow",["file-write*"],Y,J));let G=[...$.denyWithinAllow||[],...RK(X)],W=new Set;for(let U of G)W.add(EQ(JJ(U)));return Q.push(...m0("deny",["file-write*"],W,J)),Q.push(...A5(G,J)),Q}function IK({readConfig:$,writeConfig:J,httpProxyPort:X,socksProxyPort:Q,needsNetworkRestriction:Y,allowUnixSockets:G,allowAllUnixSockets:W,allowLocalBinding:U,allowMachLookup:M,allowPty:O,allowGitConfig:V=!1,enableWeakerNetworkIsolation:q=!1,allowAppleEvents:H=!1,logTag:N}){let K=["(version 1)",`(deny default (with message "${N}"))`,"",`; LogTag: ${N}`,"","; Essential permissions - based on Chrome sandbox policy","; Process permissions","(allow process-exec)","(allow process-fork)","(allow process-info* (target same-sandbox))","(allow signal (target same-sandbox))","(allow mach-priv-task-port (target same-sandbox))","","; User preferences","(allow user-preference-read)","","; Mach IPC - specific services only (no wildcard)","(allow mach-lookup",' (global-name "com.apple.audio.systemsoundserver")',' (global-name "com.apple.distributed_notifications@Uv3")',' (global-name "com.apple.FontObjectsServer")',' (global-name "com.apple.fonts")',' (global-name "com.apple.logd")',' (global-name "com.apple.lsd.mapdb")',' (global-name "com.apple.PowerManagement.control")',' (global-name "com.apple.system.logger")',' (global-name "com.apple.system.notification_center")',' (global-name "com.apple.system.opendirectoryd.libinfo")',' (global-name "com.apple.system.opendirectoryd.membership")',' (global-name "com.apple.bsd.dirhelper")',' (global-name "com.apple.securityd.xpc")',' (global-name "com.apple.coreservices.launchservicesd")',")","",...q?["; trustd.agent - needed for Go TLS certificate verification (weaker network isolation)",'(allow mach-lookup (global-name "com.apple.trustd.agent"))']:[],...H?["; Apple Events - opt-in; needed for open/osascript to talk to other apps (appleeventsd)","(allow appleevent-send)",'(allow mach-lookup (global-name "com.apple.coreservices.appleevents"))',"; Launch Services open requests need the lsopen operation plus, on","; macOS 14/15, coreservicesd and the quarantine resolver - without","; these open fails with -10822 kLSServerCommunicationErr or -54","(allow lsopen)",'(allow mach-lookup (global-name "com.apple.CoreServices.coreservicesd"))','(allow mach-lookup (global-name "com.apple.coreservices.quarantine-resolver"))']:[],...M&&M.length>0?["; User-specified XPC/Mach services",...M.map((A)=>A.endsWith("*")?`(allow mach-lookup (global-name-prefix ${oJ(A.slice(0,-1))}))`:`(allow mach-lookup (global-name ${oJ(A)}))`)]:[],"","; POSIX IPC - shared memory","(allow ipc-posix-shm)","","; POSIX IPC - semaphores for Python multiprocessing","(allow ipc-posix-sem)","","; IOKit - specific operations only","(allow iokit-open",' (iokit-registry-entry-class "IOSurfaceRootUserClient")',' (iokit-registry-entry-class "RootDomainUserClient")',' (iokit-user-client-class "IOSurfaceSendRight")',")","","; IOKit properties","(allow iokit-get-properties)","","; Specific safe system-sockets, doesn't allow network access","(allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))","","; sysctl - specific sysctls only","(allow sysctl-read",' (sysctl-name "hw.activecpu")',' (sysctl-name "hw.busfrequency_compat")',' (sysctl-name "hw.byteorder")',' (sysctl-name "hw.cacheconfig")',' (sysctl-name "hw.cachelinesize_compat")',' (sysctl-name "hw.cpufamily")',' (sysctl-name "hw.cpufrequency")',' (sysctl-name "hw.cpufrequency_compat")',' (sysctl-name "hw.cputype")',' (sysctl-name "hw.l1dcachesize_compat")',' (sysctl-name "hw.l1icachesize_compat")',' (sysctl-name "hw.l2cachesize_compat")',' (sysctl-name "hw.l3cachesize_compat")',' (sysctl-name "hw.logicalcpu")',' (sysctl-name "hw.logicalcpu_max")',' (sysctl-name "hw.machine")',' (sysctl-name "hw.memsize")',' (sysctl-name "hw.ncpu")',' (sysctl-name "hw.nperflevels")',' (sysctl-name "hw.packages")',' (sysctl-name "hw.pagesize_compat")',' (sysctl-name "hw.pagesize")',' (sysctl-name "hw.physicalcpu")',' (sysctl-name "hw.physicalcpu_max")',' (sysctl-name "hw.tbfrequency_compat")',' (sysctl-name "hw.vectorunit")',' (sysctl-name "kern.argmax")',' (sysctl-name "kern.bootargs")',' (sysctl-name "kern.hostname")',' (sysctl-name "kern.maxfiles")',' (sysctl-name "kern.maxfilesperproc")',' (sysctl-name "kern.maxproc")',' (sysctl-name "kern.ngroups")',' (sysctl-name "kern.osproductversion")',' (sysctl-name "kern.osrelease")',' (sysctl-name "kern.ostype")',' (sysctl-name "kern.osvariant_status")',' (sysctl-name "kern.osversion")',' (sysctl-name "kern.secure_kernel")',' (sysctl-name "kern.tcsm_available")',' (sysctl-name "kern.tcsm_enable")',' (sysctl-name "kern.usrstack64")',' (sysctl-name "kern.version")',' (sysctl-name "kern.willshutdown")',' (sysctl-name "machdep.cpu.brand_string")',' (sysctl-name "machdep.ptrauth_enabled")',' (sysctl-name "security.mac.lockdown_mode_state")',' (sysctl-name "sysctl.proc_cputype")',' (sysctl-name "vm.loadavg")',' (sysctl-name-prefix "hw.optional.arm")',' (sysctl-name-prefix "hw.optional.arm.")',' (sysctl-name-prefix "hw.optional.armv8_")',' (sysctl-name-prefix "hw.perflevel")',' (sysctl-name-prefix "kern.proc.all")',' (sysctl-name-prefix "kern.proc.pgrp.")',' (sysctl-name-prefix "kern.proc.pid.")',' (sysctl-name-prefix "machdep.cpu.")',' (sysctl-name-prefix "net.routetable.")',")","","; V8 thread calculations","(allow sysctl-write",' (sysctl-name "kern.tcsm_enable")',")","","; Distributed notifications","(allow distributed-notification-post)","","; Specific mach-lookup permissions for security operations",'(allow mach-lookup (global-name "com.apple.SecurityServer"))',"","; File I/O on device files",'(allow file-ioctl (literal "/dev/null"))','(allow file-ioctl (literal "/dev/zero"))','(allow file-ioctl (literal "/dev/random"))','(allow file-ioctl (literal "/dev/urandom"))','(allow file-ioctl (literal "/dev/dtracehelper"))','(allow file-ioctl (literal "/dev/tty"))',"","(allow file-ioctl file-read-data file-write-data"," (require-all",' (literal "/dev/null")'," (vnode-type CHARACTER-DEVICE)"," )",")",""];if(K.push("; Network"),!Y)K.push("(allow network*)");else{if(U)K.push('(allow network-bind (local ip "*:*"))'),K.push('(allow network-inbound (local ip "*:*"))'),K.push('(allow network-outbound (remote ip "localhost:*"))');if(W)K.push("(allow system-socket (socket-domain AF_UNIX))"),K.push('(allow network-bind (local unix-socket (path-regex #"^/")))'),K.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))');else if(G&&G.length>0){K.push("(allow system-socket (socket-domain AF_UNIX))");for(let A of G){let D=JJ(A);K.push(`(allow network-bind (local unix-socket (subpath ${oJ(D)})))`),K.push(`(allow network-outbound (remote unix-socket (subpath ${oJ(D)})))`)}}if(X!==void 0)K.push(`(allow network-bind (local ip "localhost:${X}"))`),K.push(`(allow network-inbound (local ip "localhost:${X}"))`),K.push(`(allow network-outbound (remote ip "localhost:${X}"))`);if(Q!==void 0&&Q!==X)K.push(`(allow network-bind (local ip "localhost:${Q}"))`),K.push(`(allow network-inbound (local ip "localhost:${Q}"))`),K.push(`(allow network-outbound (remote ip "localhost:${Q}"))`)}K.push("");let L=$?ZK($,J?.allowOnly):void 0;if(K.push("; File read"),K.push(...TK(L,N)),K.push(""),K.push("; File write"),K.push(...SK(J,N,V)),L){let A=jK(L,N);if(A.length>0)K.push(""),K.push("; File read: keep read-denied paths inside write roots in place"),K.push(...A)}if(O)K.push(""),K.push("; Pseudo-terminal (pty) support"),K.push("(allow pseudo-tty)"),K.push("(allow file-ioctl"),K.push(' (literal "/dev/ptmx")'),K.push(' (regex #"^/dev/ttys")'),K.push(")"),K.push("(allow file-read* file-write*"),K.push(' (literal "/dev/ptmx")'),K.push(' (regex #"^/dev/ttys")'),K.push(")");return K.join(`
67
+ `)}function oJ($){return JSON.stringify($)}function R5($){let{command:J,commandId:X,needsNetworkRestriction:Q,httpProxyPort:Y,socksProxyPort:G,proxyAuthToken:W,caCertPath:U,allowUnixSockets:M,allowAllUnixSockets:O,allowLocalBinding:V,allowMachLookup:q,readConfig:H,writeConfig:N,unsetEnvVars:K,setEnvVars:L,maskedFileBinds:A,allowPty:D,allowGitConfig:S=!1,gitSafeDirectories:B,enableWeakerNetworkIsolation:C=!1,allowAppleEvents:w=!1,binShell:P}=$,l=H;if(A&&A.length>0)Z("[Sandbox macOS] file mask degrades to deny on macOS until the interposer lands"),l={denyOnly:[...H?.denyOnly??[],...A.map((O$)=>O$.realPath)],allowWithinDeny:H?.allowWithinDeny};let $$=l&&l.denyOnly.length>0,y=N!==void 0,n=K!==void 0&&K.length>0||L!==void 0&&Object.keys(L).length>0,Y$=(B?.length??0)>0;if(!Q&&!$$&&!y&&!n&&!Y$)return J;let L$=X??J,j$=DK(L$),$J=IK({readConfig:l,writeConfig:N,httpProxyPort:Y,socksProxyPort:G,needsNetworkRestriction:Q,allowUnixSockets:M,allowAllUnixSockets:O,allowLocalBinding:V,allowMachLookup:q,allowPty:D,allowGitConfig:S,enableWeakerNetworkIsolation:C,allowAppleEvents:w,logTag:j$}),S$=jQ(Y,G,U,W,N===void 0,PJ(L$));if(V&&Q){let C$=(K??[]).includes("JAVA_TOOL_OPTIONS")?"":process.env.JAVA_TOOL_OPTIONS??"",g$=C$.includes("-Djava.net.preferIPv4Stack=true")?C$:[C$,"-Djava.net.preferIPv4Stack=true"].filter(Boolean).join(" ");S$.push(`JAVA_TOOL_OPTIONS=${g$}`)}if(B&&B.length>0){let O$=AY({safeDirs:B,unsetEnvVars:K,setEnvVars:L});for(let[e,C$]of Object.entries(O$))S$.push(`${e}=${C$}`)}let b$=P||"bash",u=Z0(b$);if(!u)throw Error(`Shell '${b$}' not found in PATH`);let J$=(K??[]).flatMap((O$)=>["-u",O$]),a=Object.entries(L??{}).map(([O$,e])=>`${O$}=${e}`),V$=TJ(["env",...J$,...a,...S$,"/usr/bin/sandbox-exec","-p",$J,u,"-c",J]);return Z(`[Sandbox macOS] Applied restrictions - network: ${!!(Y||G)}, read: ${l?"allowAllExcept"in l?"allowAllExcept":"denyAllExcept":"none"}, write: ${N?"allowAllExcept"in N?"allowAllExcept":"denyAllExcept":"none"}`),V$}function D5($,J,X=(Q)=>Q){let Q=/CMD64_(.+?)_END/,Y=/Sandbox:\s+(.+)$/,G=AK("log",["stream","--predicate",`(eventMessage ENDSWITH "${E5}")`,"--style","compact"]);return G.stdout?.on("data",(W)=>{let U=W.toString().split(`
68
+ `),M=U.find((K)=>K.includes("Sandbox:")&&K.includes("deny")),O=U.find((K)=>K.startsWith("CMD64_"));if(!M)return;let V=M.match(Y);if(!V?.[1])return;let q=V[1],H,N;if(O){if(N=O.match(Q)?.[1],N)try{H=X(JQ(N))}catch{}}if(q.includes("mDNSResponder")||q.includes("mach-lookup com.apple.diagnosticd")||q.includes("mach-lookup com.apple.analyticsd"))return;if(aQ(q,H,J))return;$({line:q,command:H,encodedCommand:N,timestamp:new Date})}),G.stderr?.on("data",(W)=>{Z(`[Sandbox Monitor] Log stream stderr: ${W.toString()}`)}),G.on("error",(W)=>{Z(`[Sandbox Monitor] Failed to start log stream: ${W.message}`)}),G.on("exit",(W)=>{Z(`[Sandbox Monitor] Log stream exited with code: ${W}`)}),()=>{Z("[Sandbox Monitor] Stopping log monitor"),G.kill("SIGTERM")}}import{randomBytes as CK}from"crypto";import{chmodSync as Z5,chownSync as wK,mkdtempSync as PK,rmSync as _K}from"fs";import{createServer as xK}from"net";import{tmpdir as vK}from"os";import{join as B5,posix as kK}from"path";import{createInterface as fK}from"readline";function j5($,J){let{allowWritePaths:X,denyWritePaths:Q,ignoreViolations:Y,resolveCommandText:G=(B)=>B,consumerUid:W,consumerGid:U}=J,M=PK(B5(vK(),"srt-obs-")),O=B5(M,`s${CK(4).toString("hex")}.sock`),V=(B,C)=>B===C||B.startsWith(C.endsWith("/")?C:C+"/"),q=(B)=>{let C=kK.normalize(B);if(Q.some((w)=>V(C,w)))return!0;return!X.some((w)=>V(C,w))},H=(B,C)=>{if(B.observe_init_error){Z(`[Sandbox Linux Monitor] observe filter not installed: ${B.observe_init_error}`);return}if(typeof B.path!=="string")return;if(!B.path.startsWith("/"))return;if(!q(B.path))return;let w;if(C)try{w=G(JQ(C))}catch{}if(aQ(B.path,w,Y))return;let P={line:`deny ${B.syscall??"syscall"} ${B.path}`,command:w,encodedCommand:C,timestamp:new Date};$(P)},N,K=new Promise((B)=>{N=B}),L=O,A=xK((B)=>{let C,w=fK({input:B});w.on("line",(P)=>{if(!P)return;let l;try{l=JSON.parse(P)}catch{return}if(l.encodedCommand&&C===void 0)C=l.encodedCommand;H(l,C??l.encodedCommand)}),B.on("error",()=>w.close()),B.on("close",()=>w.close())});A.on("error",(B)=>{Z(`[Sandbox Linux Monitor] listen failed: ${B.message} - violation monitoring disabled`,{level:"warn"}),L=void 0,N()}),A.listen(O,()=>{if(W!==void 0)Z5(M,457),wK(O,W,U??W),Z5(O,384);N()});let D=new Set;return A.on("connection",(B)=>{D.add(B),B.on("close",()=>D.delete(B))}),{get observeSocketPath(){return L},ready:K,stop:()=>{Z("[Sandbox Linux Monitor] stopping");for(let B of D)B.destroy();A.close();try{_K(M,{recursive:!0,force:!0})}catch{}}}}import*as e$ from"fs";import*as I5 from"net";import*as t$ from"path";import{spawn as yK,spawnSync as bK}from"child_process";import{once as hK}from"events";import{fileURLToPath as uK}from"url";class A$ extends Error{code;subcommand;constructor($,J,X){super(J);this.name="WindowsSandboxError",this.code=$,this.subcommand=X}}var I9=[60080,60089],T5=["-NoProfile","-Command"];function C9($){let J=process.env.SystemRoot??"C:\\Windows",X={exe:t$.win32.join(J,"System32","cmd.exe"),args:["/d","/s","/c"]};if($===void 0||$===null)return X;if(typeof $==="object"){if(!t$.win32.isAbsolute($.exe))throw new A$("bin_shell_invalid",`binShell.exe must be an absolute path (got ${JSON.stringify($.exe)})`);if(!Array.isArray($.args))throw new A$("bin_shell_invalid",`binShell.args must be an array (got ${JSON.stringify($.args)})`);return $}let Q=t$.win32.basename($),Y=Q.toLowerCase(),G=t$.win32.isAbsolute($);if(!G&&$!==Q)throw new A$("bin_shell_invalid",`binShell string must be a bare token or an absolute path (got ${JSON.stringify($)})`);switch(Y){case"bash":case"bash.exe":case"sh":case"sh.exe":if(!G)throw new A$("bin_shell_invalid",`binShell bash path must be absolute (got ${JSON.stringify($)}); pass the resolved Git Bash install path`);return{exe:$,args:["-c"]};case"pwsh":case"pwsh.exe":return{exe:G?$:"pwsh.exe",args:T5};case"powershell":case"powershell.exe":return{exe:G?$:t$.win32.join(J,"System32","WindowsPowerShell","v1.0","powershell.exe"),args:T5};case"cmd":case"cmd.exe":return G?{exe:$,args:X.args}:X;default:throw new A$("bin_shell_invalid",`unrecognised binShell ${JSON.stringify($)}: expected 'cmd' | 'powershell' | 'pwsh' or an absolute path to bash.exe/sh.exe/pwsh.exe/powershell.exe`)}}function C5(){let $=t$.dirname(uK(import.meta.url));return t$.resolve($,"..","..")}var w5={x64:"x64",arm64:"arm64"},gK=t$.join(C5(),"vendor","srt-win",w5[process.arch]??process.arch,"srt-win.exe");function mK(){let $=C5(),J=w5[process.arch],X=[];if(J)X.push(t$.join($,"vendor","srt-win",J,"srt-win.exe"));X.push(t$.join($,"vendor","srt-win-src","target","release","srt-win.exe"));for(let Q of X)if(e$.existsSync(Q))return Q;throw new A$("srt_win_not_found",`srt-win.exe not found. Set windows.srtWin.path or build with \`cargo build --release --manifest-path vendor/srt-win-src/Cargo.toml\`. Looked in: ${X.join(", ")}`)}var P5="--srt-win";function wJ($){if($?.path===void 0)throw new A$("srt_win_not_found","no srt-win path configured; set windows.srtWin.path (e.g. to the exported VENDORED_SRT_WIN_EXE constant for the packaged binary)");if(!e$.existsSync($.path))throw new A$("srt_win_not_found",`windows.srtWin.path is set to '${$.path}' but the file does not exist`);return{exe:$.path,prependArgs:[P5]}}function l0($,J={}){let{exe:X,prependArgs:Q}=J.srtWin??wJ(),Y=bK(X,[...Q,...$],{encoding:"utf8",windowsHide:!0,timeout:J.timeoutMs??15000,...J.stdin!==void 0?{input:J.stdin}:{}});if(Y.error){if(Y.error.code==="ETIMEDOUT")throw new A$("srt_win_timeout",`srt-win ${$.join(" ")} timed out after ${J.timeoutMs??15000}ms`+(Y.signal?` (killed by ${Y.signal})`:""),$[0]);throw new A$("spawn_failed",`srt-win ${$[0]}: spawn failed: ${Y.error.message}`,$[0])}return{status:Y.status,signal:Y.signal,stdout:(Y.stdout??"").trim(),stderr:(Y.stderr??"").trim()}}function t7($,J={}){let{exe:X,prependArgs:Q}=J.srtWin??wJ(),Y=J.timeoutMs??15000;return new Promise((G,W)=>{let U=yK(X,[...Q,...$],{windowsHide:!0}),M=!1,O=Y>0?setTimeout(()=>{M=!0,U.kill()},Y):void 0,V="",q="";U.stdout?.setEncoding("utf8").on("data",(H)=>V+=H),U.stderr?.setEncoding("utf8").on("data",(H)=>q+=H),U.stdin?.on("error",()=>{}).end(J.stdin),U.once("error",(H)=>{clearTimeout(O),W(new A$("spawn_failed",`srt-win ${$[0]}: spawn failed: ${H.message}`,$[0]))}),U.once("close",(H,N)=>{if(clearTimeout(O),M){W(new A$("srt_win_timeout",`srt-win ${$.join(" ")} timed out after ${Y}ms`+(N?` (killed by ${N})`:""),$[0]));return}G({status:H,signal:N,stdout:V.trim(),stderr:q.trim()})})})}function _5($,J){if(J.status!==0)throw new A$("srt_win_nonzero",`srt-win ${$.join(" ")} exited ${J.status}: ${J.stderr||J.stdout}`,$[0]);try{return JSON.parse(J.stdout)}catch(X){throw new A$("srt_win_bad_json",`srt-win ${$.join(" ")}: unparseable JSON output ${JSON.stringify(J.stdout)}: ${X.message}`,$[0])}}function e7($,J){return _5($,l0($,J))}async function $G($,J){return _5($,await t7($,J))}function x5($,J){let X=l0($,J),Q;try{Q=JSON.parse(X.stdout)}catch(Y){throw new A$("srt_win_bad_json",`srt-win ${$.join(" ")}: unparseable JSON output ${JSON.stringify(X.stdout)}: ${Y.message}`,$[0])}return{ok:X.status===0,json:Q,stderr:X.stderr}}function v5($){let J=["wfp","status"];if($)J.push("--sublayer-guid",$);return J}function w9($){return{state:$.state,filters:$.filters,...$.port_range&&{portRange:$.port_range},...$.user_sid&&{userSid:$.user_sid},...$.hint&&{hint:$.hint}}}function P9($){return{provisioned:$.user.exists,...$.user.sid&&{sid:$.user.sid},groupExists:$.user.group_exists,...$.user.group_sid&&{groupSid:$.user.group_sid},inBuiltinUsers:$.user.in_builtin_users,inSandboxGroup:$.user.in_sandbox_group,hiddenFromLogon:$.user.hidden_from_logon,credPresent:$.cred_present,...typeof $.marker_version==="number"&&{markerVersion:$.marker_version},realUserSid:$.real_user_sid,...$.ca_cert_thumb&&{caCertThumb:$.ca_cert_thumb},...$.ca_cert_pem&&{caCertPem:$.ca_cert_pem}}}function k5($={}){let J=["status"];if($.sublayerGuid)J.push("--sublayer-guid",$.sublayerGuid);let X=e7(J,{srtWin:$.srtWin});return{user:P9(X.user),wfp:w9(X.wfp)}}async function f5($={}){let J=["status"];if($.sublayerGuid)J.push("--sublayer-guid",$.sublayerGuid);let X=await $G(J,{srtWin:$.srtWin});return{user:P9(X.user),wfp:w9(X.wfp)}}function y5($={}){return w9(e7(v5($.sublayerGuid),{srtWin:$.srtWin}))}async function b5($={}){return w9(await $G(v5($.sublayerGuid),{srtWin:$.srtWin}))}async function JG($={}){let J=$.target,X;if(!J){let[Q,Y]=$.proxyPortRange??I9;for(let G=0;G<5;G++){let W=I5.createServer();W.listen(0,"127.0.0.1"),await hK(W,"listening");let U=W.address().port;if(U<Q||U>Y){X=W,J=`127.0.0.1:${U}`;break}W.close()}if(!J)throw new A$("wfp_verify_bind_failed",`verifyWindowsWfpEgress: could not bind a loopback listener outside the WFP permit range [${Q},${Y}] in 5 attempts`)}try{let Q=l0(["wfp","verify","--target",J],{timeoutMs:30000,srtWin:$.srtWin});Z(`[Sandbox Windows] wfp verify exit=${Q.status}: ${Q.stderr||Q.stdout}`);let Y;try{Y=JSON.parse(Q.stdout)}catch{throw new A$("wfp_verify_unparseable","WFP egress fence could not be verified \u2014 `srt-win wfp "+`verify\` exited ${Q.status}`+(Q.signal?` (signal ${Q.signal})`:"")+` with unparseable output ${JSON.stringify(Q.stdout)} (stderr: ${JSON.stringify(Q.stderr)})`)}if(Q.status===3)throw new A$("wfp_fence_inactive","WFP egress fence is not active \u2014 direct outbound from the "+`sandbox user to ${Y.target} succeeded. Re-run \`srt-win install\` (one UAC prompt). (${Q.stderr})`);if(Q.status!==0)throw new A$("wfp_verify_inconclusive","WFP egress fence could not be verified \u2014 probe to "+`${Y.target} was '${Y.egress_probe}' (exit ${Q.status}). The fence may be absent. Re-run \`srt-win install\`. (${Q.stderr})`);return{target:Y.target,stderr:Q.stderr}}finally{X?.close()}}function QG($={}){return P9(e7(["user","status"],{srtWin:$.srtWin}))}async function aX($={}){return P9(await $G(["user","status"],{srtWin:$.srtWin}))}function XG($,J={}){let X=$??QG(J);if(!X.caCertThumb||!X.caCertPem)return null;return{pem:X.caCertPem,thumb:X.caCertThumb}}function lK($,J={}){let X=l0(["user","trust-ca",$],{timeoutMs:60000,srtWin:J.srtWin});u5($,X)}async function h5($,J={}){let X=await t7(["user","trust-ca",$],{timeoutMs:60000,srtWin:J.srtWin});u5($,X)}function u5($,J){if(Z(`[Sandbox Windows] user trust-ca exit=${J.status}: ${J.stderr||J.stdout}`),J.status!==0)throw new A$("trust_ca_failed",`srt-win user trust-ca '${$}' failed (exit ${J.status}): ${J.stderr||J.stdout}`)}function g5(){let $=process.env.ProgramData;if(!$)throw Error("ProgramData is not set");return t$.win32.join($,"sandbox-runtime")}async function YG($={}){let J=$.status??await aX({srtWin:$.srtWin});if(!J.provisioned||!J.credPresent)throw Error(`ensurePersistentWindowsCa: sandbox user is not provisioned (user=${J.provisioned}, cred=${J.credPresent}). Run \`npx sandbox-runtime windows-install\` first.`);let X=$.dir?void 0:g5();if(X&&!e$.existsSync(X))throw Error(`ensurePersistentWindowsCa: state directory ${X} does not exist. Run \`npx sandbox-runtime windows-install\` first.`);let Q=$.dir??t$.win32.join(X,"ca"),Y=t$.join(Q,"ca.json"),G=t$.join(Q,"cert.pem"),W=t$.join(Q,"key.pem"),U=($.regenerateWithinDays??30)*24*60*60*1000,M=(A,D)=>{let S=`${A}.tmp.${process.pid}`;e$.writeFileSync(S,D),e$.renameSync(S,A)},O=async(A,D,S,B)=>{M(G,A),M(W,D);let C=B||J.caCertThumb!==S;if(C){let w=t$.join(Q,`.trust.${process.pid}.${Date.now()}.pem`);e$.writeFileSync(w,A);try{await h5(w,{srtWin:$.srtWin})}finally{e$.rmSync(w,{force:!0})}}return Z(`[Sandbox Windows] persistent CA ${B?"generated":"reused"} (thumb=${S}${C&&!B?", trust reconciled":""})`),{certPem:A,keyPem:D,certPath:G,keyPath:W,thumbprint:S,generated:B,trusted:C}},V=()=>{let A;try{A=JSON.parse(e$.readFileSync(Y,"utf8"))}catch(S){Z(`[Sandbox Windows] persistent CA ca.json unreadable (${S.message})`,{level:"warn"});return}if(typeof A.certPem!=="string"||typeof A.keyPem!=="string")return;let D=hX(A.certPem,A.keyPem);if(!D.ok){Z(`[Sandbox Windows] persistent CA invalid (${D.reason})`,{level:"warn"});return}return{certPem:A.certPem,keyPem:A.keyPem,thumbprint:D.thumbprint,notAfter:D.notAfter}};if(!$.force){let A=V();if(A&&A.notAfter.getTime()-Date.now()>U)return await O(A.certPem,A.keyPem,A.thumbprint,!1);if(A)Z(`[Sandbox Windows] persistent CA expiring ${A.notAfter.toISOString()}; regenerating`,{level:"warn"})}e$.mkdirSync(Q,{recursive:!0});try{let A=Date.now()-300000;for(let D of e$.readdirSync(Q)){if(!D.includes(".tmp.")&&!D.startsWith(".trust."))continue;let S=t$.join(Q,D);if(e$.statSync(S).mtimeMs<A)e$.rmSync(S,{force:!0})}}catch{}let q=J9({cn:"sandbox-runtime persistent CA"});M(Y,JSON.stringify({certPem:q.certPem,keyPem:q.keyPem}));let H=V(),{certPem:N,keyPem:K,thumbprint:L}=H??{certPem:q.certPem,keyPem:q.keyPem,thumbprint:pQ(q.certPem)};return await O(N,K,L,!0)}function GG($){return $.timeoutMs??120000}function m5($){let J=["install"];if($.sublayerGuid)J.push("--sublayer-guid",$.sublayerGuid);if($.proxyPortRange)J.push("--proxy-port-range",`${$.proxyPortRange[0]}-${$.proxyPortRange[1]}`);if($.sandboxUser)J.push("--sandbox-user",$.sandboxUser);if($.force)J.push("--force");return J}function l5($){if($ instanceof A$&&$.code==="srt_win_timeout")throw new A$("install_timeout","srt-win install timed out \u2014 the UAC prompt may still be open. "+`Re-run when ready to grant elevation. (${$.message})`);throw $}function p5($){if(Z(`[Sandbox Windows] install exit=${$.status}: ${$.stderr||$.stdout}`),$.status===0||$.status===10)return;let J=$.stderr||$.stdout;switch($.status){case 12:throw new A$("install_wfp_failed",`srt-win install: WFP filter install failed: ${J}`);case 14:throw new A$("install_user_failed",`srt-win install: sandbox user provisioning failed: ${J}`);case 13:throw new A$("install_config_conflict",`srt-win install: filters already exist under this sublayer with a different port range or sandbox-user name. Pass {force: true} to replace, or pick a different sublayerGuid. Output: ${J}`);case 17:throw new A$("install_ambient_failed",`srt-win install: ambient write-deny stamping failed (stock world-writable system dirs could not be deny-stamped for the sandbox user): ${J}`);default:throw new A$("install_failed",`srt-win install failed (exit ${$.status}): ${J}`)}}function pK($={}){let J=$.srtWin??wJ(),X;try{X=l0(m5($),{timeoutMs:GG($),srtWin:J})}catch(Y){l5(Y)}p5(X);let Q=k5({sublayerGuid:$.sublayerGuid,srtWin:J});return X.status===10?{...Q,cancelled:!0}:Q}async function dK($={}){let J=$.srtWin??wJ(),X;try{X=await t7(m5($),{timeoutMs:GG($),srtWin:J})}catch(Y){l5(Y)}p5(X);let Q=await f5({sublayerGuid:$.sublayerGuid,srtWin:J});return X.status===10?{...Q,cancelled:!0}:Q}function cK($={}){let J=["uninstall"];if($.sublayerGuid)J.push("--sublayer-guid",$.sublayerGuid);if($.keepUser)J.push("--keep-user");let X=l0(J,{timeoutMs:GG($),srtWin:$.srtWin});if(Z(`[Sandbox Windows] uninstall exit=${X.status}: ${X.stderr||X.stdout}`),X.status===10)return{cancelled:!0};if(X.status!==0)throw new A$("uninstall_failed",`srt-win uninstall failed (exit ${X.status}): ${X.stderr||X.stdout}`);return{}}function _9($,J){let X=new Set;for(let Q of $){let Y=JJ(Q),G=LX(Y);if(AX(Y)&&!G){X.add(Y);continue}let W=G?QQ(Y,{caseInsensitive:!0}):[Y];for(let U of W){if(!e$.statSync(U,{throwIfNoEntry:!1})){if(J?.mode==="deny"&&!G)X.add(/[\\/]$/.test(Q)&&!/[\\/]$/.test(U)?U+"\\":U);continue}X.add(U)}}return[...X]}function nK($){for(let J of $.split(/\r?\n/)){let X=J.trim();if(!X.startsWith("{")||!X.includes('"code"'))continue;try{let Q=JSON.parse(X);if(Q.code==="mapped_drive_cwd")return Object.assign(new A$("mapped_drive_cwd",Q.message??"mapped/network-drive working directory","exec"),{drive:Q.drive})}catch{}}return}function WG($){let J=$.holderPid??process.pid,X=JSON.stringify({denyRead:$.denyRead,denyWrite:$.denyWrite}),Q=l0(["acl","stamp","--holder-pid",`${J}`,"--sandbox-user-sid",$.sandboxUserSid],{timeoutMs:60000,stdin:X,srtWin:$.srtWin});if(Z(`[Sandbox Windows] acl stamp exit=${Q.status}: ${Q.stderr||Q.stdout}`),Q.status!==0)throw new A$("acl_stamp_failed",`srt-win acl stamp exited ${Q.status} `+(Q.status===2?"(partial \u2014 some inputs skipped)":"(failed)")+`: ${Q.stderr||Q.stdout}`)}function x9($){let J=$.holderPid??process.pid;try{let X=x5(["acl","restore","--holder-pid",`${J}`,"--sandbox-user-sid",$.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:$.srtWin});if(!X.ok)Z(`[Sandbox Windows] acl restore exited non-zero (per-path outcomes preserved): ${X.stderr}`,{level:"error"});return Array.isArray(X.json)?X.json:[...X.json.paths??[],...X.json.parents??[]]}catch(X){Z(`[Sandbox Windows] acl restore: ${X.message}`,{level:"error"});return}}function UG($){let J=$.holderPid??process.pid,X=JSON.stringify({read:$.read,write:$.write}),Q=l0(["acl","grant","--holder-pid",`${J}`,"--sandbox-user-sid",$.sandboxUserSid],{timeoutMs:60000,stdin:X,srtWin:$.srtWin});if(Z(`[Sandbox Windows] acl grant exit=${Q.status}: ${Q.stderr||Q.stdout}`),Q.status!==0)throw new A$("acl_grant_failed",`srt-win acl grant exited ${Q.status}: ${Q.stderr||Q.stdout}`)}function v9($){let J=$.holderPid??process.pid;try{let X=x5(["acl","revoke","--holder-pid",`${J}`,"--sandbox-user-sid",$.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:$.srtWin});if(!X.ok)Z(`[Sandbox Windows] acl revoke exited non-zero: ${X.stderr}`,{level:"error"});return X.json}catch(X){Z(`[Sandbox Windows] acl revoke: ${X.message}`,{level:"error"});return}}function d5($){let{exe:J,prependArgs:X}=$.srtWin??wJ(),Q=iK(jQ($.httpProxyPort,$.socksProxyPort,$.caCertPath?.replace(/\\/g,"/"),$.proxyAuthToken,void 0,PJ($.commandId??$.command)));delete Q.TMPDIR,delete Q.NO_PROXY,delete Q.no_proxy;let Y=RX({safeDirs:[$.cwd??process.cwd(),...$.allowWrite??[],...$.gitSafeDirectories??[]],schannelCa:$.caCertPath!==void 0,baseEnv:$.setEnvVars}),G=[J,...X,"exec"];if($.quiet!==!1)G.push("--quiet");for(let V of $.denyRead??[])G.push("--deny-read",V);for(let V of $.denyWrite??[])G.push("--deny-write",V);let W={PATH:process.env.PATH,PATHEXT:process.env.PATHEXT,...$.setEnvVars??{},...Q,...Y};for(let[V,q]of Object.entries(W))if(q!==void 0)G.push("--env",`${V}=${q}`);G.push("--");let U=$.binShell??C9(void 0);G.push(U.exe,...U.args,$.command);let M=G.reduce((V,q)=>V+q.length+3,0);if(M>30000)throw new A$("argv_too_long",`Windows sandbox argv is ~${M} chars (CreateProcessW limit is 32 767).`);let O={...process.env,...Q};return{argv:G,env:O}}function iK($){let J={};for(let X of $){let Q=X.indexOf("=");if(Q===-1)continue;J[X.slice(0,Q)]=X.slice(Q+1)}return J}function r7($){let J=$?` --sublayer-guid ${$}`:"";return`Windows sandbox needs a one-time install (one UAC prompt):
69
69
  npx sandbox-runtime windows-install
70
- `+" \u2014 or call installWindowsSandbox(), or run "+`\`srt-win.exe install${t}\` directly.
71
- No logout is needed: the WFP filter keys on the dedicated \`srt-sandbox\` user's SID, so your network is unaffected.`}function Lp(e){try{return{status:"fulfilled",value:e()}}catch(t){return{status:"rejected",reason:t}}}function eh(e,t,n){let r=[],i=[];if(t.status==="rejected")return r.push(`srt-win user status failed: ${t.reason.message}`),{errors:r,warnings:i};let a=t.value;if(!a.provisioned||!a.credPresent)r.push(`Sandbox user is not provisioned (user=${a.provisioned}, cred=${a.credPresent}). `+ec(e));let s=n();if(s.status==="rejected")return r.push(`srt-win wfp status failed: ${s.reason.message}`),{errors:r,warnings:i};let o=s.value;if(o.state==="cannot-read")C(`[Sandbox Windows] wfp status cannot-read (non-elevated): ${o.hint}`);else if(o.state!=="installed"){if(a.provisioned&&a.credPresent)r.push(`WFP filters not installed under sublayer ${e??"(default)"}. `+ec(e))}else if(o.portRange)C(`[Sandbox Windows] WFP installed: ${o.filters} filters, proxy port range ${o.portRange[0]}-${o.portRange[1]}`);return{errors:r,warnings:i}}function th(e={}){let t;try{t=e.srtWin??Bt()}catch(n){return{errors:[n.message],warnings:[]}}return C(`[Sandbox Windows] using srt-win at ${t.exe}`),eh(e.sublayerGuid,Lp(()=>ac({srtWin:t})),()=>Lp(()=>qp({sublayerGuid:e.sublayerGuid,srtWin:t})))}async function dc(e={}){let t;try{t=e.srtWin??Bt()}catch(i){return{errors:[i.message],warnings:[]}}C(`[Sandbox Windows] using srt-win at ${t.exe}`);let[n,r]=await Promise.allSettled([Wi({srtWin:t}),Gp({sublayerGuid:e.sublayerGuid,srtWin:t})]);return eh(e.sublayerGuid,n,()=>r)}import{isIP as QS}from"net";function $i(e){if(e.startsWith("[")){let r=e.indexOf("]");if(r===-1)return{hostPattern:e,port:void 0};let i=e.slice(1,r),a=_t(i)??i,s=e.slice(r+1);if(s==="")return{hostPattern:a,port:void 0};let o=rh(s.startsWith(":")?s.slice(1):"");return o===void 0?{hostPattern:e,port:void 0}:{hostPattern:a,port:o}}let t=e.lastIndexOf(":");if(t===-1)return{hostPattern:e,port:void 0};if(e.indexOf(":")!==t)return{hostPattern:_t(e)??e,port:void 0};let n=rh(e.slice(t+1));if(n===void 0)return{hostPattern:e,port:void 0};return{hostPattern:e.slice(0,t),port:n}}function rh(e){if(!/^[1-9][0-9]{0,4}$/.test(e))return;let t=Number(e);return t>65535?void 0:t}function Hi(e){return $i(e).hostPattern}function Tr(e,t){let n=e.toLowerCase();if(t==="*")return!0;if(t.startsWith("*.")){if(QS(zt(n)))return!1;let r=t.substring(2).toLowerCase();return n.endsWith("."+r)}return n===t.toLowerCase()}function Ki(e,t,n){let{hostPattern:r,port:i}=$i(n);if(i!==void 0&&i!==t)return!1;return Tr(e,r)}function Ns(e,t){let n=t.map(Hi);if(!e.startsWith("*."))return n.some((i)=>Tr(e,i));let r=e.slice(2).toLowerCase();return n.some((i)=>{if(!i.startsWith("*."))return!1;let a=i.slice(2).toLowerCase();return r===a||r.endsWith("."+a)})}function nh(e,t,n,r){if(!Hn(t))return{verdict:"deny",reason:"malformed host"};let i=_t(t)??t;for(let a of e.deniedDomains)if(Ki(i,n,a))return{verdict:"deny",reason:e.deniedDomainReasons?.[a]??"host is on the deny list",rule:a};for(let a of e.allowedDomains)if(Ki(i,n,a))return{verdict:"allow",rule:a};if(!r||e.strictAllowlist)return{verdict:"deny",reason:"host is not on the allow list"};return{verdict:"ask"}}import{EOL as fc}from"os";import{dirname as pc}from"path";var N,ji,zi,Qi,$t,Gr,qi,ih=!1,Ds,Xn,Qr,Me,Xr,Yn,jr,Ls,ah=!1,Xi,vn=new ws,Jt=new kl,Zn=new Nl,Jn=new bl;function dh(){let e=N?.network.brokerForward;if(!e)return[];let t=process.env[e.tokenEnvVar];if(t)for(let n of e.rules){let r=process.env[n.envVar];if(r)Jn.register(r,t,n.hosts,e.url)}return[e.tokenEnvVar]}function YS(e){return N?.network.brokerForward?.rules.some((t)=>t.hosts.includes(e))??!1}var Yi=new Pl;function JS(){if(ih)return;let e=()=>Sc().catch((t)=>{C(`Cleanup failed in registerCleanup ${t}`,{level:"error"})});process.once("exit",e),process.once("SIGINT",e),process.once("SIGTERM",e),ih=!0}var ZS=1024,yn=new Map;function fh(e,t){let n=t?.commandId,r=t?.commandText??e;if(n===void 0||n===r)return;let i=tn(Nt(n));yn.delete(i),yn.set(i,r);while(yn.size>ZS){let a=yn.keys().next().value;if(a===void 0)break;yn.delete(a)}}function sh(e){return yn.get(e)??e}function hc(e,t){let n=t?(()=>{let r=tn(t);return yn.get(r)??Ql(r)})():void 0;if(zn(e,n,N?.ignoreViolations))return;vn.addViolation({line:e,encodedCommand:t,command:n,timestamp:new Date})}function eb(e){try{let t=new URL(e);return`${t.origin}${t.pathname}${t.search?"?\u2026":""}`}catch{let t=e.indexOf("?");return t===-1?e:`${e.slice(0,t)}?\u2026`}}async function oh(e,t,n,r){let i=(s)=>(hc(`deny network-outbound ${t}:${e} (${s})`,r),!1);if(!N)return C("No config available, denying network request"),i("sandbox policy unavailable");let a=nh(N.network,t,e,n!==void 0);if(a.verdict==="allow")return C(`Allowed by config rule: ${t}:${e}`),!0;if(a.verdict==="deny"){if(a.reason==="malformed host")C(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:"error"});else if(a.rule!==void 0)C(`Denied by config rule: ${t}:${e}`);else C(`No matching config rule, denying: ${t}:${e}`);return i(a.reason)}C(`No matching config rule, asking user: ${t}:${e}`);try{if(await n({host:t,port:e}))return C(`User allowed: ${t}:${e}`),!0;return C(`User denied: ${t}:${e}`),i("user denied")}catch(s){return C(`Error in permission callback: ${s}`,{level:"error"}),i("permission prompt failed")}}var Os=!1;function tb(e){Os=e}function rb(){if(!Os&&!N?.credentials)return;return(e,t)=>{if(!N?.credentials)return;Jt.substituteInHeaders(e,t,Tr)}}function nb(){if(!Os&&!N?.credentials)return;return(e)=>N?.credentials?Jt.sentinelsForHost(e,Tr):void 0}function ib(){if(!Os&&!N?.credentials)return;return(e,t,n,r)=>!N?.credentials?void 0:zf(Zn,N?.credentials?.sigv4,Tr)(e,t,n,r)}function ab(e){if(!N?.network.mitmProxy)return;let{socketPath:t,domains:n}=N.network.mitmProxy,r=_t(e)??e;for(let i of n)if(Tr(r,i))return C(`Host ${e} matches MITM pattern ${i}`),t;return}function sb(e){let t=N?.network.tlsTerminate?.excludeDomains;if(!t?.length)return!0;let n=_t(e)??e;if(YS(n))return!0;for(let r of t){if(!Tr(n,r))continue;C(`Host ${e} matches tlsTerminate.excludeDomains pattern ${r}; skipping TLS termination`);let i=Jt.namesInjectableAt(n,Tr);if(i.length>0)C(`tlsTerminate.excludeDomains: masked credential(s) ${i.join(", ")} are configured for injection at ${e}, but its connections are not terminated, so the upstream will receive the placeholder`,{level:"error"});return!1}return!0}async function ob(e,t){let n=rb(),r=nb();ji=wf({filter:(o,l,c,u)=>oh(o,l,e,u),getMitmSocketPath:ab,mitmCA:Me,shouldTerminateTLS:sb,filterRequest:N?.network.filterRequest,onFilterRequestDenied:({method:o,url:l,reason:c,encodedCommand:u})=>{hc(`deny http-request ${o} ${eb(l)} (${c})`,u)},mutateHeaders:n,mutateHeadersPlaintext:N?.credentials?.allowPlaintextInject?n:void 0,getBrokerForward:(o,l)=>N?.network.brokerForward?Jn.forwardFor(o,l):void 0,getBodySubstitutions:r,getBodySubstitutionsPlaintext:N?.credentials?.allowPlaintextInject?r:void 0,planSigv4:ib(),parentProxy:Qr,proxyAuthToken:Xr}),zi=Nf({filter:(o,l,c)=>oh(o,l,e,c),parentProxy:Qr,proxyAuthToken:Xr,probeUnauthenticated:async(o,l)=>{if(!N)return{};let c=_t(l)??l;for(let u of N.network.deniedDomains)if(Ki(c,o,u)){let d=N.network.deniedDomainReasons?.[u]??"host is on the deny list";return hc(`deny network-outbound ${l}:${o} (${d})`,void 0),{deniedReason:d}}return{}}}),Qi=Of({httpServer:ji,handleSocksConnection:(o)=>zi.handleConnection(o),httpBackendPortRange:t});let i=Qi,a=await i.listenHttpBackend();await us(i.server,(o)=>i.server.listen(o,"127.0.0.1"),t,a!==void 0?new Set([a]):new Set);let s=i.getPort();if(s===void 0)throw Error("Failed to get mux proxy server port");return i.unref(),C(`Mux proxy (HTTP+SOCKS) listening on localhost:${s}`),s}async function lb(e,t,n=!1){if(Gr){await Gr;return}if(N=e,Qr=gl(e.network.parentProxy),Qr)C(`Parent proxy configured: http=${vl(Qr.httpUrl)} https=${vl(Qr.httpsUrl)}`);if(e.network.tlsTerminate&&e.network.mitmProxy)throw Error("network.tlsTerminate and network.mitmProxy are mutually exclusive");let r=e.network.tlsTerminate,i=Ne()==="windows"&&r!==void 0&&!r.caCertPath&&!r.caKeyPath;if(Me=r&&!i?cl(r):void 0,Me&&e.runAsHostUid!==void 0&&Ne()==="linux"){if(zr.chmodSync(pc(Me.trustBundlePath),457),zr.chmodSync(Me.trustBundlePath,420),Me.ephemeral)zr.chmodSync(pc(Me.certPath),457),zr.chmodSync(Me.certPath,420)}let a=await gh();if(a.errors.length>0)throw Error(`Sandbox dependencies not available: ${a.errors.join(", ")}`);if(n&&Ne()==="macos")Ds=Rp(vn.addViolation.bind(vn),N.ignoreViolations,sh),C("Started macOS sandbox log monitor");if(n&&Ne()==="linux")Xn=Np(vn.addViolation.bind(vn),{allowWritePaths:[...Cn(e.runAsHostHome),...N.filesystem.allowWrite],denyWritePaths:N.filesystem.denyWrite,ignoreViolations:N.ignoreViolations,resolveCommandText:sh,consumerUid:e.runAsHostUid,consumerGid:e.runAsHostGid}),Xn.ready,C("Started Linux seccomp violation monitor");if(JS(),Ne()==="windows"){Xi=Bt(e.windows?.srtWin);let s=Xi,o=await Wi({srtWin:s});if(!o.provisioned||!o.credPresent)throw N=void 0,new xe("not_provisioned",`Windows sandbox user is not provisioned (user=${o.provisioned}, cred=${o.credPresent}). Run \`npx sandbox-runtime windows-install\` (one UAC prompt) to provision it.`);if(!ah){try{await ic({proxyPortRange:e.windows?.proxyPortRange,srtWin:s})}catch(l){throw N=void 0,l}ah=!0}if(i&&r)try{let l=await oc({status:o,srtWin:s});Me=cl({caCertPem:l.certPem,caKeyPem:l.keyPem,caCertPath:l.certPath,caKeyPath:l.keyPath,extraCaCertPaths:r.extraCaCertPaths})}catch(l){throw N=void 0,l}if(r&&Me&&!i){let l=sc(o),c=$n(Me.certPem);if(!l)throw N=void 0,new xe("trust_ca_not_installed",`tlsTerminate on Windows requires the sandbox to be installed with this CA (thumb=${c}): run \`srt-win user trust-ca ${Me.certPath}\`. Per-exec installs into the sandbox user's Root store are not supported.`);if(l.thumb!==c)throw N=void 0,new xe("trust_ca_thumbprint_mismatch",`tlsTerminate on Windows: the sandbox's installed CA (thumb=${l.thumb}) doesn't match this session's CA (thumb=${c}). Run \`srt-win user trust-ca ${Me.certPath}\` to update it.`)}try{let l=pb(e);if(Me)l.grantRead.push(pc(Me.trustBundlePath));if(!o.sid)throw Error("sandbox user SID missing from `srt-win user status` (provisioned but in an inconsistent state)");let c=o.sid;if(jr=c,l.grantRead.length>0||l.grantWrite.length>0)uc({sandboxUserSid:c,read:l.grantRead,write:l.grantWrite,srtWin:s});if(l.denyRead.length>0||l.denyWrite.length>0)cc({sandboxUserSid:c,denyRead:l.denyRead,denyWrite:l.denyWrite,srtWin:s});if(l.grantRead.length>0||l.grantWrite.length>0||l.denyRead.length>0||l.denyWrite.length>0)Yn=l,C(`[Sandbox Windows] fs applied: ${l.grantWrite.length} grantWrite, ${l.grantRead.length} grantRead, ${l.denyRead.length} denyRead, ${l.denyWrite.length} denyWrite`);Ls=yh(e)}catch(l){if(jr)Ps({sandboxUserSid:jr,srtWin:s}),Bs({sandboxUserSid:jr,srtWin:s});throw jr=void 0,N=void 0,l}}Gr=(async()=>{try{let s=Ne()==="windows"?N.windows?.proxyPortRange??As:void 0;Xr=N.network.httpProxyPort!==void 0?void 0:XS(16).toString("hex");let l=N.network.httpProxyPort===void 0||N.network.socksProxyPort===void 0?await ob(t,s):void 0,c=N.network.httpProxyPort??l,u=N.network.socksProxyPort??l;if(Me&&l!==void 0&&Ne()==="windows")Me.crlUrl=`http://127.0.0.1:${l}${Za}`;if(N.network.httpProxyPort!==void 0)C(`Using external HTTP proxy on port ${c}`);if(N.network.socksProxyPort!==void 0)C(`Using external SOCKS proxy on port ${u}`);let d;if(Ne()==="linux")d=await bp(c,u,N.socatPath,N.runAsHostUid,N.runAsHostGid);let f={httpProxyPort:c,socksProxyPort:u,linuxBridge:d};return $t=f,C("Network infrastructure initialized"),f}catch(s){throw Gr=void 0,$t=void 0,Sc().catch((o)=>{C(`Cleanup failed in initializationPromise ${o}`,{level:"error"})}),s}})(),await Gr}function ph(){let e=Ne();if(e==="linux")return Qs()!=="1";return e==="macos"||e==="windows"}function cb(){return N!==void 0}function hh(e){if(!ph())return{done:{errors:["Unsupported platform"],warnings:[]}};let t=[],n=[],r=Ne();if(r==="linux"){let i=e??N?.ripgrep??{command:"rg"};if(Cr(i.command)===null)t.push(`ripgrep (${i.command}) not found`);let a=Sp({seccompConfig:N?.seccomp,bwrapPath:N?.bwrapPath,socatPath:N?.socatPath});t.push(...a.errors),n.push(...a.warnings)}else if(r==="windows"){let i;try{i=Bt(N?.windows?.srtWin)}catch(a){return t.push(a.message),{done:{errors:t,warnings:n}}}return{windows:{sublayerGuid:N?.windows?.sublayerGuid??N?.windows?.wfpSublayerGuid,srtWin:i}}}return{done:{errors:t,warnings:n}}}function ub(e){let t=hh(e);if("done"in t)return t.done;return th(t.windows)}async function gh(e){let t=hh(e);if("done"in t)return t.done;return dc(t.windows)}function mc(e,t){if(!e)return{denyReadPaths:[],unsetEnvVars:[],setEnvVars:{},maskedFileBinds:[],maskedFileStoreDir:void 0};let n=Us(e),r=[...new Set((t??[]).map(Hi))],i=[];for(let u of e.envVars??[])if(u.mode==="deny")i.push(u.name);let{setEnvVars:a,degradeToUnsetNames:s}=Hf(e.envVars??[],r,Jt);i.push(...s),jf(e.envVars??[],e.awsPairs,r,a,Zn);let o=e.files??[],{binds:l,degradeToDenyPaths:c}=$f(o,r,Jt,Yi);return{denyReadPaths:[...new Set([...n,...c])],unsetEnvVars:[...new Set(i)],setEnvVars:a,maskedFileBinds:l,maskedFileStoreDir:Yi.dirPath}}function Us(e){let t=e?.files??[];return[...new Set(t.filter((n)=>n.mode==="deny").map((n)=>n.path))]}function mh(e,t){return[...new Set([...e,...t.denyReadPaths])]}function db(){if(!N||N.filesystem.disabled)return{denyOnly:[],allowWithinDeny:[]};let e=mh(N.filesystem.denyRead,mc(N.credentials,N.network.allowedDomains)),t=[];for(let r of e){let i=yr(r);if(Ne()==="linux"&&xt(i)){let a=rn(r);C(`[Sandbox] Expanded glob pattern "${r}" to ${a.length} paths on Linux`),t.push(...a)}else t.push(i)}let n=[];for(let r of N.filesystem.allowRead??[]){let i=yr(r);if(Ne()==="linux"&&xt(i)){let a=rn(r);C(`[Sandbox] Expanded allowRead glob pattern "${r}" to ${a.length} paths on Linux`),n.push(...a)}else n.push(i)}return{denyOnly:t,allowWithinDeny:n}}function fb(){if(!N)return{allowOnly:Cn(),denyWithinAllow:[]};if(N.filesystem.disabled)return{allowOnly:["/"],denyWithinAllow:[]};let e=N.filesystem.allowWrite.map((r)=>yr(r)).filter((r)=>{if(Ne()==="linux"&&xt(r))return C(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0}),t=N.filesystem.denyWrite.map((r)=>yr(r)).filter((r)=>{if(Ne()==="linux"&&xt(r))return C(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0});return{allowOnly:[...Cn(gc()),...e],denyWithinAllow:t}}function pb(e){let t=e.filesystem;if(t?.disabled)return{grantRead:[],grantWrite:[],denyRead:[],denyWrite:[]};let n=Rs,r=n([...new Set([...t?.denyRead??[],...Us(e.credentials)])],{mode:"deny"}),i=n(t?.denyWrite??[],{mode:"deny"});return{grantRead:n(t?.allowRead??[],{mode:"grant"}),grantWrite:n(t?.allowWrite??[],{mode:"grant"}),denyRead:r,denyWrite:i}}function yh(e){return{disabled:e.filesystem.disabled??!1,denyRead:[...e.filesystem.denyRead],denyWrite:[...e.filesystem.denyWrite],allowRead:[...e.filesystem.allowRead??[]],allowWrite:[...e.filesystem.allowWrite],credFiles:Us(e.credentials)}}function Gi(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every((r)=>n.has(r))}function hb(e,t){return e.disabled===t.disabled&&Gi(e.denyRead,t.denyRead)&&Gi(e.denyWrite,t.denyWrite)&&Gi(e.allowRead,t.allowRead)&&Gi(e.allowWrite,t.allowWrite)&&Gi(e.credFiles,t.credFiles)}function gb(e){return Ls!==void 0&&hb(Ls,yh(e))}function mb(){if(!N)return{};let e=N.network.allowedDomains,t=N.network.deniedDomains;return{allowedHosts:e,...t.length>0&&{deniedHosts:t}}}function vh(){return N?.network?.allowUnixSockets}function lh(){return N?.network?.allowAllUnixSockets}function xh(){return N?.network?.allowLocalBinding}function Sh(){return N?.network?.allowMachLookup}function bh(){return N?.ignoreViolations}function Ch(){return N?.enableWeakerNestedSandbox}function yb(){return N?.runAsUid}function vb(){return N?.runAsGid}function xb(){return N?.runAsHostUid}function Sb(){return N?.runAsHostGid}function gc(){return N?.runAsHostHome}function bb(){return N?.runAsHostUser}function Cb(){return N?.enableWeakerNetworkIsolation}function Eb(){return N?.allowAppleEvents}function wb(){return N?.ripgrep??{command:"rg"}}function Tb(){return N?.mandatoryDenySearchDepth??3}function ch(){return N?.filesystem?.allowGitConfig??!1}function Eh(e){return[...N?.git?.safeDirectories??[],...e?.git?.safeDirectories??[]]}function Ab(){return N?.seccomp}function _b(){return Xr}function yc(){return $t?.httpProxyPort}function vc(){return $t?.socksProxyPort}function wh(){return $t?.linuxBridge?.httpSocketPath}function Th(){return $t?.linuxBridge?.socksSocketPath}async function xc(){if(!N)return!1;if(Gr)try{return await Gr,!0}catch{return!1}return $t!==void 0}async function Ah(e,t,n,r,i){let a=Ne(),s=i?.commandId;fh(e,i);let o=n?.filesystem!==void 0?n.filesystem.disabled??!1:N?.filesystem.disabled??!1,l=mc(n?.credentials??N?.credentials,n?.network?.allowedDomains??N?.network?.allowedDomains);l.unsetEnvVars.push(...dh());let c,u;if(!o){let x=(R)=>R.map((M)=>yr(M)).filter((M)=>{if(Ne()==="linux"&&xt(M))return C(`[Sandbox] Skipping glob write pattern on Linux: ${M}`),!1;return!0}),b=x(n?.filesystem?.allowWrite??N?.filesystem.allowWrite??[]);c={allowOnly:[...Cn(n?.runAsHostHome??gc()),...b],denyWithinAllow:x(n?.filesystem?.denyWrite??N?.filesystem.denyWrite??[])};let A=mh(n?.filesystem?.denyRead??N?.filesystem.denyRead??[],l),E=[];for(let R of A){let M=yr(R);if(Ne()==="linux"&&xt(M))E.push(...rn(R));else E.push(M)}let k=n?.filesystem?.allowRead??N?.filesystem.allowRead??[],I=[];for(let R of k){let M=yr(R);if(Ne()==="linux"&&xt(M))I.push(...rn(R));else I.push(M)}if(Me)I.push(Me.certPath,Me.trustBundlePath);u={denyOnly:E,allowWithinDeny:I}}let d=n?.network?.allowedDomains!==void 0||N?.network?.allowedDomains!==void 0,f=d,y=d;if(y)await xc();let p=n?.allowPty??N?.allowPty,v=Eh(n);switch(a){case"macos":return Ip({command:e,commandId:s,needsNetworkRestriction:f,httpProxyPort:y?yc():void 0,socksProxyPort:y?vc():void 0,proxyAuthToken:y?Xr:void 0,caCertPath:Me?.trustBundlePath,readConfig:u,writeConfig:c,unsetEnvVars:l.unsetEnvVars,setEnvVars:l.setEnvVars,maskedFileBinds:l.maskedFileBinds,allowUnixSockets:vh(),allowAllUnixSockets:lh(),allowLocalBinding:xh(),allowMachLookup:Sh(),ignoreViolations:bh(),allowPty:p,allowGitConfig:ch(),gitSafeDirectories:v,enableWeakerNetworkIsolation:Cb(),allowAppleEvents:Eb(),binShell:t});case"linux":return Ep({command:e,commandId:s,needsNetworkRestriction:f,httpSocketPath:y?wh():void 0,socksSocketPath:y?Th():void 0,httpProxyPort:y?$t?.httpProxyPort:void 0,socksProxyPort:y?$t?.socksProxyPort:void 0,proxyAuthToken:y?Xr:void 0,caCertPath:Me?.trustBundlePath,readConfig:u,writeConfig:c,unsetEnvVars:l.unsetEnvVars,setEnvVars:l.setEnvVars,maskedFileBinds:l.maskedFileBinds,maskedFileStoreDir:l.maskedFileStoreDir,enableWeakerNestedSandbox:Ch(),runAsUid:yb(),runAsGid:vb(),runAsHostUid:xb(),runAsHostGid:Sb(),runAsHostHome:gc(),runAsHostUser:bb(),setprivPath:"/usr/bin/setpriv",allowAllUnixSockets:lh(),binShell:t,ripgrepConfig:wb(),mandatoryDenySearchDepth:Tb(),allowGitConfig:ch(),gitSafeDirectories:v,seccompConfig:Ab(),bwrapPath:N?.bwrapPath,socatPath:N?.socatPath,observeSocketPath:Xn?.observeSocketPath,startFd:i?.startFd,argvCommand:i?.argvCommand,abortSignal:r});case"windows":throw Error("wrapWithSandbox() returns a shell string and is not supported on Windows. Use SandboxManager.wrapWithSandboxArgv() and spawn the result with {shell: false}.");default:throw Error(`Sandbox configuration is not supported on platform: ${a}`)}}async function kb(e,t,n,r,i,a){if(Ne()==="windows"){let c=n?.network?.allowedDomains!==void 0||N?.network?.allowedDomains!==void 0;if(c)await xc();let u=mc(n?.credentials??N?.credentials,n?.network?.allowedDomains??N?.network?.allowedDomains);u.unsetEnvVars.push(...dh());let d=n?.filesystem,f=[],y=[];if(!d?.disabled){if(d?.allowRead?.length||d?.allowWrite?.length)throw Error("Per-exec filesystem.allowRead/allowWrite is not supported "+"on Windows \u2014 `srt-win exec` only exposes per-exec "+"denies. Set them at the session level (initialize()).");let p=[...d?.denyRead??[],...Us(n?.credentials)],v=d?.denyWrite??[];if(p.length>0||v.length>0){let x=new Set(Yn?.denyRead??[]),b=new Set(Yn?.denyWrite??[]),A=Rs;f=A(p,{mode:"deny"}).filter((E)=>!x.has(E)),y=A(v,{mode:"deny"}).filter((E)=>!x.has(E)&&!b.has(E))}}return fh(e,a),Zp({command:e,commandId:a?.commandId,httpProxyPort:c?yc():void 0,socksProxyPort:c?vc():void 0,proxyAuthToken:c?Xr:void 0,setEnvVars:u.setEnvVars,denyRead:f,denyWrite:y,cwd:i,allowWrite:Yn?.grantWrite,gitSafeDirectories:Eh(n),caCertPath:Me?.trustBundlePath,binShell:_s(t),srtWin:n?.windows?.srtWin?Bt(n.windows.srtWin):Xi??Bt(N?.windows?.srtWin)})}if(typeof t==="object")throw Error("binShell object form is Windows-only; pass a shell path string on macOS/Linux");let o=await Ah(e,t,n,r,a);return{argv:[t??"/bin/bash","-c",o],env:process.env}}function Ib(){return N}function Rb(){Jt.clear(),Zn.clear(),Jn.clear(),Yi.dispose()}function Bb(e){if(Ne()==="windows"&&N&&!gb(e))C("[Sandbox Windows] updateConfig: the resolved file-access set "+"(filesystem.* \u222A credentials.files) changed but the ACL "+"stamp/grant is session-wide \u2014 call reset() then initialize() "+"to apply. The previously-applied set stays in effect.",{level:"warn"});let{filterRequest:t,...n}=e.network;N=structuredClone({...e,network:n}),N.network.filterRequest=t,Qr=gl(e.network.parentProxy),C("Sandbox configuration updated")}function Pb(){Es()}var Nb=1500;function uh(e,t){if(!e.pid||e.exitCode!==null||e.signalCode!==null)return Promise.resolve();try{process.kill(e.pid,"SIGTERM"),C(`Sent SIGTERM to ${t} bridge process`)}catch(n){if(n.code!=="ESRCH")C(`Error killing ${t} bridge: ${n}`,{level:"error"});return Promise.resolve()}return new Promise((n)=>{let r=!1,i=()=>{if(r)return;r=!0,clearTimeout(a),n()};e.once("exit",()=>{C(`${t} bridge process exited`),i()});let a=setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null){C(`${t} bridge did not exit, forcing SIGKILL`,{level:"warn"});try{if(e.pid)process.kill(e.pid,"SIGKILL")}catch{}}i()},Nb);a.unref?.()})}function Db(e){return new Promise((t)=>{if(typeof e.closeAllConnections==="function")e.closeAllConnections();e.close((n)=>{if(n&&n.message!=="Server is not running.")C(`Error closing HTTP proxy server: ${n.message}`,{level:"error"});t()})})}async function Lb(){if(Yn&&jr){let t=jr,n=Xi,r=new Set(["revoked","stillHeld","restored","alreadyOriginal"]),i=(a,s)=>{if(!r.has(s.status))C(`[Sandbox Windows] ${a}: '${s.path}' ${s.status} \u2014 `+"ACE may be left in place; resolve and run `srt-win acl recover` to clear",{level:"warn"})};for(let a of Ps({sandboxUserSid:t,srtWin:n})??[])i("grant revoke",a);for(let a of Bs({sandboxUserSid:t,srtWin:n})??[])i("deny restore",a)}if(Yn=void 0,jr=void 0,Ls=void 0,Xi=void 0,Es({force:!0}),Ds)Ds(),Ds=void 0;if(Xn)Xn.stop(),Xn=void 0;if($t?.linuxBridge){let{httpSocketPath:t,socksSocketPath:n,httpBridgeProcess:r,socksBridgeProcess:i}=$t.linuxBridge;if(await Promise.all([uh(r,"HTTP"),uh(i,"SOCKS")]),t)try{zr.rmSync(t,{force:!0}),C("Cleaned up HTTP socket")}catch(a){C(`HTTP socket cleanup error: ${a}`,{level:"error"})}if(n)try{zr.rmSync(n,{force:!0}),C("Cleaned up SOCKS socket")}catch(a){C(`SOCKS socket cleanup error: ${a}`,{level:"error"})}}let e=[];if(Me)e.push(Yd(Me));if(Qi)e.push(Qi.close().catch((t)=>{C(`Error closing mux proxy server: ${t.message}`,{level:"error"})}));if(ji)e.push(Db(ji));if(zi){let t=zi.close().catch((n)=>{C(`Error closing SOCKS proxy server: ${n.message}`,{level:"error"})});e.push(t)}await Promise.all(e),Qi=void 0,ji=void 0,Xr=void 0,zi=void 0,$t=void 0,Gr=void 0,Qr=void 0,Me=void 0,Jt.clear(),Zn.clear(),Yi.dispose()}async function Sc(){if(qi)return qi;qi=Lb();try{await qi}finally{qi=void 0}}function Ob(){return vn}function Ub(e,t){if(!N)return t;let n=vn.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=fc+"<sandbox_violations>"+fc;for(let i of n)r+=i.line+fc;return r+="</sandbox_violations>",r}function Vb(){if(Ne()!=="linux"||!N||N.filesystem.disabled)return[];let e=[],t=[...N.filesystem.allowWrite,...N.filesystem.denyWrite];for(let n of t){let r=yr(n);if(xt(r))e.push(n)}return e}var Fb={initialize:lb,isSupportedPlatform:ph,isSandboxingEnabled:cb,checkDependencies:ub,checkDependenciesAsync:gh,getFsReadConfig:db,getFsWriteConfig:fb,getNetworkRestrictionConfig:mb,getAllowUnixSockets:vh,getAllowLocalBinding:xh,getAllowMachLookup:Sh,getIgnoreViolations:bh,getEnableWeakerNestedSandbox:Ch,getProxyPort:yc,getProxyAuthToken:_b,getSocksProxyPort:vc,getLinuxHttpSocketPath:wh,getLinuxSocksSocketPath:Th,waitForNetworkInitialization:xc,wrapWithSandbox:Ah,wrapWithSandboxArgv:kb,cleanupAfterCommand:Pb,beginCredentialLease:()=>{Jt.beginLease(),Jn.beginLease()},endCredentialLease:()=>Object.assign(Jt.endLease(),{brokerForward:Jn.endLease()}),releaseCredentialLease:(e)=>{Jn.release(e.brokerForward??[]),Zn.forget(Jt.release(e))},reset:Sc,getMitmCA:()=>Me,getSentinelRegistry:()=>Jt,getAwsPairRegistry:()=>Zn,getMaskedFileStore:()=>Yi,getSandboxViolationStore:Ob,annotateStderrWithSandboxFailures:Ub,getLinuxGlobPatternWarnings:Vb,getConfig:Ib,updateConfig:Bb,clearMaskedCredentials:Rb,setLiveCredentialInjectors:tb};import{isIP as pC}from"net";import{isAbsolute as hC}from"path";var Ae;(function(e){e.assertEqual=(i)=>{};function t(i){}e.assertIs=t;function n(i){throw Error()}e.assertNever=n,e.arrayToEnum=(i)=>{let a={};for(let s of i)a[s]=s;return a},e.getValidEnumValues=(i)=>{let a=e.objectKeys(i).filter((o)=>typeof i[i[o]]!=="number"),s={};for(let o of a)s[o]=i[o];return e.objectValues(s)},e.objectValues=(i)=>e.objectKeys(i).map(function(a){return i[a]}),e.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{let a=[];for(let s in i)if(Object.prototype.hasOwnProperty.call(i,s))a.push(s);return a},e.find=(i,a)=>{for(let s of i)if(a(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,a=" | "){return i.map((s)=>typeof s==="string"?`'${s}'`:s).join(a)}e.joinValues=r,e.jsonStringifyReplacer=(i,a)=>{if(typeof a==="bigint")return a.toString();return a}})(Ae||(Ae={}));var _h;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(_h||(_h={}));var z=Ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ar=(e)=>{switch(typeof e){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(e)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":if(Array.isArray(e))return z.array;if(e===null)return z.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return z.promise;if(typeof Map<"u"&&e instanceof Map)return z.map;if(typeof Set<"u"&&e instanceof Set)return z.set;if(typeof Date<"u"&&e instanceof Date)return z.date;return z.object;default:return z.unknown}};var P=Ae.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Pt extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},r=(i)=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let s=n,o=0;while(o<a.path.length){let l=a.path[o];if(o!==a.path.length-1)s[l]=s[l]||{_errors:[]};else s[l]=s[l]||{_errors:[]},s[l]._errors.push(t(a));s=s[l],o++}}};return r(this),n}static assert(e){if(!(e instanceof Pt))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ae.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Pt.create=(e)=>new Pt(e);var Mb=(e,t)=>{let n;switch(e.code){case P.invalid_type:if(e.received===z.undefined)n="Required";else n=`Expected ${e.expected}, received ${e.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Ae.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ae.joinValues(e.keys,", ")}`;break;case P.invalid_union:n="Invalid input";break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ae.joinValues(e.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${Ae.joinValues(e.options)}, received '${e.received}'`;break;case P.invalid_arguments:n="Invalid function arguments";break;case P.invalid_return_type:n="Invalid function return type";break;case P.invalid_date:n="Invalid date";break;case P.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)n=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)n=`Invalid input: must end with "${e.validation.endsWith}"`;else Ae.assertNever(e.validation);else if(e.validation!=="regex")n=`Invalid ${e.validation}`;else n="Invalid";break;case P.too_small:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else n="Invalid input";break;case P.too_big:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else n="Invalid input";break;case P.custom:n="Invalid input";break;case P.invalid_intersection_types:n="Intersection results could not be merged";break;case P.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case P.not_finite:n="Number must be finite";break;default:n=t.defaultError,Ae.assertNever(e)}return{message:n}},Yr=Mb;var Wb=Yr;function Ji(){return Wb}var Vs=(e)=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],s={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let o="",l=r.filter((c)=>!!c).slice().reverse();for(let c of l)o=c(s,{data:t,defaultError:o}).message;return{...i,path:a,message:o}};function q(e,t){let n=Ji(),r=Vs({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Yr?void 0:Yr].filter((i)=>!!i)});e.common.issues.push(r)}class vt{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let n=[];for(let r of t){if(r.status==="aborted")return oe;if(r.status==="dirty")e.dirty();n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let r of t){let i=await r.key,a=await r.value;n.push({key:i,value:a})}return vt.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:i,value:a}=r;if(i.status==="aborted")return oe;if(a.status==="aborted")return oe;if(i.status==="dirty")e.dirty();if(a.status==="dirty")e.dirty();if(i.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet))n[i.value]=a.value}return{status:e.value,value:n}}}var oe=Object.freeze({status:"aborted"}),ei=(e)=>({status:"dirty",value:e}),wt=(e)=>({status:"valid",value:e}),bc=(e)=>e.status==="aborted",Cc=(e)=>e.status==="dirty",xn=(e)=>e.status==="valid",Zi=(e)=>typeof Promise<"u"&&e instanceof Promise;var J;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(J||(J={}));class Zt{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var kh=(e,t)=>{if(xn(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Pt(e.common.issues);return this._error=n,this._error}}}};function pe(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};return{errorMap:(s,o)=>{let{message:l}=e;if(s.code==="invalid_enum_value")return{message:l??o.defaultError};if(typeof o.data>"u")return{message:l??r??o.defaultError};if(s.code!=="invalid_type")return{message:o.defaultError};return{message:l??n??o.defaultError}},description:i}}class Se{get description(){return this._def.description}_getType(e){return Ar(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ar(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vt,ctx:{common:e.parent.common,data:e.data,parsedType:Ar(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Zi(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ar(e)},r=this._parseSync({data:e,path:n.path,parent:n});return kh(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ar(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return xn(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((n)=>xn(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ar(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(Zi(r)?r:Promise.resolve(r));return kh(n,i)}refine(e,t){let n=(r)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(r);else return t};return this._refinement((r,i)=>{let a=e(r),s=()=>i.addIssue({code:P.custom,...n(r)});if(typeof Promise<"u"&&a instanceof Promise)return a.then((o)=>{if(!o)return s(),!1;else return!0});if(!a)return s(),!1;else return!0})}refinement(e,t){return this._refinement((n,r)=>{if(!e(n))return r.addIssue(typeof t==="function"?t(n,r):t),!1;else return!0})}_refinement(e){return new gr({schema:this,typeName:le.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return hr.create(this,this._def)}nullable(){return Jr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pr.create(this)}promise(){return si.create(this,this._def)}or(e){return ia.create([this,e],this._def)}and(e){return aa.create(this,e,this._def)}transform(e){return new gr({...pe(this._def),schema:this,typeName:le.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new ca({...pe(this._def),innerType:this,defaultValue:t,typeName:le.ZodDefault})}brand(){return new Ac({typeName:le.ZodBranded,type:this,...pe(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new ua({...pe(this._def),innerType:this,catchValue:t,typeName:le.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return qs.create(this,e)}readonly(){return da.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var $b=/^c[^\s-]{8,}$/i,Hb=/^[0-9a-z]+$/,Kb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qb=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Gb=/^[a-z0-9_-]{21}$/i,jb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zb=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Qb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ec,Yb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Jb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Zb=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,eC=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rh="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",nC=new RegExp(`^${Rh}$`);function Bh(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function iC(e){return new RegExp(`^${Bh(e)}$`)}function aC(e){let t=`${Rh}T${Bh(e)}`,n=[];if(n.push(e.local?"Z?":"Z"),e.offset)n.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function sC(e,t){if((t==="v4"||!t)&&Yb.test(e))return!0;if((t==="v6"||!t)&&Zb.test(e))return!0;return!1}function oC(e,t){if(!jb.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));if(typeof i!=="object"||i===null)return!1;if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&i.alg!==t)return!1;return!0}catch{return!1}}function lC(e,t){if((t==="v4"||!t)&&Jb.test(e))return!0;if((t==="v6"||!t)&&eC.test(e))return!0;return!1}class kr extends Se{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==z.string){let i=this._getOrReturnCtx(e);return q(i,{code:P.invalid_type,expected:z.string,received:i.parsedType}),oe}let n=new vt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.length<i.value)r=this._getOrReturnCtx(e,r),q(r,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="max"){if(e.data.length>i.value)r=this._getOrReturnCtx(e,r),q(r,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="length"){let a=e.data.length>i.value,s=e.data.length<i.value;if(a||s){if(r=this._getOrReturnCtx(e,r),a)q(r,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(s)q(r,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});n.dirty()}}else if(i.kind==="email"){if(!Qb.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"email",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="emoji"){if(!Ec)Ec=new RegExp(Xb,"u");if(!Ec.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"emoji",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="uuid"){if(!qb.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"uuid",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="nanoid"){if(!Gb.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"nanoid",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cuid"){if(!$b.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"cuid",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cuid2"){if(!Hb.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"cuid2",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="ulid"){if(!Kb.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"ulid",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),q(r,{validation:"url",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"regex",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="trim")e.data=e.data.trim();else if(i.kind==="includes"){if(!e.data.includes(i.value,i.position))r=this._getOrReturnCtx(e,r),q(r,{code:P.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()}else if(i.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(i.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(i.kind==="startsWith"){if(!e.data.startsWith(i.value))r=this._getOrReturnCtx(e,r),q(r,{code:P.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()}else if(i.kind==="endsWith"){if(!e.data.endsWith(i.value))r=this._getOrReturnCtx(e,r),q(r,{code:P.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()}else if(i.kind==="datetime"){if(!aC(i).test(e.data))r=this._getOrReturnCtx(e,r),q(r,{code:P.invalid_string,validation:"datetime",message:i.message}),n.dirty()}else if(i.kind==="date"){if(!nC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{code:P.invalid_string,validation:"date",message:i.message}),n.dirty()}else if(i.kind==="time"){if(!iC(i).test(e.data))r=this._getOrReturnCtx(e,r),q(r,{code:P.invalid_string,validation:"time",message:i.message}),n.dirty()}else if(i.kind==="duration"){if(!zb.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"duration",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="ip"){if(!sC(e.data,i.version))r=this._getOrReturnCtx(e,r),q(r,{validation:"ip",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="jwt"){if(!oC(e.data,i.alg))r=this._getOrReturnCtx(e,r),q(r,{validation:"jwt",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cidr"){if(!lC(e.data,i.version))r=this._getOrReturnCtx(e,r),q(r,{validation:"cidr",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="base64"){if(!tC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"base64",code:P.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="base64url"){if(!rC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"base64url",code:P.invalid_string,message:i.message}),n.dirty()}else Ae.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement((r)=>e.test(r),{validation:t,code:P.invalid_string,...J.errToObj(n)})}_addCheck(e){return new kr({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...J.errToObj(e)})}url(e){return this._addCheck({kind:"url",...J.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...J.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...J.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...J.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...J.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...J.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...J.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...J.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...J.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...J.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new kr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new kr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new kr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}kr.create=(e)=>new kr({checks:[],typeName:le.ZodString,coerce:e?.coerce??!1,...pe(e)});function cC(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,a=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return a%s/10**i}class ri extends Se{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==z.number){let i=this._getOrReturnCtx(e);return q(i,{code:P.invalid_type,expected:z.number,received:i.parsedType}),oe}let n=void 0,r=new vt;for(let i of this._def.checks)if(i.kind==="int"){if(!Ae.isInteger(e.data))n=this._getOrReturnCtx(e,n),q(n,{code:P.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()}else if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:P.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:P.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(cC(e.data,i.value)!==0)n=this._getOrReturnCtx(e,n),q(n,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(e.data))n=this._getOrReturnCtx(e,n),q(n,{code:P.not_finite,message:i.message}),r.dirty()}else Ae.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(e,t,n,r){return new ri({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:J.toString(r)}]})}_addCheck(e){return new ri({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:J.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:J.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&Ae.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}return Number.isFinite(t)&&Number.isFinite(e)}}ri.create=(e)=>new ri({checks:[],typeName:le.ZodNumber,coerce:e?.coerce||!1,...pe(e)});class ni extends Se{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let n=void 0,r=new vt;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:P.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:P.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(e.data%i.value!==BigInt(0))n=this._getOrReturnCtx(e,n),q(n,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else Ae.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return q(t,{code:P.invalid_type,expected:z.bigint,received:t.parsedType}),oe}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(e,t,n,r){return new ni({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:J.toString(r)}]})}_addCheck(e){return new ni({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}ni.create=(e)=>new ni({checks:[],typeName:le.ZodBigInt,coerce:e?.coerce??!1,...pe(e)});class Fs extends Se{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return q(n,{code:P.invalid_type,expected:z.boolean,received:n.parsedType}),oe}return wt(e.data)}}Fs.create=(e)=>new Fs({typeName:le.ZodBoolean,coerce:e?.coerce||!1,...pe(e)});class ta extends Se{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==z.date){let i=this._getOrReturnCtx(e);return q(i,{code:P.invalid_type,expected:z.date,received:i.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return q(i,{code:P.invalid_date}),oe}let n=new vt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.getTime()<i.value)r=this._getOrReturnCtx(e,r),q(r,{code:P.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()}else if(i.kind==="max"){if(e.data.getTime()>i.value)r=this._getOrReturnCtx(e,r),q(r,{code:P.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()}else Ae.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ta({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:J.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}ta.create=(e)=>new ta({checks:[],coerce:e?.coerce||!1,typeName:le.ZodDate,...pe(e)});class Ms extends Se{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return q(n,{code:P.invalid_type,expected:z.symbol,received:n.parsedType}),oe}return wt(e.data)}}Ms.create=(e)=>new Ms({typeName:le.ZodSymbol,...pe(e)});class ra extends Se{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:P.invalid_type,expected:z.undefined,received:n.parsedType}),oe}return wt(e.data)}}ra.create=(e)=>new ra({typeName:le.ZodUndefined,...pe(e)});class na extends Se{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return q(n,{code:P.invalid_type,expected:z.null,received:n.parsedType}),oe}return wt(e.data)}}na.create=(e)=>new na({typeName:le.ZodNull,...pe(e)});class ii extends Se{constructor(){super(...arguments);this._any=!0}_parse(e){return wt(e.data)}}ii.create=(e)=>new ii({typeName:le.ZodAny,...pe(e)});class Sn extends Se{constructor(){super(...arguments);this._unknown=!0}_parse(e){return wt(e.data)}}Sn.create=(e)=>new Sn({typeName:le.ZodUnknown,...pe(e)});class Ir extends Se{_parse(e){let t=this._getOrReturnCtx(e);return q(t,{code:P.invalid_type,expected:z.never,received:t.parsedType}),oe}}Ir.create=(e)=>new Ir({typeName:le.ZodNever,...pe(e)});class Ws extends Se{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:P.invalid_type,expected:z.void,received:n.parsedType}),oe}return wt(e.data)}}Ws.create=(e)=>new Ws({typeName:le.ZodVoid,...pe(e)});class pr extends Se{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==z.array)return q(t,{code:P.invalid_type,expected:z.array,received:t.parsedType}),oe;if(r.exactLength!==null){let a=t.data.length>r.exactLength.value,s=t.data.length<r.exactLength.value;if(a||s)q(t,{code:a?P.too_big:P.too_small,minimum:s?r.exactLength.value:void 0,maximum:a?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty()}if(r.minLength!==null){if(t.data.length<r.minLength.value)q(t,{code:P.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()}if(r.maxLength!==null){if(t.data.length>r.maxLength.value)q(t,{code:P.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()}if(t.common.async)return Promise.all([...t.data].map((a,s)=>r.type._parseAsync(new Zt(t,a,t.path,s)))).then((a)=>vt.mergeArray(n,a));let i=[...t.data].map((a,s)=>r.type._parseSync(new Zt(t,a,t.path,s)));return vt.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new pr({...this._def,minLength:{value:e,message:J.toString(t)}})}max(e,t){return new pr({...this._def,maxLength:{value:e,message:J.toString(t)}})}length(e,t){return new pr({...this._def,exactLength:{value:e,message:J.toString(t)}})}nonempty(e){return this.min(1,e)}}pr.create=(e,t)=>new pr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:le.ZodArray,...pe(t)});function ti(e){if(e instanceof Ze){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=hr.create(ti(r))}return new Ze({...e._def,shape:()=>t})}else if(e instanceof pr)return new pr({...e._def,type:ti(e.element)});else if(e instanceof hr)return hr.create(ti(e.unwrap()));else if(e instanceof Jr)return Jr.create(ti(e.unwrap()));else if(e instanceof Rr)return Rr.create(e.items.map((t)=>ti(t)));else return e}class Ze extends Se{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Ae.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==z.object){let l=this._getOrReturnCtx(e);return q(l,{code:P.invalid_type,expected:z.object,received:l.parsedType}),oe}let{status:n,ctx:r}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof Ir&&this._def.unknownKeys==="strip")){for(let l in r.data)if(!a.includes(l))s.push(l)}let o=[];for(let l of a){let c=i[l],u=r.data[l];o.push({key:{status:"valid",value:l},value:c._parse(new Zt(r,u,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof Ir){let l=this._def.unknownKeys;if(l==="passthrough")for(let c of s)o.push({key:{status:"valid",value:c},value:{status:"valid",value:r.data[c]}});else if(l==="strict"){if(s.length>0)q(r,{code:P.unrecognized_keys,keys:s}),n.dirty()}else if(l==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let c of s){let u=r.data[c];o.push({key:{status:"valid",value:c},value:l._parse(new Zt(r,u,r.path,c)),alwaysSet:c in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let l=[];for(let c of o){let u=await c.key,d=await c.value;l.push({key:u,value:d,alwaysSet:c.alwaysSet})}return l}).then((l)=>vt.mergeObjectSync(n,l));else return vt.mergeObjectSync(n,o)}get shape(){return this._def.shape()}strict(e){return J.errToObj,new Ze({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let r=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:J.errToObj(e).message??r};return{message:r}}}:{}})}strip(){return new Ze({...this._def,unknownKeys:"strip"})}passthrough(){return new Ze({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ze({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ze({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:le.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ze({...this._def,catchall:e})}pick(e){let t={};for(let n of Ae.objectKeys(e))if(e[n]&&this.shape[n])t[n]=this.shape[n];return new Ze({...this._def,shape:()=>t})}omit(e){let t={};for(let n of Ae.objectKeys(this.shape))if(!e[n])t[n]=this.shape[n];return new Ze({...this._def,shape:()=>t})}deepPartial(){return ti(this)}partial(e){let t={};for(let n of Ae.objectKeys(this.shape)){let r=this.shape[n];if(e&&!e[n])t[n]=r;else t[n]=r.optional()}return new Ze({...this._def,shape:()=>t})}required(e){let t={};for(let n of Ae.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];while(i instanceof hr)i=i._def.innerType;t[n]=i}return new Ze({...this._def,shape:()=>t})}keyof(){return Ph(Ae.objectKeys(this.shape))}}Ze.create=(e,t)=>new Ze({shape:()=>e,unknownKeys:"strip",catchall:Ir.create(),typeName:le.ZodObject,...pe(t)});Ze.strictCreate=(e,t)=>new Ze({shape:()=>e,unknownKeys:"strict",catchall:Ir.create(),typeName:le.ZodObject,...pe(t)});Ze.lazycreate=(e,t)=>new Ze({shape:e,unknownKeys:"strip",catchall:Ir.create(),typeName:le.ZodObject,...pe(t)});class ia extends Se{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(i){for(let s of i)if(s.result.status==="valid")return s.result;for(let s of i)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map((s)=>new Pt(s.ctx.common.issues));return q(t,{code:P.invalid_union,unionErrors:a}),oe}if(t.common.async)return Promise.all(n.map(async(i)=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(r);else{let i=void 0,a=[];for(let o of n){let l={...t,common:{...t.common,issues:[]},parent:null},c=o._parseSync({data:t.data,path:t.path,parent:l});if(c.status==="valid")return c;else if(c.status==="dirty"&&!i)i={result:c,ctx:l};if(l.common.issues.length)a.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let s=a.map((o)=>new Pt(o));return q(t,{code:P.invalid_union,unionErrors:s}),oe}}get options(){return this._def.options}}ia.create=(e,t)=>new ia({options:e,typeName:le.ZodUnion,...pe(t)});var _r=(e)=>{if(e instanceof sa)return _r(e.schema);else if(e instanceof gr)return _r(e.innerType());else if(e instanceof oa)return[e.value];else if(e instanceof bn)return e.options;else if(e instanceof la)return Ae.objectValues(e.enum);else if(e instanceof ca)return _r(e._def.innerType);else if(e instanceof ra)return[void 0];else if(e instanceof na)return[null];else if(e instanceof hr)return[void 0,..._r(e.unwrap())];else if(e instanceof Jr)return[null,..._r(e.unwrap())];else if(e instanceof Ac)return _r(e.unwrap());else if(e instanceof da)return _r(e.unwrap());else if(e instanceof ua)return _r(e._def.innerType);else return[]};class Tc extends Se{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.object)return q(t,{code:P.invalid_type,expected:z.object,received:t.parsedType}),oe;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);if(!i)return q(t,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),oe;if(t.common.async)return i._parseAsync({data:t.data,path:t.path,parent:t});else return i._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let r=new Map;for(let i of t){let a=_r(i.shape[e]);if(!a.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of a){if(r.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);r.set(s,i)}}return new Tc({typeName:le.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...pe(n)})}}function wc(e,t){let n=Ar(e),r=Ar(t);if(e===t)return{valid:!0,data:e};else if(n===z.object&&r===z.object){let i=Ae.objectKeys(t),a=Ae.objectKeys(e).filter((o)=>i.indexOf(o)!==-1),s={...e,...t};for(let o of a){let l=wc(e[o],t[o]);if(!l.valid)return{valid:!1};s[o]=l.data}return{valid:!0,data:s}}else if(n===z.array&&r===z.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let a=0;a<e.length;a++){let s=e[a],o=t[a],l=wc(s,o);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else if(n===z.date&&r===z.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class aa extends Se{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(i,a)=>{if(bc(i)||bc(a))return oe;let s=wc(i.value,a.value);if(!s.valid)return q(n,{code:P.invalid_intersection_types}),oe;if(Cc(i)||Cc(a))t.dirty();return{status:t.value,value:s.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>r(i,a));else return r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}aa.create=(e,t,n)=>new aa({left:e,right:t,typeName:le.ZodIntersection,...pe(n)});class Rr extends Se{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return q(n,{code:P.invalid_type,expected:z.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return q(n,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;if(!this._def.rest&&n.data.length>this._def.items.length)q(n,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let i=[...n.data].map((a,s)=>{let o=this._def.items[s]||this._def.rest;if(!o)return null;return o._parse(new Zt(n,a,n.path,s))}).filter((a)=>!!a);if(n.common.async)return Promise.all(i).then((a)=>vt.mergeArray(t,a));else return vt.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Rr({...this._def,rest:e})}}Rr.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Rr({items:e,typeName:le.ZodTuple,rest:null,...pe(t)})};class $s extends Se{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return q(n,{code:P.invalid_type,expected:z.object,received:n.parsedType}),oe;let r=[],i=this._def.keyType,a=this._def.valueType;for(let s in n.data)r.push({key:i._parse(new Zt(n,s,n.path,s)),value:a._parse(new Zt(n,n.data[s],n.path,s)),alwaysSet:s in n.data});if(n.common.async)return vt.mergeObjectAsync(t,r);else return vt.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof Se)return new $s({keyType:e,valueType:t,typeName:le.ZodRecord,...pe(n)});return new $s({keyType:kr.create(),valueType:e,typeName:le.ZodRecord,...pe(t)})}}class Hs extends Se{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return q(n,{code:P.invalid_type,expected:z.map,received:n.parsedType}),oe;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([s,o],l)=>({key:r._parse(new Zt(n,s,n.path,[l,"key"])),value:i._parse(new Zt(n,o,n.path,[l,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let o of a){let l=await o.key,c=await o.value;if(l.status==="aborted"||c.status==="aborted")return oe;if(l.status==="dirty"||c.status==="dirty")t.dirty();s.set(l.value,c.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let o of a){let{key:l,value:c}=o;if(l.status==="aborted"||c.status==="aborted")return oe;if(l.status==="dirty"||c.status==="dirty")t.dirty();s.set(l.value,c.value)}return{status:t.value,value:s}}}}Hs.create=(e,t,n)=>new Hs({valueType:t,keyType:e,typeName:le.ZodMap,...pe(n)});class ai extends Se{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return q(n,{code:P.invalid_type,expected:z.set,received:n.parsedType}),oe;let r=this._def;if(r.minSize!==null){if(n.data.size<r.minSize.value)q(n,{code:P.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()}if(r.maxSize!==null){if(n.data.size>r.maxSize.value)q(n,{code:P.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty()}let i=this._def.valueType;function a(o){let l=new Set;for(let c of o){if(c.status==="aborted")return oe;if(c.status==="dirty")t.dirty();l.add(c.value)}return{status:t.value,value:l}}let s=[...n.data.values()].map((o,l)=>i._parse(new Zt(n,o,n.path,l)));if(n.common.async)return Promise.all(s).then((o)=>a(o));else return a(s)}min(e,t){return new ai({...this._def,minSize:{value:e,message:J.toString(t)}})}max(e,t){return new ai({...this._def,maxSize:{value:e,message:J.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ai.create=(e,t)=>new ai({valueType:e,minSize:null,maxSize:null,typeName:le.ZodSet,...pe(t)});class ea extends Se{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.function)return q(t,{code:P.invalid_type,expected:z.function,received:t.parsedType}),oe;function n(s,o){return Vs({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ji(),Yr].filter((l)=>!!l),issueData:{code:P.invalid_arguments,argumentsError:o}})}function r(s,o){return Vs({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ji(),Yr].filter((l)=>!!l),issueData:{code:P.invalid_return_type,returnTypeError:o}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof si){let s=this;return wt(async function(...o){let l=new Pt([]),c=await s._def.args.parseAsync(o,i).catch((f)=>{throw l.addIssue(n(o,f)),l}),u=await Reflect.apply(a,this,c);return await s._def.returns._def.type.parseAsync(u,i).catch((f)=>{throw l.addIssue(r(u,f)),l})})}else{let s=this;return wt(function(...o){let l=s._def.args.safeParse(o,i);if(!l.success)throw new Pt([n(o,l.error)]);let c=Reflect.apply(a,this,l.data),u=s._def.returns.safeParse(c,i);if(!u.success)throw new Pt([r(c,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ea({...this._def,args:Rr.create(e).rest(Sn.create())})}returns(e){return new ea({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ea({args:e?e:Rr.create([]).rest(Sn.create()),returns:t||Sn.create(),typeName:le.ZodFunction,...pe(n)})}}class sa extends Se{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}sa.create=(e,t)=>new sa({getter:e,typeName:le.ZodLazy,...pe(t)});class oa extends Se{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return q(t,{received:t.data,code:P.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}}oa.create=(e,t)=>new oa({value:e,typeName:le.ZodLiteral,...pe(t)});function Ph(e,t){return new bn({values:e,typeName:le.ZodEnum,...pe(t)})}class bn extends Se{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return q(t,{expected:Ae.joinValues(n),received:t.parsedType,code:P.invalid_type}),oe}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return q(t,{received:t.data,code:P.invalid_enum_value,options:n}),oe}return wt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return bn.create(e,{...this._def,...t})}exclude(e,t=this._def){return bn.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}}bn.create=Ph;class la extends Se{_parse(e){let t=Ae.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let r=Ae.objectValues(t);return q(n,{expected:Ae.joinValues(r),received:n.parsedType,code:P.invalid_type}),oe}if(!this._cache)this._cache=new Set(Ae.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let r=Ae.objectValues(t);return q(n,{received:n.data,code:P.invalid_enum_value,options:r}),oe}return wt(e.data)}get enum(){return this._def.values}}la.create=(e,t)=>new la({values:e,typeName:le.ZodNativeEnum,...pe(t)});class si extends Se{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.promise&&t.common.async===!1)return q(t,{code:P.invalid_type,expected:z.promise,received:t.parsedType}),oe;let n=t.parsedType===z.promise?t.data:Promise.resolve(t.data);return wt(n.then((r)=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}si.create=(e,t)=>new si({type:e,typeName:le.ZodPromise,...pe(t)});class gr extends Se{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===le.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:(a)=>{if(q(n,a),a.fatal)t.abort();else t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){let a=r.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async(s)=>{if(t.value==="aborted")return oe;let o=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});if(o.status==="aborted")return oe;if(o.status==="dirty")return ei(o.value);if(t.value==="dirty")return ei(o.value);return o});else{if(t.value==="aborted")return oe;let s=this._def.schema._parseSync({data:a,path:n.path,parent:n});if(s.status==="aborted")return oe;if(s.status==="dirty")return ei(s.value);if(t.value==="dirty")return ei(s.value);return s}}if(r.type==="refinement"){let a=(s)=>{let o=r.refinement(s,i);if(n.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(s.status==="aborted")return oe;if(s.status==="dirty")t.dirty();return a(s.value),{status:t.value,value:s.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((s)=>{if(s.status==="aborted")return oe;if(s.status==="dirty")t.dirty();return a(s.value).then(()=>({status:t.value,value:s.value}))})}if(r.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!xn(a))return oe;let s=r.transform(a.value,i);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((a)=>{if(!xn(a))return oe;return Promise.resolve(r.transform(a.value,i)).then((s)=>({status:t.value,value:s}))});Ae.assertNever(r)}}gr.create=(e,t,n)=>new gr({schema:e,typeName:le.ZodEffects,effect:t,...pe(n)});gr.createWithPreprocess=(e,t,n)=>new gr({schema:t,effect:{type:"preprocess",transform:e},typeName:le.ZodEffects,...pe(n)});class hr extends Se{_parse(e){if(this._getType(e)===z.undefined)return wt(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}hr.create=(e,t)=>new hr({innerType:e,typeName:le.ZodOptional,...pe(t)});class Jr extends Se{_parse(e){if(this._getType(e)===z.null)return wt(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Jr.create=(e,t)=>new Jr({innerType:e,typeName:le.ZodNullable,...pe(t)});class ca extends Se{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;if(t.parsedType===z.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ca.create=(e,t)=>new ca({innerType:e,typeName:le.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...pe(t)});class ua extends Se{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(Zi(r))return r.then((i)=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Pt(n.common.issues)},input:n.data})}));else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Pt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ua.create=(e,t)=>new ua({innerType:e,typeName:le.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...pe(t)});class Ks extends Se{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return q(n,{code:P.invalid_type,expected:z.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}}Ks.create=(e)=>new Ks({typeName:le.ZodNaN,...pe(e)});var sA=Symbol("zod_brand");class Ac extends Se{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class qs extends Se{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(i.status==="aborted")return oe;if(i.status==="dirty")return t.dirty(),ei(i.value);else return this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();else{let r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(r.status==="aborted")return oe;if(r.status==="dirty")return t.dirty(),{status:"dirty",value:r.value};else return this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,t){return new qs({in:e,out:t,typeName:le.ZodPipeline})}}class da extends Se{_parse(e){let t=this._def.innerType._parse(e),n=(r)=>{if(xn(r))r.value=Object.freeze(r.value);return r};return Zi(t)?t.then((r)=>n(r)):n(t)}unwrap(){return this._def.innerType}}da.create=(e,t)=>new da({innerType:e,typeName:le.ZodReadonly,...pe(t)});function Ih(e,t){let n=typeof e==="function"?e(t):typeof e==="string"?{message:e}:e;return typeof n==="string"?{message:n}:n}function uC(e,t={},n){if(e)return ii.create().superRefine((r,i)=>{let a=e(r);if(a instanceof Promise)return a.then((s)=>{if(!s){let o=Ih(t,r),l=o.fatal??n??!0;i.addIssue({code:"custom",...o,fatal:l})}});if(!a){let s=Ih(t,r),o=s.fatal??n??!0;i.addIssue({code:"custom",...s,fatal:o})}return});return ii.create()}var oA={object:Ze.lazycreate},le;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(le||(le={}));var ye=kr.create,Br=ri.create,lA=Ks.create,cA=ni.create,er=Fs.create,uA=ta.create,dA=Ms.create,fA=ra.create,pA=na.create,hA=ii.create,gA=Sn.create,mA=Ir.create,yA=Ws.create,je=pr.create,{create:ht,strictCreate:vA}=Ze,xA=ia.create,SA=Tc.create,bA=aa.create,dC=Rr.create,Nh=$s.create,CA=Hs.create,EA=ai.create,wA=ea.create,TA=sa.create,AA=oa.create,oi=bn.create,_A=la.create,kA=si.create,IA=gr.create,RA=hr.create,BA=Jr.create,PA=gr.createWithPreprocess,NA=qs.create;function kc(e){if(pC(e)===6)return!0;if(e.includes("://")||e.includes("/")||e.includes(":"))return!1;if(e==="localhost")return!0;if(e.startsWith("*.")){let t=e.slice(2);if(!t.includes(".")||t.startsWith(".")||t.endsWith("."))return!1;let n=t.split(".");return n.length>=2&&n.every((r)=>r.length>0)}if(e.includes("*"))return!1;return e.includes(".")&&!e.startsWith(".")&&!e.endsWith(".")}var Ic='Invalid domain pattern. Must be a valid domain (e.g., "example.com"), a wildcard (e.g., "*.example.com"), or a bracketed IPv6 literal (e.g., "[::1]", "[2001:db8::1]:443"). Overly broad patterns like "*.com" or "*" are not allowed for security reasons.',js=ye().refine(kc,{message:Ic});function Oh(e){let t=e.indexOf(":");return!(t!==-1&&e.indexOf(":",t+1)!==-1)||e.startsWith("[")}var gC=ye().refine((e)=>Oh(e)&&kc($i(e).hostPattern),{message:Ic+' An optional ":port" suffix (1-65535) restricts the entry to that port.'}),mC=ye().refine((e)=>{if(!Oh(e))return!1;let{hostPattern:t}=$i(e);return t==="*"||kc(t)},{message:Ic+' In deniedDomains a bare "*" (deny-all) is also accepted, and an optional ":port" suffix (1-65535) restricts the entry to that port.'}),fa=ye().min(1,"Path cannot be empty"),Dh=ye().min(1,"Path cannot be empty").refine((e)=>hC(e),{message:"Binary path must be absolute"}),yC=ht({socketPath:ye().min(1).describe("Unix socket path to the MITM proxy"),domains:je(js).min(1).describe('Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])')}),vC=ht({http:ye().url().optional().describe("Upstream proxy URL for plain HTTP traffic"),https:ye().url().optional().describe("Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)"),noProxy:ye().optional().describe("Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.")}),Uh=oi(["deny","mask"]),Gs=ye().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable name must start with a letter or underscore and contain only letters, digits, and underscores"),Vh=ye().superRefine((e,t)=>{try{let{groupCount:n}=Il(e);if(n<1)t.addIssue({code:P.custom,message:"extract must contain at least one capturing group \u2014 group 1 is "+'the credential value to mask (e.g. "token:\\s*(\\S+)").'})}catch(n){t.addIssue({code:P.custom,message:n instanceof Error?n.message:"Credential extract pattern is invalid"})}}),xC=ht({path:fa.describe("Path to a credential file or directory. Supports the same path forms as filesystem.denyRead (absolute paths and ~ expansion)."),mode:Uh.describe("Access mode for this path"),extract:Vh.optional().describe('Optional regex for structured masking. Applied globally; capture group 1 of each match is masked, the rest of the file is preserved. If the pattern matches nothing, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),onExtractNoMatch:oi(["warn","deny","error"]).optional().describe("What to do when extract matches nothing (or, with decode, no "+'candidate verifies): "warn" (default \u2014 stderr warning, file left '+'readable), "deny" (degrade to mode "deny" \u2014 file unreadable), or '+'"error" (throw at wrap time). Only meaningful with mode "mask" and extract or decode set.'),decode:oi(["jwt"]).optional().describe('Optional encoded-credential format. "jwt": decodes recognized JWTs so masking can target fields inside them (see maskClaims). Candidates are located with a built-in JWT regex (or the explicit extract pattern, if set) and verified to actually be JWTs before masking. Without maskClaims, the whole decoded value is treated as the credential and replaced with a structurally valid fake JWT, so client-side token parsing keeps working. If no candidate verifies, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),maskClaims:je(ye().min(1)).optional().describe('Names of top-level payload claims to mask inside each decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel; all other claims are preserved so claim-reading clients keep working. Requires decode. If no named claim matches in any verified token, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),maskDuplicates:er().optional().describe("If true, verbatim occurrences of each captured credential value outside the regex-matched spans are also replaced with the "+"corresponding sentinel \u2014 for a secret repeated where the regex "+`does not reach (e.g. in a comment). Matches raw substrings: short or common credential values may corrupt unrelated content, so this is intended for long, high-entropy secrets. With decode, only values that passed verification are scanned; duplicates reuse the verified value's fake without re-verification. Defaults to false. Only meaningful with mode "mask" and extract or decode set; accepted but ignored otherwise.`),injectHosts:je(js).optional().describe("Optional narrowing of where the proxy substitutes this credential. "+"If unset, defaults to network.allowedDomains \u2014 the credential is "+'injected at every reachable host. Only meaningful when mode is "mask"; accepted but ignored for "deny".')}),SC=ht({name:Gs.describe("Environment variable name"),mode:Uh.describe("Access mode for this environment variable"),extract:Vh.optional().describe('Optional regex for structured masking. Applied globally; capture group 1 of each match is masked, the rest of the value is preserved. If the pattern matches nothing, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),onExtractNoMatch:oi(["warn","deny","error"]).optional().describe('What to do when extract matches nothing: "warn" (default \u2014 stderr '+'warning, variable passes through unmasked), "deny" (variable unset inside the sandbox), or "error" (throw at wrap time). Only meaningful with mode "mask" and extract set.'),decode:oi(["jwt"]).optional().describe(`Optional encoded-credential format. "jwt": the variable's whole value is verified to actually be a JWT and replaced with a structurally valid fake JWT so client-side token parsing keeps working; the proxy swaps the whole fake token on egress. If the value does not verify, the variable is left unmasked with a stderr warning (fail-open). Only meaningful when mode is "mask"; accepted but ignored for "deny".`),maskClaims:je(ye().min(1)).optional().describe('Names of top-level payload claims to mask inside the decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel; all other claims are preserved so claim-reading clients keep working. Requires decode. If no named claim matches, the variable is left unmasked with a stderr warning (fail-open). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),injectHosts:je(js).optional().describe("Optional narrowing of where the proxy substitutes this credential. "+"If unset, defaults to network.allowedDomains \u2014 the credential is "+'injected at every reachable host. Only meaningful when mode is "mask"; accepted but ignored for "deny".'),injectHeaders:je(ye().regex(/^[a-z0-9-]{1,64}$/)).min(1).optional().describe('Optional narrowing of where in a request the proxy substitutes this credential: only in these headers (lower-case names), never in other headers or the body. If unset, every header and the body. Only meaningful when mode is "mask".')}),bC=ht({accessKeyIdVar:Gs.describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:Gs.describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:Gs.optional().describe("Optional name of the masked env var holding the AWS session token (temporary credentials). When set, the proxy sends the real token as x-amz-security-token on re-signed requests and adds it to the signed header set if the client did not.")}).strict(),_c=oi(["deny","passthrough"]),CC=ht({streaming:_c.optional().describe('Policy for aws-chunked streaming uploads (x-amz-content-sha256: STREAMING-*): per-chunk signatures chain off the seed signature, so re-signing would require rewriting the body. Default "deny".'),presigned:_c.optional().describe('Policy for presigned URLs (X-Amz-Algorithm/X-Amz-Signature in the query, no Authorization header): the signature lives in the URL itself. Default "deny".'),sigv4a:_c.optional().describe('Policy for SigV4A (AWS4-ECDSA-P256-SHA256) asymmetric signatures: there is no shared-key HMAC to recompute. Default "deny".')}).strict(),Fh=ht({files:je(xC).optional().describe("Credential files or directories to protect"),envVars:je(SC).optional().describe("Environment variables to protect"),allowPlaintextInject:er().optional().describe("Allow sentinel\u2192real substitution on the plain-HTTP proxy path. "+"Defaults to false: without TLS termination the upstream identity is unverified and the credential travels in cleartext. Set only for trusted-network test fixtures."),awsPairs:je(bC).optional().describe("Explicit groupings of masked env vars into AWS credential pairs for SigV4 re-signing, for non-standard variable names. The conventional AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN trio is paired automatically when masked."),sigv4:CC.optional().describe('Policies for AWS SigV4 request shapes the proxy cannot re-sign (streaming, presigned, sigv4a) when they reference a masked credential pair: "deny" (default) or "passthrough".')}).strict(),Lh=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,EC=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/,wC=ht({url:ye().url().refine((e)=>new URL(e).protocol==="https:",{message:"brokerForward.url must be https"}),tokenEnvVar:ye().regex(Lh),rules:je(ht({envVar:ye().regex(Lh),hosts:je(ye().regex(EC)).min(1).max(16)}).strict()).min(1).max(32)}).strict(),Mh=ht({allowedDomains:je(gC).describe('List of allowed domains (e.g., ["github.com", "*.npmjs.org", "api.example.com:443"]). An optional ":port" suffix restricts the entry to that destination port.'),deniedDomains:je(mC).describe('List of denied domains. Unlike allowedDomains, a bare "*" is accepted here (deny-all). An optional ":port" suffix (e.g., "*:22") restricts the entry to that destination port.'),deniedDomainReasons:Nh(ye(),ye().min(1)).optional().describe('Optional model-facing reason keyed by the exact deniedDomains entry it explains (e.g., {"github.com:22": "SSH pushes to GitHub are blocked; use an https remote"}). Reported in the <sandbox_violations> line when that entry denies a connection; entries without one use a generic reason. Keys are matched by exact entry string, so a key with no matching deniedDomains entry never fires.'),strictAllowlist:er().optional().describe("If true, hosts not in allowedDomains are denied without consulting the ask callback. Set this when allowedDomains is policy enforcement, not a prompt-suppression hint."),allowUnixSockets:je(ye()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:er().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:er().optional().describe("Whether to allow binding to local ports (default: false)"),allowMachLookup:je(ye().refine((e)=>!(e.endsWith("*")?e.slice(0,-1):e).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "2BUA8C4S2C.com.1password.*"). Needed for tools like 1Password CLI, Playwright, or the iOS Simulator that communicate via XPC.'),httpProxyPort:Br().int().min(1).max(65535).optional().describe("Port of an external HTTP proxy to use instead of starting a local one. When provided, the library will skip starting its own HTTP proxy and use this port. The external proxy must handle domain filtering."),socksProxyPort:Br().int().min(1).max(65535).optional().describe("Port of an external SOCKS proxy to use instead of starting a local one. When provided, the library will skip starting its own SOCKS proxy and use this port. The external proxy must handle domain filtering."),mitmProxy:yC.optional().describe("Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering."),filterRequest:uC((e)=>typeof e==="function",{message:"filterRequest must be a function"}).optional().describe("Per-request filter callback. Receives the parsed HTTP request (web-standard Request) and returns {action, reason?}. Denied requests get a 403 with the reason. If the callback throws, the request is denied. Applies to plain HTTP through the proxy and, when tlsTerminate is configured, to terminated HTTPS. SRT does not provide a policy language; library consumers own matching."),tlsTerminate:ht({caCertPath:ye().min(1).optional().describe("Path to a PEM-encoded CA certificate. The sandboxed child is configured to trust this CA, and the TLS-terminating proxy uses it to sign per-host certificates. If omitted, on Windows SRT generates-if-absent a persistent CA under %ProgramData%\\sandbox-runtime\\ca\\ and trusts it in the sandbox user's Root store; on other platforms SRT generates an ephemeral CA into a temp directory for the lifetime of the session."),caKeyPath:ye().min(1).optional().describe("Path to the PEM-encoded private key for caCertPath."),excludeDomains:je(js).optional().describe("Domain patterns (same syntax as allowedDomains) whose HTTPS connections are NOT terminated. Matching CONNECTs are opaque byte tunnels: still subject to the allow/deny domain lists, but the sandboxed client completes its own TLS handshake with the upstream, so filterRequest and credential injection do not apply to their HTTPS traffic (plain-HTTP requests to the same hosts keep the normal request pipeline). Use for hosts the proxy must not re-originate: mTLS upstreams (only the client holds the client certificate) and clients that pin the upstream certificate and would reject the MITM CA. Hosts still need to be reachable via allowedDomains; this list only changes how they are tunnelled."),extraCaCertPaths:je(ye().min(1)).optional().describe("Paths to PEM CA certificate files appended to the trust bundle the sandboxed child is pointed at, after the MITM CA and the host's regular roots. Use for site-local roots (e.g. an internal mTLS CA) presented by excluded/passthrough hosts, so the child can verify them itself. Only the CERTIFICATE blocks of each file are copied; files that are missing, unreadable, or contain no PEM CERTIFICATE block are skipped (with a debug log), so paths that exist on only some hosts are safe to list.")}).refine((e)=>!e.caCertPath===!e.caKeyPath,{message:"caCertPath and caKeyPath must be provided together"}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so HTTPS request/response bodies are visible to SRT. Provide a CA cert+key, or omit both to have SRT generate an ephemeral one."),parentProxy:vC.optional().describe("Upstream HTTP proxy for outbound connections. When set, SRT's proxy tunnels non-mitmProxy traffic through this parent instead of connecting directly. Falls back to HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars if unset."),brokerForward:wC.optional().describe("Credential placeholders a remote broker swaps (see broker-forward.ts).")}),Wh=ht({disabled:er().optional().describe("Disable all filesystem policy enforcement. When true, no read or write rules are emitted: denyRead/allowRead/allowWrite/denyWrite are ignored, and the built-in mandatory write protections (.git/hooks, .git/config, shell rc files, .mcp.json, .vscode/.idea, .claude/commands, .claude/agents) are NOT applied. Use only when the sandboxed process is trusted with full host filesystem access. Network and credential-env restrictions still apply. On Linux, /dev is still replaced by the bwrap minimal devtmpfs."),denyRead:je(fa).describe("Paths denied for reading"),allowRead:je(fa).optional().describe("Paths to re-allow reading within denied regions (takes precedence over denyRead). Use with denyRead to deny a broad region then allow back specific subdirectories."),allowWrite:je(fa).describe("Paths allowed for writing"),denyWrite:je(fa).describe("Paths denied for writing (takes precedence over allowWrite)"),allowGitConfig:er().optional().describe("Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.")}),$h=Nh(ye(),je(ye())).describe('Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands'),Hh=ht({command:ye().describe("The ripgrep command to execute"),args:je(ye()).optional().describe("Additional arguments to pass before ripgrep args"),argv0:ye().optional().describe("Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])")}),Kh=ht({safeDirectories:je(ye()).default([]).describe("Directories git should treat as safe (`safe.directory`) even though they're owned by a different user inside the sandbox. Use for the repo top-level when launching from a subdirectory. Does NOT grant write.")}),qh=ht({path:ye().min(1).describe("Path to the srt-win binary. Pass the exported VENDORED_SRT_WIN_EXE constant to use the packaged vendor/srt-win/<arch>/srt-win.exe (see its WARNING: in a dev checkout that file may sit inside your sandbox write grant). The binary is spawned with the `--srt-win` argv[1] sentinel so a multicall dispatcher can route to srt-win's CLI.")}),Gh=ht({sandboxUser:ye().min(1).max(20,"Windows local usernames are limited to 20 characters").optional().describe("Name for the dedicated sandbox user account that `srt-win install` creates and the sandboxed child runs as. Default: `srt-sandbox`. Install refuses if an account by this name already exists and srt-win did not create it (it will not rotate the password of an account it does not own). Must match what `srt-win install --sandbox-user` was run with."),sublayerGuid:ye().uuid().optional().describe("WFP sublayer GUID under which the filters were installed. Omit to use the srt-win compile-time default. Set this when filters were installed by enterprise tooling under a custom sublayer."),wfpSublayerGuid:ye().uuid().optional().describe("Deprecated alias for sublayerGuid."),proxyPortRange:dC([Br().int().min(1),Br().int().max(65535)]).refine(([e,t])=>e<=t&&t-e<=64,{message:"low must be \u2264 high and range width \u2264 64"}).optional().describe("Inclusive [low, high] port range the JS mux proxy listeners bind inside. MUST match the range passed to `srt-win install "+"--proxy-port-range` (default 60080\u201360089) \u2014 the WFP loopback "+"permit only covers ports in that range."),srtWin:qh.optional().describe("How to locate/invoke the srt-win helper binary. `srtWin.path` is "+"required to use the Windows sandbox \u2014 your own (multicall) binary, "+"or the exported VENDORED_SRT_WIN_EXE constant for the packaged exe.")}),TC=ht({applyPath:ye().optional().describe("Path to the apply-seccomp binary"),argv0:ye().optional().describe("Invoke apply-seccomp as a multicall binary that dispatches on the ARGV0 environment variable. When set, applyPath is used verbatim (no existence check) and the invocation inside bwrap is prefixed with ARGV0=<this value>. The caller is responsible for ensuring applyPath resolves inside the bwrap namespace and that the target binary implements the apply-seccomp interface when ARGV0 matches.")}),AC=ht({network:Mh.describe("Network restrictions configuration"),filesystem:Wh.describe("Filesystem restrictions configuration"),credentials:Fh.optional().describe("Credential handling configuration. Only the explicitly declared files and environment variables are restricted."),ignoreViolations:$h.optional().describe("Optional configuration for ignoring specific violations"),enableWeakerNestedSandbox:er().optional().describe("Enable weaker nested sandbox mode (for Docker environments)"),runAsUid:Br().int().nonnegative().optional().describe("ARA: uid to drop the sandboxed command to (bwrap --uid)"),runAsGid:Br().int().nonnegative().optional().describe("ARA: gid to drop the sandboxed command to (bwrap --gid)"),runAsHostUid:Br().int().positive().optional().describe("ARA: real host uid used to launch the sandboxed bwrap child"),runAsHostGid:Br().int().positive().optional().describe("ARA: real host gid used to launch the sandboxed bwrap child"),runAsHostHome:ye().min(1).optional().describe("ARA: HOME set inside a real-host-uid sandbox child"),runAsHostUser:ye().min(1).optional().describe("ARA: USER and LOGNAME set inside a real-host-uid sandbox child"),enableWeakerNetworkIsolation:er().optional().describe("Enable weaker network isolation to allow access to com.apple.trustd.agent (macOS only). This is needed for Go programs (gh, gcloud, terraform, kubectl, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Enabling this opens a potential data exfiltration vector through the trustd service. Only enable if you need Go TLS verification."),allowAppleEvents:er().optional().describe("Allow sending Apple Events and Launch Services open requests from the sandbox (macOS only). Needed for open, osascript, and anything that opens URLs or scripts other apps via AppleScript. This removes code-execution isolation: sandboxed commands can launch other applications unsandboxed with no user prompt (launched apps are not subject to the sandbox filesystem or network restrictions), and can script running apps subject to TCC automation consent. Default: false."),ripgrep:Hh.optional().describe('Custom ripgrep configuration (default: { command: "rg" })'),mandatoryDenySearchDepth:Br().int().min(1).max(10).optional().describe("Maximum directory depth to search for dangerous files on Linux (default: 3). Higher values provide more protection but slower performance."),allowPty:er().optional().describe("Allow pseudo-terminal (pty) operations (macOS only)"),seccomp:TC.optional().describe("Custom seccomp binary paths (Linux only)."),bwrapPath:Dh.optional().describe('Linux only: absolute path to the bwrap (bubblewrap) binary. When set, this path is used directly instead of resolving "bwrap" via PATH.'),socatPath:Dh.optional().describe('Linux only: absolute path to the socat binary. When set, this path is used directly instead of resolving "socat" via PATH.'),windows:Gh.optional().describe("Windows-specific settings (WFP sublayer, proxy port range)."),git:Kh.optional().describe("Git configuration to inject via GIT_CONFIG_* env vars (cross-platform). `safeDirectories` marks paths as `safe.directory` without adding them to `filesystem.allowWrite`.")}).superRefine((e,t)=>{let n=e.credentials;if(!n)return;let r=e.network.allowedDomains.map(Hi),i=(l,c)=>{for(let[u,d]of l.entries())if(!Ns(d,r))t.addIssue({code:P.custom,path:[...c,u],message:`injectHosts entry "${d}" is not reachable via `+`network.allowedDomains \u2014 add "${d}" (or a covering wildcard) to allowedDomains, or remove it from injectHosts.`})},a=!1,s=(l,c)=>{if(l.injectHosts)i(l.injectHosts,[...c,"injectHosts"]);if(l.mode!=="mask")return;a=!0;let u=e.network.tlsTerminate?.excludeDomains;if(u?.length){if(l.injectHosts){for(let[d,f]of l.injectHosts.entries())if(Ns(f,u))t.addIssue({code:P.custom,path:[...c,"injectHosts",d],message:`injectHosts entry "${f}" is entirely covered by network.tlsTerminate.excludeDomains. Credential injection only runs on TLS-terminated connections, so this host would receive the placeholder instead of the credential. Remove it from one of the two lists.`})}else if(r.length>0&&r.every((d)=>Ns(d,u)))t.addIssue({code:P.custom,path:c,message:"This masked credential has no injectHosts, so it defaults "+"to network.allowedDomains \u2014 but "+"network.tlsTerminate.excludeDomains covers every allowed domain, so it could never be injected anywhere. Credential injection only runs on TLS-terminated connections."})}if(l.injectHosts!==void 0&&l.injectHosts.length===0)t.addIssue({code:P.custom,path:c,message:"injectHosts is explicitly empty \u2014 the credential would be "+"masked but never injected. Omit injectHosts to default to network.allowedDomains, or list the intended hosts."})};for(let[l,c]of(n.envVars??[]).entries()){if(s(c,["credentials","envVars",l]),c.maskClaims!==void 0&&c.decode===void 0)t.addIssue({code:P.custom,path:["credentials","envVars",l,"maskClaims"],message:"maskClaims requires decode \u2014 it names claims inside the "+'decoded payload. Set decode (e.g. "jwt"), or remove maskClaims to mask the whole value.'});if(c.maskClaims!==void 0&&c.maskClaims.length===0)t.addIssue({code:P.custom,path:["credentials","envVars",l,"maskClaims"],message:"maskClaims is explicitly empty \u2014 no claim would ever be "+"masked. Omit maskClaims to mask the whole token, or list the claims to protect."})}for(let[l,c]of(n.files??[]).entries()){if(s(c,["credentials","files",l]),c.maskClaims!==void 0&&c.decode===void 0)t.addIssue({code:P.custom,path:["credentials","files",l,"maskClaims"],message:"maskClaims requires decode \u2014 it names claims inside the "+'decoded payload. Set decode (e.g. "jwt"), or remove maskClaims to mask the extracted value whole.'});if(c.maskClaims!==void 0&&c.maskClaims.length===0)t.addIssue({code:P.custom,path:["credentials","files",l,"maskClaims"],message:"maskClaims is explicitly empty \u2014 no claim would ever be "+"masked. Omit maskClaims to mask the whole token, or list the claims to protect."});if(c.mode==="mask"&&c.path.endsWith("/"))t.addIssue({code:P.custom,path:["credentials","files",l,"path"],message:`Credential mode "mask" applies to a single file, not a directory. Use mode "deny" for "${c.path}", or point at the credential file inside it.`})}let o=new Set;for(let[l,c]of(n.awsPairs??[]).entries()){let u=[["accessKeyIdVar",c.accessKeyIdVar],["secretAccessKeyVar",c.secretAccessKeyVar]];if(c.sessionTokenVar!==void 0)u.push(["sessionTokenVar",c.sessionTokenVar]);for(let[d,f]of u){let y=["credentials","awsPairs",l,d];if(o.has(f)){t.addIssue({code:P.custom,path:y,message:`"${f}" appears in more than one awsPairs slot (within `+"or across pairs) \u2014 each variable can fill exactly one slot."});continue}o.add(f);let p=(n.envVars??[]).find((v)=>v.name===f);if(p===void 0||p.mode!=="mask")t.addIssue({code:P.custom,path:y,message:`"${f}" does not reference a credentials.envVars entry `+'with mode "mask" \u2014 an AWS pair links already-masked '+"variables; add the entry (masking is the opt-in for SigV4 re-signing)."});else if(p.extract!==void 0||p.decode!==void 0)t.addIssue({code:P.custom,path:y,message:`"${f}" uses extract/decode, but an AWS pair member must be masked whole-value: the SigV4 trigger is an exact match of the fake access key id, and the signer needs the entire real value.`})}}if(a&&e.network.tlsTerminate===void 0&&!n.allowPlaintextInject)t.addIssue({code:P.custom,path:["credentials"],message:"Credential masking requires network.tlsTerminate so substitution runs only over a verified TLS connection. Enable tlsTerminate, or set credentials.allowPlaintextInject to opt out (not recommended)."})});export{Fh as CredentialsConfigSchema,As as DEFAULT_WINDOWS_PROXY_PORT_RANGE,Wh as FilesystemConfigSchema,Kh as GitConfigSchema,$h as IgnoreViolationsConfigSchema,Mh as NetworkConfigSchema,Hh as RipgrepConfigSchema,Fp as SRT_WIN_DISPATCH_ARG1,Fb as SandboxManager,AC as SandboxRuntimeConfigSchema,ws as SandboxViolationStore,qh as SrtWinConfigSchema,WS as VENDORED_SRT_WIN_EXE,Gh as WindowsConfigSchema,xe as WindowsSandboxError,fi as buildGitConfigEnv,$n as certThumbprint,dc as checkWindowsDependenciesAsync,Hp as checkWindowsSandboxStatus,Kp as checkWindowsSandboxStatusAsync,oc as ensurePersistentWindowsCa,Rs as expandWindowsFsPaths,es as generateCa,Cn as getDefaultWritePaths,$S as getSrtWinPath,sc as getWindowsSandboxCaCert,ac as getWindowsSandboxUserStatus,Wi as getWindowsSandboxUserStatusAsync,qp as getWindowsWfpStatus,Gp as getWindowsWfpStatusAsync,Qs as getWslVersion,uc as grantWindowsAcl,KS as installWindowsSandbox,qS as installWindowsSandboxAsync,di as isUncPath,_s as parseWindowsBinShell,jS as parseWindowsSandboxError,Bt as resolveSrtWin,Bs as restoreWindowsAcl,Ps as revokeWindowsAcl,cc as stampWindowsAcl,GS as uninstallWindowsSandbox,Ri as validateCaPair,ic as verifyWindowsWfpEgress,ec as windowsInstallInstructions,Qp as windowsStateDir,HS as windowsTrustCa,jp as windowsTrustCaAsync};
70
+ `+" \u2014 or call installWindowsSandbox(), or run "+`\`srt-win.exe install${J}\` directly.
71
+ No logout is needed: the WFP filter keys on the dedicated \`srt-sandbox\` user's SID, so your network is unaffected.`}function S5($){try{return{status:"fulfilled",value:$()}}catch(J){return{status:"rejected",reason:J}}}function c5($,J,X){let Q=[],Y=[];if(J.status==="rejected")return Q.push(`srt-win user status failed: ${J.reason.message}`),{errors:Q,warnings:Y};let G=J.value;if(!G.provisioned||!G.credPresent)Q.push(`Sandbox user is not provisioned (user=${G.provisioned}, cred=${G.credPresent}). `+r7($));let W=X();if(W.status==="rejected")return Q.push(`srt-win wfp status failed: ${W.reason.message}`),{errors:Q,warnings:Y};let U=W.value;if(U.state==="cannot-read")Z(`[Sandbox Windows] wfp status cannot-read (non-elevated): ${U.hint}`);else if(U.state!=="installed"){if(G.provisioned&&G.credPresent)Q.push(`WFP filters not installed under sublayer ${$??"(default)"}. `+r7($))}else if(U.portRange)Z(`[Sandbox Windows] WFP installed: ${U.filters} filters, proxy port range ${U.portRange[0]}-${U.portRange[1]}`);return{errors:Q,warnings:Y}}function n5($={}){let J;try{J=$.srtWin??wJ()}catch(X){return{errors:[X.message],warnings:[]}}return Z(`[Sandbox Windows] using srt-win at ${J.exe}`),c5($.sublayerGuid,S5(()=>QG({srtWin:J})),()=>S5(()=>y5({sublayerGuid:$.sublayerGuid,srtWin:J})))}async function MG($={}){let J;try{J=$.srtWin??wJ()}catch(Y){return{errors:[Y.message],warnings:[]}}Z(`[Sandbox Windows] using srt-win at ${J.exe}`);let[X,Q]=await Promise.allSettled([aX({srtWin:J}),b5({sublayerGuid:$.sublayerGuid,srtWin:J})]);return c5($.sublayerGuid,X,()=>Q)}import{isIP as oK}from"net";function sX($){if($.startsWith("[")){let Q=$.indexOf("]");if(Q===-1)return{hostPattern:$,port:void 0};let Y=$.slice(1,Q),G=jJ(Y)??Y,W=$.slice(Q+1);if(W==="")return{hostPattern:G,port:void 0};let U=i5(W.startsWith(":")?W.slice(1):"");return U===void 0?{hostPattern:$,port:void 0}:{hostPattern:G,port:U}}let J=$.lastIndexOf(":");if(J===-1)return{hostPattern:$,port:void 0};if($.indexOf(":")!==J)return{hostPattern:jJ($)??$,port:void 0};let X=i5($.slice(J+1));if(X===void 0)return{hostPattern:$,port:void 0};return{hostPattern:$.slice(0,J),port:X}}function i5($){if(!/^[1-9][0-9]{0,4}$/.test($))return;let J=Number($);return J>65535?void 0:J}function rX($){return sX($).hostPattern}function T0($,J){let X=$.toLowerCase();if(J==="*")return!0;if(J.startsWith("*.")){if(oK(cJ(X)))return!1;let Q=J.substring(2).toLowerCase();return X.endsWith("."+Q)}return X===J.toLowerCase()}function tX($,J,X){let{hostPattern:Q,port:Y}=sX(X);if(Y!==void 0&&Y!==J)return!1;return T0($,Q)}function k9($,J){let X=J.map(rX);if(!$.startsWith("*."))return X.some((Y)=>T0($,Y));let Q=$.slice(2).toLowerCase();return X.some((Y)=>{if(!Y.startsWith("*."))return!1;let G=Y.slice(2).toLowerCase();return Q===G||Q.endsWith("."+G)})}function o5($,J,X,Q){if(!dQ(J))return{verdict:"deny",reason:"malformed host"};let Y=jJ(J)??J;for(let G of $.deniedDomains)if(tX(Y,X,G))return{verdict:"deny",reason:$.deniedDomainReasons?.[G]??"host is on the deny list",rule:G};for(let G of $.allowedDomains)if(tX(Y,X,G))return{verdict:"allow",rule:G};if(!Q||$.strictAllowlist)return{verdict:"deny",reason:"host is not on the allow list"};return{verdict:"ask"}}import{EOL as OG}from"os";import{dirname as VG}from"path";var v,JY,QY,XY,uJ,p0,eX,a5=!1,f9,rQ,n0,u$,i0,tQ,d0,y9,s5=!1,YY,NQ=new T9,aJ=new T7,$X=new P7,eQ=new L7;function QU(){let $=v?.network.brokerForward;if(!$)return[];let J=process.env[$.tokenEnvVar];if(J)for(let X of $.rules){let Q=process.env[X.envVar];if(Q)eQ.register(Q,J,X.hosts,$.url)}return[$.tokenEnvVar]}function sK($){return v?.network.brokerForward?.rules.some((J)=>J.hosts.includes($))??!1}var GY=new w7;function rK(){if(a5)return;let $=()=>NG().catch((J)=>{Z(`Cleanup failed in registerCleanup ${J}`,{level:"error"})});process.once("exit",$),process.once("SIGINT",$),process.once("SIGTERM",$),a5=!0}var tK=1024,FQ=new Map;function XU($,J){let X=J?.commandId,Q=J?.commandText??$;if(X===void 0||X===Q)return;let Y=JQ(PJ(X));FQ.delete(Y),FQ.set(Y,Q);while(FQ.size>tK){let G=FQ.keys().next().value;if(G===void 0)break;FQ.delete(G)}}function r5($){return FQ.get($)??$}function qG($,J){let X=J?(()=>{let Q=JQ(J);return FQ.get(Q)??n7(Q)})():void 0;if(aQ($,X,v?.ignoreViolations))return;NQ.addViolation({line:$,encodedCommand:J,command:X,timestamp:new Date})}function eK($){try{let J=new URL($);return`${J.origin}${J.pathname}${J.search?"?\u2026":""}`}catch{let J=$.indexOf("?");return J===-1?$:`${$.slice(0,J)}?\u2026`}}async function t5($,J,X,Q){let Y=(W)=>{return qG(`deny network-outbound ${J}:${$} (${W})`,Q),!1};if(!v)return Z("No config available, denying network request"),Y("sandbox policy unavailable");let G=o5(v.network,J,$,X!==void 0);if(G.verdict==="allow")return Z(`Allowed by config rule: ${J}:${$}`),!0;if(G.verdict==="deny"){if(G.reason==="malformed host")Z(`Denying malformed host: ${JSON.stringify(J)}:${$}`,{level:"error"});else if(G.rule!==void 0)Z(`Denied by config rule: ${J}:${$}`);else Z(`No matching config rule, denying: ${J}:${$}`);return Y(G.reason)}Z(`No matching config rule, asking user: ${J}:${$}`);try{if(await X({host:J,port:$}))return Z(`User allowed: ${J}:${$}`),!0;return Z(`User denied: ${J}:${$}`),Y("user denied")}catch(W){return Z(`Error in permission callback: ${W}`,{level:"error"}),Y("permission prompt failed")}}var b9=!1;function $z($){b9=$}function Jz(){if(!b9&&!v?.credentials)return;return($,J)=>{if(!v?.credentials)return;aJ.substituteInHeaders($,J,T0)}}function Qz(){if(!b9&&!v?.credentials)return;return($)=>v?.credentials?aJ.sentinelsForHost($,T0):void 0}function Xz(){if(!b9&&!v?.credentials)return;return($,J,X,Q)=>!v?.credentials?void 0:u4($X,v?.credentials?.sigv4,T0)($,J,X,Q)}function Yz($){if(!v?.network.mitmProxy)return;let{socketPath:J,domains:X}=v.network.mitmProxy,Q=jJ($)??$;for(let Y of X)if(T0(Q,Y))return Z(`Host ${$} matches MITM pattern ${Y}`),J;return}function Gz($){let J=v?.network.tlsTerminate?.excludeDomains;if(!J?.length)return!0;let X=jJ($)??$;if(sK(X))return!0;for(let Q of J){if(!T0(X,Q))continue;Z(`Host ${$} matches tlsTerminate.excludeDomains pattern ${Q}; skipping TLS termination`);let Y=aJ.namesInjectableAt(X,T0);if(Y.length>0)Z(`tlsTerminate.excludeDomains: masked credential(s) ${Y.join(", ")} are configured for injection at ${$}, but its connections are not terminated, so the upstream will receive the placeholder`,{level:"error"});return!1}return!0}async function Wz($,J){let X=Jz(),Q=Qz();JY=E4({filter:(U,M,O,V)=>t5(U,M,$,V),getMitmSocketPath:Yz,mitmCA:u$,shouldTerminateTLS:Gz,filterRequest:v?.network.filterRequest,onFilterRequestDenied:({method:U,url:M,reason:O,encodedCommand:V})=>{qG(`deny http-request ${U} ${eK(M)} (${O})`,V)},mutateHeaders:X,mutateHeadersPlaintext:v?.credentials?.allowPlaintextInject?X:void 0,getBrokerForward:(U,M)=>v?.network.brokerForward?eQ.forwardFor(U,M):void 0,getBodySubstitutions:Q,getBodySubstitutionsPlaintext:v?.credentials?.allowPlaintextInject?Q:void 0,planSigv4:Xz(),parentProxy:n0,proxyAuthToken:i0}),QY=j4({filter:(U,M,O)=>t5(U,M,$,O),parentProxy:n0,proxyAuthToken:i0,probeUnauthenticated:async(U,M)=>{if(!v)return{};let O=jJ(M)??M;for(let V of v.network.deniedDomains)if(tX(O,U,V)){let q=v.network.deniedDomainReasons?.[V]??"host is on the deny list";return qG(`deny network-outbound ${M}:${U} (${q})`,void 0),{deniedReason:q}}return{}}}),XY=I4({httpServer:JY,handleSocksConnection:(U)=>QY.handleConnection(U),httpBackendPortRange:J});let Y=XY,G=await Y.listenHttpBackend();await q9(Y.server,(U)=>Y.server.listen(U,"127.0.0.1"),J,G!==void 0?new Set([G]):new Set);let W=Y.getPort();if(W===void 0)throw Error("Failed to get mux proxy server port");return Y.unref(),Z(`Mux proxy (HTTP+SOCKS) listening on localhost:${W}`),W}async function Uz($,J,X=!1){if(p0){await p0;return}if(v=$,n0=H7($.network.parentProxy),n0)Z(`Parent proxy configured: http=${E7(n0.httpUrl)} https=${E7(n0.httpsUrl)}`);if($.network.tlsTerminate&&$.network.mitmProxy)throw Error("network.tlsTerminate and network.mitmProxy are mutually exclusive");let Q=$.network.tlsTerminate,Y=x$()==="windows"&&Q!==void 0&&!Q.caCertPath&&!Q.caKeyPath;if(u$=Q&&!Y?W7(Q):void 0,u$&&$.runAsHostUid!==void 0&&x$()==="linux"){if(c0.chmodSync(VG(u$.trustBundlePath),457),c0.chmodSync(u$.trustBundlePath,420),u$.ephemeral)c0.chmodSync(VG(u$.certPath),457),c0.chmodSync(u$.certPath,420)}let G=await WU();if(G.errors.length>0)throw Error(`Sandbox dependencies not available: ${G.errors.join(", ")}`);if(X&&x$()==="macos")f9=D5(NQ.addViolation.bind(NQ),v.ignoreViolations,r5),Z("Started macOS sandbox log monitor");if(X&&x$()==="linux")rQ=j5(NQ.addViolation.bind(NQ),{allowWritePaths:[...BQ($.runAsHostHome),...v.filesystem.allowWrite],denyWritePaths:v.filesystem.denyWrite,ignoreViolations:v.ignoreViolations,resolveCommandText:r5,consumerUid:$.runAsHostUid,consumerGid:$.runAsHostGid}),rQ.ready,Z("Started Linux seccomp violation monitor");if(rK(),x$()==="windows"){YY=wJ($.windows?.srtWin);let W=YY,U=await aX({srtWin:W});if(!U.provisioned||!U.credPresent)throw v=void 0,new A$("not_provisioned",`Windows sandbox user is not provisioned (user=${U.provisioned}, cred=${U.credPresent}). Run \`npx sandbox-runtime windows-install\` (one UAC prompt) to provision it.`);if(!s5){try{await JG({proxyPortRange:$.windows?.proxyPortRange,srtWin:W})}catch(M){throw v=void 0,M}s5=!0}if(Y&&Q)try{let M=await YG({status:U,srtWin:W});u$=W7({caCertPem:M.certPem,caKeyPem:M.keyPem,caCertPath:M.certPath,caKeyPath:M.keyPath,extraCaCertPaths:Q.extraCaCertPaths})}catch(M){throw v=void 0,M}if(Q&&u$&&!Y){let M=XG(U),O=pQ(u$.certPem);if(!M)throw v=void 0,new A$("trust_ca_not_installed",`tlsTerminate on Windows requires the sandbox to be installed with this CA (thumb=${O}): run \`srt-win user trust-ca ${u$.certPath}\`. Per-exec installs into the sandbox user's Root store are not supported.`);if(M.thumb!==O)throw v=void 0,new A$("trust_ca_thumbprint_mismatch",`tlsTerminate on Windows: the sandbox's installed CA (thumb=${M.thumb}) doesn't match this session's CA (thumb=${O}). Run \`srt-win user trust-ca ${u$.certPath}\` to update it.`)}try{let M=Hz($);if(u$)M.grantRead.push(VG(u$.trustBundlePath));if(!U.sid)throw Error("sandbox user SID missing from `srt-win user status` (provisioned but in an inconsistent state)");let O=U.sid;if(d0=O,M.grantRead.length>0||M.grantWrite.length>0)UG({sandboxUserSid:O,read:M.grantRead,write:M.grantWrite,srtWin:W});if(M.denyRead.length>0||M.denyWrite.length>0)WG({sandboxUserSid:O,denyRead:M.denyRead,denyWrite:M.denyWrite,srtWin:W});if(M.grantRead.length>0||M.grantWrite.length>0||M.denyRead.length>0||M.denyWrite.length>0)tQ=M,Z(`[Sandbox Windows] fs applied: ${M.grantWrite.length} grantWrite, ${M.grantRead.length} grantRead, ${M.denyRead.length} denyRead, ${M.denyWrite.length} denyWrite`);y9=MU($)}catch(M){if(d0)v9({sandboxUserSid:d0,srtWin:W}),x9({sandboxUserSid:d0,srtWin:W});throw d0=void 0,v=void 0,M}}p0=(async()=>{try{let W=x$()==="windows"?v.windows?.proxyPortRange??I9:void 0;i0=v.network.httpProxyPort!==void 0?void 0:aK(16).toString("hex");let M=v.network.httpProxyPort===void 0||v.network.socksProxyPort===void 0?await Wz(J,W):void 0,O=v.network.httpProxyPort??M,V=v.network.socksProxyPort??M;if(u$&&M!==void 0&&x$()==="windows")u$.crlUrl=`http://127.0.0.1:${M}${$9}`;if(v.network.httpProxyPort!==void 0)Z(`Using external HTTP proxy on port ${O}`);if(v.network.socksProxyPort!==void 0)Z(`Using external SOCKS proxy on port ${V}`);let q;if(x$()==="linux")q=await H5(O,V,v.socatPath,v.runAsHostUid,v.runAsHostGid);let H={httpProxyPort:O,socksProxyPort:V,linuxBridge:q};return uJ=H,Z("Network infrastructure initialized"),H}catch(W){throw p0=void 0,uJ=void 0,NG().catch((U)=>{Z(`Cleanup failed in initializationPromise ${U}`,{level:"error"})}),W}})(),await p0}function YU(){let $=x$();if($==="linux")return i9()!=="1";return $==="macos"||$==="windows"}function Mz(){return v!==void 0}function GU($){if(!YU())return{done:{errors:["Unsupported platform"],warnings:[]}};let J=[],X=[],Q=x$();if(Q==="linux"){let Y=$??v?.ripgrep??{command:"rg"};if(Z0(Y.command)===null)J.push(`ripgrep (${Y.command}) not found`);let G=q5({seccompConfig:v?.seccomp,bwrapPath:v?.bwrapPath,socatPath:v?.socatPath});J.push(...G.errors),X.push(...G.warnings)}else if(Q==="windows"){let Y;try{Y=wJ(v?.windows?.srtWin)}catch(G){return J.push(G.message),{done:{errors:J,warnings:X}}}return{windows:{sublayerGuid:v?.windows?.sublayerGuid??v?.windows?.wfpSublayerGuid,srtWin:Y}}}return{done:{errors:J,warnings:X}}}function Oz($){let J=GU($);if("done"in J)return J.done;return n5(J.windows)}async function WU($){let J=GU($);if("done"in J)return J.done;return MG(J.windows)}function KG($,J){if(!$)return{denyReadPaths:[],unsetEnvVars:[],setEnvVars:{},maskedFileBinds:[],maskedFileStoreDir:void 0};let X=h9($),Q=[...new Set((J??[]).map(rX))],Y=[];for(let V of $.envVars??[])if(V.mode==="deny")Y.push(V.name);let{setEnvVars:G,degradeToUnsetNames:W}=k4($.envVars??[],Q,aJ);Y.push(...W),h4($.envVars??[],$.awsPairs,Q,G,$X);let U=$.files??[],{binds:M,degradeToDenyPaths:O}=v4(U,Q,aJ,GY);return{denyReadPaths:[...new Set([...X,...O])],unsetEnvVars:[...new Set(Y)],setEnvVars:G,maskedFileBinds:M,maskedFileStoreDir:GY.dirPath}}function h9($){let J=$?.files??[];return[...new Set(J.filter((X)=>X.mode==="deny").map((X)=>X.path))]}function UU($,J){return[...new Set([...$,...J.denyReadPaths])]}function Vz(){if(!v||v.filesystem.disabled)return{denyOnly:[],allowWithinDeny:[]};let $=UU(v.filesystem.denyRead,KG(v.credentials,v.network.allowedDomains)),J=[];for(let Q of $){let Y=N0(Q);if(x$()==="linux"&&NJ(Y)){let G=QQ(Q);Z(`[Sandbox] Expanded glob pattern "${Q}" to ${G.length} paths on Linux`),J.push(...G)}else J.push(Y)}let X=[];for(let Q of v.filesystem.allowRead??[]){let Y=N0(Q);if(x$()==="linux"&&NJ(Y)){let G=QQ(Q);Z(`[Sandbox] Expanded allowRead glob pattern "${Q}" to ${G.length} paths on Linux`),X.push(...G)}else X.push(Y)}return{denyOnly:J,allowWithinDeny:X}}function qz(){if(!v)return{allowOnly:BQ(),denyWithinAllow:[]};if(v.filesystem.disabled)return{allowOnly:["/"],denyWithinAllow:[]};let $=v.filesystem.allowWrite.map((Q)=>N0(Q)).filter((Q)=>{if(x$()==="linux"&&NJ(Q))return Z(`Skipping glob pattern on Linux/WSL: ${Q}`),!1;return!0}),J=v.filesystem.denyWrite.map((Q)=>N0(Q)).filter((Q)=>{if(x$()==="linux"&&NJ(Q))return Z(`Skipping glob pattern on Linux/WSL: ${Q}`),!1;return!0});return{allowOnly:[...BQ(HG()),...$],denyWithinAllow:J}}function Hz($){let J=$.filesystem;if(J?.disabled)return{grantRead:[],grantWrite:[],denyRead:[],denyWrite:[]};let X=_9,Q=X([...new Set([...J?.denyRead??[],...h9($.credentials)])],{mode:"deny"}),Y=X(J?.denyWrite??[],{mode:"deny"});return{grantRead:X(J?.allowRead??[],{mode:"grant"}),grantWrite:X(J?.allowWrite??[],{mode:"grant"}),denyRead:Q,denyWrite:Y}}function MU($){return{disabled:$.filesystem.disabled??!1,denyRead:[...$.filesystem.denyRead],denyWrite:[...$.filesystem.denyWrite],allowRead:[...$.filesystem.allowRead??[]],allowWrite:[...$.filesystem.allowWrite],credFiles:h9($.credentials)}}function $Y($,J){if($.length!==J.length)return!1;let X=new Set($);return J.every((Q)=>X.has(Q))}function Kz($,J){return $.disabled===J.disabled&&$Y($.denyRead,J.denyRead)&&$Y($.denyWrite,J.denyWrite)&&$Y($.allowRead,J.allowRead)&&$Y($.allowWrite,J.allowWrite)&&$Y($.credFiles,J.credFiles)}function zz($){return y9!==void 0&&Kz(y9,MU($))}function Ez(){if(!v)return{};let $=v.network.allowedDomains,J=v.network.deniedDomains;return{allowedHosts:$,...J.length>0&&{deniedHosts:J}}}function OU(){return v?.network?.allowUnixSockets}function e5(){return v?.network?.allowAllUnixSockets}function VU(){return v?.network?.allowLocalBinding}function qU(){return v?.network?.allowMachLookup}function HU(){return v?.ignoreViolations}function KU(){return v?.enableWeakerNestedSandbox}function Fz(){return v?.runAsUid}function Nz(){return v?.runAsGid}function Lz(){return v?.runAsHostUid}function Az(){return v?.runAsHostGid}function HG(){return v?.runAsHostHome}function Rz(){return v?.runAsHostUser}function Dz(){return v?.enableWeakerNetworkIsolation}function Zz(){return v?.allowAppleEvents}function Bz(){return v?.ripgrep??{command:"rg"}}function jz(){return v?.mandatoryDenySearchDepth??3}function $U(){return v?.filesystem?.allowGitConfig??!1}function zU($){return[...v?.git?.safeDirectories??[],...$?.git?.safeDirectories??[]]}function Tz(){return v?.seccomp}function Sz(){return i0}function zG(){return uJ?.httpProxyPort}function EG(){return uJ?.socksProxyPort}function EU(){return uJ?.linuxBridge?.httpSocketPath}function FU(){return uJ?.linuxBridge?.socksSocketPath}async function FG(){if(!v)return!1;if(p0)try{return await p0,!0}catch{return!1}return uJ!==void 0}async function NU($,J,X,Q,Y){let G=x$(),W=Y?.commandId;XU($,Y);let U=X?.filesystem!==void 0?X.filesystem.disabled??!1:v?.filesystem.disabled??!1,M=KG(X?.credentials??v?.credentials,X?.network?.allowedDomains??v?.network?.allowedDomains);M.unsetEnvVars.push(...QU());let O,V;if(!U){let A=(P)=>P.map((l)=>N0(l)).filter((l)=>{if(x$()==="linux"&&NJ(l))return Z(`[Sandbox] Skipping glob write pattern on Linux: ${l}`),!1;return!0}),D=A(X?.filesystem?.allowWrite??v?.filesystem.allowWrite??[]);O={allowOnly:[...BQ(X?.runAsHostHome??HG()),...D],denyWithinAllow:A(X?.filesystem?.denyWrite??v?.filesystem.denyWrite??[])};let S=UU(X?.filesystem?.denyRead??v?.filesystem.denyRead??[],M),B=[];for(let P of S){let l=N0(P);if(x$()==="linux"&&NJ(l))B.push(...QQ(P));else B.push(l)}let C=X?.filesystem?.allowRead??v?.filesystem.allowRead??[],w=[];for(let P of C){let l=N0(P);if(x$()==="linux"&&NJ(l))w.push(...QQ(P));else w.push(l)}if(u$)w.push(u$.certPath,u$.trustBundlePath);V={denyOnly:B,allowWithinDeny:w}}let q=X?.network?.allowedDomains!==void 0||v?.network?.allowedDomains!==void 0,H=q,N=q;if(N)await FG();let K=X?.allowPty??v?.allowPty,L=zU(X);switch(G){case"macos":return R5({command:$,commandId:W,needsNetworkRestriction:H,httpProxyPort:N?zG():void 0,socksProxyPort:N?EG():void 0,proxyAuthToken:N?i0:void 0,caCertPath:u$?.trustBundlePath,readConfig:V,writeConfig:O,unsetEnvVars:M.unsetEnvVars,setEnvVars:M.setEnvVars,maskedFileBinds:M.maskedFileBinds,allowUnixSockets:OU(),allowAllUnixSockets:e5(),allowLocalBinding:VU(),allowMachLookup:qU(),ignoreViolations:HU(),allowPty:K,allowGitConfig:$U(),gitSafeDirectories:L,enableWeakerNetworkIsolation:Dz(),allowAppleEvents:Zz(),binShell:J});case"linux":return z5({command:$,commandId:W,needsNetworkRestriction:H,httpSocketPath:N?EU():void 0,socksSocketPath:N?FU():void 0,httpProxyPort:N?uJ?.httpProxyPort:void 0,socksProxyPort:N?uJ?.socksProxyPort:void 0,proxyAuthToken:N?i0:void 0,caCertPath:u$?.trustBundlePath,readConfig:V,writeConfig:O,unsetEnvVars:M.unsetEnvVars,setEnvVars:M.setEnvVars,maskedFileBinds:M.maskedFileBinds,maskedFileStoreDir:M.maskedFileStoreDir,enableWeakerNestedSandbox:KU(),runAsUid:Fz(),runAsGid:Nz(),runAsHostUid:Lz(),runAsHostGid:Az(),runAsHostHome:HG(),runAsHostUser:Rz(),setprivPath:"/usr/bin/setpriv",allowAllUnixSockets:e5(),binShell:J,ripgrepConfig:Bz(),mandatoryDenySearchDepth:jz(),allowGitConfig:$U(),gitSafeDirectories:L,seccompConfig:Tz(),bwrapPath:v?.bwrapPath,socatPath:v?.socatPath,observeSocketPath:rQ?.observeSocketPath,startFd:Y?.startFd,argvCommand:Y?.argvCommand,abortSignal:Q});case"windows":throw Error("wrapWithSandbox() returns a shell string and is not supported on Windows. Use SandboxManager.wrapWithSandboxArgv() and spawn the result with {shell: false}.");default:throw Error(`Sandbox configuration is not supported on platform: ${G}`)}}async function Iz($,J,X,Q,Y,G){if(x$()==="windows"){let O=X?.network?.allowedDomains!==void 0||v?.network?.allowedDomains!==void 0;if(O)await FG();let V=KG(X?.credentials??v?.credentials,X?.network?.allowedDomains??v?.network?.allowedDomains);V.unsetEnvVars.push(...QU());let q=X?.filesystem,H=[],N=[];if(!q?.disabled){if(q?.allowRead?.length||q?.allowWrite?.length)throw Error("Per-exec filesystem.allowRead/allowWrite is not supported "+"on Windows \u2014 `srt-win exec` only exposes per-exec "+"denies. Set them at the session level (initialize()).");let K=[...q?.denyRead??[],...h9(X?.credentials)],L=q?.denyWrite??[];if(K.length>0||L.length>0){let A=new Set(tQ?.denyRead??[]),D=new Set(tQ?.denyWrite??[]),S=_9;H=S(K,{mode:"deny"}).filter((B)=>!A.has(B)),N=S(L,{mode:"deny"}).filter((B)=>!A.has(B)&&!D.has(B))}}return XU($,G),d5({command:$,commandId:G?.commandId,httpProxyPort:O?zG():void 0,socksProxyPort:O?EG():void 0,proxyAuthToken:O?i0:void 0,setEnvVars:V.setEnvVars,denyRead:H,denyWrite:N,cwd:Y,allowWrite:tQ?.grantWrite,gitSafeDirectories:zU(X),caCertPath:u$?.trustBundlePath,binShell:C9(J),srtWin:X?.windows?.srtWin?wJ(X.windows.srtWin):YY??wJ(v?.windows?.srtWin)})}if(typeof J==="object")throw Error("binShell object form is Windows-only; pass a shell path string on macOS/Linux");let U=await NU($,J,X,Q,G);return{argv:[J??"/bin/bash","-c",U],env:process.env}}function Cz(){return v}function wz(){aJ.clear(),$X.clear(),eQ.clear(),GY.dispose()}function Pz($){if(x$()==="windows"&&v&&!zz($))Z("[Sandbox Windows] updateConfig: the resolved file-access set "+"(filesystem.* \u222A credentials.files) changed but the ACL "+"stamp/grant is session-wide \u2014 call reset() then initialize() "+"to apply. The previously-applied set stays in effect.",{level:"warn"});let{filterRequest:J,...X}=$.network;v=structuredClone({...$,network:X}),v.network.filterRequest=J,n0=H7($.network.parentProxy),Z("Sandbox configuration updated")}function _z(){j9()}var xz=1500;function JU($,J){if(!$.pid||$.exitCode!==null||$.signalCode!==null)return Promise.resolve();try{process.kill($.pid,"SIGTERM"),Z(`Sent SIGTERM to ${J} bridge process`)}catch(X){if(X.code!=="ESRCH")Z(`Error killing ${J} bridge: ${X}`,{level:"error"});return Promise.resolve()}return new Promise((X)=>{let Q=!1,Y=()=>{if(Q)return;Q=!0,clearTimeout(G),X()};$.once("exit",()=>{Z(`${J} bridge process exited`),Y()});let G=setTimeout(()=>{if($.exitCode===null&&$.signalCode===null){Z(`${J} bridge did not exit, forcing SIGKILL`,{level:"warn"});try{if($.pid)process.kill($.pid,"SIGKILL")}catch{}}Y()},xz);G.unref?.()})}function vz($){return new Promise((J)=>{if(typeof $.closeAllConnections==="function")$.closeAllConnections();$.close((X)=>{if(X&&X.message!=="Server is not running.")Z(`Error closing HTTP proxy server: ${X.message}`,{level:"error"});J()})})}async function kz(){if(tQ&&d0){let J=d0,X=YY,Q=new Set(["revoked","stillHeld","restored","alreadyOriginal"]),Y=(G,W)=>{if(!Q.has(W.status))Z(`[Sandbox Windows] ${G}: '${W.path}' ${W.status} \u2014 `+"ACE may be left in place; resolve and run `srt-win acl recover` to clear",{level:"warn"})};for(let G of v9({sandboxUserSid:J,srtWin:X})??[])Y("grant revoke",G);for(let G of x9({sandboxUserSid:J,srtWin:X})??[])Y("deny restore",G)}if(tQ=void 0,d0=void 0,y9=void 0,YY=void 0,j9({force:!0}),f9)f9(),f9=void 0;if(rQ)rQ.stop(),rQ=void 0;if(uJ?.linuxBridge){let{httpSocketPath:J,socksSocketPath:X,httpBridgeProcess:Q,socksBridgeProcess:Y}=uJ.linuxBridge;if(await Promise.all([JU(Q,"HTTP"),JU(Y,"SOCKS")]),J)try{c0.rmSync(J,{force:!0}),Z("Cleaned up HTTP socket")}catch(G){Z(`HTTP socket cleanup error: ${G}`,{level:"error"})}if(X)try{c0.rmSync(X,{force:!0}),Z("Cleaned up SOCKS socket")}catch(G){Z(`SOCKS socket cleanup error: ${G}`,{level:"error"})}}let $=[];if(u$)$.push(pW(u$));if(XY)$.push(XY.close().catch((J)=>{Z(`Error closing mux proxy server: ${J.message}`,{level:"error"})}));if(JY)$.push(vz(JY));if(QY){let J=QY.close().catch((X)=>{Z(`Error closing SOCKS proxy server: ${X.message}`,{level:"error"})});$.push(J)}await Promise.all($),XY=void 0,JY=void 0,i0=void 0,QY=void 0,uJ=void 0,p0=void 0,n0=void 0,u$=void 0,aJ.clear(),$X.clear(),GY.dispose()}async function NG(){if(eX)return eX;eX=kz();try{await eX}finally{eX=void 0}}function fz(){return NQ}function yz($,J){if(!v)return J;let X=NQ.getViolationsForCommand($);if(X.length===0)return J;let Q=J;Q+=OG+"<sandbox_violations>"+OG;for(let Y of X)Q+=Y.line+OG;return Q+="</sandbox_violations>",Q}function bz(){if(x$()!=="linux"||!v||v.filesystem.disabled)return[];let $=[],J=[...v.filesystem.allowWrite,...v.filesystem.denyWrite];for(let X of J){let Q=N0(X);if(NJ(Q))$.push(X)}return $}var hz={initialize:Uz,isSupportedPlatform:YU,isSandboxingEnabled:Mz,checkDependencies:Oz,checkDependenciesAsync:WU,getFsReadConfig:Vz,getFsWriteConfig:qz,getNetworkRestrictionConfig:Ez,getAllowUnixSockets:OU,getAllowLocalBinding:VU,getAllowMachLookup:qU,getIgnoreViolations:HU,getEnableWeakerNestedSandbox:KU,getProxyPort:zG,getProxyAuthToken:Sz,getSocksProxyPort:EG,getLinuxHttpSocketPath:EU,getLinuxSocksSocketPath:FU,waitForNetworkInitialization:FG,wrapWithSandbox:NU,wrapWithSandboxArgv:Iz,cleanupAfterCommand:_z,beginCredentialLease:()=>{aJ.beginLease(),eQ.beginLease()},endCredentialLease:()=>Object.assign(aJ.endLease(),{brokerForward:eQ.endLease()}),releaseCredentialLease:($)=>{eQ.release($.brokerForward??[]),$X.forget(aJ.release($))},reset:NG,getMitmCA:()=>u$,getSentinelRegistry:()=>aJ,getAwsPairRegistry:()=>$X,getMaskedFileStore:()=>GY,getSandboxViolationStore:fz,annotateStderrWithSandboxFailures:yz,getLinuxGlobPatternWarnings:bz,getConfig:Cz,updateConfig:Pz,clearMaskedCredentials:wz,setLiveCredentialInjectors:$z};import{isIP as aE}from"net";import{isAbsolute as sE}from"path";var _={};eU(_,{void:()=>ZE,util:()=>B$,unknown:()=>RE,union:()=>SE,undefined:()=>NE,tuple:()=>wE,transformer:()=>uE,symbol:()=>FE,string:()=>SU,strictObject:()=>TE,setErrorMap:()=>mz,set:()=>xE,record:()=>PE,quotelessJson:()=>uz,promise:()=>hE,preprocess:()=>lE,pipeline:()=>pE,ostring:()=>dE,optional:()=>gE,onumber:()=>cE,oboolean:()=>nE,objectUtil:()=>LG,object:()=>jE,number:()=>IU,nullable:()=>mE,null:()=>LE,never:()=>DE,nativeEnum:()=>bE,nan:()=>KE,map:()=>_E,makeIssue:()=>WY,literal:()=>fE,lazy:()=>kE,late:()=>qE,isValid:()=>o0,isDirty:()=>g9,isAsync:()=>QX,isAborted:()=>u9,intersection:()=>CE,instanceof:()=>HE,getParsedType:()=>K0,getErrorMap:()=>JX,function:()=>vE,enum:()=>yE,effect:()=>uE,discriminatedUnion:()=>IE,defaultErrorMap:()=>S0,datetimeRegex:()=>BU,date:()=>EE,custom:()=>TU,coerce:()=>iE,boolean:()=>CU,bigint:()=>zE,array:()=>BE,any:()=>AE,addIssueToContext:()=>c,ZodVoid:()=>MY,ZodUnknown:()=>a0,ZodUnion:()=>MX,ZodUndefined:()=>WX,ZodType:()=>N$,ZodTuple:()=>E0,ZodTransformer:()=>$0,ZodSymbol:()=>UY,ZodString:()=>sJ,ZodSet:()=>DQ,ZodSchema:()=>N$,ZodRecord:()=>OY,ZodReadonly:()=>EX,ZodPromise:()=>ZQ,ZodPipeline:()=>HY,ZodParsedType:()=>m,ZodOptional:()=>tJ,ZodObject:()=>n$,ZodNumber:()=>s0,ZodNullable:()=>C0,ZodNull:()=>UX,ZodNever:()=>z0,ZodNativeEnum:()=>HX,ZodNaN:()=>qY,ZodMap:()=>VY,ZodLiteral:()=>qX,ZodLazy:()=>VX,ZodIssueCode:()=>h,ZodIntersection:()=>OX,ZodFunction:()=>YX,ZodFirstPartyTypeKind:()=>M$,ZodError:()=>SJ,ZodEnum:()=>t0,ZodEffects:()=>$0,ZodDiscriminatedUnion:()=>m9,ZodDefault:()=>KX,ZodDate:()=>AQ,ZodCatch:()=>zX,ZodBranded:()=>l9,ZodBoolean:()=>GX,ZodBigInt:()=>r0,ZodArray:()=>rJ,ZodAny:()=>RQ,Schema:()=>N$,ParseStatus:()=>EJ,OK:()=>FJ,NEVER:()=>oE,INVALID:()=>G$,EMPTY_PATH:()=>lz,DIRTY:()=>LQ,BRAND:()=>VE});var B$;(function($){$.assertEqual=(Y)=>{};function J(Y){}$.assertIs=J;function X(Y){throw Error()}$.assertNever=X,$.arrayToEnum=(Y)=>{let G={};for(let W of Y)G[W]=W;return G},$.getValidEnumValues=(Y)=>{let G=$.objectKeys(Y).filter((U)=>typeof Y[Y[U]]!=="number"),W={};for(let U of G)W[U]=Y[U];return $.objectValues(W)},$.objectValues=(Y)=>{return $.objectKeys(Y).map(function(G){return Y[G]})},$.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let G=[];for(let W in Y)if(Object.prototype.hasOwnProperty.call(Y,W))G.push(W);return G},$.find=(Y,G)=>{for(let W of Y)if(G(W))return W;return},$.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function Q(Y,G=" | "){return Y.map((W)=>typeof W==="string"?`'${W}'`:W).join(G)}$.joinValues=Q,$.jsonStringifyReplacer=(Y,G)=>{if(typeof G==="bigint")return G.toString();return G}})(B$||(B$={}));var LG;(function($){$.mergeShapes=(J,X)=>{return{...J,...X}}})(LG||(LG={}));var m=B$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),K0=($)=>{switch(typeof $){case"undefined":return m.undefined;case"string":return m.string;case"number":return Number.isNaN($)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":if(Array.isArray($))return m.array;if($===null)return m.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return m.promise;if(typeof Map<"u"&&$ instanceof Map)return m.map;if(typeof Set<"u"&&$ instanceof Set)return m.set;if(typeof Date<"u"&&$ instanceof Date)return m.date;return m.object;default:return m.unknown}};var h=B$.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),uz=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class SJ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(X)=>{this.issues=[...this.issues,X]},this.addIssues=(X=[])=>{this.issues=[...this.issues,...X]};let J=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,J);else this.__proto__=J;this.name="ZodError",this.issues=$}format($){let J=$||function(Y){return Y.message},X={_errors:[]},Q=(Y)=>{for(let G of Y.issues)if(G.code==="invalid_union")G.unionErrors.map(Q);else if(G.code==="invalid_return_type")Q(G.returnTypeError);else if(G.code==="invalid_arguments")Q(G.argumentsError);else if(G.path.length===0)X._errors.push(J(G));else{let W=X,U=0;while(U<G.path.length){let M=G.path[U];if(U!==G.path.length-1)W[M]=W[M]||{_errors:[]};else W[M]=W[M]||{_errors:[]},W[M]._errors.push(J(G));W=W[M],U++}}};return Q(this),X}static assert($){if(!($ instanceof SJ))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,B$.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(J)=>J.message){let J={},X=[];for(let Q of this.issues)if(Q.path.length>0){let Y=Q.path[0];J[Y]=J[Y]||[],J[Y].push($(Q))}else X.push($(Q));return{formErrors:X,fieldErrors:J}}get formErrors(){return this.flatten()}}SJ.create=($)=>{return new SJ($)};var gz=($,J)=>{let X;switch($.code){case h.invalid_type:if($.received===m.undefined)X="Required";else X=`Expected ${$.expected}, received ${$.received}`;break;case h.invalid_literal:X=`Invalid literal value, expected ${JSON.stringify($.expected,B$.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:X=`Unrecognized key(s) in object: ${B$.joinValues($.keys,", ")}`;break;case h.invalid_union:X="Invalid input";break;case h.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${B$.joinValues($.options)}`;break;case h.invalid_enum_value:X=`Invalid enum value. Expected ${B$.joinValues($.options)}, received '${$.received}'`;break;case h.invalid_arguments:X="Invalid function arguments";break;case h.invalid_return_type:X="Invalid function return type";break;case h.invalid_date:X="Invalid date";break;case h.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(X=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")X=`${X} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)X=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)X=`Invalid input: must end with "${$.validation.endsWith}"`;else B$.assertNever($.validation);else if($.validation!=="regex")X=`Invalid ${$.validation}`;else X="Invalid";break;case h.too_small:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")X=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else X="Invalid input";break;case h.too_big:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")X=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else X="Invalid input";break;case h.custom:X="Invalid input";break;case h.invalid_intersection_types:X="Intersection results could not be merged";break;case h.not_multiple_of:X=`Number must be a multiple of ${$.multipleOf}`;break;case h.not_finite:X="Number must be finite";break;default:X=J.defaultError,B$.assertNever($)}return{message:X}},S0=gz;var LU=S0;function mz($){LU=$}function JX(){return LU}var WY=($)=>{let{data:J,path:X,errorMaps:Q,issueData:Y}=$,G=[...X,...Y.path||[]],W={...Y,path:G};if(Y.message!==void 0)return{...Y,path:G,message:Y.message};let U="",M=Q.filter((O)=>!!O).slice().reverse();for(let O of M)U=O(W,{data:J,defaultError:U}).message;return{...Y,path:G,message:U}},lz=[];function c($,J){let X=JX(),Q=WY({issueData:J,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,X,X===S0?void 0:S0].filter((Y)=>!!Y)});$.common.issues.push(Q)}class EJ{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,J){let X=[];for(let Q of J){if(Q.status==="aborted")return G$;if(Q.status==="dirty")$.dirty();X.push(Q.value)}return{status:$.value,value:X}}static async mergeObjectAsync($,J){let X=[];for(let Q of J){let Y=await Q.key,G=await Q.value;X.push({key:Y,value:G})}return EJ.mergeObjectSync($,X)}static mergeObjectSync($,J){let X={};for(let Q of J){let{key:Y,value:G}=Q;if(Y.status==="aborted")return G$;if(G.status==="aborted")return G$;if(Y.status==="dirty")$.dirty();if(G.status==="dirty")$.dirty();if(Y.value!=="__proto__"&&(typeof G.value<"u"||Q.alwaysSet))X[Y.value]=G.value}return{status:$.value,value:X}}}var G$=Object.freeze({status:"aborted"}),LQ=($)=>({status:"dirty",value:$}),FJ=($)=>({status:"valid",value:$}),u9=($)=>$.status==="aborted",g9=($)=>$.status==="dirty",o0=($)=>$.status==="valid",QX=($)=>typeof Promise<"u"&&$ instanceof Promise;var t;(function($){$.errToObj=(J)=>typeof J==="string"?{message:J}:J||{},$.toString=(J)=>typeof J==="string"?J:J?.message})(t||(t={}));class eJ{constructor($,J,X,Q){this._cachedPath=[],this.parent=$,this.data=J,this._path=X,this._key=Q}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var AU=($,J)=>{if(o0(J))return{success:!0,data:J.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let X=new SJ($.common.issues);return this._error=X,this._error}}}};function K$($){if(!$)return{};let{errorMap:J,invalid_type_error:X,required_error:Q,description:Y}=$;if(J&&(X||Q))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(J)return{errorMap:J,description:Y};return{errorMap:(W,U)=>{let{message:M}=$;if(W.code==="invalid_enum_value")return{message:M??U.defaultError};if(typeof U.data>"u")return{message:M??Q??U.defaultError};if(W.code!=="invalid_type")return{message:U.defaultError};return{message:M??X??U.defaultError}},description:Y}}class N${get description(){return this._def.description}_getType($){return K0($.data)}_getOrReturnCtx($,J){return J||{common:$.parent.common,data:$.data,parsedType:K0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new EJ,ctx:{common:$.parent.common,data:$.data,parsedType:K0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let J=this._parse($);if(QX(J))throw Error("Synchronous parse encountered promise.");return J}_parseAsync($){let J=this._parse($);return Promise.resolve(J)}parse($,J){let X=this.safeParse($,J);if(X.success)return X.data;throw X.error}safeParse($,J){let X={common:{issues:[],async:J?.async??!1,contextualErrorMap:J?.errorMap},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:K0($)},Q=this._parseSync({data:$,path:X.path,parent:X});return AU(X,Q)}"~validate"($){let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:K0($)};if(!this["~standard"].async)try{let X=this._parseSync({data:$,path:[],parent:J});return o0(X)?{value:X.value}:{issues:J.common.issues}}catch(X){if(X?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:J}).then((X)=>o0(X)?{value:X.value}:{issues:J.common.issues})}async parseAsync($,J){let X=await this.safeParseAsync($,J);if(X.success)return X.data;throw X.error}async safeParseAsync($,J){let X={common:{issues:[],contextualErrorMap:J?.errorMap,async:!0},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:K0($)},Q=this._parse({data:$,path:X.path,parent:X}),Y=await(QX(Q)?Q:Promise.resolve(Q));return AU(X,Y)}refine($,J){let X=(Q)=>{if(typeof J==="string"||typeof J>"u")return{message:J};else if(typeof J==="function")return J(Q);else return J};return this._refinement((Q,Y)=>{let G=$(Q),W=()=>Y.addIssue({code:h.custom,...X(Q)});if(typeof Promise<"u"&&G instanceof Promise)return G.then((U)=>{if(!U)return W(),!1;else return!0});if(!G)return W(),!1;else return!0})}refinement($,J){return this._refinement((X,Q)=>{if(!$(X))return Q.addIssue(typeof J==="function"?J(X,Q):J),!1;else return!0})}_refinement($){return new $0({schema:this,typeName:M$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(J)=>this["~validate"](J)}}optional(){return tJ.create(this,this._def)}nullable(){return C0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return rJ.create(this)}promise(){return ZQ.create(this,this._def)}or($){return MX.create([this,$],this._def)}and($){return OX.create(this,$,this._def)}transform($){return new $0({...K$(this._def),schema:this,typeName:M$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let J=typeof $==="function"?$:()=>$;return new KX({...K$(this._def),innerType:this,defaultValue:J,typeName:M$.ZodDefault})}brand(){return new l9({typeName:M$.ZodBranded,type:this,...K$(this._def)})}catch($){let J=typeof $==="function"?$:()=>$;return new zX({...K$(this._def),innerType:this,catchValue:J,typeName:M$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return HY.create(this,$)}readonly(){return EX.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var pz=/^c[^\s-]{8,}$/i,dz=/^[0-9a-z]+$/,cz=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nz=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,iz=/^[a-z0-9_-]{21}$/i,oz=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,az=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sz=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,rz="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",AG,tz=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ez=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,$E=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,JE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,QE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,XE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,DU="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",YE=new RegExp(`^${DU}$`);function ZU($){let J="[0-5]\\d";if($.precision)J=`${J}\\.\\d{${$.precision}}`;else if($.precision==null)J=`${J}(\\.\\d+)?`;let X=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${J})${X}`}function GE($){return new RegExp(`^${ZU($)}$`)}function BU($){let J=`${DU}T${ZU($)}`,X=[];if(X.push($.local?"Z?":"Z"),$.offset)X.push("([+-]\\d{2}:?\\d{2})");return J=`${J}(${X.join("|")})`,new RegExp(`^${J}$`)}function WE($,J){if((J==="v4"||!J)&&tz.test($))return!0;if((J==="v6"||!J)&&$E.test($))return!0;return!1}function UE($,J){if(!oz.test($))return!1;try{let[X]=$.split(".");if(!X)return!1;let Q=X.replace(/-/g,"+").replace(/_/g,"/").padEnd(X.length+(4-X.length%4)%4,"="),Y=JSON.parse(atob(Q));if(typeof Y!=="object"||Y===null)return!1;if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(J&&Y.alg!==J)return!1;return!0}catch{return!1}}function ME($,J){if((J==="v4"||!J)&&ez.test($))return!0;if((J==="v6"||!J)&&JE.test($))return!0;return!1}class sJ extends N${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==m.string){let Y=this._getOrReturnCtx($);return c(Y,{code:h.invalid_type,expected:m.string,received:Y.parsedType}),G$}let X=new EJ,Q=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.length<Y.value)Q=this._getOrReturnCtx($,Q),c(Q,{code:h.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if($.data.length>Y.value)Q=this._getOrReturnCtx($,Q),c(Q,{code:h.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="length"){let G=$.data.length>Y.value,W=$.data.length<Y.value;if(G||W){if(Q=this._getOrReturnCtx($,Q),G)c(Q,{code:h.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(W)c(Q,{code:h.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});X.dirty()}}else if(Y.kind==="email"){if(!sz.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"email",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="emoji"){if(!AG)AG=new RegExp(rz,"u");if(!AG.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"emoji",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="uuid"){if(!nz.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"uuid",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="nanoid"){if(!iz.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"nanoid",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="cuid"){if(!pz.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"cuid",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="cuid2"){if(!dz.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"cuid2",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="ulid"){if(!cz.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"ulid",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="url")try{new URL($.data)}catch{Q=this._getOrReturnCtx($,Q),c(Q,{validation:"url",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"regex",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="trim")$.data=$.data.trim();else if(Y.kind==="includes"){if(!$.data.includes(Y.value,Y.position))Q=this._getOrReturnCtx($,Q),c(Q,{code:h.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),X.dirty()}else if(Y.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(Y.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(Y.kind==="startsWith"){if(!$.data.startsWith(Y.value))Q=this._getOrReturnCtx($,Q),c(Q,{code:h.invalid_string,validation:{startsWith:Y.value},message:Y.message}),X.dirty()}else if(Y.kind==="endsWith"){if(!$.data.endsWith(Y.value))Q=this._getOrReturnCtx($,Q),c(Q,{code:h.invalid_string,validation:{endsWith:Y.value},message:Y.message}),X.dirty()}else if(Y.kind==="datetime"){if(!BU(Y).test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{code:h.invalid_string,validation:"datetime",message:Y.message}),X.dirty()}else if(Y.kind==="date"){if(!YE.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{code:h.invalid_string,validation:"date",message:Y.message}),X.dirty()}else if(Y.kind==="time"){if(!GE(Y).test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{code:h.invalid_string,validation:"time",message:Y.message}),X.dirty()}else if(Y.kind==="duration"){if(!az.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"duration",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="ip"){if(!WE($.data,Y.version))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"ip",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="jwt"){if(!UE($.data,Y.alg))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"jwt",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="cidr"){if(!ME($.data,Y.version))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"cidr",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="base64"){if(!QE.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"base64",code:h.invalid_string,message:Y.message}),X.dirty()}else if(Y.kind==="base64url"){if(!XE.test($.data))Q=this._getOrReturnCtx($,Q),c(Q,{validation:"base64url",code:h.invalid_string,message:Y.message}),X.dirty()}else B$.assertNever(Y);return{status:X.value,value:$.data}}_regex($,J,X){return this.refinement((Q)=>$.test(Q),{validation:J,code:h.invalid_string,...t.errToObj(X)})}_addCheck($){return new sJ({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...t.errToObj($)})}url($){return this._addCheck({kind:"url",...t.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...t.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...t.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...t.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...t.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...t.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...t.errToObj($)})}base64($){return this._addCheck({kind:"base64",...t.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...t.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...t.errToObj($)})}ip($){return this._addCheck({kind:"ip",...t.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...t.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...t.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...t.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...t.errToObj($)})}regex($,J){return this._addCheck({kind:"regex",regex:$,...t.errToObj(J)})}includes($,J){return this._addCheck({kind:"includes",value:$,position:J?.position,...t.errToObj(J?.message)})}startsWith($,J){return this._addCheck({kind:"startsWith",value:$,...t.errToObj(J)})}endsWith($,J){return this._addCheck({kind:"endsWith",value:$,...t.errToObj(J)})}min($,J){return this._addCheck({kind:"min",value:$,...t.errToObj(J)})}max($,J){return this._addCheck({kind:"max",value:$,...t.errToObj(J)})}length($,J){return this._addCheck({kind:"length",value:$,...t.errToObj(J)})}nonempty($){return this.min(1,t.errToObj($))}trim(){return new sJ({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new sJ({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new sJ({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxLength(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}sJ.create=($)=>{return new sJ({checks:[],typeName:M$.ZodString,coerce:$?.coerce??!1,...K$($)})};function OE($,J){let X=($.toString().split(".")[1]||"").length,Q=(J.toString().split(".")[1]||"").length,Y=X>Q?X:Q,G=Number.parseInt($.toFixed(Y).replace(".","")),W=Number.parseInt(J.toFixed(Y).replace(".",""));return G%W/10**Y}class s0 extends N${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==m.number){let Y=this._getOrReturnCtx($);return c(Y,{code:h.invalid_type,expected:m.number,received:Y.parsedType}),G$}let X=void 0,Q=new EJ;for(let Y of this._def.checks)if(Y.kind==="int"){if(!B$.isInteger($.data))X=this._getOrReturnCtx($,X),c(X,{code:h.invalid_type,expected:"integer",received:"float",message:Y.message}),Q.dirty()}else if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)X=this._getOrReturnCtx($,X),c(X,{code:h.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),Q.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)X=this._getOrReturnCtx($,X),c(X,{code:h.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),Q.dirty()}else if(Y.kind==="multipleOf"){if(OE($.data,Y.value)!==0)X=this._getOrReturnCtx($,X),c(X,{code:h.not_multiple_of,multipleOf:Y.value,message:Y.message}),Q.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite($.data))X=this._getOrReturnCtx($,X),c(X,{code:h.not_finite,message:Y.message}),Q.dirty()}else B$.assertNever(Y);return{status:Q.value,value:$.data}}gte($,J){return this.setLimit("min",$,!0,t.toString(J))}gt($,J){return this.setLimit("min",$,!1,t.toString(J))}lte($,J){return this.setLimit("max",$,!0,t.toString(J))}lt($,J){return this.setLimit("max",$,!1,t.toString(J))}setLimit($,J,X,Q){return new s0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:X,message:t.toString(Q)}]})}_addCheck($){return new s0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:t.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:t.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:t.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:t.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:t.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:t.toString(J)})}finite($){return this._addCheck({kind:"finite",message:t.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:t.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:t.toString($)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&B$.isInteger($.value))}get isFinite(){let $=null,J=null;for(let X of this._def.checks)if(X.kind==="finite"||X.kind==="int"||X.kind==="multipleOf")return!0;else if(X.kind==="min"){if(J===null||X.value>J)J=X.value}else if(X.kind==="max"){if($===null||X.value<$)$=X.value}return Number.isFinite(J)&&Number.isFinite($)}}s0.create=($)=>{return new s0({checks:[],typeName:M$.ZodNumber,coerce:$?.coerce||!1,...K$($)})};class r0 extends N${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==m.bigint)return this._getInvalidInput($);let X=void 0,Q=new EJ;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)X=this._getOrReturnCtx($,X),c(X,{code:h.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),Q.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)X=this._getOrReturnCtx($,X),c(X,{code:h.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),Q.dirty()}else if(Y.kind==="multipleOf"){if($.data%Y.value!==BigInt(0))X=this._getOrReturnCtx($,X),c(X,{code:h.not_multiple_of,multipleOf:Y.value,message:Y.message}),Q.dirty()}else B$.assertNever(Y);return{status:Q.value,value:$.data}}_getInvalidInput($){let J=this._getOrReturnCtx($);return c(J,{code:h.invalid_type,expected:m.bigint,received:J.parsedType}),G$}gte($,J){return this.setLimit("min",$,!0,t.toString(J))}gt($,J){return this.setLimit("min",$,!1,t.toString(J))}lte($,J){return this.setLimit("max",$,!0,t.toString(J))}lt($,J){return this.setLimit("max",$,!1,t.toString(J))}setLimit($,J,X,Q){return new r0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:X,message:t.toString(Q)}]})}_addCheck($){return new r0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:t.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:t.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:t.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:t.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:t.toString(J)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}r0.create=($)=>{return new r0({checks:[],typeName:M$.ZodBigInt,coerce:$?.coerce??!1,...K$($)})};class GX extends N${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==m.boolean){let X=this._getOrReturnCtx($);return c(X,{code:h.invalid_type,expected:m.boolean,received:X.parsedType}),G$}return FJ($.data)}}GX.create=($)=>{return new GX({typeName:M$.ZodBoolean,coerce:$?.coerce||!1,...K$($)})};class AQ extends N${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==m.date){let Y=this._getOrReturnCtx($);return c(Y,{code:h.invalid_type,expected:m.date,received:Y.parsedType}),G$}if(Number.isNaN($.data.getTime())){let Y=this._getOrReturnCtx($);return c(Y,{code:h.invalid_date}),G$}let X=new EJ,Q=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.getTime()<Y.value)Q=this._getOrReturnCtx($,Q),c(Q,{code:h.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),X.dirty()}else if(Y.kind==="max"){if($.data.getTime()>Y.value)Q=this._getOrReturnCtx($,Q),c(Q,{code:h.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),X.dirty()}else B$.assertNever(Y);return{status:X.value,value:new Date($.data.getTime())}}_addCheck($){return new AQ({...this._def,checks:[...this._def.checks,$]})}min($,J){return this._addCheck({kind:"min",value:$.getTime(),message:t.toString(J)})}max($,J){return this._addCheck({kind:"max",value:$.getTime(),message:t.toString(J)})}get minDate(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $!=null?new Date($):null}}AQ.create=($)=>{return new AQ({checks:[],coerce:$?.coerce||!1,typeName:M$.ZodDate,...K$($)})};class UY extends N${_parse($){if(this._getType($)!==m.symbol){let X=this._getOrReturnCtx($);return c(X,{code:h.invalid_type,expected:m.symbol,received:X.parsedType}),G$}return FJ($.data)}}UY.create=($)=>{return new UY({typeName:M$.ZodSymbol,...K$($)})};class WX extends N${_parse($){if(this._getType($)!==m.undefined){let X=this._getOrReturnCtx($);return c(X,{code:h.invalid_type,expected:m.undefined,received:X.parsedType}),G$}return FJ($.data)}}WX.create=($)=>{return new WX({typeName:M$.ZodUndefined,...K$($)})};class UX extends N${_parse($){if(this._getType($)!==m.null){let X=this._getOrReturnCtx($);return c(X,{code:h.invalid_type,expected:m.null,received:X.parsedType}),G$}return FJ($.data)}}UX.create=($)=>{return new UX({typeName:M$.ZodNull,...K$($)})};class RQ extends N${constructor(){super(...arguments);this._any=!0}_parse($){return FJ($.data)}}RQ.create=($)=>{return new RQ({typeName:M$.ZodAny,...K$($)})};class a0 extends N${constructor(){super(...arguments);this._unknown=!0}_parse($){return FJ($.data)}}a0.create=($)=>{return new a0({typeName:M$.ZodUnknown,...K$($)})};class z0 extends N${_parse($){let J=this._getOrReturnCtx($);return c(J,{code:h.invalid_type,expected:m.never,received:J.parsedType}),G$}}z0.create=($)=>{return new z0({typeName:M$.ZodNever,...K$($)})};class MY extends N${_parse($){if(this._getType($)!==m.undefined){let X=this._getOrReturnCtx($);return c(X,{code:h.invalid_type,expected:m.void,received:X.parsedType}),G$}return FJ($.data)}}MY.create=($)=>{return new MY({typeName:M$.ZodVoid,...K$($)})};class rJ extends N${_parse($){let{ctx:J,status:X}=this._processInputParams($),Q=this._def;if(J.parsedType!==m.array)return c(J,{code:h.invalid_type,expected:m.array,received:J.parsedType}),G$;if(Q.exactLength!==null){let G=J.data.length>Q.exactLength.value,W=J.data.length<Q.exactLength.value;if(G||W)c(J,{code:G?h.too_big:h.too_small,minimum:W?Q.exactLength.value:void 0,maximum:G?Q.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Q.exactLength.message}),X.dirty()}if(Q.minLength!==null){if(J.data.length<Q.minLength.value)c(J,{code:h.too_small,minimum:Q.minLength.value,type:"array",inclusive:!0,exact:!1,message:Q.minLength.message}),X.dirty()}if(Q.maxLength!==null){if(J.data.length>Q.maxLength.value)c(J,{code:h.too_big,maximum:Q.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Q.maxLength.message}),X.dirty()}if(J.common.async)return Promise.all([...J.data].map((G,W)=>{return Q.type._parseAsync(new eJ(J,G,J.path,W))})).then((G)=>{return EJ.mergeArray(X,G)});let Y=[...J.data].map((G,W)=>{return Q.type._parseSync(new eJ(J,G,J.path,W))});return EJ.mergeArray(X,Y)}get element(){return this._def.type}min($,J){return new rJ({...this._def,minLength:{value:$,message:t.toString(J)}})}max($,J){return new rJ({...this._def,maxLength:{value:$,message:t.toString(J)}})}length($,J){return new rJ({...this._def,exactLength:{value:$,message:t.toString(J)}})}nonempty($){return this.min(1,$)}}rJ.create=($,J)=>{return new rJ({type:$,minLength:null,maxLength:null,exactLength:null,typeName:M$.ZodArray,...K$(J)})};function XX($){if($ instanceof n$){let J={};for(let X in $.shape){let Q=$.shape[X];J[X]=tJ.create(XX(Q))}return new n$({...$._def,shape:()=>J})}else if($ instanceof rJ)return new rJ({...$._def,type:XX($.element)});else if($ instanceof tJ)return tJ.create(XX($.unwrap()));else if($ instanceof C0)return C0.create(XX($.unwrap()));else if($ instanceof E0)return E0.create($.items.map((J)=>XX(J)));else return $}class n$ extends N${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),J=B$.objectKeys($);return this._cached={shape:$,keys:J},this._cached}_parse($){if(this._getType($)!==m.object){let M=this._getOrReturnCtx($);return c(M,{code:h.invalid_type,expected:m.object,received:M.parsedType}),G$}let{status:X,ctx:Q}=this._processInputParams($),{shape:Y,keys:G}=this._getCached(),W=[];if(!(this._def.catchall instanceof z0&&this._def.unknownKeys==="strip")){for(let M in Q.data)if(!G.includes(M))W.push(M)}let U=[];for(let M of G){let O=Y[M],V=Q.data[M];U.push({key:{status:"valid",value:M},value:O._parse(new eJ(Q,V,Q.path,M)),alwaysSet:M in Q.data})}if(this._def.catchall instanceof z0){let M=this._def.unknownKeys;if(M==="passthrough")for(let O of W)U.push({key:{status:"valid",value:O},value:{status:"valid",value:Q.data[O]}});else if(M==="strict"){if(W.length>0)c(Q,{code:h.unrecognized_keys,keys:W}),X.dirty()}else if(M==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let M=this._def.catchall;for(let O of W){let V=Q.data[O];U.push({key:{status:"valid",value:O},value:M._parse(new eJ(Q,V,Q.path,O)),alwaysSet:O in Q.data})}}if(Q.common.async)return Promise.resolve().then(async()=>{let M=[];for(let O of U){let V=await O.key,q=await O.value;M.push({key:V,value:q,alwaysSet:O.alwaysSet})}return M}).then((M)=>{return EJ.mergeObjectSync(X,M)});else return EJ.mergeObjectSync(X,U)}get shape(){return this._def.shape()}strict($){return t.errToObj,new n$({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(J,X)=>{let Q=this._def.errorMap?.(J,X).message??X.defaultError;if(J.code==="unrecognized_keys")return{message:t.errToObj($).message??Q};return{message:Q}}}:{}})}strip(){return new n$({...this._def,unknownKeys:"strip"})}passthrough(){return new n$({...this._def,unknownKeys:"passthrough"})}extend($){return new n$({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new n$({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:M$.ZodObject})}setKey($,J){return this.augment({[$]:J})}catchall($){return new n$({...this._def,catchall:$})}pick($){let J={};for(let X of B$.objectKeys($))if($[X]&&this.shape[X])J[X]=this.shape[X];return new n$({...this._def,shape:()=>J})}omit($){let J={};for(let X of B$.objectKeys(this.shape))if(!$[X])J[X]=this.shape[X];return new n$({...this._def,shape:()=>J})}deepPartial(){return XX(this)}partial($){let J={};for(let X of B$.objectKeys(this.shape)){let Q=this.shape[X];if($&&!$[X])J[X]=Q;else J[X]=Q.optional()}return new n$({...this._def,shape:()=>J})}required($){let J={};for(let X of B$.objectKeys(this.shape))if($&&!$[X])J[X]=this.shape[X];else{let Y=this.shape[X];while(Y instanceof tJ)Y=Y._def.innerType;J[X]=Y}return new n$({...this._def,shape:()=>J})}keyof(){return jU(B$.objectKeys(this.shape))}}n$.create=($,J)=>{return new n$({shape:()=>$,unknownKeys:"strip",catchall:z0.create(),typeName:M$.ZodObject,...K$(J)})};n$.strictCreate=($,J)=>{return new n$({shape:()=>$,unknownKeys:"strict",catchall:z0.create(),typeName:M$.ZodObject,...K$(J)})};n$.lazycreate=($,J)=>{return new n$({shape:$,unknownKeys:"strip",catchall:z0.create(),typeName:M$.ZodObject,...K$(J)})};class MX extends N${_parse($){let{ctx:J}=this._processInputParams($),X=this._def.options;function Q(Y){for(let W of Y)if(W.result.status==="valid")return W.result;for(let W of Y)if(W.result.status==="dirty")return J.common.issues.push(...W.ctx.common.issues),W.result;let G=Y.map((W)=>new SJ(W.ctx.common.issues));return c(J,{code:h.invalid_union,unionErrors:G}),G$}if(J.common.async)return Promise.all(X.map(async(Y)=>{let G={...J,common:{...J.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:J.data,path:J.path,parent:G}),ctx:G}})).then(Q);else{let Y=void 0,G=[];for(let U of X){let M={...J,common:{...J.common,issues:[]},parent:null},O=U._parseSync({data:J.data,path:J.path,parent:M});if(O.status==="valid")return O;else if(O.status==="dirty"&&!Y)Y={result:O,ctx:M};if(M.common.issues.length)G.push(M.common.issues)}if(Y)return J.common.issues.push(...Y.ctx.common.issues),Y.result;let W=G.map((U)=>new SJ(U));return c(J,{code:h.invalid_union,unionErrors:W}),G$}}get options(){return this._def.options}}MX.create=($,J)=>{return new MX({options:$,typeName:M$.ZodUnion,...K$(J)})};var I0=($)=>{if($ instanceof VX)return I0($.schema);else if($ instanceof $0)return I0($.innerType());else if($ instanceof qX)return[$.value];else if($ instanceof t0)return $.options;else if($ instanceof HX)return B$.objectValues($.enum);else if($ instanceof KX)return I0($._def.innerType);else if($ instanceof WX)return[void 0];else if($ instanceof UX)return[null];else if($ instanceof tJ)return[void 0,...I0($.unwrap())];else if($ instanceof C0)return[null,...I0($.unwrap())];else if($ instanceof l9)return I0($.unwrap());else if($ instanceof EX)return I0($.unwrap());else if($ instanceof zX)return I0($._def.innerType);else return[]};class m9 extends N${_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==m.object)return c(J,{code:h.invalid_type,expected:m.object,received:J.parsedType}),G$;let X=this.discriminator,Q=J.data[X],Y=this.optionsMap.get(Q);if(!Y)return c(J,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[X]}),G$;if(J.common.async)return Y._parseAsync({data:J.data,path:J.path,parent:J});else return Y._parseSync({data:J.data,path:J.path,parent:J})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,J,X){let Q=new Map;for(let Y of J){let G=I0(Y.shape[$]);if(!G.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let W of G){if(Q.has(W))throw Error(`Discriminator property ${String($)} has duplicate value ${String(W)}`);Q.set(W,Y)}}return new m9({typeName:M$.ZodDiscriminatedUnion,discriminator:$,options:J,optionsMap:Q,...K$(X)})}}function RG($,J){let X=K0($),Q=K0(J);if($===J)return{valid:!0,data:$};else if(X===m.object&&Q===m.object){let Y=B$.objectKeys(J),G=B$.objectKeys($).filter((U)=>Y.indexOf(U)!==-1),W={...$,...J};for(let U of G){let M=RG($[U],J[U]);if(!M.valid)return{valid:!1};W[U]=M.data}return{valid:!0,data:W}}else if(X===m.array&&Q===m.array){if($.length!==J.length)return{valid:!1};let Y=[];for(let G=0;G<$.length;G++){let W=$[G],U=J[G],M=RG(W,U);if(!M.valid)return{valid:!1};Y.push(M.data)}return{valid:!0,data:Y}}else if(X===m.date&&Q===m.date&&+$===+J)return{valid:!0,data:$};else return{valid:!1}}class OX extends N${_parse($){let{status:J,ctx:X}=this._processInputParams($),Q=(Y,G)=>{if(u9(Y)||u9(G))return G$;let W=RG(Y.value,G.value);if(!W.valid)return c(X,{code:h.invalid_intersection_types}),G$;if(g9(Y)||g9(G))J.dirty();return{status:J.value,value:W.data}};if(X.common.async)return Promise.all([this._def.left._parseAsync({data:X.data,path:X.path,parent:X}),this._def.right._parseAsync({data:X.data,path:X.path,parent:X})]).then(([Y,G])=>Q(Y,G));else return Q(this._def.left._parseSync({data:X.data,path:X.path,parent:X}),this._def.right._parseSync({data:X.data,path:X.path,parent:X}))}}OX.create=($,J,X)=>{return new OX({left:$,right:J,typeName:M$.ZodIntersection,...K$(X)})};class E0 extends N${_parse($){let{status:J,ctx:X}=this._processInputParams($);if(X.parsedType!==m.array)return c(X,{code:h.invalid_type,expected:m.array,received:X.parsedType}),G$;if(X.data.length<this._def.items.length)return c(X,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G$;if(!this._def.rest&&X.data.length>this._def.items.length)c(X,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J.dirty();let Y=[...X.data].map((G,W)=>{let U=this._def.items[W]||this._def.rest;if(!U)return null;return U._parse(new eJ(X,G,X.path,W))}).filter((G)=>!!G);if(X.common.async)return Promise.all(Y).then((G)=>{return EJ.mergeArray(J,G)});else return EJ.mergeArray(J,Y)}get items(){return this._def.items}rest($){return new E0({...this._def,rest:$})}}E0.create=($,J)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new E0({items:$,typeName:M$.ZodTuple,rest:null,...K$(J)})};class OY extends N${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:X}=this._processInputParams($);if(X.parsedType!==m.object)return c(X,{code:h.invalid_type,expected:m.object,received:X.parsedType}),G$;let Q=[],Y=this._def.keyType,G=this._def.valueType;for(let W in X.data)Q.push({key:Y._parse(new eJ(X,W,X.path,W)),value:G._parse(new eJ(X,X.data[W],X.path,W)),alwaysSet:W in X.data});if(X.common.async)return EJ.mergeObjectAsync(J,Q);else return EJ.mergeObjectSync(J,Q)}get element(){return this._def.valueType}static create($,J,X){if(J instanceof N$)return new OY({keyType:$,valueType:J,typeName:M$.ZodRecord,...K$(X)});return new OY({keyType:sJ.create(),valueType:$,typeName:M$.ZodRecord,...K$(J)})}}class VY extends N${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:X}=this._processInputParams($);if(X.parsedType!==m.map)return c(X,{code:h.invalid_type,expected:m.map,received:X.parsedType}),G$;let Q=this._def.keyType,Y=this._def.valueType,G=[...X.data.entries()].map(([W,U],M)=>{return{key:Q._parse(new eJ(X,W,X.path,[M,"key"])),value:Y._parse(new eJ(X,U,X.path,[M,"value"]))}});if(X.common.async){let W=new Map;return Promise.resolve().then(async()=>{for(let U of G){let M=await U.key,O=await U.value;if(M.status==="aborted"||O.status==="aborted")return G$;if(M.status==="dirty"||O.status==="dirty")J.dirty();W.set(M.value,O.value)}return{status:J.value,value:W}})}else{let W=new Map;for(let U of G){let{key:M,value:O}=U;if(M.status==="aborted"||O.status==="aborted")return G$;if(M.status==="dirty"||O.status==="dirty")J.dirty();W.set(M.value,O.value)}return{status:J.value,value:W}}}}VY.create=($,J,X)=>{return new VY({valueType:J,keyType:$,typeName:M$.ZodMap,...K$(X)})};class DQ extends N${_parse($){let{status:J,ctx:X}=this._processInputParams($);if(X.parsedType!==m.set)return c(X,{code:h.invalid_type,expected:m.set,received:X.parsedType}),G$;let Q=this._def;if(Q.minSize!==null){if(X.data.size<Q.minSize.value)c(X,{code:h.too_small,minimum:Q.minSize.value,type:"set",inclusive:!0,exact:!1,message:Q.minSize.message}),J.dirty()}if(Q.maxSize!==null){if(X.data.size>Q.maxSize.value)c(X,{code:h.too_big,maximum:Q.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Q.maxSize.message}),J.dirty()}let Y=this._def.valueType;function G(U){let M=new Set;for(let O of U){if(O.status==="aborted")return G$;if(O.status==="dirty")J.dirty();M.add(O.value)}return{status:J.value,value:M}}let W=[...X.data.values()].map((U,M)=>Y._parse(new eJ(X,U,X.path,M)));if(X.common.async)return Promise.all(W).then((U)=>G(U));else return G(W)}min($,J){return new DQ({...this._def,minSize:{value:$,message:t.toString(J)}})}max($,J){return new DQ({...this._def,maxSize:{value:$,message:t.toString(J)}})}size($,J){return this.min($,J).max($,J)}nonempty($){return this.min(1,$)}}DQ.create=($,J)=>{return new DQ({valueType:$,minSize:null,maxSize:null,typeName:M$.ZodSet,...K$(J)})};class YX extends N${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==m.function)return c(J,{code:h.invalid_type,expected:m.function,received:J.parsedType}),G$;function X(W,U){return WY({data:W,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,JX(),S0].filter((M)=>!!M),issueData:{code:h.invalid_arguments,argumentsError:U}})}function Q(W,U){return WY({data:W,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,JX(),S0].filter((M)=>!!M),issueData:{code:h.invalid_return_type,returnTypeError:U}})}let Y={errorMap:J.common.contextualErrorMap},G=J.data;if(this._def.returns instanceof ZQ){let W=this;return FJ(async function(...U){let M=new SJ([]),O=await W._def.args.parseAsync(U,Y).catch((H)=>{throw M.addIssue(X(U,H)),M}),V=await Reflect.apply(G,this,O);return await W._def.returns._def.type.parseAsync(V,Y).catch((H)=>{throw M.addIssue(Q(V,H)),M})})}else{let W=this;return FJ(function(...U){let M=W._def.args.safeParse(U,Y);if(!M.success)throw new SJ([X(U,M.error)]);let O=Reflect.apply(G,this,M.data),V=W._def.returns.safeParse(O,Y);if(!V.success)throw new SJ([Q(O,V.error)]);return V.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new YX({...this._def,args:E0.create($).rest(a0.create())})}returns($){return new YX({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,J,X){return new YX({args:$?$:E0.create([]).rest(a0.create()),returns:J||a0.create(),typeName:M$.ZodFunction,...K$(X)})}}class VX extends N${get schema(){return this._def.getter()}_parse($){let{ctx:J}=this._processInputParams($);return this._def.getter()._parse({data:J.data,path:J.path,parent:J})}}VX.create=($,J)=>{return new VX({getter:$,typeName:M$.ZodLazy,...K$(J)})};class qX extends N${_parse($){if($.data!==this._def.value){let J=this._getOrReturnCtx($);return c(J,{received:J.data,code:h.invalid_literal,expected:this._def.value}),G$}return{status:"valid",value:$.data}}get value(){return this._def.value}}qX.create=($,J)=>{return new qX({value:$,typeName:M$.ZodLiteral,...K$(J)})};function jU($,J){return new t0({values:$,typeName:M$.ZodEnum,...K$(J)})}class t0 extends N${_parse($){if(typeof $.data!=="string"){let J=this._getOrReturnCtx($),X=this._def.values;return c(J,{expected:B$.joinValues(X),received:J.parsedType,code:h.invalid_type}),G$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let J=this._getOrReturnCtx($),X=this._def.values;return c(J,{received:J.data,code:h.invalid_enum_value,options:X}),G$}return FJ($.data)}get options(){return this._def.values}get enum(){let $={};for(let J of this._def.values)$[J]=J;return $}get Values(){let $={};for(let J of this._def.values)$[J]=J;return $}get Enum(){let $={};for(let J of this._def.values)$[J]=J;return $}extract($,J=this._def){return t0.create($,{...this._def,...J})}exclude($,J=this._def){return t0.create(this.options.filter((X)=>!$.includes(X)),{...this._def,...J})}}t0.create=jU;class HX extends N${_parse($){let J=B$.getValidEnumValues(this._def.values),X=this._getOrReturnCtx($);if(X.parsedType!==m.string&&X.parsedType!==m.number){let Q=B$.objectValues(J);return c(X,{expected:B$.joinValues(Q),received:X.parsedType,code:h.invalid_type}),G$}if(!this._cache)this._cache=new Set(B$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let Q=B$.objectValues(J);return c(X,{received:X.data,code:h.invalid_enum_value,options:Q}),G$}return FJ($.data)}get enum(){return this._def.values}}HX.create=($,J)=>{return new HX({values:$,typeName:M$.ZodNativeEnum,...K$(J)})};class ZQ extends N${unwrap(){return this._def.type}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==m.promise&&J.common.async===!1)return c(J,{code:h.invalid_type,expected:m.promise,received:J.parsedType}),G$;let X=J.parsedType===m.promise?J.data:Promise.resolve(J.data);return FJ(X.then((Q)=>{return this._def.type.parseAsync(Q,{path:J.path,errorMap:J.common.contextualErrorMap})}))}}ZQ.create=($,J)=>{return new ZQ({type:$,typeName:M$.ZodPromise,...K$(J)})};class $0 extends N${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:J,ctx:X}=this._processInputParams($),Q=this._def.effect||null,Y={addIssue:(G)=>{if(c(X,G),G.fatal)J.abort();else J.dirty()},get path(){return X.path}};if(Y.addIssue=Y.addIssue.bind(Y),Q.type==="preprocess"){let G=Q.transform(X.data,Y);if(X.common.async)return Promise.resolve(G).then(async(W)=>{if(J.value==="aborted")return G$;let U=await this._def.schema._parseAsync({data:W,path:X.path,parent:X});if(U.status==="aborted")return G$;if(U.status==="dirty")return LQ(U.value);if(J.value==="dirty")return LQ(U.value);return U});else{if(J.value==="aborted")return G$;let W=this._def.schema._parseSync({data:G,path:X.path,parent:X});if(W.status==="aborted")return G$;if(W.status==="dirty")return LQ(W.value);if(J.value==="dirty")return LQ(W.value);return W}}if(Q.type==="refinement"){let G=(W)=>{let U=Q.refinement(W,Y);if(X.common.async)return Promise.resolve(U);if(U instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return W};if(X.common.async===!1){let W=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(W.status==="aborted")return G$;if(W.status==="dirty")J.dirty();return G(W.value),{status:J.value,value:W.value}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((W)=>{if(W.status==="aborted")return G$;if(W.status==="dirty")J.dirty();return G(W.value).then(()=>{return{status:J.value,value:W.value}})})}if(Q.type==="transform")if(X.common.async===!1){let G=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(!o0(G))return G$;let W=Q.transform(G.value,Y);if(W instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:J.value,value:W}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((G)=>{if(!o0(G))return G$;return Promise.resolve(Q.transform(G.value,Y)).then((W)=>({status:J.value,value:W}))});B$.assertNever(Q)}}$0.create=($,J,X)=>{return new $0({schema:$,typeName:M$.ZodEffects,effect:J,...K$(X)})};$0.createWithPreprocess=($,J,X)=>{return new $0({schema:J,effect:{type:"preprocess",transform:$},typeName:M$.ZodEffects,...K$(X)})};class tJ extends N${_parse($){if(this._getType($)===m.undefined)return FJ(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}tJ.create=($,J)=>{return new tJ({innerType:$,typeName:M$.ZodOptional,...K$(J)})};class C0 extends N${_parse($){if(this._getType($)===m.null)return FJ(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}C0.create=($,J)=>{return new C0({innerType:$,typeName:M$.ZodNullable,...K$(J)})};class KX extends N${_parse($){let{ctx:J}=this._processInputParams($),X=J.data;if(J.parsedType===m.undefined)X=this._def.defaultValue();return this._def.innerType._parse({data:X,path:J.path,parent:J})}removeDefault(){return this._def.innerType}}KX.create=($,J)=>{return new KX({innerType:$,typeName:M$.ZodDefault,defaultValue:typeof J.default==="function"?J.default:()=>J.default,...K$(J)})};class zX extends N${_parse($){let{ctx:J}=this._processInputParams($),X={...J,common:{...J.common,issues:[]}},Q=this._def.innerType._parse({data:X.data,path:X.path,parent:{...X}});if(QX(Q))return Q.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new SJ(X.common.issues)},input:X.data})}});else return{status:"valid",value:Q.status==="valid"?Q.value:this._def.catchValue({get error(){return new SJ(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}}zX.create=($,J)=>{return new zX({innerType:$,typeName:M$.ZodCatch,catchValue:typeof J.catch==="function"?J.catch:()=>J.catch,...K$(J)})};class qY extends N${_parse($){if(this._getType($)!==m.nan){let X=this._getOrReturnCtx($);return c(X,{code:h.invalid_type,expected:m.nan,received:X.parsedType}),G$}return{status:"valid",value:$.data}}}qY.create=($)=>{return new qY({typeName:M$.ZodNaN,...K$($)})};var VE=Symbol("zod_brand");class l9 extends N${_parse($){let{ctx:J}=this._processInputParams($),X=J.data;return this._def.type._parse({data:X,path:J.path,parent:J})}unwrap(){return this._def.type}}class HY extends N${_parse($){let{status:J,ctx:X}=this._processInputParams($);if(X.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:X.data,path:X.path,parent:X});if(Y.status==="aborted")return G$;if(Y.status==="dirty")return J.dirty(),LQ(Y.value);else return this._def.out._parseAsync({data:Y.value,path:X.path,parent:X})})();else{let Q=this._def.in._parseSync({data:X.data,path:X.path,parent:X});if(Q.status==="aborted")return G$;if(Q.status==="dirty")return J.dirty(),{status:"dirty",value:Q.value};else return this._def.out._parseSync({data:Q.value,path:X.path,parent:X})}}static create($,J){return new HY({in:$,out:J,typeName:M$.ZodPipeline})}}class EX extends N${_parse($){let J=this._def.innerType._parse($),X=(Q)=>{if(o0(Q))Q.value=Object.freeze(Q.value);return Q};return QX(J)?J.then((Q)=>X(Q)):X(J)}unwrap(){return this._def.innerType}}EX.create=($,J)=>{return new EX({innerType:$,typeName:M$.ZodReadonly,...K$(J)})};function RU($,J){let X=typeof $==="function"?$(J):typeof $==="string"?{message:$}:$;return typeof X==="string"?{message:X}:X}function TU($,J={},X){if($)return RQ.create().superRefine((Q,Y)=>{let G=$(Q);if(G instanceof Promise)return G.then((W)=>{if(!W){let U=RU(J,Q),M=U.fatal??X??!0;Y.addIssue({code:"custom",...U,fatal:M})}});if(!G){let W=RU(J,Q),U=W.fatal??X??!0;Y.addIssue({code:"custom",...W,fatal:U})}return});return RQ.create()}var qE={object:n$.lazycreate},M$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(M$||(M$={}));var HE=($,J={message:`Input not instance of ${$.name}`})=>TU((X)=>X instanceof $,J),SU=sJ.create,IU=s0.create,KE=qY.create,zE=r0.create,CU=GX.create,EE=AQ.create,FE=UY.create,NE=WX.create,LE=UX.create,AE=RQ.create,RE=a0.create,DE=z0.create,ZE=MY.create,BE=rJ.create,jE=n$.create,TE=n$.strictCreate,SE=MX.create,IE=m9.create,CE=OX.create,wE=E0.create,PE=OY.create,_E=VY.create,xE=DQ.create,vE=YX.create,kE=VX.create,fE=qX.create,yE=t0.create,bE=HX.create,hE=ZQ.create,uE=$0.create,gE=tJ.create,mE=C0.create,lE=$0.createWithPreprocess,pE=HY.create,dE=()=>SU().optional(),cE=()=>IU().optional(),nE=()=>CU().optional(),iE={string:($)=>sJ.create({...$,coerce:!0}),number:($)=>s0.create({...$,coerce:!0}),boolean:($)=>GX.create({...$,coerce:!0}),bigint:($)=>r0.create({...$,coerce:!0}),date:($)=>AQ.create({...$,coerce:!0})};var oE=G$;function ZG($){if(aE($)===6)return!0;if($.includes("://")||$.includes("/")||$.includes(":"))return!1;if($==="localhost")return!0;if($.startsWith("*.")){let J=$.slice(2);if(!J.includes(".")||J.startsWith(".")||J.endsWith("."))return!1;let X=J.split(".");return X.length>=2&&X.every((Q)=>Q.length>0)}if($.includes("*"))return!1;return $.includes(".")&&!$.startsWith(".")&&!$.endsWith(".")}var BG='Invalid domain pattern. Must be a valid domain (e.g., "example.com"), a wildcard (e.g., "*.example.com"), or a bracketed IPv6 literal (e.g., "[::1]", "[2001:db8::1]:443"). Overly broad patterns like "*.com" or "*" are not allowed for security reasons.',d9=_.string().refine(ZG,{message:BG});function _U($){let J=$.indexOf(":");return!(J!==-1&&$.indexOf(":",J+1)!==-1)||$.startsWith("[")}var rE=_.string().refine(($)=>_U($)&&ZG(sX($).hostPattern),{message:BG+' An optional ":port" suffix (1-65535) restricts the entry to that port.'}),tE=_.string().refine(($)=>{if(!_U($))return!1;let{hostPattern:J}=sX($);return J==="*"||ZG(J)},{message:BG+' In deniedDomains a bare "*" (deny-all) is also accepted, and an optional ":port" suffix (1-65535) restricts the entry to that port.'}),KY=_.string().min(1,"Path cannot be empty"),wU=_.string().min(1,"Path cannot be empty").refine(($)=>sE($),{message:"Binary path must be absolute"}),eE=_.object({socketPath:_.string().min(1).describe("Unix socket path to the MITM proxy"),domains:_.array(d9).min(1).describe('Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])')}),$F=_.object({http:_.string().url().optional().describe("Upstream proxy URL for plain HTTP traffic"),https:_.string().url().optional().describe("Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)"),noProxy:_.string().optional().describe("Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.")}),xU=_.enum(["deny","mask"]),p9=_.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable name must start with a letter or underscore and contain only letters, digits, and underscores"),vU=_.string().superRefine(($,J)=>{try{let{groupCount:X}=S7($);if(X<1)J.addIssue({code:_.ZodIssueCode.custom,message:"extract must contain at least one capturing group \u2014 group 1 is "+'the credential value to mask (e.g. "token:\\s*(\\S+)").'})}catch(X){J.addIssue({code:_.ZodIssueCode.custom,message:X instanceof Error?X.message:"Credential extract pattern is invalid"})}}),JF=_.object({path:KY.describe("Path to a credential file or directory. Supports the same path forms as filesystem.denyRead (absolute paths and ~ expansion)."),mode:xU.describe("Access mode for this path"),extract:vU.optional().describe('Optional regex for structured masking. Applied globally; capture group 1 of each match is masked, the rest of the file is preserved. If the pattern matches nothing, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),onExtractNoMatch:_.enum(["warn","deny","error"]).optional().describe("What to do when extract matches nothing (or, with decode, no "+'candidate verifies): "warn" (default \u2014 stderr warning, file left '+'readable), "deny" (degrade to mode "deny" \u2014 file unreadable), or '+'"error" (throw at wrap time). Only meaningful with mode "mask" and extract or decode set.'),decode:_.enum(["jwt"]).optional().describe('Optional encoded-credential format. "jwt": decodes recognized JWTs so masking can target fields inside them (see maskClaims). Candidates are located with a built-in JWT regex (or the explicit extract pattern, if set) and verified to actually be JWTs before masking. Without maskClaims, the whole decoded value is treated as the credential and replaced with a structurally valid fake JWT, so client-side token parsing keeps working. If no candidate verifies, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),maskClaims:_.array(_.string().min(1)).optional().describe('Names of top-level payload claims to mask inside each decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel; all other claims are preserved so claim-reading clients keep working. Requires decode. If no named claim matches in any verified token, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),maskDuplicates:_.boolean().optional().describe("If true, verbatim occurrences of each captured credential value outside the regex-matched spans are also replaced with the "+"corresponding sentinel \u2014 for a secret repeated where the regex "+`does not reach (e.g. in a comment). Matches raw substrings: short or common credential values may corrupt unrelated content, so this is intended for long, high-entropy secrets. With decode, only values that passed verification are scanned; duplicates reuse the verified value's fake without re-verification. Defaults to false. Only meaningful with mode "mask" and extract or decode set; accepted but ignored otherwise.`),injectHosts:_.array(d9).optional().describe("Optional narrowing of where the proxy substitutes this credential. "+"If unset, defaults to network.allowedDomains \u2014 the credential is "+'injected at every reachable host. Only meaningful when mode is "mask"; accepted but ignored for "deny".')}),QF=_.object({name:p9.describe("Environment variable name"),mode:xU.describe("Access mode for this environment variable"),extract:vU.optional().describe('Optional regex for structured masking. Applied globally; capture group 1 of each match is masked, the rest of the value is preserved. If the pattern matches nothing, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),onExtractNoMatch:_.enum(["warn","deny","error"]).optional().describe('What to do when extract matches nothing: "warn" (default \u2014 stderr '+'warning, variable passes through unmasked), "deny" (variable unset inside the sandbox), or "error" (throw at wrap time). Only meaningful with mode "mask" and extract set.'),decode:_.enum(["jwt"]).optional().describe(`Optional encoded-credential format. "jwt": the variable's whole value is verified to actually be a JWT and replaced with a structurally valid fake JWT so client-side token parsing keeps working; the proxy swaps the whole fake token on egress. If the value does not verify, the variable is left unmasked with a stderr warning (fail-open). Only meaningful when mode is "mask"; accepted but ignored for "deny".`),maskClaims:_.array(_.string().min(1)).optional().describe('Names of top-level payload claims to mask inside the decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel; all other claims are preserved so claim-reading clients keep working. Requires decode. If no named claim matches, the variable is left unmasked with a stderr warning (fail-open). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),injectHosts:_.array(d9).optional().describe("Optional narrowing of where the proxy substitutes this credential. "+"If unset, defaults to network.allowedDomains \u2014 the credential is "+'injected at every reachable host. Only meaningful when mode is "mask"; accepted but ignored for "deny".'),injectHeaders:_.array(_.string().regex(/^[a-z0-9-]{1,64}$/)).min(1).optional().describe('Optional narrowing of where in a request the proxy substitutes this credential: only in these headers (lower-case names), never in other headers or the body. If unset, every header and the body. Only meaningful when mode is "mask".')}),XF=_.object({accessKeyIdVar:p9.describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:p9.describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:p9.optional().describe("Optional name of the masked env var holding the AWS session token (temporary credentials). When set, the proxy sends the real token as x-amz-security-token on re-signed requests and adds it to the signed header set if the client did not.")}).strict(),DG=_.enum(["deny","passthrough"]),YF=_.object({streaming:DG.optional().describe('Policy for aws-chunked streaming uploads (x-amz-content-sha256: STREAMING-*): per-chunk signatures chain off the seed signature, so re-signing would require rewriting the body. Default "deny".'),presigned:DG.optional().describe('Policy for presigned URLs (X-Amz-Algorithm/X-Amz-Signature in the query, no Authorization header): the signature lives in the URL itself. Default "deny".'),sigv4a:DG.optional().describe('Policy for SigV4A (AWS4-ECDSA-P256-SHA256) asymmetric signatures: there is no shared-key HMAC to recompute. Default "deny".')}).strict(),kU=_.object({files:_.array(JF).optional().describe("Credential files or directories to protect"),envVars:_.array(QF).optional().describe("Environment variables to protect"),allowPlaintextInject:_.boolean().optional().describe("Allow sentinel\u2192real substitution on the plain-HTTP proxy path. "+"Defaults to false: without TLS termination the upstream identity is unverified and the credential travels in cleartext. Set only for trusted-network test fixtures."),awsPairs:_.array(XF).optional().describe("Explicit groupings of masked env vars into AWS credential pairs for SigV4 re-signing, for non-standard variable names. The conventional AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN trio is paired automatically when masked."),sigv4:YF.optional().describe('Policies for AWS SigV4 request shapes the proxy cannot re-sign (streaming, presigned, sigv4a) when they reference a masked credential pair: "deny" (default) or "passthrough".')}).strict(),PU=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,GF=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/,WF=_.object({url:_.string().url().refine(($)=>new URL($).protocol==="https:",{message:"brokerForward.url must be https"}),tokenEnvVar:_.string().regex(PU),rules:_.array(_.object({envVar:_.string().regex(PU),hosts:_.array(_.string().regex(GF)).min(1).max(16)}).strict()).min(1).max(32)}).strict(),fU=_.object({allowedDomains:_.array(rE).describe('List of allowed domains (e.g., ["github.com", "*.npmjs.org", "api.example.com:443"]). An optional ":port" suffix restricts the entry to that destination port.'),deniedDomains:_.array(tE).describe('List of denied domains. Unlike allowedDomains, a bare "*" is accepted here (deny-all). An optional ":port" suffix (e.g., "*:22") restricts the entry to that destination port.'),deniedDomainReasons:_.record(_.string(),_.string().min(1)).optional().describe('Optional model-facing reason keyed by the exact deniedDomains entry it explains (e.g., {"github.com:22": "SSH pushes to GitHub are blocked; use an https remote"}). Reported in the <sandbox_violations> line when that entry denies a connection; entries without one use a generic reason. Keys are matched by exact entry string, so a key with no matching deniedDomains entry never fires.'),strictAllowlist:_.boolean().optional().describe("If true, hosts not in allowedDomains are denied without consulting the ask callback. Set this when allowedDomains is policy enforcement, not a prompt-suppression hint."),allowUnixSockets:_.array(_.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:_.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:_.boolean().optional().describe("Whether to allow binding to local ports (default: false)"),allowMachLookup:_.array(_.string().refine(($)=>{return!($.endsWith("*")?$.slice(0,-1):$).includes("*")},{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "2BUA8C4S2C.com.1password.*"). Needed for tools like 1Password CLI, Playwright, or the iOS Simulator that communicate via XPC.'),httpProxyPort:_.number().int().min(1).max(65535).optional().describe("Port of an external HTTP proxy to use instead of starting a local one. When provided, the library will skip starting its own HTTP proxy and use this port. The external proxy must handle domain filtering."),socksProxyPort:_.number().int().min(1).max(65535).optional().describe("Port of an external SOCKS proxy to use instead of starting a local one. When provided, the library will skip starting its own SOCKS proxy and use this port. The external proxy must handle domain filtering."),mitmProxy:eE.optional().describe("Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering."),filterRequest:_.custom(($)=>typeof $==="function",{message:"filterRequest must be a function"}).optional().describe("Per-request filter callback. Receives the parsed HTTP request (web-standard Request) and returns {action, reason?}. Denied requests get a 403 with the reason. If the callback throws, the request is denied. Applies to plain HTTP through the proxy and, when tlsTerminate is configured, to terminated HTTPS. SRT does not provide a policy language; library consumers own matching."),tlsTerminate:_.object({caCertPath:_.string().min(1).optional().describe("Path to a PEM-encoded CA certificate. The sandboxed child is configured to trust this CA, and the TLS-terminating proxy uses it to sign per-host certificates. If omitted, on Windows SRT generates-if-absent a persistent CA under %ProgramData%\\sandbox-runtime\\ca\\ and trusts it in the sandbox user's Root store; on other platforms SRT generates an ephemeral CA into a temp directory for the lifetime of the session."),caKeyPath:_.string().min(1).optional().describe("Path to the PEM-encoded private key for caCertPath."),excludeDomains:_.array(d9).optional().describe("Domain patterns (same syntax as allowedDomains) whose HTTPS connections are NOT terminated. Matching CONNECTs are opaque byte tunnels: still subject to the allow/deny domain lists, but the sandboxed client completes its own TLS handshake with the upstream, so filterRequest and credential injection do not apply to their HTTPS traffic (plain-HTTP requests to the same hosts keep the normal request pipeline). Use for hosts the proxy must not re-originate: mTLS upstreams (only the client holds the client certificate) and clients that pin the upstream certificate and would reject the MITM CA. Hosts still need to be reachable via allowedDomains; this list only changes how they are tunnelled."),extraCaCertPaths:_.array(_.string().min(1)).optional().describe("Paths to PEM CA certificate files appended to the trust bundle the sandboxed child is pointed at, after the MITM CA and the host's regular roots. Use for site-local roots (e.g. an internal mTLS CA) presented by excluded/passthrough hosts, so the child can verify them itself. Only the CERTIFICATE blocks of each file are copied; files that are missing, unreadable, or contain no PEM CERTIFICATE block are skipped (with a debug log), so paths that exist on only some hosts are safe to list.")}).refine(($)=>!$.caCertPath===!$.caKeyPath,{message:"caCertPath and caKeyPath must be provided together"}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so HTTPS request/response bodies are visible to SRT. Provide a CA cert+key, or omit both to have SRT generate an ephemeral one."),parentProxy:$F.optional().describe("Upstream HTTP proxy for outbound connections. When set, SRT's proxy tunnels non-mitmProxy traffic through this parent instead of connecting directly. Falls back to HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars if unset."),brokerForward:WF.optional().describe("Credential placeholders a remote broker swaps (see broker-forward.ts).")}),yU=_.object({disabled:_.boolean().optional().describe("Disable all filesystem policy enforcement. When true, no read or write rules are emitted: denyRead/allowRead/allowWrite/denyWrite are ignored, and the built-in mandatory write protections (.git/hooks, .git/config, shell rc files, .mcp.json, .vscode/.idea, .claude/commands, .claude/agents) are NOT applied. Use only when the sandboxed process is trusted with full host filesystem access. Network and credential-env restrictions still apply. On Linux, /dev is still replaced by the bwrap minimal devtmpfs."),denyRead:_.array(KY).describe("Paths denied for reading"),allowRead:_.array(KY).optional().describe("Paths to re-allow reading within denied regions (takes precedence over denyRead). Use with denyRead to deny a broad region then allow back specific subdirectories."),allowWrite:_.array(KY).describe("Paths allowed for writing"),denyWrite:_.array(KY).describe("Paths denied for writing (takes precedence over allowWrite)"),allowGitConfig:_.boolean().optional().describe("Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.")}),bU=_.record(_.string(),_.array(_.string())).describe('Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands'),hU=_.object({command:_.string().describe("The ripgrep command to execute"),args:_.array(_.string()).optional().describe("Additional arguments to pass before ripgrep args"),argv0:_.string().optional().describe("Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])")}),uU=_.object({safeDirectories:_.array(_.string()).default([]).describe("Directories git should treat as safe (`safe.directory`) even though they're owned by a different user inside the sandbox. Use for the repo top-level when launching from a subdirectory. Does NOT grant write.")}),gU=_.object({path:_.string().min(1).describe("Path to the srt-win binary. Pass the exported VENDORED_SRT_WIN_EXE constant to use the packaged vendor/srt-win/<arch>/srt-win.exe (see its WARNING: in a dev checkout that file may sit inside your sandbox write grant). The binary is spawned with the `--srt-win` argv[1] sentinel so a multicall dispatcher can route to srt-win's CLI.")}),mU=_.object({sandboxUser:_.string().min(1).max(20,"Windows local usernames are limited to 20 characters").optional().describe("Name for the dedicated sandbox user account that `srt-win install` creates and the sandboxed child runs as. Default: `srt-sandbox`. Install refuses if an account by this name already exists and srt-win did not create it (it will not rotate the password of an account it does not own). Must match what `srt-win install --sandbox-user` was run with."),sublayerGuid:_.string().uuid().optional().describe("WFP sublayer GUID under which the filters were installed. Omit to use the srt-win compile-time default. Set this when filters were installed by enterprise tooling under a custom sublayer."),wfpSublayerGuid:_.string().uuid().optional().describe("Deprecated alias for sublayerGuid."),proxyPortRange:_.tuple([_.number().int().min(1),_.number().int().max(65535)]).refine(([$,J])=>$<=J&&J-$<=64,{message:"low must be \u2264 high and range width \u2264 64"}).optional().describe("Inclusive [low, high] port range the JS mux proxy listeners bind inside. MUST match the range passed to `srt-win install "+"--proxy-port-range` (default 60080\u201360089) \u2014 the WFP loopback "+"permit only covers ports in that range."),srtWin:gU.optional().describe("How to locate/invoke the srt-win helper binary. `srtWin.path` is "+"required to use the Windows sandbox \u2014 your own (multicall) binary, "+"or the exported VENDORED_SRT_WIN_EXE constant for the packaged exe.")}),UF=_.object({applyPath:_.string().optional().describe("Path to the apply-seccomp binary"),argv0:_.string().optional().describe("Invoke apply-seccomp as a multicall binary that dispatches on the ARGV0 environment variable. When set, applyPath is used verbatim (no existence check) and the invocation inside bwrap is prefixed with ARGV0=<this value>. The caller is responsible for ensuring applyPath resolves inside the bwrap namespace and that the target binary implements the apply-seccomp interface when ARGV0 matches.")}),MF=_.object({network:fU.describe("Network restrictions configuration"),filesystem:yU.describe("Filesystem restrictions configuration"),credentials:kU.optional().describe("Credential handling configuration. Only the explicitly declared files and environment variables are restricted."),ignoreViolations:bU.optional().describe("Optional configuration for ignoring specific violations"),enableWeakerNestedSandbox:_.boolean().optional().describe("Enable weaker nested sandbox mode (for Docker environments)"),runAsUid:_.number().int().nonnegative().optional().describe("ARA: uid to drop the sandboxed command to (bwrap --uid)"),runAsGid:_.number().int().nonnegative().optional().describe("ARA: gid to drop the sandboxed command to (bwrap --gid)"),runAsHostUid:_.number().int().positive().optional().describe("ARA: real host uid used to launch the sandboxed bwrap child"),runAsHostGid:_.number().int().positive().optional().describe("ARA: real host gid used to launch the sandboxed bwrap child"),runAsHostHome:_.string().min(1).optional().describe("ARA: HOME set inside a real-host-uid sandbox child"),runAsHostUser:_.string().min(1).optional().describe("ARA: USER and LOGNAME set inside a real-host-uid sandbox child"),enableWeakerNetworkIsolation:_.boolean().optional().describe("Enable weaker network isolation to allow access to com.apple.trustd.agent (macOS only). This is needed for Go programs (gh, gcloud, terraform, kubectl, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Enabling this opens a potential data exfiltration vector through the trustd service. Only enable if you need Go TLS verification."),allowAppleEvents:_.boolean().optional().describe("Allow sending Apple Events and Launch Services open requests from the sandbox (macOS only). Needed for open, osascript, and anything that opens URLs or scripts other apps via AppleScript. This removes code-execution isolation: sandboxed commands can launch other applications unsandboxed with no user prompt (launched apps are not subject to the sandbox filesystem or network restrictions), and can script running apps subject to TCC automation consent. Default: false."),ripgrep:hU.optional().describe('Custom ripgrep configuration (default: { command: "rg" })'),mandatoryDenySearchDepth:_.number().int().min(1).max(10).optional().describe("Maximum directory depth to search for dangerous files on Linux (default: 3). Higher values provide more protection but slower performance."),allowPty:_.boolean().optional().describe("Allow pseudo-terminal (pty) operations (macOS only)"),seccomp:UF.optional().describe("Custom seccomp binary paths (Linux only)."),bwrapPath:wU.optional().describe('Linux only: absolute path to the bwrap (bubblewrap) binary. When set, this path is used directly instead of resolving "bwrap" via PATH.'),socatPath:wU.optional().describe('Linux only: absolute path to the socat binary. When set, this path is used directly instead of resolving "socat" via PATH.'),windows:mU.optional().describe("Windows-specific settings (WFP sublayer, proxy port range)."),git:uU.optional().describe("Git configuration to inject via GIT_CONFIG_* env vars (cross-platform). `safeDirectories` marks paths as `safe.directory` without adding them to `filesystem.allowWrite`.")}).superRefine(($,J)=>{let X=$.credentials;if(!X)return;let Q=$.network.allowedDomains.map(rX),Y=(M,O)=>{for(let[V,q]of M.entries())if(!k9(q,Q))J.addIssue({code:_.ZodIssueCode.custom,path:[...O,V],message:`injectHosts entry "${q}" is not reachable via `+`network.allowedDomains \u2014 add "${q}" (or a covering wildcard) to allowedDomains, or remove it from injectHosts.`})},G=!1,W=(M,O)=>{if(M.injectHosts)Y(M.injectHosts,[...O,"injectHosts"]);if(M.mode!=="mask")return;G=!0;let V=$.network.tlsTerminate?.excludeDomains;if(V?.length){if(M.injectHosts){for(let[q,H]of M.injectHosts.entries())if(k9(H,V))J.addIssue({code:_.ZodIssueCode.custom,path:[...O,"injectHosts",q],message:`injectHosts entry "${H}" is entirely covered by network.tlsTerminate.excludeDomains. Credential injection only runs on TLS-terminated connections, so this host would receive the placeholder instead of the credential. Remove it from one of the two lists.`})}else if(Q.length>0&&Q.every((q)=>k9(q,V)))J.addIssue({code:_.ZodIssueCode.custom,path:O,message:"This masked credential has no injectHosts, so it defaults "+"to network.allowedDomains \u2014 but "+"network.tlsTerminate.excludeDomains covers every allowed domain, so it could never be injected anywhere. Credential injection only runs on TLS-terminated connections."})}if(M.injectHosts!==void 0&&M.injectHosts.length===0)J.addIssue({code:_.ZodIssueCode.custom,path:O,message:"injectHosts is explicitly empty \u2014 the credential would be "+"masked but never injected. Omit injectHosts to default to network.allowedDomains, or list the intended hosts."})};for(let[M,O]of(X.envVars??[]).entries()){if(W(O,["credentials","envVars",M]),O.maskClaims!==void 0&&O.decode===void 0)J.addIssue({code:_.ZodIssueCode.custom,path:["credentials","envVars",M,"maskClaims"],message:"maskClaims requires decode \u2014 it names claims inside the "+'decoded payload. Set decode (e.g. "jwt"), or remove maskClaims to mask the whole value.'});if(O.maskClaims!==void 0&&O.maskClaims.length===0)J.addIssue({code:_.ZodIssueCode.custom,path:["credentials","envVars",M,"maskClaims"],message:"maskClaims is explicitly empty \u2014 no claim would ever be "+"masked. Omit maskClaims to mask the whole token, or list the claims to protect."})}for(let[M,O]of(X.files??[]).entries()){if(W(O,["credentials","files",M]),O.maskClaims!==void 0&&O.decode===void 0)J.addIssue({code:_.ZodIssueCode.custom,path:["credentials","files",M,"maskClaims"],message:"maskClaims requires decode \u2014 it names claims inside the "+'decoded payload. Set decode (e.g. "jwt"), or remove maskClaims to mask the extracted value whole.'});if(O.maskClaims!==void 0&&O.maskClaims.length===0)J.addIssue({code:_.ZodIssueCode.custom,path:["credentials","files",M,"maskClaims"],message:"maskClaims is explicitly empty \u2014 no claim would ever be "+"masked. Omit maskClaims to mask the whole token, or list the claims to protect."});if(O.mode==="mask"&&O.path.endsWith("/"))J.addIssue({code:_.ZodIssueCode.custom,path:["credentials","files",M,"path"],message:`Credential mode "mask" applies to a single file, not a directory. Use mode "deny" for "${O.path}", or point at the credential file inside it.`})}let U=new Set;for(let[M,O]of(X.awsPairs??[]).entries()){let V=[["accessKeyIdVar",O.accessKeyIdVar],["secretAccessKeyVar",O.secretAccessKeyVar]];if(O.sessionTokenVar!==void 0)V.push(["sessionTokenVar",O.sessionTokenVar]);for(let[q,H]of V){let N=["credentials","awsPairs",M,q];if(U.has(H)){J.addIssue({code:_.ZodIssueCode.custom,path:N,message:`"${H}" appears in more than one awsPairs slot (within `+"or across pairs) \u2014 each variable can fill exactly one slot."});continue}U.add(H);let K=(X.envVars??[]).find((L)=>L.name===H);if(K===void 0||K.mode!=="mask")J.addIssue({code:_.ZodIssueCode.custom,path:N,message:`"${H}" does not reference a credentials.envVars entry `+'with mode "mask" \u2014 an AWS pair links already-masked '+"variables; add the entry (masking is the opt-in for SigV4 re-signing)."});else if(K.extract!==void 0||K.decode!==void 0)J.addIssue({code:_.ZodIssueCode.custom,path:N,message:`"${H}" uses extract/decode, but an AWS pair member must be masked whole-value: the SigV4 trigger is an exact match of the fake access key id, and the signer needs the entire real value.`})}}if(G&&$.network.tlsTerminate===void 0&&!X.allowPlaintextInject)J.addIssue({code:_.ZodIssueCode.custom,path:["credentials"],message:"Credential masking requires network.tlsTerminate so substitution runs only over a verified TLS connection. Enable tlsTerminate, or set credentials.allowPlaintextInject to opt out (not recommended)."})});export{h5 as windowsTrustCaAsync,lK as windowsTrustCa,g5 as windowsStateDir,r7 as windowsInstallInstructions,JG as verifyWindowsWfpEgress,hX as validateCaPair,cK as uninstallWindowsSandbox,WG as stampWindowsAcl,v9 as revokeWindowsAcl,x9 as restoreWindowsAcl,wJ as resolveSrtWin,nK as parseWindowsSandboxError,C9 as parseWindowsBinShell,AX as isUncPath,dK as installWindowsSandboxAsync,pK as installWindowsSandbox,UG as grantWindowsAcl,i9 as getWslVersion,b5 as getWindowsWfpStatusAsync,y5 as getWindowsWfpStatus,aX as getWindowsSandboxUserStatusAsync,QG as getWindowsSandboxUserStatus,XG as getWindowsSandboxCaCert,mK as getSrtWinPath,BQ as getDefaultWritePaths,J9 as generateCa,_9 as expandWindowsFsPaths,YG as ensurePersistentWindowsCa,f5 as checkWindowsSandboxStatusAsync,k5 as checkWindowsSandboxStatus,MG as checkWindowsDependenciesAsync,pQ as certThumbprint,RX as buildGitConfigEnv,A$ as WindowsSandboxError,mU as WindowsConfigSchema,gK as VENDORED_SRT_WIN_EXE,gU as SrtWinConfigSchema,T9 as SandboxViolationStore,MF as SandboxRuntimeConfigSchema,hz as SandboxManager,P5 as SRT_WIN_DISPATCH_ARG1,hU as RipgrepConfigSchema,fU as NetworkConfigSchema,bU as IgnoreViolationsConfigSchema,uU as GitConfigSchema,yU as FilesystemConfigSchema,I9 as DEFAULT_WINDOWS_PROXY_PORT_RANGE,kU as CredentialsConfigSchema};